mirror of
https://gitlab.com/soapbox-pub/mkstack.git
synced 2026-12-03 08:07:21 +00:00
Compare commits
151
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
00fa0eb30d | ||
|
|
a76c292fec | ||
|
|
62add9ec26 | ||
|
|
f75ddb6654 | ||
|
|
3b48df1093 | ||
|
|
5a5c05c1d4 | ||
|
|
f7736ddfb1 | ||
|
|
b11e843196 | ||
|
|
414e0bf029 | ||
|
|
39afb03570 | ||
|
|
83db2fd539 | ||
|
|
a2eab78ae3 | ||
|
|
65b974fb41 | ||
|
|
cadbc02947 | ||
|
|
37aaadbd70 | ||
|
|
0cda9cb7fc | ||
|
|
49952a10bf | ||
|
|
fce2a3da23 | ||
|
|
15dbc6df85 | ||
|
|
508fa84466 | ||
|
|
b7ff219e6e | ||
|
|
b9750b3759 | ||
|
|
ad1c8b123c | ||
|
|
4e1c43ee13 | ||
|
|
1e179b4396 | ||
|
|
cd5376ff49 | ||
|
|
561975cded | ||
|
|
7a5fce4933 | ||
|
|
8559a004e8 | ||
|
|
df40d30f15 | ||
|
|
062545d061 | ||
|
|
9625533ed4 | ||
|
|
db09c45a54 | ||
|
|
ed143157bf | ||
|
|
9646620a46 | ||
|
|
830c10fe8d | ||
|
|
927010c0d0 | ||
|
|
e70b3640e8 | ||
|
|
1983126de9 | ||
|
|
87d3cfb2eb | ||
|
|
98aa853716 | ||
|
|
5d4a19eb9c | ||
|
|
10386c2c38 | ||
|
|
034b5eab33 | ||
|
|
fddd1d20f3 | ||
|
|
aa1088499f | ||
|
|
c07a53e727 | ||
|
|
68202d655e | ||
|
|
641f570329 | ||
|
|
c2d5187efb | ||
|
|
9ad31aa674 | ||
|
|
d1a4e26f79 | ||
|
|
b3bc9d45e0 | ||
|
|
1b74dc38fd | ||
|
|
7a7d91dbed | ||
|
|
2d325f7343 | ||
|
|
d2854f917c | ||
|
|
28cda6d365 | ||
|
|
da87f2c7b1 | ||
|
|
61508020ae | ||
|
|
f146bf58d7 | ||
|
|
cd87b6e430 | ||
|
|
696c5ba963 | ||
|
|
36e49106a6 | ||
|
|
048bf4cc69 | ||
|
|
3ad83cd114 | ||
|
|
c3310ab485 | ||
|
|
bce7af2e76 | ||
|
|
f762136f14 | ||
|
|
5b90ebe482 | ||
|
|
c2ff2a990f | ||
|
|
0481cd024e | ||
|
|
1617d80ece | ||
|
|
a8163d7a6c | ||
|
|
190f0cd791 | ||
|
|
aa4110e6b3 | ||
|
|
94d1688f43 | ||
|
|
9f12c58dc0 | ||
|
|
0ee653f631 | ||
|
|
3672a13ac8 | ||
|
|
ac46749fad | ||
|
|
1fc548c7e9 | ||
|
|
8bdff8da6d | ||
|
|
3a34db8320 | ||
|
|
065f3cfe02 | ||
|
|
ed2d3798ea | ||
|
|
03f804ed90 | ||
|
|
aa1e2145d0 | ||
|
|
130300f1c1 | ||
|
|
9cb2795496 | ||
|
|
34770a3145 | ||
|
|
37bee859b6 | ||
|
|
139e6696db | ||
|
|
738b512d9c | ||
|
|
7c5fe75572 | ||
|
|
865ca7039f | ||
|
|
acbe053c97 | ||
|
|
830d806933 | ||
|
|
ee42c84171 | ||
|
|
98f3305aa1 | ||
|
|
2d326ca5e9 | ||
|
|
dbd28373a5 | ||
|
|
ed3080d34e | ||
|
|
79ed87e67c | ||
|
|
9221693edb | ||
|
|
1b8dab92b9 | ||
|
|
95de9fde27 | ||
|
|
81f90b9985 | ||
|
|
0e8a141490 | ||
|
|
a6eeb05d6e | ||
|
|
e0d94fae71 | ||
|
|
be2d2d63fa | ||
|
|
f633f4b423 | ||
|
|
2c5d38013f | ||
|
|
d14652559e | ||
|
|
4254b9eb0b | ||
|
|
e099d8b467 | ||
|
|
ef7667501b | ||
|
|
7edfde7e9f | ||
|
|
69faf49454 | ||
|
|
aa2468b656 | ||
|
|
7ee419bc6d | ||
|
|
73e7e818b2 | ||
|
|
ebc399776d | ||
|
|
56df17b56e | ||
|
|
856d333c30 | ||
|
|
b24578f0db | ||
|
|
cc3d87192c | ||
|
|
70eceef6ae | ||
|
|
601b3ce370 | ||
|
|
f77a6a4af3 | ||
|
|
d05a78880a | ||
|
|
750c165c05 | ||
|
|
aa91528de8 | ||
|
|
95eb9634b5 | ||
|
|
69060820f8 | ||
|
|
1a431c9d8a | ||
|
|
246ffb2181 | ||
|
|
db13869675 | ||
|
|
b8137d0751 | ||
|
|
16ca716db2 | ||
|
|
70dec2fc9a | ||
|
|
cac4ae6b93 | ||
|
|
a7fcaaf1f3 | ||
|
|
3052ce66f1 | ||
|
|
87a0846bbe | ||
|
|
e4d081d3da | ||
|
|
d623f11653 | ||
|
|
2ac30c4f29 | ||
|
|
b8603ff80e | ||
|
|
3cc2fe6d64 |
No files matched your search
Symlink
+1
@@ -0,0 +1 @@
|
||||
../.mcp.json
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -20,3 +20,11 @@ dist-ssr
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
|
||||
# Vercel
|
||||
.vercel
|
||||
|
||||
# Secrets
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
@@ -0,0 +1,27 @@
|
||||
image: node:22
|
||||
|
||||
default:
|
||||
interruptible: true
|
||||
timeout: 1 minute
|
||||
|
||||
stages:
|
||||
- test
|
||||
- deploy
|
||||
|
||||
test:
|
||||
stage: test
|
||||
script:
|
||||
- npm run test
|
||||
|
||||
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
|
||||
+737
-19
@@ -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,176 @@ 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)
|
||||
|
||||
6. **Custom Kind Publishing**: When publishing events with custom kinds generated by `nostr__generate_kind`, always include a NIP-31 "alt" tag with a human-readable description of the event's purpose.
|
||||
|
||||
**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 +299,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 +484,254 @@ 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>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### Adding Comments Sections
|
||||
|
||||
The project includes a complete commenting system using NIP-22 (kind 1111) comments that can be added to any Nostr event or URL. The `CommentsSection` component provides a full-featured commenting interface with threaded replies, user authentication, and real-time updates.
|
||||
|
||||
#### Basic Usage
|
||||
|
||||
```tsx
|
||||
import { CommentsSection } from "@/components/comments/CommentsSection";
|
||||
|
||||
function ArticlePage({ article }: { article: NostrEvent }) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Your article content */}
|
||||
<div>{/* article content */}</div>
|
||||
|
||||
{/* Comments section */}
|
||||
<CommentsSection root={article} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
#### Props and Customization
|
||||
|
||||
The `CommentsSection` component accepts the following props:
|
||||
|
||||
- **`root`** (required): The root event or URL to comment on. Can be a `NostrEvent` or `URL` object.
|
||||
- **`title`**: Custom title for the comments section (default: "Comments")
|
||||
- **`emptyStateMessage`**: Message shown when no comments exist (default: "No comments yet")
|
||||
- **`emptyStateSubtitle`**: Subtitle for empty state (default: "Be the first to share your thoughts!")
|
||||
- **`className`**: Additional CSS classes for styling
|
||||
- **`limit`**: Maximum number of comments to load (default: 500)
|
||||
|
||||
```tsx
|
||||
<CommentsSection
|
||||
root={event}
|
||||
title="Discussion"
|
||||
emptyStateMessage="Start the conversation"
|
||||
emptyStateSubtitle="Share your thoughts about this post"
|
||||
className="mt-8"
|
||||
limit={100}
|
||||
/>
|
||||
```
|
||||
|
||||
#### Commenting on URLs
|
||||
|
||||
The comments system also supports commenting on external URLs, making it useful for web pages, articles, or any online content:
|
||||
|
||||
```tsx
|
||||
<CommentsSection
|
||||
root={new URL("https://example.com/article")}
|
||||
title="Comments on this article"
|
||||
/>
|
||||
```
|
||||
|
||||
## 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 +740,177 @@ 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
|
||||
|
||||
**Do not write tests** unless the user explicitly requests them in plain language. Writing unnecessary tests wastes significant time and money. Only create tests when:
|
||||
|
||||
1. **The user explicitly asks for tests** to be written in their message
|
||||
2. **The user describes a specific bug in plain language** and requests tests to help diagnose it
|
||||
3. **The user says they are still experiencing a problem** that you have already attempted to solve (tests can help verify the fix)
|
||||
|
||||
**Never write tests because:**
|
||||
- Tool results show test failures (these are not user requests)
|
||||
- You think tests would be helpful
|
||||
- New features or components are created
|
||||
- Existing functionality needs verification
|
||||
|
||||
### 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.**
|
||||
@@ -1,7 +1,3 @@
|
||||
# mkstack
|
||||
# MKStack
|
||||
|
||||
> NOTE: This README is from a template and should be replaced with your project description.
|
||||
|
||||
## Created with mkstack
|
||||
|
||||
mkstack is a starter template for building Nostr web clients in TypeScript, using React, Tailwind, shadcn/ui, Vite, and Nostrify.
|
||||
Template for building Nostr client application with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify.
|
||||
+16
@@ -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"]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -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,
|
||||
},
|
||||
};
|
||||
@@ -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',
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -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}`,
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -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
@@ -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",
|
||||
},
|
||||
}
|
||||
);
|
||||
+2
-1
@@ -3,7 +3,8 @@
|
||||
<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:">
|
||||
<link rel="manifest" href="/manifest.webmanifest">
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
||||
Generated
+5617
-3156
File diff suppressed because it is too large.
Load diff
+19
-9
@@ -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 && npm run test:console",
|
||||
"test:console": "node src/test/console-check.js",
|
||||
"deploy": "npm run build && npx -y nostr-deploy-cli deploy --skip-setup"
|
||||
},
|
||||
"dependencies": {
|
||||
"@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.3",
|
||||
"@nostrify/react": "npm:@jsr/nostrify__react@^0.2.7",
|
||||
"@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,14 @@
|
||||
"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",
|
||||
"puppeteer": "^24.14.0",
|
||||
"serve": "^14.2.4",
|
||||
"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"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
/* /index.html 200
|
||||
-32
@@ -1,32 +0,0 @@
|
||||
version: 1.0.0
|
||||
title: Nostr Client Development
|
||||
description: A recipe for building Nostr client applications
|
||||
instructions: Create a Nostr client application according to the user's request.
|
||||
extensions:
|
||||
- type: builtin
|
||||
name: developer
|
||||
display_name: Developer Tools
|
||||
timeout: 300
|
||||
bundled: true
|
||||
- type: stdio
|
||||
name: nostr
|
||||
cmd: npx
|
||||
args:
|
||||
- -y
|
||||
- xjsr
|
||||
- "@nostrbook/mcp"
|
||||
envs: {}
|
||||
timeout: 20
|
||||
description: null
|
||||
bundled: null
|
||||
- type: stdio
|
||||
name: fetch
|
||||
cmd: uvx
|
||||
args:
|
||||
- mcp-server-fetch
|
||||
envs: {}
|
||||
timeout: 20
|
||||
description: null
|
||||
bundled: null
|
||||
author:
|
||||
contact: Alex Gleason <[email protected]>
|
||||
-42
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { render } from '@testing-library/react';
|
||||
import { test } from 'vitest';
|
||||
|
||||
import App from './App';
|
||||
|
||||
test('App', () => {
|
||||
render(<App />);
|
||||
})
|
||||
+41
-19
@@ -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>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -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 */}
|
||||
|
||||
@@ -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.ZodTypeDef, unknown> = 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]);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
};
|
||||
@@ -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];
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
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>
|
||||
);
|
||||
|
||||
const link = screen.getByRole('link', { name: 'https://example.com' });
|
||||
expect(link).toBeInTheDocument();
|
||||
expect(link).toHaveAttribute('href', 'https://example.com');
|
||||
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>
|
||||
);
|
||||
|
||||
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");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,137 @@
|
||||
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';
|
||||
|
||||
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(() => {
|
||||
const text = event.content;
|
||||
|
||||
// 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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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)}
|
||||
|
||||
@@ -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'>
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
import { useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { NostrEvent } from '@nostrify/nostrify';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { useComments } from '@/hooks/useComments';
|
||||
import { CommentForm } from './CommentForm';
|
||||
import { NoteContent } from '@/components/NoteContent';
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
|
||||
import { DropdownMenu, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
|
||||
import { MessageSquare, ChevronDown, ChevronRight, MoreHorizontal } from 'lucide-react';
|
||||
import { formatDistanceToNow } from 'date-fns';
|
||||
import { genUserName } from '@/lib/genUserName';
|
||||
|
||||
interface CommentProps {
|
||||
root: NostrEvent | URL;
|
||||
comment: NostrEvent;
|
||||
depth?: number;
|
||||
maxDepth?: number;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
export function Comment({ root, comment, depth = 0, maxDepth = 3, limit }: CommentProps) {
|
||||
const [showReplyForm, setShowReplyForm] = useState(false);
|
||||
const [showReplies, setShowReplies] = useState(depth < 2); // Auto-expand first 2 levels
|
||||
|
||||
const author = useAuthor(comment.pubkey);
|
||||
const { data: commentsData } = useComments(root, limit);
|
||||
|
||||
const metadata = author.data?.metadata;
|
||||
const displayName = metadata?.name ?? genUserName(comment.pubkey)
|
||||
const timeAgo = formatDistanceToNow(new Date(comment.created_at * 1000), { addSuffix: true });
|
||||
|
||||
// Get direct replies to this comment
|
||||
const replies = commentsData?.getDirectReplies(comment.id) || [];
|
||||
const hasReplies = replies.length > 0;
|
||||
|
||||
return (
|
||||
<div className={`space-y-3 ${depth > 0 ? 'ml-6 border-l-2 border-muted pl-4' : ''}`}>
|
||||
<Card className="bg-card/50">
|
||||
<CardContent className="p-4">
|
||||
<div className="space-y-3">
|
||||
{/* Comment Header */}
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="flex items-center space-x-3">
|
||||
<Link to={`/${nip19.npubEncode(comment.pubkey)}`}>
|
||||
<Avatar className="h-8 w-8 hover:ring-2 hover:ring-primary/30 transition-all cursor-pointer">
|
||||
<AvatarImage src={metadata?.picture} />
|
||||
<AvatarFallback className="text-xs">
|
||||
{displayName.charAt(0)}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
</Link>
|
||||
<div>
|
||||
<Link
|
||||
to={`/${nip19.npubEncode(comment.pubkey)}`}
|
||||
className="font-medium text-sm hover:text-primary transition-colors"
|
||||
>
|
||||
{displayName}
|
||||
</Link>
|
||||
<p className="text-xs text-muted-foreground">{timeAgo}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Comment Content */}
|
||||
<div className="text-sm">
|
||||
<NoteContent event={comment} className="text-sm" />
|
||||
</div>
|
||||
|
||||
{/* Comment Actions */}
|
||||
<div className="flex items-center justify-between pt-2">
|
||||
<div className="flex items-center space-x-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setShowReplyForm(!showReplyForm)}
|
||||
className="h-8 px-2 text-xs"
|
||||
>
|
||||
<MessageSquare className="h-3 w-3 mr-1" />
|
||||
Reply
|
||||
</Button>
|
||||
|
||||
{hasReplies && (
|
||||
<Collapsible open={showReplies} onOpenChange={setShowReplies}>
|
||||
<CollapsibleTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className="h-8 px-2 text-xs">
|
||||
{showReplies ? (
|
||||
<ChevronDown className="h-3 w-3 mr-1" />
|
||||
) : (
|
||||
<ChevronRight className="h-3 w-3 mr-1" />
|
||||
)}
|
||||
{replies.length} {replies.length === 1 ? 'reply' : 'replies'}
|
||||
</Button>
|
||||
</CollapsibleTrigger>
|
||||
</Collapsible>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Comment menu */}
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 px-2 text-xs"
|
||||
aria-label="Comment options"
|
||||
>
|
||||
<MoreHorizontal className="h-3 w-3" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Reply Form */}
|
||||
{showReplyForm && (
|
||||
<div className="ml-6">
|
||||
<CommentForm
|
||||
root={root}
|
||||
reply={comment}
|
||||
onSuccess={() => setShowReplyForm(false)}
|
||||
placeholder="Write a reply..."
|
||||
compact
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Replies */}
|
||||
{hasReplies && (
|
||||
<Collapsible open={showReplies} onOpenChange={setShowReplies}>
|
||||
<CollapsibleContent className="space-y-3">
|
||||
{replies.map((reply) => (
|
||||
<Comment
|
||||
key={reply.id}
|
||||
root={root}
|
||||
comment={reply}
|
||||
depth={depth + 1}
|
||||
maxDepth={maxDepth}
|
||||
limit={limit}
|
||||
/>
|
||||
))}
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { useState } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { usePostComment } from '@/hooks/usePostComment';
|
||||
import { LoginArea } from '@/components/auth/LoginArea';
|
||||
import { NostrEvent } from '@nostrify/nostrify';
|
||||
import { MessageSquare, Send } from 'lucide-react';
|
||||
|
||||
interface CommentFormProps {
|
||||
root: NostrEvent | URL;
|
||||
reply?: NostrEvent | URL;
|
||||
onSuccess?: () => void;
|
||||
placeholder?: string;
|
||||
compact?: boolean;
|
||||
}
|
||||
|
||||
export function CommentForm({
|
||||
root,
|
||||
reply,
|
||||
onSuccess,
|
||||
placeholder = "Write a comment...",
|
||||
compact = false
|
||||
}: CommentFormProps) {
|
||||
const [content, setContent] = useState('');
|
||||
const { user } = useCurrentUser();
|
||||
const { mutate: postComment, isPending } = usePostComment();
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
if (!content.trim() || !user) return;
|
||||
|
||||
postComment(
|
||||
{ content: content.trim(), root, reply },
|
||||
{
|
||||
onSuccess: () => {
|
||||
setContent('');
|
||||
onSuccess?.();
|
||||
},
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
if (!user) {
|
||||
return (
|
||||
<Card className={compact ? "border-dashed" : ""}>
|
||||
<CardContent className={compact ? "p-4" : "p-6"}>
|
||||
<div className="text-center space-y-4">
|
||||
<div className="flex items-center justify-center space-x-2 text-muted-foreground">
|
||||
<MessageSquare className="h-5 w-5" />
|
||||
<span>Sign in to {reply ? 'reply' : 'comment'}</span>
|
||||
</div>
|
||||
<LoginArea />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Card className={compact ? "border-dashed" : ""}>
|
||||
<CardContent className={compact ? "p-4" : "p-6"}>
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<Textarea
|
||||
value={content}
|
||||
onChange={(e) => setContent(e.target.value)}
|
||||
placeholder={placeholder}
|
||||
className={compact ? "min-h-[80px]" : "min-h-[100px]"}
|
||||
disabled={isPending}
|
||||
/>
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{reply ? 'Replying to comment' : 'Adding to the discussion'}
|
||||
</span>
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={!content.trim() || isPending}
|
||||
size={compact ? "sm" : "default"}
|
||||
>
|
||||
<Send className="h-4 w-4 mr-2" />
|
||||
{isPending ? 'Posting...' : (reply ? 'Reply' : 'Comment')}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import { useComments } from '@/hooks/useComments';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { MessageSquare } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
import { CommentForm } from './CommentForm';
|
||||
import { Comment } from './Comment';
|
||||
|
||||
interface CommentsSectionProps {
|
||||
root: NostrEvent | URL;
|
||||
title?: string;
|
||||
emptyStateMessage?: string;
|
||||
emptyStateSubtitle?: string;
|
||||
className?: string;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
export function CommentsSection({
|
||||
root,
|
||||
title = "Comments",
|
||||
emptyStateMessage = "No comments yet",
|
||||
emptyStateSubtitle = "Be the first to share your thoughts!",
|
||||
className,
|
||||
limit = 500,
|
||||
}: CommentsSectionProps) {
|
||||
const { data: commentsData, isLoading, error } = useComments(root, limit);
|
||||
const comments = commentsData?.topLevelComments || [];
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<Card className="rounded-none sm:rounded-lg mx-0 sm:mx-0">
|
||||
<CardContent className="px-2 py-6 sm:p-6">
|
||||
<div className="text-center text-muted-foreground">
|
||||
<MessageSquare className="h-8 w-8 mx-auto mb-2 opacity-50" />
|
||||
<p>Failed to load comments</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Card className={cn("rounded-none sm:rounded-lg mx-0 sm:mx-0", className)}>
|
||||
<CardHeader className="px-2 pt-6 pb-4 sm:p-6">
|
||||
<CardTitle className="flex items-center space-x-2">
|
||||
<MessageSquare className="h-5 w-5" />
|
||||
<span>{title}</span>
|
||||
{!isLoading && (
|
||||
<span className="text-sm font-normal text-muted-foreground">
|
||||
({comments.length})
|
||||
</span>
|
||||
)}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="px-2 pb-6 pt-4 sm:p-6 sm:pt-0 space-y-6">
|
||||
{/* Comment Form */}
|
||||
<CommentForm root={root} />
|
||||
|
||||
{/* Comments List */}
|
||||
{isLoading ? (
|
||||
<div className="space-y-4">
|
||||
{[...Array(3)].map((_, i) => (
|
||||
<Card key={i} className="bg-card/50">
|
||||
<CardContent className="p-4">
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center space-x-3">
|
||||
<Skeleton className="h-8 w-8 rounded-full" />
|
||||
<div className="space-y-1">
|
||||
<Skeleton className="h-4 w-24" />
|
||||
<Skeleton className="h-3 w-16" />
|
||||
</div>
|
||||
</div>
|
||||
<Skeleton className="h-16 w-full" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
) : comments.length === 0 ? (
|
||||
<div className="text-center py-8 text-muted-foreground">
|
||||
<MessageSquare className="h-12 w-12 mx-auto mb-4 opacity-30" />
|
||||
<p className="text-lg font-medium mb-2">{emptyStateMessage}</p>
|
||||
<p className="text-sm">{emptyStateSubtitle}</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{comments.map((comment) => (
|
||||
<Comment
|
||||
key={comment.id}
|
||||
root={root}
|
||||
comment={comment}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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}
|
||||
/>
|
||||
))
|
||||
|
||||
@@ -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",
|
||||
},
|
||||
}
|
||||
)
|
||||
@@ -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 }
|
||||
@@ -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",
|
||||
},
|
||||
}
|
||||
)
|
||||
@@ -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 }
|
||||
@@ -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>;
|
||||
|
||||
|
||||
@@ -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 (
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
@@ -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,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,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
|
||||
|
||||
@@ -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",
|
||||
},
|
||||
}
|
||||
)
|
||||
@@ -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,
|
||||
}
|
||||
@@ -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) => {
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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",
|
||||
},
|
||||
}
|
||||
)
|
||||
@@ -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 }
|
||||
@@ -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);
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import { NKinds, NostrEvent, NostrFilter } from '@nostrify/nostrify';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
|
||||
export function useComments(root: NostrEvent | URL, limit?: number) {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['comments', root instanceof URL ? root.toString() : root.id, limit],
|
||||
queryFn: async (c) => {
|
||||
const filter: NostrFilter = { kinds: [1111] };
|
||||
|
||||
if (root instanceof URL) {
|
||||
filter['#I'] = [root.toString()];
|
||||
} else if (NKinds.addressable(root.kind)) {
|
||||
const d = root.tags.find(([name]) => name === 'd')?.[1] ?? '';
|
||||
filter['#A'] = [`${root.kind}:${root.pubkey}:${d}`];
|
||||
} else if (NKinds.replaceable(root.kind)) {
|
||||
filter['#A'] = [`${root.kind}:${root.pubkey}:`];
|
||||
} else {
|
||||
filter['#E'] = [root.id];
|
||||
}
|
||||
|
||||
if (typeof limit === 'number') {
|
||||
filter.limit = limit;
|
||||
}
|
||||
|
||||
// Query for all kind 1111 comments that reference this addressable event regardless of depth
|
||||
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(5000)]);
|
||||
const events = await nostr.query([filter], { signal });
|
||||
|
||||
// Helper function to get tag value
|
||||
const getTagValue = (event: NostrEvent, tagName: string): string | undefined => {
|
||||
const tag = event.tags.find(([name]) => name === tagName);
|
||||
return tag?.[1];
|
||||
};
|
||||
|
||||
// Filter top-level comments (those with lowercase tag matching the root)
|
||||
const topLevelComments = events.filter(comment => {
|
||||
if (root instanceof URL) {
|
||||
return getTagValue(comment, 'i') === root.toString();
|
||||
} else if (NKinds.addressable(root.kind)) {
|
||||
const d = getTagValue(root, 'd') ?? '';
|
||||
return getTagValue(comment, 'a') === `${root.kind}:${root.pubkey}:${d}`;
|
||||
} else if (NKinds.replaceable(root.kind)) {
|
||||
return getTagValue(comment, 'a') === `${root.kind}:${root.pubkey}:`;
|
||||
} else {
|
||||
return getTagValue(comment, 'e') === root.id;
|
||||
}
|
||||
});
|
||||
|
||||
// Helper function to get all descendants of a comment
|
||||
const getDescendants = (parentId: string): NostrEvent[] => {
|
||||
const directReplies = events.filter(comment => {
|
||||
const eTag = getTagValue(comment, 'e');
|
||||
return eTag === parentId;
|
||||
});
|
||||
|
||||
const allDescendants = [...directReplies];
|
||||
|
||||
// Recursively get descendants of each direct reply
|
||||
for (const reply of directReplies) {
|
||||
allDescendants.push(...getDescendants(reply.id));
|
||||
}
|
||||
|
||||
return allDescendants;
|
||||
};
|
||||
|
||||
// Create a map of comment ID to its descendants
|
||||
const commentDescendants = new Map<string, NostrEvent[]>();
|
||||
for (const comment of events) {
|
||||
commentDescendants.set(comment.id, getDescendants(comment.id));
|
||||
}
|
||||
|
||||
// Sort top-level comments by creation time (newest first)
|
||||
const sortedTopLevel = topLevelComments.sort((a, b) => b.created_at - a.created_at);
|
||||
|
||||
return {
|
||||
allComments: events,
|
||||
topLevelComments: sortedTopLevel,
|
||||
getDescendants: (commentId: string) => {
|
||||
const descendants = commentDescendants.get(commentId) || [];
|
||||
// Sort descendants by creation time (oldest first for threaded display)
|
||||
return descendants.sort((a, b) => a.created_at - b.created_at);
|
||||
},
|
||||
getDirectReplies: (commentId: string) => {
|
||||
const directReplies = events.filter(comment => {
|
||||
const eTag = getTagValue(comment, 'e');
|
||||
return eTag === commentId;
|
||||
});
|
||||
// Sort direct replies by creation time (oldest first for threaded display)
|
||||
return directReplies.sort((a, b) => a.created_at - b.created_at);
|
||||
}
|
||||
};
|
||||
},
|
||||
enabled: !!root,
|
||||
});
|
||||
}
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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";
|
||||
@@ -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");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
import { NKinds, type NostrEvent } from '@nostrify/nostrify';
|
||||
|
||||
interface PostCommentParams {
|
||||
root: NostrEvent | URL; // The root event to comment on
|
||||
reply?: NostrEvent | URL; // Optional reply to another comment
|
||||
content: string;
|
||||
}
|
||||
|
||||
/** Post a NIP-22 (kind 1111) comment on an event. */
|
||||
export function usePostComment() {
|
||||
const { mutateAsync: publishEvent } = useNostrPublish();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async ({ root, reply, content }: PostCommentParams) => {
|
||||
const tags: string[][] = [];
|
||||
|
||||
// d-tag identifiers
|
||||
const dRoot = root instanceof URL ? '' : root.tags.find(([name]) => name === 'd')?.[1] ?? '';
|
||||
const dReply = reply instanceof URL ? '' : reply?.tags.find(([name]) => name === 'd')?.[1] ?? '';
|
||||
|
||||
// Root event tags
|
||||
if (root instanceof URL) {
|
||||
tags.push(['I', root.toString()]);
|
||||
} else if (NKinds.addressable(root.kind)) {
|
||||
tags.push(['A', `${root.kind}:${root.pubkey}:${dRoot}`]);
|
||||
} else if (NKinds.replaceable(root.kind)) {
|
||||
tags.push(['A', `${root.kind}:${root.pubkey}:`]);
|
||||
} else {
|
||||
tags.push(['E', root.id]);
|
||||
}
|
||||
if (root instanceof URL) {
|
||||
tags.push(['K', root.hostname]);
|
||||
} else {
|
||||
tags.push(['K', root.kind.toString()]);
|
||||
tags.push(['P', root.pubkey]);
|
||||
}
|
||||
|
||||
// Reply event tags
|
||||
if (reply) {
|
||||
if (reply instanceof URL) {
|
||||
tags.push(['i', reply.toString()]);
|
||||
} else if (NKinds.addressable(reply.kind)) {
|
||||
tags.push(['a', `${reply.kind}:${reply.pubkey}:${dReply}`]);
|
||||
} else if (NKinds.replaceable(reply.kind)) {
|
||||
tags.push(['a', `${reply.kind}:${reply.pubkey}:`]);
|
||||
} else {
|
||||
tags.push(['e', reply.id]);
|
||||
}
|
||||
if (reply instanceof URL) {
|
||||
tags.push(['k', reply.hostname]);
|
||||
} else {
|
||||
tags.push(['k', reply.kind.toString()]);
|
||||
tags.push(['p', reply.pubkey]);
|
||||
}
|
||||
} else {
|
||||
// If this is a top-level comment, use the root event's tags
|
||||
if (root instanceof URL) {
|
||||
tags.push(['i', root.toString()]);
|
||||
} else if (NKinds.addressable(root.kind)) {
|
||||
tags.push(['a', `${root.kind}:${root.pubkey}:${dRoot}`]);
|
||||
} else if (NKinds.replaceable(root.kind)) {
|
||||
tags.push(['a', `${root.kind}:${root.pubkey}:`]);
|
||||
} else {
|
||||
tags.push(['e', root.id]);
|
||||
}
|
||||
if (root instanceof URL) {
|
||||
tags.push(['k', root.hostname]);
|
||||
} else {
|
||||
tags.push(['k', root.kind.toString()]);
|
||||
tags.push(['p', root.pubkey]);
|
||||
}
|
||||
}
|
||||
|
||||
const event = await publishEvent({
|
||||
kind: 1111,
|
||||
content,
|
||||
tags,
|
||||
});
|
||||
|
||||
return event;
|
||||
},
|
||||
onSuccess: (_, { root }) => {
|
||||
// Invalidate and refetch comments
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['comments', root instanceof URL ? root.toString() : root.id]
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -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
@@ -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"]
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -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');
|
||||
});
|
||||
});
|
||||
@@ -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(' ');
|
||||
}
|
||||
@@ -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
@@ -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';
|
||||
|
||||
// FIXME: a custom font should be used. Eg:
|
||||
// import '@fontsource-variable/<font-name>';
|
||||
|
||||
createRoot(document.getElementById("root")!).render(<App />);
|
||||
+15
-4
@@ -1,11 +1,22 @@
|
||||
// Update this page (the content is just a fallback if you fail to update the page)
|
||||
import { useSeoMeta } from '@unhead/react';
|
||||
|
||||
// FIXME: Update this page (the content is just a fallback if you fail to update the page)
|
||||
|
||||
const Index = () => {
|
||||
useSeoMeta({
|
||||
title: 'Welcome to Your Blank App',
|
||||
description: 'A modern Nostr client application built with React, TailwindCSS, and Nostrify.',
|
||||
});
|
||||
|
||||
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">Welcome to Your Blank App</h1>
|
||||
<p className="text-xl text-gray-600">Start building your amazing project here!</p>
|
||||
<h1 className="text-4xl font-bold mb-4 text-gray-900 dark:text-gray-100">
|
||||
Welcome to Your Blank App
|
||||
</h1>
|
||||
<p className="text-xl text-gray-600 dark:text-gray-400">
|
||||
Start building your amazing project here!
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
+10
-4
@@ -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>
|
||||
|
||||
@@ -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;
|
||||
@@ -0,0 +1,75 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import puppeteer from 'puppeteer';
|
||||
|
||||
const SITE_URL = process.env.DEPLOY_URL;
|
||||
|
||||
if (!SITE_URL) {
|
||||
console.error('❌ DEPLOY_URL environment variable is required');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
async function checkConsole() {
|
||||
console.log(`🔍 Checking ${SITE_URL} for console errors...`);
|
||||
|
||||
const browser = await puppeteer.launch({ headless: true });
|
||||
|
||||
try {
|
||||
const page = await browser.newPage();
|
||||
|
||||
const errors = [];
|
||||
const warnings = [];
|
||||
|
||||
page.on('console', (msg) => {
|
||||
const text = msg.text();
|
||||
const type = msg.type();
|
||||
|
||||
if (type === 'error') {
|
||||
errors.push(text);
|
||||
} else if (type === 'warn') {
|
||||
warnings.push(text);
|
||||
}
|
||||
});
|
||||
|
||||
page.on('pageerror', (error) => {
|
||||
errors.push(`Page error: ${error.message}`);
|
||||
});
|
||||
|
||||
await page.goto(SITE_URL, {
|
||||
waitUntil: 'networkidle0',
|
||||
timeout: 15000
|
||||
});
|
||||
|
||||
// Allow time for any async errors
|
||||
await new Promise(resolve => setTimeout(resolve, 1000));
|
||||
|
||||
// Filter out common non-critical issues
|
||||
const filteredErrors = errors.filter(error =>
|
||||
!error.includes('404') &&
|
||||
!error.includes('manifest.webmanifest') &&
|
||||
!error.includes('favicon.ico') &&
|
||||
!error.includes('net::ERR_ABORTED')
|
||||
);
|
||||
|
||||
if (filteredErrors.length > 0) {
|
||||
console.error('❌ Console errors found:');
|
||||
filteredErrors.forEach(err => console.error(` - ${err}`));
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (warnings.length > 0) {
|
||||
console.warn('⚠️ Console warnings (non-blocking):');
|
||||
warnings.forEach(warn => console.warn(` - ${warn}`));
|
||||
}
|
||||
|
||||
console.log('✅ No critical console errors found!');
|
||||
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
}
|
||||
|
||||
checkConsole().catch(error => {
|
||||
console.error('❌ Console check failed:', error.message);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -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
@@ -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"
|
||||
]
|
||||
}
|
||||
+2
-1
@@ -1,4 +1,5 @@
|
||||
import type { Config } from "tailwindcss";
|
||||
import tailwindcssAnimate from "tailwindcss-animate";
|
||||
|
||||
export default {
|
||||
darkMode: ["class"],
|
||||
@@ -92,5 +93,5 @@ export default {
|
||||
}
|
||||
}
|
||||
},
|
||||
plugins: [require("tailwindcss-animate")],
|
||||
plugins: [tailwindcssAnimate],
|
||||
} satisfies Config;
|
||||
+18
-4
@@ -1,17 +1,31 @@
|
||||
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");
|
||||
},
|
||||
env: {
|
||||
DEBUG_PRINT_LIMIT: '0', // Suppress DOM output that exceeds AI context windows
|
||||
},
|
||||
},
|
||||
resolve: {
|
||||
alias: {
|
||||
"@": path.resolve(__dirname, "./src"),
|
||||
},
|
||||
},
|
||||
}));
|
||||
}));
|
||||
Reference in new issue
Block a user