Compare commits

...

18 Commits

Author SHA1 Message Date
b4c03ff25e style(ui): standardize UI component file formatting 2026-04-07 08:10:13 -04:00
fd5716f39e style(components): standardize main component file formatting 2026-04-07 08:10:05 -04:00
954e73c007 style(app): standardize app page file formatting 2026-04-07 08:09:56 -04:00
48ef4f60df style(api): standardize API route file formatting 2026-04-07 08:09:49 -04:00
e39ba6be97 style(lib): standardize utils file formatting 2026-04-07 08:09:43 -04:00
3b7c246a47 style(lib): standardize rfc5545-types file formatting 2026-04-07 08:09:40 -04:00
5be55cec7c style(lib): standardize events-db file formatting 2026-04-07 08:09:36 -04:00
dab77befc2 style(auth): standardize auth file formatting 2026-04-07 08:09:32 -04:00
076cf8acd0 style(db): standardize database source file formatting 2026-04-07 08:09:26 -04:00
ae8d547486 style(public): standardize manifest.json formatting 2026-04-07 08:09:19 -04:00
3d9e2452c4 style(db): standardize database migration file formatting 2026-04-07 08:09:15 -04:00
db9d6399dd style(config): standardize configuration file formatting 2026-04-07 08:09:09 -04:00
a897e8ead1 feat(lib): add OpenRouter client implementation 2026-04-07 08:08:58 -04:00
c3e3018018 feat(deps): add @openrouter/sdk dependency 2026-04-07 08:08:51 -04:00
be389c6cfa style(skills): standardize utility-types.ts formatting 2026-04-07 08:08:44 -04:00
ada8e03a04 chore(config): add OpenRouterTeam to skill selector repos 2026-04-07 08:08:36 -04:00
956de68591 style(skills): standardize skill metadata JSON formatting 2026-04-07 08:08:28 -04:00
e25f917b9a chore(skills): add create-agent and typescript-sdk skills 2026-04-07 08:08:01 -04:00
73 changed files with 5723 additions and 3381 deletions

View 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"
}

View 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

View 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"
]
}

View File

