Compare commits
18 Commits
3fec791f28
...
b4c03ff25e
| Author | SHA1 | Date | |
|---|---|---|---|
| b4c03ff25e | |||
| fd5716f39e | |||
| 954e73c007 | |||
| 48ef4f60df | |||
| e39ba6be97 | |||
| 3b7c246a47 | |||
| 5be55cec7c | |||
| dab77befc2 | |||
| 076cf8acd0 | |||
| ae8d547486 | |||
| 3d9e2452c4 | |||
| db9d6399dd | |||
| a897e8ead1 | |||
| c3e3018018 | |||
| be389c6cfa | |||
| ada8e03a04 | |||
| 956de68591 | |||
| e25f917b9a |
6
.claude/skills/create-agent/.openskills.json
Normal file
6
.claude/skills/create-agent/.openskills.json
Normal file
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"source": "/tmp/skill-selector-curated-812268656",
|
||||
"sourceType": "local",
|
||||
"localPath": "/tmp/skill-selector-curated-812268656/create-agent",
|
||||
"installedAt": "2026-04-07T03:45:37.970Z"
|
||||
}
|
||||
852
.claude/skills/create-agent/SKILL.md
Normal file
852
.claude/skills/create-agent/SKILL.md
Normal file
@@ -0,0 +1,852 @@
|
||||
---
|
||||
name: create-agent
|
||||
description: Bootstrap a modular AI agent with OpenRouter SDK, extensible hooks, and optional Ink TUI
|
||||
metadata:
|
||||
version: 0.0.0
|
||||
homepage: https://openrouter.ai
|
||||
---
|
||||
|
||||
# Build a Modular AI Agent with OpenRouter
|
||||
|
||||
This skill helps you create a **modular AI agent** with:
|
||||
|
||||
- **Standalone Agent Core** - Runs independently, extensible via hooks
|
||||
- **OpenRouter SDK** - Unified access to 300+ language models
|
||||
- **Optional Ink TUI** - Beautiful terminal UI (separate from agent logic)
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────┐
|
||||
│ Your Application │
|
||||
├─────────────────────────────────────────────────────┤
|
||||
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
|
||||
│ │ Ink TUI │ │ HTTP API │ │ Discord │ │
|
||||
│ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ │
|
||||
│ │ │ │ │
|
||||
│ └────────────────┼────────────────┘ │
|
||||
│ ▼ │
|
||||
│ ┌───────────────────────┐ │
|
||||
│ │ Agent Core │ │
|
||||
│ │ (hooks & lifecycle) │ │
|
||||
│ └───────────┬───────────┘ │
|
||||
│ ▼ │
|
||||
│ ┌───────────────────────┐ │
|
||||
│ │ OpenRouter SDK │ │
|
||||
│ └───────────────────────┘ │
|
||||
└─────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Get an OpenRouter API key at: https://openrouter.ai/settings/keys
|
||||
|
||||
⚠️ **Security:** Never commit API keys. Use environment variables.
|
||||
|
||||
## Project Setup
|
||||
|
||||
### Step 1: Initialize Project
|
||||
|
||||
```bash
|
||||
mkdir my-agent && cd my-agent
|
||||
npm init -y
|
||||
npm pkg set type="module"
|
||||
```
|
||||
|
||||
### Step 2: Install Dependencies
|
||||
|
||||
```bash
|
||||
npm install @openrouter/sdk zod eventemitter3
|
||||
npm install ink react # Optional: only for TUI
|
||||
npm install -D typescript @types/react tsx
|
||||
```
|
||||
|
||||
### Step 3: Create tsconfig.json
|
||||
|
||||
```json
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"jsx": "react-jsx",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"outDir": "dist"
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
```
|
||||
|
||||
### Step 4: Add Scripts to package.json
|
||||
|
||||
```json
|
||||
{
|
||||
"scripts": {
|
||||
"start": "tsx src/cli.tsx",
|
||||
"start:headless": "tsx src/headless.ts",
|
||||
"dev": "tsx watch src/cli.tsx"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## File Structure
|
||||
|
||||
```bash
|
||||
src/
|
||||
├── agent.ts # Standalone agent core with hooks
|
||||
├── tools.ts # Tool definitions
|
||||
├── cli.tsx # Ink TUI (optional interface)
|
||||
└── headless.ts # Headless usage example
|
||||
```
|
||||
|
||||
## Step 1: Agent Core with Hooks
|
||||
|
||||
Create `src/agent.ts` - the standalone agent that can run anywhere:
|
||||
|
||||
```typescript
|
||||
import { OpenRouter, tool, stepCountIs } from '@openrouter/sdk';
|
||||
import type { Tool, StopCondition, StreamableOutputItem } from '@openrouter/sdk';
|
||||
import { EventEmitter } from 'eventemitter3';
|
||||
import { z } from 'zod';
|
||||
|
||||
// Message types
|
||||
export interface Message {
|
||||
role: 'user' | 'assistant' | 'system';
|
||||
content: string;
|
||||
}
|
||||
|
||||
// Agent events for hooks (items-based streaming model)
|
||||
export interface AgentEvents {
|
||||
'message:user': (message: Message) => void;
|
||||
'message:assistant': (message: Message) => void;
|
||||
'item:update': (item: StreamableOutputItem) => void; // Items emitted with same ID, replace by ID
|
||||
'stream:start': () => void;
|
||||
'stream:delta': (delta: string, accumulated: string) => void;
|
||||
'stream:end': (fullText: string) => void;
|
||||
'tool:call': (name: string, args: unknown) => void;
|
||||
'tool:result': (name: string, result: unknown) => void;
|
||||
'reasoning:update': (text: string) => void; // Extended thinking content
|
||||
'error': (error: Error) => void;
|
||||
'thinking:start': () => void;
|
||||
'thinking:end': () => void;
|
||||
}
|
||||
|
||||
|
||||
// Agent configuration
|
||||
export interface AgentConfig {
|
||||
apiKey: string;
|
||||
model?: string;
|
||||
instructions?: string;
|
||||
tools?: Tool<z.ZodTypeAny, z.ZodTypeAny>[];
|
||||
maxSteps?: number;
|
||||
}
|
||||
|
||||
// The Agent class - runs independently of any UI
|
||||
export class Agent extends EventEmitter<AgentEvents> {
|
||||
private client: OpenRouter;
|
||||
private messages: Message[] = [];
|
||||
private config: Required<Omit<AgentConfig, 'apiKey'>> & { apiKey: string };
|
||||
|
||||
constructor(config: AgentConfig) {
|
||||
super();
|
||||
this.client = new OpenRouter({ apiKey: config.apiKey });
|
||||
this.config = {
|
||||
apiKey: config.apiKey,
|
||||
model: config.model ?? 'openrouter/auto',
|
||||
instructions: config.instructions ?? 'You are a helpful assistant.',
|
||||
tools: config.tools ?? [],
|
||||
maxSteps: config.maxSteps ?? 5,
|
||||
};
|
||||
}
|
||||
|
||||
// Get conversation history
|
||||
getMessages(): Message[] {
|
||||
return [...this.messages];
|
||||
}
|
||||
|
||||
// Clear conversation
|
||||
clearHistory(): void {
|
||||
this.messages = [];
|
||||
}
|
||||
|
||||
// Add a system message
|
||||
setInstructions(instructions: string): void {
|
||||
this.config.instructions = instructions;
|
||||
}
|
||||
|
||||
// Register additional tools at runtime
|
||||
addTool(newTool: Tool<z.ZodTypeAny, z.ZodTypeAny>): void {
|
||||
this.config.tools.push(newTool);
|
||||
}
|
||||
|
||||
// Send a message and get streaming response using items-based model
|
||||
// Items are emitted multiple times with the same ID but progressively updated content
|
||||
// Replace items by their ID rather than accumulating chunks
|
||||
async send(content: string): Promise<string> {
|
||||
const userMessage: Message = { role: 'user', content };
|
||||
this.messages.push(userMessage);
|
||||
this.emit('message:user', userMessage);
|
||||
this.emit('thinking:start');
|
||||
|
||||
try {
|
||||
const result = this.client.callModel({
|
||||
model: this.config.model,
|
||||
instructions: this.config.instructions,
|
||||
input: this.messages.map((m) => ({ role: m.role, content: m.content })),
|
||||
tools: this.config.tools.length > 0 ? this.config.tools : undefined,
|
||||
stopWhen: [stepCountIs(this.config.maxSteps)],
|
||||
});
|
||||
|
||||
this.emit('stream:start');
|
||||
let fullText = '';
|
||||
|
||||
// Use getItemsStream() for items-based streaming (recommended)
|
||||
// Each item emission is complete - replace by ID, don't accumulate
|
||||
for await (const item of result.getItemsStream()) {
|
||||
// Emit the item for UI state management (use Map keyed by item.id)
|
||||
this.emit('item:update', item);
|
||||
|
||||
switch (item.type) {
|
||||
case 'message':
|
||||
// Message items contain progressively updated content
|
||||
const textContent = item.content?.find((c: { type: string }) => c.type === 'output_text');
|
||||
if (textContent && 'text' in textContent) {
|
||||
const newText = textContent.text;
|
||||
if (newText !== fullText) {
|
||||
const delta = newText.slice(fullText.length);
|
||||
fullText = newText;
|
||||
this.emit('stream:delta', delta, fullText);
|
||||
}
|
||||
}
|
||||
break;
|
||||
case 'function_call':
|
||||
// Function call arguments stream progressively
|
||||
if (item.status === 'completed') {
|
||||
this.emit('tool:call', item.name, JSON.parse(item.arguments || '{}'));
|
||||
}
|
||||
break;
|
||||
case 'function_call_output':
|
||||
this.emit('tool:result', item.callId, item.output);
|
||||
break;
|
||||
case 'reasoning':
|
||||
// Extended thinking/reasoning content
|
||||
const reasoningText = item.content?.find((c: { type: string }) => c.type === 'reasoning_text');
|
||||
if (reasoningText && 'text' in reasoningText) {
|
||||
this.emit('reasoning:update', reasoningText.text);
|
||||
}
|
||||
break;
|
||||
// Additional item types: web_search_call, file_search_call, image_generation_call
|
||||
}
|
||||
}
|
||||
|
||||
// Get final text if streaming didn't capture it
|
||||
if (!fullText) {
|
||||
fullText = await result.getText();
|
||||
}
|
||||
|
||||
this.emit('stream:end', fullText);
|
||||
|
||||
const assistantMessage: Message = { role: 'assistant', content: fullText };
|
||||
this.messages.push(assistantMessage);
|
||||
this.emit('message:assistant', assistantMessage);
|
||||
|
||||
return fullText;
|
||||
} catch (err) {
|
||||
const error = err instanceof Error ? err : new Error(String(err));
|
||||
this.emit('error', error);
|
||||
throw error;
|
||||
} finally {
|
||||
this.emit('thinking:end');
|
||||
}
|
||||
}
|
||||
|
||||
// Send without streaming (simpler for programmatic use)
|
||||
async sendSync(content: string): Promise<string> {
|
||||
const userMessage: Message = { role: 'user', content };
|
||||
this.messages.push(userMessage);
|
||||
this.emit('message:user', userMessage);
|
||||
|
||||
try {
|
||||
const result = this.client.callModel({
|
||||
model: this.config.model,
|
||||
instructions: this.config.instructions,
|
||||
input: this.messages.map((m) => ({ role: m.role, content: m.content })),
|
||||
tools: this.config.tools.length > 0 ? this.config.tools : undefined,
|
||||
stopWhen: [stepCountIs(this.config.maxSteps)],
|
||||
});
|
||||
|
||||
const fullText = await result.getText();
|
||||
const assistantMessage: Message = { role: 'assistant', content: fullText };
|
||||
this.messages.push(assistantMessage);
|
||||
this.emit('message:assistant', assistantMessage);
|
||||
|
||||
return fullText;
|
||||
} catch (err) {
|
||||
const error = err instanceof Error ? err : new Error(String(err));
|
||||
this.emit('error', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Factory function for easy creation
|
||||
export function createAgent(config: AgentConfig): Agent {
|
||||
return new Agent(config);
|
||||
}
|
||||
```
|
||||
|
||||
## Step 2: Define Tools
|
||||
|
||||
Create `src/tools.ts`:
|
||||
|
||||
```typescript
|
||||
import { tool } from '@openrouter/sdk';
|
||||
import { z } from 'zod';
|
||||
|
||||
export const timeTool = tool({
|
||||
name: 'get_current_time',
|
||||
description: 'Get the current date and time',
|
||||
inputSchema: z.object({
|
||||
timezone: z.string().optional().describe('Timezone (e.g., "UTC", "America/New_York")'),
|
||||
}),
|
||||
execute: async ({ timezone }) => {
|
||||
return {
|
||||
time: new Date().toLocaleString('en-US', { timeZone: timezone || 'UTC' }),
|
||||
timezone: timezone || 'UTC',
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
export const calculatorTool = tool({
|
||||
name: 'calculate',
|
||||
description: 'Perform mathematical calculations',
|
||||
inputSchema: z.object({
|
||||
expression: z.string().describe('Math expression (e.g., "2 + 2", "sqrt(16)")'),
|
||||
}),
|
||||
execute: async ({ expression }) => {
|
||||
// Simple safe eval for basic math
|
||||
const sanitized = expression.replace(/[^0-9+\-*/().\s]/g, '');
|
||||
const result = Function(`"use strict"; return (${sanitized})`)();
|
||||
return { expression, result };
|
||||
},
|
||||
});
|
||||
|
||||
export const defaultTools = [timeTool, calculatorTool];
|
||||
```
|
||||
|
||||
## Step 3: Headless Usage (No UI)
|
||||
|
||||
Create `src/headless.ts` - use the agent programmatically:
|
||||
|
||||
```typescript
|
||||
import { createAgent } from './agent.js';
|
||||
import { defaultTools } from './tools.js';
|
||||
|
||||
async function main() {
|
||||
const agent = createAgent({
|
||||
apiKey: process.env.OPENROUTER_API_KEY!,
|
||||
model: 'openrouter/auto',
|
||||
instructions: 'You are a helpful assistant with access to tools.',
|
||||
tools: defaultTools,
|
||||
});
|
||||
|
||||
// Hook into events
|
||||
agent.on('thinking:start', () => console.log('\n🤔 Thinking...'));
|
||||
agent.on('tool:call', (name, args) => console.log(`🔧 Using ${name}:`, args));
|
||||
agent.on('stream:delta', (delta) => process.stdout.write(delta));
|
||||
agent.on('stream:end', () => console.log('\n'));
|
||||
agent.on('error', (err) => console.error('❌ Error:', err.message));
|
||||
|
||||
// Interactive loop
|
||||
const readline = await import('readline');
|
||||
const rl = readline.createInterface({
|
||||
input: process.stdin,
|
||||
output: process.stdout,
|
||||
});
|
||||
|
||||
console.log('Agent ready. Type your message (Ctrl+C to exit):\n');
|
||||
|
||||
const prompt = () => {
|
||||
rl.question('You: ', async (input) => {
|
||||
if (!input.trim()) {
|
||||
prompt();
|
||||
return;
|
||||
}
|
||||
await agent.send(input);
|
||||
prompt();
|
||||
});
|
||||
};
|
||||
|
||||
prompt();
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
```
|
||||
|
||||
Run headless: `OPENROUTER_API_KEY=sk-or-... npm run start:headless`
|
||||
|
||||
## Step 4: Ink TUI (Optional Interface)
|
||||
|
||||
Create `src/cli.tsx` - a beautiful terminal UI that uses the agent with items-based streaming:
|
||||
|
||||
```tsx
|
||||
import React, { useState, useEffect, useCallback } from 'react';
|
||||
import { render, Box, Text, useInput, useApp } from 'ink';
|
||||
import type { StreamableOutputItem } from '@openrouter/sdk';
|
||||
import { createAgent, type Agent, type Message } from './agent.js';
|
||||
import { defaultTools } from './tools.js';
|
||||
|
||||
// Initialize agent (runs independently of UI)
|
||||
const agent = createAgent({
|
||||
apiKey: process.env.OPENROUTER_API_KEY!,
|
||||
model: 'openrouter/auto',
|
||||
instructions: 'You are a helpful assistant. Be concise.',
|
||||
tools: defaultTools,
|
||||
});
|
||||
|
||||
function ChatMessage({ message }: { message: Message }) {
|
||||
const isUser = message.role === 'user';
|
||||
return (
|
||||
<Box flexDirection="column" marginBottom={1}>
|
||||
<Text bold color={isUser ? 'cyan' : 'green'}>
|
||||
{isUser ? '▶ You' : '◀ Assistant'}
|
||||
</Text>
|
||||
<Text wrap="wrap">{message.content}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
// Render streaming items by type using the items-based pattern
|
||||
function ItemRenderer({ item }: { item: StreamableOutputItem }) {
|
||||
switch (item.type) {
|
||||
case 'message': {
|
||||
const textContent = item.content?.find((c: { type: string }) => c.type === 'output_text');
|
||||
const text = textContent && 'text' in textContent ? textContent.text : '';
|
||||
return (
|
||||
<Box flexDirection="column" marginBottom={1}>
|
||||
<Text bold color="green">◀ Assistant</Text>
|
||||
<Text wrap="wrap">{text}</Text>
|
||||
{item.status !== 'completed' && <Text color="gray">▌</Text>}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
case 'function_call':
|
||||
return (
|
||||
<Text color="yellow">
|
||||
{item.status === 'completed' ? ' ✓' : ' 🔧'} {item.name}
|
||||
{item.status === 'in_progress' && '...'}
|
||||
</Text>
|
||||
);
|
||||
case 'reasoning': {
|
||||
const reasoningText = item.content?.find((c: { type: string }) => c.type === 'reasoning_text');
|
||||
const text = reasoningText && 'text' in reasoningText ? reasoningText.text : '';
|
||||
return (
|
||||
<Box flexDirection="column" marginBottom={1}>
|
||||
<Text bold color="magenta">💭 Thinking</Text>
|
||||
<Text wrap="wrap" color="gray">{text}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function InputField({
|
||||
value,
|
||||
onChange,
|
||||
onSubmit,
|
||||
disabled,
|
||||
}: {
|
||||
value: string;
|
||||
onChange: (v: string) => void;
|
||||
onSubmit: () => void;
|
||||
disabled: boolean;
|
||||
}) {
|
||||
useInput((input, key) => {
|
||||
if (disabled) return;
|
||||
if (key.return) onSubmit();
|
||||
else if (key.backspace || key.delete) onChange(value.slice(0, -1));
|
||||
else if (input && !key.ctrl && !key.meta) onChange(value + input);
|
||||
});
|
||||
|
||||
return (
|
||||
<Box>
|
||||
<Text color="yellow">{'> '}</Text>
|
||||
<Text>{value}</Text>
|
||||
<Text color="gray">{disabled ? ' ···' : '█'}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
function App() {
|
||||
const { exit } = useApp();
|
||||
const [messages, setMessages] = useState<Message[]>([]);
|
||||
const [input, setInput] = useState('');
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
// Use Map keyed by item ID for efficient React state updates (items-based pattern)
|
||||
const [items, setItems] = useState<Map<string, StreamableOutputItem>>(new Map());
|
||||
|
||||
useInput((_, key) => {
|
||||
if (key.escape) exit();
|
||||
});
|
||||
|
||||
// Subscribe to agent events using items-based streaming
|
||||
useEffect(() => {
|
||||
const onThinkingStart = () => {
|
||||
setIsLoading(true);
|
||||
setItems(new Map()); // Clear items for new response
|
||||
};
|
||||
|
||||
// Items-based streaming: replace items by ID, don't accumulate
|
||||
const onItemUpdate = (item: StreamableOutputItem) => {
|
||||
setItems((prev) => new Map(prev).set(item.id, item));
|
||||
};
|
||||
|
||||
const onMessageAssistant = () => {
|
||||
setMessages(agent.getMessages());
|
||||
setItems(new Map()); // Clear streaming items
|
||||
setIsLoading(false);
|
||||
};
|
||||
|
||||
const onError = (err: Error) => {
|
||||
setIsLoading(false);
|
||||
};
|
||||
|
||||
agent.on('thinking:start', onThinkingStart);
|
||||
agent.on('item:update', onItemUpdate);
|
||||
agent.on('message:assistant', onMessageAssistant);
|
||||
agent.on('error', onError);
|
||||
|
||||
return () => {
|
||||
agent.off('thinking:start', onThinkingStart);
|
||||
agent.off('item:update', onItemUpdate);
|
||||
agent.off('message:assistant', onMessageAssistant);
|
||||
agent.off('error', onError);
|
||||
};
|
||||
}, []);
|
||||
|
||||
const sendMessage = useCallback(async () => {
|
||||
if (!input.trim() || isLoading) return;
|
||||
const text = input.trim();
|
||||
setInput('');
|
||||
setMessages((prev) => [...prev, { role: 'user', content: text }]);
|
||||
await agent.send(text);
|
||||
}, [input, isLoading]);
|
||||
|
||||
return (
|
||||
<Box flexDirection="column" padding={1}>
|
||||
<Box marginBottom={1}>
|
||||
<Text bold color="magenta">🤖 OpenRouter Agent</Text>
|
||||
<Text color="gray"> (Esc to exit)</Text>
|
||||
</Box>
|
||||
|
||||
<Box flexDirection="column" marginBottom={1}>
|
||||
{/* Render completed messages */}
|
||||
{messages.map((msg, i) => (
|
||||
<ChatMessage key={i} message={msg} />
|
||||
))}
|
||||
|
||||
{/* Render streaming items by type (items-based pattern) */}
|
||||
{Array.from(items.values()).map((item) => (
|
||||
<ItemRenderer key={item.id} item={item} />
|
||||
))}
|
||||
</Box>
|
||||
|
||||
<Box borderStyle="single" borderColor="gray" paddingX={1}>
|
||||
<InputField
|
||||
value={input}
|
||||
onChange={setInput}
|
||||
onSubmit={sendMessage}
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
render(<App />);
|
||||
```
|
||||
|
||||
Run TUI: `OPENROUTER_API_KEY=sk-or-... npm start`
|
||||
|
||||
## Understanding Items-Based Streaming
|
||||
|
||||
The OpenRouter SDK uses an **items-based streaming model** - a key paradigm where items are emitted multiple times with the same ID but progressively updated content. Instead of accumulating chunks, you **replace items by their ID**.
|
||||
|
||||
### How It Works
|
||||
|
||||
Each iteration of `getItemsStream()` yields a complete item with updated content:
|
||||
|
||||
```typescript
|
||||
// Iteration 1: Partial message
|
||||
{ id: "msg_123", type: "message", content: [{ type: "output_text", text: "Hello" }] }
|
||||
|
||||
// Iteration 2: Updated message (replace, don't append)
|
||||
{ id: "msg_123", type: "message", content: [{ type: "output_text", text: "Hello world" }] }
|
||||
```
|
||||
|
||||
For function calls, arguments stream progressively:
|
||||
|
||||
```typescript
|
||||
// Iteration 1: Partial arguments
|
||||
{ id: "call_456", type: "function_call", name: "get_weather", arguments: "{\"q" }
|
||||
|
||||
// Iteration 2: Complete arguments
|
||||
{ id: "call_456", type: "function_call", name: "get_weather", arguments: "{\"query\": \"Paris\"}", status: "completed" }
|
||||
```
|
||||
|
||||
### Why Items Are Better
|
||||
|
||||
**Traditional (accumulation required):**
|
||||
```typescript
|
||||
let text = '';
|
||||
for await (const chunk of result.getTextStream()) {
|
||||
text += chunk; // Manual accumulation
|
||||
updateUI(text);
|
||||
}
|
||||
```
|
||||
|
||||
**Items (complete replacement):**
|
||||
```typescript
|
||||
const items = new Map<string, StreamableOutputItem>();
|
||||
for await (const item of result.getItemsStream()) {
|
||||
items.set(item.id, item); // Replace by ID
|
||||
updateUI(items);
|
||||
}
|
||||
```
|
||||
|
||||
Benefits:
|
||||
- **No manual chunk management** - each item is complete
|
||||
- **Handles concurrent outputs** - function calls and messages can stream in parallel
|
||||
- **Full TypeScript inference** for all item types
|
||||
- **Natural Map-based state** works perfectly with React/UI frameworks
|
||||
|
||||
## Extending the Agent
|
||||
|
||||
### Add Custom Hooks
|
||||
|
||||
```typescript
|
||||
const agent = createAgent({ apiKey: '...' });
|
||||
|
||||
// Log all events
|
||||
agent.on('message:user', (msg) => {
|
||||
saveToDatabase('user', msg.content);
|
||||
});
|
||||
|
||||
agent.on('message:assistant', (msg) => {
|
||||
saveToDatabase('assistant', msg.content);
|
||||
sendWebhook('new_message', msg);
|
||||
});
|
||||
|
||||
agent.on('tool:call', (name, args) => {
|
||||
analytics.track('tool_used', { name, args });
|
||||
});
|
||||
|
||||
agent.on('error', (err) => {
|
||||
errorReporting.capture(err);
|
||||
});
|
||||
```
|
||||
|
||||
### Use with HTTP Server
|
||||
|
||||
```typescript
|
||||
import express from 'express';
|
||||
import { createAgent } from './agent.js';
|
||||
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
|
||||
// One agent per session (store in memory or Redis)
|
||||
const sessions = new Map<string, Agent>();
|
||||
|
||||
app.post('/chat', async (req, res) => {
|
||||
const { sessionId, message } = req.body;
|
||||
|
||||
let agent = sessions.get(sessionId);
|
||||
if (!agent) {
|
||||
agent = createAgent({ apiKey: process.env.OPENROUTER_API_KEY! });
|
||||
sessions.set(sessionId, agent);
|
||||
}
|
||||
|
||||
const response = await agent.sendSync(message);
|
||||
res.json({ response, history: agent.getMessages() });
|
||||
});
|
||||
|
||||
app.listen(3000);
|
||||
```
|
||||
|
||||
### Use with Discord
|
||||
|
||||
```typescript
|
||||
import { Client, GatewayIntentBits } from 'discord.js';
|
||||
import { createAgent } from './agent.js';
|
||||
|
||||
const discord = new Client({
|
||||
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages],
|
||||
});
|
||||
|
||||
const agents = new Map<string, Agent>();
|
||||
|
||||
discord.on('messageCreate', async (msg) => {
|
||||
if (msg.author.bot) return;
|
||||
|
||||
let agent = agents.get(msg.channelId);
|
||||
if (!agent) {
|
||||
agent = createAgent({ apiKey: process.env.OPENROUTER_API_KEY! });
|
||||
agents.set(msg.channelId, agent);
|
||||
}
|
||||
|
||||
const response = await agent.sendSync(msg.content);
|
||||
await msg.reply(response);
|
||||
});
|
||||
|
||||
discord.login(process.env.DISCORD_TOKEN);
|
||||
```
|
||||
|
||||
## Agent API Reference
|
||||
|
||||
### Constructor Options
|
||||
|
||||
| Option | Type | Default | Description |
|
||||
|--------|------|---------|-------------|
|
||||
| apiKey | string | required | OpenRouter API key |
|
||||
| model | string | 'openrouter/auto' | Model to use |
|
||||
| instructions | string | 'You are a helpful assistant.' | System prompt |
|
||||
| tools | Tool[] | [] | Available tools |
|
||||
| maxSteps | number | 5 | Max agentic loop iterations |
|
||||
|
||||
### Methods
|
||||
|
||||
| Method | Returns | Description |
|
||||
|--------|---------|-------------|
|
||||
| `send(content)` | Promise<string> | Send message with streaming |
|
||||
| `sendSync(content)` | Promise<string> | Send message without streaming |
|
||||
| `getMessages()` | Message[] | Get conversation history |
|
||||
| `clearHistory()` | void | Clear conversation |
|
||||
| `setInstructions(text)` | void | Update system prompt |
|
||||
| `addTool(tool)` | void | Add tool at runtime |
|
||||
|
||||
### Events
|
||||
|
||||
| Event | Payload | Description |
|
||||
|-------|---------|-------------|
|
||||
| `message:user` | Message | User message added |
|
||||
| `message:assistant` | Message | Assistant response complete |
|
||||
| `item:update` | StreamableOutputItem | Item emitted (replace by ID, don't accumulate) |
|
||||
| `stream:start` | - | Streaming started |
|
||||
| `stream:delta` | (delta, accumulated) | New text chunk |
|
||||
| `stream:end` | fullText | Streaming complete |
|
||||
| `tool:call` | (name, args) | Tool being called |
|
||||
| `tool:result` | (name, result) | Tool returned result |
|
||||
| `reasoning:update` | text | Extended thinking content |
|
||||
| `thinking:start` | - | Agent processing |
|
||||
| `thinking:end` | - | Agent done processing |
|
||||
| `error` | Error | Error occurred |
|
||||
|
||||
### Item Types (from getItemsStream)
|
||||
|
||||
The SDK uses an items-based streaming model where items are emitted multiple times with the same ID but progressively updated content. Replace items by their ID rather than accumulating chunks.
|
||||
|
||||
| Type | Purpose |
|
||||
|------|---------|
|
||||
| `message` | Assistant text responses |
|
||||
| `function_call` | Tool invocations with streaming arguments |
|
||||
| `function_call_output` | Results from executed tools |
|
||||
| `reasoning` | Extended thinking content |
|
||||
| `web_search_call` | Web search operations |
|
||||
| `file_search_call` | File search operations |
|
||||
| `image_generation_call` | Image generation operations |
|
||||
|
||||
## Discovering Models
|
||||
|
||||
**Do not hardcode model IDs** - they change frequently. Use the models API:
|
||||
|
||||
### Fetch Available Models
|
||||
|
||||
```typescript
|
||||
interface OpenRouterModel {
|
||||
id: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
context_length: number;
|
||||
pricing: { prompt: string; completion: string };
|
||||
top_provider?: { is_moderated: boolean };
|
||||
}
|
||||
|
||||
async function fetchModels(): Promise<OpenRouterModel[]> {
|
||||
const res = await fetch('https://openrouter.ai/api/v1/models');
|
||||
const data = await res.json();
|
||||
return data.data;
|
||||
}
|
||||
|
||||
// Find models by criteria
|
||||
async function findModels(filter: {
|
||||
author?: string; // e.g., 'anthropic', 'openai', 'google'
|
||||
minContext?: number; // e.g., 100000 for 100k context
|
||||
maxPromptPrice?: number; // e.g., 0.001 for cheap models
|
||||
}): Promise<OpenRouterModel[]> {
|
||||
const models = await fetchModels();
|
||||
|
||||
return models.filter((m) => {
|
||||
if (filter.author && !m.id.startsWith(filter.author + '/')) return false;
|
||||
if (filter.minContext && m.context_length < filter.minContext) return false;
|
||||
if (filter.maxPromptPrice) {
|
||||
const price = parseFloat(m.pricing.prompt);
|
||||
if (price > filter.maxPromptPrice) return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
// Example: Get latest Claude models
|
||||
const claudeModels = await findModels({ author: 'anthropic' });
|
||||
console.log(claudeModels.map((m) => m.id));
|
||||
|
||||
// Example: Get models with 100k+ context
|
||||
const longContextModels = await findModels({ minContext: 100000 });
|
||||
|
||||
// Example: Get cheap models
|
||||
const cheapModels = await findModels({ maxPromptPrice: 0.0005 });
|
||||
```
|
||||
|
||||
### Dynamic Model Selection in Agent
|
||||
|
||||
```typescript
|
||||
// Create agent with dynamic model selection
|
||||
const models = await fetchModels();
|
||||
const bestModel = models.find((m) => m.id.includes('claude')) || models[0];
|
||||
|
||||
const agent = createAgent({
|
||||
apiKey: process.env.OPENROUTER_API_KEY!,
|
||||
model: bestModel.id, // Use discovered model
|
||||
instructions: 'You are a helpful assistant.',
|
||||
});
|
||||
```
|
||||
|
||||
### Using openrouter/auto
|
||||
|
||||
For simplicity, use `openrouter/auto` which automatically selects the best
|
||||
available model for your request:
|
||||
|
||||
```typescript
|
||||
const agent = createAgent({
|
||||
apiKey: process.env.OPENROUTER_API_KEY!,
|
||||
model: 'openrouter/auto', // Auto-selects best model
|
||||
});
|
||||
```
|
||||
|
||||
### Models API Reference
|
||||
|
||||
- **Endpoint**: `GET https://openrouter.ai/api/v1/models`
|
||||
- **Response**: `{ data: OpenRouterModel[] }`
|
||||
- **Browse models**: https://openrouter.ai/models
|
||||
|
||||
## Resources
|
||||
|
||||
- OpenRouter Docs: https://openrouter.ai/docs
|
||||
- Models API: https://openrouter.ai/api/v1/models
|
||||
- Ink Docs: https://github.com/vadimdemedes/ink
|
||||
- Get API Key: https://openrouter.ai/settings/keys
|
||||
13
.claude/skills/create-agent/metadata.json
Normal file
13
.claude/skills/create-agent/metadata.json
Normal file
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"version": "1.1.0",
|
||||
"organization": "OpenRouter Inc",
|
||||
"date": "January 2026",
|
||||
"abstract": "Complete guide for building modular AI agents with the OpenRouter TypeScript SDK. Features a standalone Agent class with EventEmitter-based hooks for extensibility, items-based streaming model for efficient UI state management, optional Ink TUI for interactive terminal interfaces, and examples for HTTP server and Discord integrations. Includes Zod-based tool definitions, streaming responses with support for reasoning/thinking items, multi-turn conversations, and dynamic model discovery via the OpenRouter Models API.",
|
||||
"references": [
|
||||
"https://openrouter.ai/docs/sdks/typescript",
|
||||
"https://openrouter.ai/docs/sdks/typescript/call-model/working-with-items",
|
||||
"https://openrouter.ai/docs/api-reference",
|
||||
"https://openrouter.ai/api/v1/models",
|
||||
"https://github.com/vadimdemedes/ink"
|
||||
]
|
||||
}
|
||||
@@ -16,14 +16,14 @@
|
||||
* type UserId = Brand<string, 'UserId'>
|
||||
* type OrderId = Brand<string, 'OrderId'>
|
||||
*/
|
||||
export type Brand<K, T> = K & { readonly __brand: T }
|
||||
export type Brand<K, T> = K & { readonly __brand: T };
|
||||
|
||||
// Branded type constructors
|
||||
export type UserId = Brand<string, 'UserId'>
|
||||
export type Email = Brand<string, 'Email'>
|
||||
export type UUID = Brand<string, 'UUID'>
|
||||
export type Timestamp = Brand<number, 'Timestamp'>
|
||||
export type PositiveNumber = Brand<number, 'PositiveNumber'>
|
||||
export type UserId = Brand<string, "UserId">;
|
||||
export type Email = Brand<string, "Email">;
|
||||
export type UUID = Brand<string, "UUID">;
|
||||
export type Timestamp = Brand<number, "Timestamp">;
|
||||
export type PositiveNumber = Brand<number, "PositiveNumber">;
|
||||
|
||||
// =============================================================================
|
||||
// RESULT TYPE (Error Handling)
|
||||
@@ -34,17 +34,17 @@ export type PositiveNumber = Brand<number, 'PositiveNumber'>
|
||||
*/
|
||||
export type Result<T, E = Error> =
|
||||
| { success: true; data: T }
|
||||
| { success: false; error: E }
|
||||
| { success: false; error: E };
|
||||
|
||||
export const ok = <T>(data: T): Result<T, never> => ({
|
||||
success: true,
|
||||
data
|
||||
})
|
||||
data,
|
||||
});
|
||||
|
||||
export const err = <E>(error: E): Result<never, E> => ({
|
||||
success: false,
|
||||
error
|
||||
})
|
||||
error,
|
||||
});
|
||||
|
||||
// =============================================================================
|
||||
// OPTION TYPE (Nullable Handling)
|
||||
@@ -53,13 +53,13 @@ export const err = <E>(error: E): Result<never, E> => ({
|
||||
/**
|
||||
* Explicit optional value handling.
|
||||
*/
|
||||
export type Option<T> = Some<T> | None
|
||||
export type Option<T> = Some<T> | None;
|
||||
|
||||
export type Some<T> = { type: 'some'; value: T }
|
||||
export type None = { type: 'none' }
|
||||
export type Some<T> = { type: "some"; value: T };
|
||||
export type None = { type: "none" };
|
||||
|
||||
export const some = <T>(value: T): Some<T> => ({ type: 'some', value })
|
||||
export const none: None = { type: 'none' }
|
||||
export const some = <T>(value: T): Some<T> => ({ type: "some", value });
|
||||
export const none: None = { type: "none" };
|
||||
|
||||
// =============================================================================
|
||||
// DEEP UTILITIES
|
||||
@@ -72,28 +72,28 @@ export type DeepReadonly<T> = T extends (...args: any[]) => any
|
||||
? T
|
||||
: T extends object
|
||||
? { readonly [K in keyof T]: DeepReadonly<T[K]> }
|
||||
: T
|
||||
: T;
|
||||
|
||||
/**
|
||||
* Make all properties deeply optional.
|
||||
*/
|
||||
export type DeepPartial<T> = T extends object
|
||||
? { [K in keyof T]?: DeepPartial<T[K]> }
|
||||
: T
|
||||
: T;
|
||||
|
||||
/**
|
||||
* Make all properties deeply required.
|
||||
*/
|
||||
export type DeepRequired<T> = T extends object
|
||||
? { [K in keyof T]-?: DeepRequired<T[K]> }
|
||||
: T
|
||||
: T;
|
||||
|
||||
/**
|
||||
* Make all properties deeply mutable (remove readonly).
|
||||
*/
|
||||
export type DeepMutable<T> = T extends object
|
||||
? { -readonly [K in keyof T]: DeepMutable<T[K]> }
|
||||
: T
|
||||
: T;
|
||||
|
||||
// =============================================================================
|
||||
// OBJECT UTILITIES
|
||||
@@ -103,38 +103,40 @@ export type DeepMutable<T> = T extends object
|
||||
* Get keys of object where value matches type.
|
||||
*/
|
||||
export type KeysOfType<T, V> = {
|
||||
[K in keyof T]: T[K] extends V ? K : never
|
||||
}[keyof T]
|
||||
[K in keyof T]: T[K] extends V ? K : never;
|
||||
}[keyof T];
|
||||
|
||||
/**
|
||||
* Pick properties by value type.
|
||||
*/
|
||||
export type PickByType<T, V> = Pick<T, KeysOfType<T, V>>
|
||||
export type PickByType<T, V> = Pick<T, KeysOfType<T, V>>;
|
||||
|
||||
/**
|
||||
* Omit properties by value type.
|
||||
*/
|
||||
export type OmitByType<T, V> = Omit<T, KeysOfType<T, V>>
|
||||
export type OmitByType<T, V> = Omit<T, KeysOfType<T, V>>;
|
||||
|
||||
/**
|
||||
* Make specific keys optional.
|
||||
*/
|
||||
export type PartialBy<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>
|
||||
export type PartialBy<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
|
||||
|
||||
/**
|
||||
* Make specific keys required.
|
||||
*/
|
||||
export type RequiredBy<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>
|
||||
export type RequiredBy<T, K extends keyof T> = Omit<T, K> &
|
||||
Required<Pick<T, K>>;
|
||||
|
||||
/**
|
||||
* Make specific keys readonly.
|
||||
*/
|
||||
export type ReadonlyBy<T, K extends keyof T> = Omit<T, K> & Readonly<Pick<T, K>>
|
||||
export type ReadonlyBy<T, K extends keyof T> = Omit<T, K> &
|
||||
Readonly<Pick<T, K>>;
|
||||
|
||||
/**
|
||||
* Merge two types (second overrides first).
|
||||
*/
|
||||
export type Merge<T, U> = Omit<T, keyof U> & U
|
||||
export type Merge<T, U> = Omit<T, keyof U> & U;
|
||||
|
||||
// =============================================================================
|
||||
// ARRAY UTILITIES
|
||||
@@ -143,7 +145,7 @@ export type Merge<T, U> = Omit<T, keyof U> & U
|
||||
/**
|
||||
* Get element type from array.
|
||||
*/
|
||||
export type ElementOf<T> = T extends (infer E)[] ? E : never
|
||||
export type ElementOf<T> = T extends (infer E)[] ? E : never;
|
||||
|
||||
/**
|
||||
* Tuple of specific length.
|
||||
@@ -152,21 +154,21 @@ export type Tuple<T, N extends number> = N extends N
|
||||
? number extends N
|
||||
? T[]
|
||||
: _TupleOf<T, N, []>
|
||||
: never
|
||||
: never;
|
||||
|
||||
type _TupleOf<T, N extends number, R extends unknown[]> = R['length'] extends N
|
||||
type _TupleOf<T, N extends number, R extends unknown[]> = R["length"] extends N
|
||||
? R
|
||||
: _TupleOf<T, N, [T, ...R]>
|
||||
: _TupleOf<T, N, [T, ...R]>;
|
||||
|
||||
/**
|
||||
* Non-empty array.
|
||||
*/
|
||||
export type NonEmptyArray<T> = [T, ...T[]]
|
||||
export type NonEmptyArray<T> = [T, ...T[]];
|
||||
|
||||
/**
|
||||
* At least N elements.
|
||||
*/
|
||||
export type AtLeast<T, N extends number> = [...Tuple<T, N>, ...T[]]
|
||||
export type AtLeast<T, N extends number> = [...Tuple<T, N>, ...T[]];
|
||||
|
||||
// =============================================================================
|
||||
// FUNCTION UTILITIES
|
||||
@@ -175,28 +177,28 @@ export type AtLeast<T, N extends number> = [...Tuple<T, N>, ...T[]]
|
||||
/**
|
||||
* Get function arguments as tuple.
|
||||
*/
|
||||
export type Arguments<T> = T extends (...args: infer A) => any ? A : never
|
||||
export type Arguments<T> = T extends (...args: infer A) => any ? A : never;
|
||||
|
||||
/**
|
||||
* Get first argument of function.
|
||||
*/
|
||||
export type FirstArgument<T> = T extends (first: infer F, ...args: any[]) => any
|
||||
? F
|
||||
: never
|
||||
: never;
|
||||
|
||||
/**
|
||||
* Async version of function.
|
||||
*/
|
||||
export type AsyncFunction<T extends (...args: any[]) => any> = (
|
||||
...args: Parameters<T>
|
||||
) => Promise<Awaited<ReturnType<T>>>
|
||||
) => Promise<Awaited<ReturnType<T>>>;
|
||||
|
||||
/**
|
||||
* Promisify return type.
|
||||
*/
|
||||
export type Promisify<T> = T extends (...args: infer A) => infer R
|
||||
? (...args: A) => Promise<Awaited<R>>
|
||||
: never
|
||||
: never;
|
||||
|
||||
// =============================================================================
|
||||
// STRING UTILITIES
|
||||
@@ -205,22 +207,21 @@ export type Promisify<T> = T extends (...args: infer A) => infer R
|
||||
/**
|
||||
* Split string by delimiter.
|
||||
*/
|
||||
export type Split<S extends string, D extends string> =
|
||||
S extends `${infer T}${D}${infer U}`
|
||||
? [T, ...Split<U, D>]
|
||||
: [S]
|
||||
export type Split<
|
||||
S extends string,
|
||||
D extends string,
|
||||
> = S extends `${infer T}${D}${infer U}` ? [T, ...Split<U, D>] : [S];
|
||||
|
||||
/**
|
||||
* Join tuple to string.
|
||||
*/
|
||||
export type Join<T extends string[], D extends string> =
|
||||
T extends []
|
||||
? ''
|
||||
export type Join<T extends string[], D extends string> = T extends []
|
||||
? ""
|
||||
: T extends [infer F extends string]
|
||||
? F
|
||||
: T extends [infer F extends string, ...infer R extends string[]]
|
||||
? `${F}${D}${Join<R, D>}`
|
||||
: never
|
||||
: never;
|
||||
|
||||
/**
|
||||
* Path to nested object.
|
||||
@@ -229,7 +230,7 @@ export type PathOf<T, K extends keyof T = keyof T> = K extends string
|
||||
? T[K] extends object
|
||||
? K | `${K}.${PathOf<T[K]>}`
|
||||
: K
|
||||
: never
|
||||
: never;
|
||||
|
||||
// =============================================================================
|
||||
// UNION UTILITIES
|
||||
@@ -238,27 +239,28 @@ export type PathOf<T, K extends keyof T = keyof T> = K extends string
|
||||
/**
|
||||
* Last element of union.
|
||||
*/
|
||||
export type UnionLast<T> = UnionToIntersection<
|
||||
T extends any ? () => T : never
|
||||
> extends () => infer R
|
||||
export type UnionLast<T> =
|
||||
UnionToIntersection<T extends any ? () => T : never> extends () => infer R
|
||||
? R
|
||||
: never
|
||||
: never;
|
||||
|
||||
/**
|
||||
* Union to intersection.
|
||||
*/
|
||||
export type UnionToIntersection<U> = (
|
||||
U extends any ? (k: U) => void : never
|
||||
U extends any
|
||||
? (k: U) => void
|
||||
: never
|
||||
) extends (k: infer I) => void
|
||||
? I
|
||||
: never
|
||||
: never;
|
||||
|
||||
/**
|
||||
* Union to tuple.
|
||||
*/
|
||||
export type UnionToTuple<T, L = UnionLast<T>> = [T] extends [never]
|
||||
? []
|
||||
: [...UnionToTuple<Exclude<T, L>>, L]
|
||||
: [...UnionToTuple<Exclude<T, L>>, L];
|
||||
|
||||
// =============================================================================
|
||||
// VALIDATION UTILITIES
|
||||
@@ -268,28 +270,25 @@ export type UnionToTuple<T, L = UnionLast<T>> = [T] extends [never]
|
||||
* Assert type at compile time.
|
||||
*/
|
||||
export type AssertEqual<T, U> =
|
||||
(<V>() => V extends T ? 1 : 2) extends (<V>() => V extends U ? 1 : 2)
|
||||
(<V>() => V extends T ? 1 : 2) extends <V>() => V extends U ? 1 : 2
|
||||
? true
|
||||
: false
|
||||
: false;
|
||||
|
||||
/**
|
||||
* Ensure type is not never.
|
||||
*/
|
||||
export type IsNever<T> = [T] extends [never] ? true : false
|
||||
export type IsNever<T> = [T] extends [never] ? true : false;
|
||||
|
||||
/**
|
||||
* Ensure type is any.
|
||||
*/
|
||||
export type IsAny<T> = 0 extends 1 & T ? true : false
|
||||
export type IsAny<T> = 0 extends 1 & T ? true : false;
|
||||
|
||||
/**
|
||||
* Ensure type is unknown.
|
||||
*/
|
||||
export type IsUnknown<T> = IsAny<T> extends true
|
||||
? false
|
||||
: unknown extends T
|
||||
? true
|
||||
: false
|
||||
export type IsUnknown<T> =
|
||||
IsAny<T> extends true ? false : unknown extends T ? true : false;
|
||||
|
||||
// =============================================================================
|
||||
// JSON UTILITIES
|
||||
@@ -298,10 +297,10 @@ export type IsUnknown<T> = IsAny<T> extends true
|
||||
/**
|
||||
* JSON-safe types.
|
||||
*/
|
||||
export type JsonPrimitive = string | number | boolean | null
|
||||
export type JsonArray = JsonValue[]
|
||||
export type JsonObject = { [key: string]: JsonValue }
|
||||
export type JsonValue = JsonPrimitive | JsonArray | JsonObject
|
||||
export type JsonPrimitive = string | number | boolean | null;
|
||||
export type JsonArray = JsonValue[];
|
||||
export type JsonObject = { [key: string]: JsonValue };
|
||||
export type JsonValue = JsonPrimitive | JsonArray | JsonObject;
|
||||
|
||||
/**
|
||||
* Make type JSON-serializable.
|
||||
@@ -314,7 +313,7 @@ export type Jsonify<T> = T extends JsonPrimitive
|
||||
? R
|
||||
: T extends object
|
||||
? { [K in keyof T]: Jsonify<T[K]> }
|
||||
: never
|
||||
: never;
|
||||
|
||||
// =============================================================================
|
||||
// EXHAUSTIVE CHECK
|
||||
@@ -324,7 +323,7 @@ export type Jsonify<T> = T extends JsonPrimitive
|
||||
* Ensure all cases are handled in switch/if.
|
||||
*/
|
||||
export function assertNever(value: never, message?: string): never {
|
||||
throw new Error(message ?? `Unexpected value: ${value}`)
|
||||
throw new Error(message ?? `Unexpected value: ${value}`);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
6
.claude/skills/typescript-sdk/.openskills.json
Normal file
6
.claude/skills/typescript-sdk/.openskills.json
Normal file
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"source": "/tmp/skill-selector-curated-812268656",
|
||||
"sourceType": "local",
|
||||
"localPath": "/tmp/skill-selector-curated-812268656/typescript-sdk",
|
||||
"installedAt": "2026-04-07T03:45:37.971Z"
|
||||
}
|
||||
1249
.claude/skills/typescript-sdk/SKILL.md
Normal file
1249
.claude/skills/typescript-sdk/SKILL.md
Normal file
File diff suppressed because it is too large
Load Diff
13
.claude/skills/typescript-sdk/metadata.json
Normal file
13
.claude/skills/typescript-sdk/metadata.json
Normal file
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"version": "1.0.0",
|
||||
"organization": "OpenRouter Inc",
|
||||
"date": "January 2026",
|
||||
"abstract": "Complete reference for the OpenRouter TypeScript SDK, enabling AI agents to integrate with 300+ AI models through a unified, type-safe interface. Covers the callModel pattern for text generation, streaming, and multi-turn conversations with automatic tool execution. Includes detailed TypeScript interfaces for Responses API message shapes, streaming event types, authentication methods (API key and OAuth PKCE flow), Zod-based tool definitions, stop conditions, and format conversion helpers. Designed for AI agent consumption with production-ready examples and best practices.",
|
||||
"references": [
|
||||
"https://openrouter.ai/docs/sdks/typescript/call-model/overview",
|
||||
"https://openrouter.ai/docs/sdks",
|
||||
"https://openrouter.ai/docs/api/reference/overview",
|
||||
"https://openrouter.ai/docs/sdks/typescript/api-reference/api-reference/oauth",
|
||||
"https://openrouter.ai/docs/sdks/llms-full.txt"
|
||||
]
|
||||
}
|
||||
@@ -20,4 +20,5 @@ repos:
|
||||
- sickn33/antigravity-awesome-skills
|
||||
- tfriedel/claude-office-skills
|
||||
- wshobson/agents
|
||||
- OpenRouterTeam/agent-skills
|
||||
- ~/projects/ai-skills
|
||||
|
||||
3
bun.lock
3
bun.lock
@@ -5,6 +5,7 @@
|
||||
"": {
|
||||
"name": "ical-pwa",
|
||||
"dependencies": {
|
||||
"@openrouter/sdk": "^0.11.2",
|
||||
"@radix-ui/react-checkbox": "^1.3.3",
|
||||
"@radix-ui/react-dialog": "^1.1.15",
|
||||
"@radix-ui/react-dropdown-menu": "^2.1.16",
|
||||
@@ -266,6 +267,8 @@
|
||||
|
||||
"@nolyfill/is-core-module": ["@nolyfill/is-core-module@1.0.39", "", {}, "sha512-nn5ozdjYQpUCZlWGuxcJY/KpxkWQs4DcbMCmKojjyrYDEAGy4Ce19NN4v5MduafTwJlbKc99UA8YhSVqq9yPZA=="],
|
||||
|
||||
"@openrouter/sdk": ["@openrouter/sdk@0.11.2", "", { "dependencies": { "zod": "^3.25.0 || ^4.0.0" } }, "sha512-uu8zu7vd4hA2l4vUD1UiZuefxqaH2/ixFcUG8GIO9+qcEJkWX4AYAil7SpGmZOTgy8STLFTEk4M4MmyUW0YMLg=="],
|
||||
|
||||
"@opentelemetry/api": ["@opentelemetry/api@1.9.1", "", {}, "sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q=="],
|
||||
|
||||
"@opentelemetry/semantic-conventions": ["@opentelemetry/semantic-conventions@1.40.0", "", {}, "sha512-cifvXDhcqMwwTlTK04GBNeIe7yyo28Mfby85QXFe1Yk8nmi36Ab/5UQwptOx84SsoGNRg+EVSjwzfSZMy6pmlw=="],
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
import { defineConfig } from 'drizzle-kit';
|
||||
import * as dotenv from 'dotenv';
|
||||
import { defineConfig } from "drizzle-kit";
|
||||
import * as dotenv from "dotenv";
|
||||
|
||||
if (!process.env.DATABASE_URL) {
|
||||
if (process.env.NODE_ENV === "production") {
|
||||
dotenv.config({ path: '.env.production' });
|
||||
dotenv.config({ path: ".env.production" });
|
||||
} else {
|
||||
dotenv.config({ path: '.env.local' });
|
||||
dotenv.config({ path: ".env.local" });
|
||||
}
|
||||
}
|
||||
|
||||
export default defineConfig({
|
||||
dialect: 'postgresql',
|
||||
schema: './src/db/schema.ts',
|
||||
out: './drizzle',
|
||||
dialect: "postgresql",
|
||||
schema: "./src/db/schema.ts",
|
||||
out: "./drizzle",
|
||||
dbCredentials: {
|
||||
url: process.env.DATABASE_URL!,
|
||||
},
|
||||
|
||||
@@ -34,12 +34,8 @@
|
||||
"tableFrom": "session",
|
||||
"tableTo": "user",
|
||||
"schemaTo": "public",
|
||||
"columnsFrom": [
|
||||
"userId"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["userId"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -121,10 +117,7 @@
|
||||
"compositePrimaryKeys": {
|
||||
"verificationToken_identifier_token_pk": {
|
||||
"name": "verificationToken_identifier_token_pk",
|
||||
"columns": [
|
||||
"identifier",
|
||||
"token"
|
||||
]
|
||||
"columns": ["identifier", "token"]
|
||||
}
|
||||
},
|
||||
"uniqueConstraints": {},
|
||||
@@ -192,12 +185,8 @@
|
||||
"tableFrom": "authenticator",
|
||||
"tableTo": "user",
|
||||
"schemaTo": "public",
|
||||
"columnsFrom": [
|
||||
"userId"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["userId"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -205,17 +194,12 @@
|
||||
"compositePrimaryKeys": {
|
||||
"authenticator_userId_credentialID_pk": {
|
||||
"name": "authenticator_userId_credentialID_pk",
|
||||
"columns": [
|
||||
"credentialID",
|
||||
"userId"
|
||||
]
|
||||
"columns": ["credentialID", "userId"]
|
||||
}
|
||||
},
|
||||
"uniqueConstraints": {
|
||||
"authenticator_credentialID_unique": {
|
||||
"columns": [
|
||||
"credentialID"
|
||||
],
|
||||
"columns": ["credentialID"],
|
||||
"nullsNotDistinct": false,
|
||||
"name": "authenticator_credentialID_unique"
|
||||
}
|
||||
@@ -302,12 +286,8 @@
|
||||
"tableFrom": "account",
|
||||
"tableTo": "user",
|
||||
"schemaTo": "public",
|
||||
"columnsFrom": [
|
||||
"userId"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["userId"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -315,10 +295,7 @@
|
||||
"compositePrimaryKeys": {
|
||||
"account_provider_providerAccountId_pk": {
|
||||
"name": "account_provider_providerAccountId_pk",
|
||||
"columns": [
|
||||
"provider",
|
||||
"providerAccountId"
|
||||
]
|
||||
"columns": ["provider", "providerAccountId"]
|
||||
}
|
||||
},
|
||||
"uniqueConstraints": {},
|
||||
|
||||
@@ -95,12 +95,8 @@
|
||||
"name": "account_userId_user_id_fk",
|
||||
"tableFrom": "account",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"userId"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["userId"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -172,12 +168,8 @@
|
||||
"name": "session_userId_user_id_fk",
|
||||
"tableFrom": "session",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"userId"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["userId"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -187,9 +179,7 @@
|
||||
"session_token_unique": {
|
||||
"name": "session_token_unique",
|
||||
"nullsNotDistinct": false,
|
||||
"columns": [
|
||||
"token"
|
||||
]
|
||||
"columns": ["token"]
|
||||
}
|
||||
},
|
||||
"policies": {},
|
||||
@@ -253,9 +243,7 @@
|
||||
"user_email_unique": {
|
||||
"name": "user_email_unique",
|
||||
"nullsNotDistinct": false,
|
||||
"columns": [
|
||||
"email"
|
||||
]
|
||||
"columns": ["email"]
|
||||
}
|
||||
},
|
||||
"policies": {},
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
import { relations } from "drizzle-orm/relations";
|
||||
import { user, session, account } from "./schema";
|
||||
|
||||
export const sessionRelations = relations(session, ({one}) => ({
|
||||
export const sessionRelations = relations(session, ({ one }) => ({
|
||||
user: one(user, {
|
||||
fields: [session.userId],
|
||||
references: [user.id]
|
||||
references: [user.id],
|
||||
}),
|
||||
}));
|
||||
|
||||
export const userRelations = relations(user, ({many}) => ({
|
||||
export const userRelations = relations(user, ({ many }) => ({
|
||||
sessions: many(session),
|
||||
accounts: many(account),
|
||||
}));
|
||||
|
||||
export const accountRelations = relations(account, ({one}) => ({
|
||||
export const accountRelations = relations(account, ({ one }) => ({
|
||||
user: one(user, {
|
||||
fields: [account.userId],
|
||||
references: [user.id]
|
||||
references: [user.id],
|
||||
}),
|
||||
}));
|
||||
@@ -1,37 +1,57 @@
|
||||
import { pgTable, foreignKey, text, timestamp, primaryKey, unique, integer, boolean } from "drizzle-orm/pg-core"
|
||||
import { sql } from "drizzle-orm"
|
||||
import {
|
||||
pgTable,
|
||||
foreignKey,
|
||||
text,
|
||||
timestamp,
|
||||
primaryKey,
|
||||
unique,
|
||||
integer,
|
||||
boolean,
|
||||
} from "drizzle-orm/pg-core";
|
||||
import { sql } from "drizzle-orm";
|
||||
|
||||
|
||||
|
||||
export const session = pgTable("session", {
|
||||
export const session = pgTable(
|
||||
"session",
|
||||
{
|
||||
sessionToken: text().primaryKey().notNull(),
|
||||
userId: text().notNull(),
|
||||
expires: timestamp({ mode: 'string' }).notNull(),
|
||||
}, (table) => [
|
||||
expires: timestamp({ mode: "string" }).notNull(),
|
||||
},
|
||||
(table) => [
|
||||
foreignKey({
|
||||
columns: [table.userId],
|
||||
foreignColumns: [user.id],
|
||||
name: "session_userId_user_id_fk"
|
||||
name: "session_userId_user_id_fk",
|
||||
}).onDelete("cascade"),
|
||||
]);
|
||||
],
|
||||
);
|
||||
|
||||
export const user = pgTable("user", {
|
||||
id: text().primaryKey().notNull(),
|
||||
name: text(),
|
||||
email: text().notNull(),
|
||||
emailVerified: timestamp({ mode: 'string' }),
|
||||
emailVerified: timestamp({ mode: "string" }),
|
||||
image: text(),
|
||||
});
|
||||
|
||||
export const verificationToken = pgTable("verificationToken", {
|
||||
export const verificationToken = pgTable(
|
||||
"verificationToken",
|
||||
{
|
||||
identifier: text().notNull(),
|
||||
token: text().notNull(),
|
||||
expires: timestamp({ mode: 'string' }).notNull(),
|
||||
}, (table) => [
|
||||
primaryKey({ columns: [table.identifier, table.token], name: "verificationToken_identifier_token_pk"}),
|
||||
]);
|
||||
expires: timestamp({ mode: "string" }).notNull(),
|
||||
},
|
||||
(table) => [
|
||||
primaryKey({
|
||||
columns: [table.identifier, table.token],
|
||||
name: "verificationToken_identifier_token_pk",
|
||||
}),
|
||||
],
|
||||
);
|
||||
|
||||
export const authenticator = pgTable("authenticator", {
|
||||
export const authenticator = pgTable(
|
||||
"authenticator",
|
||||
{
|
||||
credentialId: text().notNull(),
|
||||
userId: text().notNull(),
|
||||
providerAccountId: text().notNull(),
|
||||
@@ -40,17 +60,24 @@ export const authenticator = pgTable("authenticator", {
|
||||
credentialDeviceType: text().notNull(),
|
||||
credentialBackedUp: boolean().notNull(),
|
||||
transports: text(),
|
||||
}, (table) => [
|
||||
},
|
||||
(table) => [
|
||||
foreignKey({
|
||||
columns: [table.userId],
|
||||
foreignColumns: [user.id],
|
||||
name: "authenticator_userId_user_id_fk"
|
||||
name: "authenticator_userId_user_id_fk",
|
||||
}).onDelete("cascade"),
|
||||
primaryKey({ columns: [table.credentialId, table.userId], name: "authenticator_userId_credentialID_pk"}),
|
||||
primaryKey({
|
||||
columns: [table.credentialId, table.userId],
|
||||
name: "authenticator_userId_credentialID_pk",
|
||||
}),
|
||||
unique("authenticator_credentialID_unique").on(table.credentialId),
|
||||
]);
|
||||
],
|
||||
);
|
||||
|
||||
export const account = pgTable("account", {
|
||||
export const account = pgTable(
|
||||
"account",
|
||||
{
|
||||
userId: text().notNull(),
|
||||
type: text().notNull(),
|
||||
provider: text().notNull(),
|
||||
@@ -62,11 +89,16 @@ export const account = pgTable("account", {
|
||||
scope: text(),
|
||||
idToken: text("id_token"),
|
||||
sessionState: text("session_state"),
|
||||
}, (table) => [
|
||||
},
|
||||
(table) => [
|
||||
foreignKey({
|
||||
columns: [table.userId],
|
||||
foreignColumns: [user.id],
|
||||
name: "account_userId_user_id_fk"
|
||||
name: "account_userId_user_id_fk",
|
||||
}).onDelete("cascade"),
|
||||
primaryKey({ columns: [table.provider, table.providerAccountId], name: "account_provider_providerAccountId_pk"}),
|
||||
]);
|
||||
primaryKey({
|
||||
columns: [table.provider, table.providerAccountId],
|
||||
name: "account_provider_providerAccountId_pk",
|
||||
}),
|
||||
],
|
||||
);
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
"lint": "next lint"
|
||||
},
|
||||
"dependencies": {
|
||||
"@openrouter/sdk": "^0.11.2",
|
||||
"@radix-ui/react-checkbox": "^1.3.3",
|
||||
"@radix-ui/react-dialog": "^1.1.15",
|
||||
"@radix-ui/react-dropdown-menu": "^2.1.16",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { auth } from "@/auth";
|
||||
import { headers } from "next/headers";
|
||||
import { openRouterClient } from "@/lib/openrouter-client";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const session = await auth.api.getSession({
|
||||
@@ -10,7 +11,7 @@ export async function POST(request: Request) {
|
||||
if (!session?.user) {
|
||||
return NextResponse.json(
|
||||
{ error: "Authentication required" },
|
||||
{ status: 401 }
|
||||
{ status: 401 },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -20,13 +21,13 @@ export async function POST(request: Request) {
|
||||
if (!prompt || typeof prompt !== "string" || prompt.trim().length === 0) {
|
||||
return NextResponse.json(
|
||||
{ error: "Prompt is required and must be a non-empty string" },
|
||||
{ status: 400 }
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
if (prompt.length > 2000) {
|
||||
return NextResponse.json(
|
||||
{ error: "Prompt must be less than 2000 characters" },
|
||||
{ status: 400 }
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -57,29 +58,23 @@ Rules:
|
||||
- Output ONLY valid JSON (no prose).
|
||||
`;
|
||||
|
||||
const res = await fetch("https://openrouter.ai/api/v1/chat/completions", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${process.env.OPENROUTER_API_KEY}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: "openai/gpt-4.1-nano",
|
||||
messages: [
|
||||
{ role: "system", content: systemPrompt },
|
||||
{ role: "user", content: prompt },
|
||||
],
|
||||
}),
|
||||
try {
|
||||
const result = openRouterClient.callModel({
|
||||
model: "openai/gpt-5.4-mini",
|
||||
instructions: systemPrompt,
|
||||
input: prompt,
|
||||
});
|
||||
|
||||
const data = await res.json();
|
||||
try {
|
||||
const content = data.choices[0].message.content;
|
||||
const parsed = JSON.parse(content);
|
||||
const text = await result.getText();
|
||||
const parsed = JSON.parse(text);
|
||||
return NextResponse.json(parsed);
|
||||
} catch {
|
||||
} catch (error) {
|
||||
console.error("AI Event Creation Error:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to parse AI output", raw: data },
|
||||
{
|
||||
error: "Failed to parse AI output",
|
||||
raw: error instanceof Error ? error.message : error,
|
||||
},
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { auth } from "@/auth";
|
||||
import { headers } from "next/headers";
|
||||
import { openRouterClient } from "@/lib/openrouter-client";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const session = await auth.api.getSession({
|
||||
@@ -30,32 +31,18 @@ export async function POST(request: Request) {
|
||||
);
|
||||
}
|
||||
|
||||
const res = await fetch("https://openrouter.ai/api/v1/chat/completions", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${process.env.OPENROUTER_API_KEY}`, // Server-side only
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
const result = openRouterClient.callModel({
|
||||
model: "@preset/i-cal-editor-summarize", // FREE model
|
||||
messages: [
|
||||
{
|
||||
role: "system",
|
||||
content: `You summarize a list of events in natural language. Include date, time, and title. Be concise.`,
|
||||
},
|
||||
{ role: "user", content: JSON.stringify(events) },
|
||||
],
|
||||
instructions:
|
||||
"You summarize a list of events in natural language. Include date, time, and title. Be concise.",
|
||||
input: JSON.stringify(events),
|
||||
temperature: 0.4,
|
||||
// max_tokens: 300,
|
||||
}),
|
||||
});
|
||||
|
||||
const data = await res.json();
|
||||
const summary =
|
||||
data?.choices?.[0]?.message?.content || "No summary generated.";
|
||||
const summary = await result.getText();
|
||||
return NextResponse.json({ summary });
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
console.error("AI Summary Error:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to summarize events" },
|
||||
{ status: 500 },
|
||||
|
||||
@@ -1,23 +1,25 @@
|
||||
"use client"
|
||||
"use client";
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import Link from "next/link"
|
||||
import { useSearchParams } from "next/navigation"
|
||||
import { Suspense } from "react"
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import Link from "next/link";
|
||||
import { useSearchParams } from "next/navigation";
|
||||
import { Suspense } from "react";
|
||||
|
||||
function Search() {
|
||||
const searchParams = useSearchParams()
|
||||
const errorMessage = searchParams.get('error')
|
||||
const searchParams = useSearchParams();
|
||||
const errorMessage = searchParams.get("error");
|
||||
|
||||
// Sanitize error message to prevent XSS
|
||||
const sanitizedError = errorMessage
|
||||
? errorMessage.replace(/[<>]/g, '')
|
||||
: 'An authentication error occurred'
|
||||
? errorMessage.replace(/[<>]/g, "")
|
||||
: "An authentication error occurred";
|
||||
|
||||
return (<div className="text-center p-3 bg-background rounded-lg">
|
||||
return (
|
||||
<div className="text-center p-3 bg-background rounded-lg">
|
||||
{sanitizedError}
|
||||
</div>)
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function AuthErrorPage() {
|
||||
@@ -39,5 +41,5 @@ export default function AuthErrorPage() {
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,44 +1,50 @@
|
||||
"use client"
|
||||
"use client";
|
||||
|
||||
import { signIn, useSession } from "@/lib/auth-client"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import Link from "next/link"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { useEffect, useState } from "react"
|
||||
import { toast } from "sonner"
|
||||
import { signIn, useSession } from "@/lib/auth-client";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
export default function SignInPage() {
|
||||
const { data: session, isPending } = useSession()
|
||||
const router = useRouter()
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const { data: session, isPending } = useSession();
|
||||
const router = useRouter();
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (session?.user) {
|
||||
router.push("/")
|
||||
router.push("/");
|
||||
}
|
||||
}, [session, router])
|
||||
}, [session, router]);
|
||||
|
||||
const handleSignIn = async () => {
|
||||
setIsLoading(true)
|
||||
setIsLoading(true);
|
||||
try {
|
||||
await signIn.oauth2({
|
||||
providerId: "authentik",
|
||||
callbackURL: "/",
|
||||
})
|
||||
});
|
||||
} catch (_error) {
|
||||
toast.error("Failed to sign in. Please try again.")
|
||||
toast.error("Failed to sign in. Please try again.");
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (isPending) {
|
||||
return null
|
||||
return null;
|
||||
}
|
||||
|
||||
if (session?.user) {
|
||||
return null
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -51,17 +57,25 @@ export default function SignInPage() {
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<Button onClick={handleSignIn} className="w-full" size="lg" disabled={isLoading}>
|
||||
<Button
|
||||
onClick={handleSignIn}
|
||||
className="w-full"
|
||||
size="lg"
|
||||
disabled={isLoading}
|
||||
>
|
||||
{isLoading ? "Signing in..." : "Continue with Authentik"}
|
||||
</Button>
|
||||
|
||||
<div className="text-center">
|
||||
<Link href="/" className="text-sm text-muted-foreground hover:underline">
|
||||
<Link
|
||||
href="/"
|
||||
className="text-sm text-muted-foreground hover:underline"
|
||||
>
|
||||
Continue without signing in
|
||||
</Link>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,29 +1,35 @@
|
||||
"use client"
|
||||
"use client";
|
||||
|
||||
import { signOut, useSession } from "@/lib/auth-client"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import Link from "next/link"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { useEffect } from "react"
|
||||
import { signOut, useSession } from "@/lib/auth-client";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect } from "react";
|
||||
|
||||
export default function SignOutPage() {
|
||||
const { data: session, isPending } = useSession()
|
||||
const router = useRouter()
|
||||
const { data: session, isPending } = useSession();
|
||||
const router = useRouter();
|
||||
|
||||
useEffect(() => {
|
||||
if (!session?.user) {
|
||||
router.push("/")
|
||||
router.push("/");
|
||||
}
|
||||
}, [session, router])
|
||||
}, [session, router]);
|
||||
|
||||
const handleSignOut = async () => {
|
||||
await signOut()
|
||||
router.push("/")
|
||||
}
|
||||
await signOut();
|
||||
router.push("/");
|
||||
};
|
||||
|
||||
if (isPending || !session?.user) {
|
||||
return null
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -31,18 +37,24 @@ export default function SignOutPage() {
|
||||
<Card className="w-full max-w-md">
|
||||
<CardHeader className="text-center">
|
||||
<CardTitle className="text-2xl font-bold">Sign Out</CardTitle>
|
||||
<CardDescription>
|
||||
Are you sure you want to sign out?
|
||||
</CardDescription>
|
||||
<CardDescription>Are you sure you want to sign out?</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="text-center p-3 bg-muted rounded-lg">
|
||||
<div className="text-sm text-muted-foreground">Currently signed in as</div>
|
||||
<div className="font-medium">{session.user?.name || session.user?.email}</div>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
Currently signed in as
|
||||
</div>
|
||||
<div className="font-medium">
|
||||
{session.user?.name || session.user?.email}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<Button onClick={handleSignOut} variant="destructive" className="w-full">
|
||||
<Button
|
||||
onClick={handleSignOut}
|
||||
variant="destructive"
|
||||
className="w-full"
|
||||
>
|
||||
Sign Out
|
||||
</Button>
|
||||
|
||||
@@ -53,5 +65,5 @@ export default function SignOutPage() {
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -5,17 +5,24 @@ import { ThemeProvider } from "next-themes";
|
||||
import { ModeToggle } from "@/components/mode-toggle";
|
||||
import SignIn from "@/components/sign-in";
|
||||
import { Toaster } from "@/components/ui/sonner";
|
||||
import Link from "next/link"
|
||||
import Link from "next/link";
|
||||
|
||||
const geist = Geist({ subsets: ['latin', 'cyrillic'], variable: "--font-geist-sans" })
|
||||
const geist = Geist({
|
||||
subsets: ["latin", "cyrillic"],
|
||||
variable: "--font-geist-sans",
|
||||
});
|
||||
|
||||
const magra = Magra({ subsets: ["latin"], weight: "400", variable: "--font-cascadia-code" })
|
||||
const magra = Magra({
|
||||
subsets: ["latin"],
|
||||
weight: "400",
|
||||
variable: "--font-cascadia-code",
|
||||
});
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: 'Local iCal',
|
||||
description: 'Local iCal editor for calendar events',
|
||||
title: "Local iCal",
|
||||
description: "Local iCal editor for calendar events",
|
||||
creator: "Dmytro Stanchiev",
|
||||
}
|
||||
};
|
||||
|
||||
export default function RootLayout({
|
||||
children,
|
||||
@@ -36,7 +43,7 @@ export default function RootLayout({
|
||||
<header className="dark:text-white text-gray-900 px-4 py-3 font-bold flex justify-between items-center-safe">
|
||||
<Link href={"/"}>
|
||||
<p className={`${magra.variable}`}>
|
||||
{metadata.title as string || "iCal PWA"}
|
||||
{(metadata.title as string) || "iCal PWA"}
|
||||
</p>
|
||||
</Link>
|
||||
<div className="flex flex-row gap-2">
|
||||
|
||||
326
src/app/page.tsx
326
src/app/page.tsx
@@ -1,62 +1,70 @@
|
||||
"use client"
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { nanoid } from 'nanoid'
|
||||
import { useSession } from '@/lib/auth-client'
|
||||
import { toast } from 'sonner'
|
||||
import { useEffect, useState } from "react";
|
||||
import { nanoid } from "nanoid";
|
||||
import { useSession } from "@/lib/auth-client";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { saveEvent as addEvent, deleteEvent, getEvents as getAllEvents, clearEvents, updateEvent } from '@/lib/events-db'
|
||||
import { parseICS, generateICS } from '@/lib/ical'
|
||||
import type { CalendarEvent } from '@/lib/types'
|
||||
import {
|
||||
saveEvent as addEvent,
|
||||
deleteEvent,
|
||||
getEvents as getAllEvents,
|
||||
clearEvents,
|
||||
updateEvent,
|
||||
} from "@/lib/events-db";
|
||||
import { parseICS, generateICS } from "@/lib/ical";
|
||||
import type { CalendarEvent } from "@/lib/types";
|
||||
|
||||
import { AIToolbar } from '@/components/ai-toolbar'
|
||||
import { EventActionsToolbar } from '@/components/event-actions-toolbar'
|
||||
import { EventsList } from '@/components/events-list'
|
||||
import { EventDialog } from '@/components/event-dialog'
|
||||
import { DragDropContainer } from '@/components/drag-drop-container'
|
||||
import { AIToolbar } from "@/components/ai-toolbar";
|
||||
import { EventActionsToolbar } from "@/components/event-actions-toolbar";
|
||||
import { EventsList } from "@/components/events-list";
|
||||
import { EventDialog } from "@/components/event-dialog";
|
||||
import { DragDropContainer } from "@/components/drag-drop-container";
|
||||
|
||||
export default function HomePage() {
|
||||
const [events, setEvents] = useState<CalendarEvent[]>([])
|
||||
const [dialogOpen, setDialogOpen] = useState(false)
|
||||
const [editingId, setEditingId] = useState<string | null>(null)
|
||||
const [isDragOver, setIsDragOver] = useState(false)
|
||||
const [events, setEvents] = useState<CalendarEvent[]>([]);
|
||||
const [dialogOpen, setDialogOpen] = useState(false);
|
||||
const [editingId, setEditingId] = useState<string | null>(null);
|
||||
const [isDragOver, setIsDragOver] = useState(false);
|
||||
|
||||
// Form fields
|
||||
const [title, setTitle] = useState('')
|
||||
const [description, setDescription] = useState('')
|
||||
const [location, setLocation] = useState('')
|
||||
const [url, setUrl] = useState('')
|
||||
const [start, setStart] = useState('')
|
||||
const [end, setEnd] = useState('')
|
||||
const [allDay, setAllDay] = useState(false)
|
||||
const [recurrenceRule, setRecurrenceRule] = useState<string | undefined>(undefined)
|
||||
const [title, setTitle] = useState("");
|
||||
const [description, setDescription] = useState("");
|
||||
const [location, setLocation] = useState("");
|
||||
const [url, setUrl] = useState("");
|
||||
const [start, setStart] = useState("");
|
||||
const [end, setEnd] = useState("");
|
||||
const [allDay, setAllDay] = useState(false);
|
||||
const [recurrenceRule, setRecurrenceRule] = useState<string | undefined>(
|
||||
undefined,
|
||||
);
|
||||
|
||||
// AI
|
||||
const [aiPrompt, setAiPrompt] = useState('')
|
||||
const [aiLoading, setAiLoading] = useState(false)
|
||||
const [summary, setSummary] = useState<string | null>(null)
|
||||
const [summaryUpdated, setSummaryUpdated] = useState<string | null>(null)
|
||||
const [aiPrompt, setAiPrompt] = useState("");
|
||||
const [aiLoading, setAiLoading] = useState(false);
|
||||
const [summary, setSummary] = useState<string | null>(null);
|
||||
const [summaryUpdated, setSummaryUpdated] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
const stored = await getAllEvents()
|
||||
setEvents(stored)
|
||||
})()
|
||||
}, [])
|
||||
const stored = await getAllEvents();
|
||||
setEvents(stored);
|
||||
})();
|
||||
}, []);
|
||||
|
||||
const { data: session, isPending } = useSession()
|
||||
const { data: session, isPending } = useSession();
|
||||
|
||||
const resetForm = () => {
|
||||
setTitle('')
|
||||
setDescription('')
|
||||
setLocation('')
|
||||
setUrl('')
|
||||
setStart('')
|
||||
setEnd('')
|
||||
setAllDay(false)
|
||||
setEditingId(null)
|
||||
setRecurrenceRule(undefined)
|
||||
}
|
||||
setTitle("");
|
||||
setDescription("");
|
||||
setLocation("");
|
||||
setUrl("");
|
||||
setStart("");
|
||||
setEnd("");
|
||||
setAllDay(false);
|
||||
setEditingId(null);
|
||||
setRecurrenceRule(undefined);
|
||||
};
|
||||
|
||||
const handleSave = async () => {
|
||||
const eventData: CalendarEvent = {
|
||||
@@ -70,96 +78,98 @@ export default function HomePage() {
|
||||
end: end || undefined,
|
||||
allDay,
|
||||
createdAt: editingId
|
||||
? events.find(e => e.id === editingId)?.createdAt
|
||||
? events.find((e) => e.id === editingId)?.createdAt
|
||||
: new Date().toISOString(),
|
||||
lastModified: new Date().toISOString(),
|
||||
}
|
||||
};
|
||||
if (editingId) {
|
||||
await updateEvent(eventData)
|
||||
setEvents(prev => prev.map(e => (e.id === editingId ? eventData : e)))
|
||||
await updateEvent(eventData);
|
||||
setEvents((prev) =>
|
||||
prev.map((e) => (e.id === editingId ? eventData : e)),
|
||||
);
|
||||
} else {
|
||||
await addEvent(eventData)
|
||||
setEvents(prev => [...prev, eventData])
|
||||
}
|
||||
resetForm()
|
||||
setDialogOpen(false)
|
||||
await addEvent(eventData);
|
||||
setEvents((prev) => [...prev, eventData]);
|
||||
}
|
||||
resetForm();
|
||||
setDialogOpen(false);
|
||||
};
|
||||
|
||||
const handleDelete = async (id: string) => {
|
||||
await deleteEvent(id)
|
||||
setEvents(prev => prev.filter(e => e.id !== id))
|
||||
}
|
||||
await deleteEvent(id);
|
||||
setEvents((prev) => prev.filter((e) => e.id !== id));
|
||||
};
|
||||
|
||||
const handleClearAll = async () => {
|
||||
await clearEvents()
|
||||
setEvents([])
|
||||
}
|
||||
await clearEvents();
|
||||
setEvents([]);
|
||||
};
|
||||
|
||||
const handleImport = async (file: File) => {
|
||||
const text = await file.text()
|
||||
const parsed = parseICS(text)
|
||||
const text = await file.text();
|
||||
const parsed = parseICS(text);
|
||||
for (const ev of parsed) {
|
||||
await addEvent(ev)
|
||||
}
|
||||
const stored = await getAllEvents()
|
||||
setEvents(stored)
|
||||
await addEvent(ev);
|
||||
}
|
||||
const stored = await getAllEvents();
|
||||
setEvents(stored);
|
||||
};
|
||||
|
||||
const handleExport = () => {
|
||||
const icsData = generateICS(events)
|
||||
const blob = new Blob([icsData], { type: 'text/calendar' })
|
||||
const url = URL.createObjectURL(blob)
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
a.download = `icallocal-export-${new Date().toLocaleTimeString()}.ics`
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
document.body.removeChild(a)
|
||||
URL.revokeObjectURL(url)
|
||||
}
|
||||
const icsData = generateICS(events);
|
||||
const blob = new Blob([icsData], { type: "text/calendar" });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = `icallocal-export-${new Date().toLocaleTimeString()}.ics`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(url);
|
||||
};
|
||||
|
||||
// AI Create Event
|
||||
const handleAiCreate = async () => {
|
||||
if (!aiPrompt.trim()) return
|
||||
setAiLoading(true)
|
||||
if (!aiPrompt.trim()) return;
|
||||
setAiLoading(true);
|
||||
|
||||
const promise = (): Promise<{ message: string }> => new Promise(async (resolve, reject) => {
|
||||
const promise = (): Promise<{ message: string }> =>
|
||||
new Promise(async (resolve, reject) => {
|
||||
try {
|
||||
const res = await fetch('/api/ai-event', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ prompt: aiPrompt })
|
||||
})
|
||||
const res = await fetch("/api/ai-event", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ prompt: aiPrompt }),
|
||||
});
|
||||
|
||||
if (res.status === 401) {
|
||||
setAiLoading(false)
|
||||
setAiLoading(false);
|
||||
reject({
|
||||
message: 'Please sign in to use AI features.'
|
||||
})
|
||||
return
|
||||
message: "Please sign in to use AI features.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const data = await res.json()
|
||||
const data = await res.json();
|
||||
|
||||
if (Array.isArray(data) && data.length > 0) {
|
||||
if (data.length === 1) {
|
||||
// Prefill dialog directly (same as before)
|
||||
const ev = data[0]
|
||||
setTitle(ev.title || '')
|
||||
setDescription(ev.description || '')
|
||||
setLocation(ev.location || '')
|
||||
setUrl(ev.url || '')
|
||||
setStart(ev.start || '')
|
||||
setEnd(ev.end || '')
|
||||
setAllDay(ev.allDay || false)
|
||||
setEditingId(null)
|
||||
setAiPrompt("")
|
||||
setDialogOpen(true)
|
||||
setRecurrenceRule(ev.recurrenceRule || undefined)
|
||||
const ev = data[0];
|
||||
setTitle(ev.title || "");
|
||||
setDescription(ev.description || "");
|
||||
setLocation(ev.location || "");
|
||||
setUrl(ev.url || "");
|
||||
setStart(ev.start || "");
|
||||
setEnd(ev.end || "");
|
||||
setAllDay(ev.allDay || false);
|
||||
setEditingId(null);
|
||||
setAiPrompt("");
|
||||
setDialogOpen(true);
|
||||
setRecurrenceRule(ev.recurrenceRule || undefined);
|
||||
resolve({
|
||||
message: 'Event has been created!'
|
||||
})
|
||||
|
||||
message: "Event has been created!",
|
||||
});
|
||||
} else {
|
||||
// Save them all directly to DB
|
||||
for (const ev of data) {
|
||||
@@ -168,86 +178,86 @@ export default function HomePage() {
|
||||
...ev,
|
||||
createdAt: new Date().toISOString(),
|
||||
lastModified: new Date().toISOString(),
|
||||
};
|
||||
await addEvent(newEvent);
|
||||
}
|
||||
await addEvent(newEvent)
|
||||
}
|
||||
const stored = await getAllEvents()
|
||||
setEvents(stored)
|
||||
setAiPrompt("")
|
||||
setSummary(`Added ${data.length} AI-generated events.`)
|
||||
setSummaryUpdated(new Date().toLocaleString())
|
||||
const stored = await getAllEvents();
|
||||
setEvents(stored);
|
||||
setAiPrompt("");
|
||||
setSummary(`Added ${data.length} AI-generated events.`);
|
||||
setSummaryUpdated(new Date().toLocaleString());
|
||||
resolve({
|
||||
message: 'Event has been created!'
|
||||
})
|
||||
message: "Event has been created!",
|
||||
});
|
||||
}
|
||||
} else {
|
||||
reject({
|
||||
message: 'AI did not return event data.'
|
||||
})
|
||||
message: "AI did not return event data.",
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err)
|
||||
console.error(err);
|
||||
reject({
|
||||
message: 'Error from AI service.'
|
||||
})
|
||||
message: "Error from AI service.",
|
||||
});
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
toast.promise(promise, {
|
||||
loading: "Generating event...",
|
||||
success: ({ message }) => {
|
||||
return message
|
||||
return message;
|
||||
},
|
||||
error: ({ message }) => {
|
||||
return message
|
||||
}
|
||||
})
|
||||
return message;
|
||||
},
|
||||
});
|
||||
|
||||
setAiLoading(false)
|
||||
}
|
||||
setAiLoading(false);
|
||||
};
|
||||
|
||||
// AI Summarize Events
|
||||
const handleAiSummarize = async () => {
|
||||
if (!events.length) {
|
||||
setSummary("No events to summarize.")
|
||||
setSummaryUpdated(new Date().toLocaleString())
|
||||
return
|
||||
setSummary("No events to summarize.");
|
||||
setSummaryUpdated(new Date().toLocaleString());
|
||||
return;
|
||||
}
|
||||
setAiLoading(true)
|
||||
setAiLoading(true);
|
||||
try {
|
||||
const res = await fetch('/api/ai-summary', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ events })
|
||||
})
|
||||
const data = await res.json()
|
||||
const res = await fetch("/api/ai-summary", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ events }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (data.summary) {
|
||||
setSummary(data.summary)
|
||||
setSummaryUpdated(new Date().toLocaleString())
|
||||
setSummary(data.summary);
|
||||
setSummaryUpdated(new Date().toLocaleString());
|
||||
} else {
|
||||
setSummary("No summary generated.")
|
||||
setSummaryUpdated(new Date().toLocaleString())
|
||||
setSummary("No summary generated.");
|
||||
setSummaryUpdated(new Date().toLocaleString());
|
||||
}
|
||||
} catch {
|
||||
setSummary("Error summarizing events")
|
||||
setSummaryUpdated(new Date().toLocaleString())
|
||||
setSummary("Error summarizing events");
|
||||
setSummaryUpdated(new Date().toLocaleString());
|
||||
} finally {
|
||||
setAiLoading(false)
|
||||
}
|
||||
setAiLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleEdit = (eventData: CalendarEvent) => {
|
||||
setTitle(eventData.title)
|
||||
setDescription(eventData.description || "")
|
||||
setLocation(eventData.location || "")
|
||||
setUrl(eventData.url || "")
|
||||
setStart(eventData.start)
|
||||
setEnd(eventData.end || "")
|
||||
setAllDay(eventData.allDay || false)
|
||||
setEditingId(eventData.id)
|
||||
setRecurrenceRule(eventData.recurrenceRule)
|
||||
setDialogOpen(true)
|
||||
}
|
||||
setTitle(eventData.title);
|
||||
setDescription(eventData.description || "");
|
||||
setLocation(eventData.location || "");
|
||||
setUrl(eventData.url || "");
|
||||
setStart(eventData.start);
|
||||
setEnd(eventData.end || "");
|
||||
setAllDay(eventData.allDay || false);
|
||||
setEditingId(eventData.id);
|
||||
setRecurrenceRule(eventData.recurrenceRule);
|
||||
setDialogOpen(true);
|
||||
};
|
||||
|
||||
return (
|
||||
<DragDropContainer
|
||||
@@ -275,11 +285,7 @@ export default function HomePage() {
|
||||
onClearAll={handleClearAll}
|
||||
/>
|
||||
|
||||
<EventsList
|
||||
events={events}
|
||||
onEdit={handleEdit}
|
||||
onDelete={handleDelete}
|
||||
/>
|
||||
<EventsList events={events} onEdit={handleEdit} onDelete={handleDelete} />
|
||||
|
||||
<EventDialog
|
||||
open={dialogOpen}
|
||||
@@ -305,5 +311,5 @@ export default function HomePage() {
|
||||
onReset={resetForm}
|
||||
/>
|
||||
</DragDropContainer>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { Card } from '@/components/ui/card'
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Card } from "@/components/ui/card";
|
||||
|
||||
interface AIToolbarProps {
|
||||
isAuthenticated: boolean
|
||||
isPending: boolean
|
||||
aiPrompt: string
|
||||
setAiPrompt: (prompt: string) => void
|
||||
aiLoading: boolean
|
||||
onAiCreate: () => void
|
||||
onAiSummarize: () => void
|
||||
summary: string | null
|
||||
summaryUpdated: string | null
|
||||
isAuthenticated: boolean;
|
||||
isPending: boolean;
|
||||
aiPrompt: string;
|
||||
setAiPrompt: (prompt: string) => void;
|
||||
aiLoading: boolean;
|
||||
onAiCreate: () => void;
|
||||
onAiSummarize: () => void;
|
||||
summary: string | null;
|
||||
summaryUpdated: string | null;
|
||||
}
|
||||
|
||||
export const AIToolbar = ({
|
||||
@@ -23,28 +23,30 @@ export const AIToolbar = ({
|
||||
onAiCreate,
|
||||
onAiSummarize,
|
||||
summary,
|
||||
summaryUpdated
|
||||
summaryUpdated,
|
||||
}: AIToolbarProps) => {
|
||||
return (
|
||||
<>
|
||||
{isPending ? (
|
||||
<div className='mb-4 p-4 text-center animate-pulse bg-muted'>Loading...</div>
|
||||
<div className="mb-4 p-4 text-center animate-pulse bg-muted">
|
||||
Loading...
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
{isAuthenticated ? (
|
||||
<div className="flex flex-col sm:flex-row gap-4 mb-4 items-start">
|
||||
<div className='w-full'>
|
||||
<div className="w-full">
|
||||
<Textarea
|
||||
className="wrap-anywhere field-sizing-content resize-none w-full min-h-[2.5rem] max-h-64 overflow-y-auto sm:overflow-y-visible px-3 py-2 scroll-p-8 placeholder:italic"
|
||||
style={{ clipPath: "inset(0 round 1rem)" }}
|
||||
placeholder='Describe event for AI to create'
|
||||
placeholder="Describe event for AI to create"
|
||||
value={aiPrompt}
|
||||
onChange={e => setAiPrompt(e.target.value)}
|
||||
onChange={(e) => setAiPrompt(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className='flex flex-row gap-2 pt-1'>
|
||||
<div className="flex flex-row gap-2 pt-1">
|
||||
<Button onClick={onAiCreate} disabled={aiLoading}>
|
||||
{aiLoading ? 'Thinking...' : 'AI Create'}
|
||||
{aiLoading ? "Thinking..." : "AI Create"}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -61,20 +63,22 @@ export const AIToolbar = ({
|
||||
{/* Summary Panel */}
|
||||
{summary && (
|
||||
<Card className="p-4 mb-4">
|
||||
<div className="text-sm mb-1">
|
||||
Summary updated {summaryUpdated}
|
||||
</div>
|
||||
<div className="text-sm mb-1">Summary updated {summaryUpdated}</div>
|
||||
<div>{summary}</div>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* AI Actions Toolbar */}
|
||||
<p className='text-muted-foreground text-sm pb-2 pl-1'>AI actions</p>
|
||||
<p className="text-muted-foreground text-sm pb-2 pl-1">AI actions</p>
|
||||
<div className="gap-2 mb-4">
|
||||
<Button variant="secondary" onClick={onAiSummarize} disabled={aiLoading}>
|
||||
{aiLoading ? 'Summarizing...' : 'AI Summarize'}
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={onAiSummarize}
|
||||
disabled={aiLoading}
|
||||
>
|
||||
{aiLoading ? "Summarizing..." : "AI Summarize"}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,41 +1,41 @@
|
||||
import { ReactNode } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
import { ReactNode } from "react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
interface DragDropContainerProps {
|
||||
children: ReactNode
|
||||
isDragOver: boolean
|
||||
setIsDragOver: (isDragOver: boolean) => void
|
||||
onImport: (file: File) => void
|
||||
children: ReactNode;
|
||||
isDragOver: boolean;
|
||||
setIsDragOver: (isDragOver: boolean) => void;
|
||||
onImport: (file: File) => void;
|
||||
}
|
||||
|
||||
export const DragDropContainer = ({
|
||||
children,
|
||||
isDragOver,
|
||||
setIsDragOver,
|
||||
onImport
|
||||
onImport,
|
||||
}: DragDropContainerProps) => {
|
||||
const handleDragOver = (e: React.DragEvent) => {
|
||||
e.preventDefault()
|
||||
setIsDragOver(true)
|
||||
}
|
||||
e.preventDefault();
|
||||
setIsDragOver(true);
|
||||
};
|
||||
|
||||
const handleDragLeave = (e: React.DragEvent) => {
|
||||
e.preventDefault()
|
||||
setIsDragOver(false)
|
||||
}
|
||||
e.preventDefault();
|
||||
setIsDragOver(false);
|
||||
};
|
||||
|
||||
const handleDrop = (e: React.DragEvent) => {
|
||||
e.preventDefault()
|
||||
setIsDragOver(false)
|
||||
e.preventDefault();
|
||||
setIsDragOver(false);
|
||||
if (e.dataTransfer.files?.length) {
|
||||
const file = e.dataTransfer.files[0]
|
||||
if (file.name.endsWith('.ics')) {
|
||||
onImport(file)
|
||||
const file = e.dataTransfer.files[0];
|
||||
if (file.name.endsWith(".ics")) {
|
||||
onImport(file);
|
||||
} else {
|
||||
toast.warning('Please drop an .ics file')
|
||||
}
|
||||
toast.warning("Please drop an .ics file");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -43,13 +43,13 @@ export const DragDropContainer = ({
|
||||
onDragLeave={handleDragLeave}
|
||||
onDrop={handleDrop}
|
||||
className={`p-4 min-h-[80vh] flex flex-col rounded border-2 border-dashed transition ${
|
||||
isDragOver ? 'border-blue-500 bg-blue-50' : 'border-gray-700'
|
||||
isDragOver ? "border-blue-500 bg-blue-50" : "border-gray-700"
|
||||
}`}
|
||||
>
|
||||
{children}
|
||||
<div className='mt-auto w-full pb-4 text-gray-400'>
|
||||
<div className='max-w-fit m-auto'>Drag & Drop *.ics here</div>
|
||||
<div className="mt-auto w-full pb-4 text-gray-400">
|
||||
<div className="max-w-fit m-auto">Drag & Drop *.ics here</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { IcsFilePicker } from '@/components/ics-file-picker'
|
||||
import type { CalendarEvent } from '@/lib/types'
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { IcsFilePicker } from "@/components/ics-file-picker";
|
||||
import type { CalendarEvent } from "@/lib/types";
|
||||
|
||||
interface EventActionsToolbarProps {
|
||||
events: CalendarEvent[]
|
||||
onAddEvent: () => void
|
||||
onImport: (file: File) => void
|
||||
onExport: () => void
|
||||
onClearAll: () => void
|
||||
events: CalendarEvent[];
|
||||
onAddEvent: () => void;
|
||||
onImport: (file: File) => void;
|
||||
onExport: () => void;
|
||||
onClearAll: () => void;
|
||||
}
|
||||
|
||||
export const EventActionsToolbar = ({
|
||||
@@ -15,22 +15,28 @@ export const EventActionsToolbar = ({
|
||||
onAddEvent,
|
||||
onImport,
|
||||
onExport,
|
||||
onClearAll
|
||||
onClearAll,
|
||||
}: EventActionsToolbarProps) => {
|
||||
return (
|
||||
<>
|
||||
{/* Control Toolbar */}
|
||||
<p className='text-muted-foreground text-sm pb-2 pl-1'>Event Actions</p>
|
||||
<p className="text-muted-foreground text-sm pb-2 pl-1">Event Actions</p>
|
||||
<div className="flex flex-wrap gap-2 mb-4">
|
||||
<Button onClick={onAddEvent}>Add Event</Button>
|
||||
<IcsFilePicker onFileSelect={onImport} variant='secondary'>Import .ics</IcsFilePicker>
|
||||
<IcsFilePicker onFileSelect={onImport} variant="secondary">
|
||||
Import .ics
|
||||
</IcsFilePicker>
|
||||
{events.length > 0 && (
|
||||
<>
|
||||
<Button variant="secondary" onClick={onExport}>Export .ics</Button>
|
||||
<Button variant="destructive" onClick={onClearAll}>Clear All</Button>
|
||||
<Button variant="secondary" onClick={onExport}>
|
||||
Export .ics
|
||||
</Button>
|
||||
<Button variant="destructive" onClick={onClearAll}>
|
||||
Clear All
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,35 +1,40 @@
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardHeader, CardContent } from '@/components/ui/card'
|
||||
import { LucideMapPin, Clock, MoreHorizontal } from 'lucide-react'
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuTrigger, DropdownMenuItem } from '@/components/ui/dropdown-menu'
|
||||
import { RRuleDisplay } from '@/components/rrule-display'
|
||||
import type { CalendarEvent } from '@/lib/types'
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardHeader, CardContent } from "@/components/ui/card";
|
||||
import { LucideMapPin, Clock, MoreHorizontal } from "lucide-react";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuTrigger,
|
||||
DropdownMenuItem,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { RRuleDisplay } from "@/components/rrule-display";
|
||||
import type { CalendarEvent } from "@/lib/types";
|
||||
|
||||
interface EventCardProps {
|
||||
event: CalendarEvent
|
||||
onEdit: (event: CalendarEvent) => void
|
||||
onDelete: (eventId: string) => void
|
||||
event: CalendarEvent;
|
||||
onEdit: (event: CalendarEvent) => void;
|
||||
onDelete: (eventId: string) => void;
|
||||
}
|
||||
|
||||
export const EventCard = ({ event, onEdit, onDelete }: EventCardProps) => {
|
||||
const formatDateTime = (dateStr: string, allDay: boolean | undefined) => {
|
||||
return allDay
|
||||
? new Date(dateStr).toLocaleDateString()
|
||||
: new Date(dateStr).toLocaleString()
|
||||
}
|
||||
: new Date(dateStr).toLocaleString();
|
||||
};
|
||||
|
||||
const handleEdit = () => {
|
||||
onEdit({
|
||||
id: event.id,
|
||||
title: event.title,
|
||||
description: event.description || '',
|
||||
location: event.location || '',
|
||||
url: event.url || '',
|
||||
description: event.description || "",
|
||||
location: event.location || "",
|
||||
url: event.url || "",
|
||||
start: event.start,
|
||||
end: event.end || '',
|
||||
allDay: event.allDay || false
|
||||
})
|
||||
}
|
||||
end: event.end || "",
|
||||
allDay: event.allDay || false,
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<Card className="w-full">
|
||||
@@ -58,9 +63,7 @@ export const EventCard = ({ event, onEdit, onDelete }: EventCardProps) => {
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={handleEdit}>
|
||||
Edit
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={handleEdit}>Edit</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => onDelete(event.id)}
|
||||
className="text-destructive"
|
||||
@@ -88,5 +91,5 @@ export const EventCard = ({ event, onEdit, onDelete }: EventCardProps) => {
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,30 +1,36 @@
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { RecurrencePicker } from '@/components/recurrence-picker'
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { RecurrencePicker } from "@/components/recurrence-picker";
|
||||
|
||||
interface EventDialogProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
editingId: string | null
|
||||
title: string
|
||||
setTitle: (title: string) => void
|
||||
description: string
|
||||
setDescription: (description: string) => void
|
||||
location: string
|
||||
setLocation: (location: string) => void
|
||||
url: string
|
||||
setUrl: (url: string) => void
|
||||
start: string
|
||||
setStart: (start: string) => void
|
||||
end: string
|
||||
setEnd: (end: string) => void
|
||||
allDay: boolean
|
||||
setAllDay: (allDay: boolean) => void
|
||||
recurrenceRule: string | undefined
|
||||
setRecurrenceRule: (rule: string | undefined) => void
|
||||
onSave: () => void
|
||||
onReset: () => void
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
editingId: string | null;
|
||||
title: string;
|
||||
setTitle: (title: string) => void;
|
||||
description: string;
|
||||
setDescription: (description: string) => void;
|
||||
location: string;
|
||||
setLocation: (location: string) => void;
|
||||
url: string;
|
||||
setUrl: (url: string) => void;
|
||||
start: string;
|
||||
setStart: (start: string) => void;
|
||||
end: string;
|
||||
setEnd: (end: string) => void;
|
||||
allDay: boolean;
|
||||
setAllDay: (allDay: boolean) => void;
|
||||
recurrenceRule: string | undefined;
|
||||
setRecurrenceRule: (rule: string | undefined) => void;
|
||||
onSave: () => void;
|
||||
onReset: () => void;
|
||||
}
|
||||
|
||||
export const EventDialog = ({
|
||||
@@ -48,49 +54,81 @@ export const EventDialog = ({
|
||||
recurrenceRule,
|
||||
setRecurrenceRule,
|
||||
onSave,
|
||||
onReset
|
||||
onReset,
|
||||
}: EventDialogProps) => {
|
||||
const handleOpenChange = (val: boolean) => {
|
||||
if (!val) onReset()
|
||||
onOpenChange(val)
|
||||
}
|
||||
if (!val) onReset();
|
||||
onOpenChange(val);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{editingId ? 'Edit Event' : 'Add Event'}</DialogTitle>
|
||||
<DialogTitle>{editingId ? "Edit Event" : "Add Event"}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<Input placeholder="Title" value={title} onChange={e => setTitle(e.target.value)} />
|
||||
<Input
|
||||
placeholder="Title"
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
/>
|
||||
<textarea
|
||||
className="border rounded p-2 w-full"
|
||||
placeholder="Description"
|
||||
value={description}
|
||||
onChange={e => setDescription(e.target.value)}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
/>
|
||||
<Input
|
||||
placeholder="Location"
|
||||
value={location}
|
||||
onChange={(e) => setLocation(e.target.value)}
|
||||
/>
|
||||
<Input
|
||||
placeholder="URL"
|
||||
value={url}
|
||||
onChange={(e) => setUrl(e.target.value)}
|
||||
/>
|
||||
<Input placeholder="Location" value={location} onChange={e => setLocation(e.target.value)} />
|
||||
<Input placeholder="URL" value={url} onChange={e => setUrl(e.target.value)} />
|
||||
<RecurrencePicker value={recurrenceRule} onChange={setRecurrenceRule} />
|
||||
|
||||
<label className="flex items-center gap-2 mt-2">
|
||||
<input type="checkbox" checked={allDay} onChange={e => setAllDay(e.target.checked)} />
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={allDay}
|
||||
onChange={(e) => setAllDay(e.target.checked)}
|
||||
/>
|
||||
All day event
|
||||
</label>
|
||||
{!allDay ? (
|
||||
<>
|
||||
<Input type="datetime-local" value={start} onChange={e => setStart(e.target.value)} />
|
||||
<Input type="datetime-local" value={end} onChange={e => setEnd(e.target.value)} />
|
||||
<Input
|
||||
type="datetime-local"
|
||||
value={start}
|
||||
onChange={(e) => setStart(e.target.value)}
|
||||
/>
|
||||
<Input
|
||||
type="datetime-local"
|
||||
value={end}
|
||||
onChange={(e) => setEnd(e.target.value)}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Input type="date" value={start ? start.split('T')[0] : ''} onChange={e => setStart(e.target.value)} />
|
||||
<Input type="date" value={end ? end.split('T')[0] : ''} onChange={e => setEnd(e.target.value)} />
|
||||
<Input
|
||||
type="date"
|
||||
value={start ? start.split("T")[0] : ""}
|
||||
onChange={(e) => setStart(e.target.value)}
|
||||
/>
|
||||
<Input
|
||||
type="date"
|
||||
value={end ? end.split("T")[0] : ""}
|
||||
onChange={(e) => setEnd(e.target.value)}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
<DialogFooter>
|
||||
<Button onClick={onSave}>{editingId ? 'Update' : 'Save'}</Button>
|
||||
<Button onClick={onSave}>{editingId ? "Update" : "Save"}</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,27 +1,31 @@
|
||||
import { Calendar1Icon } from 'lucide-react'
|
||||
import { EventCard } from './event-card'
|
||||
import type { CalendarEvent } from '@/lib/types'
|
||||
import { Calendar1Icon } from "lucide-react";
|
||||
import { EventCard } from "./event-card";
|
||||
import type { CalendarEvent } from "@/lib/types";
|
||||
|
||||
interface EventsListProps {
|
||||
events: CalendarEvent[]
|
||||
onEdit: (event: CalendarEvent) => void
|
||||
onDelete: (eventId: string) => void
|
||||
events: CalendarEvent[];
|
||||
onEdit: (event: CalendarEvent) => void;
|
||||
onDelete: (eventId: string) => void;
|
||||
}
|
||||
|
||||
export const EventsList = ({ events, onEdit, onDelete }: EventsListProps) => {
|
||||
if (events.length === 0) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center py-8 text-center">
|
||||
<Calendar1Icon className='h-12 w-12 text-muted-foreground mb-4' />
|
||||
<h3 className="text-lg font-medium text-muted-foreground">No events yet</h3>
|
||||
<p className="text-sm text-muted-foreground">Create your first event to get started</p>
|
||||
<Calendar1Icon className="h-12 w-12 text-muted-foreground mb-4" />
|
||||
<h3 className="text-lg font-medium text-muted-foreground">
|
||||
No events yet
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Create your first event to get started
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{events.map(event => (
|
||||
{events.map((event) => (
|
||||
<EventCard
|
||||
key={event.id}
|
||||
event={event}
|
||||
@@ -30,5 +34,5 @@ export const EventsList = ({ events, onEdit, onDelete }: EventsListProps) => {
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,17 +1,23 @@
|
||||
"use client"
|
||||
"use client";
|
||||
|
||||
import type React from "react"
|
||||
import type React from "react";
|
||||
|
||||
import { useRef } from "react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Calendar } from "lucide-react"
|
||||
import { useRef } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Calendar } from "lucide-react";
|
||||
|
||||
interface IcsFilePickerProps {
|
||||
onFileSelect?: (file: File) => void
|
||||
className?: string
|
||||
children?: React.ReactNode
|
||||
variant?: "default" | "destructive" | "outline" | "secondary" | "ghost" | "link"
|
||||
size?: "default" | "sm" | "lg" | "icon"
|
||||
onFileSelect?: (file: File) => void;
|
||||
className?: string;
|
||||
children?: React.ReactNode;
|
||||
variant?:
|
||||
| "default"
|
||||
| "destructive"
|
||||
| "outline"
|
||||
| "secondary"
|
||||
| "ghost"
|
||||
| "link";
|
||||
size?: "default" | "sm" | "lg" | "icon";
|
||||
}
|
||||
|
||||
export function IcsFilePicker({
|
||||
@@ -21,18 +27,18 @@ export function IcsFilePicker({
|
||||
variant = "default",
|
||||
size = "default",
|
||||
}: IcsFilePickerProps) {
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const handleButtonClick = () => {
|
||||
fileInputRef.current?.click()
|
||||
}
|
||||
fileInputRef.current?.click();
|
||||
};
|
||||
|
||||
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = event.target.files?.[0]
|
||||
const file = event.target.files?.[0];
|
||||
if (file && onFileSelect) {
|
||||
onFileSelect(file)
|
||||
}
|
||||
onFileSelect(file);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -44,7 +50,12 @@ export function IcsFilePicker({
|
||||
className="hidden"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<Button onClick={handleButtonClick} variant={variant} size={size} className={className}>
|
||||
<Button
|
||||
onClick={handleButtonClick}
|
||||
variant={variant}
|
||||
size={size}
|
||||
className={className}
|
||||
>
|
||||
{children || (
|
||||
<>
|
||||
<Calendar className="mr-2 h-4 w-4" />
|
||||
@@ -53,6 +64,5 @@ export function IcsFilePicker({
|
||||
)}
|
||||
</Button>
|
||||
</>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,56 +1,55 @@
|
||||
"use client"
|
||||
"use client";
|
||||
|
||||
import * as React from "react"
|
||||
import { Moon, Sun, Monitor } from "lucide-react"
|
||||
import { useTheme } from "next-themes"
|
||||
import * as React from "react";
|
||||
import { Moon, Sun, Monitor } from "lucide-react";
|
||||
import { useTheme } from "next-themes";
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
|
||||
type ThemeIconProps = {
|
||||
theme?: string
|
||||
}
|
||||
theme?: string;
|
||||
};
|
||||
|
||||
const ThemeIcon = ({ theme }: ThemeIconProps) => {
|
||||
|
||||
const [mounted, setMounted] = React.useState(false)
|
||||
const [mounted, setMounted] = React.useState(false);
|
||||
|
||||
React.useEffect(() => {
|
||||
setMounted(true)
|
||||
}, [])
|
||||
setMounted(true);
|
||||
}, []);
|
||||
|
||||
if (!mounted) {
|
||||
return null
|
||||
return null;
|
||||
}
|
||||
|
||||
switch (theme) {
|
||||
case "light":
|
||||
return (
|
||||
<Sun className="absolute h-[1.2rem] w-[1.2rem] scale-100 rotate-0 transition-all dark:scale-0 dark:-rotate-90" />
|
||||
)
|
||||
);
|
||||
case "dark":
|
||||
return (
|
||||
<Moon className="absolute h-[1.2rem] w-[1.2rem] scale-0 rotate-90 transition-all dark:scale-100 dark:rotate-0" />
|
||||
)
|
||||
);
|
||||
case "system":
|
||||
return (
|
||||
<Monitor className="absolute h-[1.2rem] w-[1.2rem] scale-100" />
|
||||
)
|
||||
return <Monitor className="absolute h-[1.2rem] w-[1.2rem] scale-100" />;
|
||||
default:
|
||||
return (<>
|
||||
return (
|
||||
<>
|
||||
<Sun className="h-[1.2rem] w-[1.2rem] scale-100 rotate-0 transition-all dark:scale-0 dark:-rotate-90" />
|
||||
<Moon className="absolute h-[1.2rem] w-[1.2rem] scale-0 rotate-90 transition-all dark:scale-100 dark:rotate-0" />
|
||||
</>)
|
||||
</>
|
||||
);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export function ModeToggle() {
|
||||
const { setTheme, theme } = useTheme()
|
||||
const { setTheme, theme } = useTheme();
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
@@ -72,6 +71,5 @@ export function ModeToggle() {
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,65 +1,76 @@
|
||||
"use client"
|
||||
"use client";
|
||||
|
||||
import { useState } from "react"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
||||
import { Checkbox } from "@/components/ui/checkbox"
|
||||
import { useState } from "react";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
|
||||
type Recurrence = {
|
||||
freq: "NONE" | "DAILY" | "WEEKLY" | "MONTHLY"
|
||||
interval: number
|
||||
byDay?: string[]
|
||||
count?: number
|
||||
until?: string
|
||||
}
|
||||
freq: "NONE" | "DAILY" | "WEEKLY" | "MONTHLY";
|
||||
interval: number;
|
||||
byDay?: string[];
|
||||
count?: number;
|
||||
until?: string;
|
||||
};
|
||||
|
||||
interface Props {
|
||||
value?: string
|
||||
onChange: (rrule: string | undefined) => void
|
||||
value?: string;
|
||||
onChange: (rrule: string | undefined) => void;
|
||||
}
|
||||
|
||||
export function RecurrencePicker({ value, onChange }: Props) {
|
||||
const [rec, setRec] = useState<Recurrence>(() => {
|
||||
// If existing rrule, parse minimally (for simplicity we only rehydrate FREQ and INTERVAL)
|
||||
if (value) {
|
||||
const parts = Object.fromEntries(value.split(";").map((p) => p.split("=")))
|
||||
const parts = Object.fromEntries(
|
||||
value.split(";").map((p) => p.split("=")),
|
||||
);
|
||||
return {
|
||||
freq: parts.FREQ || "NONE",
|
||||
interval: parts.INTERVAL ? Number.parseInt(parts.INTERVAL, 10) : 1,
|
||||
byDay: parts.BYDAY ? parts.BYDAY.split(",") : [],
|
||||
count: parts.COUNT ? Number.parseInt(parts.COUNT, 10) : undefined,
|
||||
until: parts.UNTIL,
|
||||
};
|
||||
}
|
||||
}
|
||||
return { freq: "NONE", interval: 1 }
|
||||
})
|
||||
return { freq: "NONE", interval: 1 };
|
||||
});
|
||||
|
||||
const update = (updates: Partial<Recurrence>) => {
|
||||
const newRec = { ...rec, ...updates }
|
||||
setRec(newRec)
|
||||
const newRec = { ...rec, ...updates };
|
||||
setRec(newRec);
|
||||
|
||||
if (newRec.freq === "NONE") {
|
||||
onChange(undefined)
|
||||
return
|
||||
onChange(undefined);
|
||||
return;
|
||||
}
|
||||
|
||||
// Build RRULE string
|
||||
let rrule = `FREQ=${newRec.freq};INTERVAL=${newRec.interval}`
|
||||
let rrule = `FREQ=${newRec.freq};INTERVAL=${newRec.interval}`;
|
||||
if (newRec.freq === "WEEKLY" && newRec.byDay?.length) {
|
||||
rrule += `;BYDAY=${newRec.byDay.join(",")}`
|
||||
rrule += `;BYDAY=${newRec.byDay.join(",")}`;
|
||||
}
|
||||
if (newRec.count) rrule += `;COUNT=${newRec.count}`
|
||||
if (newRec.until) rrule += `;UNTIL=${newRec.until.replace(/-/g, "")}T000000Z`
|
||||
if (newRec.count) rrule += `;COUNT=${newRec.count}`;
|
||||
if (newRec.until)
|
||||
rrule += `;UNTIL=${newRec.until.replace(/-/g, "")}T000000Z`;
|
||||
|
||||
onChange(rrule)
|
||||
}
|
||||
onChange(rrule);
|
||||
};
|
||||
|
||||
const toggleDay = (day: string) => {
|
||||
const byDay = rec.byDay || []
|
||||
const newByDay = byDay.includes(day) ? byDay.filter((d) => d !== day) : [...byDay, day]
|
||||
update({ byDay: newByDay })
|
||||
}
|
||||
const byDay = rec.byDay || [];
|
||||
const newByDay = byDay.includes(day)
|
||||
? byDay.filter((d) => d !== day)
|
||||
: [...byDay, day];
|
||||
update({ byDay: newByDay });
|
||||
};
|
||||
|
||||
const dayLabels = {
|
||||
MO: "Mon",
|
||||
@@ -69,13 +80,20 @@ export function RecurrencePicker({ value, onChange }: Props) {
|
||||
FR: "Fri",
|
||||
SA: "Sat",
|
||||
SU: "Sun",
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="">
|
||||
<Label htmlFor="frequency" className="pt-4 pb-2 pl-1">Repeats</Label>
|
||||
<Label htmlFor="frequency" className="pt-4 pb-2 pl-1">
|
||||
Repeats
|
||||
</Label>
|
||||
<div className="space-y-2">
|
||||
<Select value={rec.freq} onValueChange={(value) => update({ freq: value as Recurrence["freq"] })}>
|
||||
<Select
|
||||
value={rec.freq}
|
||||
onValueChange={(value) =>
|
||||
update({ freq: value as Recurrence["freq"] })
|
||||
}
|
||||
>
|
||||
<SelectTrigger id="frequency">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
@@ -92,7 +110,12 @@ export function RecurrencePicker({ value, onChange }: Props) {
|
||||
<>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="interval">
|
||||
Interval (every {rec.interval} {rec.freq === "DAILY" ? "day" : rec.freq === "WEEKLY" ? "week" : "month"}
|
||||
Interval (every {rec.interval}{" "}
|
||||
{rec.freq === "DAILY"
|
||||
? "day"
|
||||
: rec.freq === "WEEKLY"
|
||||
? "week"
|
||||
: "month"}
|
||||
{rec.interval > 1 ? "s" : ""})
|
||||
</Label>
|
||||
<Input
|
||||
@@ -100,7 +123,9 @@ export function RecurrencePicker({ value, onChange }: Props) {
|
||||
type="number"
|
||||
min={1}
|
||||
value={rec.interval}
|
||||
onChange={(e) => update({ interval: Number.parseInt(e.target.value, 10) || 1 })}
|
||||
onChange={(e) =>
|
||||
update({ interval: Number.parseInt(e.target.value, 10) || 1 })
|
||||
}
|
||||
className="w-24"
|
||||
/>
|
||||
</div>
|
||||
@@ -133,7 +158,13 @@ export function RecurrencePicker({ value, onChange }: Props) {
|
||||
type="number"
|
||||
placeholder="e.g. 10"
|
||||
value={rec.count || ""}
|
||||
onChange={(e) => update({ count: e.target.value ? Number.parseInt(e.target.value, 10) : undefined })}
|
||||
onChange={(e) =>
|
||||
update({
|
||||
count: e.target.value
|
||||
? Number.parseInt(e.target.value, 10)
|
||||
: undefined,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
@@ -149,5 +180,5 @@ export function RecurrencePicker({ value, onChange }: Props) {
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,32 +1,38 @@
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import type { RecurrenceRule } from "@/lib/rfc5545-types"
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import type { RecurrenceRule } from "@/lib/rfc5545-types";
|
||||
|
||||
interface RRuleDisplayProps {
|
||||
rrule: string | RecurrenceRule
|
||||
className?: string
|
||||
rrule: string | RecurrenceRule;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function RRuleDisplay({ rrule, className }: RRuleDisplayProps) {
|
||||
const parsedRule = typeof rrule === 'string' ? parseRRuleString(rrule) : rrule
|
||||
const humanText = formatRRuleToHuman(parsedRule)
|
||||
const parsedRule =
|
||||
typeof rrule === "string" ? parseRRuleString(rrule) : rrule;
|
||||
const humanText = formatRRuleToHuman(parsedRule);
|
||||
|
||||
return (
|
||||
<div className={className}>
|
||||
<span className="text-sm text-muted-foreground">{humanText}</span>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
interface RRuleDisplayDetailedProps {
|
||||
rrule: string | RecurrenceRule
|
||||
className?: string
|
||||
showBadges?: boolean
|
||||
rrule: string | RecurrenceRule;
|
||||
className?: string;
|
||||
showBadges?: boolean;
|
||||
}
|
||||
|
||||
export function RRuleDisplayDetailed({ rrule, className, showBadges = true }: RRuleDisplayDetailedProps) {
|
||||
const parsedRule = typeof rrule === 'string' ? parseRRuleString(rrule) : rrule
|
||||
const humanText = formatRRuleToHuman(parsedRule)
|
||||
const details = getRRuleDetails(parsedRule)
|
||||
export function RRuleDisplayDetailed({
|
||||
rrule,
|
||||
className,
|
||||
showBadges = true,
|
||||
}: RRuleDisplayDetailedProps) {
|
||||
const parsedRule =
|
||||
typeof rrule === "string" ? parseRRuleString(rrule) : rrule;
|
||||
const humanText = formatRRuleToHuman(parsedRule);
|
||||
const details = getRRuleDetails(parsedRule);
|
||||
|
||||
return (
|
||||
<div className={className}>
|
||||
@@ -44,201 +50,257 @@ export function RRuleDisplayDetailed({ rrule, className, showBadges = true }: RR
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function parseRRuleString(rruleString: string): RecurrenceRule {
|
||||
const parts = Object.fromEntries(rruleString.split(";").map(p => p.split("=")))
|
||||
const parts = Object.fromEntries(
|
||||
rruleString.split(";").map((p) => p.split("=")),
|
||||
);
|
||||
|
||||
return {
|
||||
freq: parts.FREQ as RecurrenceRule['freq'],
|
||||
until: parts.UNTIL ? new Date(parts.UNTIL.replace(/(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z?/, '$1-$2-$3T$4:$5:$6Z')).toISOString() : undefined,
|
||||
freq: parts.FREQ as RecurrenceRule["freq"],
|
||||
until: parts.UNTIL
|
||||
? new Date(
|
||||
parts.UNTIL.replace(
|
||||
/(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z?/,
|
||||
"$1-$2-$3T$4:$5:$6Z",
|
||||
),
|
||||
).toISOString()
|
||||
: undefined,
|
||||
count: parts.COUNT ? parseInt(parts.COUNT, 10) : undefined,
|
||||
interval: parts.INTERVAL ? parseInt(parts.INTERVAL, 10) : undefined,
|
||||
bySecond: parts.BYSECOND ? parts.BYSECOND.split(",").map((n: string) => parseInt(n, 10)) : undefined,
|
||||
byMinute: parts.BYMINUTE ? parts.BYMINUTE.split(",").map((n: string) => parseInt(n, 10)) : undefined,
|
||||
byHour: parts.BYHOUR ? parts.BYHOUR.split(",").map((n: string) => parseInt(n, 10)) : undefined,
|
||||
bySecond: parts.BYSECOND
|
||||
? parts.BYSECOND.split(",").map((n: string) => parseInt(n, 10))
|
||||
: undefined,
|
||||
byMinute: parts.BYMINUTE
|
||||
? parts.BYMINUTE.split(",").map((n: string) => parseInt(n, 10))
|
||||
: undefined,
|
||||
byHour: parts.BYHOUR
|
||||
? parts.BYHOUR.split(",").map((n: string) => parseInt(n, 10))
|
||||
: undefined,
|
||||
byDay: parts.BYDAY ? parts.BYDAY.split(",") : undefined,
|
||||
byMonthDay: parts.BYMONTHDAY ? parts.BYMONTHDAY.split(",").map((n: string) => parseInt(n, 10)) : undefined,
|
||||
byYearDay: parts.BYYEARDAY ? parts.BYYEARDAY.split(",").map((n: string) => parseInt(n, 10)) : undefined,
|
||||
byWeekNo: parts.BYWEEKNO ? parts.BYWEEKNO.split(",").map((n: string) => parseInt(n, 10)) : undefined,
|
||||
byMonth: parts.BYMONTH ? parts.BYMONTH.split(",").map((n: string) => parseInt(n, 10)) : undefined,
|
||||
bySetPos: parts.BYSETPOS ? parts.BYSETPOS.split(",").map((n: string) => parseInt(n, 10)) : undefined,
|
||||
wkst: parts.WKST as RecurrenceRule['wkst'],
|
||||
}
|
||||
byMonthDay: parts.BYMONTHDAY
|
||||
? parts.BYMONTHDAY.split(",").map((n: string) => parseInt(n, 10))
|
||||
: undefined,
|
||||
byYearDay: parts.BYYEARDAY
|
||||
? parts.BYYEARDAY.split(",").map((n: string) => parseInt(n, 10))
|
||||
: undefined,
|
||||
byWeekNo: parts.BYWEEKNO
|
||||
? parts.BYWEEKNO.split(",").map((n: string) => parseInt(n, 10))
|
||||
: undefined,
|
||||
byMonth: parts.BYMONTH
|
||||
? parts.BYMONTH.split(",").map((n: string) => parseInt(n, 10))
|
||||
: undefined,
|
||||
bySetPos: parts.BYSETPOS
|
||||
? parts.BYSETPOS.split(",").map((n: string) => parseInt(n, 10))
|
||||
: undefined,
|
||||
wkst: parts.WKST as RecurrenceRule["wkst"],
|
||||
};
|
||||
}
|
||||
|
||||
function formatRRuleToHuman(rule: RecurrenceRule): string {
|
||||
const { freq, interval = 1, count, until, byDay, byMonthDay, byMonth, byHour, byMinute, bySecond } = rule
|
||||
const {
|
||||
freq,
|
||||
interval = 1,
|
||||
count,
|
||||
until,
|
||||
byDay,
|
||||
byMonthDay,
|
||||
byMonth,
|
||||
byHour,
|
||||
byMinute,
|
||||
bySecond,
|
||||
} = rule;
|
||||
|
||||
let text = ""
|
||||
let text = "";
|
||||
|
||||
// Base frequency
|
||||
switch (freq) {
|
||||
case 'SECONDLY':
|
||||
text = interval === 1 ? "Every second" : `Every ${interval} seconds`
|
||||
break
|
||||
case 'MINUTELY':
|
||||
text = interval === 1 ? "Every minute" : `Every ${interval} minutes`
|
||||
break
|
||||
case 'HOURLY':
|
||||
text = interval === 1 ? "Every hour" : `Every ${interval} hours`
|
||||
break
|
||||
case 'DAILY':
|
||||
text = interval === 1 ? "Daily" : `Every ${interval} days`
|
||||
break
|
||||
case 'WEEKLY':
|
||||
text = interval === 1 ? "Weekly" : `Every ${interval} weeks`
|
||||
break
|
||||
case 'MONTHLY':
|
||||
text = interval === 1 ? "Monthly" : `Every ${interval} months`
|
||||
break
|
||||
case 'YEARLY':
|
||||
text = interval === 1 ? "Yearly" : `Every ${interval} years`
|
||||
break
|
||||
case "SECONDLY":
|
||||
text = interval === 1 ? "Every second" : `Every ${interval} seconds`;
|
||||
break;
|
||||
case "MINUTELY":
|
||||
text = interval === 1 ? "Every minute" : `Every ${interval} minutes`;
|
||||
break;
|
||||
case "HOURLY":
|
||||
text = interval === 1 ? "Every hour" : `Every ${interval} hours`;
|
||||
break;
|
||||
case "DAILY":
|
||||
text = interval === 1 ? "Daily" : `Every ${interval} days`;
|
||||
break;
|
||||
case "WEEKLY":
|
||||
text = interval === 1 ? "Weekly" : `Every ${interval} weeks`;
|
||||
break;
|
||||
case "MONTHLY":
|
||||
text = interval === 1 ? "Monthly" : `Every ${interval} months`;
|
||||
break;
|
||||
case "YEARLY":
|
||||
text = interval === 1 ? "Yearly" : `Every ${interval} years`;
|
||||
break;
|
||||
}
|
||||
|
||||
// Add day specifications
|
||||
if (byDay?.length) {
|
||||
const dayNames = {
|
||||
'SU': 'Sunday', 'MO': 'Monday', 'TU': 'Tuesday', 'WE': 'Wednesday',
|
||||
'TH': 'Thursday', 'FR': 'Friday', 'SA': 'Saturday'
|
||||
}
|
||||
SU: "Sunday",
|
||||
MO: "Monday",
|
||||
TU: "Tuesday",
|
||||
WE: "Wednesday",
|
||||
TH: "Thursday",
|
||||
FR: "Friday",
|
||||
SA: "Saturday",
|
||||
};
|
||||
|
||||
const days = byDay.map(day => {
|
||||
const days = byDay.map((day) => {
|
||||
// Handle numbered days like "2TU" (second Tuesday)
|
||||
const match = day.match(/^(-?\d+)?([A-Z]{2})$/)
|
||||
const match = day.match(/^(-?\d+)?([A-Z]{2})$/);
|
||||
if (match) {
|
||||
const [, num, dayCode] = match
|
||||
const dayName = dayNames[dayCode as keyof typeof dayNames]
|
||||
const [, num, dayCode] = match;
|
||||
const dayName = dayNames[dayCode as keyof typeof dayNames];
|
||||
if (num) {
|
||||
const ordinal = getOrdinal(parseInt(num))
|
||||
return `${ordinal} ${dayName}`
|
||||
const ordinal = getOrdinal(parseInt(num));
|
||||
return `${ordinal} ${dayName}`;
|
||||
}
|
||||
return dayName
|
||||
return dayName;
|
||||
}
|
||||
return day
|
||||
})
|
||||
return day;
|
||||
});
|
||||
|
||||
if (freq === 'WEEKLY') {
|
||||
text += ` on ${formatList(days)}`
|
||||
if (freq === "WEEKLY") {
|
||||
text += ` on ${formatList(days)}`;
|
||||
} else {
|
||||
text += ` on ${formatList(days)}`
|
||||
text += ` on ${formatList(days)}`;
|
||||
}
|
||||
}
|
||||
|
||||
// Add month day specifications
|
||||
if (byMonthDay?.length) {
|
||||
const days = byMonthDay.map(day => {
|
||||
const days = byMonthDay.map((day) => {
|
||||
if (day < 0) {
|
||||
return `${getOrdinal(Math.abs(day))} to last day`
|
||||
return `${getOrdinal(Math.abs(day))} to last day`;
|
||||
}
|
||||
return getOrdinal(day)
|
||||
})
|
||||
text += ` on the ${formatList(days)}`
|
||||
return getOrdinal(day);
|
||||
});
|
||||
text += ` on the ${formatList(days)}`;
|
||||
}
|
||||
|
||||
// Add month specifications
|
||||
if (byMonth?.length) {
|
||||
const monthNames = [
|
||||
'January', 'February', 'March', 'April', 'May', 'June',
|
||||
'July', 'August', 'September', 'October', 'November', 'December'
|
||||
]
|
||||
const months = byMonth.map(month => monthNames[month - 1])
|
||||
text += ` in ${formatList(months)}`
|
||||
"January",
|
||||
"February",
|
||||
"March",
|
||||
"April",
|
||||
"May",
|
||||
"June",
|
||||
"July",
|
||||
"August",
|
||||
"September",
|
||||
"October",
|
||||
"November",
|
||||
"December",
|
||||
];
|
||||
const months = byMonth.map((month) => monthNames[month - 1]);
|
||||
text += ` in ${formatList(months)}`;
|
||||
}
|
||||
|
||||
// Add time specifications
|
||||
if (byHour?.length || byMinute?.length || bySecond?.length) {
|
||||
const timeSpecs = []
|
||||
const timeSpecs = [];
|
||||
if (byHour?.length) {
|
||||
const hours = byHour.map(h => `${h.toString().padStart(2, '0')}:00`)
|
||||
timeSpecs.push(`at ${formatList(hours)}`)
|
||||
const hours = byHour.map((h) => `${h.toString().padStart(2, "0")}:00`);
|
||||
timeSpecs.push(`at ${formatList(hours)}`);
|
||||
}
|
||||
if (byMinute?.length && !byHour?.length) {
|
||||
timeSpecs.push(`at minute ${formatList(byMinute.map(String))}`)
|
||||
timeSpecs.push(`at minute ${formatList(byMinute.map(String))}`);
|
||||
}
|
||||
if (bySecond?.length && !byHour?.length && !byMinute?.length) {
|
||||
timeSpecs.push(`at second ${formatList(bySecond.map(String))}`)
|
||||
timeSpecs.push(`at second ${formatList(bySecond.map(String))}`);
|
||||
}
|
||||
if (timeSpecs.length) {
|
||||
text += ` ${timeSpecs.join(' ')}`
|
||||
text += ` ${timeSpecs.join(" ")}`;
|
||||
}
|
||||
}
|
||||
|
||||
// Add end conditions
|
||||
if (count) {
|
||||
text += `, ${count} time${count === 1 ? '' : 's'}`
|
||||
text += `, ${count} time${count === 1 ? "" : "s"}`;
|
||||
} else if (until) {
|
||||
const date = new Date(until)
|
||||
text += `, until ${date.toLocaleDateString()}`
|
||||
const date = new Date(until);
|
||||
text += `, until ${date.toLocaleDateString()}`;
|
||||
}
|
||||
|
||||
return text
|
||||
return text;
|
||||
}
|
||||
|
||||
function getRRuleDetails(rule: RecurrenceRule): string[] {
|
||||
const details: string[] = []
|
||||
const details: string[] = [];
|
||||
|
||||
if (rule.wkst && rule.wkst !== 'MO') {
|
||||
if (rule.wkst && rule.wkst !== "MO") {
|
||||
const dayNames = {
|
||||
'SU': 'Sunday', 'MO': 'Monday', 'TU': 'Tuesday', 'WE': 'Wednesday',
|
||||
'TH': 'Thursday', 'FR': 'Friday', 'SA': 'Saturday'
|
||||
}
|
||||
details.push(`Week starts ${dayNames[rule.wkst]}`)
|
||||
SU: "Sunday",
|
||||
MO: "Monday",
|
||||
TU: "Tuesday",
|
||||
WE: "Wednesday",
|
||||
TH: "Thursday",
|
||||
FR: "Friday",
|
||||
SA: "Saturday",
|
||||
};
|
||||
details.push(`Week starts ${dayNames[rule.wkst]}`);
|
||||
}
|
||||
|
||||
if (rule.byWeekNo?.length) {
|
||||
details.push(`Week ${formatList(rule.byWeekNo.map(String))}`)
|
||||
details.push(`Week ${formatList(rule.byWeekNo.map(String))}`);
|
||||
}
|
||||
|
||||
if (rule.byYearDay?.length) {
|
||||
details.push(`Day ${formatList(rule.byYearDay.map(String))} of year`)
|
||||
details.push(`Day ${formatList(rule.byYearDay.map(String))} of year`);
|
||||
}
|
||||
|
||||
if (rule.bySetPos?.length) {
|
||||
const positions = rule.bySetPos.map(pos => {
|
||||
const positions = rule.bySetPos.map((pos) => {
|
||||
if (pos < 0) {
|
||||
return `${getOrdinal(Math.abs(pos))} to last`
|
||||
return `${getOrdinal(Math.abs(pos))} to last`;
|
||||
}
|
||||
return getOrdinal(pos)
|
||||
})
|
||||
details.push(`Position ${formatList(positions)}`)
|
||||
return getOrdinal(pos);
|
||||
});
|
||||
details.push(`Position ${formatList(positions)}`);
|
||||
}
|
||||
|
||||
return details
|
||||
return details;
|
||||
}
|
||||
|
||||
function getOrdinal(num: number): string {
|
||||
const suffix = ['th', 'st', 'nd', 'rd']
|
||||
const v = num % 100
|
||||
return num + (suffix[(v - 20) % 10] || suffix[v] || suffix[0])
|
||||
const suffix = ["th", "st", "nd", "rd"];
|
||||
const v = num % 100;
|
||||
return num + (suffix[(v - 20) % 10] || suffix[v] || suffix[0]);
|
||||
}
|
||||
|
||||
function formatList(items: string[]): string {
|
||||
if (items.length === 0) return ''
|
||||
if (items.length === 1) return items[0]
|
||||
if (items.length === 2) return `${items[0]} and ${items[1]}`
|
||||
return `${items.slice(0, -1).join(', ')}, and ${items[items.length - 1]}`
|
||||
if (items.length === 0) return "";
|
||||
if (items.length === 1) return items[0];
|
||||
if (items.length === 2) return `${items[0]} and ${items[1]}`;
|
||||
return `${items.slice(0, -1).join(", ")}, and ${items[items.length - 1]}`;
|
||||
}
|
||||
|
||||
// Hook for easy usage in components
|
||||
export function useRRuleDisplay(rrule?: string) {
|
||||
if (!rrule) return null
|
||||
if (!rrule) return null;
|
||||
|
||||
try {
|
||||
const parsedRule = parseRRuleString(rrule)
|
||||
const parsedRule = parseRRuleString(rrule);
|
||||
return {
|
||||
humanText: formatRRuleToHuman(parsedRule),
|
||||
details: getRRuleDetails(parsedRule),
|
||||
parsedRule
|
||||
}
|
||||
parsedRule,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
humanText: "Invalid recurrence rule",
|
||||
details: [],
|
||||
parsedRule: null,
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
}
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,25 +1,25 @@
|
||||
"use client"
|
||||
"use client";
|
||||
|
||||
import { signOut, useSession } from "@/lib/auth-client"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { toast } from "sonner"
|
||||
import { signOut, useSession } from "@/lib/auth-client";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { toast } from "sonner";
|
||||
|
||||
export default function SignIn() {
|
||||
const { data: session, isPending } = useSession()
|
||||
const router = useRouter()
|
||||
const { data: session, isPending } = useSession();
|
||||
const router = useRouter();
|
||||
|
||||
const handleSignOut = async () => {
|
||||
try {
|
||||
await signOut()
|
||||
router.push("/")
|
||||
await signOut();
|
||||
router.push("/");
|
||||
} catch (_error) {
|
||||
toast.error("Failed to sign out. Please try again.")
|
||||
}
|
||||
toast.error("Failed to sign out. Please try again.");
|
||||
}
|
||||
};
|
||||
|
||||
if (isPending) {
|
||||
return <div className="h-8 w-16 bg-muted animate-pulse rounded"></div>
|
||||
return <div className="h-8 w-16 bg-muted animate-pulse rounded"></div>;
|
||||
}
|
||||
|
||||
if (session?.user) {
|
||||
@@ -29,7 +29,7 @@ export default function SignIn() {
|
||||
Sign Out
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -40,5 +40,5 @@ export default function SignIn() {
|
||||
>
|
||||
Sign In
|
||||
</Button>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
"use client"
|
||||
"use client";
|
||||
|
||||
import * as React from "react"
|
||||
import { ThemeProvider as NextThemesProvider } from "next-themes"
|
||||
import * as React from "react";
|
||||
import { ThemeProvider as NextThemesProvider } from "next-themes";
|
||||
|
||||
export function ThemeProvider({
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof NextThemesProvider>) {
|
||||
return <NextThemesProvider {...props}>{children}</NextThemesProvider>
|
||||
return <NextThemesProvider {...props}>{children}</NextThemesProvider>;
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import * as React from "react"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import * as React from "react";
|
||||
import { Slot } from "@radix-ui/react-slot";
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const badgeVariants = cva(
|
||||
"inline-flex items-center justify-center rounded-md border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",
|
||||
@@ -22,8 +22,8 @@ const badgeVariants = cva(
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
},
|
||||
);
|
||||
|
||||
function Badge({
|
||||
className,
|
||||
@@ -32,7 +32,7 @@ function Badge({
|
||||
...props
|
||||
}: React.ComponentProps<"span"> &
|
||||
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
|
||||
const Comp = asChild ? Slot : "span"
|
||||
const Comp = asChild ? Slot : "span";
|
||||
|
||||
return (
|
||||
<Comp
|
||||
@@ -40,7 +40,7 @@ function Badge({
|
||||
className={cn(badgeVariants({ variant }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export { Badge, badgeVariants }
|
||||
export { Badge, badgeVariants };
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import * as React from "react"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import * as React from "react";
|
||||
import { Slot } from "@radix-ui/react-slot";
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const buttonVariants = cva(
|
||||
"active:scale-[.95] inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium duration-100 transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||
@@ -32,8 +32,8 @@ const buttonVariants = cva(
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
},
|
||||
);
|
||||
|
||||
function Button({
|
||||
className,
|
||||
@@ -43,9 +43,9 @@ function Button({
|
||||
...props
|
||||
}: React.ComponentProps<"button"> &
|
||||
VariantProps<typeof buttonVariants> & {
|
||||
asChild?: boolean
|
||||
asChild?: boolean;
|
||||
}) {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
const Comp = asChild ? Slot : "button";
|
||||
|
||||
return (
|
||||
<Comp
|
||||
@@ -53,7 +53,7 @@ function Button({
|
||||
className={cn(buttonVariants({ variant, size, className }))}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export { Button, buttonVariants }
|
||||
export { Button, buttonVariants };
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
"use client"
|
||||
"use client";
|
||||
|
||||
import * as React from "react"
|
||||
import * as React from "react";
|
||||
import {
|
||||
ChevronDownIcon,
|
||||
ChevronLeftIcon,
|
||||
ChevronRightIcon,
|
||||
} from "lucide-react"
|
||||
import { DayButton, DayPicker, getDefaultClassNames } from "react-day-picker"
|
||||
} from "lucide-react";
|
||||
import { DayButton, DayPicker, getDefaultClassNames } from "react-day-picker";
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Button, buttonVariants } from "@/components/ui/button"
|
||||
import { cn } from "@/lib/utils";
|
||||
import { Button, buttonVariants } from "@/components/ui/button";
|
||||
|
||||
function Calendar({
|
||||
className,
|
||||
@@ -21,9 +21,9 @@ function Calendar({
|
||||
components,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DayPicker> & {
|
||||
buttonVariant?: React.ComponentProps<typeof Button>["variant"]
|
||||
buttonVariant?: React.ComponentProps<typeof Button>["variant"];
|
||||
}) {
|
||||
const defaultClassNames = getDefaultClassNames()
|
||||
const defaultClassNames = getDefaultClassNames();
|
||||
|
||||
return (
|
||||
<DayPicker
|
||||
@@ -32,7 +32,7 @@ function Calendar({
|
||||
"bg-background group/calendar p-3 [--cell-size:--spacing(8)] [[data-slot=card-content]_&]:bg-transparent [[data-slot=popover-content]_&]:bg-transparent",
|
||||
String.raw`rtl:**:[.rdp-button\_next>svg]:rotate-180`,
|
||||
String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`,
|
||||
className
|
||||
className,
|
||||
)}
|
||||
captionLayout={captionLayout}
|
||||
formatters={{
|
||||
@@ -44,82 +44,82 @@ function Calendar({
|
||||
root: cn("w-fit", defaultClassNames.root),
|
||||
months: cn(
|
||||
"flex gap-4 flex-col md:flex-row relative",
|
||||
defaultClassNames.months
|
||||
defaultClassNames.months,
|
||||
),
|
||||
month: cn("flex flex-col w-full gap-4", defaultClassNames.month),
|
||||
nav: cn(
|
||||
"flex items-center gap-1 w-full absolute top-0 inset-x-0 justify-between",
|
||||
defaultClassNames.nav
|
||||
defaultClassNames.nav,
|
||||
),
|
||||
button_previous: cn(
|
||||
buttonVariants({ variant: buttonVariant }),
|
||||
"size-(--cell-size) aria-disabled:opacity-50 p-0 select-none",
|
||||
defaultClassNames.button_previous
|
||||
defaultClassNames.button_previous,
|
||||
),
|
||||
button_next: cn(
|
||||
buttonVariants({ variant: buttonVariant }),
|
||||
"size-(--cell-size) aria-disabled:opacity-50 p-0 select-none",
|
||||
defaultClassNames.button_next
|
||||
defaultClassNames.button_next,
|
||||
),
|
||||
month_caption: cn(
|
||||
"flex items-center justify-center h-(--cell-size) w-full px-(--cell-size)",
|
||||
defaultClassNames.month_caption
|
||||
defaultClassNames.month_caption,
|
||||
),
|
||||
dropdowns: cn(
|
||||
"w-full flex items-center text-sm font-medium justify-center h-(--cell-size) gap-1.5",
|
||||
defaultClassNames.dropdowns
|
||||
defaultClassNames.dropdowns,
|
||||
),
|
||||
dropdown_root: cn(
|
||||
"relative has-focus:border-ring border border-input shadow-xs has-focus:ring-ring/50 has-focus:ring-[3px] rounded-md",
|
||||
defaultClassNames.dropdown_root
|
||||
defaultClassNames.dropdown_root,
|
||||
),
|
||||
dropdown: cn(
|
||||
"absolute bg-popover inset-0 opacity-0",
|
||||
defaultClassNames.dropdown
|
||||
defaultClassNames.dropdown,
|
||||
),
|
||||
caption_label: cn(
|
||||
"select-none font-medium",
|
||||
captionLayout === "label"
|
||||
? "text-sm"
|
||||
: "rounded-md pl-2 pr-1 flex items-center gap-1 text-sm h-8 [&>svg]:text-muted-foreground [&>svg]:size-3.5",
|
||||
defaultClassNames.caption_label
|
||||
defaultClassNames.caption_label,
|
||||
),
|
||||
table: "w-full border-collapse",
|
||||
weekdays: cn("flex", defaultClassNames.weekdays),
|
||||
weekday: cn(
|
||||
"text-muted-foreground rounded-md flex-1 font-normal text-[0.8rem] select-none",
|
||||
defaultClassNames.weekday
|
||||
defaultClassNames.weekday,
|
||||
),
|
||||
week: cn("flex w-full mt-2", defaultClassNames.week),
|
||||
week_number_header: cn(
|
||||
"select-none w-(--cell-size)",
|
||||
defaultClassNames.week_number_header
|
||||
defaultClassNames.week_number_header,
|
||||
),
|
||||
week_number: cn(
|
||||
"text-[0.8rem] select-none text-muted-foreground",
|
||||
defaultClassNames.week_number
|
||||
defaultClassNames.week_number,
|
||||
),
|
||||
day: cn(
|
||||
"relative w-full h-full p-0 text-center [&:first-child[data-selected=true]_button]:rounded-l-md [&:last-child[data-selected=true]_button]:rounded-r-md group/day aspect-square select-none",
|
||||
defaultClassNames.day
|
||||
defaultClassNames.day,
|
||||
),
|
||||
range_start: cn(
|
||||
"rounded-l-md bg-accent",
|
||||
defaultClassNames.range_start
|
||||
defaultClassNames.range_start,
|
||||
),
|
||||
range_middle: cn("rounded-none", defaultClassNames.range_middle),
|
||||
range_end: cn("rounded-r-md bg-accent", defaultClassNames.range_end),
|
||||
today: cn(
|
||||
"bg-accent text-accent-foreground rounded-md data-[selected=true]:rounded-none",
|
||||
defaultClassNames.today
|
||||
defaultClassNames.today,
|
||||
),
|
||||
outside: cn(
|
||||
"text-muted-foreground aria-selected:text-muted-foreground",
|
||||
defaultClassNames.outside
|
||||
defaultClassNames.outside,
|
||||
),
|
||||
disabled: cn(
|
||||
"text-muted-foreground opacity-50",
|
||||
defaultClassNames.disabled
|
||||
defaultClassNames.disabled,
|
||||
),
|
||||
hidden: cn("invisible", defaultClassNames.hidden),
|
||||
...classNames,
|
||||
@@ -133,13 +133,13 @@ function Calendar({
|
||||
className={cn(className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
},
|
||||
Chevron: ({ className, orientation, ...props }) => {
|
||||
if (orientation === "left") {
|
||||
return (
|
||||
<ChevronLeftIcon className={cn("size-4", className)} {...props} />
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (orientation === "right") {
|
||||
@@ -148,12 +148,12 @@ function Calendar({
|
||||
className={cn("size-4", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<ChevronDownIcon className={cn("size-4", className)} {...props} />
|
||||
)
|
||||
);
|
||||
},
|
||||
DayButton: CalendarDayButton,
|
||||
WeekNumber: ({ children, ...props }) => {
|
||||
@@ -163,13 +163,13 @@ function Calendar({
|
||||
{children}
|
||||
</div>
|
||||
</td>
|
||||
)
|
||||
);
|
||||
},
|
||||
...components,
|
||||
}}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function CalendarDayButton({
|
||||
@@ -178,12 +178,12 @@ function CalendarDayButton({
|
||||
modifiers,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DayButton>) {
|
||||
const defaultClassNames = getDefaultClassNames()
|
||||
const defaultClassNames = getDefaultClassNames();
|
||||
|
||||
const ref = React.useRef<HTMLButtonElement>(null)
|
||||
const ref = React.useRef<HTMLButtonElement>(null);
|
||||
React.useEffect(() => {
|
||||
if (modifiers.focused) ref.current?.focus()
|
||||
}, [modifiers.focused])
|
||||
if (modifiers.focused) ref.current?.focus();
|
||||
}, [modifiers.focused]);
|
||||
|
||||
return (
|
||||
<Button
|
||||
@@ -203,11 +203,11 @@ function CalendarDayButton({
|
||||
className={cn(
|
||||
"data-[selected-single=true]:bg-primary data-[selected-single=true]:text-primary-foreground data-[range-middle=true]:bg-accent data-[range-middle=true]:text-accent-foreground data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-ring/50 dark:hover:text-accent-foreground flex aspect-square size-auto w-full min-w-(--cell-size) flex-col gap-1 leading-none font-normal group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:ring-[3px] data-[range-end=true]:rounded-md data-[range-end=true]:rounded-r-md data-[range-middle=true]:rounded-none data-[range-start=true]:rounded-md data-[range-start=true]:rounded-l-md [&>span]:text-xs [&>span]:opacity-70",
|
||||
defaultClassNames.day,
|
||||
className
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export { Calendar, CalendarDayButton }
|
||||
export { Calendar, CalendarDayButton };
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import * as React from "react"
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
function Card({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
@@ -8,11 +8,11 @@ function Card({ className, ...props }: React.ComponentProps<"div">) {
|
||||
data-slot="card"
|
||||
className={cn(
|
||||
"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",
|
||||
className
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
@@ -21,11 +21,11 @@ function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
data-slot="card-header"
|
||||
className={cn(
|
||||
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
|
||||
className
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||
@@ -35,7 +35,7 @@ function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||
className={cn("leading-none font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
|
||||
@@ -45,7 +45,7 @@ function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
|
||||
@@ -54,11 +54,11 @@ function CardAction({ className, ...props }: React.ComponentProps<"div">) {
|
||||
data-slot="card-action"
|
||||
className={cn(
|
||||
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
|
||||
className
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
@@ -68,7 +68,7 @@ function CardContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
className={cn("px-6", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
@@ -78,7 +78,7 @@ function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
@@ -89,4 +89,4 @@ export {
|
||||
CardAction,
|
||||
CardDescription,
|
||||
CardContent,
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
"use client"
|
||||
"use client";
|
||||
|
||||
import * as React from "react"
|
||||
import * as CheckboxPrimitive from "@radix-ui/react-checkbox"
|
||||
import { CheckIcon } from "lucide-react"
|
||||
import * as React from "react";
|
||||
import * as CheckboxPrimitive from "@radix-ui/react-checkbox";
|
||||
import { CheckIcon } from "lucide-react";
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
function Checkbox({
|
||||
className,
|
||||
@@ -15,7 +15,7 @@ function Checkbox({
|
||||
data-slot="checkbox"
|
||||
className={cn(
|
||||
"peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
@@ -26,7 +26,7 @@ function Checkbox({
|
||||
<CheckIcon className="size-3.5" />
|
||||
</CheckboxPrimitive.Indicator>
|
||||
</CheckboxPrimitive.Root>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export { Checkbox }
|
||||
export { Checkbox };
|
||||
|
||||
@@ -1,33 +1,33 @@
|
||||
"use client"
|
||||
"use client";
|
||||
|
||||
import * as React from "react"
|
||||
import * as DialogPrimitive from "@radix-ui/react-dialog"
|
||||
import { XIcon } from "lucide-react"
|
||||
import * as React from "react";
|
||||
import * as DialogPrimitive from "@radix-ui/react-dialog";
|
||||
import { XIcon } from "lucide-react";
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
function Dialog({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
|
||||
return <DialogPrimitive.Root data-slot="dialog" {...props} />
|
||||
return <DialogPrimitive.Root data-slot="dialog" {...props} />;
|
||||
}
|
||||
|
||||
function DialogTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
|
||||
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
|
||||
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />;
|
||||
}
|
||||
|
||||
function DialogPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
|
||||
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
|
||||
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />;
|
||||
}
|
||||
|
||||
function DialogClose({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
|
||||
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
|
||||
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />;
|
||||
}
|
||||
|
||||
function DialogOverlay({
|
||||
@@ -39,11 +39,11 @@ function DialogOverlay({
|
||||
data-slot="dialog-overlay"
|
||||
className={cn(
|
||||
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
|
||||
className
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function DialogContent({
|
||||
@@ -52,7 +52,7 @@ function DialogContent({
|
||||
showCloseButton = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
|
||||
showCloseButton?: boolean
|
||||
showCloseButton?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<DialogPortal data-slot="dialog-portal">
|
||||
@@ -61,7 +61,7 @@ function DialogContent({
|
||||
data-slot="dialog-content"
|
||||
className={cn(
|
||||
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
|
||||
className
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
@@ -77,7 +77,7 @@ function DialogContent({
|
||||
)}
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPortal>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
@@ -87,7 +87,7 @@ function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
@@ -96,11 +96,11 @@ function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
data-slot="dialog-footer"
|
||||
className={cn(
|
||||
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
|
||||
className
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function DialogTitle({
|
||||
@@ -113,7 +113,7 @@ function DialogTitle({
|
||||
className={cn("text-lg leading-none font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function DialogDescription({
|
||||
@@ -126,7 +126,7 @@ function DialogDescription({
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
@@ -140,4 +140,4 @@ export {
|
||||
DialogPortal,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
"use client"
|
||||
"use client";
|
||||
|
||||
import * as React from "react"
|
||||
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"
|
||||
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
|
||||
import * as React from "react";
|
||||
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu";
|
||||
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react";
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
function DropdownMenu({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
|
||||
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />
|
||||
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />;
|
||||
}
|
||||
|
||||
function DropdownMenuPortal({
|
||||
@@ -17,7 +17,7 @@ function DropdownMenuPortal({
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuTrigger({
|
||||
@@ -28,7 +28,7 @@ function DropdownMenuTrigger({
|
||||
data-slot="dropdown-menu-trigger"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuContent({
|
||||
@@ -43,12 +43,12 @@ function DropdownMenuContent({
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",
|
||||
className
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</DropdownMenuPrimitive.Portal>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuGroup({
|
||||
@@ -56,7 +56,7 @@ function DropdownMenuGroup({
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuItem({
|
||||
@@ -65,8 +65,8 @@ function DropdownMenuItem({
|
||||
variant = "default",
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
|
||||
inset?: boolean
|
||||
variant?: "default" | "destructive"
|
||||
inset?: boolean;
|
||||
variant?: "default" | "destructive";
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Item
|
||||
@@ -75,11 +75,11 @@ function DropdownMenuItem({
|
||||
data-variant={variant}
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuCheckboxItem({
|
||||
@@ -93,7 +93,7 @@ function DropdownMenuCheckboxItem({
|
||||
data-slot="dropdown-menu-checkbox-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
className,
|
||||
)}
|
||||
checked={checked}
|
||||
{...props}
|
||||
@@ -105,7 +105,7 @@ function DropdownMenuCheckboxItem({
|
||||
</span>
|
||||
{children}
|
||||
</DropdownMenuPrimitive.CheckboxItem>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuRadioGroup({
|
||||
@@ -116,7 +116,7 @@ function DropdownMenuRadioGroup({
|
||||
data-slot="dropdown-menu-radio-group"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuRadioItem({
|
||||
@@ -129,7 +129,7 @@ function DropdownMenuRadioItem({
|
||||
data-slot="dropdown-menu-radio-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
@@ -140,7 +140,7 @@ function DropdownMenuRadioItem({
|
||||
</span>
|
||||
{children}
|
||||
</DropdownMenuPrimitive.RadioItem>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuLabel({
|
||||
@@ -148,7 +148,7 @@ function DropdownMenuLabel({
|
||||
inset,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
|
||||
inset?: boolean
|
||||
inset?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Label
|
||||
@@ -156,11 +156,11 @@ function DropdownMenuLabel({
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
|
||||
className
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuSeparator({
|
||||
@@ -173,7 +173,7 @@ function DropdownMenuSeparator({
|
||||
className={cn("bg-border -mx-1 my-1 h-px", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuShortcut({
|
||||
@@ -185,17 +185,17 @@ function DropdownMenuShortcut({
|
||||
data-slot="dropdown-menu-shortcut"
|
||||
className={cn(
|
||||
"text-muted-foreground ml-auto text-xs tracking-widest",
|
||||
className
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuSub({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
|
||||
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />
|
||||
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />;
|
||||
}
|
||||
|
||||
function DropdownMenuSubTrigger({
|
||||
@@ -204,7 +204,7 @@ function DropdownMenuSubTrigger({
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
|
||||
inset?: boolean
|
||||
inset?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.SubTrigger
|
||||
@@ -212,14 +212,14 @@ function DropdownMenuSubTrigger({
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8",
|
||||
className
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronRightIcon className="ml-auto size-4" />
|
||||
</DropdownMenuPrimitive.SubTrigger>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuSubContent({
|
||||
@@ -231,11 +231,11 @@ function DropdownMenuSubContent({
|
||||
data-slot="dropdown-menu-sub-content"
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
|
||||
className
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
@@ -254,4 +254,4 @@ export {
|
||||
DropdownMenuSub,
|
||||
DropdownMenuSubTrigger,
|
||||
DropdownMenuSubContent,
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import * as React from "react"
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
|
||||
return (
|
||||
@@ -11,11 +11,11 @@ function Input({ className, type, ...props }: React.ComponentProps<"input">) {
|
||||
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
|
||||
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||
className
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export { Input }
|
||||
export { Input };
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"use client"
|
||||
"use client";
|
||||
|
||||
import * as React from "react"
|
||||
import * as LabelPrimitive from "@radix-ui/react-label"
|
||||
import * as React from "react";
|
||||
import * as LabelPrimitive from "@radix-ui/react-label";
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
function Label({
|
||||
className,
|
||||
@@ -14,11 +14,11 @@ function Label({
|
||||
data-slot="label"
|
||||
className={cn(
|
||||
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
|
||||
className
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export { Label }
|
||||
export { Label };
|
||||
|
||||
@@ -1,27 +1,27 @@
|
||||
"use client"
|
||||
"use client";
|
||||
|
||||
import * as React from "react"
|
||||
import * as SelectPrimitive from "@radix-ui/react-select"
|
||||
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react"
|
||||
import * as React from "react";
|
||||
import * as SelectPrimitive from "@radix-ui/react-select";
|
||||
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react";
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
function Select({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Root>) {
|
||||
return <SelectPrimitive.Root data-slot="select" {...props} />
|
||||
return <SelectPrimitive.Root data-slot="select" {...props} />;
|
||||
}
|
||||
|
||||
function SelectGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Group>) {
|
||||
return <SelectPrimitive.Group data-slot="select-group" {...props} />
|
||||
return <SelectPrimitive.Group data-slot="select-group" {...props} />;
|
||||
}
|
||||
|
||||
function SelectValue({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Value>) {
|
||||
return <SelectPrimitive.Value data-slot="select-value" {...props} />
|
||||
return <SelectPrimitive.Value data-slot="select-value" {...props} />;
|
||||
}
|
||||
|
||||
function SelectTrigger({
|
||||
@@ -30,7 +30,7 @@ function SelectTrigger({
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
|
||||
size?: "sm" | "default"
|
||||
size?: "sm" | "default";
|
||||
}) {
|
||||
return (
|
||||
<SelectPrimitive.Trigger
|
||||
@@ -38,7 +38,7 @@ function SelectTrigger({
|
||||
data-size={size}
|
||||
className={cn(
|
||||
"border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
@@ -47,7 +47,7 @@ function SelectTrigger({
|
||||
<ChevronDownIcon className="size-4 opacity-50" />
|
||||
</SelectPrimitive.Icon>
|
||||
</SelectPrimitive.Trigger>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function SelectContent({
|
||||
@@ -64,7 +64,7 @@ function SelectContent({
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",
|
||||
position === "popper" &&
|
||||
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
|
||||
className
|
||||
className,
|
||||
)}
|
||||
position={position}
|
||||
{...props}
|
||||
@@ -74,7 +74,7 @@ function SelectContent({
|
||||
className={cn(
|
||||
"p-1",
|
||||
position === "popper" &&
|
||||
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"
|
||||
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1",
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
@@ -82,7 +82,7 @@ function SelectContent({
|
||||
<SelectScrollDownButton />
|
||||
</SelectPrimitive.Content>
|
||||
</SelectPrimitive.Portal>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function SelectLabel({
|
||||
@@ -95,7 +95,7 @@ function SelectLabel({
|
||||
className={cn("text-muted-foreground px-2 py-1.5 text-xs", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function SelectItem({
|
||||
@@ -108,7 +108,7 @@ function SelectItem({
|
||||
data-slot="select-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
|
||||
className
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
@@ -119,7 +119,7 @@ function SelectItem({
|
||||
</span>
|
||||
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
|
||||
</SelectPrimitive.Item>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function SelectSeparator({
|
||||
@@ -132,7 +132,7 @@ function SelectSeparator({
|
||||
className={cn("bg-border pointer-events-none -mx-1 my-1 h-px", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function SelectScrollUpButton({
|
||||
@@ -144,13 +144,13 @@ function SelectScrollUpButton({
|
||||
data-slot="select-scroll-up-button"
|
||||
className={cn(
|
||||
"flex cursor-default items-center justify-center py-1",
|
||||
className
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronUpIcon className="size-4" />
|
||||
</SelectPrimitive.ScrollUpButton>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function SelectScrollDownButton({
|
||||
@@ -162,13 +162,13 @@ function SelectScrollDownButton({
|
||||
data-slot="select-scroll-down-button"
|
||||
className={cn(
|
||||
"flex cursor-default items-center justify-center py-1",
|
||||
className
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronDownIcon className="size-4" />
|
||||
</SelectPrimitive.ScrollDownButton>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
@@ -182,4 +182,4 @@ export {
|
||||
SelectSeparator,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
"use client"
|
||||
"use client";
|
||||
|
||||
import { useTheme } from "next-themes"
|
||||
import { Toaster as Sonner, ToasterProps } from "sonner"
|
||||
import { useTheme } from "next-themes";
|
||||
import { Toaster as Sonner, ToasterProps } from "sonner";
|
||||
|
||||
const Toaster = ({ ...props }: ToasterProps) => {
|
||||
const { theme = "system" } = useTheme()
|
||||
const { theme = "system" } = useTheme();
|
||||
|
||||
return (
|
||||
<Sonner
|
||||
@@ -19,7 +19,7 @@ const Toaster = ({ ...props }: ToasterProps) => {
|
||||
}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
export { Toaster }
|
||||
export { Toaster };
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import * as React from "react"
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
|
||||
return (
|
||||
@@ -8,11 +8,11 @@ function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
|
||||
data-slot="textarea"
|
||||
className={cn(
|
||||
"border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
className
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export { Textarea }
|
||||
export { Textarea };
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { drizzle } from 'drizzle-orm/postgres-js';
|
||||
import postgres from 'postgres';
|
||||
import * as schema from './schema';
|
||||
import { drizzle } from "drizzle-orm/postgres-js";
|
||||
import postgres from "postgres";
|
||||
import * as schema from "./schema";
|
||||
|
||||
const connectionString = process.env.DATABASE_URL!;
|
||||
|
||||
|
||||
@@ -1,47 +1,51 @@
|
||||
import { pgTable, text, timestamp, boolean } from 'drizzle-orm/pg-core';
|
||||
import { pgTable, text, timestamp, boolean } from "drizzle-orm/pg-core";
|
||||
|
||||
export const user = pgTable('user', {
|
||||
id: text('id').primaryKey(),
|
||||
name: text('name'),
|
||||
email: text('email').notNull().unique(),
|
||||
emailVerified: boolean('emailVerified').default(false),
|
||||
image: text('image'),
|
||||
createdAt: timestamp('createdAt').defaultNow(),
|
||||
updatedAt: timestamp('updatedAt').defaultNow(),
|
||||
export const user = pgTable("user", {
|
||||
id: text("id").primaryKey(),
|
||||
name: text("name"),
|
||||
email: text("email").notNull().unique(),
|
||||
emailVerified: boolean("emailVerified").default(false),
|
||||
image: text("image"),
|
||||
createdAt: timestamp("createdAt").defaultNow(),
|
||||
updatedAt: timestamp("updatedAt").defaultNow(),
|
||||
});
|
||||
|
||||
export const session = pgTable('session', {
|
||||
id: text('id').primaryKey(),
|
||||
expiresAt: timestamp('expiresAt').notNull(),
|
||||
token: text('token').notNull().unique(),
|
||||
createdAt: timestamp('createdAt').defaultNow(),
|
||||
updatedAt: timestamp('updatedAt').defaultNow(),
|
||||
ipAddress: text('ipAddress'),
|
||||
userAgent: text('userAgent'),
|
||||
userId: text('userId').notNull().references(() => user.id, { onDelete: 'cascade' }),
|
||||
export const session = pgTable("session", {
|
||||
id: text("id").primaryKey(),
|
||||
expiresAt: timestamp("expiresAt").notNull(),
|
||||
token: text("token").notNull().unique(),
|
||||
createdAt: timestamp("createdAt").defaultNow(),
|
||||
updatedAt: timestamp("updatedAt").defaultNow(),
|
||||
ipAddress: text("ipAddress"),
|
||||
userAgent: text("userAgent"),
|
||||
userId: text("userId")
|
||||
.notNull()
|
||||
.references(() => user.id, { onDelete: "cascade" }),
|
||||
});
|
||||
|
||||
export const account = pgTable('account', {
|
||||
id: text('id').primaryKey(),
|
||||
accountId: text('accountId').notNull(),
|
||||
providerId: text('providerId').notNull(),
|
||||
userId: text('userId').notNull().references(() => user.id, { onDelete: 'cascade' }),
|
||||
accessToken: text('accessToken'),
|
||||
refreshToken: text('refreshToken'),
|
||||
accessTokenExpiresAt: timestamp('accessTokenExpiresAt'),
|
||||
refreshTokenExpiresAt: timestamp('refreshTokenExpiresAt'),
|
||||
scope: text('scope'),
|
||||
idToken: text('idToken'),
|
||||
password: text('password'),
|
||||
createdAt: timestamp('createdAt').defaultNow(),
|
||||
updatedAt: timestamp('updatedAt').defaultNow(),
|
||||
export const account = pgTable("account", {
|
||||
id: text("id").primaryKey(),
|
||||
accountId: text("accountId").notNull(),
|
||||
providerId: text("providerId").notNull(),
|
||||
userId: text("userId")
|
||||
.notNull()
|
||||
.references(() => user.id, { onDelete: "cascade" }),
|
||||
accessToken: text("accessToken"),
|
||||
refreshToken: text("refreshToken"),
|
||||
accessTokenExpiresAt: timestamp("accessTokenExpiresAt"),
|
||||
refreshTokenExpiresAt: timestamp("refreshTokenExpiresAt"),
|
||||
scope: text("scope"),
|
||||
idToken: text("idToken"),
|
||||
password: text("password"),
|
||||
createdAt: timestamp("createdAt").defaultNow(),
|
||||
updatedAt: timestamp("updatedAt").defaultNow(),
|
||||
});
|
||||
|
||||
export const verification = pgTable('verification', {
|
||||
id: text('id').primaryKey(),
|
||||
identifier: text('identifier').notNull(),
|
||||
value: text('value').notNull(),
|
||||
expiresAt: timestamp('expiresAt').notNull(),
|
||||
createdAt: timestamp('createdAt').defaultNow(),
|
||||
updatedAt: timestamp('updatedAt').defaultNow(),
|
||||
export const verification = pgTable("verification", {
|
||||
id: text("id").primaryKey(),
|
||||
identifier: text("identifier").notNull(),
|
||||
value: text("value").notNull(),
|
||||
expiresAt: timestamp("expiresAt").notNull(),
|
||||
createdAt: timestamp("createdAt").defaultNow(),
|
||||
updatedAt: timestamp("updatedAt").defaultNow(),
|
||||
});
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { openDB, type IDBPDatabase } from 'idb';
|
||||
import type { CalendarEvent } from '@/lib/types';
|
||||
import { openDB, type IDBPDatabase } from "idb";
|
||||
import type { CalendarEvent } from "@/lib/types";
|
||||
|
||||
const DB_NAME = 'LocalCalEvents';
|
||||
const DB_NAME = "LocalCalEvents";
|
||||
const DB_VERSION = 1;
|
||||
const EVENTS_STORE = 'events';
|
||||
const EVENTS_STORE = "events";
|
||||
|
||||
let dbPromise: Promise<IDBPDatabase> | null = null;
|
||||
|
||||
@@ -12,9 +12,9 @@ function getDB() {
|
||||
dbPromise = openDB(DB_NAME, DB_VERSION, {
|
||||
upgrade(db) {
|
||||
if (!db.objectStoreNames.contains(EVENTS_STORE)) {
|
||||
const store = db.createObjectStore(EVENTS_STORE, { keyPath: 'id' });
|
||||
store.createIndex('start', 'start');
|
||||
store.createIndex('title', 'title');
|
||||
const store = db.createObjectStore(EVENTS_STORE, { keyPath: "id" });
|
||||
store.createIndex("start", "start");
|
||||
store.createIndex("title", "title");
|
||||
}
|
||||
},
|
||||
});
|
||||
@@ -47,10 +47,13 @@ export async function updateEvent(event: CalendarEvent): Promise<void> {
|
||||
await db.put(EVENTS_STORE, event);
|
||||
}
|
||||
|
||||
export async function getEventsByDateRange(startDate: string, endDate: string): Promise<CalendarEvent[]> {
|
||||
export async function getEventsByDateRange(
|
||||
startDate: string,
|
||||
endDate: string,
|
||||
): Promise<CalendarEvent[]> {
|
||||
const db = await getDB();
|
||||
const tx = db.transaction(EVENTS_STORE, 'readonly');
|
||||
const index = tx.store.index('start');
|
||||
const tx = db.transaction(EVENTS_STORE, "readonly");
|
||||
const index = tx.store.index("start");
|
||||
const events = await index.getAll(IDBKeyRange.bound(startDate, endDate));
|
||||
await tx.done;
|
||||
return events;
|
||||
|
||||
9
src/lib/openrouter-client.ts
Normal file
9
src/lib/openrouter-client.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { OpenRouter } from "@openrouter/sdk";
|
||||
|
||||
if (!process.env.OPENROUTER_API_KEY) {
|
||||
throw new Error("OPENROUTER_API_KEY environment variable is not set");
|
||||
}
|
||||
|
||||
export const openRouterClient = new OpenRouter({
|
||||
apiKey: process.env.OPENROUTER_API_KEY,
|
||||
});
|
||||
@@ -1,23 +1,30 @@
|
||||
// RFC 5545 (iCalendar) Recurrence Rule types
|
||||
// Based on the iCalendar specification for RRULE
|
||||
|
||||
export type Frequency = 'SECONDLY' | 'MINUTELY' | 'HOURLY' | 'DAILY' | 'WEEKLY' | 'MONTHLY' | 'YEARLY'
|
||||
export type Frequency =
|
||||
| "SECONDLY"
|
||||
| "MINUTELY"
|
||||
| "HOURLY"
|
||||
| "DAILY"
|
||||
| "WEEKLY"
|
||||
| "MONTHLY"
|
||||
| "YEARLY";
|
||||
|
||||
export type Weekday = 'SU' | 'MO' | 'TU' | 'WE' | 'TH' | 'FR' | 'SA'
|
||||
export type Weekday = "SU" | "MO" | "TU" | "WE" | "TH" | "FR" | "SA";
|
||||
|
||||
export interface RecurrenceRule {
|
||||
freq: Frequency
|
||||
until?: string // ISO 8601 date string
|
||||
count?: number
|
||||
interval?: number
|
||||
bySecond?: number[]
|
||||
byMinute?: number[]
|
||||
byHour?: number[]
|
||||
byDay?: string[]
|
||||
byMonthDay?: number[]
|
||||
byYearDay?: number[]
|
||||
byWeekNo?: number[]
|
||||
byMonth?: number[]
|
||||
bySetPos?: number[]
|
||||
wkst?: Weekday
|
||||
freq: Frequency;
|
||||
until?: string; // ISO 8601 date string
|
||||
count?: number;
|
||||
interval?: number;
|
||||
bySecond?: number[];
|
||||
byMinute?: number[];
|
||||
byHour?: number[];
|
||||
byDay?: string[];
|
||||
byMonthDay?: number[];
|
||||
byYearDay?: number[];
|
||||
byWeekNo?: number[];
|
||||
byMonth?: number[];
|
||||
bySetPos?: number[];
|
||||
wkst?: Weekday;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { clsx, type ClassValue } from "clsx"
|
||||
import { twMerge } from "tailwind-merge"
|
||||
import { clsx, type ClassValue } from "clsx";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs))
|
||||
return twMerge(clsx(inputs));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user