@@ -16,14 +16,14 @@
* type UserId = Brand<string, 'UserId'> * type UserId = Brand<string, 'UserId'>
* type OrderId = Brand<string, 'OrderId'> * 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 // Branded type constructors
export type UserId = Brand<string, 'UserId'> export type UserId = Brand<string, "UserId">;
export type Email = Brand<string, 'Email'> export type Email = Brand<string, "Email">;
export type UUID = Brand<string, 'UUID'> export type UUID = Brand<string, "UUID">;
export type Timestamp = Brand<number, 'Timestamp'> export type Timestamp = Brand<number, "Timestamp">;
export type PositiveNumber = Brand<number, 'PositiveNumber'> export type PositiveNumber = Brand<number, "PositiveNumber">;
// ============================================================================= // =============================================================================
// RESULT TYPE (Error Handling) // RESULT TYPE (Error Handling)
@@ -34,17 +34,17 @@ export type PositiveNumber = Brand<number, 'PositiveNumber'>
*/ */
export type Result<T, E = Error> = export type Result<T, E = Error> =
| { success: true; data: T } | { success: true; data: T }
| { success: false; error: E } | { success: false; error: E };
export const ok = <T>(data: T): Result<T, never> => ({ export const ok = <T>(data: T): Result<T, never> => ({
success: true, success: true,
data data,
}) });
export const err = <E>(error: E): Result<never, E> => ({ export const err = <E>(error: E): Result<never, E> => ({
success: false, success: false,
error error,
}) });
// ============================================================================= // =============================================================================
// OPTION TYPE (Nullable Handling) // OPTION TYPE (Nullable Handling)
@@ -53,13 +53,13 @@ export const err = <E>(error: E): Result<never, E> => ({
/** /**
* Explicit optional value handling. * 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 Some<T> = { type: "some"; value: T };
export type None = { type: 'none' } export type None = { type: "none" };
export const some = <T>(value: T): Some<T> => ({ type: 'some', value }) export const some = <T>(value: T): Some<T> => ({ type: "some", value });
export const none: None = { type: 'none' } export const none: None = { type: "none" };
// ============================================================================= // =============================================================================
// DEEP UTILITIES // DEEP UTILITIES
@@ -72,28 +72,28 @@ export type DeepReadonly<T> = T extends (...args: any[]) => any
? T ? T
: T extends object : T extends object
? { readonly [K in keyof T]: DeepReadonly<T[K]> } ? { readonly [K in keyof T]: DeepReadonly<T[K]> }
: T : T;
/** /**
* Make all properties deeply optional. * Make all properties deeply optional.
*/ */
export type DeepPartial<T> = T extends object export type DeepPartial<T> = T extends object
? { [K in keyof T]?: DeepPartial<T[K]> } ? { [K in keyof T]?: DeepPartial<T[K]> }
: T : T;
/** /**
* Make all properties deeply required. * Make all properties deeply required.
*/ */
export type DeepRequired<T> = T extends object export type DeepRequired<T> = T extends object
? { [K in keyof T]-?: DeepRequired<T[K]> } ? { [K in keyof T]-?: DeepRequired<T[K]> }
: T : T;
/** /**
* Make all properties deeply mutable (remove readonly). * Make all properties deeply mutable (remove readonly).
*/ */
export type DeepMutable<T> = T extends object export type DeepMutable<T> = T extends object
? { -readonly [K in keyof T]: DeepMutable<T[K]> } ? { -readonly [K in keyof T]: DeepMutable<T[K]> }
: T : T;
// ============================================================================= // =============================================================================
// OBJECT UTILITIES // OBJECT UTILITIES
@@ -103,38 +103,40 @@ export type DeepMutable<T> = T extends object
* Get keys of object where value matches type. * Get keys of object where value matches type.
*/ */
export type KeysOfType<T, V> = { export type KeysOfType<T, V> = {
[K in keyof T]: T[K] extends V ? K : never [K in keyof T]: T[K] extends V ? K : never;
}[keyof T] }[keyof T];
/** /**
* Pick properties by value type. * 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. * 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. * 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. * 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. * 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). * 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 // ARRAY UTILITIES
@@ -143,7 +145,7 @@ export type Merge<T, U> = Omit<T, keyof U> & U
/** /**
* Get element type from array. * 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. * Tuple of specific length.
@@ -152,21 +154,21 @@ export type Tuple<T, N extends number> = N extends N
? number extends N ? number extends N
? T[] ? T[]
: _TupleOf<T, N, []> : _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 ? R
: _TupleOf<T, N, [T, ...R]> : _TupleOf<T, N, [T, ...R]>;
/** /**
* Non-empty array. * Non-empty array.
*/ */
export type NonEmptyArray<T> = [T, ...T[]] export type NonEmptyArray<T> = [T, ...T[]];
/** /**
* At least N elements. * 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 // FUNCTION UTILITIES
@@ -175,28 +177,28 @@ export type AtLeast<T, N extends number> = [...Tuple<T, N>, ...T[]]
/** /**
* Get function arguments as tuple. * 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. * Get first argument of function.
*/ */
export type FirstArgument<T> = T extends (first: infer F, ...args: any[]) => any export type FirstArgument<T> = T extends (first: infer F, ...args: any[]) => any
? F ? F
: never : never;
/** /**
* Async version of function. * Async version of function.
*/ */
export type AsyncFunction<T extends (...args: any[]) => any> = ( export type AsyncFunction<T extends (...args: any[]) => any> = (
...args: Parameters<T> ...args: Parameters<T>
) => Promise<Awaited<ReturnType<T>>> ) => Promise<Awaited<ReturnType<T>>>;
/** /**
* Promisify return type. * Promisify return type.
*/ */
export type Promisify<T> = T extends (...args: infer A) => infer R export type Promisify<T> = T extends (...args: infer A) => infer R
? (...args: A) => Promise<Awaited<R>> ? (...args: A) => Promise<Awaited<R>>
: never : never;
// ============================================================================= // =============================================================================
// STRING UTILITIES // STRING UTILITIES
@@ -205,22 +207,21 @@ export type Promisify<T> = T extends (...args: infer A) => infer R
/** /**
* Split string by delimiter. * Split string by delimiter.
*/ */
export type Split<S extends string, D extends string> = export type Split<
S extends `${infer T}${D}${infer U}` S extends string,
? [T, ...Split<U, D>] D extends string,
: [S] > = S extends `${infer T}${D}${infer U}` ? [T, ...Split<U, D>] : [S];
/** /**
* Join tuple to string. * Join tuple to string.
*/ */
export type Join<T extends string[], D extends string> = export type Join<T extends string[], D extends string> = T extends []
T extends [] ? ""
? ''
: T extends [infer F extends string] : T extends [infer F extends string]
? F ? F
: T extends [infer F extends string, ...infer R extends string[]] : T extends [infer F extends string, ...infer R extends string[]]
? `${F}${D}${Join<R, D>}` ? `${F}${D}${Join<R, D>}`
: never : never;
/** /**
* Path to nested object. * 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 ? T[K] extends object
? K | `${K}.${PathOf<T[K]>}` ? K | `${K}.${PathOf<T[K]>}`
: K : K
: never : never;
// ============================================================================= // =============================================================================
// UNION UTILITIES // UNION UTILITIES
@@ -238,27 +239,28 @@ export type PathOf<T, K extends keyof T = keyof T> = K extends string
/** /**
* Last element of union. * Last element of union.
*/ */
export type UnionLast<T> = UnionToIntersection< export type UnionLast<T> =
T extends any ? () => T : never UnionToIntersection<T extends any ? () => T : never> extends () => infer R
> extends () => infer R
? R ? R
: never : never;
/** /**
* Union to intersection. * Union to intersection.
*/ */
export type UnionToIntersection<U> = ( export type UnionToIntersection<U> = (
U extends any ? (k: U) => void : never U extends any
? (k: U) => void
: never
) extends (k: infer I) => void ) extends (k: infer I) => void
? I ? I
: never : never;
/** /**
* Union to tuple. * Union to tuple.
*/ */
export type UnionToTuple<T, L = UnionLast<T>> = [T] extends [never] export type UnionToTuple<T, L = UnionLast<T>> = [T] extends [never]
? [] ? []
: [...UnionToTuple<Exclude<T, L>>, L] : [...UnionToTuple<Exclude<T, L>>, L];
// ============================================================================= // =============================================================================
// VALIDATION UTILITIES // VALIDATION UTILITIES
@@ -268,28 +270,25 @@ export type UnionToTuple<T, L = UnionLast<T>> = [T] extends [never]
* Assert type at compile time. * Assert type at compile time.
*/ */
export type AssertEqual<T, U> = 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 ? true
: false : false;
/** /**
* Ensure type is not never. * 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. * 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. * Ensure type is unknown.
*/ */
export type IsUnknown<T> = IsAny<T> extends true export type IsUnknown<T> =
? false IsAny<T> extends true ? false : unknown extends T ? true : false;
: unknown extends T
? true
: false
// ============================================================================= // =============================================================================
// JSON UTILITIES // JSON UTILITIES
@@ -298,10 +297,10 @@ export type IsUnknown<T> = IsAny<T> extends true
/** /**
* JSON-safe types. * JSON-safe types.
*/ */
export type JsonPrimitive = string | number | boolean | null export type JsonPrimitive = string | number | boolean | null;
export type JsonArray = JsonValue[] export type JsonArray = JsonValue[];
export type JsonObject = { [key: string]: JsonValue } export type JsonObject = { [key: string]: JsonValue };
export type JsonValue = JsonPrimitive | JsonArray | JsonObject export type JsonValue = JsonPrimitive | JsonArray | JsonObject;
/** /**
* Make type JSON-serializable. * Make type JSON-serializable.
@@ -314,7 +313,7 @@ export type Jsonify<T> = T extends JsonPrimitive
? R ? R
: T extends object : T extends object
? { [K in keyof T]: Jsonify<T[K]> } ? { [K in keyof T]: Jsonify<T[K]> }
: never : never;
// ============================================================================= // =============================================================================
// EXHAUSTIVE CHECK // EXHAUSTIVE CHECK
@@ -324,7 +323,7 @@ export type Jsonify<T> = T extends JsonPrimitive
* Ensure all cases are handled in switch/if. * Ensure all cases are handled in switch/if.
*/ */
export function assertNever(value: never, message?: string): never { export function assertNever(value: never, message?: string): never {
throw new Error(message ?? `Unexpected value: ${value}`) throw new Error(message ?? `Unexpected value: ${value}`);
} }
/** /**

View 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"
}

File diff suppressed because it is too large Load Diff

View 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"
]
}

View File

@@ -20,4 +20,5 @@ repos:
- sickn33/antigravity-awesome-skills - sickn33/antigravity-awesome-skills
- tfriedel/claude-office-skills - tfriedel/claude-office-skills
- wshobson/agents - wshobson/agents
- OpenRouterTeam/agent-skills
- ~/projects/ai-skills - ~/projects/ai-skills

View File

@@ -5,6 +5,7 @@
"": { "": {
"name": "ical-pwa", "name": "ical-pwa",
"dependencies": { "dependencies": {
"@openrouter/sdk": "^0.11.2",
"@radix-ui/react-checkbox": "^1.3.3", "@radix-ui/react-checkbox": "^1.3.3",
"@radix-ui/react-dialog": "^1.1.15", "@radix-ui/react-dialog": "^1.1.15",
"@radix-ui/react-dropdown-menu": "^2.1.16", "@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=="], "@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/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=="], "@opentelemetry/semantic-conventions": ["@opentelemetry/semantic-conventions@1.40.0", "", {}, "sha512-cifvXDhcqMwwTlTK04GBNeIe7yyo28Mfby85QXFe1Yk8nmi36Ab/5UQwptOx84SsoGNRg+EVSjwzfSZMy6pmlw=="],

View File

@@ -1,18 +1,18 @@
import { defineConfig } from 'drizzle-kit'; import { defineConfig } from "drizzle-kit";
import * as dotenv from 'dotenv'; import * as dotenv from "dotenv";
if (!process.env.DATABASE_URL) { if (!process.env.DATABASE_URL) {
if (process.env.NODE_ENV === "production") { if (process.env.NODE_ENV === "production") {
dotenv.config({ path: '.env.production' }); dotenv.config({ path: ".env.production" });
} else { } else {
dotenv.config({ path: '.env.local' }); dotenv.config({ path: ".env.local" });
} }
} }
export default defineConfig({ export default defineConfig({
dialect: 'postgresql', dialect: "postgresql",
schema: './src/db/schema.ts', schema: "./src/db/schema.ts",
out: './drizzle', out: "./drizzle",
dbCredentials: { dbCredentials: {
url: process.env.DATABASE_URL!, url: process.env.DATABASE_URL!,
}, },

View File

@@ -34,12 +34,8 @@
"tableFrom": "session", "tableFrom": "session",
"tableTo": "user", "tableTo": "user",
"schemaTo": "public", "schemaTo": "public",
"columnsFrom": [ "columnsFrom": ["userId"],
"userId" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
} }
@@ -121,10 +117,7 @@
"compositePrimaryKeys": { "compositePrimaryKeys": {
"verificationToken_identifier_token_pk": { "verificationToken_identifier_token_pk": {
"name": "verificationToken_identifier_token_pk", "name": "verificationToken_identifier_token_pk",
"columns": [ "columns": ["identifier", "token"]
"identifier",
"token"
]
} }
}, },
"uniqueConstraints": {}, "uniqueConstraints": {},
@@ -192,12 +185,8 @@
"tableFrom": "authenticator", "tableFrom": "authenticator",
"tableTo": "user", "tableTo": "user",
"schemaTo": "public", "schemaTo": "public",
"columnsFrom": [ "columnsFrom": ["userId"],
"userId" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
} }
@@ -205,17 +194,12 @@
"compositePrimaryKeys": { "compositePrimaryKeys": {
"authenticator_userId_credentialID_pk": { "authenticator_userId_credentialID_pk": {
"name": "authenticator_userId_credentialID_pk", "name": "authenticator_userId_credentialID_pk",
"columns": [ "columns": ["credentialID", "userId"]
"credentialID",
"userId"
]
} }
}, },
"uniqueConstraints": { "uniqueConstraints": {
"authenticator_credentialID_unique": { "authenticator_credentialID_unique": {
"columns": [ "columns": ["credentialID"],
"credentialID"
],
"nullsNotDistinct": false, "nullsNotDistinct": false,
"name": "authenticator_credentialID_unique" "name": "authenticator_credentialID_unique"
} }
@@ -302,12 +286,8 @@
"tableFrom": "account", "tableFrom": "account",
"tableTo": "user", "tableTo": "user",
"schemaTo": "public", "schemaTo": "public",
"columnsFrom": [ "columnsFrom": ["userId"],
"userId" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
} }
@@ -315,10 +295,7 @@
"compositePrimaryKeys": { "compositePrimaryKeys": {
"account_provider_providerAccountId_pk": { "account_provider_providerAccountId_pk": {
"name": "account_provider_providerAccountId_pk", "name": "account_provider_providerAccountId_pk",
"columns": [ "columns": ["provider", "providerAccountId"]
"provider",
"providerAccountId"
]
} }
}, },
"uniqueConstraints": {}, "uniqueConstraints": {},

View File

@@ -95,12 +95,8 @@
"name": "account_userId_user_id_fk", "name": "account_userId_user_id_fk",
"tableFrom": "account", "tableFrom": "account",
"tableTo": "user", "tableTo": "user",
"columnsFrom": [ "columnsFrom": ["userId"],
"userId" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
} }
@@ -172,12 +168,8 @@
"name": "session_userId_user_id_fk", "name": "session_userId_user_id_fk",
"tableFrom": "session", "tableFrom": "session",
"tableTo": "user", "tableTo": "user",
"columnsFrom": [ "columnsFrom": ["userId"],
"userId" "columnsTo": ["id"],
],
"columnsTo": [
"id"
],
"onDelete": "cascade", "onDelete": "cascade",
"onUpdate": "no action" "onUpdate": "no action"
} }
@@ -187,9 +179,7 @@
"session_token_unique": { "session_token_unique": {
"name": "session_token_unique", "name": "session_token_unique",
"nullsNotDistinct": false, "nullsNotDistinct": false,
"columns": [ "columns": ["token"]
"token"
]
} }
}, },
"policies": {}, "policies": {},
@@ -253,9 +243,7 @@
"user_email_unique": { "user_email_unique": {
"name": "user_email_unique", "name": "user_email_unique",
"nullsNotDistinct": false, "nullsNotDistinct": false,
"columns": [ "columns": ["email"]
"email"
]
} }
}, },
"policies": {}, "policies": {},

View File

@@ -4,7 +4,7 @@ import { user, session, account } from "./schema";
export const sessionRelations = relations(session, ({ one }) => ({ export const sessionRelations = relations(session, ({ one }) => ({
user: one(user, { user: one(user, {
fields: [session.userId], fields: [session.userId],
references: [user.id] references: [user.id],
}), }),
})); }));
@@ -16,6 +16,6 @@ export const userRelations = relations(user, ({many}) => ({
export const accountRelations = relations(account, ({ one }) => ({ export const accountRelations = relations(account, ({ one }) => ({
user: one(user, { user: one(user, {
fields: [account.userId], fields: [account.userId],
references: [user.id] references: [user.id],
}), }),
})); }));

View File

@@ -1,37 +1,57 @@
import { pgTable, foreignKey, text, timestamp, primaryKey, unique, integer, boolean } from "drizzle-orm/pg-core" import {
import { sql } from "drizzle-orm" 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(), sessionToken: text().primaryKey().notNull(),
userId: text().notNull(), userId: text().notNull(),
expires: timestamp({ mode: 'string' }).notNull(), expires: timestamp({ mode: "string" }).notNull(),
}, (table) => [ },
(table) => [
foreignKey({ foreignKey({
columns: [table.userId], columns: [table.userId],
foreignColumns: [user.id], foreignColumns: [user.id],
name: "session_userId_user_id_fk" name: "session_userId_user_id_fk",
}).onDelete("cascade"), }).onDelete("cascade"),
]); ],
);
export const user = pgTable("user", { export const user = pgTable("user", {
id: text().primaryKey().notNull(), id: text().primaryKey().notNull(),
name: text(), name: text(),
email: text().notNull(), email: text().notNull(),
emailVerified: timestamp({ mode: 'string' }), emailVerified: timestamp({ mode: "string" }),
image: text(), image: text(),
}); });
export const verificationToken = pgTable("verificationToken", { export const verificationToken = pgTable(
"verificationToken",
{
identifier: text().notNull(), identifier: text().notNull(),
token: text().notNull(), token: text().notNull(),
expires: timestamp({ mode: 'string' }).notNull(), expires: timestamp({ mode: "string" }).notNull(),
}, (table) => [ },
primaryKey({ columns: [table.identifier, table.token], name: "verificationToken_identifier_token_pk"}), (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(), credentialId: text().notNull(),
userId: text().notNull(), userId: text().notNull(),
providerAccountId: text().notNull(), providerAccountId: text().notNull(),
@@ -40,17 +60,24 @@ export const authenticator = pgTable("authenticator", {
credentialDeviceType: text().notNull(), credentialDeviceType: text().notNull(),
credentialBackedUp: boolean().notNull(), credentialBackedUp: boolean().notNull(),
transports: text(), transports: text(),
}, (table) => [ },
(table) => [
foreignKey({ foreignKey({
columns: [table.userId], columns: [table.userId],
foreignColumns: [user.id], foreignColumns: [user.id],
name: "authenticator_userId_user_id_fk" name: "authenticator_userId_user_id_fk",
}).onDelete("cascade"), }).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), unique("authenticator_credentialID_unique").on(table.credentialId),
]); ],
);
export const account = pgTable("account", { export const account = pgTable(
"account",
{
userId: text().notNull(), userId: text().notNull(),
type: text().notNull(), type: text().notNull(),
provider: text().notNull(), provider: text().notNull(),
@@ -62,11 +89,16 @@ export const account = pgTable("account", {
scope: text(), scope: text(),
idToken: text("id_token"), idToken: text("id_token"),
sessionState: text("session_state"), sessionState: text("session_state"),
}, (table) => [ },
(table) => [
foreignKey({ foreignKey({
columns: [table.userId], columns: [table.userId],
foreignColumns: [user.id], foreignColumns: [user.id],
name: "account_userId_user_id_fk" name: "account_userId_user_id_fk",
}).onDelete("cascade"), }).onDelete("cascade"),
primaryKey({ columns: [table.provider, table.providerAccountId], name: "account_provider_providerAccountId_pk"}), primaryKey({
]); columns: [table.provider, table.providerAccountId],
name: "account_provider_providerAccountId_pk",
}),
],
);

View File

@@ -9,6 +9,7 @@
"lint": "next lint" "lint": "next lint"
}, },
"dependencies": { "dependencies": {
"@openrouter/sdk": "^0.11.2",
"@radix-ui/react-checkbox": "^1.3.3", "@radix-ui/react-checkbox": "^1.3.3",
"@radix-ui/react-dialog": "^1.1.15", "@radix-ui/react-dialog": "^1.1.15",
"@radix-ui/react-dropdown-menu": "^2.1.16", "@radix-ui/react-dropdown-menu": "^2.1.16",

View File

@@ -1,6 +1,7 @@
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
import { auth } from "@/auth"; import { auth } from "@/auth";
import { headers } from "next/headers"; import { headers } from "next/headers";
import { openRouterClient } from "@/lib/openrouter-client";
export async function POST(request: Request) { export async function POST(request: Request) {
const session = await auth.api.getSession({ const session = await auth.api.getSession({
@@ -10,7 +11,7 @@ export async function POST(request: Request) {
if (!session?.user) { if (!session?.user) {
return NextResponse.json( return NextResponse.json(
{ error: "Authentication required" }, { 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) { if (!prompt || typeof prompt !== "string" || prompt.trim().length === 0) {
return NextResponse.json( return NextResponse.json(
{ error: "Prompt is required and must be a non-empty string" }, { error: "Prompt is required and must be a non-empty string" },
{ status: 400 } { status: 400 },
); );
} }
if (prompt.length > 2000) { if (prompt.length > 2000) {
return NextResponse.json( return NextResponse.json(
{ error: "Prompt must be less than 2000 characters" }, { error: "Prompt must be less than 2000 characters" },
{ status: 400 } { status: 400 },
); );
} }
@@ -57,29 +58,23 @@ Rules:
- Output ONLY valid JSON (no prose). - Output ONLY valid JSON (no prose).
`; `;
const res = await fetch("https://openrouter.ai/api/v1/chat/completions", { try {
method: "POST", const result = openRouterClient.callModel({
headers: { model: "openai/gpt-5.4-mini",
Authorization: `Bearer ${process.env.OPENROUTER_API_KEY}`, instructions: systemPrompt,
"Content-Type": "application/json", input: prompt,
},
body: JSON.stringify({
model: "openai/gpt-4.1-nano",
messages: [
{ role: "system", content: systemPrompt },
{ role: "user", content: prompt },
],
}),
}); });
const data = await res.json(); const text = await result.getText();
try { const parsed = JSON.parse(text);
const content = data.choices[0].message.content;
const parsed = JSON.parse(content);
return NextResponse.json(parsed); return NextResponse.json(parsed);
} catch { } catch (error) {
console.error("AI Event Creation Error:", error);
return NextResponse.json( 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 }, { status: 500 },
); );
} }

View File

@@ -1,6 +1,7 @@
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
import { auth } from "@/auth"; import { auth } from "@/auth";
import { headers } from "next/headers"; import { headers } from "next/headers";
import { openRouterClient } from "@/lib/openrouter-client";
export async function POST(request: Request) { export async function POST(request: Request) {
const session = await auth.api.getSession({ 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", { const result = openRouterClient.callModel({
method: "POST",
headers: {
Authorization: `Bearer ${process.env.OPENROUTER_API_KEY}`, // Server-side only
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "@preset/i-cal-editor-summarize", // FREE model model: "@preset/i-cal-editor-summarize", // FREE model
messages: [ instructions:
{ "You summarize a list of events in natural language. Include date, time, and title. Be concise.",
role: "system", input: JSON.stringify(events),
content: `You summarize a list of events in natural language. Include date, time, and title. Be concise.`,
},
{ role: "user", content: JSON.stringify(events) },
],
temperature: 0.4, temperature: 0.4,
// max_tokens: 300,
}),
}); });
const data = await res.json(); const summary = await result.getText();
const summary =
data?.choices?.[0]?.message?.content || "No summary generated.";
return NextResponse.json({ summary }); return NextResponse.json({ summary });
} catch (error) { } catch (error) {
console.error(error); console.error("AI Summary Error:", error);
return NextResponse.json( return NextResponse.json(
{ error: "Failed to summarize events" }, { error: "Failed to summarize events" },
{ status: 500 }, { status: 500 },

View File

@@ -1,23 +1,25 @@
"use client" "use client";
import { Button } from "@/components/ui/button" import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card" import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import Link from "next/link" import Link from "next/link";
import { useSearchParams } from "next/navigation" import { useSearchParams } from "next/navigation";
import { Suspense } from "react" import { Suspense } from "react";
function Search() { function Search() {
const searchParams = useSearchParams() const searchParams = useSearchParams();
const errorMessage = searchParams.get('error') const errorMessage = searchParams.get("error");
// Sanitize error message to prevent XSS // Sanitize error message to prevent XSS
const sanitizedError = errorMessage const sanitizedError = errorMessage
? errorMessage.replace(/[<>]/g, '') ? errorMessage.replace(/[<>]/g, "")
: 'An authentication error occurred' : "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} {sanitizedError}
</div>) </div>
);
} }
export default function AuthErrorPage() { export default function AuthErrorPage() {
@@ -39,5 +41,5 @@ export default function AuthErrorPage() {
</CardContent> </CardContent>
</Card> </Card>
</div> </div>
) );
} }

View File

@@ -1,44 +1,50 @@
"use client" "use client";
import { signIn, useSession } from "@/lib/auth-client" import { signIn, useSession } from "@/lib/auth-client";
import { Button } from "@/components/ui/button" import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card" import {
import Link from "next/link" Card,
import { useRouter } from "next/navigation" CardContent,
import { useEffect, useState } from "react" CardDescription,
import { toast } from "sonner" 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() { export default function SignInPage() {
const { data: session, isPending } = useSession() const { data: session, isPending } = useSession();
const router = useRouter() const router = useRouter();
const [isLoading, setIsLoading] = useState(false) const [isLoading, setIsLoading] = useState(false);
useEffect(() => { useEffect(() => {
if (session?.user) { if (session?.user) {
router.push("/") router.push("/");
} }
}, [session, router]) }, [session, router]);
const handleSignIn = async () => { const handleSignIn = async () => {
setIsLoading(true) setIsLoading(true);
try { try {
await signIn.oauth2({ await signIn.oauth2({
providerId: "authentik", providerId: "authentik",
callbackURL: "/", callbackURL: "/",
}) });
} catch (_error) { } catch (_error) {
toast.error("Failed to sign in. Please try again.") toast.error("Failed to sign in. Please try again.");
} finally { } finally {
setIsLoading(false) setIsLoading(false);
}
} }
};
if (isPending) { if (isPending) {
return null return null;
} }
if (session?.user) { if (session?.user) {
return null return null;
} }
return ( return (
@@ -51,17 +57,25 @@ export default function SignInPage() {
</CardDescription> </CardDescription>
</CardHeader> </CardHeader>
<CardContent className="space-y-4"> <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"} {isLoading ? "Signing in..." : "Continue with Authentik"}
</Button> </Button>
<div className="text-center"> <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 Continue without signing in
</Link> </Link>
</div> </div>
</CardContent> </CardContent>
</Card> </Card>
</div> </div>
) );
} }

View File

@@ -1,29 +1,35 @@
"use client" "use client";
import { signOut, useSession } from "@/lib/auth-client" import { signOut, useSession } from "@/lib/auth-client";
import { Button } from "@/components/ui/button" import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card" import {
import Link from "next/link" Card,
import { useRouter } from "next/navigation" CardContent,
import { useEffect } from "react" 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() { export default function SignOutPage() {
const { data: session, isPending } = useSession() const { data: session, isPending } = useSession();
const router = useRouter() const router = useRouter();
useEffect(() => { useEffect(() => {
if (!session?.user) { if (!session?.user) {
router.push("/") router.push("/");
} }
}, [session, router]) }, [session, router]);
const handleSignOut = async () => { const handleSignOut = async () => {
await signOut() await signOut();
router.push("/") router.push("/");
} };
if (isPending || !session?.user) { if (isPending || !session?.user) {
return null return null;
} }
return ( return (
@@ -31,18 +37,24 @@ export default function SignOutPage() {
<Card className="w-full max-w-md"> <Card className="w-full max-w-md">
<CardHeader className="text-center"> <CardHeader className="text-center">
<CardTitle className="text-2xl font-bold">Sign Out</CardTitle> <CardTitle className="text-2xl font-bold">Sign Out</CardTitle>
<CardDescription> <CardDescription>Are you sure you want to sign out?</CardDescription>
Are you sure you want to sign out?
</CardDescription>
</CardHeader> </CardHeader>
<CardContent className="space-y-4"> <CardContent className="space-y-4">
<div className="text-center p-3 bg-muted rounded-lg"> <div className="text-center p-3 bg-muted rounded-lg">
<div className="text-sm text-muted-foreground">Currently signed in as</div> <div className="text-sm text-muted-foreground">
<div className="font-medium">{session.user?.name || session.user?.email}</div> Currently signed in as
</div>
<div className="font-medium">
{session.user?.name || session.user?.email}
</div>
</div> </div>
<div className="grid grid-cols-2 gap-3"> <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 Sign Out
</Button> </Button>
@@ -53,5 +65,5 @@ export default function SignOutPage() {
</CardContent> </CardContent>
</Card> </Card>
</div> </div>
) );
} }

View File

@@ -5,17 +5,24 @@ import { ThemeProvider } from "next-themes";
import { ModeToggle } from "@/components/mode-toggle"; import { ModeToggle } from "@/components/mode-toggle";
import SignIn from "@/components/sign-in"; import SignIn from "@/components/sign-in";
import { Toaster } from "@/components/ui/sonner"; 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 = { export const metadata: Metadata = {
title: 'Local iCal', title: "Local iCal",
description: 'Local iCal editor for calendar events', description: "Local iCal editor for calendar events",
creator: "Dmytro Stanchiev", creator: "Dmytro Stanchiev",
} };
export default function RootLayout({ export default function RootLayout({
children, 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"> <header className="dark:text-white text-gray-900 px-4 py-3 font-bold flex justify-between items-center-safe">
<Link href={"/"}> <Link href={"/"}>
<p className={`${magra.variable}`}> <p className={`${magra.variable}`}>
{metadata.title as string || "iCal PWA"} {(metadata.title as string) || "iCal PWA"}
</p> </p>
</Link> </Link>
<div className="flex flex-row gap-2"> <div className="flex flex-row gap-2">

View File

@@ -1,62 +1,70 @@
"use client" "use client";
import { useEffect, useState } from 'react' import { useEffect, useState } from "react";
import { nanoid } from 'nanoid' import { nanoid } from "nanoid";
import { useSession } from '@/lib/auth-client' import { useSession } from "@/lib/auth-client";
import { toast } from 'sonner' import { toast } from "sonner";
import { saveEvent as addEvent, deleteEvent, getEvents as getAllEvents, clearEvents, updateEvent } from '@/lib/events-db' import {
import { parseICS, generateICS } from '@/lib/ical' saveEvent as addEvent,
import type { CalendarEvent } from '@/lib/types' 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 { AIToolbar } from "@/components/ai-toolbar";
import { EventActionsToolbar } from '@/components/event-actions-toolbar' import { EventActionsToolbar } from "@/components/event-actions-toolbar";
import { EventsList } from '@/components/events-list' import { EventsList } from "@/components/events-list";
import { EventDialog } from '@/components/event-dialog' import { EventDialog } from "@/components/event-dialog";
import { DragDropContainer } from '@/components/drag-drop-container' import { DragDropContainer } from "@/components/drag-drop-container";
export default function HomePage() { export default function HomePage() {
const [events, setEvents] = useState<CalendarEvent[]>([]) const [events, setEvents] = useState<CalendarEvent[]>([]);
const [dialogOpen, setDialogOpen] = useState(false) const [dialogOpen, setDialogOpen] = useState(false);
const [editingId, setEditingId] = useState<string | null>(null) const [editingId, setEditingId] = useState<string | null>(null);
const [isDragOver, setIsDragOver] = useState(false) const [isDragOver, setIsDragOver] = useState(false);
// Form fields // Form fields
const [title, setTitle] = useState('') const [title, setTitle] = useState("");
const [description, setDescription] = useState('') const [description, setDescription] = useState("");
const [location, setLocation] = useState('') const [location, setLocation] = useState("");
const [url, setUrl] = useState('') const [url, setUrl] = useState("");
const [start, setStart] = useState('') const [start, setStart] = useState("");
const [end, setEnd] = useState('') const [end, setEnd] = useState("");
const [allDay, setAllDay] = useState(false) const [allDay, setAllDay] = useState(false);
const [recurrenceRule, setRecurrenceRule] = useState<string | undefined>(undefined) const [recurrenceRule, setRecurrenceRule] = useState<string | undefined>(
undefined,
);
// AI // AI
const [aiPrompt, setAiPrompt] = useState('') const [aiPrompt, setAiPrompt] = useState("");
const [aiLoading, setAiLoading] = useState(false) const [aiLoading, setAiLoading] = useState(false);
const [summary, setSummary] = useState<string | null>(null) const [summary, setSummary] = useState<string | null>(null);
const [summaryUpdated, setSummaryUpdated] = useState<string | null>(null) const [summaryUpdated, setSummaryUpdated] = useState<string | null>(null);
useEffect(() => { useEffect(() => {
(async () => { (async () => {
const stored = await getAllEvents() const stored = await getAllEvents();
setEvents(stored) setEvents(stored);
})() })();
}, []) }, []);
const { data: session, isPending } = useSession() const { data: session, isPending } = useSession();
const resetForm = () => { const resetForm = () => {
setTitle('') setTitle("");
setDescription('') setDescription("");
setLocation('') setLocation("");
setUrl('') setUrl("");
setStart('') setStart("");
setEnd('') setEnd("");
setAllDay(false) setAllDay(false);
setEditingId(null) setEditingId(null);
setRecurrenceRule(undefined) setRecurrenceRule(undefined);
} };
const handleSave = async () => { const handleSave = async () => {
const eventData: CalendarEvent = { const eventData: CalendarEvent = {
@@ -70,96 +78,98 @@ export default function HomePage() {
end: end || undefined, end: end || undefined,
allDay, allDay,
createdAt: editingId createdAt: editingId
? events.find(e => e.id === editingId)?.createdAt ? events.find((e) => e.id === editingId)?.createdAt
: new Date().toISOString(), : new Date().toISOString(),
lastModified: new Date().toISOString(), lastModified: new Date().toISOString(),
} };
if (editingId) { if (editingId) {
await updateEvent(eventData) await updateEvent(eventData);
setEvents(prev => prev.map(e => (e.id === editingId ? eventData : e))) setEvents((prev) =>
prev.map((e) => (e.id === editingId ? eventData : e)),
);
} else { } else {
await addEvent(eventData) await addEvent(eventData);
setEvents(prev => [...prev, eventData]) setEvents((prev) => [...prev, eventData]);
}
resetForm()
setDialogOpen(false)
} }
resetForm();
setDialogOpen(false);
};
const handleDelete = async (id: string) => { const handleDelete = async (id: string) => {
await deleteEvent(id) await deleteEvent(id);
setEvents(prev => prev.filter(e => e.id !== id)) setEvents((prev) => prev.filter((e) => e.id !== id));
} };
const handleClearAll = async () => { const handleClearAll = async () => {
await clearEvents() await clearEvents();
setEvents([]) setEvents([]);
} };
const handleImport = async (file: File) => { const handleImport = async (file: File) => {
const text = await file.text() const text = await file.text();
const parsed = parseICS(text) const parsed = parseICS(text);
for (const ev of parsed) { for (const ev of parsed) {
await addEvent(ev) await addEvent(ev);
}
const stored = await getAllEvents()
setEvents(stored)
} }
const stored = await getAllEvents();
setEvents(stored);
};
const handleExport = () => { const handleExport = () => {
const icsData = generateICS(events) const icsData = generateICS(events);
const blob = new Blob([icsData], { type: 'text/calendar' }) const blob = new Blob([icsData], { type: "text/calendar" });
const url = URL.createObjectURL(blob) const url = URL.createObjectURL(blob);
const a = document.createElement('a') const a = document.createElement("a");
a.href = url a.href = url;
a.download = `icallocal-export-${new Date().toLocaleTimeString()}.ics` a.download = `icallocal-export-${new Date().toLocaleTimeString()}.ics`;
document.body.appendChild(a) document.body.appendChild(a);
a.click() a.click();
document.body.removeChild(a) document.body.removeChild(a);
URL.revokeObjectURL(url) URL.revokeObjectURL(url);
} };
// AI Create Event // AI Create Event
const handleAiCreate = async () => { const handleAiCreate = async () => {
if (!aiPrompt.trim()) return if (!aiPrompt.trim()) return;
setAiLoading(true) setAiLoading(true);
const promise = (): Promise<{ message: string }> => new Promise(async (resolve, reject) => { const promise = (): Promise<{ message: string }> =>
new Promise(async (resolve, reject) => {
try { try {
const res = await fetch('/api/ai-event', { const res = await fetch("/api/ai-event", {
method: 'POST', method: "POST",
headers: { 'Content-Type': 'application/json' }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ prompt: aiPrompt }) body: JSON.stringify({ prompt: aiPrompt }),
}) });
if (res.status === 401) { if (res.status === 401) {
setAiLoading(false) setAiLoading(false);
reject({ reject({
message: 'Please sign in to use AI features.' message: "Please sign in to use AI features.",
}) });
return return;
} }
const data = await res.json() const data = await res.json();
if (Array.isArray(data) && data.length > 0) { if (Array.isArray(data) && data.length > 0) {
if (data.length === 1) { if (data.length === 1) {
// Prefill dialog directly (same as before) // Prefill dialog directly (same as before)
const ev = data[0] const ev = data[0];
setTitle(ev.title || '') setTitle(ev.title || "");
setDescription(ev.description || '') setDescription(ev.description || "");
setLocation(ev.location || '') setLocation(ev.location || "");
setUrl(ev.url || '') setUrl(ev.url || "");
setStart(ev.start || '') setStart(ev.start || "");
setEnd(ev.end || '') setEnd(ev.end || "");
setAllDay(ev.allDay || false) setAllDay(ev.allDay || false);
setEditingId(null) setEditingId(null);
setAiPrompt("") setAiPrompt("");
setDialogOpen(true) setDialogOpen(true);
setRecurrenceRule(ev.recurrenceRule || undefined) setRecurrenceRule(ev.recurrenceRule || undefined);
resolve({ resolve({
message: 'Event has been created!' message: "Event has been created!",
}) });
} else { } else {
// Save them all directly to DB // Save them all directly to DB
for (const ev of data) { for (const ev of data) {
@@ -168,86 +178,86 @@ export default function HomePage() {
...ev, ...ev,
createdAt: new Date().toISOString(), createdAt: new Date().toISOString(),
lastModified: new Date().toISOString(), lastModified: new Date().toISOString(),
};
await addEvent(newEvent);
} }
await addEvent(newEvent) const stored = await getAllEvents();
} setEvents(stored);
const stored = await getAllEvents() setAiPrompt("");
setEvents(stored) setSummary(`Added ${data.length} AI-generated events.`);
setAiPrompt("") setSummaryUpdated(new Date().toLocaleString());
setSummary(`Added ${data.length} AI-generated events.`)
setSummaryUpdated(new Date().toLocaleString())
resolve({ resolve({
message: 'Event has been created!' message: "Event has been created!",
}) });
} }
} else { } else {
reject({ reject({
message: 'AI did not return event data.' message: "AI did not return event data.",
}) });
} }
} catch (err) { } catch (err) {
console.error(err) console.error(err);
reject({ reject({
message: 'Error from AI service.' message: "Error from AI service.",
}) });
} }
}) });
toast.promise(promise, { toast.promise(promise, {
loading: "Generating event...", loading: "Generating event...",
success: ({ message }) => { success: ({ message }) => {
return message return message;
}, },
error: ({ message }) => { error: ({ message }) => {
return message return message;
} },
}) });
setAiLoading(false) setAiLoading(false);
} };
// AI Summarize Events // AI Summarize Events
const handleAiSummarize = async () => { const handleAiSummarize = async () => {
if (!events.length) { if (!events.length) {
setSummary("No events to summarize.") setSummary("No events to summarize.");
setSummaryUpdated(new Date().toLocaleString()) setSummaryUpdated(new Date().toLocaleString());
return return;
} }
setAiLoading(true) setAiLoading(true);
try { try {
const res = await fetch('/api/ai-summary', { const res = await fetch("/api/ai-summary", {
method: 'POST', method: "POST",
headers: { 'Content-Type': 'application/json' }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ events }) body: JSON.stringify({ events }),
}) });
const data = await res.json() const data = await res.json();
if (data.summary) { if (data.summary) {
setSummary(data.summary) setSummary(data.summary);
setSummaryUpdated(new Date().toLocaleString()) setSummaryUpdated(new Date().toLocaleString());
} else { } else {
setSummary("No summary generated.") setSummary("No summary generated.");
setSummaryUpdated(new Date().toLocaleString()) setSummaryUpdated(new Date().toLocaleString());
} }
} catch { } catch {
setSummary("Error summarizing events") setSummary("Error summarizing events");
setSummaryUpdated(new Date().toLocaleString()) setSummaryUpdated(new Date().toLocaleString());
} finally { } finally {
setAiLoading(false) setAiLoading(false);
}
} }
};
const handleEdit = (eventData: CalendarEvent) => { const handleEdit = (eventData: CalendarEvent) => {
setTitle(eventData.title) setTitle(eventData.title);
setDescription(eventData.description || "") setDescription(eventData.description || "");
setLocation(eventData.location || "") setLocation(eventData.location || "");
setUrl(eventData.url || "") setUrl(eventData.url || "");
setStart(eventData.start) setStart(eventData.start);
setEnd(eventData.end || "") setEnd(eventData.end || "");
setAllDay(eventData.allDay || false) setAllDay(eventData.allDay || false);
setEditingId(eventData.id) setEditingId(eventData.id);
setRecurrenceRule(eventData.recurrenceRule) setRecurrenceRule(eventData.recurrenceRule);
setDialogOpen(true) setDialogOpen(true);
} };
return ( return (
<DragDropContainer <DragDropContainer
@@ -275,11 +285,7 @@ export default function HomePage() {
onClearAll={handleClearAll} onClearAll={handleClearAll}
/> />
<EventsList <EventsList events={events} onEdit={handleEdit} onDelete={handleDelete} />
events={events}
onEdit={handleEdit}
onDelete={handleDelete}
/>
<EventDialog <EventDialog
open={dialogOpen} open={dialogOpen}
@@ -305,5 +311,5 @@ export default function HomePage() {
onReset={resetForm} onReset={resetForm}
/> />
</DragDropContainer> </DragDropContainer>
) );
} }

View File

@@ -1,17 +1,17 @@
import { Button } from '@/components/ui/button' import { Button } from "@/components/ui/button";
import { Textarea } from '@/components/ui/textarea' import { Textarea } from "@/components/ui/textarea";
import { Card } from '@/components/ui/card' import { Card } from "@/components/ui/card";
interface AIToolbarProps { interface AIToolbarProps {
isAuthenticated: boolean isAuthenticated: boolean;
isPending: boolean isPending: boolean;
aiPrompt: string aiPrompt: string;
setAiPrompt: (prompt: string) => void setAiPrompt: (prompt: string) => void;
aiLoading: boolean aiLoading: boolean;
onAiCreate: () => void onAiCreate: () => void;
onAiSummarize: () => void onAiSummarize: () => void;
summary: string | null summary: string | null;
summaryUpdated: string | null summaryUpdated: string | null;
} }
export const AIToolbar = ({ export const AIToolbar = ({
@@ -23,28 +23,30 @@ export const AIToolbar = ({
onAiCreate, onAiCreate,
onAiSummarize, onAiSummarize,
summary, summary,
summaryUpdated summaryUpdated,
}: AIToolbarProps) => { }: AIToolbarProps) => {
return ( return (
<> <>
{isPending ? ( {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> <div>
{isAuthenticated ? ( {isAuthenticated ? (
<div className="flex flex-col sm:flex-row gap-4 mb-4 items-start"> <div className="flex flex-col sm:flex-row gap-4 mb-4 items-start">
<div className='w-full'> <div className="w-full">
<Textarea <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" 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)" }} style={{ clipPath: "inset(0 round 1rem)" }}
placeholder='Describe event for AI to create' placeholder="Describe event for AI to create"
value={aiPrompt} value={aiPrompt}
onChange={e => setAiPrompt(e.target.value)} onChange={(e) => setAiPrompt(e.target.value)}
/> />
</div> </div>
<div className='flex flex-row gap-2 pt-1'> <div className="flex flex-row gap-2 pt-1">
<Button onClick={onAiCreate} disabled={aiLoading}> <Button onClick={onAiCreate} disabled={aiLoading}>
{aiLoading ? 'Thinking...' : 'AI Create'} {aiLoading ? "Thinking..." : "AI Create"}
</Button> </Button>
</div> </div>
</div> </div>
@@ -61,20 +63,22 @@ export const AIToolbar = ({
{/* Summary Panel */} {/* Summary Panel */}
{summary && ( {summary && (
<Card className="p-4 mb-4"> <Card className="p-4 mb-4">
<div className="text-sm mb-1"> <div className="text-sm mb-1">Summary updated {summaryUpdated}</div>
Summary updated {summaryUpdated}
</div>
<div>{summary}</div> <div>{summary}</div>
</Card> </Card>
)} )}
{/* AI Actions Toolbar */} {/* 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"> <div className="gap-2 mb-4">
<Button variant="secondary" onClick={onAiSummarize} disabled={aiLoading}> <Button
{aiLoading ? 'Summarizing...' : 'AI Summarize'} variant="secondary"
onClick={onAiSummarize}
disabled={aiLoading}
>
{aiLoading ? "Summarizing..." : "AI Summarize"}
</Button> </Button>
</div> </div>
</> </>
) );
} };

View File

@@ -1,41 +1,41 @@
import { ReactNode } from 'react' import { ReactNode } from "react";
import { toast } from 'sonner' import { toast } from "sonner";
interface DragDropContainerProps { interface DragDropContainerProps {
children: ReactNode children: ReactNode;
isDragOver: boolean isDragOver: boolean;
setIsDragOver: (isDragOver: boolean) => void setIsDragOver: (isDragOver: boolean) => void;
onImport: (file: File) => void onImport: (file: File) => void;
} }
export const DragDropContainer = ({ export const DragDropContainer = ({
children, children,
isDragOver, isDragOver,
setIsDragOver, setIsDragOver,
onImport onImport,
}: DragDropContainerProps) => { }: DragDropContainerProps) => {
const handleDragOver = (e: React.DragEvent) => { const handleDragOver = (e: React.DragEvent) => {
e.preventDefault() e.preventDefault();
setIsDragOver(true) setIsDragOver(true);
} };
const handleDragLeave = (e: React.DragEvent) => { const handleDragLeave = (e: React.DragEvent) => {
e.preventDefault() e.preventDefault();
setIsDragOver(false) setIsDragOver(false);
} };
const handleDrop = (e: React.DragEvent) => { const handleDrop = (e: React.DragEvent) => {
e.preventDefault() e.preventDefault();
setIsDragOver(false) setIsDragOver(false);
if (e.dataTransfer.files?.length) { if (e.dataTransfer.files?.length) {
const file = e.dataTransfer.files[0] const file = e.dataTransfer.files[0];
if (file.name.endsWith('.ics')) { if (file.name.endsWith(".ics")) {
onImport(file) onImport(file);
} else { } else {
toast.warning('Please drop an .ics file') toast.warning("Please drop an .ics file");
}
} }
} }
};
return ( return (
<div <div
@@ -43,13 +43,13 @@ export const DragDropContainer = ({
onDragLeave={handleDragLeave} onDragLeave={handleDragLeave}
onDrop={handleDrop} onDrop={handleDrop}
className={`p-4 min-h-[80vh] flex flex-col rounded border-2 border-dashed transition ${ 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} {children}
<div className='mt-auto w-full pb-4 text-gray-400'> <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="max-w-fit m-auto">Drag & Drop *.ics here</div>
</div> </div>
</div> </div>
) );
} };

View File

@@ -1,13 +1,13 @@
import { Button } from '@/components/ui/button' import { Button } from "@/components/ui/button";
import { IcsFilePicker } from '@/components/ics-file-picker' import { IcsFilePicker } from "@/components/ics-file-picker";
import type { CalendarEvent } from '@/lib/types' import type { CalendarEvent } from "@/lib/types";
interface EventActionsToolbarProps { interface EventActionsToolbarProps {
events: CalendarEvent[] events: CalendarEvent[];
onAddEvent: () => void onAddEvent: () => void;
onImport: (file: File) => void onImport: (file: File) => void;
onExport: () => void onExport: () => void;
onClearAll: () => void onClearAll: () => void;
} }
export const EventActionsToolbar = ({ export const EventActionsToolbar = ({
@@ -15,22 +15,28 @@ export const EventActionsToolbar = ({
onAddEvent, onAddEvent,
onImport, onImport,
onExport, onExport,
onClearAll onClearAll,
}: EventActionsToolbarProps) => { }: EventActionsToolbarProps) => {
return ( return (
<> <>
{/* Control Toolbar */} {/* 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"> <div className="flex flex-wrap gap-2 mb-4">
<Button onClick={onAddEvent}>Add Event</Button> <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 && ( {events.length > 0 && (
<> <>
<Button variant="secondary" onClick={onExport}>Export .ics</Button> <Button variant="secondary" onClick={onExport}>
<Button variant="destructive" onClick={onClearAll}>Clear All</Button> Export .ics
</Button>
<Button variant="destructive" onClick={onClearAll}>
Clear All
</Button>
</> </>
)} )}
</div> </div>
</> </>
) );
} };

View File

@@ -1,35 +1,40 @@
import { Button } from '@/components/ui/button' import { Button } from "@/components/ui/button";
import { Card, CardHeader, CardContent } from '@/components/ui/card' import { Card, CardHeader, CardContent } from "@/components/ui/card";
import { LucideMapPin, Clock, MoreHorizontal } from 'lucide-react' import { LucideMapPin, Clock, MoreHorizontal } from "lucide-react";
import { DropdownMenu, DropdownMenuContent, DropdownMenuTrigger, DropdownMenuItem } from '@/components/ui/dropdown-menu' import {
import { RRuleDisplay } from '@/components/rrule-display' DropdownMenu,
import type { CalendarEvent } from '@/lib/types' DropdownMenuContent,
DropdownMenuTrigger,
DropdownMenuItem,
} from "@/components/ui/dropdown-menu";
import { RRuleDisplay } from "@/components/rrule-display";
import type { CalendarEvent } from "@/lib/types";
interface EventCardProps { interface EventCardProps {
event: CalendarEvent event: CalendarEvent;
onEdit: (event: CalendarEvent) => void onEdit: (event: CalendarEvent) => void;
onDelete: (eventId: string) => void onDelete: (eventId: string) => void;
} }
export const EventCard = ({ event, onEdit, onDelete }: EventCardProps) => { export const EventCard = ({ event, onEdit, onDelete }: EventCardProps) => {
const formatDateTime = (dateStr: string, allDay: boolean | undefined) => { const formatDateTime = (dateStr: string, allDay: boolean | undefined) => {
return allDay return allDay
? new Date(dateStr).toLocaleDateString() ? new Date(dateStr).toLocaleDateString()
: new Date(dateStr).toLocaleString() : new Date(dateStr).toLocaleString();
} };
const handleEdit = () => { const handleEdit = () => {
onEdit({ onEdit({
id: event.id, id: event.id,
title: event.title, title: event.title,
description: event.description || '', description: event.description || "",
location: event.location || '', location: event.location || "",
url: event.url || '', url: event.url || "",
start: event.start, start: event.start,
end: event.end || '', end: event.end || "",
allDay: event.allDay || false allDay: event.allDay || false,
}) });
} };
return ( return (
<Card className="w-full"> <Card className="w-full">
@@ -58,9 +63,7 @@ export const EventCard = ({ event, onEdit, onDelete }: EventCardProps) => {
</Button> </Button>
</DropdownMenuTrigger> </DropdownMenuTrigger>
<DropdownMenuContent align="end"> <DropdownMenuContent align="end">
<DropdownMenuItem onClick={handleEdit}> <DropdownMenuItem onClick={handleEdit}>Edit</DropdownMenuItem>
Edit
</DropdownMenuItem>
<DropdownMenuItem <DropdownMenuItem
onClick={() => onDelete(event.id)} onClick={() => onDelete(event.id)}
className="text-destructive" className="text-destructive"
@@ -88,5 +91,5 @@ export const EventCard = ({ event, onEdit, onDelete }: EventCardProps) => {
</div> </div>
</CardContent> </CardContent>
</Card> </Card>
) );
} };

View File

@@ -1,30 +1,36 @@
import { Button } from '@/components/ui/button' import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog' import {
import { Input } from '@/components/ui/input' Dialog,
import { RecurrencePicker } from '@/components/recurrence-picker' DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { RecurrencePicker } from "@/components/recurrence-picker";
interface EventDialogProps { interface EventDialogProps {
open: boolean open: boolean;
onOpenChange: (open: boolean) => void onOpenChange: (open: boolean) => void;
editingId: string | null editingId: string | null;
title: string title: string;
setTitle: (title: string) => void setTitle: (title: string) => void;
description: string description: string;
setDescription: (description: string) => void setDescription: (description: string) => void;
location: string location: string;
setLocation: (location: string) => void setLocation: (location: string) => void;
url: string url: string;
setUrl: (url: string) => void setUrl: (url: string) => void;
start: string start: string;
setStart: (start: string) => void setStart: (start: string) => void;
end: string end: string;
setEnd: (end: string) => void setEnd: (end: string) => void;
allDay: boolean allDay: boolean;
setAllDay: (allDay: boolean) => void setAllDay: (allDay: boolean) => void;
recurrenceRule: string | undefined recurrenceRule: string | undefined;
setRecurrenceRule: (rule: string | undefined) => void setRecurrenceRule: (rule: string | undefined) => void;
onSave: () => void onSave: () => void;
onReset: () => void onReset: () => void;
} }
export const EventDialog = ({ export const EventDialog = ({
@@ -48,49 +54,81 @@ export const EventDialog = ({
recurrenceRule, recurrenceRule,
setRecurrenceRule, setRecurrenceRule,
onSave, onSave,
onReset onReset,
}: EventDialogProps) => { }: EventDialogProps) => {
const handleOpenChange = (val: boolean) => { const handleOpenChange = (val: boolean) => {
if (!val) onReset() if (!val) onReset();
onOpenChange(val) onOpenChange(val);
} };
return ( return (
<Dialog open={open} onOpenChange={handleOpenChange}> <Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent> <DialogContent>
<DialogHeader> <DialogHeader>
<DialogTitle>{editingId ? 'Edit Event' : 'Add Event'}</DialogTitle> <DialogTitle>{editingId ? "Edit Event" : "Add Event"}</DialogTitle>
</DialogHeader> </DialogHeader>
<Input placeholder="Title" value={title} onChange={e => setTitle(e.target.value)} /> <Input
placeholder="Title"
value={title}
onChange={(e) => setTitle(e.target.value)}
/>
<textarea <textarea
className="border rounded p-2 w-full" className="border rounded p-2 w-full"
placeholder="Description" placeholder="Description"
value={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} /> <RecurrencePicker value={recurrenceRule} onChange={setRecurrenceRule} />
<label className="flex items-center gap-2 mt-2"> <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 All day event
</label> </label>
{!allDay ? ( {!allDay ? (
<> <>
<Input type="datetime-local" value={start} onChange={e => setStart(e.target.value)} /> <Input
<Input type="datetime-local" value={end} onChange={e => setEnd(e.target.value)} /> 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
<Input type="date" value={end ? end.split('T')[0] : ''} onChange={e => setEnd(e.target.value)} /> 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> <DialogFooter>
<Button onClick={onSave}>{editingId ? 'Update' : 'Save'}</Button> <Button onClick={onSave}>{editingId ? "Update" : "Save"}</Button>
</DialogFooter> </DialogFooter>
</DialogContent> </DialogContent>
</Dialog> </Dialog>
) );
} };

View File

@@ -1,27 +1,31 @@
import { Calendar1Icon } from 'lucide-react' import { Calendar1Icon } from "lucide-react";
import { EventCard } from './event-card' import { EventCard } from "./event-card";
import type { CalendarEvent } from '@/lib/types' import type { CalendarEvent } from "@/lib/types";
interface EventsListProps { interface EventsListProps {
events: CalendarEvent[] events: CalendarEvent[];
onEdit: (event: CalendarEvent) => void onEdit: (event: CalendarEvent) => void;
onDelete: (eventId: string) => void onDelete: (eventId: string) => void;
} }
export const EventsList = ({ events, onEdit, onDelete }: EventsListProps) => { export const EventsList = ({ events, onEdit, onDelete }: EventsListProps) => {
if (events.length === 0) { if (events.length === 0) {
return ( return (
<div className="flex flex-col items-center justify-center py-8 text-center"> <div className="flex flex-col items-center justify-center py-8 text-center">
<Calendar1Icon className='h-12 w-12 text-muted-foreground mb-4' /> <Calendar1Icon className="h-12 w-12 text-muted-foreground mb-4" />
<h3 className="text-lg font-medium text-muted-foreground">No events yet</h3> <h3 className="text-lg font-medium text-muted-foreground">
<p className="text-sm text-muted-foreground">Create your first event to get started</p> No events yet
</h3>
<p className="text-sm text-muted-foreground">
Create your first event to get started
</p>
</div> </div>
) );
} }
return ( return (
<div className="space-y-4"> <div className="space-y-4">
{events.map(event => ( {events.map((event) => (
<EventCard <EventCard
key={event.id} key={event.id}
event={event} event={event}
@@ -30,5 +34,5 @@ export const EventsList = ({ events, onEdit, onDelete }: EventsListProps) => {
/> />
))} ))}
</div> </div>
) );
} };

View File

@@ -1,17 +1,23 @@
"use client" "use client";
import type React from "react" import type React from "react";
import { useRef } from "react" import { useRef } from "react";
import { Button } from "@/components/ui/button" import { Button } from "@/components/ui/button";
import { Calendar } from "lucide-react" import { Calendar } from "lucide-react";
interface IcsFilePickerProps { interface IcsFilePickerProps {
onFileSelect?: (file: File) => void onFileSelect?: (file: File) => void;
className?: string className?: string;
children?: React.ReactNode children?: React.ReactNode;
variant?: "default" | "destructive" | "outline" | "secondary" | "ghost" | "link" variant?:
size?: "default" | "sm" | "lg" | "icon" | "default"
| "destructive"
| "outline"
| "secondary"
| "ghost"
| "link";
size?: "default" | "sm" | "lg" | "icon";
} }
export function IcsFilePicker({ export function IcsFilePicker({
@@ -21,18 +27,18 @@ export function IcsFilePicker({
variant = "default", variant = "default",
size = "default", size = "default",
}: IcsFilePickerProps) { }: IcsFilePickerProps) {
const fileInputRef = useRef<HTMLInputElement>(null) const fileInputRef = useRef<HTMLInputElement>(null);
const handleButtonClick = () => { const handleButtonClick = () => {
fileInputRef.current?.click() fileInputRef.current?.click();
} };
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => { const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0] const file = event.target.files?.[0];
if (file && onFileSelect) { if (file && onFileSelect) {
onFileSelect(file) onFileSelect(file);
}
} }
};
return ( return (
<> <>
@@ -44,7 +50,12 @@ export function IcsFilePicker({
className="hidden" className="hidden"
aria-hidden="true" aria-hidden="true"
/> />
<Button onClick={handleButtonClick} variant={variant} size={size} className={className}> <Button
onClick={handleButtonClick}
variant={variant}
size={size}
className={className}
>
{children || ( {children || (
<> <>
<Calendar className="mr-2 h-4 w-4" /> <Calendar className="mr-2 h-4 w-4" />
@@ -53,6 +64,5 @@ export function IcsFilePicker({
)} )}
</Button> </Button>
</> </>
) );
} }

View File

@@ -1,56 +1,55 @@
"use client" "use client";
import * as React from "react" import * as React from "react";
import { Moon, Sun, Monitor } from "lucide-react" import { Moon, Sun, Monitor } from "lucide-react";
import { useTheme } from "next-themes" import { useTheme } from "next-themes";
import { Button } from "@/components/ui/button" import { Button } from "@/components/ui/button";
import { import {
DropdownMenu, DropdownMenu,
DropdownMenuContent, DropdownMenuContent,
DropdownMenuItem, DropdownMenuItem,
DropdownMenuTrigger, DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu" } from "@/components/ui/dropdown-menu";
type ThemeIconProps = { type ThemeIconProps = {
theme?: string theme?: string;
} };
const ThemeIcon = ({ theme }: ThemeIconProps) => { const ThemeIcon = ({ theme }: ThemeIconProps) => {
const [mounted, setMounted] = React.useState(false);
const [mounted, setMounted] = React.useState(false)
React.useEffect(() => { React.useEffect(() => {
setMounted(true) setMounted(true);
}, []) }, []);
if (!mounted) { if (!mounted) {
return null return null;
} }
switch (theme) { switch (theme) {
case "light": case "light":
return ( return (
<Sun className="absolute h-[1.2rem] w-[1.2rem] scale-100 rotate-0 transition-all dark:scale-0 dark:-rotate-90" /> <Sun className="absolute h-[1.2rem] w-[1.2rem] scale-100 rotate-0 transition-all dark:scale-0 dark:-rotate-90" />
) );
case "dark": case "dark":
return ( return (
<Moon className="absolute h-[1.2rem] w-[1.2rem] scale-0 rotate-90 transition-all dark:scale-100 dark:rotate-0" /> <Moon className="absolute h-[1.2rem] w-[1.2rem] scale-0 rotate-90 transition-all dark:scale-100 dark:rotate-0" />
) );
case "system": case "system":
return ( return <Monitor className="absolute h-[1.2rem] w-[1.2rem] scale-100" />;
<Monitor className="absolute h-[1.2rem] w-[1.2rem] scale-100" />
)
default: default:
return (<> return (
<>
<Sun className="h-[1.2rem] w-[1.2rem] scale-100 rotate-0 transition-all dark:scale-0 dark:-rotate-90" /> <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" /> <Moon className="absolute h-[1.2rem] w-[1.2rem] scale-0 rotate-90 transition-all dark:scale-100 dark:rotate-0" />
</>) </>
} );
} }
};
export function ModeToggle() { export function ModeToggle() {
const { setTheme, theme } = useTheme() const { setTheme, theme } = useTheme();
return ( return (
<DropdownMenu> <DropdownMenu>
@@ -72,6 +71,5 @@ export function ModeToggle() {
</DropdownMenuItem> </DropdownMenuItem>
</DropdownMenuContent> </DropdownMenuContent>
</DropdownMenu> </DropdownMenu>
) );
} }

View File

@@ -1,65 +1,76 @@
"use client" "use client";
import { useState } from "react" import { useState } from "react";
import { Input } from "@/components/ui/input" import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label" import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select" import {
import { Checkbox } from "@/components/ui/checkbox" Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Checkbox } from "@/components/ui/checkbox";
type Recurrence = { type Recurrence = {
freq: "NONE" | "DAILY" | "WEEKLY" | "MONTHLY" freq: "NONE" | "DAILY" | "WEEKLY" | "MONTHLY";
interval: number interval: number;
byDay?: string[] byDay?: string[];
count?: number count?: number;
until?: string until?: string;
} };
interface Props { interface Props {
value?: string value?: string;
onChange: (rrule: string | undefined) => void onChange: (rrule: string | undefined) => void;
} }
export function RecurrencePicker({ value, onChange }: Props) { export function RecurrencePicker({ value, onChange }: Props) {
const [rec, setRec] = useState<Recurrence>(() => { const [rec, setRec] = useState<Recurrence>(() => {
// If existing rrule, parse minimally (for simplicity we only rehydrate FREQ and INTERVAL) // If existing rrule, parse minimally (for simplicity we only rehydrate FREQ and INTERVAL)
if (value) { if (value) {
const parts = Object.fromEntries(value.split(";").map((p) => p.split("="))) const parts = Object.fromEntries(
value.split(";").map((p) => p.split("=")),
);
return { return {
freq: parts.FREQ || "NONE", freq: parts.FREQ || "NONE",
interval: parts.INTERVAL ? Number.parseInt(parts.INTERVAL, 10) : 1, interval: parts.INTERVAL ? Number.parseInt(parts.INTERVAL, 10) : 1,
byDay: parts.BYDAY ? parts.BYDAY.split(",") : [], byDay: parts.BYDAY ? parts.BYDAY.split(",") : [],
count: parts.COUNT ? Number.parseInt(parts.COUNT, 10) : undefined, count: parts.COUNT ? Number.parseInt(parts.COUNT, 10) : undefined,
until: parts.UNTIL, until: parts.UNTIL,
};
} }
} return { freq: "NONE", interval: 1 };
return { freq: "NONE", interval: 1 } });
})
const update = (updates: Partial<Recurrence>) => { const update = (updates: Partial<Recurrence>) => {
const newRec = { ...rec, ...updates } const newRec = { ...rec, ...updates };
setRec(newRec) setRec(newRec);
if (newRec.freq === "NONE") { if (newRec.freq === "NONE") {
onChange(undefined) onChange(undefined);
return return;
} }
// Build RRULE string // 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) { 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.count) rrule += `;COUNT=${newRec.count}`;
if (newRec.until) rrule += `;UNTIL=${newRec.until.replace(/-/g, "")}T000000Z` if (newRec.until)
rrule += `;UNTIL=${newRec.until.replace(/-/g, "")}T000000Z`;
onChange(rrule) onChange(rrule);
} };
const toggleDay = (day: string) => { const toggleDay = (day: string) => {
const byDay = rec.byDay || [] const byDay = rec.byDay || [];
const newByDay = byDay.includes(day) ? byDay.filter((d) => d !== day) : [...byDay, day] const newByDay = byDay.includes(day)
update({ byDay: newByDay }) ? byDay.filter((d) => d !== day)
} : [...byDay, day];
update({ byDay: newByDay });
};
const dayLabels = { const dayLabels = {
MO: "Mon", MO: "Mon",
@@ -69,13 +80,20 @@ export function RecurrencePicker({ value, onChange }: Props) {
FR: "Fri", FR: "Fri",
SA: "Sat", SA: "Sat",
SU: "Sun", SU: "Sun",
} };
return ( return (
<div className=""> <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"> <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"> <SelectTrigger id="frequency">
<SelectValue /> <SelectValue />
</SelectTrigger> </SelectTrigger>
@@ -92,7 +110,12 @@ export function RecurrencePicker({ value, onChange }: Props) {
<> <>
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="interval"> <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" : ""}) {rec.interval > 1 ? "s" : ""})
</Label> </Label>
<Input <Input
@@ -100,7 +123,9 @@ export function RecurrencePicker({ value, onChange }: Props) {
type="number" type="number"
min={1} min={1}
value={rec.interval} 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" className="w-24"
/> />
</div> </div>
@@ -133,7 +158,13 @@ export function RecurrencePicker({ value, onChange }: Props) {
type="number" type="number"
placeholder="e.g. 10" placeholder="e.g. 10"
value={rec.count || ""} 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>
<div className="space-y-2"> <div className="space-y-2">
@@ -149,5 +180,5 @@ export function RecurrencePicker({ value, onChange }: Props) {
</> </>
)} )}
</div> </div>
) );
} }

View File

@@ -1,32 +1,38 @@
import { Badge } from "@/components/ui/badge" import { Badge } from "@/components/ui/badge";
import type { RecurrenceRule } from "@/lib/rfc5545-types" import type { RecurrenceRule } from "@/lib/rfc5545-types";
interface RRuleDisplayProps { interface RRuleDisplayProps {
rrule: string | RecurrenceRule rrule: string | RecurrenceRule;
className?: string className?: string;
} }
export function RRuleDisplay({ rrule, className }: RRuleDisplayProps) { export function RRuleDisplay({ rrule, className }: RRuleDisplayProps) {
const parsedRule = typeof rrule === 'string' ? parseRRuleString(rrule) : rrule const parsedRule =
const humanText = formatRRuleToHuman(parsedRule) typeof rrule === "string" ? parseRRuleString(rrule) : rrule;
const humanText = formatRRuleToHuman(parsedRule);
return ( return (
<div className={className}> <div className={className}>
<span className="text-sm text-muted-foreground">{humanText}</span> <span className="text-sm text-muted-foreground">{humanText}</span>
</div> </div>
) );
} }
interface RRuleDisplayDetailedProps { interface RRuleDisplayDetailedProps {
rrule: string | RecurrenceRule rrule: string | RecurrenceRule;
className?: string className?: string;
showBadges?: boolean showBadges?: boolean;
} }
export function RRuleDisplayDetailed({ rrule, className, showBadges = true }: RRuleDisplayDetailedProps) { export function RRuleDisplayDetailed({
const parsedRule = typeof rrule === 'string' ? parseRRuleString(rrule) : rrule rrule,
const humanText = formatRRuleToHuman(parsedRule) className,
const details = getRRuleDetails(parsedRule) showBadges = true,
}: RRuleDisplayDetailedProps) {
const parsedRule =
typeof rrule === "string" ? parseRRuleString(rrule) : rrule;
const humanText = formatRRuleToHuman(parsedRule);
const details = getRRuleDetails(parsedRule);
return ( return (
<div className={className}> <div className={className}>
@@ -44,201 +50,257 @@ export function RRuleDisplayDetailed({ rrule, className, showBadges = true }: RR
)} )}
</div> </div>
</div> </div>
) );
} }
function parseRRuleString(rruleString: string): RecurrenceRule { 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 { return {
freq: parts.FREQ as RecurrenceRule['freq'], 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, 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, count: parts.COUNT ? parseInt(parts.COUNT, 10) : undefined,
interval: parts.INTERVAL ? parseInt(parts.INTERVAL, 10) : undefined, interval: parts.INTERVAL ? parseInt(parts.INTERVAL, 10) : undefined,
bySecond: parts.BYSECOND ? parts.BYSECOND.split(",").map((n: string) => parseInt(n, 10)) : undefined, bySecond: parts.BYSECOND
byMinute: parts.BYMINUTE ? parts.BYMINUTE.split(",").map((n: string) => parseInt(n, 10)) : undefined, ? parts.BYSECOND.split(",").map((n: string) => parseInt(n, 10))
byHour: parts.BYHOUR ? parts.BYHOUR.split(",").map((n: string) => parseInt(n, 10)) : undefined, : 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, byDay: parts.BYDAY ? parts.BYDAY.split(",") : undefined,
byMonthDay: parts.BYMONTHDAY ? parts.BYMONTHDAY.split(",").map((n: string) => parseInt(n, 10)) : undefined, byMonthDay: parts.BYMONTHDAY
byYearDay: parts.BYYEARDAY ? parts.BYYEARDAY.split(",").map((n: string) => parseInt(n, 10)) : undefined, ? parts.BYMONTHDAY.split(",").map((n: string) => parseInt(n, 10))
byWeekNo: parts.BYWEEKNO ? parts.BYWEEKNO.split(",").map((n: string) => parseInt(n, 10)) : undefined, : undefined,
byMonth: parts.BYMONTH ? parts.BYMONTH.split(",").map((n: string) => parseInt(n, 10)) : undefined, byYearDay: parts.BYYEARDAY
bySetPos: parts.BYSETPOS ? parts.BYSETPOS.split(",").map((n: string) => parseInt(n, 10)) : undefined, ? parts.BYYEARDAY.split(",").map((n: string) => parseInt(n, 10))
wkst: parts.WKST as RecurrenceRule['wkst'], : 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 { 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 // Base frequency
switch (freq) { switch (freq) {
case 'SECONDLY': case "SECONDLY":
text = interval === 1 ? "Every second" : `Every ${interval} seconds` text = interval === 1 ? "Every second" : `Every ${interval} seconds`;
break break;
case 'MINUTELY': case "MINUTELY":
text = interval === 1 ? "Every minute" : `Every ${interval} minutes` text = interval === 1 ? "Every minute" : `Every ${interval} minutes`;
break break;
case 'HOURLY': case "HOURLY":
text = interval === 1 ? "Every hour" : `Every ${interval} hours` text = interval === 1 ? "Every hour" : `Every ${interval} hours`;
break break;
case 'DAILY': case "DAILY":
text = interval === 1 ? "Daily" : `Every ${interval} days` text = interval === 1 ? "Daily" : `Every ${interval} days`;
break break;
case 'WEEKLY': case "WEEKLY":
text = interval === 1 ? "Weekly" : `Every ${interval} weeks` text = interval === 1 ? "Weekly" : `Every ${interval} weeks`;
break break;
case 'MONTHLY': case "MONTHLY":
text = interval === 1 ? "Monthly" : `Every ${interval} months` text = interval === 1 ? "Monthly" : `Every ${interval} months`;
break break;
case 'YEARLY': case "YEARLY":
text = interval === 1 ? "Yearly" : `Every ${interval} years` text = interval === 1 ? "Yearly" : `Every ${interval} years`;
break break;
} }
// Add day specifications // Add day specifications
if (byDay?.length) { if (byDay?.length) {
const dayNames = { const dayNames = {
'SU': 'Sunday', 'MO': 'Monday', 'TU': 'Tuesday', 'WE': 'Wednesday', SU: "Sunday",
'TH': 'Thursday', 'FR': 'Friday', 'SA': 'Saturday' 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) // 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) { if (match) {
const [, num, dayCode] = match const [, num, dayCode] = match;
const dayName = dayNames[dayCode as keyof typeof dayNames] const dayName = dayNames[dayCode as keyof typeof dayNames];
if (num) { if (num) {
const ordinal = getOrdinal(parseInt(num)) const ordinal = getOrdinal(parseInt(num));
return `${ordinal} ${dayName}` return `${ordinal} ${dayName}`;
} }
return dayName return dayName;
} }
return day return day;
}) });
if (freq === 'WEEKLY') { if (freq === "WEEKLY") {
text += ` on ${formatList(days)}` text += ` on ${formatList(days)}`;
} else { } else {
text += ` on ${formatList(days)}` text += ` on ${formatList(days)}`;
} }
} }
// Add month day specifications // Add month day specifications
if (byMonthDay?.length) { if (byMonthDay?.length) {
const days = byMonthDay.map(day => { const days = byMonthDay.map((day) => {
if (day < 0) { if (day < 0) {
return `${getOrdinal(Math.abs(day))} to last day` return `${getOrdinal(Math.abs(day))} to last day`;
} }
return getOrdinal(day) return getOrdinal(day);
}) });
text += ` on the ${formatList(days)}` text += ` on the ${formatList(days)}`;
} }
// Add month specifications // Add month specifications
if (byMonth?.length) { if (byMonth?.length) {
const monthNames = [ const monthNames = [
'January', 'February', 'March', 'April', 'May', 'June', "January",
'July', 'August', 'September', 'October', 'November', 'December' "February",
] "March",
const months = byMonth.map(month => monthNames[month - 1]) "April",
text += ` in ${formatList(months)}` "May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
];
const months = byMonth.map((month) => monthNames[month - 1]);
text += ` in ${formatList(months)}`;
} }
// Add time specifications // Add time specifications
if (byHour?.length || byMinute?.length || bySecond?.length) { if (byHour?.length || byMinute?.length || bySecond?.length) {
const timeSpecs = [] const timeSpecs = [];
if (byHour?.length) { if (byHour?.length) {
const hours = byHour.map(h => `${h.toString().padStart(2, '0')}:00`) const hours = byHour.map((h) => `${h.toString().padStart(2, "0")}:00`);
timeSpecs.push(`at ${formatList(hours)}`) timeSpecs.push(`at ${formatList(hours)}`);
} }
if (byMinute?.length && !byHour?.length) { 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) { 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) { if (timeSpecs.length) {
text += ` ${timeSpecs.join(' ')}` text += ` ${timeSpecs.join(" ")}`;
} }
} }
// Add end conditions // Add end conditions
if (count) { if (count) {
text += `, ${count} time${count === 1 ? '' : 's'}` text += `, ${count} time${count === 1 ? "" : "s"}`;
} else if (until) { } else if (until) {
const date = new Date(until) const date = new Date(until);
text += `, until ${date.toLocaleDateString()}` text += `, until ${date.toLocaleDateString()}`;
} }
return text return text;
} }
function getRRuleDetails(rule: RecurrenceRule): string[] { 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 = { const dayNames = {
'SU': 'Sunday', 'MO': 'Monday', 'TU': 'Tuesday', 'WE': 'Wednesday', SU: "Sunday",
'TH': 'Thursday', 'FR': 'Friday', 'SA': 'Saturday' MO: "Monday",
} TU: "Tuesday",
details.push(`Week starts ${dayNames[rule.wkst]}`) WE: "Wednesday",
TH: "Thursday",
FR: "Friday",
SA: "Saturday",
};
details.push(`Week starts ${dayNames[rule.wkst]}`);
} }
if (rule.byWeekNo?.length) { if (rule.byWeekNo?.length) {
details.push(`Week ${formatList(rule.byWeekNo.map(String))}`) details.push(`Week ${formatList(rule.byWeekNo.map(String))}`);
} }
if (rule.byYearDay?.length) { 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) { if (rule.bySetPos?.length) {
const positions = rule.bySetPos.map(pos => { const positions = rule.bySetPos.map((pos) => {
if (pos < 0) { if (pos < 0) {
return `${getOrdinal(Math.abs(pos))} to last` return `${getOrdinal(Math.abs(pos))} to last`;
} }
return getOrdinal(pos) return getOrdinal(pos);
}) });
details.push(`Position ${formatList(positions)}`) details.push(`Position ${formatList(positions)}`);
} }
return details return details;
} }
function getOrdinal(num: number): string { function getOrdinal(num: number): string {
const suffix = ['th', 'st', 'nd', 'rd'] const suffix = ["th", "st", "nd", "rd"];
const v = num % 100 const v = num % 100;
return num + (suffix[(v - 20) % 10] || suffix[v] || suffix[0]) return num + (suffix[(v - 20) % 10] || suffix[v] || suffix[0]);
} }
function formatList(items: string[]): string { function formatList(items: string[]): string {
if (items.length === 0) return '' if (items.length === 0) return "";
if (items.length === 1) return items[0] if (items.length === 1) return items[0];
if (items.length === 2) return `${items[0]} and ${items[1]}` if (items.length === 2) return `${items[0]} and ${items[1]}`;
return `${items.slice(0, -1).join(', ')}, and ${items[items.length - 1]}` return `${items.slice(0, -1).join(", ")}, and ${items[items.length - 1]}`;
} }
// Hook for easy usage in components // Hook for easy usage in components
export function useRRuleDisplay(rrule?: string) { export function useRRuleDisplay(rrule?: string) {
if (!rrule) return null if (!rrule) return null;
try { try {
const parsedRule = parseRRuleString(rrule) const parsedRule = parseRRuleString(rrule);
return { return {
humanText: formatRRuleToHuman(parsedRule), humanText: formatRRuleToHuman(parsedRule),
details: getRRuleDetails(parsedRule), details: getRRuleDetails(parsedRule),
parsedRule parsedRule,
} };
} catch (error) { } catch (error) {
return { return {
humanText: "Invalid recurrence rule", humanText: "Invalid recurrence rule",
details: [], details: [],
parsedRule: null, parsedRule: null,
error: error instanceof Error ? error.message : String(error) error: error instanceof Error ? error.message : String(error),
} };
} }
} }

View File

@@ -1,25 +1,25 @@
"use client" "use client";
import { signOut, useSession } from "@/lib/auth-client" import { signOut, useSession } from "@/lib/auth-client";
import { Button } from "@/components/ui/button" import { Button } from "@/components/ui/button";
import { useRouter } from "next/navigation" import { useRouter } from "next/navigation";
import { toast } from "sonner" import { toast } from "sonner";
export default function SignIn() { export default function SignIn() {
const { data: session, isPending } = useSession() const { data: session, isPending } = useSession();
const router = useRouter() const router = useRouter();
const handleSignOut = async () => { const handleSignOut = async () => {
try { try {
await signOut() await signOut();
router.push("/") router.push("/");
} catch (_error) { } catch (_error) {
toast.error("Failed to sign out. Please try again.") toast.error("Failed to sign out. Please try again.");
}
} }
};
if (isPending) { 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) { if (session?.user) {
@@ -29,7 +29,7 @@ export default function SignIn() {
Sign Out Sign Out
</Button> </Button>
</div> </div>
) );
} }
return ( return (
@@ -40,5 +40,5 @@ export default function SignIn() {
> >
Sign In Sign In
</Button> </Button>
) );
} }

View File

@@ -1,11 +1,11 @@
"use client" "use client";
import * as React from "react" import * as React from "react";
import { ThemeProvider as NextThemesProvider } from "next-themes" import { ThemeProvider as NextThemesProvider } from "next-themes";
export function ThemeProvider({ export function ThemeProvider({
children, children,
...props ...props
}: React.ComponentProps<typeof NextThemesProvider>) { }: React.ComponentProps<typeof NextThemesProvider>) {
return <NextThemesProvider {...props}>{children}</NextThemesProvider> return <NextThemesProvider {...props}>{children}</NextThemesProvider>;
} }

View File

@@ -1,8 +1,8 @@
import * as React from "react" import * as React from "react";
import { Slot } from "@radix-ui/react-slot" import { Slot } from "@radix-ui/react-slot";
import { cva, type VariantProps } from "class-variance-authority" import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils" import { cn } from "@/lib/utils";
const badgeVariants = cva( 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", "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: { defaultVariants: {
variant: "default", variant: "default",
}, },
} },
) );
function Badge({ function Badge({
className, className,
@@ -32,7 +32,7 @@ function Badge({
...props ...props
}: React.ComponentProps<"span"> & }: React.ComponentProps<"span"> &
VariantProps<typeof badgeVariants> & { asChild?: boolean }) { VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
const Comp = asChild ? Slot : "span" const Comp = asChild ? Slot : "span";
return ( return (
<Comp <Comp
@@ -40,7 +40,7 @@ function Badge({
className={cn(badgeVariants({ variant }), className)} className={cn(badgeVariants({ variant }), className)}
{...props} {...props}
/> />
) );
} }
export { Badge, badgeVariants } export { Badge, badgeVariants };

View File

@@ -1,8 +1,8 @@
import * as React from "react" import * as React from "react";
import { Slot } from "@radix-ui/react-slot" import { Slot } from "@radix-ui/react-slot";
import { cva, type VariantProps } from "class-variance-authority" import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils" import { cn } from "@/lib/utils";
const buttonVariants = cva( 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", "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", variant: "default",
size: "default", size: "default",
}, },
} },
) );
function Button({ function Button({
className, className,
@@ -43,9 +43,9 @@ function Button({
...props ...props
}: React.ComponentProps<"button"> & }: React.ComponentProps<"button"> &
VariantProps<typeof buttonVariants> & { VariantProps<typeof buttonVariants> & {
asChild?: boolean asChild?: boolean;
}) { }) {
const Comp = asChild ? Slot : "button" const Comp = asChild ? Slot : "button";
return ( return (
<Comp <Comp
@@ -53,7 +53,7 @@ function Button({
className={cn(buttonVariants({ variant, size, className }))} className={cn(buttonVariants({ variant, size, className }))}
{...props} {...props}
/> />
) );
} }
export { Button, buttonVariants } export { Button, buttonVariants };

View File

@@ -1,15 +1,15 @@
"use client" "use client";
import * as React from "react" import * as React from "react";
import { import {
ChevronDownIcon, ChevronDownIcon,
ChevronLeftIcon, ChevronLeftIcon,
ChevronRightIcon, ChevronRightIcon,
} from "lucide-react" } from "lucide-react";
import { DayButton, DayPicker, getDefaultClassNames } from "react-day-picker" import { DayButton, DayPicker, getDefaultClassNames } from "react-day-picker";
import { cn } from "@/lib/utils" import { cn } from "@/lib/utils";
import { Button, buttonVariants } from "@/components/ui/button" import { Button, buttonVariants } from "@/components/ui/button";
function Calendar({ function Calendar({
className, className,
@@ -21,9 +21,9 @@ function Calendar({
components, components,
...props ...props
}: React.ComponentProps<typeof DayPicker> & { }: React.ComponentProps<typeof DayPicker> & {
buttonVariant?: React.ComponentProps<typeof Button>["variant"] buttonVariant?: React.ComponentProps<typeof Button>["variant"];
}) { }) {
const defaultClassNames = getDefaultClassNames() const defaultClassNames = getDefaultClassNames();
return ( return (
<DayPicker <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", "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\_next>svg]:rotate-180`,
String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`, String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`,
className className,
)} )}
captionLayout={captionLayout} captionLayout={captionLayout}
formatters={{ formatters={{
@@ -44,82 +44,82 @@ function Calendar({
root: cn("w-fit", defaultClassNames.root), root: cn("w-fit", defaultClassNames.root),
months: cn( months: cn(
"flex gap-4 flex-col md:flex-row relative", "flex gap-4 flex-col md:flex-row relative",
defaultClassNames.months defaultClassNames.months,
), ),
month: cn("flex flex-col w-full gap-4", defaultClassNames.month), month: cn("flex flex-col w-full gap-4", defaultClassNames.month),
nav: cn( nav: cn(
"flex items-center gap-1 w-full absolute top-0 inset-x-0 justify-between", "flex items-center gap-1 w-full absolute top-0 inset-x-0 justify-between",
defaultClassNames.nav defaultClassNames.nav,
), ),
button_previous: cn( button_previous: cn(
buttonVariants({ variant: buttonVariant }), buttonVariants({ variant: buttonVariant }),
"size-(--cell-size) aria-disabled:opacity-50 p-0 select-none", "size-(--cell-size) aria-disabled:opacity-50 p-0 select-none",
defaultClassNames.button_previous defaultClassNames.button_previous,
), ),
button_next: cn( button_next: cn(
buttonVariants({ variant: buttonVariant }), buttonVariants({ variant: buttonVariant }),
"size-(--cell-size) aria-disabled:opacity-50 p-0 select-none", "size-(--cell-size) aria-disabled:opacity-50 p-0 select-none",
defaultClassNames.button_next defaultClassNames.button_next,
), ),
month_caption: cn( month_caption: cn(
"flex items-center justify-center h-(--cell-size) w-full px-(--cell-size)", "flex items-center justify-center h-(--cell-size) w-full px-(--cell-size)",
defaultClassNames.month_caption defaultClassNames.month_caption,
), ),
dropdowns: cn( dropdowns: cn(
"w-full flex items-center text-sm font-medium justify-center h-(--cell-size) gap-1.5", "w-full flex items-center text-sm font-medium justify-center h-(--cell-size) gap-1.5",
defaultClassNames.dropdowns defaultClassNames.dropdowns,
), ),
dropdown_root: cn( dropdown_root: cn(
"relative has-focus:border-ring border border-input shadow-xs has-focus:ring-ring/50 has-focus:ring-[3px] rounded-md", "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( dropdown: cn(
"absolute bg-popover inset-0 opacity-0", "absolute bg-popover inset-0 opacity-0",
defaultClassNames.dropdown defaultClassNames.dropdown,
), ),
caption_label: cn( caption_label: cn(
"select-none font-medium", "select-none font-medium",
captionLayout === "label" captionLayout === "label"
? "text-sm" ? "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", : "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", table: "w-full border-collapse",
weekdays: cn("flex", defaultClassNames.weekdays), weekdays: cn("flex", defaultClassNames.weekdays),
weekday: cn( weekday: cn(
"text-muted-foreground rounded-md flex-1 font-normal text-[0.8rem] select-none", "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: cn("flex w-full mt-2", defaultClassNames.week),
week_number_header: cn( week_number_header: cn(
"select-none w-(--cell-size)", "select-none w-(--cell-size)",
defaultClassNames.week_number_header defaultClassNames.week_number_header,
), ),
week_number: cn( week_number: cn(
"text-[0.8rem] select-none text-muted-foreground", "text-[0.8rem] select-none text-muted-foreground",
defaultClassNames.week_number defaultClassNames.week_number,
), ),
day: cn( 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", "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( range_start: cn(
"rounded-l-md bg-accent", "rounded-l-md bg-accent",
defaultClassNames.range_start defaultClassNames.range_start,
), ),
range_middle: cn("rounded-none", defaultClassNames.range_middle), range_middle: cn("rounded-none", defaultClassNames.range_middle),
range_end: cn("rounded-r-md bg-accent", defaultClassNames.range_end), range_end: cn("rounded-r-md bg-accent", defaultClassNames.range_end),
today: cn( today: cn(
"bg-accent text-accent-foreground rounded-md data-[selected=true]:rounded-none", "bg-accent text-accent-foreground rounded-md data-[selected=true]:rounded-none",
defaultClassNames.today defaultClassNames.today,
), ),
outside: cn( outside: cn(
"text-muted-foreground aria-selected:text-muted-foreground", "text-muted-foreground aria-selected:text-muted-foreground",
defaultClassNames.outside defaultClassNames.outside,
), ),
disabled: cn( disabled: cn(
"text-muted-foreground opacity-50", "text-muted-foreground opacity-50",
defaultClassNames.disabled defaultClassNames.disabled,
), ),
hidden: cn("invisible", defaultClassNames.hidden), hidden: cn("invisible", defaultClassNames.hidden),
...classNames, ...classNames,
@@ -133,13 +133,13 @@ function Calendar({
className={cn(className)} className={cn(className)}
{...props} {...props}
/> />
) );
}, },
Chevron: ({ className, orientation, ...props }) => { Chevron: ({ className, orientation, ...props }) => {
if (orientation === "left") { if (orientation === "left") {
return ( return (
<ChevronLeftIcon className={cn("size-4", className)} {...props} /> <ChevronLeftIcon className={cn("size-4", className)} {...props} />
) );
} }
if (orientation === "right") { if (orientation === "right") {
@@ -148,12 +148,12 @@ function Calendar({
className={cn("size-4", className)} className={cn("size-4", className)}
{...props} {...props}
/> />
) );
} }
return ( return (
<ChevronDownIcon className={cn("size-4", className)} {...props} /> <ChevronDownIcon className={cn("size-4", className)} {...props} />
) );
}, },
DayButton: CalendarDayButton, DayButton: CalendarDayButton,
WeekNumber: ({ children, ...props }) => { WeekNumber: ({ children, ...props }) => {
@@ -163,13 +163,13 @@ function Calendar({
{children} {children}
</div> </div>
</td> </td>
) );
}, },
...components, ...components,
}} }}
{...props} {...props}
/> />
) );
} }
function CalendarDayButton({ function CalendarDayButton({
@@ -178,12 +178,12 @@ function CalendarDayButton({
modifiers, modifiers,
...props ...props
}: React.ComponentProps<typeof DayButton>) { }: React.ComponentProps<typeof DayButton>) {
const defaultClassNames = getDefaultClassNames() const defaultClassNames = getDefaultClassNames();
const ref = React.useRef<HTMLButtonElement>(null) const ref = React.useRef<HTMLButtonElement>(null);
React.useEffect(() => { React.useEffect(() => {
if (modifiers.focused) ref.current?.focus() if (modifiers.focused) ref.current?.focus();
}, [modifiers.focused]) }, [modifiers.focused]);
return ( return (
<Button <Button
@@ -203,11 +203,11 @@ function CalendarDayButton({
className={cn( 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", "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, defaultClassNames.day,
className className,
)} )}
{...props} {...props}
/> />
) );
} }
export { Calendar, CalendarDayButton } export { Calendar, CalendarDayButton };

View File

@@ -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">) { function Card({ className, ...props }: React.ComponentProps<"div">) {
return ( return (
@@ -8,11 +8,11 @@ function Card({ className, ...props }: React.ComponentProps<"div">) {
data-slot="card" data-slot="card"
className={cn( className={cn(
"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm", "bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",
className className,
)} )}
{...props} {...props}
/> />
) );
} }
function CardHeader({ className, ...props }: React.ComponentProps<"div">) { function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
@@ -21,11 +21,11 @@ function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
data-slot="card-header" data-slot="card-header"
className={cn( 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", "@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} {...props}
/> />
) );
} }
function CardTitle({ className, ...props }: React.ComponentProps<"div">) { 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)} className={cn("leading-none font-semibold", className)}
{...props} {...props}
/> />
) );
} }
function CardDescription({ className, ...props }: React.ComponentProps<"div">) { 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)} className={cn("text-muted-foreground text-sm", className)}
{...props} {...props}
/> />
) );
} }
function CardAction({ className, ...props }: React.ComponentProps<"div">) { function CardAction({ className, ...props }: React.ComponentProps<"div">) {
@@ -54,11 +54,11 @@ function CardAction({ className, ...props }: React.ComponentProps<"div">) {
data-slot="card-action" data-slot="card-action"
className={cn( className={cn(
"col-start-2 row-span-2 row-start-1 self-start justify-self-end", "col-start-2 row-span-2 row-start-1 self-start justify-self-end",
className className,
)} )}
{...props} {...props}
/> />
) );
} }
function CardContent({ className, ...props }: React.ComponentProps<"div">) { function CardContent({ className, ...props }: React.ComponentProps<"div">) {
@@ -68,7 +68,7 @@ function CardContent({ className, ...props }: React.ComponentProps<"div">) {
className={cn("px-6", className)} className={cn("px-6", className)}
{...props} {...props}
/> />
) );
} }
function CardFooter({ className, ...props }: React.ComponentProps<"div">) { 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)} className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
{...props} {...props}
/> />
) );
} }
export { export {
@@ -89,4 +89,4 @@ export {
CardAction, CardAction,
CardDescription, CardDescription,
CardContent, CardContent,
} };

View File

@@ -1,10 +1,10 @@
"use client" "use client";
import * as React from "react" import * as React from "react";
import * as CheckboxPrimitive from "@radix-ui/react-checkbox" import * as CheckboxPrimitive from "@radix-ui/react-checkbox";
import { CheckIcon } from "lucide-react" import { CheckIcon } from "lucide-react";
import { cn } from "@/lib/utils" import { cn } from "@/lib/utils";
function Checkbox({ function Checkbox({
className, className,
@@ -15,7 +15,7 @@ function Checkbox({
data-slot="checkbox" data-slot="checkbox"
className={cn( 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", "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} {...props}
> >
@@ -26,7 +26,7 @@ function Checkbox({
<CheckIcon className="size-3.5" /> <CheckIcon className="size-3.5" />
</CheckboxPrimitive.Indicator> </CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root> </CheckboxPrimitive.Root>
) );
} }
export { Checkbox } export { Checkbox };

View File

@@ -1,33 +1,33 @@
"use client" "use client";
import * as React from "react" import * as React from "react";
import * as DialogPrimitive from "@radix-ui/react-dialog" import * as DialogPrimitive from "@radix-ui/react-dialog";
import { XIcon } from "lucide-react" import { XIcon } from "lucide-react";
import { cn } from "@/lib/utils" import { cn } from "@/lib/utils";
function Dialog({ function Dialog({
...props ...props
}: React.ComponentProps<typeof DialogPrimitive.Root>) { }: React.ComponentProps<typeof DialogPrimitive.Root>) {
return <DialogPrimitive.Root data-slot="dialog" {...props} /> return <DialogPrimitive.Root data-slot="dialog" {...props} />;
} }
function DialogTrigger({ function DialogTrigger({
...props ...props
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) { }: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} /> return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />;
} }
function DialogPortal({ function DialogPortal({
...props ...props
}: React.ComponentProps<typeof DialogPrimitive.Portal>) { }: React.ComponentProps<typeof DialogPrimitive.Portal>) {
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} /> return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />;
} }
function DialogClose({ function DialogClose({
...props ...props
}: React.ComponentProps<typeof DialogPrimitive.Close>) { }: React.ComponentProps<typeof DialogPrimitive.Close>) {
return <DialogPrimitive.Close data-slot="dialog-close" {...props} /> return <DialogPrimitive.Close data-slot="dialog-close" {...props} />;
} }
function DialogOverlay({ function DialogOverlay({
@@ -39,11 +39,11 @@ function DialogOverlay({
data-slot="dialog-overlay" data-slot="dialog-overlay"
className={cn( 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", "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} {...props}
/> />
) );
} }
function DialogContent({ function DialogContent({
@@ -52,7 +52,7 @@ function DialogContent({
showCloseButton = true, showCloseButton = true,
...props ...props
}: React.ComponentProps<typeof DialogPrimitive.Content> & { }: React.ComponentProps<typeof DialogPrimitive.Content> & {
showCloseButton?: boolean showCloseButton?: boolean;
}) { }) {
return ( return (
<DialogPortal data-slot="dialog-portal"> <DialogPortal data-slot="dialog-portal">
@@ -61,7 +61,7 @@ function DialogContent({
data-slot="dialog-content" data-slot="dialog-content"
className={cn( 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", "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} {...props}
> >
@@ -77,7 +77,7 @@ function DialogContent({
)} )}
</DialogPrimitive.Content> </DialogPrimitive.Content>
</DialogPortal> </DialogPortal>
) );
} }
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) { 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)} className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
{...props} {...props}
/> />
) );
} }
function DialogFooter({ className, ...props }: React.ComponentProps<"div">) { function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
@@ -96,11 +96,11 @@ function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
data-slot="dialog-footer" data-slot="dialog-footer"
className={cn( className={cn(
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end", "flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
className className,
)} )}
{...props} {...props}
/> />
) );
} }
function DialogTitle({ function DialogTitle({
@@ -113,7 +113,7 @@ function DialogTitle({
className={cn("text-lg leading-none font-semibold", className)} className={cn("text-lg leading-none font-semibold", className)}
{...props} {...props}
/> />
) );
} }
function DialogDescription({ function DialogDescription({
@@ -126,7 +126,7 @@ function DialogDescription({
className={cn("text-muted-foreground text-sm", className)} className={cn("text-muted-foreground text-sm", className)}
{...props} {...props}
/> />
) );
} }
export { export {
@@ -140,4 +140,4 @@ export {
DialogPortal, DialogPortal,
DialogTitle, DialogTitle,
DialogTrigger, DialogTrigger,
} };

View File

@@ -1,15 +1,15 @@
"use client" "use client";
import * as React from "react" import * as React from "react";
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu" import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu";
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react" import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react";
import { cn } from "@/lib/utils" import { cn } from "@/lib/utils";
function DropdownMenu({ function DropdownMenu({
...props ...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) { }: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} /> return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />;
} }
function DropdownMenuPortal({ function DropdownMenuPortal({
@@ -17,7 +17,7 @@ function DropdownMenuPortal({
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) { }: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
return ( return (
<DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} /> <DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
) );
} }
function DropdownMenuTrigger({ function DropdownMenuTrigger({
@@ -28,7 +28,7 @@ function DropdownMenuTrigger({
data-slot="dropdown-menu-trigger" data-slot="dropdown-menu-trigger"
{...props} {...props}
/> />
) );
} }
function DropdownMenuContent({ function DropdownMenuContent({
@@ -43,12 +43,12 @@ function DropdownMenuContent({
sideOffset={sideOffset} sideOffset={sideOffset}
className={cn( 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", "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} {...props}
/> />
</DropdownMenuPrimitive.Portal> </DropdownMenuPrimitive.Portal>
) );
} }
function DropdownMenuGroup({ function DropdownMenuGroup({
@@ -56,7 +56,7 @@ function DropdownMenuGroup({
}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) { }: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
return ( return (
<DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} /> <DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
) );
} }
function DropdownMenuItem({ function DropdownMenuItem({
@@ -65,8 +65,8 @@ function DropdownMenuItem({
variant = "default", variant = "default",
...props ...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & { }: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean inset?: boolean;
variant?: "default" | "destructive" variant?: "default" | "destructive";
}) { }) {
return ( return (
<DropdownMenuPrimitive.Item <DropdownMenuPrimitive.Item
@@ -75,11 +75,11 @@ function DropdownMenuItem({
data-variant={variant} data-variant={variant}
className={cn( 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", "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} {...props}
/> />
) );
} }
function DropdownMenuCheckboxItem({ function DropdownMenuCheckboxItem({
@@ -93,7 +93,7 @@ function DropdownMenuCheckboxItem({
data-slot="dropdown-menu-checkbox-item" data-slot="dropdown-menu-checkbox-item"
className={cn( 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", "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} checked={checked}
{...props} {...props}
@@ -105,7 +105,7 @@ function DropdownMenuCheckboxItem({
</span> </span>
{children} {children}
</DropdownMenuPrimitive.CheckboxItem> </DropdownMenuPrimitive.CheckboxItem>
) );
} }
function DropdownMenuRadioGroup({ function DropdownMenuRadioGroup({
@@ -116,7 +116,7 @@ function DropdownMenuRadioGroup({
data-slot="dropdown-menu-radio-group" data-slot="dropdown-menu-radio-group"
{...props} {...props}
/> />
) );
} }
function DropdownMenuRadioItem({ function DropdownMenuRadioItem({
@@ -129,7 +129,7 @@ function DropdownMenuRadioItem({
data-slot="dropdown-menu-radio-item" data-slot="dropdown-menu-radio-item"
className={cn( 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", "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} {...props}
> >
@@ -140,7 +140,7 @@ function DropdownMenuRadioItem({
</span> </span>
{children} {children}
</DropdownMenuPrimitive.RadioItem> </DropdownMenuPrimitive.RadioItem>
) );
} }
function DropdownMenuLabel({ function DropdownMenuLabel({
@@ -148,7 +148,7 @@ function DropdownMenuLabel({
inset, inset,
...props ...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & { }: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
inset?: boolean inset?: boolean;
}) { }) {
return ( return (
<DropdownMenuPrimitive.Label <DropdownMenuPrimitive.Label
@@ -156,11 +156,11 @@ function DropdownMenuLabel({
data-inset={inset} data-inset={inset}
className={cn( className={cn(
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8", "px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
className className,
)} )}
{...props} {...props}
/> />
) );
} }
function DropdownMenuSeparator({ function DropdownMenuSeparator({
@@ -173,7 +173,7 @@ function DropdownMenuSeparator({
className={cn("bg-border -mx-1 my-1 h-px", className)} className={cn("bg-border -mx-1 my-1 h-px", className)}
{...props} {...props}
/> />
) );
} }
function DropdownMenuShortcut({ function DropdownMenuShortcut({
@@ -185,17 +185,17 @@ function DropdownMenuShortcut({
data-slot="dropdown-menu-shortcut" data-slot="dropdown-menu-shortcut"
className={cn( className={cn(
"text-muted-foreground ml-auto text-xs tracking-widest", "text-muted-foreground ml-auto text-xs tracking-widest",
className className,
)} )}
{...props} {...props}
/> />
) );
} }
function DropdownMenuSub({ function DropdownMenuSub({
...props ...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) { }: 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({ function DropdownMenuSubTrigger({
@@ -204,7 +204,7 @@ function DropdownMenuSubTrigger({
children, children,
...props ...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & { }: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
inset?: boolean inset?: boolean;
}) { }) {
return ( return (
<DropdownMenuPrimitive.SubTrigger <DropdownMenuPrimitive.SubTrigger
@@ -212,14 +212,14 @@ function DropdownMenuSubTrigger({
data-inset={inset} data-inset={inset}
className={cn( 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", "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} {...props}
> >
{children} {children}
<ChevronRightIcon className="ml-auto size-4" /> <ChevronRightIcon className="ml-auto size-4" />
</DropdownMenuPrimitive.SubTrigger> </DropdownMenuPrimitive.SubTrigger>
) );
} }
function DropdownMenuSubContent({ function DropdownMenuSubContent({
@@ -231,11 +231,11 @@ function DropdownMenuSubContent({
data-slot="dropdown-menu-sub-content" data-slot="dropdown-menu-sub-content"
className={cn( 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", "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} {...props}
/> />
) );
} }
export { export {
@@ -254,4 +254,4 @@ export {
DropdownMenuSub, DropdownMenuSub,
DropdownMenuSubTrigger, DropdownMenuSubTrigger,
DropdownMenuSubContent, DropdownMenuSubContent,
} };

View File

@@ -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">) { function Input({ className, type, ...props }: React.ComponentProps<"input">) {
return ( 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", "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]", "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", "aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
className className,
)} )}
{...props} {...props}
/> />
) );
} }
export { Input } export { Input };

View File

@@ -1,9 +1,9 @@
"use client" "use client";
import * as React from "react" import * as React from "react";
import * as LabelPrimitive from "@radix-ui/react-label" import * as LabelPrimitive from "@radix-ui/react-label";
import { cn } from "@/lib/utils" import { cn } from "@/lib/utils";
function Label({ function Label({
className, className,
@@ -14,11 +14,11 @@ function Label({
data-slot="label" data-slot="label"
className={cn( 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", "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} {...props}
/> />
) );
} }
export { Label } export { Label };

View File

@@ -1,27 +1,27 @@
"use client" "use client";
import * as React from "react" import * as React from "react";
import * as SelectPrimitive from "@radix-ui/react-select" import * as SelectPrimitive from "@radix-ui/react-select";
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react" import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react";
import { cn } from "@/lib/utils" import { cn } from "@/lib/utils";
function Select({ function Select({
...props ...props
}: React.ComponentProps<typeof SelectPrimitive.Root>) { }: React.ComponentProps<typeof SelectPrimitive.Root>) {
return <SelectPrimitive.Root data-slot="select" {...props} /> return <SelectPrimitive.Root data-slot="select" {...props} />;
} }
function SelectGroup({ function SelectGroup({
...props ...props
}: React.ComponentProps<typeof SelectPrimitive.Group>) { }: React.ComponentProps<typeof SelectPrimitive.Group>) {
return <SelectPrimitive.Group data-slot="select-group" {...props} /> return <SelectPrimitive.Group data-slot="select-group" {...props} />;
} }
function SelectValue({ function SelectValue({
...props ...props
}: React.ComponentProps<typeof SelectPrimitive.Value>) { }: React.ComponentProps<typeof SelectPrimitive.Value>) {
return <SelectPrimitive.Value data-slot="select-value" {...props} /> return <SelectPrimitive.Value data-slot="select-value" {...props} />;
} }
function SelectTrigger({ function SelectTrigger({
@@ -30,7 +30,7 @@ function SelectTrigger({
children, children,
...props ...props
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & { }: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
size?: "sm" | "default" size?: "sm" | "default";
}) { }) {
return ( return (
<SelectPrimitive.Trigger <SelectPrimitive.Trigger
@@ -38,7 +38,7 @@ function SelectTrigger({
data-size={size} data-size={size}
className={cn( 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", "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} {...props}
> >
@@ -47,7 +47,7 @@ function SelectTrigger({
<ChevronDownIcon className="size-4 opacity-50" /> <ChevronDownIcon className="size-4 opacity-50" />
</SelectPrimitive.Icon> </SelectPrimitive.Icon>
</SelectPrimitive.Trigger> </SelectPrimitive.Trigger>
) );
} }
function SelectContent({ 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", "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" && 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", "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} position={position}
{...props} {...props}
@@ -74,7 +74,7 @@ function SelectContent({
className={cn( className={cn(
"p-1", "p-1",
position === "popper" && 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} {children}
@@ -82,7 +82,7 @@ function SelectContent({
<SelectScrollDownButton /> <SelectScrollDownButton />
</SelectPrimitive.Content> </SelectPrimitive.Content>
</SelectPrimitive.Portal> </SelectPrimitive.Portal>
) );
} }
function SelectLabel({ function SelectLabel({
@@ -95,7 +95,7 @@ function SelectLabel({
className={cn("text-muted-foreground px-2 py-1.5 text-xs", className)} className={cn("text-muted-foreground px-2 py-1.5 text-xs", className)}
{...props} {...props}
/> />
) );
} }
function SelectItem({ function SelectItem({
@@ -108,7 +108,7 @@ function SelectItem({
data-slot="select-item" data-slot="select-item"
className={cn( 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", "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} {...props}
> >
@@ -119,7 +119,7 @@ function SelectItem({
</span> </span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText> <SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item> </SelectPrimitive.Item>
) );
} }
function SelectSeparator({ function SelectSeparator({
@@ -132,7 +132,7 @@ function SelectSeparator({
className={cn("bg-border pointer-events-none -mx-1 my-1 h-px", className)} className={cn("bg-border pointer-events-none -mx-1 my-1 h-px", className)}
{...props} {...props}
/> />
) );
} }
function SelectScrollUpButton({ function SelectScrollUpButton({
@@ -144,13 +144,13 @@ function SelectScrollUpButton({
data-slot="select-scroll-up-button" data-slot="select-scroll-up-button"
className={cn( className={cn(
"flex cursor-default items-center justify-center py-1", "flex cursor-default items-center justify-center py-1",
className className,
)} )}
{...props} {...props}
> >
<ChevronUpIcon className="size-4" /> <ChevronUpIcon className="size-4" />
</SelectPrimitive.ScrollUpButton> </SelectPrimitive.ScrollUpButton>
) );
} }
function SelectScrollDownButton({ function SelectScrollDownButton({
@@ -162,13 +162,13 @@ function SelectScrollDownButton({
data-slot="select-scroll-down-button" data-slot="select-scroll-down-button"
className={cn( className={cn(
"flex cursor-default items-center justify-center py-1", "flex cursor-default items-center justify-center py-1",
className className,
)} )}
{...props} {...props}
> >
<ChevronDownIcon className="size-4" /> <ChevronDownIcon className="size-4" />
</SelectPrimitive.ScrollDownButton> </SelectPrimitive.ScrollDownButton>
) );
} }
export { export {
@@ -182,4 +182,4 @@ export {
SelectSeparator, SelectSeparator,
SelectTrigger, SelectTrigger,
SelectValue, SelectValue,
} };

View File

@@ -1,10 +1,10 @@
"use client" "use client";
import { useTheme } from "next-themes" import { useTheme } from "next-themes";
import { Toaster as Sonner, ToasterProps } from "sonner" import { Toaster as Sonner, ToasterProps } from "sonner";
const Toaster = ({ ...props }: ToasterProps) => { const Toaster = ({ ...props }: ToasterProps) => {
const { theme = "system" } = useTheme() const { theme = "system" } = useTheme();
return ( return (
<Sonner <Sonner
@@ -19,7 +19,7 @@ const Toaster = ({ ...props }: ToasterProps) => {
} }
{...props} {...props}
/> />
) );
} };
export { Toaster } export { Toaster };

View File

@@ -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">) { function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
return ( return (
@@ -8,11 +8,11 @@ function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
data-slot="textarea" data-slot="textarea"
className={cn( 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", "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} {...props}
/> />
) );
} }
export { Textarea } export { Textarea };

View File

@@ -1,6 +1,6 @@
import { drizzle } from 'drizzle-orm/postgres-js'; import { drizzle } from "drizzle-orm/postgres-js";
import postgres from 'postgres'; import postgres from "postgres";
import * as schema from './schema'; import * as schema from "./schema";
const connectionString = process.env.DATABASE_URL!; const connectionString = process.env.DATABASE_URL!;

View File

@@ -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', { export const user = pgTable("user", {
id: text('id').primaryKey(), id: text("id").primaryKey(),
name: text('name'), name: text("name"),
email: text('email').notNull().unique(), email: text("email").notNull().unique(),
emailVerified: boolean('emailVerified').default(false), emailVerified: boolean("emailVerified").default(false),
image: text('image'), image: text("image"),
createdAt: timestamp('createdAt').defaultNow(), createdAt: timestamp("createdAt").defaultNow(),
updatedAt: timestamp('updatedAt').defaultNow(), updatedAt: timestamp("updatedAt").defaultNow(),
}); });
export const session = pgTable('session', { export const session = pgTable("session", {
id: text('id').primaryKey(), id: text("id").primaryKey(),
expiresAt: timestamp('expiresAt').notNull(), expiresAt: timestamp("expiresAt").notNull(),
token: text('token').notNull().unique(), token: text("token").notNull().unique(),
createdAt: timestamp('createdAt').defaultNow(), createdAt: timestamp("createdAt").defaultNow(),
updatedAt: timestamp('updatedAt').defaultNow(), updatedAt: timestamp("updatedAt").defaultNow(),
ipAddress: text('ipAddress'), ipAddress: text("ipAddress"),
userAgent: text('userAgent'), userAgent: text("userAgent"),
userId: text('userId').notNull().references(() => user.id, { onDelete: 'cascade' }), userId: text("userId")
.notNull()
.references(() => user.id, { onDelete: "cascade" }),
}); });
export const account = pgTable('account', { export const account = pgTable("account", {
id: text('id').primaryKey(), id: text("id").primaryKey(),
accountId: text('accountId').notNull(), accountId: text("accountId").notNull(),
providerId: text('providerId').notNull(), providerId: text("providerId").notNull(),
userId: text('userId').notNull().references(() => user.id, { onDelete: 'cascade' }), userId: text("userId")
accessToken: text('accessToken'), .notNull()
refreshToken: text('refreshToken'), .references(() => user.id, { onDelete: "cascade" }),
accessTokenExpiresAt: timestamp('accessTokenExpiresAt'), accessToken: text("accessToken"),
refreshTokenExpiresAt: timestamp('refreshTokenExpiresAt'), refreshToken: text("refreshToken"),
scope: text('scope'), accessTokenExpiresAt: timestamp("accessTokenExpiresAt"),
idToken: text('idToken'), refreshTokenExpiresAt: timestamp("refreshTokenExpiresAt"),
password: text('password'), scope: text("scope"),
createdAt: timestamp('createdAt').defaultNow(), idToken: text("idToken"),
updatedAt: timestamp('updatedAt').defaultNow(), password: text("password"),
createdAt: timestamp("createdAt").defaultNow(),
updatedAt: timestamp("updatedAt").defaultNow(),
}); });
export const verification = pgTable('verification', { export const verification = pgTable("verification", {
id: text('id').primaryKey(), id: text("id").primaryKey(),
identifier: text('identifier').notNull(), identifier: text("identifier").notNull(),
value: text('value').notNull(), value: text("value").notNull(),
expiresAt: timestamp('expiresAt').notNull(), expiresAt: timestamp("expiresAt").notNull(),
createdAt: timestamp('createdAt').defaultNow(), createdAt: timestamp("createdAt").defaultNow(),
updatedAt: timestamp('updatedAt').defaultNow(), updatedAt: timestamp("updatedAt").defaultNow(),
}); });

View File

@@ -1,9 +1,9 @@
import { openDB, type IDBPDatabase } from 'idb'; import { openDB, type IDBPDatabase } from "idb";
import type { CalendarEvent } from '@/lib/types'; import type { CalendarEvent } from "@/lib/types";
const DB_NAME = 'LocalCalEvents'; const DB_NAME = "LocalCalEvents";
const DB_VERSION = 1; const DB_VERSION = 1;
const EVENTS_STORE = 'events'; const EVENTS_STORE = "events";
let dbPromise: Promise<IDBPDatabase> | null = null; let dbPromise: Promise<IDBPDatabase> | null = null;
@@ -12,9 +12,9 @@ function getDB() {
dbPromise = openDB(DB_NAME, DB_VERSION, { dbPromise = openDB(DB_NAME, DB_VERSION, {
upgrade(db) { upgrade(db) {
if (!db.objectStoreNames.contains(EVENTS_STORE)) { if (!db.objectStoreNames.contains(EVENTS_STORE)) {
const store = db.createObjectStore(EVENTS_STORE, { keyPath: 'id' }); const store = db.createObjectStore(EVENTS_STORE, { keyPath: "id" });
store.createIndex('start', 'start'); store.createIndex("start", "start");
store.createIndex('title', 'title'); store.createIndex("title", "title");
} }
}, },
}); });
@@ -47,10 +47,13 @@ export async function updateEvent(event: CalendarEvent): Promise<void> {
await db.put(EVENTS_STORE, event); 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 db = await getDB();
const tx = db.transaction(EVENTS_STORE, 'readonly'); const tx = db.transaction(EVENTS_STORE, "readonly");
const index = tx.store.index('start'); const index = tx.store.index("start");
const events = await index.getAll(IDBKeyRange.bound(startDate, endDate)); const events = await index.getAll(IDBKeyRange.bound(startDate, endDate));
await tx.done; await tx.done;
return events; return events;

View 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,
});

View File

@@ -1,23 +1,30 @@
// RFC 5545 (iCalendar) Recurrence Rule types // RFC 5545 (iCalendar) Recurrence Rule types
// Based on the iCalendar specification for RRULE // 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 { export interface RecurrenceRule {
freq: Frequency freq: Frequency;
until?: string // ISO 8601 date string until?: string; // ISO 8601 date string
count?: number count?: number;
interval?: number interval?: number;
bySecond?: number[] bySecond?: number[];
byMinute?: number[] byMinute?: number[];
byHour?: number[] byHour?: number[];
byDay?: string[] byDay?: string[];
byMonthDay?: number[] byMonthDay?: number[];
byYearDay?: number[] byYearDay?: number[];
byWeekNo?: number[] byWeekNo?: number[];
byMonth?: number[] byMonth?: number[];
bySetPos?: number[] bySetPos?: number[];
wkst?: Weekday wkst?: Weekday;
} }

View File

@@ -1,6 +1,6 @@
import { clsx, type ClassValue } from "clsx" import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge" import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) { export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs)) return twMerge(clsx(inputs));
} }