Arcadia Suite - Projeto completo

This commit is contained in:
jonaspachecoometas 2026-02-09 17:46:40 -03:00
parent 0812f4ab18
commit 065ab19a17
442 changed files with 203490 additions and 1 deletions

8
.gitignore vendored Normal file
View File

@ -0,0 +1,8 @@
node_modules
dist
.DS_Store
server/public
vite.config.ts.*
*.tar.gz
metabase/metabase-data.*
metabase/plugins/

88
.replit Normal file
View File

@ -0,0 +1,88 @@
modules = ["nodejs-20", "web", "python-3.11", "python3", "postgresql-16"]
run = "npm run dev"
hidden = [".config", ".git", "generated-icon.png", "node_modules", "dist"]
[nix]
channel = "stable-24_05"
packages = ["cairo", "cargo", "ffmpeg-full", "freetype", "ghostscript", "gitFull", "glibcLocales", "gobject-introspection", "gtk3", "libiconv", "libxcrypt", "mysql80", "openssl", "php82", "php82Packages.composer", "pkg-config", "playwright-driver", "qhull", "rustc", "tcl", "tk", "unzip", "xcodebuild", "zlib", "jdk21"]
[[ports]]
localPort = 5000
externalPort = 80
[[ports]]
localPort = 8001
externalPort = 3001
[[ports]]
localPort = 8002
externalPort = 3000
[[ports]]
localPort = 8003
externalPort = 3003
[[ports]]
localPort = 8004
externalPort = 4200
[[ports]]
localPort = 8005
externalPort = 3002
[[ports]]
localPort = 8006
externalPort = 5173
[[ports]]
localPort = 8080
externalPort = 8080
[[ports]]
localPort = 8088
externalPort = 5000
[env]
PORT = "5000"
[deployment]
deploymentTarget = "autoscale"
build = ["npm", "run", "build"]
publicDir = "dist/public"
run = ["node", "./dist/index.cjs"]
[workflows]
runButton = "Project"
[[workflows.workflow]]
name = "Project"
mode = "parallel"
author = "agent"
[[workflows.workflow.tasks]]
task = "workflow.run"
args = "Start application"
[[workflows.workflow]]
name = "Start application"
author = "agent"
[[workflows.workflow.tasks]]
task = "shell.exec"
args = "npm run dev"
waitForPort = 5000
[agent]
mockupState = "FULLSTACK"
integrations = ["javascript_openai_ai_integrations:2.0.0", "github:1.0.0"]
[userenv]
[userenv.shared]
FISCO_PYTHON_URL = "http://localhost:8002"
FISCO_PORT = "8002"
CONTABIL_PYTHON_URL = "http://localhost:8003"
PEOPLE_PYTHON_URL = "http://localhost:8004"
CONTABIL_PORT = "8003"
PEOPLE_PORT = "8004"
SSO_SECRET = "arcadia-sso-secret-2024-plus-integration-key-secure"

553
DOCUMENTATION.md Normal file
View File

@ -0,0 +1,553 @@
# Arcádia Suite - Documentação Técnica Completa
**Versão:** 1.0
**Data:** Janeiro 2026
**Desenvolvido por:** Arcádia Technology
---
## Sumário
1. [Visão Geral](#visão-geral)
2. [Arquitetura do Sistema](#arquitetura-do-sistema)
3. [Módulos do Sistema](#módulos-do-sistema)
4. [Modelo de Dados](#modelo-de-dados)
5. [APIs e Endpoints](#apis-e-endpoints)
6. [Integrações Externas](#integrações-externas)
7. [Segurança e Autenticação](#segurança-e-autenticação)
8. [Guia de Implantação](#guia-de-implantação)
---
## Visão Geral
O **Arcádia Suite** é um Sistema Operacional Empresarial (Business Operating System) alimentado por Inteligência Artificial, projetado para revolucionar operações empresariais. O sistema integra cinco pilares fundamentais:
### Os 5 Pilares
1. **Knowledge Graph** - Grafo de conhecimento para dados empresariais interconectados
2. **Central Intelligence (Scientist)** - Módulo de IA para geração automática de soluções
3. **Manus (Agente Autônomo)** - Execução de tarefas e automação
4. **Centro de Comunicação Unificado** - Interação com clientes via múltiplas plataformas
5. **IDE Completa** - Ambiente de desenvolvimento multi-modal
### Segmentação de Produtos
| Produto | Público-Alvo | Stack Tecnológica |
|---------|-------------|-------------------|
| **Arcádia Plus** | Pequenas empresas | Node.js + Python + PostgreSQL |
| **Arcádia Next** | Médias/Grandes empresas | Frappe Framework + PostgreSQL |
Ambos compartilham o **Arcádia Fisco** como motor fiscal centralizado.
---
## Arquitetura do Sistema
### Arquitetura em 4 Camadas
```
┌─────────────────────────────────────────────────────────────────┐
│ CAMADA DE APRESENTAÇÃO │
│ React 18 + TypeScript + Tailwind CSS + shadcn/ui │
│ Interface estilo navegador com abas e omnibox │
│ Porta: 5000 │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ CAMADA DE ORQUESTRAÇÃO │
│ Express.js + Socket.IO + Manus Agent │
│ API REST + WebSocket em tempo real │
│ Porta: 5000 │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ CAMADA DE INTELIGÊNCIA │
│ FastAPI (Python) + OpenAI API │
│ Scientist, Embeddings, RPA, Workflows │
│ Porta: 8001 (IA) / 8002 (Fisco) │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ CAMADA DE DADOS │
│ PostgreSQL + Knowledge Graph + ChromaDB │
│ Drizzle ORM + Session Store │
└─────────────────────────────────────────────────────────────────┘
```
### Estrutura de Diretórios
```
arcadia-suite/
├── client/ # Frontend React
│ └── src/
│ ├── components/ # Componentes reutilizáveis
│ ├── hooks/ # React hooks customizados
│ ├── lib/ # Utilitários e configurações
│ └── pages/ # Páginas da aplicação
├── server/ # Backend Node.js
│ ├── admin/ # Rotas administrativas
│ ├── api-central/ # Central de APIs
│ ├── automations/ # Motor de automações
│ ├── bi/ # Business Intelligence
│ ├── chat/ # Chat interno
│ ├── compass/ # Process Compass (clientes/projetos)
│ ├── crm/ # Gestão de relacionamento
│ ├── email/ # Serviço de e-mail
│ ├── erp/ # Integração ERP
│ ├── fisco/ # Motor fiscal (NF-e)
│ ├── ide/ # IDE integrada
│ ├── learning/ # Sistema de aprendizado
│ ├── login-bridge/ # Bridge de autenticação
│ ├── manus/ # Agente autônomo
│ ├── production/ # Gestão de produção
│ ├── productivity/ # Hub de produtividade
│ ├── proxy/ # Proxy reverso
│ ├── python/ # Serviços Python (FastAPI)
│ ├── support/ # Central de suporte
│ ├── valuation/ # Precificação e valuation
│ └── whatsapp/ # Integração WhatsApp
└── shared/ # Código compartilhado
└── schema.ts # Schemas do banco de dados
```
---
## Módulos do Sistema
### 1. Cockpit (Dashboard Principal)
**Arquivo:** `client/src/pages/Cockpit.tsx`
Painel central com visão geral do sistema:
- Widgets configuráveis
- Métricas em tempo real
- Atividades recentes
- Atalhos para módulos
### 2. Process Compass
**Arquivo:** `client/src/pages/ProcessCompass.tsx`
**API:** `/api/compass/*`
Gestão completa de processos empresariais:
- **Clientes:** Cadastro, histórico, segmentação
- **Projetos:** Cronograma, tarefas, milestones
- **Contratos:** Gestão de contratos e renovações
- **Timesheet:** Controle de horas trabalhadas
### 3. Comunicação Unificada
**Arquivo:** `client/src/pages/Comunicacao.tsx`
**API:** `/api/whatsapp/*`
Centro de comunicação multi-canal:
- **WhatsApp Business:** Atendimento via Baileys
- **Chat Interno:** Comunicação da equipe
- **E-mail:** Integração IMAP/SMTP
- **Tickets:** Sistema de filas de atendimento
### 4. CRM (Customer Relationship Management)
**Arquivo:** `client/src/pages/Crm.tsx`
**API:** `/api/crm/*`
Gestão de relacionamento com clientes:
- Pipeline de vendas
- Funil de conversão
- Gestão de oportunidades
- Comissionamento automático
- Integração com Google Calendar
### 5. Business Intelligence (Arcádia Insights)
**Arquivo:** `client/src/pages/BiWorkspace.tsx`
**API:** `/api/bi/*`
Análise e visualização de dados:
- Upload de arquivos (CSV, Excel)
- Gráficos interativos (Recharts)
- Dashboards personalizáveis
- Conexão com múltiplas fontes
### 6. Scientist (Central de Inteligência)
**Arquivo:** `client/src/pages/Scientist.tsx`
**API:** `/api/scientist/*`
Módulo de auto-programação com IA:
- Análise de dados automatizada
- Geração de código (Python/SQL)
- Execução em sandbox
- Armazenamento de soluções reutilizáveis
### 7. Manus (Agente Autônomo)
**Arquivo:** `client/src/pages/Agent.tsx`
**API:** `/api/manus/*`
Executor de tarefas autônomo:
- Loop pensamento-ação-observação
- Ferramentas disponíveis:
- Busca web
- Consulta ao Knowledge Graph
- Consulta ERP
- Cálculos
- Envio de mensagens
- Geração de relatórios
- Agendamentos
### 8. Arcádia Fisco (Motor Fiscal)
**Arquivo:** `client/src/pages/Fisco.tsx`
**API:** `/api/fisco/*`
Motor fiscal centralizado para compliance brasileiro:
- **NCM:** Nomenclatura Comum do Mercosul
- **CFOP:** Código Fiscal de Operações
- **CEST:** Código Especificador da Substituição Tributária
- **Grupos de Tributação:** Configuração de impostos
- **Certificados Digitais:** Gestão de A1/A3
- **NF-e/NFC-e:** Emissão de notas fiscais eletrônicas
- **IBS/CBS:** Campos para Reforma Tributária
#### Integração nfelib (Python)
**Arquivo:** `server/python/fisco_service.py`
Serviço FastAPI para processamento de NF-e:
- Geração de XML (layout 4.00)
- Assinatura digital com certificado A1
- Comunicação com SEFAZ (homologação/produção)
- Consulta, cancelamento e inutilização
### 9. Produção
**Arquivo:** `client/src/pages/Production.tsx`
**API:** `/api/production/*`
Gestão de produção e manufatura:
- Ordens de produção
- Controle de estoque
- Rastreabilidade
- Custos de produção
### 10. Valuation (Precificação)
**Arquivo:** `client/src/pages/Valuation.tsx`
**API:** `/api/valuation/*`
Sistema de precificação inteligente:
- Cálculo de custos
- Margem de contribuição
- Markup
- Simulações de preço
### 11. Suporte
**Arquivo:** `client/src/pages/Support.tsx`
**API:** `/api/support/*`
Central de atendimento:
- Tickets de suporte
- Base de conhecimento
- SLA e prioridades
- Histórico de atendimentos
### 12. Automações
**Arquivo:** `client/src/pages/Automations.tsx`
**API:** `/api/automations/*`
Motor de automações:
- Triggers e ações
- Workflows visuais
- Integrações via webhooks
- Agendamentos (cron)
### 13. Knowledge Base
**Arquivo:** `client/src/pages/Knowledge.tsx`
**API:** `/api/knowledge/*`
Base de conhecimento:
- Artigos e documentação
- Categorização
- Busca semântica
- Integração com IA
### 14. IDE
**Arquivo:** `client/src/pages/IDE.tsx`
**API:** `/api/ide/*`
Ambiente de desenvolvimento integrado:
- Monaco Editor
- Terminal (Xterm.js)
- Execução de código
- Gerenciamento de arquivos
### 15. Administração
**Arquivo:** `client/src/pages/Admin.tsx`
**API:** `/api/admin/*`
Painel administrativo:
- **Usuários:** Gestão de contas
- **Perfis:** Controle de acesso
- **Parceiros:** Hierarquia multi-tenant
- **Módulos:** Configuração de funcionalidades
- **Configurações:** Parâmetros do sistema
### 16. API Hub
**Arquivo:** `client/src/pages/ApiHub.tsx`
Documentação interativa de APIs:
- Listagem de endpoints
- Testes em tempo real
- Exemplos de uso
- Geração de código
---
## Modelo de Dados
### Entidades Principais
#### Usuários e Autenticação
```sql
users -- Usuários do sistema
profiles -- Perfis de acesso
roles -- Papéis (RBAC)
permissions -- Permissões granulares
role_permissions -- Associação papel-permissão
user_roles -- Associação usuário-papel
module_access -- Controle de acesso a módulos
```
#### Produtividade
```sql
workspace_pages -- Páginas estilo Notion
page_blocks -- Blocos de conteúdo
page_links -- Links bidirecionais
dashboard_widgets -- Widgets do dashboard
quick_notes -- Notas rápidas
activity_feed -- Feed de atividades
user_favorites -- Favoritos
command_history -- Histórico de comandos
```
#### Conversação e IA
```sql
conversations -- Conversas com agente
messages -- Mensagens
chat_attachments -- Anexos
knowledge_base -- Base de conhecimento
```
#### ERP e Integrações
```sql
erp_connections -- Conexões com ERPs
agent_tasks -- Tarefas do agente
task_executions -- Execuções de tarefas
```
#### Comunicação
```sql
chat_threads -- Threads de chat
chat_participants -- Participantes
chat_messages -- Mensagens de chat
whatsapp_sessions -- Sessões WhatsApp
whatsapp_contacts -- Contatos WhatsApp
whatsapp_messages -- Mensagens WhatsApp
whatsapp_queues -- Filas de atendimento
whatsapp_tickets -- Tickets de atendimento
```
#### Process Compass
```sql
compass_clients -- Clientes
compass_projects -- Projetos
compass_project_members -- Membros de projeto
compass_project_phases -- Fases de projeto
compass_contracts -- Contratos
compass_timesheet -- Timesheet
compass_invoices -- Faturas
compass_payments -- Pagamentos
```
#### CRM
```sql
crm_leads -- Leads
crm_opportunities -- Oportunidades
crm_activities -- Atividades
crm_pipelines -- Pipelines
crm_stages -- Estágios
crm_commissions -- Comissões
```
#### Fisco
```sql
fisco_ncm -- NCMs
fisco_cest -- CESTs
fisco_cfop -- CFOPs
fisco_grupos_tributacao -- Grupos de tributação
fisco_natureza_operacao -- Naturezas de operação
fisco_ibpt -- Tabela IBPT
fisco_certificados -- Certificados digitais
fisco_configuracoes -- Configurações fiscais
fisco_notas -- Notas fiscais
fisco_nota_itens -- Itens das notas
fisco_nota_eventos -- Eventos fiscais
```
#### Multi-Tenant
```sql
partners -- Parceiros
partner_invites -- Convites de parceiros
tenant_clients -- Clientes dos tenants
```
---
## APIs e Endpoints
### Estrutura Base
| Módulo | Base URL | Descrição |
|--------|----------|-----------|
| Admin | `/api/admin` | Administração do sistema |
| Compass | `/api/compass` | Process Compass |
| CRM | `/api/crm` | Gestão de relacionamento |
| WhatsApp | `/api/whatsapp` | Comunicação WhatsApp |
| Fisco | `/api/fisco` | Motor fiscal |
| BI | `/api/bi` | Business Intelligence |
| Production | `/api/production` | Gestão de produção |
| Valuation | `/api/valuation` | Precificação |
| Support | `/api/support` | Central de suporte |
| Automations | `/api/automations` | Automações |
| IDE | `/api/ide` | Ambiente de desenvolvimento |
| Learning | `/api/learning` | Sistema de aprendizado |
### Exemplos de Endpoints
#### Fisco - NF-e
```
GET /api/fisco/nfe/service-status # Status do serviço
POST /api/fisco/nfe/validar-certificado # Validar certificado A1
POST /api/fisco/nfe/gerar-xml # Gerar XML preview
POST /api/fisco/nfe/emitir # Emitir NF-e
POST /api/fisco/nfe/consultar # Consultar na SEFAZ
POST /api/fisco/nfe/cancelar # Cancelar NF-e
POST /api/fisco/nfe/inutilizar # Inutilizar numeração
```
#### Compass - Clientes
```
GET /api/compass/clients # Listar clientes
GET /api/compass/clients/:id # Detalhes do cliente
POST /api/compass/clients # Criar cliente
PUT /api/compass/clients/:id # Atualizar cliente
DELETE /api/compass/clients/:id # Excluir cliente
```
#### Admin - Usuários
```
GET /api/admin/users # Listar usuários
GET /api/admin/users/:id # Detalhes do usuário
POST /api/admin/users # Criar usuário
PUT /api/admin/users/:id # Atualizar usuário
DELETE /api/admin/users/:id # Excluir usuário
```
---
## Integrações Externas
### OpenAI API
- **Uso:** Agente de IA, Scientist, auto-replies
- **Modelo:** gpt-4o-mini
- **Configuração:** Via Replit Secrets
### Baileys (WhatsApp)
- **Uso:** Conexão multi-sessão WhatsApp
- **Recursos:** QR Code, mensagens em tempo real
- **Armazenamento:** Sessões no banco de dados
### nfelib (Python)
- **Uso:** Emissão de NF-e/NFC-e
- **Recursos:** XML, assinatura digital, SEFAZ
- **Certificados:** A1 (PFX)
### Frappe Framework
- **Uso:** Arcádia Next (futuro)
- **Recursos:** ERPNext integration
### Google Calendar
- **Uso:** Sincronização de eventos CRM
- **OAuth:** Configurável por usuário
---
## Segurança e Autenticação
### Autenticação
- **Método:** Session-based com Passport.js
- **Hash:** bcrypt para senhas
- **Sessões:** PostgreSQL session store
### Controle de Acesso (RBAC)
```
Hierarquia:
├── Master (Arcádia)
│ └── Parceiros
│ └── Clientes
```
### Permissões
- Baseadas em módulos e ações
- Código formato: `modulo.recurso.acao`
- Exemplo: `compass.clients.write`
### Certificados Digitais
- Tipo A1 (arquivo PFX)
- Armazenamento seguro com senha
- Validação de expiração
---
## Guia de Implantação
### Requisitos
- Node.js 20+
- Python 3.11+
- PostgreSQL 15+
- Certificado SSL (produção)
### Variáveis de Ambiente
```env
DATABASE_URL=postgresql://...
SESSION_SECRET=...
OPENAI_API_KEY=...
FISCO_PYTHON_URL=http://localhost:8002
FISCO_PORT=8002
```
### Comandos de Inicialização
```bash
# Instalar dependências
npm install
# Iniciar em desenvolvimento
npm run dev
# Serviço Python Fisco (separado)
cd server/python && python fisco_service.py
```
### Portas
| Serviço | Porta |
|---------|-------|
| Frontend + API | 5000 |
| Python Fisco | 8002 |
| Python IA | 8001 |
---
## Changelog
### Janeiro 2026
- Integração nfelib para NF-e
- Módulo Fisco completo
- Sistema de aprendizado automático
- Validação Zod em todas as rotas fiscais
---
**Arcádia Suite** - Transformando a gestão empresarial com Inteligência Artificial
*Documentação gerada automaticamente pelo sistema.*

421
PLANO_EVOLUCAO_ARCADIA.md Normal file
View File

@ -0,0 +1,421 @@
# PLANO ESTRATÉGICO DE EVOLUÇÃO
## Arcádia Suite → Frappe Framework
### Versão 1.0 - Janeiro 2026
---
## 1. VISÃO GERAL
### 1.1 Objetivo
Evoluir o Arcádia Suite para um **Business Operating System** completo, inspirado em três referências:
| Referência | O que Inspira |
|------------|---------------|
| **Notion** | Blocos modulares, banco de dados relacional, personalização |
| **Replit** | IDE no navegador, colaboração em tempo real, deploy instantâneo |
| **Discord** | Comunidades, canais contextuais, comunicação em tempo real |
### 1.2 Estratégia de Migração: Strangler Fig
A estratégia Strangler Fig permite:
- Manter WhatsApp, Manus, CRM funcionando durante toda a migração
- Construir o novo sistema em paralelo
- Migrar módulo a módulo até o sistema legado "desaparecer"
```
Sistema Atual (Express/React) continua funcionando
Você vai adicionando "camadas Frappe" por cima
Cada módulo migrado substitui o antigo
No final, o "núcleo antigo" sumiu naturalmente
```
### 1.3 Stack Técnico
| Camada | Atual | Futuro |
|--------|-------|--------|
| Frontend | React 18 + TypeScript | Frappe Desk + React |
| Backend | Express.js | Frappe Framework |
| Database | PostgreSQL | PostgreSQL (mesmo) |
| Real-time | Socket.IO | Frappe Realtime + Socket.IO |
| WhatsApp | Baileys | Frappe App (Baileys) |
| IDE | Monaco + Terminal | IDE 3 Modos |
---
## 2. ESTRUTURA MULTI-TENANT
### 2.1 Hierarquia de 3 Níveis
```
NÍVEL 1: MASTER (Arcádia)
═════════════════════════
• Equipe de desenvolvimento
• Acesso total ao sistema
• IDE Pro-Code completa
• Central de Bibliotecas (publica apps)
• Suporte N3 (acessa tenants para debug)
• Gerencia parceiros e planos
├───────────────────────┬───────────────────────┐
▼ ▼ ▼
NÍVEL 2: PARCEIROS
══════════════════
• Consultorias, integradores, revendas
• IDE Low-Code
• Gerencia seus clientes
• Comissões sobre vendas
• Suporte N2 aos clientes
• Baixa apps da biblioteca
┌────┴────┐
▼ ▼
NÍVEL 3: CLIENTES
═════════════════
• Empresas usuárias finais
• Cockpit personalizado
• CRM/ERP operacional
• WhatsApp (N sessões conforme plano)
• BI próprio
• Manus com tools básicas
```
### 2.2 Matriz de Permissões por Tipo de Tenant
| Módulo | Master | Parceiro | Cliente |
|--------|--------|----------|---------|
| **IDE Pro-Code** | ✅ | ❌ | ❌ |
| **IDE Low-Code** | ✅ | ✅ | ❌ |
| **IDE No-Code** | ✅ | ✅ | ✅ (se habilitado) |
| **Central de Bibliotecas** | ✅ Publicar | ✅ Baixar | ❌ |
| **Central de APIs** | ✅ Gerenciar | ⚠️ Seus conectores | ⚠️ Leitura |
| **WhatsApp** | ✅ Ilimitado | ✅ N sessões | ✅ N sessões |
| **CRM/ERP** | ✅ Global | ✅ Próprio | ✅ Próprio |
| **Manus (IA)** | ✅ Todas tools | ✅ Tools permitidas | ✅ Básicas |
| **BI/Relatórios** | ✅ Global | ✅ Próprio | ✅ Próprio |
| **Suporte N3** | ✅ Acessa tenants | ❌ | ❌ |
| **Ver Parceiros** | ✅ | ✅ Seus clientes | ❌ |
| **Comissões** | ✅ Gerencia | ✅ Visualiza suas | ❌ |
### 2.3 Alterações no Schema
```sql
-- Alterações na tabela tenants
ALTER TABLE tenants ADD COLUMN tenant_type TEXT DEFAULT 'client';
-- master = Arcádia, partner = Parceiros, client = Clientes
ALTER TABLE tenants ADD COLUMN parent_tenant_id INTEGER REFERENCES tenants(id);
-- Referência ao tenant pai (hierarquia)
ALTER TABLE tenants ADD COLUMN partner_code TEXT;
-- Código do parceiro para rastreamento
ALTER TABLE tenants ADD COLUMN max_users INTEGER DEFAULT 5;
ALTER TABLE tenants ADD COLUMN max_storage_mb INTEGER DEFAULT 1000;
ALTER TABLE tenants ADD COLUMN features JSONB;
ALTER TABLE tenants ADD COLUMN commission_rate NUMERIC(5,2);
ALTER TABLE tenants ADD COLUMN trial_ends_at TIMESTAMP;
-- Nova tabela: Planos
CREATE TABLE tenant_plans (
id SERIAL PRIMARY KEY,
code TEXT NOT NULL UNIQUE,
name TEXT NOT NULL,
tenant_type TEXT NOT NULL,
max_users INTEGER DEFAULT 5,
max_storage_mb INTEGER DEFAULT 1000,
features JSONB,
monthly_price INTEGER DEFAULT 0,
yearly_price INTEGER DEFAULT 0,
is_active TEXT DEFAULT 'true',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- Nova tabela: Relacionamento Parceiro-Cliente
CREATE TABLE partner_clients (
id SERIAL PRIMARY KEY,
partner_id INTEGER NOT NULL REFERENCES tenants(id),
client_id INTEGER NOT NULL REFERENCES tenants(id),
commission_rate NUMERIC(5,2),
status TEXT DEFAULT 'active',
started_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
ended_at TIMESTAMP
);
-- Nova tabela: Comissões
CREATE TABLE partner_commissions (
id SERIAL PRIMARY KEY,
partner_id INTEGER NOT NULL REFERENCES tenants(id),
client_id INTEGER NOT NULL REFERENCES tenants(id),
reference_month TEXT NOT NULL,
client_plan_value INTEGER NOT NULL,
commission_rate NUMERIC(5,2) NOT NULL,
commission_value INTEGER NOT NULL,
status TEXT DEFAULT 'pending',
paid_at TIMESTAMP,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
```
---
## 3. CRONOGRAMA GERAL (6-9 Meses)
```
Mês 1 Mês 2 Mês 3 Mês 4 Mês 5 Mês 6+
├──────────┼──────────┼──────────┼──────────┼──────────┼────────►
FASE 0 ████████████████████
FUNDAÇÃO
Setup + Tenants + SSO
FASE 1 ████████████████████████████
INFRAESTRUTURA
CRM/ERP + Central APIs + Manus
FASE 2 ████████████████████████████████
EXPERIÊNCIA
Cockpit + Comunidades + IDE
FASE 3 ████████████████████►
AUTOMAÇÃO
WhatsApp + RPA + Decommission
```
---
## 4. FASE 0: FUNDAÇÃO (Semanas 1-8)
### 4.1 Objetivo
Preparar a base técnica sem quebrar nada do sistema atual.
### 4.2 Entregas
| # | Entrega | Descrição | Semana |
|---|---------|-----------|--------|
| 0.1 | **Setup Frappe Bench** | Instalar Frappe em servidor paralelo | 1-2 |
| 0.2 | **Hierarquia de Tenants** | Novos campos e tabelas no PostgreSQL | 2-3 |
| 0.3 | **SSO Bridge** | Login unificado (usuário loga uma vez) | 3-4 |
| 0.4 | **CDC Pipeline** | Sincronização de dados PostgreSQL ↔ Frappe | 4-6 |
| 0.5 | **Vault de Secrets** | Gerenciamento seguro de API keys | 5-6 |
| 0.6 | **Feature Flags** | Sistema de features por plano/tenant | 6-7 |
| 0.7 | **Planos e Preços** | Tabela de planos (free, starter, pro, enterprise) | 7-8 |
### 4.3 Resultado
- ✅ Frappe rodando em paralelo
- ✅ Hierarquia master/partner/client funcionando
- ✅ Login único nos dois sistemas
- ✅ Dados sincronizados em tempo real
- ✅ Planos e features configuráveis
---
## 5. FASE 1: INFRAESTRUTURA (Semanas 6-16)
### 5.1 Objetivo
Migrar dados mestres e criar a Central de APIs.
### 5.2 Entregas
| # | Entrega | Descrição | Semana |
|---|---------|-----------|--------|
| 1.1 | **DocTypes CRM** | Clientes, Leads, Oportunidades no Frappe | 6-8 |
| 1.2 | **DocTypes ERP** | Produtos, Pedidos, Faturas no Frappe | 8-10 |
| 1.3 | **Central de APIs (MVP)** | Dashboard visual de integrações | 9-12 |
| 1.4 | **Conectores Básicos** | Interface para SEFAZ, Bancos (dados demo) | 12-14 |
| 1.5 | **Manus Frappe** | Agente IA via background jobs | 13-15 |
| 1.6 | **Knowledge Graph** | Migração do grafo para DocTypes | 14-16 |
### 5.3 Central de APIs - Detalhamento
**IMPORTANTE:** A Central de APIs é uma interface visual de gerenciamento. Os dados de integrações (SEFAZ, Bancos, Mercado Livre) são ILUSTRATIVOS/DEMO. Não fazemos integração real com APIs externas nesta fase.
O que construímos:
- ✅ Interface visual (React)
- ✅ CRUD de conectores (cadastrar, editar, remover)
- ✅ Status visual (online, warning, error)
- ✅ Logs fictícios para demonstração
- ✅ Configurações por conector
- ✅ Permissões por tenant type
O que NÃO fazemos:
- ❌ Conectar à SEFAZ real
- ❌ Conectar a bancos reais
- ❌ Chamadas API externas
### 5.4 Resultado
- ✅ CRM/ERP acessível via Frappe Desk
- ✅ Central de APIs funcionando (dados demo)
- ✅ Manus consultando dados do Frappe
- ✅ Knowledge Graph migrado
---
## 6. FASE 2: EXPERIÊNCIA (Semanas 12-24)
### 6.1 Objetivo
Construir a nova interface (Cockpit, Comunidades, IDE).
### 6.2 Entregas
| # | Entrega | Descrição | Semana |
|---|---------|-----------|--------|
| 2.1 | **Cockpit PARA** | Navegação Projetos/Áreas/Recursos/Arquivo | 12-15 |
| 2.2 | **Dashboard Tríade** | Importante/Urgente/Circunstancial | 14-16 |
| 2.3 | **Widgets Sistema** | Tarefas, Calendário, Gráficos | 15-17 |
| 2.4 | **Comunidades MVP** | Canais por projeto (Socket.IO via Frappe) | 16-19 |
| 2.5 | **IDE No-Code** | DocType Builder visual | 18-20 |
| 2.6 | **IDE Low-Code** | Templates de scripts | 20-22 |
| 2.7 | **IDE Pro-Code** | Monaco + Terminal + Live Preview | 21-23 |
| 2.8 | **Central de Bibliotecas** | Repositório de apps Frappe | 22-24 |
### 6.3 Cockpit PARA + Tríade
O Cockpit é a interface principal do usuário, baseado em duas metodologias:
**Método PARA (Tiago Forte):**
- **P**rojetos: Todos os projetos ativos com metas e prazos
- **Á**reas: Áreas de responsabilidade contínua (Vendas, Financeiro, RH)
- **R**ecursos: Base de conhecimento, templates, manuais
- **A**rquivo: Tudo concluído ou inativo, para consulta futura
**Tríade do Tempo (Christian Barbosa):**
- 🟢 **Importante** (70% do tempo): Atividades que geram valor
- 🟡 **Urgente** (20% do tempo): Atividades com prazo apertado
- 🔴 **Circunstancial** (10% do tempo): Atividades que não agregam
### 6.4 IDE 3 Modos
| Modo | Quem Usa | O que Faz |
|------|----------|-----------|
| **No-Code** | Clientes | Criar formulários arrastando, workflows visuais, relatórios com filtros |
| **Low-Code** | Parceiros | Server Scripts com templates, validações, webhooks, fórmulas |
| **Pro-Code** | Arcádia | Monaco Editor completo, Terminal, Git, Deploy de apps |
### 6.5 Resultado
- ✅ Cockpit PARA + Tríade funcionando
- ✅ Comunidades com canais por projeto
- ✅ IDE com 3 modos operando
- ✅ Central de Bibliotecas publicando apps
---
## 7. FASE 3: AUTOMAÇÃO E DECOMMISSION (Semana 20+)
### 7.1 Objetivo
Migrar serviços restantes e desligar o legado.
### 7.2 Entregas
| # | Entrega | Descrição | Semana |
|---|---------|-----------|--------|
| 3.1 | **WhatsApp Frappe App** | Reconstruir Baileys como app nativo | 20-24 |
| 3.2 | **Motor de Workflows** | Automações visuais (RPA) | 22-26 |
| 3.3 | **Scientist Frappe** | Migrar para Frappe Workers | 24-28 |
| 3.4 | **Validação de Paridade** | Testes A/B, métricas | 26-30 |
| 3.5 | **Decommission Express** | Desligar endpoints legados | 30+ |
### 7.3 Resultado
- ✅ Sistema 100% unificado no Frappe
- ✅ Express/React desligado
- ✅ Uma única plataforma para manter
---
## 8. MAPEAMENTO DE MÓDULOS
| Módulo Atual | O que Acontece | Fase |
|--------------|----------------|------|
| **users, tenants** | Expande com hierarquia | 0 |
| **profiles, roles, permissions** | Migra para Frappe RBAC | 0 |
| **whatsapp_contacts, messages, tickets** | Mantém → Migra na Fase 3 | 3 |
| **pc_crm_leads, stages, opportunities** | Migra para Frappe DocTypes | 1 |
| **pc_clients, projects, tasks** | Migra para Frappe DocTypes | 1 |
| **graph_nodes, graph_edges** | Migra para Frappe Knowledge Graph | 1 |
| **internal_chat_*** | Evolui para Comunidades | 2 |
| **manus_*** | Integra via background jobs | 1 |
| **bi_*** | Mantém + novos widgets Cockpit | 2 |
| **ide_*** | Evolui para 3 modos | 2 |
---
## 9. RISCOS E MITIGAÇÕES
| Risco | Probabilidade | Impacto | Mitigação |
|-------|---------------|---------|-----------|
| **Drift de dados** | Média | Alto | CDC com validação contínua |
| **Performance chat** | Média | Médio | Load test antes de migrar |
| **Tokens WhatsApp** | Baixa | Alto | Vault de secrets |
| **Curva aprendizado Frappe** | Alta | Médio | Treinamento na Fase 0 |
| **Regressões funcionais** | Média | Alto | Testes A/B, telemetria |
| **Resistência usuários** | Média | Médio | Piloto gradual: Master → Partners → Clients |
---
## 10. QUICK WINS (Entregas Rápidas)
| Item | Tempo | Valor |
|------|-------|-------|
| **Hierarquia de Tenants** | 2 semanas | Estrutura para parceiros |
| **SSO unificado** | 2 semanas | Login único |
| **Central de APIs (UI)** | 3 semanas | Visibilidade integrações |
| **Dashboard Tríade** | 2 semanas | Consciência sobre tempo |
| **Planos e Features** | 2 semanas | Monetização estruturada |
---
## 11. OS 5 PILARES DO SISTEMA
### Pilar 1: Knowledge Graph
- Todos os dados do negócio conectados e pesquisáveis
- Navegação visual entre entidades relacionadas
- Base para IA contextual
### Pilar 2: Central Intelligence (Scientist)
- IA que aprende com interações do sistema
- Gera e executa código automaticamente
- Detecta padrões e sugere otimizações
### Pilar 3: Autonomous Agent (Manus)
- Executa tarefas multi-step de forma autônoma
- Acessa ferramentas e APIs
- Deep research com planejamento
### Pilar 4: Unified Communication
- WhatsApp integrado com CRM
- Chat interno com canais por projeto
- Email (futuro)
- Todos os canais em um lugar
### Pilar 5: Complete IDE
- 3 modos de desenvolvimento (No/Low/Pro Code)
- Central de Bibliotecas
- Deploy integrado
---
## 12. DOCUMENTOS DE REFERÊNCIA
Os documentos originais que basearam este plano estão em:
- `attached_assets/cocpti_docs/cocpti/` - Cockpit e DNA Notion
- `attached_assets/cocpti_docs/Ide Arcadia/` - Proposta IDE
- `attached_assets/cocpti_docs/Rota de desenvolviento/` - Roadmap original
- `attached_assets/cocpti_docs/Central de API/` - Central de APIs
---
## 13. PRÓXIMOS PASSOS
1. [ ] Implementar hierarquia de tenants no schema
2. [ ] Criar tabelas de planos e comissões
3. [ ] Documentar arquitetura CDC
4. [ ] Provisionar servidor Frappe
5. [ ] Implementar Central de APIs (UI com dados demo)
6. [ ] Construir Cockpit PARA + Tríade
---
*Documento criado em Janeiro 2026*
*Última atualização: Janeiro 2026*

View File

@ -1 +0,0 @@
# Arcadia Suite\nOffice Estratégico Empresarial

27
client/index.html Normal file
View File

@ -0,0 +1,27 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1" />
<meta property="og:title" content="Arcádia Suite" />
<meta property="og:description" content="Ambiente empresarial integrado para gestão de sistemas e aplicações" />
<meta property="og:type" content="website" />
<meta property="og:image" content="https://replit.com/public/images/opengraph.png" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:site" content="@replit" />
<meta name="twitter:title" content="Arcádia Suite" />
<meta name="twitter:description" content="Ambiente empresarial integrado para gestão de sistemas e aplicações" />
<meta name="twitter:image" content="https://replit.com/public/images/opengraph.png" />
<link rel="icon" type="image/png" href="/favicon.png" />
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
<title>Arcádia Suite</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

BIN
client/public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

BIN
client/public/favicon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

BIN
client/public/opengraph.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

152
client/src/App.tsx Normal file
View File

@ -0,0 +1,152 @@
import { Switch, Route } from "wouter";
import { queryClient } from "./lib/queryClient";
import { QueryClientProvider } from "@tanstack/react-query";
import { Toaster } from "@/components/ui/toaster";
import { TooltipProvider } from "@/components/ui/tooltip";
import { AuthProvider } from "@/hooks/use-auth";
import { ErpProfileProvider } from "@/contexts/ErpProfileContext";
import { ProtectedRoute } from "@/lib/protected-route";
import { CommandPalette } from "@/components/CommandPalette";
import { KnowledgeCollectorInit } from "@/components/KnowledgeCollectorInit";
import NotFound from "@/pages/not-found";
import AuthPage from "@/pages/auth-page";
import Agent from "@/pages/Agent";
import Admin from "@/pages/Admin";
import Chat from "@/pages/Chat";
import WhatsApp from "@/pages/WhatsApp";
import Automations from "@/pages/Automations";
import BiWorkspace from "@/pages/BiWorkspace";
import ProcessCompass from "@/pages/ProcessCompass";
import WorkspacePage from "@/pages/WorkspacePage";
import AppViewer from "@/pages/AppViewer";
import Crm from "@/pages/Crm";
import Production from "@/pages/Production";
import Support from "@/pages/Support";
import Valuation from "@/pages/Valuation";
import Canvas from "@/pages/Canvas";
import IDE from "@/pages/IDE";
import Scientist from "@/pages/Scientist";
import Knowledge from "@/pages/Knowledge";
import CentralApis from "@/pages/CentralApis";
import ApiTesterPage from "@/pages/ApiTesterPage";
import ApiHub from "@/pages/ApiHub";
import Cockpit from "@/pages/Cockpit";
import Fisco from "@/pages/Fisco";
import People from "@/pages/People";
import Contabil from "@/pages/Contabil";
import ERP from "@/pages/ERP";
import Financeiro from "@/pages/Financeiro";
import Communities from "@/pages/Communities";
import ArcadiaNext from "@/pages/ArcadiaNext";
import QualityModule from "@/pages/QualityModule";
import CommercialEnv from "@/pages/CommercialEnv";
import FieldOperations from "@/pages/FieldOperations";
import TechnicalModule from "@/pages/TechnicalModule";
import SuppliersPortal from "@/pages/SuppliersPortal";
import NPSSurvey from "@/pages/NPSSurvey";
import EngineeringHub from "@/pages/EngineeringHub";
import DocTypeBuilder from "@/pages/DocTypeBuilder";
import PageBuilder from "@/pages/PageBuilder";
import DevelopmentModule from "@/pages/DevelopmentModule";
import ArcadiaRetail from "@/pages/ArcadiaRetail";
import Plus from "@/pages/Plus";
import SuperAdmin from "@/pages/SuperAdmin";
import Marketplace from "@/pages/Marketplace";
import LMS from "@/pages/LMS";
import AppCenter from "@/pages/AppCenter";
import XosCentral from "@/pages/XosCentral";
import XosCrm from "@/pages/XosCrm";
import XosInbox from "@/pages/XosInbox";
import XosTickets from "@/pages/XosTickets";
import Migration from "@/pages/Migration";
import DevCenter from "@/pages/DevCenter";
import XosCampaigns from "@/pages/XosCampaigns";
import XosAutomations from "@/pages/XosAutomations";
import XosSites from "@/pages/XosSites";
import XosGovernance from "@/pages/XosGovernance";
import XosPipeline from "@/pages/XosPipeline";
function Router() {
return (
<Switch>
<ProtectedRoute path="/" component={Cockpit} />
<ProtectedRoute path="/agent" component={Agent} />
<ProtectedRoute path="/admin" component={Admin} />
<ProtectedRoute path="/chat" component={Chat} />
<ProtectedRoute path="/whatsapp" component={WhatsApp} />
<ProtectedRoute path="/comunicacao" component={XosInbox} />
<ProtectedRoute path="/automations" component={Automations} />
<ProtectedRoute path="/insights" component={BiWorkspace} />
<ProtectedRoute path="/compass" component={ProcessCompass} />
<ProtectedRoute path="/crm" component={Crm} />
<ProtectedRoute path="/production" component={Production} />
<ProtectedRoute path="/support" component={Support} />
<ProtectedRoute path="/valuation" component={Valuation} />
<ProtectedRoute path="/canvas" component={Canvas} />
<ProtectedRoute path="/ide" component={IDE} />
<ProtectedRoute path="/scientist" component={Scientist} />
<ProtectedRoute path="/knowledge" component={Knowledge} />
<ProtectedRoute path="/central-apis" component={CentralApis} />
<ProtectedRoute path="/api-tester" component={ApiTesterPage} />
<ProtectedRoute path="/api-hub" component={ApiHub} />
<ProtectedRoute path="/fisco" component={Fisco} />
<ProtectedRoute path="/people" component={People} />
<ProtectedRoute path="/contabil" component={Contabil} />
<ProtectedRoute path="/erp" component={ERP} />
<ProtectedRoute path="/financeiro" component={Financeiro} />
<ProtectedRoute path="/communities" component={Communities} />
<ProtectedRoute path="/quality" component={QualityModule} />
<ProtectedRoute path="/commercial-env" component={CommercialEnv} />
<ProtectedRoute path="/field-ops" component={FieldOperations} />
<ProtectedRoute path="/technical" component={TechnicalModule} />
<ProtectedRoute path="/suppliers" component={SuppliersPortal} />
<ProtectedRoute path="/nps" component={NPSSurvey} />
<ProtectedRoute path="/engineering" component={EngineeringHub} />
<ProtectedRoute path="/development" component={DevelopmentModule} />
<ProtectedRoute path="/retail" component={ArcadiaRetail} />
<ProtectedRoute path="/plus" component={Plus} />
<ProtectedRoute path="/super-admin" component={SuperAdmin} />
<ProtectedRoute path="/marketplace" component={Marketplace} />
<ProtectedRoute path="/lms" component={LMS} />
<ProtectedRoute path="/apps" component={AppCenter} />
<ProtectedRoute path="/xos" component={XosCentral} />
<ProtectedRoute path="/xos/crm" component={XosCrm} />
<ProtectedRoute path="/xos/inbox" component={XosInbox} />
<ProtectedRoute path="/xos/tickets" component={XosTickets} />
<ProtectedRoute path="/xos/campaigns" component={XosCampaigns} />
<ProtectedRoute path="/xos/automations" component={XosAutomations} />
<ProtectedRoute path="/xos/sites" component={XosSites} />
<ProtectedRoute path="/xos/governance" component={XosGovernance} />
<ProtectedRoute path="/xos/pipeline" component={XosPipeline} />
<ProtectedRoute path="/doctype-builder" component={DocTypeBuilder} />
<ProtectedRoute path="/page-builder" component={PageBuilder} />
<ProtectedRoute path="/migration" component={Migration} />
<ProtectedRoute path="/dev-center" component={DevCenter} />
<ProtectedRoute path="/page/:id" component={WorkspacePage} />
<ProtectedRoute path="/app/:id" component={AppViewer} />
<Route path="/auth" component={AuthPage} />
<Route component={NotFound} />
</Switch>
);
}
function App() {
return (
<QueryClientProvider client={queryClient}>
<AuthProvider>
<ErpProfileProvider>
<TooltipProvider>
<KnowledgeCollectorInit />
<Toaster />
<CommandPalette />
<Router />
</TooltipProvider>
</ErpProfileProvider>
</AuthProvider>
</QueryClientProvider>
);
}
export default App;

View File

@ -0,0 +1,651 @@
import { useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
Plus,
Play,
Save,
Trash2,
Edit,
Send,
Clock,
CheckCircle,
XCircle,
RefreshCw,
Copy,
Eye,
EyeOff,
PlugZap,
Code,
FileJson,
} from "lucide-react";
interface ApiConnection {
id: number;
name: string;
type: string;
base_url: string;
api_key?: string;
status: string;
last_sync_at?: string;
}
interface ApiEndpoint {
id: number;
connection_id: number;
name: string;
method: string;
path: string;
description?: string;
headers?: Record<string, string>;
body_template?: string;
}
interface ApiLog {
id: number;
method: string;
url: string;
response_status: number;
latency_ms: number;
created_at: string;
}
export default function ApiTester() {
const queryClient = useQueryClient();
const [showNewConnectionDialog, setShowNewConnectionDialog] = useState(false);
const [showNewEndpointDialog, setShowNewEndpointDialog] = useState(false);
const [showExecuteDialog, setShowExecuteDialog] = useState(false);
const [selectedConnection, setSelectedConnection] = useState<ApiConnection | null>(null);
const [showApiKey, setShowApiKey] = useState(false);
const [newConnection, setNewConnection] = useState({
name: "",
type: "rest",
baseUrl: "",
apiKey: "",
apiSecret: "",
});
const [newEndpoint, setNewEndpoint] = useState({
name: "",
method: "GET",
path: "",
description: "",
bodyTemplate: "",
});
const [executeRequest, setExecuteRequest] = useState({
method: "GET",
url: "",
headers: "{}",
body: "",
});
const [executeResponse, setExecuteResponse] = useState<{
status?: number;
body?: string;
latency?: number;
error?: string;
} | null>(null);
const { data: connections = [] } = useQuery<ApiConnection[]>({
queryKey: ["/api/api-central/connections"],
queryFn: async () => {
const res = await fetch("/api/api-central/connections", { credentials: "include" });
if (!res.ok) return [];
return res.json();
},
});
const { data: endpoints = [] } = useQuery<ApiEndpoint[]>({
queryKey: ["/api/api-central/endpoints", selectedConnection?.id],
queryFn: async () => {
if (!selectedConnection) return [];
const res = await fetch(`/api/api-central/connections/${selectedConnection.id}/endpoints`, { credentials: "include" });
if (!res.ok) return [];
return res.json();
},
enabled: !!selectedConnection,
});
const { data: logs = [] } = useQuery<ApiLog[]>({
queryKey: ["/api/api-central/logs"],
queryFn: async () => {
const res = await fetch("/api/api-central/logs?limit=20", { credentials: "include" });
if (!res.ok) return [];
return res.json();
},
});
const createConnectionMutation = useMutation({
mutationFn: async (data: typeof newConnection) => {
const res = await fetch("/api/api-central/connections", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
name: data.name,
type: data.type,
baseUrl: data.baseUrl,
apiKey: data.apiKey,
apiSecret: data.apiSecret,
}),
credentials: "include",
});
if (!res.ok) throw new Error("Falha ao criar conexão");
return res.json();
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["/api/api-central/connections"] });
setShowNewConnectionDialog(false);
setNewConnection({ name: "", type: "rest", baseUrl: "", apiKey: "", apiSecret: "" });
},
});
const deleteConnectionMutation = useMutation({
mutationFn: async (id: number) => {
const res = await fetch(`/api/api-central/connections/${id}`, {
method: "DELETE",
credentials: "include",
});
if (!res.ok) throw new Error("Falha ao deletar");
return res.json();
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["/api/api-central/connections"] });
setSelectedConnection(null);
},
});
const createEndpointMutation = useMutation({
mutationFn: async (data: typeof newEndpoint) => {
if (!selectedConnection) throw new Error("Selecione uma conexão");
const res = await fetch(`/api/api-central/connections/${selectedConnection.id}/endpoints`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
credentials: "include",
});
if (!res.ok) throw new Error("Falha ao criar endpoint");
return res.json();
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["/api/api-central/endpoints", selectedConnection?.id] });
setShowNewEndpointDialog(false);
setNewEndpoint({ name: "", method: "GET", path: "", description: "", bodyTemplate: "" });
},
});
const executeMutation = useMutation({
mutationFn: async (data: typeof executeRequest) => {
const res = await fetch("/api/api-central/execute", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
connectionId: selectedConnection?.id,
method: data.method,
url: data.url,
headers: JSON.parse(data.headers || "{}"),
body: data.body ? JSON.parse(data.body) : undefined,
}),
credentials: "include",
});
return res.json();
},
onSuccess: (result) => {
setExecuteResponse({
status: result.status,
body: result.body,
latency: result.latency,
error: result.error,
});
queryClient.invalidateQueries({ queryKey: ["/api/api-central/logs"] });
},
onError: (error: any) => {
setExecuteResponse({ error: error.message });
},
});
const testConnectionMutation = useMutation({
mutationFn: async (id: number) => {
const res = await fetch(`/api/api-central/connections/${id}/test`, {
method: "POST",
credentials: "include",
});
return res.json();
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["/api/api-central/connections"] });
},
});
const getMethodColor = (method: string) => {
switch (method) {
case "GET": return "bg-green-500/20 text-green-400";
case "POST": return "bg-blue-500/20 text-blue-400";
case "PUT": return "bg-amber-500/20 text-amber-400";
case "DELETE": return "bg-red-500/20 text-red-400";
default: return "bg-slate-500/20 text-slate-400";
}
};
const getStatusColor = (status: number) => {
if (status >= 200 && status < 300) return "bg-green-500/20 text-green-400";
if (status >= 400) return "bg-red-500/20 text-red-400";
return "bg-amber-500/20 text-amber-400";
};
return (
<div className="h-full flex bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 text-white">
{/* Sidebar - Conexões */}
<div className="w-72 border-r border-slate-700/50 flex flex-col">
<div className="p-4 border-b border-slate-700/50">
<div className="flex items-center justify-between mb-3">
<h2 className="font-semibold flex items-center gap-2">
<PlugZap className="h-5 w-5 text-cyan-400" />
Minhas Conexões
</h2>
<Button
size="sm"
className="bg-cyan-600 hover:bg-cyan-700 h-8"
onClick={() => setShowNewConnectionDialog(true)}
>
<Plus className="h-4 w-4" />
</Button>
</div>
</div>
<ScrollArea className="flex-1">
<div className="p-2 space-y-1">
{connections.map((conn) => (
<div
key={conn.id}
onClick={() => setSelectedConnection(conn)}
className={`p-3 rounded-lg cursor-pointer transition-colors ${
selectedConnection?.id === conn.id
? "bg-cyan-500/20 border border-cyan-500/30"
: "hover:bg-slate-800/50"
}`}
>
<div className="flex items-center justify-between">
<span className="font-medium truncate">{conn.name}</span>
<div className={`w-2 h-2 rounded-full ${
conn.status === "connected" ? "bg-green-500" : "bg-slate-500"
}`} />
</div>
<p className="text-xs text-slate-500 truncate mt-1">{conn.base_url}</p>
</div>
))}
{connections.length === 0 && (
<div className="text-center text-slate-500 py-8">
<PlugZap className="h-8 w-8 mx-auto mb-2 opacity-50" />
<p className="text-sm">Nenhuma conexão</p>
<p className="text-xs">Clique em + para adicionar</p>
</div>
)}
</div>
</ScrollArea>
</div>
{/* Main Content */}
<div className="flex-1 flex flex-col">
{selectedConnection ? (
<Tabs defaultValue="endpoints" className="flex-1 flex flex-col">
<div className="p-4 border-b border-slate-700/50">
<div className="flex items-center justify-between mb-3">
<div>
<h2 className="text-xl font-bold">{selectedConnection.name}</h2>
<p className="text-sm text-slate-400">{selectedConnection.base_url}</p>
</div>
<div className="flex gap-2">
<Button
variant="outline"
size="sm"
className="border-slate-600"
onClick={() => testConnectionMutation.mutate(selectedConnection.id)}
disabled={testConnectionMutation.isPending}
>
{testConnectionMutation.isPending ? (
<RefreshCw className="h-4 w-4 animate-spin" />
) : (
<Play className="h-4 w-4" />
)}
Testar
</Button>
<Button
variant="outline"
size="sm"
className="border-red-500/50 text-red-400 hover:bg-red-500/10"
onClick={() => {
if (confirm("Deletar esta conexão?")) {
deleteConnectionMutation.mutate(selectedConnection.id);
}
}}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</div>
<TabsList className="bg-slate-800">
<TabsTrigger value="endpoints">Endpoints</TabsTrigger>
<TabsTrigger value="execute">Executar</TabsTrigger>
<TabsTrigger value="logs">Logs</TabsTrigger>
</TabsList>
</div>
<TabsContent value="endpoints" className="flex-1 p-4 mt-0 overflow-auto">
<div className="flex justify-between items-center mb-4">
<h3 className="font-semibold">Endpoints Salvos</h3>
<Button
size="sm"
className="bg-cyan-600 hover:bg-cyan-700"
onClick={() => setShowNewEndpointDialog(true)}
>
<Plus className="h-4 w-4 mr-1" />
Novo Endpoint
</Button>
</div>
<div className="space-y-2">
{endpoints.map((endpoint) => (
<Card key={endpoint.id} className="bg-slate-800/50 border-slate-700">
<CardContent className="p-3 flex items-center justify-between">
<div className="flex items-center gap-3">
<Badge className={getMethodColor(endpoint.method)}>
{endpoint.method}
</Badge>
<code className="text-cyan-300 text-sm">{endpoint.path}</code>
{endpoint.name && (
<span className="text-slate-400 text-sm">- {endpoint.name}</span>
)}
</div>
<Button
size="sm"
variant="ghost"
onClick={() => {
setExecuteRequest({
method: endpoint.method,
url: selectedConnection.base_url + endpoint.path,
headers: JSON.stringify(endpoint.headers || {}, null, 2),
body: endpoint.body_template || "",
});
setShowExecuteDialog(true);
}}
>
<Play className="h-4 w-4 mr-1" />
Executar
</Button>
</CardContent>
</Card>
))}
{endpoints.length === 0 && (
<div className="text-center text-slate-500 py-12">
<Code className="h-12 w-12 mx-auto mb-3 opacity-50" />
<p>Nenhum endpoint salvo</p>
<p className="text-sm">Adicione endpoints para reutilizar</p>
</div>
)}
</div>
</TabsContent>
<TabsContent value="execute" className="flex-1 p-4 mt-0 overflow-auto">
<div className="grid grid-cols-2 gap-4 h-full">
<div className="space-y-4">
<div className="flex gap-2">
<select
value={executeRequest.method}
onChange={(e) => setExecuteRequest({ ...executeRequest, method: e.target.value })}
className="bg-slate-800 border border-slate-700 rounded-md px-3 py-2 text-white w-28"
>
<option value="GET">GET</option>
<option value="POST">POST</option>
<option value="PUT">PUT</option>
<option value="DELETE">DELETE</option>
<option value="PATCH">PATCH</option>
</select>
<Input
value={executeRequest.url}
onChange={(e) => setExecuteRequest({ ...executeRequest, url: e.target.value })}
placeholder="https://api.exemplo.com/endpoint"
className="flex-1 bg-slate-800 border-slate-700 text-white"
/>
<Button
className="bg-green-600 hover:bg-green-700"
onClick={() => executeMutation.mutate(executeRequest)}
disabled={executeMutation.isPending}
>
{executeMutation.isPending ? (
<RefreshCw className="h-4 w-4 animate-spin" />
) : (
<Send className="h-4 w-4" />
)}
</Button>
</div>
<div>
<label className="text-sm text-slate-400 mb-1 block">Headers (JSON)</label>
<Textarea
value={executeRequest.headers}
onChange={(e) => setExecuteRequest({ ...executeRequest, headers: e.target.value })}
placeholder='{"Authorization": "Bearer token"}'
className="bg-slate-800 border-slate-700 text-white font-mono text-sm h-24"
/>
</div>
{executeRequest.method !== "GET" && (
<div>
<label className="text-sm text-slate-400 mb-1 block">Body (JSON)</label>
<Textarea
value={executeRequest.body}
onChange={(e) => setExecuteRequest({ ...executeRequest, body: e.target.value })}
placeholder='{"key": "value"}'
className="bg-slate-800 border-slate-700 text-white font-mono text-sm h-32"
/>
</div>
)}
</div>
<div>
<div className="flex items-center justify-between mb-2">
<label className="text-sm text-slate-400">Resposta</label>
{executeResponse?.status && (
<div className="flex items-center gap-2">
<Badge className={getStatusColor(executeResponse.status)}>
{executeResponse.status}
</Badge>
<span className="text-xs text-slate-500">{executeResponse.latency}ms</span>
</div>
)}
</div>
<div className="bg-slate-950 rounded-lg p-4 h-[calc(100%-2rem)] overflow-auto font-mono text-sm">
{executeResponse?.body ? (
<pre className="text-green-400 whitespace-pre-wrap">{executeResponse.body}</pre>
) : executeResponse?.error ? (
<pre className="text-red-400">{executeResponse.error}</pre>
) : (
<span className="text-slate-500">Execute uma requisição para ver a resposta</span>
)}
</div>
</div>
</div>
</TabsContent>
<TabsContent value="logs" className="flex-1 p-4 mt-0 overflow-auto">
<ScrollArea className="h-full">
<div className="space-y-2">
{logs.map((log) => (
<div key={log.id} className="p-3 rounded-lg bg-slate-800/50 flex items-center gap-3">
<span className="text-slate-500 text-xs w-20">
{new Date(log.created_at).toLocaleTimeString()}
</span>
<Badge className={getStatusColor(log.response_status)}>
{log.response_status}
</Badge>
<Badge className={getMethodColor(log.method)}>
{log.method}
</Badge>
<span className="text-slate-300 text-sm truncate flex-1">{log.url}</span>
<span className="text-slate-500 text-xs">{log.latency_ms}ms</span>
</div>
))}
{logs.length === 0 && (
<div className="text-center text-slate-500 py-12">
<FileJson className="h-12 w-12 mx-auto mb-3 opacity-50" />
<p>Nenhum log ainda</p>
</div>
)}
</div>
</ScrollArea>
</TabsContent>
</Tabs>
) : (
<div className="flex-1 flex items-center justify-center">
<div className="text-center">
<PlugZap className="h-16 w-16 mx-auto mb-4 text-slate-600" />
<h2 className="text-xl font-semibold mb-2">API Tester</h2>
<p className="text-slate-400 mb-6">
Crie conexões e teste APIs em tempo real
</p>
<Button
className="bg-cyan-600 hover:bg-cyan-700"
onClick={() => setShowNewConnectionDialog(true)}
>
<Plus className="h-4 w-4 mr-2" />
Nova Conexão
</Button>
</div>
</div>
)}
</div>
{/* Dialog: Nova Conexão */}
<Dialog open={showNewConnectionDialog} onOpenChange={setShowNewConnectionDialog}>
<DialogContent className="bg-slate-900 border-slate-700 text-white">
<DialogHeader>
<DialogTitle>Nova Conexão de API</DialogTitle>
</DialogHeader>
<div className="space-y-4">
<div>
<label className="text-sm text-slate-400 mb-1 block">Nome</label>
<Input
value={newConnection.name}
onChange={(e) => setNewConnection({ ...newConnection, name: e.target.value })}
placeholder="Minha API"
className="bg-slate-800 border-slate-700 text-white"
/>
</div>
<div>
<label className="text-sm text-slate-400 mb-1 block">URL Base</label>
<Input
value={newConnection.baseUrl}
onChange={(e) => setNewConnection({ ...newConnection, baseUrl: e.target.value })}
placeholder="https://api.exemplo.com"
className="bg-slate-800 border-slate-700 text-white"
/>
</div>
<div>
<label className="text-sm text-slate-400 mb-1 block">API Key (opcional)</label>
<div className="relative">
<Input
type={showApiKey ? "text" : "password"}
value={newConnection.apiKey}
onChange={(e) => setNewConnection({ ...newConnection, apiKey: e.target.value })}
placeholder="sua-api-key"
className="bg-slate-800 border-slate-700 text-white pr-10"
/>
<Button
type="button"
size="icon"
variant="ghost"
className="absolute right-1 top-1/2 -translate-y-1/2 h-7 w-7"
onClick={() => setShowApiKey(!showApiKey)}
>
{showApiKey ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
</Button>
</div>
</div>
</div>
<DialogFooter>
<Button variant="ghost" onClick={() => setShowNewConnectionDialog(false)}>
Cancelar
</Button>
<Button
className="bg-cyan-600 hover:bg-cyan-700"
onClick={() => createConnectionMutation.mutate(newConnection)}
disabled={createConnectionMutation.isPending || !newConnection.name || !newConnection.baseUrl}
>
{createConnectionMutation.isPending ? "Criando..." : "Criar Conexão"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* Dialog: Novo Endpoint */}
<Dialog open={showNewEndpointDialog} onOpenChange={setShowNewEndpointDialog}>
<DialogContent className="bg-slate-900 border-slate-700 text-white">
<DialogHeader>
<DialogTitle>Novo Endpoint</DialogTitle>
</DialogHeader>
<div className="space-y-4">
<div className="flex gap-2">
<div className="w-28">
<label className="text-sm text-slate-400 mb-1 block">Método</label>
<select
value={newEndpoint.method}
onChange={(e) => setNewEndpoint({ ...newEndpoint, method: e.target.value })}
className="w-full bg-slate-800 border border-slate-700 rounded-md px-3 py-2 text-white"
>
<option value="GET">GET</option>
<option value="POST">POST</option>
<option value="PUT">PUT</option>
<option value="DELETE">DELETE</option>
</select>
</div>
<div className="flex-1">
<label className="text-sm text-slate-400 mb-1 block">Path</label>
<Input
value={newEndpoint.path}
onChange={(e) => setNewEndpoint({ ...newEndpoint, path: e.target.value })}
placeholder="/users"
className="bg-slate-800 border-slate-700 text-white"
/>
</div>
</div>
<div>
<label className="text-sm text-slate-400 mb-1 block">Nome (opcional)</label>
<Input
value={newEndpoint.name}
onChange={(e) => setNewEndpoint({ ...newEndpoint, name: e.target.value })}
placeholder="Listar usuários"
className="bg-slate-800 border-slate-700 text-white"
/>
</div>
<div>
<label className="text-sm text-slate-400 mb-1 block">Descrição (opcional)</label>
<Input
value={newEndpoint.description}
onChange={(e) => setNewEndpoint({ ...newEndpoint, description: e.target.value })}
placeholder="Retorna todos os usuários do sistema"
className="bg-slate-800 border-slate-700 text-white"
/>
</div>
</div>
<DialogFooter>
<Button variant="ghost" onClick={() => setShowNewEndpointDialog(false)}>
Cancelar
</Button>
<Button
className="bg-cyan-600 hover:bg-cyan-700"
onClick={() => createEndpointMutation.mutate(newEndpoint)}
disabled={createEndpointMutation.isPending || !newEndpoint.path}
>
{createEndpointMutation.isPending ? "Criando..." : "Criar Endpoint"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
}

View File

@ -0,0 +1,645 @@
import { useState, useRef, useCallback, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import {
Circle,
Square,
Diamond,
ArrowRight,
Trash2,
ZoomIn,
ZoomOut,
RotateCcw,
Save,
Play,
StopCircle,
Timer,
Mail,
MessageSquare,
GitBranch,
Layers,
Move,
} from "lucide-react";
// ═══════════════════════════════════════════════════
// TIPOS BPMN
// ═══════════════════════════════════════════════════
export type BpmnElementType =
| "startEvent"
| "endEvent"
| "task"
| "userTask"
| "serviceTask"
| "timerEvent"
| "messageEvent"
| "exclusiveGateway"
| "parallelGateway"
| "inclusiveGateway"
| "subProcess"
| "lane";
export interface BpmnNode {
id: string;
type: BpmnElementType;
x: number;
y: number;
width: number;
height: number;
label: string;
color?: string;
}
export interface BpmnConnection {
id: string;
sourceId: string;
targetId: string;
label?: string;
}
export interface BpmnDiagramData {
nodes: BpmnNode[];
connections: BpmnConnection[];
}
// ═══════════════════════════════════════════════════
// PALETA DE ELEMENTOS BPMN
// ═══════════════════════════════════════════════════
const BPMN_PALETTE: {
category: string;
items: { type: BpmnElementType; label: string; icon: any }[];
}[] = [
{
category: "Eventos",
items: [
{ type: "startEvent", label: "Início", icon: Play },
{ type: "endEvent", label: "Fim", icon: StopCircle },
{ type: "timerEvent", label: "Timer", icon: Timer },
{ type: "messageEvent", label: "Mensagem", icon: Mail },
],
},
{
category: "Atividades",
items: [
{ type: "task", label: "Tarefa", icon: Square },
{ type: "userTask", label: "Tarefa Usuário", icon: MessageSquare },
{ type: "serviceTask", label: "Tarefa Serviço", icon: Layers },
{ type: "subProcess", label: "Sub-Processo", icon: GitBranch },
],
},
{
category: "Gateways",
items: [
{ type: "exclusiveGateway", label: "Exclusivo (XOR)", icon: Diamond },
{ type: "parallelGateway", label: "Paralelo (AND)", icon: Diamond },
{ type: "inclusiveGateway", label: "Inclusivo (OR)", icon: Diamond },
],
},
];
const DEFAULT_SIZES: Record<BpmnElementType, { w: number; h: number }> = {
startEvent: { w: 40, h: 40 },
endEvent: { w: 40, h: 40 },
timerEvent: { w: 40, h: 40 },
messageEvent: { w: 40, h: 40 },
task: { w: 140, h: 60 },
userTask: { w: 140, h: 60 },
serviceTask: { w: 140, h: 60 },
subProcess: { w: 160, h: 80 },
exclusiveGateway: { w: 50, h: 50 },
parallelGateway: { w: 50, h: 50 },
inclusiveGateway: { w: 50, h: 50 },
lane: { w: 600, h: 200 },
};
// ═══════════════════════════════════════════════════
// RENDERIZADORES SVG DOS ELEMENTOS
// ═══════════════════════════════════════════════════
function renderBpmnElement(
node: BpmnNode,
isSelected: boolean,
isConnecting: boolean
) {
const { x, y, width, height, type, label } = node;
const cx = x + width / 2;
const cy = y + height / 2;
const strokeColor = isSelected ? "#3b82f6" : isConnecting ? "#f59e0b" : "#64748b";
const strokeWidth = isSelected ? 2.5 : 1.5;
switch (type) {
case "startEvent":
return (
<g key={node.id}>
<circle cx={cx} cy={cy} r={18} fill="#dcfce7" stroke="#22c55e" strokeWidth={strokeWidth} />
<polygon points={`${cx - 5},${cy - 8} ${cx - 5},${cy + 8} ${cx + 7},${cy}`} fill="#22c55e" />
<text x={cx} y={cy + 32} textAnchor="middle" fontSize={11} fill="#374151">{label}</text>
</g>
);
case "endEvent":
return (
<g key={node.id}>
<circle cx={cx} cy={cy} r={18} fill="#fce7f3" stroke="#ef4444" strokeWidth={3} />
<rect x={cx - 6} y={cy - 6} width={12} height={12} rx={2} fill="#ef4444" />
<text x={cx} y={cy + 32} textAnchor="middle" fontSize={11} fill="#374151">{label}</text>
</g>
);
case "timerEvent":
return (
<g key={node.id}>
<circle cx={cx} cy={cy} r={18} fill="#fef3c7" stroke="#f59e0b" strokeWidth={strokeWidth} />
<circle cx={cx} cy={cy} r={12} fill="none" stroke="#f59e0b" strokeWidth={1} />
<line x1={cx} y1={cy} x2={cx} y2={cy - 8} stroke="#f59e0b" strokeWidth={1.5} />
<line x1={cx} y1={cy} x2={cx + 6} y2={cy + 3} stroke="#f59e0b" strokeWidth={1.5} />
<text x={cx} y={cy + 32} textAnchor="middle" fontSize={11} fill="#374151">{label}</text>
</g>
);
case "messageEvent":
return (
<g key={node.id}>
<circle cx={cx} cy={cy} r={18} fill="#dbeafe" stroke="#3b82f6" strokeWidth={strokeWidth} />
<rect x={cx - 9} y={cy - 6} width={18} height={12} rx={1} fill="none" stroke="#3b82f6" strokeWidth={1.2} />
<polyline points={`${cx - 9},${cy - 6} ${cx},${cy + 1} ${cx + 9},${cy - 6}`} fill="none" stroke="#3b82f6" strokeWidth={1.2} />
<text x={cx} y={cy + 32} textAnchor="middle" fontSize={11} fill="#374151">{label}</text>
</g>
);
case "task":
case "userTask":
case "serviceTask":
const taskFill = type === "userTask" ? "#eff6ff" : type === "serviceTask" ? "#f0fdf4" : "#fff";
const taskStroke = type === "userTask" ? "#3b82f6" : type === "serviceTask" ? "#22c55e" : strokeColor;
const iconChar = type === "userTask" ? "👤" : type === "serviceTask" ? "⚙️" : "";
return (
<g key={node.id}>
<rect x={x} y={y} width={width} height={height} rx={8} fill={taskFill}
stroke={taskStroke} strokeWidth={strokeWidth} filter="url(#shadow)" />
{iconChar && (
<text x={x + 8} y={y + 16} fontSize={12}>{iconChar}</text>
)}
<text x={cx} y={cy + 4} textAnchor="middle" fontSize={12} fill="#1f2937" fontWeight="500">
{label.length > 18 ? label.slice(0, 18) + "…" : label}
</text>
</g>
);
case "subProcess":
return (
<g key={node.id}>
<rect x={x} y={y} width={width} height={height} rx={8} fill="#faf5ff"
stroke="#8b5cf6" strokeWidth={strokeWidth} strokeDasharray="6 3" filter="url(#shadow)" />
<text x={cx} y={cy + 4} textAnchor="middle" fontSize={12} fill="#1f2937" fontWeight="500">
{label.length > 20 ? label.slice(0, 20) + "…" : label}
</text>
<rect x={cx - 6} y={y + height - 14} width={12} height={8} rx={1} fill="none" stroke="#8b5cf6" strokeWidth={1} />
<line x1={cx} y1={y + height - 14} x2={cx} y2={y + height - 6} stroke="#8b5cf6" strokeWidth={1} />
</g>
);
case "exclusiveGateway":
case "parallelGateway":
case "inclusiveGateway": {
const gFill = type === "exclusiveGateway" ? "#fef9c3" : type === "parallelGateway" ? "#cffafe" : "#fce7f3";
const gStroke = type === "exclusiveGateway" ? "#eab308" : type === "parallelGateway" ? "#06b6d4" : "#ec4899";
return (
<g key={node.id}>
<polygon
points={`${cx},${y} ${x + width},${cy} ${cx},${y + height} ${x},${cy}`}
fill={gFill} stroke={gStroke} strokeWidth={strokeWidth}
/>
{type === "exclusiveGateway" && (
<>
<line x1={cx - 8} y1={cy - 8} x2={cx + 8} y2={cy + 8} stroke={gStroke} strokeWidth={2.5} />
<line x1={cx + 8} y1={cy - 8} x2={cx - 8} y2={cy + 8} stroke={gStroke} strokeWidth={2.5} />
</>
)}
{type === "parallelGateway" && (
<>
<line x1={cx} y1={cy - 10} x2={cx} y2={cy + 10} stroke={gStroke} strokeWidth={2.5} />
<line x1={cx - 10} y1={cy} x2={cx + 10} y2={cy} stroke={gStroke} strokeWidth={2.5} />
</>
)}
{type === "inclusiveGateway" && (
<circle cx={cx} cy={cy} r={10} fill="none" stroke={gStroke} strokeWidth={2.5} />
)}
<text x={cx} y={cy + height / 2 + 16} textAnchor="middle" fontSize={11} fill="#374151">{label}</text>
</g>
);
}
default:
return null;
}
}
function getConnectionPoint(node: BpmnNode, side: "left" | "right" | "top" | "bottom") {
const cx = node.x + node.width / 2;
const cy = node.y + node.height / 2;
switch (side) {
case "right": return { x: node.x + node.width, y: cy };
case "left": return { x: node.x, y: cy };
case "bottom": return { x: cx, y: node.y + node.height };
case "top": return { x: cx, y: node.y };
}
}
function getBestConnectionPoints(source: BpmnNode, target: BpmnNode) {
const scx = source.x + source.width / 2;
const scy = source.y + source.height / 2;
const tcx = target.x + target.width / 2;
const tcy = target.y + target.height / 2;
const dx = tcx - scx;
const dy = tcy - scy;
let sourceSide: "left" | "right" | "top" | "bottom";
let targetSide: "left" | "right" | "top" | "bottom";
if (Math.abs(dx) > Math.abs(dy)) {
sourceSide = dx > 0 ? "right" : "left";
targetSide = dx > 0 ? "left" : "right";
} else {
sourceSide = dy > 0 ? "bottom" : "top";
targetSide = dy > 0 ? "top" : "bottom";
}
return {
source: getConnectionPoint(source, sourceSide),
target: getConnectionPoint(target, targetSide),
};
}
// ═══════════════════════════════════════════════════
// COMPONENTE PRINCIPAL
// ═══════════════════════════════════════════════════
interface BpmnDiagramProps {
initialData?: BpmnDiagramData;
onSave?: (data: BpmnDiagramData) => void;
processName?: string;
}
export default function BpmnDiagram({ initialData, onSave, processName }: BpmnDiagramProps) {
const [nodes, setNodes] = useState<BpmnNode[]>(initialData?.nodes || []);
const [connections, setConnections] = useState<BpmnConnection[]>(initialData?.connections || []);
const [selectedNodeId, setSelectedNodeId] = useState<string | null>(null);
const [connectingFrom, setConnectingFrom] = useState<string | null>(null);
const [dragging, setDragging] = useState<{ nodeId: string; offsetX: number; offsetY: number } | null>(null);
const [editingLabel, setEditingLabel] = useState<string | null>(null);
const [zoom, setZoom] = useState(1);
const [pan, setPan] = useState({ x: 0, y: 0 });
const svgRef = useRef<SVGSVGElement>(null);
const [mode, setMode] = useState<"select" | "connect">("select");
const generateId = () => `bpmn_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
const addNode = useCallback((type: BpmnElementType) => {
const size = DEFAULT_SIZES[type];
const newNode: BpmnNode = {
id: generateId(),
type,
x: 200 + Math.random() * 300,
y: 100 + Math.random() * 200,
width: size.w,
height: size.h,
label: BPMN_PALETTE.flatMap(c => c.items).find(i => i.type === type)?.label || type,
};
setNodes(prev => [...prev, newNode]);
setSelectedNodeId(newNode.id);
}, []);
const deleteSelected = useCallback(() => {
if (!selectedNodeId) return;
setNodes(prev => prev.filter(n => n.id !== selectedNodeId));
setConnections(prev => prev.filter(c => c.sourceId !== selectedNodeId && c.targetId !== selectedNodeId));
setSelectedNodeId(null);
}, [selectedNodeId]);
const handleSvgMouseDown = useCallback((e: React.MouseEvent<SVGSVGElement>) => {
const target = e.target as SVGElement;
const nodeG = target.closest("[data-node-id]");
if (nodeG) {
const nodeId = nodeG.getAttribute("data-node-id")!;
const node = nodes.find(n => n.id === nodeId);
if (!node) return;
if (mode === "connect") {
if (!connectingFrom) {
setConnectingFrom(nodeId);
} else if (connectingFrom !== nodeId) {
const exists = connections.some(
c => (c.sourceId === connectingFrom && c.targetId === nodeId)
);
if (!exists) {
setConnections(prev => [...prev, {
id: generateId(),
sourceId: connectingFrom,
targetId: nodeId,
}]);
}
setConnectingFrom(null);
}
return;
}
setSelectedNodeId(nodeId);
const svgRect = svgRef.current!.getBoundingClientRect();
const mouseX = (e.clientX - svgRect.left - pan.x) / zoom;
const mouseY = (e.clientY - svgRect.top - pan.y) / zoom;
setDragging({ nodeId, offsetX: mouseX - node.x, offsetY: mouseY - node.y });
} else {
setSelectedNodeId(null);
setConnectingFrom(null);
}
}, [nodes, mode, connectingFrom, connections, zoom, pan]);
const handleSvgMouseMove = useCallback((e: React.MouseEvent<SVGSVGElement>) => {
if (!dragging) return;
const svgRect = svgRef.current!.getBoundingClientRect();
const mouseX = (e.clientX - svgRect.left - pan.x) / zoom;
const mouseY = (e.clientY - svgRect.top - pan.y) / zoom;
setNodes(prev => prev.map(n =>
n.id === dragging.nodeId
? { ...n, x: Math.max(0, mouseX - dragging.offsetX), y: Math.max(0, mouseY - dragging.offsetY) }
: n
));
}, [dragging, zoom, pan]);
const handleSvgMouseUp = useCallback(() => {
setDragging(null);
}, []);
const handleLabelChange = useCallback((nodeId: string, newLabel: string) => {
setNodes(prev => prev.map(n => n.id === nodeId ? { ...n, label: newLabel } : n));
}, []);
const handleSave = useCallback(() => {
onSave?.({ nodes, connections });
}, [nodes, connections, onSave]);
const resetView = useCallback(() => {
setZoom(1);
setPan({ x: 0, y: 0 });
}, []);
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === "Delete" || e.key === "Backspace") {
if (editingLabel) return;
deleteSelected();
}
if (e.key === "Escape") {
setSelectedNodeId(null);
setConnectingFrom(null);
setMode("select");
}
};
window.addEventListener("keydown", handleKeyDown);
return () => window.removeEventListener("keydown", handleKeyDown);
}, [deleteSelected, editingLabel]);
const selectedNode = nodes.find(n => n.id === selectedNodeId);
return (
<div className="flex flex-col h-full border rounded-lg overflow-hidden bg-white" data-testid="bpmn-diagram">
{/* Toolbar */}
<div className="flex items-center justify-between border-b px-3 py-2 bg-muted/30">
<div className="flex items-center gap-2">
<span className="font-semibold text-sm">{processName || "Diagramador BPMN"}</span>
<Badge variant="outline" className="text-xs">{nodes.length} elementos</Badge>
<Badge variant="outline" className="text-xs">{connections.length} conexões</Badge>
</div>
<div className="flex items-center gap-1">
<Button
variant={mode === "select" ? "default" : "ghost"}
size="sm"
onClick={() => { setMode("select"); setConnectingFrom(null); }}
data-testid="btn-mode-select"
>
<Move className="h-4 w-4" />
</Button>
<Button
variant={mode === "connect" ? "default" : "ghost"}
size="sm"
onClick={() => setMode("connect")}
data-testid="btn-mode-connect"
>
<ArrowRight className="h-4 w-4" />
</Button>
<div className="w-px h-5 bg-border mx-1" />
<Button variant="ghost" size="sm" onClick={() => setZoom(z => Math.min(2, z + 0.1))} data-testid="btn-zoom-in">
<ZoomIn className="h-4 w-4" />
</Button>
<span className="text-xs w-10 text-center">{Math.round(zoom * 100)}%</span>
<Button variant="ghost" size="sm" onClick={() => setZoom(z => Math.max(0.3, z - 0.1))} data-testid="btn-zoom-out">
<ZoomOut className="h-4 w-4" />
</Button>
<Button variant="ghost" size="sm" onClick={resetView}>
<RotateCcw className="h-4 w-4" />
</Button>
<div className="w-px h-5 bg-border mx-1" />
{selectedNodeId && (
<Button variant="ghost" size="sm" onClick={deleteSelected} className="text-red-500" data-testid="btn-delete">
<Trash2 className="h-4 w-4" />
</Button>
)}
<Button variant="default" size="sm" onClick={handleSave} data-testid="btn-save-bpmn">
<Save className="h-4 w-4 mr-1" /> Salvar
</Button>
</div>
</div>
<div className="flex flex-1 overflow-hidden">
{/* Painel lateral de elementos */}
<div className="w-48 border-r bg-muted/20 overflow-y-auto p-2" data-testid="bpmn-palette">
{BPMN_PALETTE.map(category => (
<div key={category.category} className="mb-3">
<p className="text-[10px] font-semibold text-muted-foreground uppercase tracking-wider px-2 mb-1">
{category.category}
</p>
{category.items.map(item => {
const Icon = item.icon;
return (
<button
key={item.type}
className="flex items-center gap-2 w-full px-2 py-1.5 rounded text-sm hover:bg-muted transition-colors text-left"
onClick={() => addNode(item.type)}
data-testid={`palette-${item.type}`}
>
<Icon className="h-3.5 w-3.5 text-muted-foreground" />
<span>{item.label}</span>
</button>
);
})}
</div>
))}
{mode === "connect" && (
<div className="mt-3 p-2 bg-amber-50 border border-amber-200 rounded text-xs text-amber-700">
Modo conexão: clique no elemento de origem e depois no destino.
</div>
)}
{connectingFrom && (
<div className="mt-2 p-2 bg-blue-50 border border-blue-200 rounded text-xs text-blue-700">
Conectando de: {nodes.find(n => n.id === connectingFrom)?.label}
</div>
)}
</div>
{/* Canvas SVG */}
<div className="flex-1 relative overflow-hidden bg-[#fafbfc]">
<svg
ref={svgRef}
className="w-full h-full cursor-crosshair"
onMouseDown={handleSvgMouseDown}
onMouseMove={handleSvgMouseMove}
onMouseUp={handleSvgMouseUp}
onMouseLeave={handleSvgMouseUp}
data-testid="bpmn-canvas"
>
<defs>
<filter id="shadow" x="-4%" y="-4%" width="108%" height="108%">
<feDropShadow dx="0" dy="1" stdDeviation="2" floodOpacity="0.1" />
</filter>
<marker id="arrowhead" markerWidth="10" markerHeight="7" refX="10" refY="3.5" orient="auto">
<polygon points="0 0, 10 3.5, 0 7" fill="#64748b" />
</marker>
<pattern id="grid" width="20" height="20" patternUnits="userSpaceOnUse">
<circle cx="1" cy="1" r="0.5" fill="#e2e8f0" />
</pattern>
</defs>
<g transform={`translate(${pan.x},${pan.y}) scale(${zoom})`}>
{/* Grid */}
<rect width="4000" height="4000" fill="url(#grid)" />
{/* Conexões */}
{connections.map(conn => {
const source = nodes.find(n => n.id === conn.sourceId);
const target = nodes.find(n => n.id === conn.targetId);
if (!source || !target) return null;
const pts = getBestConnectionPoints(source, target);
const midX = (pts.source.x + pts.target.x) / 2;
const midY = (pts.source.y + pts.target.y) / 2;
return (
<g key={conn.id}>
<path
d={`M ${pts.source.x} ${pts.source.y} C ${midX} ${pts.source.y}, ${midX} ${pts.target.y}, ${pts.target.x} ${pts.target.y}`}
fill="none"
stroke="#94a3b8"
strokeWidth={1.5}
markerEnd="url(#arrowhead)"
/>
{conn.label && (
<text x={midX} y={midY - 6} textAnchor="middle" fontSize={10} fill="#64748b">
{conn.label}
</text>
)}
</g>
);
})}
{/* Nós */}
{nodes.map(node => (
<g
key={node.id}
data-node-id={node.id}
style={{ cursor: mode === "connect" ? "crosshair" : "grab" }}
onDoubleClick={(e) => {
e.stopPropagation();
setEditingLabel(node.id);
setSelectedNodeId(node.id);
}}
>
{renderBpmnElement(node, selectedNodeId === node.id, connectingFrom === node.id)}
{/* Pontos de conexão ao selecionar */}
{selectedNodeId === node.id && mode === "select" && (
<>
{(["left", "right", "top", "bottom"] as const).map(side => {
const pt = getConnectionPoint(node, side);
return (
<circle key={side} cx={pt.x} cy={pt.y} r={4} fill="#3b82f6" stroke="white" strokeWidth={1.5} />
);
})}
</>
)}
</g>
))}
</g>
</svg>
</div>
{/* Painel de propriedades */}
{selectedNode && (
<div className="w-56 border-l bg-muted/20 p-3 overflow-y-auto" data-testid="bpmn-properties">
<p className="text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-3">Propriedades</p>
<div className="space-y-3">
<div>
<label className="text-xs text-muted-foreground">Nome</label>
<Input
value={selectedNode.label}
onChange={(e) => handleLabelChange(selectedNode.id, e.target.value)}
className="h-8 text-sm"
data-testid="input-node-label"
/>
</div>
<div>
<label className="text-xs text-muted-foreground">Tipo</label>
<Badge variant="outline" className="mt-1 block w-fit">
{BPMN_PALETTE.flatMap(c => c.items).find(i => i.type === selectedNode.type)?.label || selectedNode.type}
</Badge>
</div>
<div className="grid grid-cols-2 gap-2">
<div>
<label className="text-xs text-muted-foreground">X</label>
<Input value={Math.round(selectedNode.x)} readOnly className="h-7 text-xs" />
</div>
<div>
<label className="text-xs text-muted-foreground">Y</label>
<Input value={Math.round(selectedNode.y)} readOnly className="h-7 text-xs" />
</div>
</div>
<div>
<label className="text-xs text-muted-foreground">Conexões</label>
<div className="mt-1 space-y-1">
{connections
.filter(c => c.sourceId === selectedNode.id || c.targetId === selectedNode.id)
.map(c => {
const other = c.sourceId === selectedNode.id
? nodes.find(n => n.id === c.targetId)
: nodes.find(n => n.id === c.sourceId);
const dir = c.sourceId === selectedNode.id ? "→" : "←";
return (
<div key={c.id} className="flex items-center justify-between text-xs bg-muted rounded px-2 py-1">
<span>{dir} {other?.label || "?"}</span>
<button
className="text-red-400 hover:text-red-600"
onClick={() => setConnections(prev => prev.filter(cc => cc.id !== c.id))}
>
×
</button>
</div>
);
})}
{connections.filter(c => c.sourceId === selectedNode.id || c.targetId === selectedNode.id).length === 0 && (
<p className="text-xs text-muted-foreground">Sem conexões</p>
)}
</div>
</div>
</div>
</div>
)}
</div>
</div>
);
}

View File

@ -0,0 +1,246 @@
import { useLocation } from "wouter";
import React, { useEffect } from "react";
import { Bot, Settings, MessageCircle, Zap, LayoutDashboard, Compass, Users, Ticket, LogOut, User, Shield, Receipt, Package, Rocket, Beaker, TrendingUp, MapPin, Droplets, Star, Database, Layout, Code, Code2, Store, Layers } from "lucide-react";
import browserIcon from "@assets/arcadia_branding/arcadia_suite_icon.png";
import { useAuth } from "@/hooks/use-auth";
import { useNavigationTracking } from "@/hooks/use-navigation-tracking";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
interface BrowserFrameProps {
children: React.ReactNode;
}
function CompactNavigationBar() {
const [location, setLocation] = useLocation();
const { user, logoutMutation } = useAuth();
const { trackPageView } = useNavigationTracking();
const navigateTo = (path: string, pageName: string) => {
trackPageView(pageName, path);
setLocation(path);
};
return (
<div className="h-10 bg-background border-b border-border flex items-center px-3 gap-2 text-xs text-muted-foreground shadow-xs z-10">
<div className="flex items-center gap-1 overflow-x-auto scrollbar-hide flex-1">
{user?.role === "admin" && (
<div
className="flex items-center gap-1 hover:bg-muted px-2 py-1.5 rounded cursor-pointer transition-colors flex-shrink-0"
onClick={() => navigateTo("/admin", "Administração")}
data-testid="bookmark-admin"
>
<div className="w-4 h-4 bg-gradient-to-br from-slate-700 to-slate-900 rounded-sm flex items-center justify-center">
<Settings className="w-2.5 h-2.5 text-white" />
</div>
<span className="hidden md:inline">Administração</span>
</div>
)}
<div
className="flex items-center gap-1 hover:bg-muted px-2 py-1.5 rounded cursor-pointer transition-colors flex-shrink-0"
onClick={() => navigateTo("/", "Início")}
data-testid="bookmark-home"
>
<img src={browserIcon} className="w-4 h-4 rounded-sm object-cover" alt="" />
<span className="hidden md:inline">Início</span>
</div>
<div
className="flex items-center gap-1 hover:bg-muted px-2 py-1.5 rounded cursor-pointer transition-colors flex-shrink-0"
onClick={() => navigateTo("/agent", "Agent")}
data-testid="bookmark-agent"
>
<div className="w-4 h-4 bg-gradient-to-br from-primary to-blue-600 rounded-sm flex items-center justify-center">
<Bot className="w-2.5 h-2.5 text-white" />
</div>
<span className="hidden md:inline">Agent</span>
</div>
<div
className="flex items-center gap-1 hover:bg-muted px-2 py-1.5 rounded cursor-pointer transition-colors flex-shrink-0"
onClick={() => navigateTo("/xos/inbox", "XOS Inbox")}
data-testid="bookmark-xos-inbox"
>
<div className="w-4 h-4 bg-gradient-to-br from-[#00a884] to-[#25D366] rounded-sm flex items-center justify-center">
<MessageCircle className="w-2.5 h-2.5 text-white" />
</div>
<span className="hidden md:inline">Inbox</span>
</div>
<div
className="flex items-center gap-1 hover:bg-muted px-2 py-1.5 rounded cursor-pointer transition-colors flex-shrink-0"
onClick={() => navigateTo("/automations", "Automações")}
data-testid="bookmark-automations"
>
<div className="w-4 h-4 bg-gradient-to-br from-[#c89b3c] to-[#d4a94a] rounded-sm flex items-center justify-center">
<Zap className="w-2.5 h-2.5 text-white" />
</div>
<span className="hidden md:inline">Automações</span>
</div>
<div
className="flex items-center gap-1 hover:bg-muted px-2 py-1.5 rounded cursor-pointer transition-colors flex-shrink-0"
onClick={() => navigateTo("/insights", "Insights")}
data-testid="bookmark-insights"
>
<div className="w-4 h-4 bg-gradient-to-br from-[#1f334d] to-[#2d4a6f] rounded-sm flex items-center justify-center">
<LayoutDashboard className="w-2.5 h-2.5 text-[#c89b3c]" />
</div>
<span className="hidden md:inline">Insights</span>
</div>
<div
className="flex items-center gap-1 hover:bg-muted px-2 py-1.5 rounded cursor-pointer transition-colors flex-shrink-0"
onClick={() => navigateTo("/compass", "Compass")}
data-testid="bookmark-compass"
>
<div className="w-4 h-4 bg-gradient-to-br from-[#c89b3c] to-[#1f334d] rounded-sm flex items-center justify-center">
<Compass className="w-2.5 h-2.5 text-white" />
</div>
<span className="hidden md:inline">Compass</span>
</div>
<div
className="flex items-center gap-1 hover:bg-muted px-2 py-1.5 rounded cursor-pointer transition-colors flex-shrink-0"
onClick={() => navigateTo("/production", "Produção")}
data-testid="bookmark-production"
>
<div className="w-4 h-4 bg-gradient-to-br from-indigo-500 to-indigo-700 rounded-sm flex items-center justify-center">
<Users className="w-2.5 h-2.5 text-white" />
</div>
<span className="hidden md:inline">Produção</span>
</div>
<div
className="flex items-center gap-1 hover:bg-muted px-2 py-1.5 rounded cursor-pointer transition-colors flex-shrink-0"
onClick={() => navigateTo("/support", "Suporte")}
data-testid="bookmark-support"
>
<div className="w-4 h-4 bg-gradient-to-br from-rose-500 to-rose-700 rounded-sm flex items-center justify-center">
<Ticket className="w-2.5 h-2.5 text-white" />
</div>
<span className="hidden md:inline">Suporte</span>
</div>
<div
className="flex items-center gap-1 hover:bg-muted px-2 py-1.5 rounded cursor-pointer transition-colors flex-shrink-0"
onClick={() => navigateTo("/erp", "ERP")}
data-testid="bookmark-erp"
>
<div className="w-4 h-4 bg-gradient-to-br from-blue-600 to-blue-800 rounded-sm flex items-center justify-center">
<Package className="w-2.5 h-2.5 text-white" />
</div>
<span className="hidden md:inline">ERP</span>
</div>
<div
className="flex items-center gap-1 hover:bg-muted px-2 py-1.5 rounded cursor-pointer transition-colors flex-shrink-0"
onClick={() => navigateTo("/retail", "Retail")}
data-testid="bookmark-retail"
>
<div className="w-4 h-4 bg-gradient-to-br from-cyan-500 to-blue-600 rounded-sm flex items-center justify-center">
<Store className="w-2.5 h-2.5 text-white" />
</div>
<span className="hidden md:inline">Retail</span>
</div>
<div
className="flex items-center gap-1 hover:bg-muted px-2 py-1.5 rounded cursor-pointer transition-colors flex-shrink-0"
onClick={() => navigateTo("/plus", "Plus")}
data-testid="bookmark-plus"
>
<div className="w-4 h-4 bg-gradient-to-br from-purple-500 to-purple-700 rounded-sm flex items-center justify-center">
<Layers className="w-2.5 h-2.5 text-white" />
</div>
<span className="hidden md:inline">Plus</span>
</div>
<div
className="flex items-center gap-1 hover:bg-muted px-2 py-1.5 rounded cursor-pointer transition-colors flex-shrink-0"
onClick={() => navigateTo("/fisco", "Fisco")}
data-testid="bookmark-fisco"
>
<div className="w-4 h-4 bg-gradient-to-br from-emerald-600 to-emerald-800 rounded-sm flex items-center justify-center">
<Receipt className="w-2.5 h-2.5 text-white" />
</div>
<span className="hidden md:inline">Fisco</span>
</div>
<div
className="flex items-center gap-1 hover:bg-muted px-2 py-1.5 rounded cursor-pointer transition-colors flex-shrink-0"
onClick={() => navigateTo("/engineering", "Engenharia")}
data-testid="bookmark-engineering"
>
<div className="w-4 h-4 bg-gradient-to-br from-teal-500 to-green-700 rounded-sm flex items-center justify-center">
<Compass className="w-2.5 h-2.5 text-white" />
</div>
<span className="hidden md:inline">Engenharia</span>
</div>
</div>
<div className="flex items-center gap-2 flex-shrink-0 border-l pl-3 ml-2">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="sm" className="h-7 px-2 gap-1.5" data-testid="button-user-menu">
<div className="w-5 h-5 rounded-full bg-primary text-primary-foreground flex items-center justify-center text-xs font-medium">
{user?.name?.[0]?.toUpperCase() || user?.username?.[0]?.toUpperCase() || "U"}
</div>
<span className="hidden sm:inline text-xs">{user?.name || user?.username}</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-56">
<DropdownMenuLabel className="font-normal">
<div className="flex flex-col space-y-1">
<p className="text-sm font-medium leading-none">{user?.name || user?.username}</p>
<p className="text-xs leading-none text-muted-foreground">@{user?.username}</p>
{user?.role === "admin" && (
<p className="text-xs leading-none text-primary flex items-center gap-1 mt-1">
<Shield className="w-3 h-3" />
Administrador
</p>
)}
</div>
</DropdownMenuLabel>
<DropdownMenuSeparator />
<DropdownMenuItem className="cursor-pointer">
<User className="mr-2 h-4 w-4" />
<span>Meu Perfil</span>
</DropdownMenuItem>
{user?.role === "admin" && (
<>
<DropdownMenuSeparator />
<DropdownMenuLabel className="text-xs text-muted-foreground">Plataforma</DropdownMenuLabel>
<DropdownMenuItem
className="cursor-pointer"
onClick={() => navigateTo("/development", "Desenvolvimento")}
data-testid="menu-development"
>
<Code2 className="mr-2 h-4 w-4" />
<span>Centro de Desenvolvimento</span>
</DropdownMenuItem>
</>
)}
<DropdownMenuSeparator />
<DropdownMenuItem
className="cursor-pointer text-destructive focus:text-destructive"
onClick={() => logoutMutation.mutate()}
data-testid="button-logout"
>
<LogOut className="mr-2 h-4 w-4" />
<span>Sair</span>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
);
}
export function BrowserFrame({ children }: BrowserFrameProps) {
return (
<div className="flex flex-col h-screen w-screen bg-background overflow-hidden">
{/* Navigation Bar */}
<CompactNavigationBar />
{/* Content Area */}
<div className="flex-1 bg-white relative overflow-y-auto overflow-x-hidden">
{children}
</div>
</div>
);
}

View File

@ -0,0 +1,110 @@
import {
ArrowLeft,
ArrowRight,
RotateCw,
Star,
Lock,
MoreVertical,
Puzzle,
LogOut,
User,
Shield
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { useAuth } from "@/hooks/use-auth";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
interface OmniboxProps {
url: string;
onNavigate: (url: string) => void;
isLoading?: boolean;
}
export function Omnibox({ url, onNavigate, isLoading }: OmniboxProps) {
const { user, logoutMutation } = useAuth();
return (
<div className="flex items-center gap-2 w-full h-10 px-2 bg-background border-b border-border shadow-xs z-20">
<div className="flex gap-1">
<Button variant="ghost" size="icon" className="h-8 w-8 rounded-full">
<ArrowLeft className="w-4 h-4 text-muted-foreground" />
</Button>
<Button variant="ghost" size="icon" className="h-8 w-8 rounded-full">
<ArrowRight className="w-4 h-4 text-muted-foreground" />
</Button>
<Button variant="ghost" size="icon" className="h-8 w-8 rounded-full">
<RotateCw className={`w-4 h-4 text-muted-foreground ${isLoading ? 'animate-spin' : ''}`} />
</Button>
</div>
<div className="flex-1 flex items-center bg-muted/50 hover:bg-muted/80 focus-within:bg-white focus-within:shadow-sm focus-within:ring-2 ring-primary/20 transition-all rounded-full px-3 h-8 mx-2 border border-transparent focus-within:border-primary/30">
<Lock className="w-3.5 h-3.5 text-green-600 mr-2 shrink-0" />
<input
className="flex-1 bg-transparent border-none outline-none text-sm h-full w-full"
value={url}
readOnly
/>
<div className="flex items-center gap-1">
<Button variant="ghost" size="icon" className="h-6 w-6 rounded-full hover:bg-slate-200">
<Star className="w-3.5 h-3.5 text-muted-foreground" />
</Button>
</div>
</div>
<div className="flex gap-1 items-center">
<Button variant="ghost" size="icon" className="h-8 w-8 rounded-full">
<Puzzle className="w-4 h-4 text-muted-foreground" />
</Button>
<div className="w-[1px] h-4 bg-border mx-1" />
<Button variant="ghost" size="icon" className="h-8 w-8 rounded-full">
<MoreVertical className="w-4 h-4 text-muted-foreground" />
</Button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon" className="h-8 w-8 rounded-full ml-1" data-testid="button-user-menu">
<div className="w-6 h-6 rounded-full bg-primary text-primary-foreground flex items-center justify-center text-xs font-medium">
{user?.name?.[0]?.toUpperCase() || user?.username?.[0]?.toUpperCase() || "U"}
</div>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-56">
<DropdownMenuLabel className="font-normal">
<div className="flex flex-col space-y-1">
<p className="text-sm font-medium leading-none">{user?.name || user?.username}</p>
<p className="text-xs leading-none text-muted-foreground">@{user?.username}</p>
{user?.role === "admin" && (
<p className="text-xs leading-none text-primary flex items-center gap-1 mt-1">
<Shield className="w-3 h-3" />
Administrador
</p>
)}
</div>
</DropdownMenuLabel>
<DropdownMenuSeparator />
<DropdownMenuItem className="cursor-pointer">
<User className="mr-2 h-4 w-4" />
<span>Meu Perfil</span>
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
className="cursor-pointer text-destructive focus:text-destructive"
onClick={() => logoutMutation.mutate()}
data-testid="button-logout"
>
<LogOut className="mr-2 h-4 w-4" />
<span>Sair</span>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
);
}

View File

@ -0,0 +1,51 @@
import { X, Globe, Lock } from "lucide-react";
import { cn } from "@/lib/utils";
import { motion } from "framer-motion";
interface TabProps {
id: string;
title: string;
isActive: boolean;
favicon?: string;
onClose: (e: React.MouseEvent) => void;
onClick: () => void;
}
export function Tab({ id, title, isActive, favicon, onClose, onClick }: TabProps) {
return (
<motion.div
layout
initial={false}
onClick={onClick}
className={cn(
"group relative flex items-center gap-2 px-3 py-2 text-sm max-w-[240px] min-w-[120px] flex-1 cursor-default select-none transition-colors",
isActive
? "bg-background text-foreground rounded-t-lg shadow-sm z-10"
: "text-muted-foreground hover:bg-white/50 dark:hover:bg-white/5 rounded-t-lg"
)}
>
{/* Divider - only show if not active and previous is not active (simplified logic for now) */}
{!isActive && (
<div className="absolute right-0 top-1/2 -translate-y-1/2 w-[1px] h-4 bg-border group-hover:hidden" />
)}
{favicon ? (
<img src={favicon} alt="" className="w-4 h-4 rounded-sm object-cover" />
) : (
<Globe className="w-4 h-4 text-muted-foreground" />
)}
<span className="truncate flex-1 font-medium">{title}</span>
<button
onClick={onClose}
className={cn(
"p-0.5 rounded-full hover:bg-muted opacity-0 group-hover:opacity-100 transition-all",
isActive && "opacity-100"
)}
>
<X className="w-3 h-3" />
</button>
</motion.div>
);
}

View File

@ -0,0 +1,45 @@
import { Plus } from "lucide-react";
import { Tab } from "./Tab";
import { Reorder } from "framer-motion";
interface TabData {
id: string;
title: string;
url: string;
active: boolean;
favicon?: string;
}
interface TabBarProps {
tabs: TabData[];
onTabClick: (id: string) => void;
onTabClose: (id: string) => void;
onNewTab: () => void;
}
export function TabBar({ tabs, onTabClick, onTabClose, onNewTab }: TabBarProps) {
return (
<div className="flex items-end h-full w-full gap-1 overflow-x-auto no-scrollbar pt-2">
{tabs.map((tab) => (
<Tab
key={tab.id}
id={tab.id}
title={tab.title}
isActive={tab.active}
favicon={tab.favicon}
onClick={() => onTabClick(tab.id)}
onClose={(e) => {
e.stopPropagation();
onTabClose(tab.id);
}}
/>
))}
<button
onClick={onNewTab}
className="p-2 ml-1 mb-1 rounded-full hover:bg-white/50 text-muted-foreground hover:text-foreground transition-colors"
>
<Plus className="w-4 h-4" />
</button>
</div>
);
}

View File

@ -0,0 +1,17 @@
import { X, Minus, Square } from "lucide-react";
export function WindowControls() {
return (
<div className="flex items-center gap-2 px-4">
<div className="w-3 h-3 rounded-full bg-red-500 hover:bg-red-600 flex items-center justify-center group cursor-pointer transition-colors">
<X className="w-2 h-2 text-red-900 opacity-0 group-hover:opacity-100" />
</div>
<div className="w-3 h-3 rounded-full bg-yellow-500 hover:bg-yellow-600 flex items-center justify-center group cursor-pointer transition-colors">
<Minus className="w-2 h-2 text-yellow-900 opacity-0 group-hover:opacity-100" />
</div>
<div className="w-3 h-3 rounded-full bg-green-500 hover:bg-green-600 flex items-center justify-center group cursor-pointer transition-colors">
<Square className="w-2 h-2 text-green-900 opacity-0 group-hover:opacity-100 fill-current" />
</div>
</div>
);
}

View File

@ -0,0 +1,421 @@
import { useState, useEffect, useCallback, useMemo, useRef } from "react";
import { useLocation } from "wouter";
import {
Search, FileText, Users, FolderKanban, CheckSquare,
MessageSquare, BookOpen, Plus, Settings, Home,
BarChart3, Bot, Compass, MessageCircle, Zap, X, Handshake, TrendingUp, Globe,
Calculator, Receipt, UserCog
} from "lucide-react";
import { Dialog, DialogContent, DialogTitle, DialogDescription } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { useQuery, useMutation } from "@tanstack/react-query";
import { VisuallyHidden } from "@radix-ui/react-visually-hidden";
interface SearchResult {
id: number | string;
title?: string;
name?: string;
content?: string;
_type: string;
_module: string;
}
interface CommandItem {
id: string;
name: string;
shortcut?: string;
icon: React.ReactNode;
action: () => void;
keywords?: string[];
group: string;
}
export function CommandPalette() {
const [open, setOpen] = useState(false);
const [search, setSearch] = useState("");
const [selectedIndex, setSelectedIndex] = useState(0);
const [, navigate] = useLocation();
const inputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
const down = (e: KeyboardEvent) => {
if ((e.key === "k" && (e.metaKey || e.ctrlKey)) || e.key === "F1") {
e.preventDefault();
setOpen((o) => !o);
}
};
document.addEventListener("keydown", down);
return () => document.removeEventListener("keydown", down);
}, []);
useEffect(() => {
if (open) {
setSearch("");
setSelectedIndex(0);
setTimeout(() => inputRef.current?.focus(), 100);
}
}, [open]);
const { data: searchResults } = useQuery<{ results: SearchResult[] }>({
queryKey: ["/api/productivity/search", search],
queryFn: async () => {
if (!search || search.length < 2) return { results: [] };
const res = await fetch(`/api/productivity/search?q=${encodeURIComponent(search)}&limit=10`, { credentials: "include" });
if (!res.ok) return { results: [] };
return res.json();
},
enabled: search.length >= 2 && open,
staleTime: 1000,
});
const trackCommand = useMutation({
mutationFn: async (command: string) => {
await fetch("/api/productivity/commands/track", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ command }),
credentials: "include",
});
},
});
const runCommand = useCallback((callback: () => void, commandId?: string) => {
setOpen(false);
setSearch("");
if (commandId) {
trackCommand.mutate(commandId);
}
callback();
}, [trackCommand]);
const navigateTo = useCallback((path: string) => {
navigate(path);
}, [navigate]);
const commands: CommandItem[] = useMemo(() => [
{
id: "nav-home",
name: "Ir para Início",
shortcut: "⌘H",
icon: <Home className="h-4 w-4" />,
action: () => navigateTo("/"),
keywords: ["home", "início", "dashboard"],
group: "Navegação",
},
{
id: "nav-agent",
name: "Abrir Arcádia Agent",
icon: <Bot className="h-4 w-4" />,
action: () => navigateTo("/agent"),
keywords: ["ia", "assistente", "chat", "gpt"],
group: "Navegação",
},
{
id: "nav-compass",
name: "Abrir Process Compass",
icon: <Compass className="h-4 w-4" />,
action: () => navigateTo("/compass"),
keywords: ["projetos", "clientes", "consultoria"],
group: "Navegação",
},
{
id: "nav-crm",
name: "Abrir Arcádia CRM",
icon: <Handshake className="h-4 w-4" />,
action: () => navigateTo("/crm"),
keywords: ["crm", "parceiros", "contratos", "vendas", "whatsapp"],
group: "Navegação",
},
{
id: "nav-insights",
name: "Abrir Arcádia Insights",
icon: <BarChart3 className="h-4 w-4" />,
action: () => navigateTo("/insights"),
keywords: ["bi", "dados", "relatórios", "analytics"],
group: "Navegação",
},
{
id: "nav-automations",
name: "Abrir Automações",
icon: <Zap className="h-4 w-4" />,
action: () => navigateTo("/automations"),
keywords: ["workflows", "automação"],
group: "Navegação",
},
{
id: "nav-communities",
name: "Abrir Comunidades",
icon: <MessageCircle className="h-4 w-4" />,
action: () => navigateTo("/communities"),
keywords: ["discord", "comunidades", "chat", "mensagens", "comunicação", "equipe"],
group: "Navegação",
},
{
id: "nav-admin",
name: "Painel de Administração",
icon: <Settings className="h-4 w-4" />,
action: () => navigateTo("/admin"),
keywords: ["config", "usuários", "permissões"],
group: "Navegação",
},
{
id: "nav-central-apis",
name: "Abrir Central de APIs",
icon: <Globe className="h-4 w-4" />,
action: () => navigateTo("/central-apis"),
keywords: ["api", "integrações", "sefaz", "nfe", "pix", "bancos", "marketplace"],
group: "Navegação",
},
{
id: "nav-people",
name: "Abrir Arcádia People",
icon: <UserCog className="h-4 w-4" />,
action: () => navigateTo("/people"),
keywords: ["rh", "folha", "funcionários", "inss", "fgts", "esocial", "férias"],
group: "Navegação",
},
{
id: "nav-contabil",
name: "Abrir Arcádia Contábil",
icon: <Calculator className="h-4 w-4" />,
action: () => navigateTo("/contabil"),
keywords: ["contabilidade", "plano de contas", "lançamento", "dre", "balanço", "sped"],
group: "Navegação",
},
{
id: "nav-fisco",
name: "Abrir Arcádia Fisco",
icon: <Receipt className="h-4 w-4" />,
action: () => navigateTo("/fisco"),
keywords: ["fiscal", "nfe", "ncm", "cfop", "imposto", "tributário"],
group: "Navegação",
},
{
id: "create-page",
name: "Criar Nova Página",
shortcut: "⌘N",
icon: <Plus className="h-4 w-4" />,
action: () => {
window.dispatchEvent(new CustomEvent("create-new-page"));
},
keywords: ["novo", "documento", "nota"],
group: "Criar",
},
{
id: "create-note",
name: "Criar Nota Rápida",
icon: <FileText className="h-4 w-4" />,
action: () => {
window.dispatchEvent(new CustomEvent("create-quick-note"));
},
keywords: ["nota", "lembrete"],
group: "Criar",
},
], [navigateTo]);
const getResultIcon = (type: string) => {
switch (type) {
case "page": return <FileText className="h-4 w-4" />;
case "client": return <Users className="h-4 w-4" />;
case "project": return <FolderKanban className="h-4 w-4" />;
case "task": return <CheckSquare className="h-4 w-4" />;
case "conversation": return <MessageSquare className="h-4 w-4" />;
case "knowledge": return <BookOpen className="h-4 w-4" />;
default: return <FileText className="h-4 w-4" />;
}
};
const getResultPath = (result: SearchResult): string => {
switch (result._type) {
case "page": return `/page/${result.id}`;
case "client": return `/compass?tab=clients&id=${result.id}`;
case "project": return `/compass?tab=projects&id=${result.id}`;
case "task": return `/compass?tab=tasks&id=${result.id}`;
case "conversation": return `/agent?conversation=${result.id}`;
case "knowledge": return `/agent?knowledge=${result.id}`;
default: return "/";
}
};
const getModuleLabel = (module: string) => {
switch (module) {
case "workspace": return "Páginas";
case "compass": return "Process Compass";
case "agent": return "Arcádia Agent";
default: return module;
}
};
const getTypeLabel = (type: string) => {
switch (type) {
case "page": return "Página";
case "client": return "Cliente";
case "project": return "Projeto";
case "task": return "Tarefa";
case "conversation": return "Conversa";
case "knowledge": return "Conhecimento";
default: return type;
}
};
const filteredCommands = useMemo(() => {
if (!search) return commands;
const lower = search.toLowerCase();
return commands.filter(cmd =>
cmd.name.toLowerCase().includes(lower) ||
cmd.keywords?.some(k => k.toLowerCase().includes(lower))
);
}, [commands, search]);
const allItems = useMemo(() => {
const items: { type: 'result' | 'command'; data: SearchResult | CommandItem }[] = [];
if (searchResults?.results) {
searchResults.results.forEach(r => items.push({ type: 'result', data: r }));
}
filteredCommands.forEach(c => items.push({ type: 'command', data: c }));
return items;
}, [searchResults?.results, filteredCommands]);
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === "ArrowDown") {
e.preventDefault();
setSelectedIndex(i => Math.min(i + 1, allItems.length - 1));
} else if (e.key === "ArrowUp") {
e.preventDefault();
setSelectedIndex(i => Math.max(i - 1, 0));
} else if (e.key === "Enter") {
e.preventDefault();
const item = allItems[selectedIndex];
if (item) {
if (item.type === 'result') {
runCommand(() => navigateTo(getResultPath(item.data as SearchResult)));
} else {
const cmd = item.data as CommandItem;
runCommand(cmd.action, cmd.id);
}
}
} else if (e.key === "Escape") {
setOpen(false);
}
};
const groupedCommands = useMemo(() => {
return filteredCommands.reduce((acc, cmd) => {
if (!acc[cmd.group]) acc[cmd.group] = [];
acc[cmd.group].push(cmd);
return acc;
}, {} as Record<string, CommandItem[]>);
}, [filteredCommands]);
let itemIndex = -1;
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent className="overflow-hidden p-0 shadow-lg max-w-[640px]" data-testid="command-palette">
<VisuallyHidden>
<DialogTitle>Paleta de Comandos</DialogTitle>
<DialogDescription>Pesquise ou execute comandos</DialogDescription>
</VisuallyHidden>
<div className="flex flex-col">
<div className="flex items-center border-b px-3 py-2">
<Search className="mr-2 h-4 w-4 shrink-0 opacity-50" />
<Input
ref={inputRef}
placeholder="Pesquisar ou digitar comando..."
className="flex-1 border-none focus-visible:ring-0 shadow-none"
value={search}
onChange={(e) => {
setSearch(e.target.value);
setSelectedIndex(0);
}}
onKeyDown={handleKeyDown}
data-testid="command-input"
/>
{search && (
<button onClick={() => setSearch("")} className="p-1 hover:bg-muted rounded">
<X className="h-4 w-4 opacity-50" />
</button>
)}
</div>
<div className="max-h-[400px] overflow-y-auto overflow-x-hidden p-2">
{allItems.length === 0 && (
<div className="py-6 text-center text-sm text-muted-foreground">
Nenhum resultado encontrado.
</div>
)}
{searchResults?.results && searchResults.results.length > 0 && (
<div className="mb-2">
<div className="px-2 py-1 text-xs font-medium text-muted-foreground">
Resultados da Busca
</div>
{searchResults.results.map((result) => {
itemIndex++;
const isSelected = itemIndex === selectedIndex;
return (
<div
key={`${result._type}-${result.id}`}
className={`flex items-center gap-2 px-2 py-2 cursor-pointer rounded ${isSelected ? 'bg-accent' : 'hover:bg-muted'}`}
onClick={() => runCommand(() => navigateTo(getResultPath(result)))}
data-testid={`search-result-${result._type}-${result.id}`}
>
{getResultIcon(result._type)}
<div className="flex flex-col flex-1 min-w-0">
<span className="truncate text-sm">{result.title || result.name || "Sem título"}</span>
<span className="text-xs text-muted-foreground">
{getTypeLabel(result._type)} · {getModuleLabel(result._module)}
</span>
</div>
</div>
);
})}
</div>
)}
{Object.entries(groupedCommands).map(([group, items]) => (
<div key={group} className="mb-2">
<div className="px-2 py-1 text-xs font-medium text-muted-foreground">
{group}
</div>
{items.map((cmd) => {
itemIndex++;
const isSelected = itemIndex === selectedIndex;
return (
<div
key={cmd.id}
className={`flex items-center gap-2 px-2 py-2 cursor-pointer rounded ${isSelected ? 'bg-accent' : 'hover:bg-muted'}`}
onClick={() => runCommand(cmd.action, cmd.id)}
data-testid={`command-${cmd.id}`}
>
{cmd.icon}
<span className="flex-1 text-sm">{cmd.name}</span>
{cmd.shortcut && (
<kbd className="pointer-events-none inline-flex h-5 select-none items-center gap-1 rounded border bg-muted px-1.5 font-mono text-[10px] font-medium text-muted-foreground">
{cmd.shortcut}
</kbd>
)}
</div>
);
})}
</div>
))}
</div>
<div className="flex items-center justify-between border-t px-3 py-2 text-xs text-muted-foreground">
<div className="flex gap-2">
<span> Navegar</span>
<span> Selecionar</span>
<span>Esc Fechar</span>
</div>
<span>K para abrir</span>
</div>
</div>
</DialogContent>
</Dialog>
);
}

View File

@ -0,0 +1,488 @@
import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { ScrollArea } from "@/components/ui/scroll-area";
import {
CheckCircle,
XCircle,
Clock,
Loader2,
ChevronDown,
ChevronRight,
FileText,
Code,
Brain,
Wrench,
Shield,
Rocket,
TrendingUp,
AlertCircle,
RefreshCw,
Filter,
BarChart3,
GitBranch,
Eye,
Layers,
Play,
} from "lucide-react";
interface TimelineEntry {
id: number;
agent: string;
action: string;
thought: string;
observation?: string;
createdAt: string;
}
interface SubtaskEntry {
id: number;
title: string;
status: string;
assignedAgent: string;
startedAt?: string;
completedAt?: string;
}
interface ArtifactEntry {
id: number;
type: string;
name: string;
createdBy: string;
createdAt: string;
}
interface HistoryTask {
id: number;
type: string;
title: string;
description: string;
status: string;
priority: number;
assignedAgent?: string;
userId?: string;
result?: any;
errorMessage?: string;
createdAt: string;
updatedAt?: string;
startedAt?: string;
completedAt?: string;
subtaskCount: number;
artifactCount: number;
logCount: number;
subtasks: SubtaskEntry[];
artifacts: ArtifactEntry[];
timeline: TimelineEntry[];
}
const AGENT_CONFIG: Record<string, { label: string; color: string; icon: any }> = {
architect: { label: "Arquiteto", color: "bg-blue-100 text-blue-700 border-blue-200", icon: Brain },
generator: { label: "Gerador", color: "bg-purple-100 text-purple-700 border-purple-200", icon: Code },
validator: { label: "Validador", color: "bg-amber-100 text-amber-700 border-amber-200", icon: Shield },
executor: { label: "Executor", color: "bg-green-100 text-green-700 border-green-200", icon: Rocket },
evolution: { label: "Evolução", color: "bg-cyan-100 text-cyan-700 border-cyan-200", icon: TrendingUp },
dispatcher: { label: "Dispatcher", color: "bg-slate-100 text-slate-700 border-slate-200", icon: Layers },
};
const STATUS_CONFIG: Record<string, { label: string; color: string; icon: any }> = {
pending: { label: "Pendente", color: "bg-slate-100 text-slate-600", icon: Clock },
in_progress: { label: "Em Progresso", color: "bg-blue-100 text-blue-600", icon: Loader2 },
completed: { label: "Concluída", color: "bg-green-100 text-green-600", icon: CheckCircle },
failed: { label: "Falhou", color: "bg-red-100 text-red-600", icon: XCircle },
blocked: { label: "Bloqueada", color: "bg-orange-100 text-orange-600", icon: AlertCircle },
};
const ARTIFACT_ICONS: Record<string, any> = {
spec: FileText,
code: Code,
test: Shield,
doc: FileText,
config: Wrench,
analysis: BarChart3,
};
function formatDate(dateStr?: string) {
if (!dateStr) return "—";
const d = new Date(dateStr);
return d.toLocaleDateString("pt-BR", { day: "2-digit", month: "2-digit", year: "2-digit" }) +
" " + d.toLocaleTimeString("pt-BR", { hour: "2-digit", minute: "2-digit" });
}
function formatDuration(start?: string, end?: string) {
if (!start || !end) return null;
const ms = new Date(end).getTime() - new Date(start).getTime();
if (ms < 1000) return `${ms}ms`;
if (ms < 60000) return `${Math.round(ms / 1000)}s`;
return `${Math.round(ms / 60000)}min`;
}
function TaskCard({ task, onContinueTask }: { task: HistoryTask; onContinueTask?: (title: string) => void }) {
const [expanded, setExpanded] = useState(false);
const [activeSection, setActiveSection] = useState<"timeline" | "subtasks" | "artifacts">("timeline");
const statusCfg = STATUS_CONFIG[task.status] || STATUS_CONFIG.pending;
const StatusIcon = statusCfg.icon;
const duration = formatDuration(task.startedAt || task.createdAt, task.completedAt);
return (
<Card className="overflow-hidden transition-shadow hover:shadow-md" data-testid={`history-task-${task.id}`}>
<div
className="flex items-center gap-3 px-4 py-3 cursor-pointer hover:bg-muted/30 transition-colors"
onClick={() => setExpanded(!expanded)}
>
<div className="shrink-0">
{expanded ? <ChevronDown className="h-4 w-4 text-muted-foreground" /> : <ChevronRight className="h-4 w-4 text-muted-foreground" />}
</div>
<div className="flex items-center gap-2 shrink-0">
<div className={`w-8 h-8 rounded-lg flex items-center justify-center ${statusCfg.color}`}>
<StatusIcon className="h-4 w-4" />
</div>
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<span className="font-medium text-sm truncate">{task.title}</span>
<Badge variant="outline" className="text-[10px] shrink-0">#{task.id}</Badge>
</div>
<p className="text-xs text-muted-foreground truncate">{task.description}</p>
</div>
<div className="flex items-center gap-3 shrink-0 text-xs text-muted-foreground">
{duration && (
<span className="flex items-center gap-1">
<Clock className="h-3 w-3" /> {duration}
</span>
)}
<span className="flex items-center gap-1">
<GitBranch className="h-3 w-3" /> {task.subtaskCount}
</span>
<span className="flex items-center gap-1">
<FileText className="h-3 w-3" /> {task.artifactCount}
</span>
<span className="text-[10px]">{formatDate(task.createdAt)}</span>
{onContinueTask && (
<Button
variant="outline"
size="sm"
className="h-6 text-[10px] px-2 ml-1 border-purple-300 text-purple-600 hover:bg-purple-50"
onClick={(e) => {
e.stopPropagation();
onContinueTask(task.title);
}}
data-testid={`btn-continue-task-${task.id}`}
>
<Play className="h-3 w-3 mr-1" /> Continuar
</Button>
)}
</div>
</div>
{expanded && (
<div className="border-t">
{task.errorMessage && (
<div className="mx-4 mt-3 p-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-700">
<strong>Erro:</strong> {task.errorMessage}
</div>
)}
<div className="flex border-b mx-4 mt-2">
{[
{ key: "timeline" as const, label: "Timeline", count: task.logCount },
{ key: "subtasks" as const, label: "Subtarefas", count: task.subtaskCount },
{ key: "artifacts" as const, label: "Artefatos", count: task.artifactCount },
].map(tab => (
<button
key={tab.key}
className={`px-3 py-2 text-xs font-medium border-b-2 transition-colors ${
activeSection === tab.key
? "border-primary text-primary"
: "border-transparent text-muted-foreground hover:text-foreground"
}`}
onClick={() => setActiveSection(tab.key)}
data-testid={`tab-${tab.key}-${task.id}`}
>
{tab.label} ({tab.count})
</button>
))}
</div>
<div className="p-4">
{activeSection === "timeline" && (
<div className="space-y-1">
{task.timeline.length === 0 ? (
<p className="text-sm text-muted-foreground text-center py-4">Nenhum registro na timeline</p>
) : (
<div className="relative">
<div className="absolute left-4 top-2 bottom-2 w-px bg-border" />
{task.timeline.map((entry, idx) => {
const agentCfg = AGENT_CONFIG[entry.agent] || AGENT_CONFIG.dispatcher;
const AgentIcon = agentCfg.icon;
return (
<div key={entry.id || idx} className="relative pl-10 pb-3">
<div className={`absolute left-2 top-1 w-5 h-5 rounded-full flex items-center justify-center border ${agentCfg.color}`}>
<AgentIcon className="h-2.5 w-2.5" />
</div>
<div className="bg-muted/30 rounded-lg px-3 py-2">
<div className="flex items-center justify-between gap-2 mb-0.5">
<div className="flex items-center gap-2">
<Badge variant="outline" className={`text-[10px] ${agentCfg.color}`}>
{agentCfg.label}
</Badge>
<span className="text-[10px] font-medium text-muted-foreground uppercase">{entry.action}</span>
</div>
<span className="text-[10px] text-muted-foreground">{formatDate(entry.createdAt)}</span>
</div>
<p className="text-xs text-foreground">{entry.thought}</p>
{entry.observation && (
<p className="text-[11px] text-muted-foreground mt-1 italic border-l-2 border-muted pl-2">
{entry.observation.length > 200 ? entry.observation.slice(0, 200) + "…" : entry.observation}
</p>
)}
</div>
</div>
);
})}
</div>
)}
</div>
)}
{activeSection === "subtasks" && (
<div className="space-y-2">
{task.subtasks.length === 0 ? (
<p className="text-sm text-muted-foreground text-center py-4">Nenhuma subtarefa</p>
) : (
task.subtasks.map(sub => {
const subStatus = STATUS_CONFIG[sub.status] || STATUS_CONFIG.pending;
const SubIcon = subStatus.icon;
const agentCfg = AGENT_CONFIG[sub.assignedAgent] || AGENT_CONFIG.dispatcher;
const AgentIcon = agentCfg.icon;
const subDuration = formatDuration(sub.startedAt, sub.completedAt);
return (
<div key={sub.id} className="flex items-center gap-3 p-3 border rounded-lg">
<div className={`w-7 h-7 rounded flex items-center justify-center ${subStatus.color}`}>
<SubIcon className="h-3.5 w-3.5" />
</div>
<div className="flex-1 min-w-0">
<p className="text-sm font-medium truncate">{sub.title}</p>
<div className="flex items-center gap-2 mt-0.5">
<Badge variant="outline" className={`text-[10px] ${agentCfg.color}`}>
<AgentIcon className="h-2.5 w-2.5 mr-1" />
{agentCfg.label}
</Badge>
{subDuration && (
<span className="text-[10px] text-muted-foreground flex items-center gap-0.5">
<Clock className="h-2.5 w-2.5" /> {subDuration}
</span>
)}
</div>
</div>
<Badge className={`text-[10px] ${subStatus.color}`}>{subStatus.label}</Badge>
</div>
);
})
)}
</div>
)}
{activeSection === "artifacts" && (
<div className="space-y-2">
{task.artifacts.length === 0 ? (
<p className="text-sm text-muted-foreground text-center py-4">Nenhum artefato gerado</p>
) : (
task.artifacts.map(art => {
const ArtIcon = ARTIFACT_ICONS[art.type] || FileText;
const agentCfg = AGENT_CONFIG[art.createdBy] || AGENT_CONFIG.dispatcher;
return (
<div key={art.id} className="flex items-center gap-3 p-3 border rounded-lg">
<div className="w-8 h-8 rounded-lg bg-muted flex items-center justify-center">
<ArtIcon className="h-4 w-4 text-muted-foreground" />
</div>
<div className="flex-1 min-w-0">
<p className="text-sm font-medium truncate">{art.name}</p>
<div className="flex items-center gap-2 mt-0.5">
<Badge variant="outline" className="text-[10px]">{art.type}</Badge>
<Badge variant="outline" className={`text-[10px] ${agentCfg.color}`}>
{agentCfg.label}
</Badge>
<span className="text-[10px] text-muted-foreground">{formatDate(art.createdAt)}</span>
</div>
</div>
</div>
);
})
)}
</div>
)}
</div>
</div>
)}
</Card>
);
}
interface DevHistoryProps {
embedded?: boolean;
onContinueTask?: (taskTitle: string) => void;
}
export default function DevHistory({ embedded, onContinueTask }: DevHistoryProps) {
const [statusFilter, setStatusFilter] = useState<string>("all");
const [page, setPage] = useState(0);
const pageSize = 20;
const { data: historyData, isLoading, refetch } = useQuery({
queryKey: ["/api/blackboard/history", statusFilter, page],
queryFn: async () => {
const params = new URLSearchParams();
params.set("limit", pageSize.toString());
params.set("offset", (page * pageSize).toString());
if (statusFilter !== "all") params.set("status", statusFilter);
const res = await fetch(`/api/blackboard/history?${params}`, { credentials: "include" });
if (!res.ok) throw new Error("Falha ao carregar histórico");
return res.json();
},
refetchInterval: 15000,
});
const { data: statsData } = useQuery({
queryKey: ["/api/blackboard/stats"],
queryFn: async () => {
const res = await fetch("/api/blackboard/stats", { credentials: "include" });
if (!res.ok) throw new Error("Falha ao carregar stats");
return res.json();
},
refetchInterval: 15000,
});
const tasks: HistoryTask[] = historyData?.tasks || [];
const stats = statsData?.stats;
const agents = statsData?.agents || [];
return (
<div className={`space-y-4 ${embedded ? "" : "p-4"}`} data-testid="dev-history">
{/* Stats Cards */}
<div className="grid grid-cols-2 md:grid-cols-5 gap-3">
{[
{ label: "Total", value: stats?.totalTasks || 0, color: "text-foreground", bgColor: "bg-muted/50" },
{ label: "Pendentes", value: stats?.pendingTasks || 0, color: "text-amber-600", bgColor: "bg-amber-50" },
{ label: "Concluídas", value: stats?.completedTasks || 0, color: "text-green-600", bgColor: "bg-green-50" },
{ label: "Falhas", value: stats?.failedTasks || 0, color: "text-red-600", bgColor: "bg-red-50" },
{ label: "Artefatos", value: stats?.artifactsCount || 0, color: "text-blue-600", bgColor: "bg-blue-50" },
].map(stat => (
<Card key={stat.label} className={`${stat.bgColor}`}>
<CardContent className="p-3 text-center">
<p className={`text-2xl font-bold ${stat.color}`}>{stat.value}</p>
<p className="text-xs text-muted-foreground">{stat.label}</p>
</CardContent>
</Card>
))}
</div>
{/* Agentes Status */}
{agents.length > 0 && (
<div className="flex items-center gap-2 flex-wrap">
<span className="text-xs font-medium text-muted-foreground">Agentes:</span>
{agents.map((agent: any) => {
const cfg = AGENT_CONFIG[agent.name] || AGENT_CONFIG.dispatcher;
return (
<Badge key={agent.name} variant="outline" className={`text-[10px] ${cfg.color}`}>
<div className={`w-1.5 h-1.5 rounded-full mr-1.5 ${agent.running ? "bg-green-500" : "bg-slate-400"}`} />
{cfg.label}
{agent.tasksProcessed > 0 && ` (${agent.tasksProcessed})`}
</Badge>
);
})}
</div>
)}
{/* Filtros e ações */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-1">
<Filter className="h-4 w-4 text-muted-foreground" />
{[
{ key: "all", label: "Todas" },
{ key: "completed", label: "Concluídas" },
{ key: "failed", label: "Falhas" },
{ key: "in_progress", label: "Em Progresso" },
{ key: "pending", label: "Pendentes" },
].map(f => (
<Button
key={f.key}
variant={statusFilter === f.key ? "default" : "ghost"}
size="sm"
className="h-7 text-xs"
onClick={() => { setStatusFilter(f.key); setPage(0); }}
data-testid={`filter-${f.key}`}
>
{f.label}
</Button>
))}
</div>
<Button variant="ghost" size="sm" onClick={() => refetch()} data-testid="btn-refresh-history">
<RefreshCw className="h-4 w-4" />
</Button>
</div>
{/* Lista de Tarefas */}
<ScrollArea className={embedded ? "h-[calc(100vh-380px)]" : "h-[calc(100vh-300px)]"}>
{isLoading ? (
<div className="flex items-center justify-center py-16">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
<span className="ml-2 text-sm text-muted-foreground">Carregando histórico...</span>
</div>
) : tasks.length === 0 ? (
<Card className="border-dashed">
<CardContent className="flex flex-col items-center justify-center py-16">
<Eye className="h-12 w-12 text-muted-foreground mb-3" />
<h3 className="font-semibold text-lg mb-1">Nenhuma tarefa encontrada</h3>
<p className="text-sm text-muted-foreground text-center max-w-md">
As tarefas executadas pelos agentes autônomos aparecerão aqui com todos os detalhes.
</p>
</CardContent>
</Card>
) : (
<div className="space-y-2 pr-2">
{tasks.map(task => (
<TaskCard key={task.id} task={task} onContinueTask={onContinueTask} />
))}
</div>
)}
</ScrollArea>
{/* Pagination */}
{(historyData?.total || 0) > pageSize && (
<div className="flex items-center justify-between pt-2 border-t">
<span className="text-xs text-muted-foreground">
{page * pageSize + 1}{Math.min((page + 1) * pageSize, historyData?.total || 0)} de {historyData?.total || 0}
</span>
<div className="flex gap-1">
<Button
variant="ghost"
size="sm"
className="h-7 text-xs"
disabled={page === 0}
onClick={() => setPage(p => Math.max(0, p - 1))}
data-testid="btn-prev-page"
>
Anterior
</Button>
<Button
variant="ghost"
size="sm"
className="h-7 text-xs"
disabled={(page + 1) * pageSize >= (historyData?.total || 0)}
onClick={() => setPage(p => p + 1)}
data-testid="btn-next-page"
>
Próximo
</Button>
</div>
</div>
)}
</div>
);
}

View File

@ -0,0 +1,38 @@
import { useState, useEffect } from "react";
import { Clock } from "lucide-react";
export function DigitalClock() {
const [time, setTime] = useState(new Date());
useEffect(() => {
const timer = setInterval(() => setTime(new Date()), 1000);
return () => clearInterval(timer);
}, []);
const formatTime = (date: Date) => {
return date.toLocaleTimeString("pt-BR", {
hour: "2-digit",
minute: "2-digit",
});
};
const formatDate = (date: Date) => {
return date.toLocaleDateString("pt-BR", {
weekday: "short",
day: "2-digit",
month: "short",
});
};
return (
<div
className="flex items-center gap-2 text-xs text-muted-foreground px-2 py-1 rounded bg-muted/50"
data-testid="digital-clock"
>
<Clock className="w-3 h-3" />
<span className="font-mono">{formatTime(time)}</span>
<span className="text-muted-foreground/70"></span>
<span>{formatDate(time)}</span>
</div>
);
}

View File

@ -0,0 +1,12 @@
import React from 'react';
const ElementPanel: React.FC = () => {
return (
<div data-testid="element-panel" className="border p-4 flex flex-col">
<h2 className="font-bold text-lg">Elementos BPMN</h2>
<p className="text-sm text-muted-foreground">Use o diagramador integrado no Process Compass.</p>
</div>
);
};
export default ElementPanel;

View File

@ -0,0 +1,6 @@
import { useKnowledgeCollector } from "@/hooks/use-knowledge-collector";
export function KnowledgeCollectorInit() {
useKnowledgeCollector();
return null;
}

View File

@ -0,0 +1,196 @@
import { useState, useEffect, useCallback } from "react";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { ExternalLink, CheckCircle, Loader2, AlertCircle } from "lucide-react";
interface LoginBridgePopupProps {
isOpen: boolean;
onClose: () => void;
targetUrl: string;
appName: string;
onLoginComplete: () => void;
onLoginPending?: (pending: boolean) => void;
}
export function LoginBridgePopup({
isOpen,
onClose,
targetUrl,
appName,
onLoginComplete,
onLoginPending,
}: LoginBridgePopupProps) {
const [status, setStatus] = useState<"idle" | "waiting" | "syncing" | "complete" | "error">("idle");
const [popupWindow, setPopupWindow] = useState<Window | null>(null);
// Notificar quando o status muda para waiting
useEffect(() => {
onLoginPending?.(status === "waiting");
}, [status, onLoginPending]);
const openLoginPopup = useCallback(() => {
const width = 900;
const height = 700;
const left = window.screenX + (window.outerWidth - width) / 2;
const top = window.screenY + (window.outerHeight - height) / 2;
const popup = window.open(
targetUrl,
`login_${appName}`,
`width=${width},height=${height},left=${left},top=${top},menubar=no,toolbar=no,location=yes,status=yes`
);
if (popup) {
setPopupWindow(popup);
setStatus("waiting");
const checkClosed = setInterval(() => {
if (popup.closed) {
clearInterval(checkClosed);
setPopupWindow(null);
}
}, 500);
}
}, [targetUrl, appName]);
const handleLoginComplete = useCallback(async () => {
setStatus("syncing");
try {
await fetch("/api/login-bridge/mark-logged-in", {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify({
url: targetUrl,
timestamp: Date.now()
}),
});
setStatus("complete");
if (popupWindow && !popupWindow.closed) {
popupWindow.close();
}
setTimeout(() => {
onLoginComplete();
onClose();
}, 1500);
} catch (err) {
console.error("Failed to mark login complete:", err);
setStatus("error");
}
}, [targetUrl, popupWindow, onLoginComplete, onClose]);
useEffect(() => {
if (!isOpen) {
setStatus("idle");
if (popupWindow && !popupWindow.closed) {
popupWindow.close();
}
setPopupWindow(null);
}
}, [isOpen, popupWindow]);
return (
<Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<ExternalLink className="h-5 w-5" />
Login Externo - {appName}
</DialogTitle>
<DialogDescription>
Faça login na janela que será aberta e depois clique em "Concluir Login".
</DialogDescription>
</DialogHeader>
<div className="py-4">
{status === "idle" && (
<div className="text-center space-y-4">
<p className="text-sm text-muted-foreground">
Clique no botão abaixo para abrir a página de login em uma nova janela.
</p>
<Button onClick={openLoginPopup} className="w-full">
<ExternalLink className="h-4 w-4 mr-2" />
Abrir Página de Login
</Button>
</div>
)}
{status === "waiting" && (
<div className="text-center space-y-4">
<div className="bg-green-50 border-2 border-green-400 rounded-lg p-4 text-left">
<p className="text-lg font-bold text-green-800 mb-3 text-center"> fez login na outra janela?</p>
<p className="text-sm text-green-700 mb-4 text-center">
Se você logou no site externo, clique no botão abaixo para concluir!
</p>
<Button onClick={handleLoginComplete} className="w-full bg-green-600 hover:bg-green-700" size="lg">
<CheckCircle className="h-5 w-5 mr-2" />
Sim, Concluir Login!
</Button>
</div>
<div className="text-xs text-muted-foreground border-t pt-3">
<p className="mb-2">Ainda não logou? Siga os passos:</p>
<ol className="text-left space-y-1 list-decimal list-inside">
<li>Faça login na janela que abriu</li>
<li>Volte para esta aba do navegador</li>
<li>Clique em "Concluir Login" acima</li>
</ol>
</div>
<Button
onClick={openLoginPopup}
variant="outline"
size="sm"
>
<ExternalLink className="h-4 w-4 mr-2" />
Abrir janela de login novamente
</Button>
</div>
)}
{status === "syncing" && (
<div className="text-center space-y-2">
<Loader2 className="h-8 w-8 animate-spin mx-auto text-primary" />
<p className="text-sm">Sincronizando sessão...</p>
</div>
)}
{status === "complete" && (
<div className="text-center space-y-2">
<CheckCircle className="h-8 w-8 mx-auto text-green-500" />
<p className="text-sm font-medium text-green-600">Login concluído!</p>
<p className="text-xs text-muted-foreground">Recarregando o aplicativo...</p>
</div>
)}
{status === "error" && (
<div className="text-center space-y-4">
<AlertCircle className="h-8 w-8 mx-auto text-red-500" />
<p className="text-sm text-red-600">Erro ao sincronizar. Tente novamente.</p>
<Button onClick={() => setStatus("idle")} variant="outline">
Tentar Novamente
</Button>
</div>
)}
</div>
<DialogFooter>
<Button variant="ghost" onClick={onClose}>
Cancelar
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}

View File

@ -0,0 +1,184 @@
import { useCallback, useState, useEffect } from "react";
import {
ReactFlow,
MiniMap,
Controls,
Background,
useNodesState,
useEdgesState,
addEdge,
Connection,
Node,
Edge,
BackgroundVariant,
Panel,
} from "@xyflow/react";
import "@xyflow/react/dist/style.css";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Plus, Save, Trash2, Circle, Square, Diamond, ArrowRight } from "lucide-react";
interface ProcessDiagramProps {
initialNodes?: Node[];
initialEdges?: Edge[];
initialViewport?: { x: number; y: number; zoom: number };
onSave?: (nodes: Node[], edges: Edge[], viewport: { x: number; y: number; zoom: number }) => void;
readOnly?: boolean;
}
const nodeTypes = {
start: { label: "Início", color: "#22c55e", icon: Circle },
end: { label: "Fim", color: "#ef4444", icon: Circle },
process: { label: "Processo", color: "#3b82f6", icon: Square },
decision: { label: "Decisão", color: "#f59e0b", icon: Diamond },
subprocess: { label: "Subprocesso", color: "#8b5cf6", icon: Square },
};
export function ProcessDiagram({ initialNodes = [], initialEdges = [], initialViewport, onSave, readOnly = false }: ProcessDiagramProps) {
const [nodes, setNodes, onNodesChange] = useNodesState(initialNodes);
const [edges, setEdges, onEdgesChange] = useEdgesState(initialEdges);
const [showAddNodeDialog, setShowAddNodeDialog] = useState(false);
const [newNodeData, setNewNodeData] = useState({ label: "", type: "process" });
const [viewport, setViewport] = useState(initialViewport || { x: 0, y: 0, zoom: 1 });
useEffect(() => {
setNodes(initialNodes);
setEdges(initialEdges);
if (initialViewport) {
setViewport(initialViewport);
} else {
setViewport({ x: 0, y: 0, zoom: 1 });
}
}, [initialNodes, initialEdges, initialViewport, setNodes, setEdges]);
const onConnect = useCallback(
(params: Connection) => setEdges((eds) => addEdge({ ...params, animated: true, type: "smoothstep" }, eds)),
[setEdges]
);
const handleAddNode = () => {
if (!newNodeData.label.trim()) return;
const nodeConfig = nodeTypes[newNodeData.type as keyof typeof nodeTypes];
const newNode: Node = {
id: `node-${Date.now()}`,
type: "default",
position: { x: Math.random() * 400 + 100, y: Math.random() * 300 + 100 },
data: {
label: newNodeData.label,
nodeType: newNodeData.type,
},
style: {
background: nodeConfig.color,
color: "#fff",
border: "none",
borderRadius: newNodeData.type === "decision" ? "0" : newNodeData.type === "start" || newNodeData.type === "end" ? "50%" : "8px",
padding: "16px",
minWidth: "120px",
textAlign: "center" as const,
transform: newNodeData.type === "decision" ? "rotate(45deg)" : undefined,
},
};
setNodes((nds) => [...nds, newNode]);
setNewNodeData({ label: "", type: "process" });
setShowAddNodeDialog(false);
};
const handleDeleteSelected = () => {
setNodes((nds) => nds.filter((node) => !node.selected));
setEdges((eds) => eds.filter((edge) => !edge.selected));
};
const handleSave = () => {
if (onSave) {
onSave(nodes, edges, viewport);
}
};
return (
<div className="w-full h-[500px] border rounded-lg overflow-hidden">
<ReactFlow
nodes={nodes}
edges={edges}
onNodesChange={readOnly ? undefined : onNodesChange}
onEdgesChange={readOnly ? undefined : onEdgesChange}
onConnect={readOnly ? undefined : onConnect}
onViewportChange={setViewport}
defaultViewport={initialViewport || { x: 0, y: 0, zoom: 1 }}
fitView={!initialViewport}
snapToGrid
snapGrid={[15, 15]}
nodesDraggable={!readOnly}
nodesConnectable={!readOnly}
elementsSelectable={!readOnly}
>
<Controls />
<MiniMap />
<Background variant={BackgroundVariant.Dots} gap={12} size={1} />
{!readOnly && (
<Panel position="top-left" className="flex gap-2">
<Button size="sm" onClick={() => setShowAddNodeDialog(true)} data-testid="btn-add-node">
<Plus className="h-4 w-4 mr-1" /> Adicionar
</Button>
<Button size="sm" variant="outline" onClick={handleDeleteSelected} data-testid="btn-delete-node">
<Trash2 className="h-4 w-4 mr-1" /> Excluir
</Button>
<Button size="sm" onClick={handleSave} data-testid="btn-save-diagram">
<Save className="h-4 w-4 mr-1" /> Salvar
</Button>
</Panel>
)}
</ReactFlow>
<Dialog open={showAddNodeDialog} onOpenChange={setShowAddNodeDialog}>
<DialogContent>
<DialogHeader>
<DialogTitle>Adicionar Elemento</DialogTitle>
</DialogHeader>
<div className="space-y-4">
<div>
<Label>Tipo</Label>
<Select value={newNodeData.type} onValueChange={(value) => setNewNodeData({ ...newNodeData, type: value })}>
<SelectTrigger data-testid="select-node-type">
<SelectValue />
</SelectTrigger>
<SelectContent>
{Object.entries(nodeTypes).map(([key, { label, color }]) => (
<SelectItem key={key} value={key}>
<div className="flex items-center gap-2">
<div className="w-3 h-3 rounded" style={{ backgroundColor: color }} />
{label}
</div>
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div>
<Label>Nome</Label>
<Input
value={newNodeData.label}
onChange={(e) => setNewNodeData({ ...newNodeData, label: e.target.value })}
placeholder="Nome do elemento"
data-testid="input-node-label"
/>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setShowAddNodeDialog(false)}>
Cancelar
</Button>
<Button onClick={handleAddNode} data-testid="btn-confirm-add-node">
Adicionar
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
}

View File

@ -0,0 +1,366 @@
import React, { useState, useRef } from "react";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogClose } from "@/components/ui/dialog";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { Button } from "@/components/ui/button";
import { ScrollArea } from "@/components/ui/scroll-area";
import {
Share,
Download,
X,
Maximize2,
MoreHorizontal,
FileText,
FileType,
File,
CloudUpload,
Check,
Copy
} from "lucide-react";
import { jsPDF } from "jspdf";
import { Document, Packer, Paragraph, TextRun, HeadingLevel } from "docx";
import { saveAs } from "file-saver";
interface ResultViewerProps {
isOpen: boolean;
onClose: () => void;
title: string;
recipient?: string;
sender?: string;
date?: string;
content: string;
}
function parseMarkdownContent(content: string) {
const lines = content.split('\n');
const sections: { type: 'heading' | 'paragraph' | 'list'; level?: number; text: string }[] = [];
lines.forEach(line => {
const headingMatch = line.match(/^(#{1,6})\s+(.+)$/);
if (headingMatch) {
sections.push({
type: 'heading',
level: headingMatch[1].length,
text: headingMatch[2]
});
} else if (line.startsWith('- ') || line.startsWith('* ')) {
sections.push({
type: 'list',
text: line.substring(2)
});
} else if (line.trim()) {
sections.push({
type: 'paragraph',
text: line
});
}
});
return sections;
}
function RenderContent({ content }: { content: string }) {
const sections = parseMarkdownContent(content);
const renderHeading = (level: number, text: string, key: number) => {
const baseClass = "text-[#1f334d]";
switch (level) {
case 1: return <h1 key={key} data-testid={`heading-h1-${key}`} className={`${baseClass} text-2xl font-bold mb-4 mt-6`}>{text}</h1>;
case 2: return <h2 key={key} data-testid={`heading-h2-${key}`} className={`${baseClass} text-xl font-semibold mb-3 mt-5`}>{text}</h2>;
case 3: return <h3 key={key} data-testid={`heading-h3-${key}`} className={`${baseClass} text-lg font-semibold mb-2 mt-4`}>{text}</h3>;
case 4: return <h4 key={key} data-testid={`heading-h4-${key}`} className={`${baseClass} text-base font-medium mb-2 mt-3`}>{text}</h4>;
default: return <h5 key={key} data-testid={`heading-h5-${key}`} className={`${baseClass} text-sm font-medium mb-1 mt-2`}>{text}</h5>;
}
};
const elements: React.ReactNode[] = [];
let currentListItems: { text: string; idx: number }[] = [];
const flushList = () => {
if (currentListItems.length > 0) {
elements.push(
<ul key={`list-${currentListItems[0].idx}`} className="list-disc ml-6 mb-3" data-testid={`list-${currentListItems[0].idx}`}>
{currentListItems.map(item => (
<li key={item.idx} data-testid={`list-item-${item.idx}`} className="mb-1 text-[#1f334d] leading-relaxed">
{item.text}
</li>
))}
</ul>
);
currentListItems = [];
}
};
sections.forEach((section, idx) => {
if (section.type === 'list') {
currentListItems.push({ text: section.text, idx });
} else {
flushList();
if (section.type === 'heading') {
elements.push(renderHeading(section.level || 1, section.text, idx));
} else {
elements.push(
<p key={idx} data-testid={`paragraph-${idx}`} className="mb-3 text-[#1f334d] leading-relaxed">
{section.text}
</p>
);
}
}
});
flushList();
return (
<div className="prose prose-sm max-w-none text-[#1f334d]" data-testid="render-content">
{elements}
</div>
);
}
export function ResultViewer({
isOpen,
onClose,
title,
recipient,
sender,
date,
content
}: ResultViewerProps) {
const [copied, setCopied] = useState(false);
const contentRef = useRef<HTMLDivElement>(null);
const currentDate = date || new Date().toLocaleDateString('pt-BR', {
day: 'numeric',
month: 'long',
year: 'numeric'
});
const exportToMarkdown = () => {
let md = `# ${title}\n\n`;
if (recipient) md += `**Para:** ${recipient}\n\n`;
if (sender) md += `**De:** ${sender}\n\n`;
md += `**Data:** ${currentDate}\n\n---\n\n`;
md += content;
const blob = new Blob([md], { type: "text/markdown;charset=utf-8" });
saveAs(blob, `${title.replace(/\s+/g, '-').toLowerCase()}.md`);
};
const exportToPDF = () => {
const doc = new jsPDF();
const pageWidth = doc.internal.pageSize.getWidth();
const margin = 20;
const maxWidth = pageWidth - margin * 2;
let currentY = 20;
doc.setFontSize(18);
doc.setTextColor(31, 51, 77);
const titleLines = doc.splitTextToSize(title, maxWidth);
doc.text(titleLines, margin, currentY);
currentY += titleLines.length * 8 + 10;
doc.setFontSize(10);
doc.setTextColor(90, 108, 125);
if (recipient) {
doc.text(`Para: ${recipient}`, margin, currentY);
currentY += 6;
}
if (sender) {
doc.text(`De: ${sender}`, margin, currentY);
currentY += 6;
}
doc.text(`Data: ${currentDate}`, margin, currentY);
currentY += 10;
doc.setDrawColor(200, 200, 200);
doc.line(margin, currentY, pageWidth - margin, currentY);
currentY += 10;
doc.setFontSize(11);
doc.setTextColor(31, 51, 77);
const cleanContent = content.replace(/^#{1,6}\s+/gm, '');
const contentLines = doc.splitTextToSize(cleanContent, maxWidth);
contentLines.forEach((line: string) => {
if (currentY > doc.internal.pageSize.getHeight() - margin) {
doc.addPage();
currentY = margin;
}
doc.text(line, margin, currentY);
currentY += 6;
});
doc.save(`${title.replace(/\s+/g, '-').toLowerCase()}.pdf`);
};
const exportToDocx = async () => {
const paragraphs = [];
paragraphs.push(
new Paragraph({
children: [new TextRun({ text: title, bold: true, size: 36 })],
heading: HeadingLevel.HEADING_1,
})
);
paragraphs.push(new Paragraph({ children: [] }));
if (recipient) {
paragraphs.push(
new Paragraph({
children: [
new TextRun({ text: "Para: ", bold: true }),
new TextRun({ text: recipient })
]
})
);
}
if (sender) {
paragraphs.push(
new Paragraph({
children: [
new TextRun({ text: "De: ", bold: true }),
new TextRun({ text: sender })
]
})
);
}
paragraphs.push(
new Paragraph({
children: [
new TextRun({ text: "Data: ", bold: true }),
new TextRun({ text: currentDate })
]
})
);
paragraphs.push(new Paragraph({ children: [] }));
const sections = parseMarkdownContent(content);
sections.forEach(section => {
if (section.type === 'heading') {
const level = section.level || 3;
const getHeadingLevel = (l: number) => {
if (l === 1) return HeadingLevel.HEADING_1;
if (l === 2) return HeadingLevel.HEADING_2;
return HeadingLevel.HEADING_3;
};
paragraphs.push(
new Paragraph({
children: [new TextRun({ text: section.text, bold: true })],
heading: getHeadingLevel(level),
})
);
} else {
paragraphs.push(
new Paragraph({
children: [new TextRun({ text: section.text })]
})
);
}
});
const doc = new Document({
sections: [{ properties: {}, children: paragraphs }],
});
const blob = await Packer.toBlob(doc);
saveAs(blob, `${title.replace(/\s+/g, '-').toLowerCase()}.docx`);
};
const copyToClipboard = async () => {
await navigator.clipboard.writeText(content);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
};
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent className="max-w-4xl max-h-[90vh] p-0 gap-0 bg-white">
<DialogHeader className="flex flex-row items-center justify-between px-4 py-3 border-b bg-white">
<div className="flex items-center gap-3">
<div className="w-8 h-8 bg-blue-100 rounded flex items-center justify-center">
<FileText className="w-4 h-4 text-blue-600" />
</div>
<div>
<DialogTitle className="text-base font-medium text-[#1f334d]" data-testid="result-viewer-title">
{title}
</DialogTitle>
<p className="text-xs text-gray-500">Última modificação: pouco</p>
</div>
</div>
<div className="flex items-center gap-2">
<Button
variant="ghost"
size="icon"
onClick={copyToClipboard}
className="h-8 w-8"
title="Copiar"
data-testid="button-copy-content"
>
{copied ? <Check className="w-4 h-4 text-green-600" /> : <Copy className="w-4 h-4" />}
</Button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon" className="h-8 w-8" data-testid="button-export-menu">
<Download className="w-4 h-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-56">
<DropdownMenuItem onClick={exportToMarkdown} data-testid="export-markdown">
<FileText className="w-4 h-4 mr-2 text-blue-600" />
Markdown
</DropdownMenuItem>
<DropdownMenuItem onClick={exportToPDF} data-testid="export-pdf">
<File className="w-4 h-4 mr-2 text-red-600" />
PDF
</DropdownMenuItem>
<DropdownMenuItem onClick={exportToDocx} data-testid="export-docx">
<FileType className="w-4 h-4 mr-2 text-blue-700" />
Docx
</DropdownMenuItem>
<DropdownMenuItem disabled className="text-gray-400" data-testid="export-google-drive">
<CloudUpload className="w-4 h-4 mr-2" />
Salvar no Google Drive
</DropdownMenuItem>
<DropdownMenuItem disabled className="text-gray-400" data-testid="export-onedrive-personal">
<CloudUpload className="w-4 h-4 mr-2" />
Salvar no OneDrive (pessoal)
</DropdownMenuItem>
<DropdownMenuItem disabled className="text-gray-400" data-testid="export-onedrive-work">
<CloudUpload className="w-4 h-4 mr-2" />
Salvar no OneDrive (trabalho/escola)
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<Button variant="ghost" size="icon" className="h-8 w-8" title="Maximizar" data-testid="button-maximize">
<Maximize2 className="w-4 h-4" />
</Button>
<DialogClose asChild>
<Button variant="ghost" size="icon" className="h-8 w-8" data-testid="button-close-viewer">
<X className="w-4 h-4" />
</Button>
</DialogClose>
</div>
</DialogHeader>
<ScrollArea className="flex-1 max-h-[calc(90vh-80px)]">
<div ref={contentRef} className="px-12 py-8 bg-white min-h-[500px]">
{(recipient || sender) && (
<div className="mb-6 text-sm text-gray-600 space-y-1" data-testid="document-metadata">
{recipient && <p data-testid="text-recipient"><strong>Para:</strong> {recipient}</p>}
{sender && <p data-testid="text-sender"><strong>De:</strong> {sender}</p>}
<p data-testid="text-date"><strong>Data:</strong> {currentDate}</p>
</div>
)}
<div className="border-b border-gray-200 mb-6" />
<RenderContent content={content} />
</div>
</ScrollArea>
</DialogContent>
</Dialog>
);
}
export default ResultViewer;

View File

@ -0,0 +1,342 @@
import { useEditor, EditorContent } from '@tiptap/react';
import StarterKit from '@tiptap/starter-kit';
import Link from '@tiptap/extension-link';
import Image from '@tiptap/extension-image';
import Youtube from '@tiptap/extension-youtube';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { useState, useCallback } from 'react';
import {
Bold,
Italic,
Strikethrough,
Code,
List,
ListOrdered,
Quote,
Link as LinkIcon,
Image as ImageIcon,
Youtube as YoutubeIcon,
Undo,
Redo,
Heading1,
Heading2,
Heading3,
} from 'lucide-react';
import {
Popover,
PopoverContent,
PopoverTrigger,
} from '@/components/ui/popover';
interface RichTextEditorProps {
content: string;
onChange: (content: string) => void;
placeholder?: string;
className?: string;
}
export function RichTextEditor({ content, onChange, placeholder, className }: RichTextEditorProps) {
const [linkUrl, setLinkUrl] = useState('');
const [imageUrl, setImageUrl] = useState('');
const [youtubeUrl, setYoutubeUrl] = useState('');
const [showLinkPopover, setShowLinkPopover] = useState(false);
const [showImagePopover, setShowImagePopover] = useState(false);
const [showYoutubePopover, setShowYoutubePopover] = useState(false);
const editor = useEditor({
extensions: [
StarterKit.configure({
heading: {
levels: [1, 2, 3],
},
}),
Link.configure({
openOnClick: true,
HTMLAttributes: {
class: 'text-primary underline cursor-pointer',
},
}),
Image.configure({
HTMLAttributes: {
class: 'max-w-full h-auto rounded-lg my-2',
},
}),
Youtube.configure({
HTMLAttributes: {
class: 'w-full aspect-video rounded-lg my-2',
},
}),
],
content,
editorProps: {
attributes: {
class: 'prose prose-sm max-w-none focus:outline-none min-h-[150px] p-3',
},
},
onUpdate: ({ editor }) => {
onChange(editor.getHTML());
},
});
const addLink = useCallback(() => {
if (linkUrl && editor) {
editor.chain().focus().extendMarkRange('link').setLink({ href: linkUrl }).run();
setLinkUrl('');
setShowLinkPopover(false);
}
}, [editor, linkUrl]);
const addImage = useCallback(() => {
if (imageUrl && editor) {
editor.chain().focus().setImage({ src: imageUrl }).run();
setImageUrl('');
setShowImagePopover(false);
}
}, [editor, imageUrl]);
const addYoutubeVideo = useCallback(() => {
if (youtubeUrl && editor) {
editor.chain().focus().setYoutubeVideo({ src: youtubeUrl }).run();
setYoutubeUrl('');
setShowYoutubePopover(false);
}
}, [editor, youtubeUrl]);
const handlePaste = useCallback((e: React.ClipboardEvent) => {
const items = e.clipboardData?.items;
if (!items || !editor) return;
for (let i = 0; i < items.length; i++) {
if (items[i].type.indexOf('image') !== -1) {
e.preventDefault();
const blob = items[i].getAsFile();
if (blob) {
const reader = new FileReader();
reader.onload = (event) => {
const base64 = event.target?.result as string;
editor.chain().focus().setImage({ src: base64 }).run();
};
reader.readAsDataURL(blob);
}
return;
}
}
}, [editor]);
if (!editor) return null;
return (
<div className={`border rounded-lg overflow-hidden ${className}`}>
<div className="flex flex-wrap items-center gap-1 p-2 border-b bg-muted/30">
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => editor.chain().focus().toggleBold().run()}
className={editor.isActive('bold') ? 'bg-muted' : ''}
data-testid="btn-bold"
>
<Bold className="h-4 w-4" />
</Button>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => editor.chain().focus().toggleItalic().run()}
className={editor.isActive('italic') ? 'bg-muted' : ''}
data-testid="btn-italic"
>
<Italic className="h-4 w-4" />
</Button>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => editor.chain().focus().toggleStrike().run()}
className={editor.isActive('strike') ? 'bg-muted' : ''}
data-testid="btn-strike"
>
<Strikethrough className="h-4 w-4" />
</Button>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => editor.chain().focus().toggleCode().run()}
className={editor.isActive('code') ? 'bg-muted' : ''}
data-testid="btn-code"
>
<Code className="h-4 w-4" />
</Button>
<div className="w-px h-6 bg-border mx-1" />
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => editor.chain().focus().toggleHeading({ level: 1 }).run()}
className={editor.isActive('heading', { level: 1 }) ? 'bg-muted' : ''}
data-testid="btn-h1"
>
<Heading1 className="h-4 w-4" />
</Button>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => editor.chain().focus().toggleHeading({ level: 2 }).run()}
className={editor.isActive('heading', { level: 2 }) ? 'bg-muted' : ''}
data-testid="btn-h2"
>
<Heading2 className="h-4 w-4" />
</Button>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => editor.chain().focus().toggleHeading({ level: 3 }).run()}
className={editor.isActive('heading', { level: 3 }) ? 'bg-muted' : ''}
data-testid="btn-h3"
>
<Heading3 className="h-4 w-4" />
</Button>
<div className="w-px h-6 bg-border mx-1" />
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => editor.chain().focus().toggleBulletList().run()}
className={editor.isActive('bulletList') ? 'bg-muted' : ''}
data-testid="btn-bullet-list"
>
<List className="h-4 w-4" />
</Button>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => editor.chain().focus().toggleOrderedList().run()}
className={editor.isActive('orderedList') ? 'bg-muted' : ''}
data-testid="btn-ordered-list"
>
<ListOrdered className="h-4 w-4" />
</Button>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => editor.chain().focus().toggleBlockquote().run()}
className={editor.isActive('blockquote') ? 'bg-muted' : ''}
data-testid="btn-quote"
>
<Quote className="h-4 w-4" />
</Button>
<div className="w-px h-6 bg-border mx-1" />
<Popover open={showLinkPopover} onOpenChange={setShowLinkPopover}>
<PopoverTrigger asChild>
<Button
type="button"
variant="ghost"
size="sm"
className={editor.isActive('link') ? 'bg-muted' : ''}
data-testid="btn-add-link"
>
<LinkIcon className="h-4 w-4" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-72">
<div className="space-y-2">
<Input
placeholder="Cole a URL aqui..."
value={linkUrl}
onChange={(e) => setLinkUrl(e.target.value)}
data-testid="input-link-url"
/>
<Button size="sm" onClick={addLink} className="w-full" data-testid="btn-confirm-link">
Adicionar Link
</Button>
</div>
</PopoverContent>
</Popover>
<Popover open={showImagePopover} onOpenChange={setShowImagePopover}>
<PopoverTrigger asChild>
<Button type="button" variant="ghost" size="sm" data-testid="btn-add-image">
<ImageIcon className="h-4 w-4" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-72">
<div className="space-y-2">
<Input
placeholder="Cole a URL da imagem..."
value={imageUrl}
onChange={(e) => setImageUrl(e.target.value)}
data-testid="input-image-url"
/>
<Button size="sm" onClick={addImage} className="w-full" data-testid="btn-confirm-image">
Adicionar Imagem
</Button>
<p className="text-xs text-muted-foreground text-center">
Ou cole uma imagem diretamente (Ctrl+V)
</p>
</div>
</PopoverContent>
</Popover>
<Popover open={showYoutubePopover} onOpenChange={setShowYoutubePopover}>
<PopoverTrigger asChild>
<Button type="button" variant="ghost" size="sm" data-testid="btn-add-youtube">
<YoutubeIcon className="h-4 w-4" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-72">
<div className="space-y-2">
<Input
placeholder="Cole a URL do YouTube..."
value={youtubeUrl}
onChange={(e) => setYoutubeUrl(e.target.value)}
data-testid="input-youtube-url"
/>
<Button size="sm" onClick={addYoutubeVideo} className="w-full" data-testid="btn-confirm-youtube">
Adicionar Vídeo
</Button>
</div>
</PopoverContent>
</Popover>
<div className="flex-1" />
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => editor.chain().focus().undo().run()}
disabled={!editor.can().undo()}
data-testid="btn-undo"
>
<Undo className="h-4 w-4" />
</Button>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => editor.chain().focus().redo().run()}
disabled={!editor.can().redo()}
data-testid="btn-redo"
>
<Redo className="h-4 w-4" />
</Button>
</div>
<div onPaste={handlePaste}>
<EditorContent editor={editor} />
</div>
</div>
);
}

View File

@ -0,0 +1,988 @@
import { useState, useRef, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Checkbox } from "@/components/ui/checkbox";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { useToast } from "@/hooks/use-toast";
import { Printer, Save, FileText, Pen, X, RotateCcw, Search, User } from "lucide-react";
interface Person {
id: number;
fullName: string;
cpfCnpj: string;
phone?: string;
email?: string;
}
interface TradeInFormProps {
onClose: () => void;
onSave?: (data: any) => void;
initialEvaluation?: any;
customerId?: number;
}
interface ChecklistItem {
id: string;
description: string;
value: "sim" | "nao" | "";
observation: string;
}
interface PartItem {
peca: string;
valor: string;
}
const DEFAULT_CHECKLIST: ChecklistItem[] = [
{ id: "liga", description: "Aparelho liga corretamente", value: "", observation: "" },
{ id: "avarias", description: "Avarias, travamentos ou toque fantasma", value: "", observation: "" },
{ id: "manchas_tela", description: "Manchas na tela", value: "", observation: "" },
{ id: "botoes", description: "Botões funcionando", value: "", observation: "" },
{ id: "marcas_uso", description: "Marcas de uso", value: "", observation: "" },
{ id: "wifi", description: "Wi-Fi funcionando", value: "", observation: "" },
{ id: "chip", description: "Chip funcionando", value: "", observation: "" },
{ id: "4g5g", description: "4G/5G funcionando", value: "", observation: "" },
{ id: "sensores", description: "Sensores funcionando / NFC", value: "", observation: "" },
{ id: "faceid", description: "Face ID / Touch ID funcionando", value: "", observation: "" },
{ id: "microfones", description: "Microfones funcionando", value: "", observation: "" },
{ id: "auricular", description: "Áudio auricular funcionando", value: "", observation: "" },
{ id: "altofalante", description: "Áudio alto-falante funcionando", value: "", observation: "" },
{ id: "carregamento", description: "Entrada de carregamento funcionando", value: "", observation: "" },
{ id: "cameras", description: "Câmeras funcionando / Manchas", value: "", observation: "" },
{ id: "flash", description: "Flash funcionando", value: "", observation: "" },
{ id: "carregador", description: "Possui carregador", value: "", observation: "" },
{ id: "3utools", description: "Análise pelo 3uTools OK", value: "", observation: "" },
];
export default function TradeInForm({ onClose, onSave, initialEvaluation, customerId }: TradeInFormProps) {
const { toast } = useToast();
const printRef = useRef<HTMLDivElement>(null);
const canvasRef = useRef<HTMLCanvasElement>(null);
const employeeCanvasRef = useRef<HTMLCanvasElement>(null);
const [formData, setFormData] = useState({
data: new Date().toLocaleDateString("pt-BR"),
senha: "",
cliente: "",
cpf: "",
aparelho: "",
imei: "",
valor: "",
consultor: "",
venda: "",
saudeBateria: "",
});
const [availableEvaluations, setAvailableEvaluations] = useState<any[]>([]);
const [showEvaluationPicker, setShowEvaluationPicker] = useState(false);
const [loadingEvaluations, setLoadingEvaluations] = useState(false);
const [parts, setParts] = useState<PartItem[]>([
{ peca: "", valor: "" },
{ peca: "", valor: "" },
{ peca: "", valor: "" },
{ peca: "", valor: "" },
{ peca: "", valor: "" },
]);
const [checklist, setChecklist] = useState<ChecklistItem[]>(DEFAULT_CHECKLIST);
const [declarations, setDeclarations] = useState({
removeuDados: false,
transferePropriedade: false,
});
const [customerSignature, setCustomerSignature] = useState<string | null>(null);
const [employeeSignature, setEmployeeSignature] = useState<string | null>(null);
const [isSigningCustomer, setIsSigningCustomer] = useState(false);
const [isSigningEmployee, setIsSigningEmployee] = useState(false);
const [isDrawing, setIsDrawing] = useState(false);
const [personsList, setPersonsList] = useState<Person[]>([]);
const [filteredPersons, setFilteredPersons] = useState<Person[]>([]);
const [showPersonDropdown, setShowPersonDropdown] = useState(false);
const [selectedPersonId, setSelectedPersonId] = useState<number | null>(null);
const personSearchRef = useRef<HTMLDivElement>(null);
useEffect(() => {
const loadPersons = async () => {
try {
const res = await fetch("/api/erp/persons", { credentials: "include" });
if (res.ok) {
const data = await res.json();
setPersonsList(data);
}
} catch (error) {
console.error("Error loading persons:", error);
}
};
loadPersons();
}, []);
useEffect(() => {
const loadEvaluations = async () => {
setLoadingEvaluations(true);
try {
const res = await fetch("/api/retail/evaluations?status=approved,pending", { credentials: "include" });
if (res.ok) {
const data = await res.json();
setAvailableEvaluations(data);
}
} catch (error) {
console.error("Error loading evaluations:", error);
} finally {
setLoadingEvaluations(false);
}
};
loadEvaluations();
}, []);
useEffect(() => {
if (initialEvaluation) {
loadEvaluationData(initialEvaluation);
}
}, [initialEvaluation]);
const loadEvaluationData = (evaluation: any) => {
const notesData = evaluation.notes ? JSON.parse(evaluation.notes) : {};
setFormData({
data: evaluation.evaluationDate ? new Date(evaluation.evaluationDate).toLocaleDateString("pt-BR") : new Date().toLocaleDateString("pt-BR"),
senha: notesData.senha || "",
cliente: evaluation.customerName || "",
cpf: evaluation.customerCpf || "",
aparelho: `${evaluation.brand || ""} ${evaluation.model || ""}`.trim(),
imei: evaluation.imei || "",
valor: evaluation.estimatedValue ? `R$ ${parseFloat(evaluation.estimatedValue).toLocaleString("pt-BR", { minimumFractionDigits: 2 })}` : "",
consultor: notesData.consultor || "",
venda: notesData.venda || "",
saudeBateria: evaluation.batteryHealth?.toString() || "",
});
if (notesData.parts) setParts(notesData.parts);
if (notesData.checklist) setChecklist(notesData.checklist);
if (notesData.declarations) setDeclarations(notesData.declarations);
setShowEvaluationPicker(false);
toast({ title: "Dados da avaliação carregados!" });
};
useEffect(() => {
if (formData.cliente.length >= 2 && !selectedPersonId) {
const filtered = personsList.filter(p =>
p.fullName.toLowerCase().includes(formData.cliente.toLowerCase()) ||
(p.cpfCnpj && p.cpfCnpj.includes(formData.cliente))
);
setFilteredPersons(filtered);
setShowPersonDropdown(filtered.length > 0);
} else {
setShowPersonDropdown(false);
}
}, [formData.cliente, personsList, selectedPersonId]);
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (personSearchRef.current && !personSearchRef.current.contains(event.target as Node)) {
setShowPersonDropdown(false);
}
};
document.addEventListener("mousedown", handleClickOutside);
return () => document.removeEventListener("mousedown", handleClickOutside);
}, []);
const selectPerson = (person: Person) => {
setFormData({
...formData,
cliente: person.fullName,
cpf: person.cpfCnpj || "",
});
setSelectedPersonId(person.id);
setShowPersonDropdown(false);
};
useEffect(() => {
if (isSigningCustomer && canvasRef.current) {
const canvas = canvasRef.current;
const ctx = canvas.getContext("2d");
if (ctx) {
ctx.fillStyle = "#ffffff";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.strokeStyle = "#000000";
ctx.lineWidth = 2;
ctx.lineCap = "round";
ctx.lineJoin = "round";
}
}
}, [isSigningCustomer]);
useEffect(() => {
if (isSigningEmployee && employeeCanvasRef.current) {
const canvas = employeeCanvasRef.current;
const ctx = canvas.getContext("2d");
if (ctx) {
ctx.fillStyle = "#ffffff";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.strokeStyle = "#000000";
ctx.lineWidth = 2;
ctx.lineCap = "round";
ctx.lineJoin = "round";
}
}
}, [isSigningEmployee]);
const startDrawing = (e: React.MouseEvent<HTMLCanvasElement> | React.TouchEvent<HTMLCanvasElement>, canvas: HTMLCanvasElement | null) => {
if (!canvas) return;
setIsDrawing(true);
const ctx = canvas.getContext("2d");
if (!ctx) return;
const rect = canvas.getBoundingClientRect();
const x = "touches" in e ? e.touches[0].clientX - rect.left : e.clientX - rect.left;
const y = "touches" in e ? e.touches[0].clientY - rect.top : e.clientY - rect.top;
ctx.beginPath();
ctx.moveTo(x, y);
};
const draw = (e: React.MouseEvent<HTMLCanvasElement> | React.TouchEvent<HTMLCanvasElement>, canvas: HTMLCanvasElement | null) => {
if (!isDrawing || !canvas) return;
const ctx = canvas.getContext("2d");
if (!ctx) return;
const rect = canvas.getBoundingClientRect();
const x = "touches" in e ? e.touches[0].clientX - rect.left : e.clientX - rect.left;
const y = "touches" in e ? e.touches[0].clientY - rect.top : e.clientY - rect.top;
ctx.lineTo(x, y);
ctx.stroke();
};
const stopDrawing = () => {
setIsDrawing(false);
};
const clearSignature = (isCustomer: boolean) => {
const canvas = isCustomer ? canvasRef.current : employeeCanvasRef.current;
if (!canvas) return;
const ctx = canvas.getContext("2d");
if (ctx) {
ctx.fillStyle = "#ffffff";
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
};
const saveSignature = (isCustomer: boolean) => {
const canvas = isCustomer ? canvasRef.current : employeeCanvasRef.current;
if (!canvas) return;
const dataUrl = canvas.toDataURL("image/png");
if (isCustomer) {
setCustomerSignature(dataUrl);
setIsSigningCustomer(false);
} else {
setEmployeeSignature(dataUrl);
setIsSigningEmployee(false);
}
};
const updateChecklist = (id: string, field: "value" | "observation", val: any) => {
setChecklist(prev => prev.map(item =>
item.id === id ? { ...item, [field]: val } : item
));
};
const updatePart = (index: number, field: "peca" | "valor", val: string) => {
setParts(prev => prev.map((p, i) =>
i === index ? { ...p, [field]: val } : p
));
};
const handlePrint = () => {
const printContent = printRef.current;
if (!printContent) return;
const printWindow = window.open("", "_blank");
if (!printWindow) {
toast({ title: "Erro ao abrir janela de impressão", variant: "destructive" });
return;
}
printWindow.document.write(`
<!DOCTYPE html>
<html>
<head>
<title>Checklist Trade-In - ${formData.cliente}</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: Arial, sans-serif; font-size: 11px; padding: 15px; }
.header { text-align: center; margin-bottom: 15px; border-bottom: 2px solid #000; padding-bottom: 10px; }
.header h1 { font-size: 16px; margin-bottom: 5px; }
.header-row { display: flex; justify-content: space-between; margin-bottom: 8px; font-size: 12px; }
.field-row { display: flex; gap: 20px; margin-bottom: 8px; }
.field { flex: 1; }
.field-label { font-weight: bold; }
.field-value { border-bottom: 1px solid #000; min-height: 18px; padding-left: 5px; }
.section { margin-top: 15px; margin-bottom: 10px; }
.section-title { font-size: 12px; font-weight: bold; background: #e0e0e0; padding: 5px; margin-bottom: 8px; }
.parts-grid { display: grid; grid-template-columns: repeat(5, 1fr); gap: 8px; margin-bottom: 15px; }
.part-box { border: 1px solid #ccc; padding: 5px; font-size: 10px; }
.term { font-size: 9px; text-align: justify; background: #f5f5f5; padding: 10px; border: 1px solid #ddd; margin-bottom: 15px; }
table { width: 100%; border-collapse: collapse; margin-bottom: 15px; }
th, td { border: 1px solid #000; padding: 4px 6px; text-align: left; }
th { background: #e0e0e0; font-size: 10px; }
td { font-size: 10px; }
.check-cell { width: 40px; text-align: center; }
.obs-cell { width: 150px; }
.declarations { background: #f9f9f9; padding: 10px; border: 1px solid #ddd; margin-bottom: 15px; }
.declaration-item { margin-bottom: 8px; }
.signatures { display: flex; justify-content: space-between; margin-top: 30px; }
.signature-box { width: 45%; text-align: center; }
.signature-line { border-top: 1px solid #000; margin-top: 60px; padding-top: 5px; }
.signature-image { max-width: 200px; max-height: 60px; margin-bottom: 5px; }
@media print {
body { padding: 10px; }
.no-print { display: none; }
}
</style>
</head>
<body>
<div class="header">
<h1>CHECKLIST DE AVALIAÇÃO - TRADE-IN</h1>
<h2 style="font-size: 12px; font-weight: normal;">SUPERSTORE</h2>
</div>
<div class="header-row">
<span><strong>DATA:</strong> ${formData.data}</span>
<span><strong>SENHA:</strong> ${formData.senha}</span>
</div>
<div class="field-row">
<div class="field" style="flex: 2;">
<span class="field-label">CLIENTE:</span>
<span class="field-value">${formData.cliente}</span>
</div>
<div class="field">
<span class="field-label">CPF:</span>
<span class="field-value">${formData.cpf}</span>
</div>
</div>
<div class="field-row">
<div class="field">
<span class="field-label">APARELHO:</span>
<span class="field-value">${formData.aparelho}</span>
</div>
<div class="field">
<span class="field-label">IMEI:</span>
<span class="field-value">${formData.imei}</span>
</div>
<div class="field">
<span class="field-label">VALOR:</span>
<span class="field-value">${formData.valor}</span>
</div>
</div>
<div class="field-row">
<div class="field">
<span class="field-label">CONSULTOR:</span>
<span class="field-value">${formData.consultor}</span>
</div>
<div class="field">
<span class="field-label">VENDA:</span>
<span class="field-value">${formData.venda}</span>
</div>
</div>
<div class="section">
<div class="section-title">VALOR DO APARELHO E PEÇAS RELATÓRIO INTERNO</div>
<div class="parts-grid">
${parts.map((p, i) => `
<div class="part-box">
<div><strong>Peça ${i + 1}:</strong> ${p.peca}</div>
<div><strong>Valor:</strong> ${p.valor}</div>
</div>
`).join("")}
</div>
</div>
<div class="term">
<strong>TERMO DE TRANSFERÊNCIA DE PROPRIEDADE DO APARELHO (CONTINGÊNCIA)</strong><br><br>
Na condição de proprietário do aparelho acima descrito, declaro, por livre e espontânea vontade, a boa procedência do equipamento, transferindo neste ato sua propriedade à SUPERSTORE. Declaro que o aparelho não contém dados pessoais ou de terceiros. Autorizo expressamente que, caso sejam encontrados quaisquer dados no dispositivo, seja realizada a remoção e destruição definitiva das informações, sem possibilidade de recuperação. Reconheço que esta decisão é irrevogável e assumo total responsabilidade por ela.
</div>
<table>
<thead>
<tr>
<th>Descrição</th>
<th class="check-cell">Sim</th>
<th class="check-cell">Não</th>
<th class="obs-cell">Observações</th>
</tr>
</thead>
<tbody>
${checklist.map(item => `
<tr>
<td>${item.description}</td>
<td class="check-cell">${item.value === "sim" ? "✓" : ""}</td>
<td class="check-cell">${item.value === "nao" ? "✓" : ""}</td>
<td class="obs-cell">${item.observation}</td>
</tr>
`).join("")}
<tr>
<td><strong>Saúde da Bateria</strong></td>
<td colspan="3">${formData.saudeBateria}%</td>
</tr>
</tbody>
</table>
<div class="declarations">
<div class="section-title">DECLARAÇÕES DO CLIENTE</div>
<div class="declaration-item">
Declaro que removi todas as minhas informações pessoais do dispositivo antes da entrega:
<strong>( ${declarations.removeuDados ? "X" : " "} ) Sim ( ${!declarations.removeuDados ? "X" : " "} ) Não</strong>
</div>
<div class="declaration-item">
Declaro que estou transferindo a propriedade do meu aparelho:
<strong>( ${declarations.transferePropriedade ? "X" : " "} ) Sim ( ${!declarations.transferePropriedade ? "X" : " "} ) Não</strong>
</div>
</div>
<div class="signatures">
<div class="signature-box">
${employeeSignature ? `<img src="${employeeSignature}" class="signature-image" />` : ""}
<div class="signature-line">
<strong>Assinatura do Vendedor</strong><br>
${formData.consultor}
</div>
</div>
<div class="signature-box">
${customerSignature ? `<img src="${customerSignature}" class="signature-image" />` : ""}
<div class="signature-line">
<strong>Assinatura do Cliente</strong><br>
${formData.cliente}<br>
CPF: ${formData.cpf}
</div>
</div>
</div>
<script>
window.onload = function() { window.print(); }
</script>
</body>
</html>
`);
printWindow.document.close();
};
const handleSave = async () => {
if (!formData.cliente || !formData.imei || !formData.aparelho) {
toast({ title: "Preencha os campos obrigatórios", variant: "destructive" });
return;
}
try {
const res = await fetch("/api/retail/evaluations", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
imei: formData.imei,
brand: formData.aparelho.split(" ")[0],
model: formData.aparelho,
customerName: formData.cliente,
customerCpf: formData.cpf,
estimatedValue: formData.valor.replace(/[^\d,]/g, "").replace(",", "."),
batteryHealth: parseInt(formData.saudeBateria) || null,
status: "pending",
notes: JSON.stringify({
senha: formData.senha,
consultor: formData.consultor,
venda: formData.venda,
parts,
checklist,
declarations,
}),
}),
});
if (res.ok) {
const evaluation = await res.json();
if (customerSignature) {
await fetch("/api/retail/transfer-documents", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
evaluationId: evaluation.id,
customerName: formData.cliente,
customerCpf: formData.cpf,
deviceBrand: formData.aparelho.split(" ")[0],
deviceModel: formData.aparelho,
deviceImei: formData.imei,
agreedValue: formData.valor.replace(/[^\d,]/g, "").replace(",", ".") || "0",
customerSignature,
employeeSignature,
employeeName: formData.consultor,
termsAccepted: declarations.transferePropriedade,
}),
});
}
toast({ title: "Avaliação salva com sucesso!" });
onSave?.(evaluation);
onClose();
}
} catch (error) {
toast({ title: "Erro ao salvar avaliação", variant: "destructive" });
}
};
return (
<div className="fixed inset-0 z-50 bg-background overflow-auto">
<div className="max-w-5xl mx-auto p-6" ref={printRef}>
<div className="flex items-center justify-between mb-6 print:hidden">
<h1 className="text-2xl font-bold">Checklist de Avaliação - Trade-In</h1>
<div className="flex gap-2">
<Button variant="outline" onClick={() => setShowEvaluationPicker(true)} data-testid="btn-load-evaluation">
<FileText className="h-4 w-4 mr-2" />
Carregar Avaliação
</Button>
<Button variant="outline" onClick={handlePrint}>
<Printer className="h-4 w-4 mr-2" />
Imprimir
</Button>
<Button onClick={handleSave}>
<Save className="h-4 w-4 mr-2" />
Salvar
</Button>
<Button variant="ghost" onClick={onClose}>
<X className="h-4 w-4" />
</Button>
</div>
</div>
{showEvaluationPicker && (
<Card className="mb-6 border-blue-500 border-2">
<CardHeader className="pb-2 bg-blue-50 dark:bg-blue-950">
<div className="flex items-center justify-between">
<CardTitle className="text-lg flex items-center gap-2">
<FileText className="h-5 w-5" />
Selecionar Avaliação Existente
</CardTitle>
<Button variant="ghost" size="sm" onClick={() => setShowEvaluationPicker(false)}>
<X className="h-4 w-4" />
</Button>
</div>
</CardHeader>
<CardContent className="pt-4">
{loadingEvaluations ? (
<p className="text-center text-muted-foreground py-4">Carregando avaliações...</p>
) : availableEvaluations.length === 0 ? (
<p className="text-center text-muted-foreground py-4">Nenhuma avaliação pendente ou aprovada encontrada.</p>
) : (
<div className="grid gap-2 max-h-60 overflow-y-auto">
{availableEvaluations.map((evaluation) => (
<div
key={evaluation.id}
className="p-3 border rounded-lg hover:bg-accent cursor-pointer flex items-center justify-between"
onClick={() => loadEvaluationData(evaluation)}
data-testid={`evaluation-item-${evaluation.id}`}
>
<div>
<p className="font-medium">{evaluation.brand} {evaluation.model}</p>
<p className="text-sm text-muted-foreground">IMEI: {evaluation.imei}</p>
<p className="text-sm text-muted-foreground">Cliente: {evaluation.customerName || "Não informado"}</p>
</div>
<div className="text-right">
<p className="font-bold text-green-600">
R$ {parseFloat(evaluation.estimatedValue || 0).toLocaleString("pt-BR", { minimumFractionDigits: 2 })}
</p>
<span className={`text-xs px-2 py-0.5 rounded-full ${
evaluation.status === "approved" ? "bg-green-100 text-green-700" : "bg-yellow-100 text-yellow-700"
}`}>
{evaluation.status === "approved" ? "Aprovado" : "Pendente"}
</span>
</div>
</div>
))}
</div>
)}
</CardContent>
</Card>
)}
<Card className="mb-6">
<CardHeader className="pb-4">
<CardTitle className="text-lg">Dados Gerais</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
<div>
<Label>Data</Label>
<Input
value={formData.data}
onChange={(e) => setFormData({...formData, data: e.target.value})}
/>
</div>
<div>
<Label>Senha</Label>
<Input
value={formData.senha}
onChange={(e) => setFormData({...formData, senha: e.target.value})}
placeholder="Senha do atendimento"
/>
</div>
<div>
<Label>Consultor</Label>
<Input
value={formData.consultor}
onChange={(e) => setFormData({...formData, consultor: e.target.value})}
placeholder="Nome do vendedor"
/>
</div>
<div>
<Label>Venda</Label>
<Input
value={formData.venda}
onChange={(e) => setFormData({...formData, venda: e.target.value})}
placeholder="Nº da venda"
/>
</div>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div ref={personSearchRef} className="relative">
<Label>Cliente *</Label>
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
value={formData.cliente}
onChange={(e) => {
setFormData({...formData, cliente: e.target.value});
if (selectedPersonId) setSelectedPersonId(null);
}}
placeholder="Digite para buscar cliente..."
className="pl-9"
/>
</div>
{showPersonDropdown && (
<div className="absolute z-50 w-full mt-1 bg-background border rounded-md shadow-lg max-h-48 overflow-y-auto">
{filteredPersons.map((person) => (
<div
key={person.id}
className="px-3 py-2 hover:bg-accent cursor-pointer flex items-center gap-2"
onClick={() => selectPerson(person)}
>
<User className="h-4 w-4 text-muted-foreground" />
<div>
<div className="font-medium">{person.fullName}</div>
<div className="text-xs text-muted-foreground">{person.cpfCnpj}</div>
</div>
</div>
))}
</div>
)}
</div>
<div>
<Label>CPF</Label>
<Input
value={formData.cpf}
onChange={(e) => setFormData({...formData, cpf: e.target.value})}
placeholder="000.000.000-00"
readOnly={!!selectedPersonId}
/>
</div>
</div>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<div>
<Label>Aparelho *</Label>
<Input
value={formData.aparelho}
onChange={(e) => setFormData({...formData, aparelho: e.target.value})}
placeholder="iPhone 13 Pro Max 256GB"
/>
</div>
<div>
<Label>IMEI *</Label>
<Input
value={formData.imei}
onChange={(e) => setFormData({...formData, imei: e.target.value})}
placeholder="000000000000000"
/>
</div>
<div>
<Label>Valor</Label>
<Input
value={formData.valor}
onChange={(e) => setFormData({...formData, valor: e.target.value})}
placeholder="R$ 2.500,00"
/>
</div>
</div>
</CardContent>
</Card>
<Card className="mb-6">
<CardHeader className="pb-4">
<CardTitle className="text-lg">Valor do Aparelho e Peças Relatório Interno</CardTitle>
</CardHeader>
<CardContent>
<div className="grid grid-cols-2 md:grid-cols-5 gap-4">
{parts.map((part, idx) => (
<div key={idx} className="space-y-2 p-3 border rounded-lg">
<div>
<Label className="text-xs">Peça {idx + 1}</Label>
<Input
value={part.peca}
onChange={(e) => updatePart(idx, "peca", e.target.value)}
placeholder="Nome da peça"
className="h-8 text-sm"
/>
</div>
<div>
<Label className="text-xs">Valor</Label>
<Input
value={part.valor}
onChange={(e) => updatePart(idx, "valor", e.target.value)}
placeholder="R$ 0,00"
className="h-8 text-sm"
/>
</div>
</div>
))}
</div>
</CardContent>
</Card>
<Card className="mb-6">
<CardHeader className="pb-4 bg-muted/50">
<CardTitle className="text-sm font-normal">
<strong>TERMO DE TRANSFERÊNCIA DE PROPRIEDADE DO APARELHO (CONTINGÊNCIA)</strong>
</CardTitle>
</CardHeader>
<CardContent className="pt-4">
<p className="text-sm text-muted-foreground text-justify">
Na condição de proprietário do aparelho acima descrito, declaro, por livre e espontânea vontade,
a boa procedência do equipamento, transferindo neste ato sua propriedade à SUPERSTORE.
Declaro que o aparelho não contém dados pessoais ou de terceiros.
Autorizo expressamente que, caso sejam encontrados quaisquer dados no dispositivo,
seja realizada a remoção e destruição definitiva das informações, sem possibilidade de recuperação.
Reconheço que esta decisão é irrevogável e assumo total responsabilidade por ela.
</p>
</CardContent>
</Card>
<Card className="mb-6">
<CardHeader className="pb-4">
<CardTitle className="text-lg">Checklist de Avaliação</CardTitle>
</CardHeader>
<CardContent>
<div className="border rounded-lg overflow-hidden">
<table className="w-full">
<thead className="bg-muted/50">
<tr>
<th className="text-left p-3 font-medium">Descrição</th>
<th className="w-16 text-center p-3 font-medium">Sim</th>
<th className="w-16 text-center p-3 font-medium">Não</th>
<th className="w-48 text-left p-3 font-medium">Observações</th>
</tr>
</thead>
<tbody>
{checklist.map((item) => (
<tr key={item.id} className="border-t">
<td className="p-3">{item.description}</td>
<td className="p-2 text-center">
<Checkbox
checked={item.value === "sim"}
onCheckedChange={() => updateChecklist(item.id, "value", item.value === "sim" ? "" : "sim")}
/>
</td>
<td className="p-2 text-center">
<Checkbox
checked={item.value === "nao"}
onCheckedChange={() => updateChecklist(item.id, "value", item.value === "nao" ? "" : "nao")}
/>
</td>
<td className="p-2">
<Input
value={item.observation}
onChange={(e) => updateChecklist(item.id, "observation", e.target.value)}
placeholder="Obs..."
className="h-8 text-sm"
/>
</td>
</tr>
))}
<tr className="border-t bg-muted/30">
<td className="p-3 font-medium">Saúde da Bateria</td>
<td colSpan={3} className="p-2">
<div className="flex items-center gap-2">
<Input
type="number"
min="0"
max="100"
value={formData.saudeBateria}
onChange={(e) => setFormData({...formData, saudeBateria: e.target.value})}
placeholder="85"
className="w-24 h-8"
/>
<span className="text-muted-foreground">%</span>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</CardContent>
</Card>
<Card className="mb-6">
<CardHeader className="pb-4">
<CardTitle className="text-lg">Declarações do Cliente</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex items-center gap-3 p-3 border rounded-lg">
<Checkbox
id="removeuDados"
checked={declarations.removeuDados}
onCheckedChange={(v) => setDeclarations({...declarations, removeuDados: v === true})}
/>
<Label htmlFor="removeuDados" className="flex-1 cursor-pointer">
Declaro que removi todas as minhas informações pessoais do dispositivo antes da entrega
</Label>
</div>
<div className="flex items-center gap-3 p-3 border rounded-lg">
<Checkbox
id="transferePropriedade"
checked={declarations.transferePropriedade}
onCheckedChange={(v) => setDeclarations({...declarations, transferePropriedade: v === true})}
/>
<Label htmlFor="transferePropriedade" className="flex-1 cursor-pointer">
Declaro que estou transferindo a propriedade do meu aparelho
</Label>
</div>
</CardContent>
</Card>
<Card className="mb-6">
<CardHeader className="pb-4">
<CardTitle className="text-lg">Assinaturas</CardTitle>
</CardHeader>
<CardContent>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div className="border rounded-lg p-4">
<h4 className="font-medium mb-3">Assinatura do Vendedor</h4>
{employeeSignature ? (
<div className="text-center">
<img src={employeeSignature} alt="Assinatura do Vendedor" className="max-h-24 mx-auto border rounded" />
<Button variant="outline" size="sm" onClick={() => setEmployeeSignature(null)} className="mt-2">
<RotateCcw className="h-4 w-4 mr-1" />
Refazer
</Button>
</div>
) : isSigningEmployee ? (
<div>
<canvas
ref={employeeCanvasRef}
width={350}
height={120}
className="border rounded bg-white cursor-crosshair w-full"
onMouseDown={(e) => startDrawing(e, employeeCanvasRef.current)}
onMouseMove={(e) => draw(e, employeeCanvasRef.current)}
onMouseUp={stopDrawing}
onMouseLeave={stopDrawing}
onTouchStart={(e) => startDrawing(e, employeeCanvasRef.current)}
onTouchMove={(e) => draw(e, employeeCanvasRef.current)}
onTouchEnd={stopDrawing}
/>
<div className="flex gap-2 mt-2">
<Button size="sm" variant="outline" onClick={() => clearSignature(false)}>
<RotateCcw className="h-4 w-4 mr-1" />
Limpar
</Button>
<Button size="sm" onClick={() => saveSignature(false)}>
Confirmar
</Button>
<Button size="sm" variant="ghost" onClick={() => setIsSigningEmployee(false)}>
Cancelar
</Button>
</div>
</div>
) : (
<Button variant="outline" onClick={() => setIsSigningEmployee(true)} className="w-full h-24">
<Pen className="h-5 w-5 mr-2" />
Clique para assinar
</Button>
)}
<p className="text-sm text-muted-foreground mt-2 text-center">{formData.consultor || "Nome do vendedor"}</p>
</div>
<div className="border rounded-lg p-4">
<h4 className="font-medium mb-3">Assinatura do Cliente</h4>
{customerSignature ? (
<div className="text-center">
<img src={customerSignature} alt="Assinatura do Cliente" className="max-h-24 mx-auto border rounded" />
<Button variant="outline" size="sm" onClick={() => setCustomerSignature(null)} className="mt-2">
<RotateCcw className="h-4 w-4 mr-1" />
Refazer
</Button>
</div>
) : isSigningCustomer ? (
<div>
<canvas
ref={canvasRef}
width={350}
height={120}
className="border rounded bg-white cursor-crosshair w-full"
onMouseDown={(e) => startDrawing(e, canvasRef.current)}
onMouseMove={(e) => draw(e, canvasRef.current)}
onMouseUp={stopDrawing}
onMouseLeave={stopDrawing}
onTouchStart={(e) => startDrawing(e, canvasRef.current)}
onTouchMove={(e) => draw(e, canvasRef.current)}
onTouchEnd={stopDrawing}
/>
<div className="flex gap-2 mt-2">
<Button size="sm" variant="outline" onClick={() => clearSignature(true)}>
<RotateCcw className="h-4 w-4 mr-1" />
Limpar
</Button>
<Button size="sm" onClick={() => saveSignature(true)}>
Confirmar
</Button>
<Button size="sm" variant="ghost" onClick={() => setIsSigningCustomer(false)}>
Cancelar
</Button>
</div>
</div>
) : (
<Button variant="outline" onClick={() => setIsSigningCustomer(true)} className="w-full h-24">
<Pen className="h-5 w-5 mr-2" />
Clique para assinar
</Button>
)}
<p className="text-sm text-muted-foreground mt-2 text-center">
{formData.cliente || "Nome do cliente"}<br />
CPF: {formData.cpf || "___.___.___-__"}
</p>
</div>
</div>
</CardContent>
</Card>
<div className="flex justify-end gap-4 print:hidden">
<Button variant="outline" onClick={onClose}>
Cancelar
</Button>
<Button variant="outline" onClick={handlePrint}>
<Printer className="h-4 w-4 mr-2" />
Imprimir
</Button>
<Button onClick={handleSave}>
<Save className="h-4 w-4 mr-2" />
Salvar Avaliação
</Button>
</div>
</div>
</div>
);
}

View File

@ -0,0 +1,39 @@
import React from 'react';
interface UserAvatarProps {
name: string;
size?: number;
}
const UserAvatar: React.FC<UserAvatarProps> = ({ name, size = 40 }) => {
const initials = name.split(' ').map((n) => n[0]).join('').toUpperCase();
const generateColor = (name: string) => {
const hash = Array.from(name).reduce((acc, char) => acc + char.charCodeAt(0), 0);
const colors = ['#FF5733', '#33FF57', '#3357FF', '#FF33A1', '#FFBD33'];
return colors[hash % colors.length];
};
const backgroundColor = generateColor(name);
return (
<div
data-testid="user-avatar"
style={{
width: size,
height: size,
borderRadius: '50%',
backgroundColor,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
color: '#fff',
fontSize: size / 2,
}}
>
{initials}
</div>
);
};
export default UserAvatar;

View File

@ -0,0 +1,267 @@
import { useState, useRef, useEffect } from "react";
import { useMutation } from "@tanstack/react-query";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Textarea } from "@/components/ui/textarea";
import {
Bot, Send, Sparkles, Database, Layout, GitBranch,
Code2, Loader2, CheckCircle, AlertCircle, Lightbulb,
Wand2, FileCode, Zap, ArrowRight
} from "lucide-react";
interface Message {
id: string;
role: "user" | "assistant";
content: string;
timestamp: Date;
action?: {
type: "create_doctype" | "create_page" | "create_workflow" | "generate_code";
status: "pending" | "executing" | "completed" | "failed";
result?: any;
};
}
const suggestions = [
{ icon: Database, text: "Criar um DocType para cadastro de clientes", category: "DocType" },
{ icon: Layout, text: "Criar uma página de listagem com filtros", category: "Página" },
{ icon: GitBranch, text: "Criar workflow de aprovação de documentos", category: "Workflow" },
{ icon: Code2, text: "Gerar script de validação de campos", category: "Script" },
{ icon: Zap, text: "Criar dashboard com KPIs de vendas", category: "Dashboard" },
];
export default function DevAgent() {
const [messages, setMessages] = useState<Message[]>([
{
id: "welcome",
role: "assistant",
content: "Olá! Sou o Dev Agent, seu assistente de desenvolvimento. Posso ajudar você a:\n\n• Criar DocTypes (entidades de dados)\n• Montar Páginas visuais\n• Configurar Workflows de automação\n• Gerar Scripts personalizados\n• Construir Dashboards e Relatórios\n\nO que você gostaria de criar hoje?",
timestamp: new Date()
}
]);
const [input, setInput] = useState("");
const [isTyping, setIsTyping] = useState(false);
const scrollRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (scrollRef.current) {
scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
}
}, [messages]);
const sendMessage = useMutation({
mutationFn: async (userMessage: string) => {
const res = await fetch("/api/dev-agent/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
message: userMessage,
context: "development",
history: messages.slice(-10).map(m => ({ role: m.role, content: m.content }))
})
});
if (!res.ok) throw new Error("Failed to send message");
return res.json();
},
onSuccess: (data) => {
const assistantMessage: Message = {
id: `msg_${Date.now()}`,
role: "assistant",
content: data.response,
timestamp: new Date(),
action: data.action
};
setMessages(prev => [...prev, assistantMessage]);
setIsTyping(false);
},
onError: () => {
const errorMessage: Message = {
id: `msg_${Date.now()}`,
role: "assistant",
content: "Desculpe, ocorreu um erro ao processar sua solicitação. Tente novamente.",
timestamp: new Date()
};
setMessages(prev => [...prev, errorMessage]);
setIsTyping(false);
}
});
const handleSend = () => {
if (!input.trim()) return;
const userMessage: Message = {
id: `msg_${Date.now()}`,
role: "user",
content: input,
timestamp: new Date()
};
setMessages(prev => [...prev, userMessage]);
setInput("");
setIsTyping(true);
sendMessage.mutate(input);
};
const handleSuggestion = (text: string) => {
setInput(text);
};
const renderMessage = (message: Message) => {
const isUser = message.role === "user";
return (
<div
key={message.id}
className={`flex ${isUser ? "justify-end" : "justify-start"} mb-4`}
>
<div className={`flex items-start gap-3 max-w-[80%] ${isUser ? "flex-row-reverse" : ""}`}>
<div className={`w-8 h-8 rounded-full flex items-center justify-center ${
isUser ? "bg-blue-600" : "bg-gradient-to-br from-violet-500 to-purple-600"
}`}>
{isUser ? (
<span className="text-white text-sm font-medium">U</span>
) : (
<Bot className="w-4 h-4 text-white" />
)}
</div>
<div className={`rounded-2xl px-4 py-3 ${
isUser
? "bg-blue-600 text-white"
: "bg-white border shadow-sm"
}`}>
<p className="text-sm whitespace-pre-wrap">{message.content}</p>
{message.action && (
<div className={`mt-3 p-3 rounded-lg ${
message.action.status === "completed" ? "bg-green-50 border border-green-200" :
message.action.status === "failed" ? "bg-red-50 border border-red-200" :
"bg-blue-50 border border-blue-200"
}`}>
<div className="flex items-center gap-2">
{message.action.status === "executing" && (
<Loader2 className="w-4 h-4 animate-spin text-blue-600" />
)}
{message.action.status === "completed" && (
<CheckCircle className="w-4 h-4 text-green-600" />
)}
{message.action.status === "failed" && (
<AlertCircle className="w-4 h-4 text-red-600" />
)}
<span className="text-sm font-medium">
{message.action.type === "create_doctype" && "Criando DocType..."}
{message.action.type === "create_page" && "Criando Página..."}
{message.action.type === "create_workflow" && "Criando Workflow..."}
{message.action.type === "generate_code" && "Gerando código..."}
</span>
</div>
{message.action.result && (
<div className="mt-2 text-xs text-gray-600">
{JSON.stringify(message.action.result, null, 2)}
</div>
)}
</div>
)}
</div>
</div>
</div>
);
};
return (
<div className="h-full flex flex-col bg-gray-50">
<div className="bg-gradient-to-r from-violet-600 to-purple-600 text-white p-4">
<div className="flex items-center gap-3">
<div className="w-10 h-10 bg-white/20 rounded-full flex items-center justify-center">
<Wand2 className="w-5 h-5" />
</div>
<div>
<h2 className="font-semibold">Dev Agent</h2>
<p className="text-sm text-white/80">Assistente de desenvolvimento low-code</p>
</div>
<Badge variant="secondary" className="ml-auto bg-white/20 text-white hover:bg-white/30">
<Sparkles className="w-3 h-3 mr-1" />
AI Powered
</Badge>
</div>
</div>
<ScrollArea className="flex-1 p-4" ref={scrollRef}>
{messages.map(renderMessage)}
{isTyping && (
<div className="flex items-start gap-3 mb-4">
<div className="w-8 h-8 rounded-full bg-gradient-to-br from-violet-500 to-purple-600 flex items-center justify-center">
<Bot className="w-4 h-4 text-white" />
</div>
<div className="bg-white border shadow-sm rounded-2xl px-4 py-3">
<div className="flex items-center gap-1">
<div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: "0ms" }} />
<div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: "150ms" }} />
<div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: "300ms" }} />
</div>
</div>
</div>
)}
</ScrollArea>
{messages.length === 1 && (
<div className="px-4 pb-4">
<div className="flex items-center gap-2 mb-3">
<Lightbulb className="w-4 h-4 text-amber-500" />
<span className="text-sm font-medium text-gray-600">Sugestões para começar</span>
</div>
<div className="grid grid-cols-1 gap-2">
{suggestions.map((suggestion, idx) => (
<button
key={idx}
onClick={() => handleSuggestion(suggestion.text)}
className="flex items-center gap-3 p-3 bg-white border rounded-lg hover:bg-gray-50 hover:border-violet-300 transition-colors text-left group"
data-testid={`dev-suggestion-${idx}`}
>
<div className="p-2 bg-violet-100 rounded-lg group-hover:bg-violet-200 transition-colors">
<suggestion.icon className="w-4 h-4 text-violet-600" />
</div>
<div className="flex-1">
<p className="text-sm text-gray-700">{suggestion.text}</p>
</div>
<Badge variant="outline" className="text-xs">{suggestion.category}</Badge>
<ArrowRight className="w-4 h-4 text-gray-400 opacity-0 group-hover:opacity-100 transition-opacity" />
</button>
))}
</div>
</div>
)}
<div className="p-4 border-t bg-white">
<div className="flex gap-2">
<Input
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && !e.shiftKey && handleSend()}
placeholder="Descreva o que você quer criar..."
className="flex-1"
disabled={isTyping}
data-testid="dev-agent-input"
/>
<Button
onClick={handleSend}
disabled={!input.trim() || isTyping}
className="bg-violet-600 hover:bg-violet-700"
data-testid="dev-agent-send"
>
{isTyping ? (
<Loader2 className="w-4 h-4 animate-spin" />
) : (
<Send className="w-4 h-4" />
)}
</Button>
</div>
<p className="text-xs text-gray-400 mt-2 text-center">
O Dev Agent usa IA para criar componentes automaticamente
</p>
</div>
</div>
);
}

View File

@ -0,0 +1,316 @@
import { useState, useEffect } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Checkbox } from "@/components/ui/checkbox";
import { Calendar } from "@/components/ui/calendar";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Save, X, Calendar as CalendarIcon, Loader2 } from "lucide-react";
import { format } from "date-fns";
import { cn } from "@/lib/utils";
import { apiRequest } from "@/lib/queryClient";
interface Field {
id: number;
field_name: string;
label: string;
field_type: string;
options?: string;
default_value?: string;
mandatory: boolean;
read_only: boolean;
hidden: boolean;
placeholder?: string;
help_text?: string;
section?: string;
}
interface DynamicFormProps {
docTypeName: string;
initialData?: Record<string, any>;
onSubmit?: (data: Record<string, any>) => void;
onCancel?: () => void;
readOnly?: boolean;
}
export function DynamicForm({ docTypeName, initialData, onSubmit, onCancel, readOnly = false }: DynamicFormProps) {
const [formData, setFormData] = useState<Record<string, any>>(initialData || {});
const queryClient = useQueryClient();
const { data: schema, isLoading } = useQuery({
queryKey: ["/api/lowcode/doctypes", docTypeName, "schema"],
queryFn: async () => {
const res = await fetch(`/api/lowcode/doctypes/${docTypeName}/schema`);
if (!res.ok) throw new Error("Failed to fetch schema");
return res.json();
}
});
useEffect(() => {
if (schema?.fields && !initialData) {
const defaults: Record<string, any> = {};
schema.fields.forEach((field: Field) => {
if (field.default_value) {
defaults[field.field_name] = field.default_value;
}
});
setFormData(defaults);
}
}, [schema, initialData]);
const handleChange = (fieldName: string, value: any) => {
setFormData(prev => ({ ...prev, [fieldName]: value }));
};
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
onSubmit?.(formData);
};
const renderField = (field: Field) => {
if (field.hidden) return null;
const value = formData[field.field_name] ?? "";
const isDisabled = readOnly || field.read_only;
switch (field.field_type) {
case "text":
case "data":
return (
<Input
data-testid={`input-${field.field_name}`}
value={value}
onChange={(e) => handleChange(field.field_name, e.target.value)}
placeholder={field.placeholder}
disabled={isDisabled}
required={field.mandatory}
/>
);
case "number":
case "int":
case "float":
case "currency":
return (
<Input
data-testid={`input-${field.field_name}`}
type="number"
value={value}
onChange={(e) => handleChange(field.field_name, parseFloat(e.target.value) || 0)}
placeholder={field.placeholder}
disabled={isDisabled}
required={field.mandatory}
/>
);
case "textarea":
case "long_text":
case "text_editor":
return (
<Textarea
data-testid={`textarea-${field.field_name}`}
value={value}
onChange={(e) => handleChange(field.field_name, e.target.value)}
placeholder={field.placeholder}
disabled={isDisabled}
required={field.mandatory}
rows={4}
/>
);
case "select":
const options = field.options?.split("\n").filter(Boolean) || [];
return (
<Select
value={value}
onValueChange={(val) => handleChange(field.field_name, val)}
disabled={isDisabled}
>
<SelectTrigger data-testid={`select-${field.field_name}`}>
<SelectValue placeholder={field.placeholder || "Selecione..."} />
</SelectTrigger>
<SelectContent>
{options.map((opt) => (
<SelectItem key={opt} value={opt}>{opt}</SelectItem>
))}
</SelectContent>
</Select>
);
case "check":
case "boolean":
return (
<div className="flex items-center gap-2">
<Checkbox
data-testid={`checkbox-${field.field_name}`}
checked={value === true || value === "1" || value === 1}
onCheckedChange={(checked) => handleChange(field.field_name, checked)}
disabled={isDisabled}
/>
<span className="text-sm text-muted-foreground">{field.help_text || "Sim"}</span>
</div>
);
case "date":
return (
<Popover>
<PopoverTrigger asChild>
<Button
data-testid={`date-${field.field_name}`}
variant="outline"
disabled={isDisabled}
className={cn("w-full justify-start text-left font-normal", !value && "text-muted-foreground")}
>
<CalendarIcon className="mr-2 h-4 w-4" />
{value ? format(new Date(value), "dd/MM/yyyy") : "Selecione data..."}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0">
<Calendar
mode="single"
selected={value ? new Date(value) : undefined}
onSelect={(date) => handleChange(field.field_name, date?.toISOString().split("T")[0])}
/>
</PopoverContent>
</Popover>
);
case "datetime":
return (
<Input
data-testid={`datetime-${field.field_name}`}
type="datetime-local"
value={value}
onChange={(e) => handleChange(field.field_name, e.target.value)}
disabled={isDisabled}
required={field.mandatory}
/>
);
case "email":
return (
<Input
data-testid={`input-${field.field_name}`}
type="email"
value={value}
onChange={(e) => handleChange(field.field_name, e.target.value)}
placeholder={field.placeholder || "email@exemplo.com"}
disabled={isDisabled}
required={field.mandatory}
/>
);
case "phone":
return (
<Input
data-testid={`input-${field.field_name}`}
type="tel"
value={value}
onChange={(e) => handleChange(field.field_name, e.target.value)}
placeholder={field.placeholder || "(00) 00000-0000"}
disabled={isDisabled}
required={field.mandatory}
/>
);
default:
return (
<Input
data-testid={`input-${field.field_name}`}
value={value}
onChange={(e) => handleChange(field.field_name, e.target.value)}
placeholder={field.placeholder}
disabled={isDisabled}
required={field.mandatory}
/>
);
}
};
if (isLoading) {
return (
<div className="flex items-center justify-center p-8">
<Loader2 className="h-8 w-8 animate-spin text-blue-500" />
</div>
);
}
if (!schema) {
return (
<div className="p-4 text-center text-muted-foreground">
DocType não encontrado
</div>
);
}
const fields = schema.fields as Field[];
const sections = Array.from(new Set(fields.map(f => f.section).filter(Boolean))) as string[];
const ungroupedFields = fields.filter(f => !f.section);
return (
<form onSubmit={handleSubmit} className="space-y-6">
<div className="flex items-center justify-between mb-4">
<h2 className="text-xl font-semibold">{schema.doctype.label}</h2>
{!readOnly && (
<div className="flex gap-2">
{onCancel && (
<Button type="button" variant="outline" onClick={onCancel} data-testid="button-cancel">
<X className="h-4 w-4 mr-2" />
Cancelar
</Button>
)}
<Button type="submit" data-testid="button-submit">
<Save className="h-4 w-4 mr-2" />
Salvar
</Button>
</div>
)}
</div>
{ungroupedFields.length > 0 && (
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{ungroupedFields.map((field) => (
<div key={field.id} className={field.field_type === "textarea" || field.field_type === "long_text" ? "col-span-2" : ""}>
<Label htmlFor={field.field_name} className="flex items-center gap-1">
{field.label}
{field.mandatory && <span className="text-red-500">*</span>}
</Label>
<div className="mt-1">{renderField(field)}</div>
{field.help_text && field.field_type !== "check" && (
<p className="text-xs text-muted-foreground mt-1">{field.help_text}</p>
)}
</div>
))}
</div>
)}
{sections.map((section) => (
<Card key={section}>
<CardHeader className="py-3">
<CardTitle className="text-sm font-medium">{section}</CardTitle>
</CardHeader>
<CardContent>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{fields.filter(f => f.section === section).map((field) => (
<div key={field.id} className={field.field_type === "textarea" || field.field_type === "long_text" ? "col-span-2" : ""}>
<Label htmlFor={field.field_name} className="flex items-center gap-1">
{field.label}
{field.mandatory && <span className="text-red-500">*</span>}
</Label>
<div className="mt-1">{renderField(field)}</div>
{field.help_text && field.field_type !== "check" && (
<p className="text-xs text-muted-foreground mt-1">{field.help_text}</p>
)}
</div>
))}
</div>
</CardContent>
</Card>
))}
</form>
);
}

View File

@ -0,0 +1,258 @@
import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { Plus, Search, Filter, Download, Upload, MoreVertical, Eye, Edit, Trash2, Loader2 } from "lucide-react";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import * as Icons from "lucide-react";
interface Field {
id: number;
field_name: string;
label: string;
field_type: string;
in_list_view: boolean;
in_filter: boolean;
}
interface DynamicListProps {
docTypeName: string;
data?: any[];
onNew?: () => void;
onView?: (item: any) => void;
onEdit?: (item: any) => void;
onDelete?: (item: any) => void;
customActions?: { label: string; icon: string; onClick: (item: any) => void }[];
}
export function DynamicList({
docTypeName,
data = [],
onNew,
onView,
onEdit,
onDelete,
customActions = []
}: DynamicListProps) {
const [search, setSearch] = useState("");
const [filters, setFilters] = useState<Record<string, string>>({});
const { data: schema, isLoading } = useQuery({
queryKey: ["/api/lowcode/doctypes", docTypeName, "schema"],
queryFn: async () => {
const res = await fetch(`/api/lowcode/doctypes/${docTypeName}/schema`);
if (!res.ok) throw new Error("Failed to fetch schema");
return res.json();
}
});
if (isLoading) {
return (
<div className="flex items-center justify-center p-8">
<Loader2 className="h-8 w-8 animate-spin text-blue-500" />
</div>
);
}
if (!schema) {
return (
<div className="p-4 text-center text-muted-foreground">
DocType não encontrado
</div>
);
}
const fields = (schema.fields as Field[]).filter(f => f.in_list_view);
const filterFields = (schema.fields as Field[]).filter(f => f.in_filter);
const IconComponent = (Icons as any)[schema.doctype.icon] || Icons.FileText;
const filteredData = data.filter(item => {
if (search) {
const searchLower = search.toLowerCase();
const matchesSearch = fields.some(field => {
const value = item[field.field_name];
return value && String(value).toLowerCase().includes(searchLower);
});
if (!matchesSearch) return false;
}
for (const [key, value] of Object.entries(filters)) {
if (value && item[key] !== value) return false;
}
return true;
});
const formatValue = (value: any, fieldType: string) => {
if (value === null || value === undefined) return "-";
switch (fieldType) {
case "date":
return new Date(value).toLocaleDateString("pt-BR");
case "datetime":
return new Date(value).toLocaleString("pt-BR");
case "currency":
return new Intl.NumberFormat("pt-BR", { style: "currency", currency: "BRL" }).format(value);
case "check":
case "boolean":
return value ? "Sim" : "Não";
default:
return String(value);
}
};
return (
<Card>
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<div className={`w-10 h-10 rounded-lg bg-${schema.doctype.color || "blue"}-100 flex items-center justify-center`}>
<IconComponent className={`h-5 w-5 text-${schema.doctype.color || "blue"}-600`} />
</div>
<div>
<CardTitle>{schema.doctype.label}</CardTitle>
{schema.doctype.description && (
<p className="text-sm text-muted-foreground">{schema.doctype.description}</p>
)}
</div>
</div>
<div className="flex items-center gap-2">
{schema.doctype.allow_import && (
<Button variant="outline" size="sm" data-testid="button-import">
<Upload className="h-4 w-4 mr-2" />
Importar
</Button>
)}
{schema.doctype.allow_export && (
<Button variant="outline" size="sm" data-testid="button-export">
<Download className="h-4 w-4 mr-2" />
Exportar
</Button>
)}
{onNew && (
<Button onClick={onNew} data-testid="button-new">
<Plus className="h-4 w-4 mr-2" />
Novo
</Button>
)}
</div>
</div>
</CardHeader>
<CardContent>
<div className="flex items-center gap-4 mb-4">
<div className="relative flex-1">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
data-testid="input-search"
placeholder="Buscar..."
value={search}
onChange={(e) => setSearch(e.target.value)}
className="pl-10"
/>
</div>
{filterFields.length > 0 && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" size="icon" data-testid="button-filter">
<Filter className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-56">
{filterFields.map((field) => (
<div key={field.id} className="p-2">
<label className="text-sm font-medium">{field.label}</label>
<Input
value={filters[field.field_name] || ""}
onChange={(e) => setFilters(prev => ({ ...prev, [field.field_name]: e.target.value }))}
placeholder={`Filtrar ${field.label}...`}
className="mt-1"
/>
</div>
))}
</DropdownMenuContent>
</DropdownMenu>
)}
</div>
<div className="border rounded-lg">
<Table>
<TableHeader>
<TableRow>
{fields.map((field) => (
<TableHead key={field.id}>{field.label}</TableHead>
))}
<TableHead className="w-[100px]">Ações</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{filteredData.length === 0 ? (
<TableRow>
<TableCell colSpan={fields.length + 1} className="text-center py-8 text-muted-foreground">
Nenhum registro encontrado
</TableCell>
</TableRow>
) : (
filteredData.map((item, index) => (
<TableRow key={item.id || index} data-testid={`row-${docTypeName}-${item.id || index}`}>
{fields.map((field) => (
<TableCell key={field.id}>
{formatValue(item[field.field_name], field.field_type)}
</TableCell>
))}
<TableCell>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon" data-testid={`button-actions-${item.id || index}`}>
<MoreVertical className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{onView && (
<DropdownMenuItem onClick={() => onView(item)}>
<Eye className="h-4 w-4 mr-2" />
Visualizar
</DropdownMenuItem>
)}
{onEdit && (
<DropdownMenuItem onClick={() => onEdit(item)}>
<Edit className="h-4 w-4 mr-2" />
Editar
</DropdownMenuItem>
)}
{customActions.map((action, i) => {
const ActionIcon = (Icons as any)[action.icon] || Icons.Circle;
return (
<DropdownMenuItem key={i} onClick={() => action.onClick(item)}>
<ActionIcon className="h-4 w-4 mr-2" />
{action.label}
</DropdownMenuItem>
);
})}
{onDelete && (
<DropdownMenuItem onClick={() => onDelete(item)} className="text-red-600">
<Trash2 className="h-4 w-4 mr-2" />
Excluir
</DropdownMenuItem>
)}
</DropdownMenuContent>
</DropdownMenu>
</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
</div>
<div className="flex items-center justify-between mt-4 text-sm text-muted-foreground">
<span>{filteredData.length} registro(s)</span>
</div>
</CardContent>
</Card>
);
}

View File

@ -0,0 +1,2 @@
export { DynamicForm } from "./DynamicForm";
export { DynamicList } from "./DynamicList";

View File

@ -0,0 +1,55 @@
import * as React from "react"
import * as AccordionPrimitive from "@radix-ui/react-accordion"
import { ChevronDown } from "lucide-react"
import { cn } from "@/lib/utils"
const Accordion = AccordionPrimitive.Root
const AccordionItem = React.forwardRef<
React.ElementRef<typeof AccordionPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Item>
>(({ className, ...props }, ref) => (
<AccordionPrimitive.Item
ref={ref}
className={cn("border-b", className)}
{...props}
/>
))
AccordionItem.displayName = "AccordionItem"
const AccordionTrigger = React.forwardRef<
React.ElementRef<typeof AccordionPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
<AccordionPrimitive.Header className="flex">
<AccordionPrimitive.Trigger
ref={ref}
className={cn(
"flex flex-1 items-center justify-between py-4 text-sm font-medium transition-all hover:underline text-left [&[data-state=open]>svg]:rotate-180",
className
)}
{...props}
>
{children}
<ChevronDown className="h-4 w-4 shrink-0 text-muted-foreground transition-transform duration-200" />
</AccordionPrimitive.Trigger>
</AccordionPrimitive.Header>
))
AccordionTrigger.displayName = AccordionPrimitive.Trigger.displayName
const AccordionContent = React.forwardRef<
React.ElementRef<typeof AccordionPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<AccordionPrimitive.Content
ref={ref}
className="overflow-hidden text-sm data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down"
{...props}
>
<div className={cn("pb-4 pt-0", className)}>{children}</div>
</AccordionPrimitive.Content>
))
AccordionContent.displayName = AccordionPrimitive.Content.displayName
export { Accordion, AccordionItem, AccordionTrigger, AccordionContent }

View File

@ -0,0 +1,139 @@
import * as React from "react"
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog"
import { cn } from "@/lib/utils"
import { buttonVariants } from "@/components/ui/button"
const AlertDialog = AlertDialogPrimitive.Root
const AlertDialogTrigger = AlertDialogPrimitive.Trigger
const AlertDialogPortal = AlertDialogPrimitive.Portal
const AlertDialogOverlay = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Overlay
className={cn(
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className
)}
{...props}
ref={ref}
/>
))
AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName
const AlertDialogContent = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Content>
>(({ className, ...props }, ref) => (
<AlertDialogPortal>
<AlertDialogOverlay />
<AlertDialogPrimitive.Content
ref={ref}
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 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-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
className
)}
{...props}
/>
</AlertDialogPortal>
))
AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName
const AlertDialogHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col space-y-2 text-center sm:text-left",
className
)}
{...props}
/>
)
AlertDialogHeader.displayName = "AlertDialogHeader"
const AlertDialogFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
className
)}
{...props}
/>
)
AlertDialogFooter.displayName = "AlertDialogFooter"
const AlertDialogTitle = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Title
ref={ref}
className={cn("text-lg font-semibold", className)}
{...props}
/>
))
AlertDialogTitle.displayName = AlertDialogPrimitive.Title.displayName
const AlertDialogDescription = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Description
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
AlertDialogDescription.displayName =
AlertDialogPrimitive.Description.displayName
const AlertDialogAction = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Action>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Action>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Action
ref={ref}
className={cn(buttonVariants(), className)}
{...props}
/>
))
AlertDialogAction.displayName = AlertDialogPrimitive.Action.displayName
const AlertDialogCancel = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Cancel>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Cancel>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Cancel
ref={ref}
className={cn(
buttonVariants({ variant: "outline" }),
"mt-2 sm:mt-0",
className
)}
{...props}
/>
))
AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName
export {
AlertDialog,
AlertDialogPortal,
AlertDialogOverlay,
AlertDialogTrigger,
AlertDialogContent,
AlertDialogHeader,
AlertDialogFooter,
AlertDialogTitle,
AlertDialogDescription,
AlertDialogAction,
AlertDialogCancel,
}

View File

@ -0,0 +1,59 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const alertVariants = cva(
"relative w-full rounded-lg border px-4 py-3 text-sm [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground [&>svg~*]:pl-7",
{
variants: {
variant: {
default: "bg-background text-foreground",
destructive:
"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive",
},
},
defaultVariants: {
variant: "default",
},
}
)
const Alert = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement> & VariantProps<typeof alertVariants>
>(({ className, variant, ...props }, ref) => (
<div
ref={ref}
role="alert"
className={cn(alertVariants({ variant }), className)}
{...props}
/>
))
Alert.displayName = "Alert"
const AlertTitle = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLHeadingElement>
>(({ className, ...props }, ref) => (
<h5
ref={ref}
className={cn("mb-1 font-medium leading-none tracking-tight", className)}
{...props}
/>
))
AlertTitle.displayName = "AlertTitle"
const AlertDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("text-sm [&_p]:leading-relaxed", className)}
{...props}
/>
))
AlertDescription.displayName = "AlertDescription"
export { Alert, AlertTitle, AlertDescription }

View File

@ -0,0 +1,5 @@
import * as AspectRatioPrimitive from "@radix-ui/react-aspect-ratio"
const AspectRatio = AspectRatioPrimitive.Root
export { AspectRatio }

View File

@ -0,0 +1,50 @@
"use client"
import * as React from "react"
import * as AvatarPrimitive from "@radix-ui/react-avatar"
import { cn } from "@/lib/utils"
const Avatar = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Root>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Root
ref={ref}
className={cn(
"relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",
className
)}
{...props}
/>
))
Avatar.displayName = AvatarPrimitive.Root.displayName
const AvatarImage = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Image>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Image>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Image
ref={ref}
className={cn("aspect-square h-full w-full", className)}
{...props}
/>
))
AvatarImage.displayName = AvatarPrimitive.Image.displayName
const AvatarFallback = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Fallback>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Fallback>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Fallback
ref={ref}
className={cn(
"flex h-full w-full items-center justify-center rounded-full bg-muted",
className
)}
{...props}
/>
))
AvatarFallback.displayName = AvatarPrimitive.Fallback.displayName
export { Avatar, AvatarImage, AvatarFallback }

View File

@ -0,0 +1,43 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const badgeVariants = cva(
// @replit
// Whitespace-nowrap: Badges should never wrap.
"whitespace-nowrap inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2" +
" hover-elevate ",
{
variants: {
variant: {
default:
// @replit shadow-xs instead of shadow, no hover because we use hover-elevate
"border-transparent bg-primary text-primary-foreground shadow-xs",
secondary:
// @replit no hover because we use hover-elevate
"border-transparent bg-secondary text-secondary-foreground",
destructive:
// @replit shadow-xs instead of shadow, no hover because we use hover-elevate
"border-transparent bg-destructive text-destructive-foreground shadow-xs",
// @replit shadow-xs" - use badge outline variable
outline: "text-foreground border [border-color:var(--badge-outline)]",
},
},
defaultVariants: {
variant: "default",
},
}
)
export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>,
VariantProps<typeof badgeVariants> {}
function Badge({ className, variant, ...props }: BadgeProps) {
return (
<div className={cn(badgeVariants({ variant }), className)} {...props} />
)
}
export { Badge, badgeVariants }

View File

@ -0,0 +1,115 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { ChevronRight, MoreHorizontal } from "lucide-react"
import { cn } from "@/lib/utils"
const Breadcrumb = React.forwardRef<
HTMLElement,
React.ComponentPropsWithoutRef<"nav"> & {
separator?: React.ReactNode
}
>(({ ...props }, ref) => <nav ref={ref} aria-label="breadcrumb" {...props} />)
Breadcrumb.displayName = "Breadcrumb"
const BreadcrumbList = React.forwardRef<
HTMLOListElement,
React.ComponentPropsWithoutRef<"ol">
>(({ className, ...props }, ref) => (
<ol
ref={ref}
className={cn(
"flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",
className
)}
{...props}
/>
))
BreadcrumbList.displayName = "BreadcrumbList"
const BreadcrumbItem = React.forwardRef<
HTMLLIElement,
React.ComponentPropsWithoutRef<"li">
>(({ className, ...props }, ref) => (
<li
ref={ref}
className={cn("inline-flex items-center gap-1.5", className)}
{...props}
/>
))
BreadcrumbItem.displayName = "BreadcrumbItem"
const BreadcrumbLink = React.forwardRef<
HTMLAnchorElement,
React.ComponentPropsWithoutRef<"a"> & {
asChild?: boolean
}
>(({ asChild, className, ...props }, ref) => {
const Comp = asChild ? Slot : "a"
return (
<Comp
ref={ref}
className={cn("transition-colors hover:text-foreground", className)}
{...props}
/>
)
})
BreadcrumbLink.displayName = "BreadcrumbLink"
const BreadcrumbPage = React.forwardRef<
HTMLSpanElement,
React.ComponentPropsWithoutRef<"span">
>(({ className, ...props }, ref) => (
<span
ref={ref}
role="link"
aria-disabled="true"
aria-current="page"
className={cn("font-normal text-foreground", className)}
{...props}
/>
))
BreadcrumbPage.displayName = "BreadcrumbPage"
const BreadcrumbSeparator = ({
children,
className,
...props
}: React.ComponentProps<"li">) => (
<li
role="presentation"
aria-hidden="true"
className={cn("[&>svg]:w-3.5 [&>svg]:h-3.5", className)}
{...props}
>
{children ?? <ChevronRight />}
</li>
)
BreadcrumbSeparator.displayName = "BreadcrumbSeparator"
const BreadcrumbEllipsis = ({
className,
...props
}: React.ComponentProps<"span">) => (
<span
role="presentation"
aria-hidden="true"
className={cn("flex h-9 w-9 items-center justify-center", className)}
{...props}
>
<MoreHorizontal className="h-4 w-4" />
<span className="sr-only">More</span>
</span>
)
BreadcrumbEllipsis.displayName = "BreadcrumbElipssis"
export {
Breadcrumb,
BreadcrumbList,
BreadcrumbItem,
BreadcrumbLink,
BreadcrumbPage,
BreadcrumbSeparator,
BreadcrumbEllipsis,
}

View File

@ -0,0 +1,83 @@
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
import { Separator } from "@/components/ui/separator"
const buttonGroupVariants = cva(
"flex w-fit items-stretch has-[>[data-slot=button-group]]:gap-2 [&>*]:focus-visible:relative [&>*]:focus-visible:z-10 has-[select[aria-hidden=true]:last-child]:[&>[data-slot=select-trigger]:last-of-type]:rounded-r-md [&>[data-slot=select-trigger]:not([class*='w-'])]:w-fit [&>input]:flex-1",
{
variants: {
orientation: {
horizontal:
"[&>*:not(:first-child)]:rounded-l-none [&>*:not(:first-child)]:border-l-0 [&>*:not(:last-child)]:rounded-r-none",
vertical:
"flex-col [&>*:not(:first-child)]:rounded-t-none [&>*:not(:first-child)]:border-t-0 [&>*:not(:last-child)]:rounded-b-none",
},
},
defaultVariants: {
orientation: "horizontal",
},
}
)
function ButtonGroup({
className,
orientation,
...props
}: React.ComponentProps<"div"> & VariantProps<typeof buttonGroupVariants>) {
return (
<div
role="group"
data-slot="button-group"
data-orientation={orientation}
className={cn(buttonGroupVariants({ orientation }), className)}
{...props}
/>
)
}
function ButtonGroupText({
className,
asChild = false,
...props
}: React.ComponentProps<"div"> & {
asChild?: boolean
}) {
const Comp = asChild ? Slot : "div"
return (
<Comp
className={cn(
"bg-muted shadow-xs flex items-center gap-2 rounded-md border px-4 text-sm font-medium [&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none",
className
)}
{...props}
/>
)
}
function ButtonGroupSeparator({
className,
orientation = "vertical",
...props
}: React.ComponentProps<typeof Separator>) {
return (
<Separator
data-slot="button-group-separator"
orientation={orientation}
className={cn(
"bg-input relative !m-0 self-stretch data-[orientation=vertical]:h-auto",
className
)}
{...props}
/>
)
}
export {
ButtonGroup,
ButtonGroupSeparator,
ButtonGroupText,
buttonGroupVariants,
}

View File

@ -0,0 +1,65 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0" +
" hover-elevate active-elevate-2",
{
variants: {
variant: {
default:
// @replit: no hover, and add primary border
"bg-primary text-primary-foreground border border-primary-border",
destructive:
"bg-destructive text-destructive-foreground shadow-sm border-destructive-border",
outline:
// @replit Shows the background color of whatever card / sidebar / accent background it is inside of.
// Inherits the current text color. Uses shadow-xs. no shadow on active
// No hover state
" border [border-color:var(--button-outline)] shadow-xs active:shadow-none ",
secondary:
// @replit border, no hover, no shadow, secondary border.
"border bg-secondary text-secondary-foreground border border-secondary-border ",
// @replit no hover, transparent border
ghost: "border border-transparent",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
// @replit changed sizes
default: "min-h-9 px-4 py-2",
sm: "min-h-8 rounded-md px-3 text-xs",
lg: "min-h-10 rounded-md px-8",
icon: "h-9 w-9",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button"
return (
<Comp
className={cn(buttonVariants({ variant, size, className }))}
ref={ref}
{...props}
/>
)
}
)
Button.displayName = "Button"
export { Button, buttonVariants }

View File

@ -0,0 +1,213 @@
"use client"
import * as React from "react"
import {
ChevronDownIcon,
ChevronLeftIcon,
ChevronRightIcon,
} from "lucide-react"
import { DayButton, DayPicker, getDefaultClassNames } from "react-day-picker"
import { cn } from "@/lib/utils"
import { Button, buttonVariants } from "@/components/ui/button"
function Calendar({
className,
classNames,
showOutsideDays = true,
captionLayout = "label",
buttonVariant = "ghost",
formatters,
components,
...props
}: React.ComponentProps<typeof DayPicker> & {
buttonVariant?: React.ComponentProps<typeof Button>["variant"]
}) {
const defaultClassNames = getDefaultClassNames()
return (
<DayPicker
showOutsideDays={showOutsideDays}
className={cn(
"bg-background group/calendar p-3 [--cell-size:2rem] [[data-slot=card-content]_&]:bg-transparent [[data-slot=popover-content]_&]:bg-transparent",
String.raw`rtl:**:[.rdp-button\_next>svg]:rotate-180`,
String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`,
className
)}
captionLayout={captionLayout}
formatters={{
formatMonthDropdown: (date) =>
date.toLocaleString("default", { month: "short" }),
...formatters,
}}
classNames={{
root: cn("w-fit", defaultClassNames.root),
months: cn(
"relative flex flex-col gap-4 md:flex-row",
defaultClassNames.months
),
month: cn("flex w-full flex-col gap-4", defaultClassNames.month),
nav: cn(
"absolute inset-x-0 top-0 flex w-full items-center justify-between gap-1",
defaultClassNames.nav
),
button_previous: cn(
buttonVariants({ variant: buttonVariant }),
"h-[--cell-size] w-[--cell-size] select-none p-0 aria-disabled:opacity-50",
defaultClassNames.button_previous
),
button_next: cn(
buttonVariants({ variant: buttonVariant }),
"h-[--cell-size] w-[--cell-size] select-none p-0 aria-disabled:opacity-50",
defaultClassNames.button_next
),
month_caption: cn(
"flex h-[--cell-size] w-full items-center justify-center px-[--cell-size]",
defaultClassNames.month_caption
),
dropdowns: cn(
"flex h-[--cell-size] w-full items-center justify-center gap-1.5 text-sm font-medium",
defaultClassNames.dropdowns
),
dropdown_root: cn(
"has-focus:border-ring border-input shadow-xs has-focus:ring-ring/50 has-focus:ring-[3px] relative rounded-md border",
defaultClassNames.dropdown_root
),
dropdown: cn(
"bg-popover absolute inset-0 opacity-0",
defaultClassNames.dropdown
),
caption_label: cn(
"select-none font-medium",
captionLayout === "label"
? "text-sm"
: "[&>svg]:text-muted-foreground flex h-8 items-center gap-1 rounded-md pl-2 pr-1 text-sm [&>svg]:size-3.5",
defaultClassNames.caption_label
),
table: "w-full border-collapse",
weekdays: cn("flex", defaultClassNames.weekdays),
weekday: cn(
"text-muted-foreground flex-1 select-none rounded-md text-[0.8rem] font-normal",
defaultClassNames.weekday
),
week: cn("mt-2 flex w-full", defaultClassNames.week),
week_number_header: cn(
"w-[--cell-size] select-none",
defaultClassNames.week_number_header
),
week_number: cn(
"text-muted-foreground select-none text-[0.8rem]",
defaultClassNames.week_number
),
day: cn(
"group/day relative aspect-square h-full w-full select-none p-0 text-center [&:first-child[data-selected=true]_button]:rounded-l-md [&:last-child[data-selected=true]_button]:rounded-r-md",
defaultClassNames.day
),
range_start: cn(
"bg-accent rounded-l-md",
defaultClassNames.range_start
),
range_middle: cn("rounded-none", defaultClassNames.range_middle),
range_end: cn("bg-accent rounded-r-md", defaultClassNames.range_end),
today: cn(
"bg-accent text-accent-foreground rounded-md data-[selected=true]:rounded-none",
defaultClassNames.today
),
outside: cn(
"text-muted-foreground aria-selected:text-muted-foreground",
defaultClassNames.outside
),
disabled: cn(
"text-muted-foreground opacity-50",
defaultClassNames.disabled
),
hidden: cn("invisible", defaultClassNames.hidden),
...classNames,
}}
components={{
Root: ({ className, rootRef, ...props }) => {
return (
<div
data-slot="calendar"
ref={rootRef}
className={cn(className)}
{...props}
/>
)
},
Chevron: ({ className, orientation, ...props }) => {
if (orientation === "left") {
return (
<ChevronLeftIcon className={cn("size-4", className)} {...props} />
)
}
if (orientation === "right") {
return (
<ChevronRightIcon
className={cn("size-4", className)}
{...props}
/>
)
}
return (
<ChevronDownIcon className={cn("size-4", className)} {...props} />
)
},
DayButton: CalendarDayButton,
WeekNumber: ({ children, ...props }) => {
return (
<td {...props}>
<div className="flex size-[--cell-size] items-center justify-center text-center">
{children}
</div>
</td>
)
},
...components,
}}
{...props}
/>
)
}
function CalendarDayButton({
className,
day,
modifiers,
...props
}: React.ComponentProps<typeof DayButton>) {
const defaultClassNames = getDefaultClassNames()
const ref = React.useRef<HTMLButtonElement>(null)
React.useEffect(() => {
if (modifiers.focused) ref.current?.focus()
}, [modifiers.focused])
return (
<Button
ref={ref}
variant="ghost"
size="icon"
data-day={day.date.toLocaleDateString()}
data-selected-single={
modifiers.selected &&
!modifiers.range_start &&
!modifiers.range_end &&
!modifiers.range_middle
}
data-range-start={modifiers.range_start}
data-range-end={modifiers.range_end}
data-range-middle={modifiers.range_middle}
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 flex aspect-square h-auto w-full min-w-[--cell-size] flex-col gap-1 font-normal leading-none data-[range-end=true]:rounded-md data-[range-middle=true]:rounded-none data-[range-start=true]:rounded-md group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:ring-[3px] [&>span]:text-xs [&>span]:opacity-70",
defaultClassNames.day,
className
)}
{...props}
/>
)
}
export { Calendar, CalendarDayButton }

View File

@ -0,0 +1,76 @@
import * as React from "react"
import { cn } from "@/lib/utils"
const Card = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn(
"rounded-xl border bg-card text-card-foreground shadow",
className
)}
{...props}
/>
))
Card.displayName = "Card"
const CardHeader = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex flex-col space-y-1.5 p-6", className)}
{...props}
/>
))
CardHeader.displayName = "CardHeader"
const CardTitle = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("font-semibold leading-none tracking-tight", className)}
{...props}
/>
))
CardTitle.displayName = "CardTitle"
const CardDescription = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
CardDescription.displayName = "CardDescription"
const CardContent = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
))
CardContent.displayName = "CardContent"
const CardFooter = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex items-center p-6 pt-0", className)}
{...props}
/>
))
CardFooter.displayName = "CardFooter"
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent }

View File

@ -0,0 +1,260 @@
import * as React from "react"
import useEmblaCarousel, {
type UseEmblaCarouselType,
} from "embla-carousel-react"
import { ArrowLeft, ArrowRight } from "lucide-react"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
type CarouselApi = UseEmblaCarouselType[1]
type UseCarouselParameters = Parameters<typeof useEmblaCarousel>
type CarouselOptions = UseCarouselParameters[0]
type CarouselPlugin = UseCarouselParameters[1]
type CarouselProps = {
opts?: CarouselOptions
plugins?: CarouselPlugin
orientation?: "horizontal" | "vertical"
setApi?: (api: CarouselApi) => void
}
type CarouselContextProps = {
carouselRef: ReturnType<typeof useEmblaCarousel>[0]
api: ReturnType<typeof useEmblaCarousel>[1]
scrollPrev: () => void
scrollNext: () => void
canScrollPrev: boolean
canScrollNext: boolean
} & CarouselProps
const CarouselContext = React.createContext<CarouselContextProps | null>(null)
function useCarousel() {
const context = React.useContext(CarouselContext)
if (!context) {
throw new Error("useCarousel must be used within a <Carousel />")
}
return context
}
const Carousel = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement> & CarouselProps
>(
(
{
orientation = "horizontal",
opts,
setApi,
plugins,
className,
children,
...props
},
ref
) => {
const [carouselRef, api] = useEmblaCarousel(
{
...opts,
axis: orientation === "horizontal" ? "x" : "y",
},
plugins
)
const [canScrollPrev, setCanScrollPrev] = React.useState(false)
const [canScrollNext, setCanScrollNext] = React.useState(false)
const onSelect = React.useCallback((api: CarouselApi) => {
if (!api) {
return
}
setCanScrollPrev(api.canScrollPrev())
setCanScrollNext(api.canScrollNext())
}, [])
const scrollPrev = React.useCallback(() => {
api?.scrollPrev()
}, [api])
const scrollNext = React.useCallback(() => {
api?.scrollNext()
}, [api])
const handleKeyDown = React.useCallback(
(event: React.KeyboardEvent<HTMLDivElement>) => {
if (event.key === "ArrowLeft") {
event.preventDefault()
scrollPrev()
} else if (event.key === "ArrowRight") {
event.preventDefault()
scrollNext()
}
},
[scrollPrev, scrollNext]
)
React.useEffect(() => {
if (!api || !setApi) {
return
}
setApi(api)
}, [api, setApi])
React.useEffect(() => {
if (!api) {
return
}
onSelect(api)
api.on("reInit", onSelect)
api.on("select", onSelect)
return () => {
api?.off("select", onSelect)
}
}, [api, onSelect])
return (
<CarouselContext.Provider
value={{
carouselRef,
api: api,
opts,
orientation:
orientation || (opts?.axis === "y" ? "vertical" : "horizontal"),
scrollPrev,
scrollNext,
canScrollPrev,
canScrollNext,
}}
>
<div
ref={ref}
onKeyDownCapture={handleKeyDown}
className={cn("relative", className)}
role="region"
aria-roledescription="carousel"
{...props}
>
{children}
</div>
</CarouselContext.Provider>
)
}
)
Carousel.displayName = "Carousel"
const CarouselContent = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => {
const { carouselRef, orientation } = useCarousel()
return (
<div ref={carouselRef} className="overflow-hidden">
<div
ref={ref}
className={cn(
"flex",
orientation === "horizontal" ? "-ml-4" : "-mt-4 flex-col",
className
)}
{...props}
/>
</div>
)
})
CarouselContent.displayName = "CarouselContent"
const CarouselItem = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => {
const { orientation } = useCarousel()
return (
<div
ref={ref}
role="group"
aria-roledescription="slide"
className={cn(
"min-w-0 shrink-0 grow-0 basis-full",
orientation === "horizontal" ? "pl-4" : "pt-4",
className
)}
{...props}
/>
)
})
CarouselItem.displayName = "CarouselItem"
const CarouselPrevious = React.forwardRef<
HTMLButtonElement,
React.ComponentProps<typeof Button>
>(({ className, variant = "outline", size = "icon", ...props }, ref) => {
const { orientation, scrollPrev, canScrollPrev } = useCarousel()
return (
<Button
ref={ref}
variant={variant}
size={size}
className={cn(
"absolute h-8 w-8 rounded-full",
orientation === "horizontal"
? "-left-12 top-1/2 -translate-y-1/2"
: "-top-12 left-1/2 -translate-x-1/2 rotate-90",
className
)}
disabled={!canScrollPrev}
onClick={scrollPrev}
{...props}
>
<ArrowLeft className="h-4 w-4" />
<span className="sr-only">Previous slide</span>
</Button>
)
})
CarouselPrevious.displayName = "CarouselPrevious"
const CarouselNext = React.forwardRef<
HTMLButtonElement,
React.ComponentProps<typeof Button>
>(({ className, variant = "outline", size = "icon", ...props }, ref) => {
const { orientation, scrollNext, canScrollNext } = useCarousel()
return (
<Button
ref={ref}
variant={variant}
size={size}
className={cn(
"absolute h-8 w-8 rounded-full",
orientation === "horizontal"
? "-right-12 top-1/2 -translate-y-1/2"
: "-bottom-12 left-1/2 -translate-x-1/2 rotate-90",
className
)}
disabled={!canScrollNext}
onClick={scrollNext}
{...props}
>
<ArrowRight className="h-4 w-4" />
<span className="sr-only">Next slide</span>
</Button>
)
})
CarouselNext.displayName = "CarouselNext"
export {
type CarouselApi,
Carousel,
CarouselContent,
CarouselItem,
CarouselPrevious,
CarouselNext,
}

View File

@ -0,0 +1,367 @@
import * as React from "react"
import * as RechartsPrimitive from "recharts"
import { cn } from "@/lib/utils"
// Format: { THEME_NAME: CSS_SELECTOR }
const THEMES = { light: "", dark: ".dark" } as const
export type ChartConfig = {
[k in string]: {
label?: React.ReactNode
icon?: React.ComponentType
} & (
| { color?: string; theme?: never }
| { color?: never; theme: Record<keyof typeof THEMES, string> }
)
}
type ChartContextProps = {
config: ChartConfig
}
const ChartContext = React.createContext<ChartContextProps | null>(null)
function useChart() {
const context = React.useContext(ChartContext)
if (!context) {
throw new Error("useChart must be used within a <ChartContainer />")
}
return context
}
const ChartContainer = React.forwardRef<
HTMLDivElement,
React.ComponentProps<"div"> & {
config: ChartConfig
children: React.ComponentProps<
typeof RechartsPrimitive.ResponsiveContainer
>["children"]
}
>(({ id, className, children, config, ...props }, ref) => {
const uniqueId = React.useId()
const chartId = `chart-${id || uniqueId.replace(/:/g, "")}`
return (
<ChartContext.Provider value={{ config }}>
<div
data-chart={chartId}
ref={ref}
className={cn(
"flex aspect-video justify-center text-xs [&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-none [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-sector]:outline-none [&_.recharts-surface]:outline-none",
className
)}
{...props}
>
<ChartStyle id={chartId} config={config} />
<RechartsPrimitive.ResponsiveContainer>
{children}
</RechartsPrimitive.ResponsiveContainer>
</div>
</ChartContext.Provider>
)
})
ChartContainer.displayName = "Chart"
const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => {
const colorConfig = Object.entries(config).filter(
([, config]) => config.theme || config.color
)
if (!colorConfig.length) {
return null
}
return (
<style
dangerouslySetInnerHTML={{
__html: Object.entries(THEMES)
.map(
([theme, prefix]) => `
${prefix} [data-chart=${id}] {
${colorConfig
.map(([key, itemConfig]) => {
const color =
itemConfig.theme?.[theme as keyof typeof itemConfig.theme] ||
itemConfig.color
return color ? ` --color-${key}: ${color};` : null
})
.join("\n")}
}
`
)
.join("\n"),
}}
/>
)
}
const ChartTooltip = RechartsPrimitive.Tooltip
const ChartTooltipContent = React.forwardRef<
HTMLDivElement,
React.ComponentProps<typeof RechartsPrimitive.Tooltip> &
React.ComponentProps<"div"> & {
hideLabel?: boolean
hideIndicator?: boolean
indicator?: "line" | "dot" | "dashed"
nameKey?: string
labelKey?: string
}
>(
(
{
active,
payload,
className,
indicator = "dot",
hideLabel = false,
hideIndicator = false,
label,
labelFormatter,
labelClassName,
formatter,
color,
nameKey,
labelKey,
},
ref
) => {
const { config } = useChart()
const tooltipLabel = React.useMemo(() => {
if (hideLabel || !payload?.length) {
return null
}
const [item] = payload
const key = `${labelKey || item?.dataKey || item?.name || "value"}`
const itemConfig = getPayloadConfigFromPayload(config, item, key)
const value =
!labelKey && typeof label === "string"
? config[label as keyof typeof config]?.label || label
: itemConfig?.label
if (labelFormatter) {
return (
<div className={cn("font-medium", labelClassName)}>
{labelFormatter(value, payload)}
</div>
)
}
if (!value) {
return null
}
return <div className={cn("font-medium", labelClassName)}>{value}</div>
}, [
label,
labelFormatter,
payload,
hideLabel,
labelClassName,
config,
labelKey,
])
if (!active || !payload?.length) {
return null
}
const nestLabel = payload.length === 1 && indicator !== "dot"
return (
<div
ref={ref}
className={cn(
"grid min-w-[8rem] items-start gap-1.5 rounded-lg border border-border/50 bg-background px-2.5 py-1.5 text-xs shadow-xl",
className
)}
>
{!nestLabel ? tooltipLabel : null}
<div className="grid gap-1.5">
{payload
.filter((item) => item.type !== "none")
.map((item, index) => {
const key = `${nameKey || item.name || item.dataKey || "value"}`
const itemConfig = getPayloadConfigFromPayload(config, item, key)
const indicatorColor = color || item.payload.fill || item.color
return (
<div
key={item.dataKey}
className={cn(
"flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground",
indicator === "dot" && "items-center"
)}
>
{formatter && item?.value !== undefined && item.name ? (
formatter(item.value, item.name, item, index, item.payload)
) : (
<>
{itemConfig?.icon ? (
<itemConfig.icon />
) : (
!hideIndicator && (
<div
className={cn(
"shrink-0 rounded-[2px] border-[--color-border] bg-[--color-bg]",
{
"h-2.5 w-2.5": indicator === "dot",
"w-1": indicator === "line",
"w-0 border-[1.5px] border-dashed bg-transparent":
indicator === "dashed",
"my-0.5": nestLabel && indicator === "dashed",
}
)}
style={
{
"--color-bg": indicatorColor,
"--color-border": indicatorColor,
} as React.CSSProperties
}
/>
)
)}
<div
className={cn(
"flex flex-1 justify-between leading-none",
nestLabel ? "items-end" : "items-center"
)}
>
<div className="grid gap-1.5">
{nestLabel ? tooltipLabel : null}
<span className="text-muted-foreground">
{itemConfig?.label || item.name}
</span>
</div>
{item.value && (
<span className="font-mono font-medium tabular-nums text-foreground">
{item.value.toLocaleString()}
</span>
)}
</div>
</>
)}
</div>
)
})}
</div>
</div>
)
}
)
ChartTooltipContent.displayName = "ChartTooltip"
const ChartLegend = RechartsPrimitive.Legend
const ChartLegendContent = React.forwardRef<
HTMLDivElement,
React.ComponentProps<"div"> &
Pick<RechartsPrimitive.LegendProps, "payload" | "verticalAlign"> & {
hideIcon?: boolean
nameKey?: string
}
>(
(
{ className, hideIcon = false, payload, verticalAlign = "bottom", nameKey },
ref
) => {
const { config } = useChart()
if (!payload?.length) {
return null
}
return (
<div
ref={ref}
className={cn(
"flex items-center justify-center gap-4",
verticalAlign === "top" ? "pb-3" : "pt-3",
className
)}
>
{payload
.filter((item) => item.type !== "none")
.map((item) => {
const key = `${nameKey || item.dataKey || "value"}`
const itemConfig = getPayloadConfigFromPayload(config, item, key)
return (
<div
key={item.value}
className={cn(
"flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground"
)}
>
{itemConfig?.icon && !hideIcon ? (
<itemConfig.icon />
) : (
<div
className="h-2 w-2 shrink-0 rounded-[2px]"
style={{
backgroundColor: item.color,
}}
/>
)}
{itemConfig?.label}
</div>
)
})}
</div>
)
}
)
ChartLegendContent.displayName = "ChartLegend"
// Helper to extract item config from a payload.
function getPayloadConfigFromPayload(
config: ChartConfig,
payload: unknown,
key: string
) {
if (typeof payload !== "object" || payload === null) {
return undefined
}
const payloadPayload =
"payload" in payload &&
typeof payload.payload === "object" &&
payload.payload !== null
? payload.payload
: undefined
let configLabelKey: string = key
if (
key in payload &&
typeof payload[key as keyof typeof payload] === "string"
) {
configLabelKey = payload[key as keyof typeof payload] as string
} else if (
payloadPayload &&
key in payloadPayload &&
typeof payloadPayload[key as keyof typeof payloadPayload] === "string"
) {
configLabelKey = payloadPayload[
key as keyof typeof payloadPayload
] as string
}
return configLabelKey in config
? config[configLabelKey]
: config[key as keyof typeof config]
}
export {
ChartContainer,
ChartTooltip,
ChartTooltipContent,
ChartLegend,
ChartLegendContent,
ChartStyle,
}

View File

@ -0,0 +1,28 @@
import * as React from "react"
import * as CheckboxPrimitive from "@radix-ui/react-checkbox"
import { Check } from "lucide-react"
import { cn } from "@/lib/utils"
const Checkbox = React.forwardRef<
React.ElementRef<typeof CheckboxPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>
>(({ className, ...props }, ref) => (
<CheckboxPrimitive.Root
ref={ref}
className={cn(
"grid place-content-center peer h-4 w-4 shrink-0 rounded-sm border border-primary shadow focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",
className
)}
{...props}
>
<CheckboxPrimitive.Indicator
className={cn("grid place-content-center text-current")}
>
<Check className="h-4 w-4" />
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
))
Checkbox.displayName = CheckboxPrimitive.Root.displayName
export { Checkbox }

View File

@ -0,0 +1,11 @@
"use client"
import * as CollapsiblePrimitive from "@radix-ui/react-collapsible"
const Collapsible = CollapsiblePrimitive.Root
const CollapsibleTrigger = CollapsiblePrimitive.CollapsibleTrigger
const CollapsibleContent = CollapsiblePrimitive.CollapsibleContent
export { Collapsible, CollapsibleTrigger, CollapsibleContent }

View File

@ -0,0 +1,153 @@
"use client"
import * as React from "react"
import { type DialogProps } from "@radix-ui/react-dialog"
import { Command as CommandPrimitive } from "cmdk"
import { Search } from "lucide-react"
import { cn } from "@/lib/utils"
import { Dialog, DialogContent } from "@/components/ui/dialog"
const Command = React.forwardRef<
React.ElementRef<typeof CommandPrimitive>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive>
>(({ className, ...props }, ref) => (
<CommandPrimitive
ref={ref}
className={cn(
"flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",
className
)}
{...props}
/>
))
Command.displayName = CommandPrimitive.displayName
const CommandDialog = ({ children, ...props }: DialogProps) => {
return (
<Dialog {...props}>
<DialogContent className="overflow-hidden p-0">
<Command className="[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">
{children}
</Command>
</DialogContent>
</Dialog>
)
}
const CommandInput = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Input>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Input>
>(({ className, ...props }, ref) => (
<div className="flex items-center border-b px-3" cmdk-input-wrapper="">
<Search className="mr-2 h-4 w-4 shrink-0 opacity-50" />
<CommandPrimitive.Input
ref={ref}
className={cn(
"flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",
className
)}
{...props}
/>
</div>
))
CommandInput.displayName = CommandPrimitive.Input.displayName
const CommandList = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.List>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.List>
>(({ className, ...props }, ref) => (
<CommandPrimitive.List
ref={ref}
className={cn("max-h-[300px] overflow-y-auto overflow-x-hidden", className)}
{...props}
/>
))
CommandList.displayName = CommandPrimitive.List.displayName
const CommandEmpty = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Empty>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Empty>
>((props, ref) => (
<CommandPrimitive.Empty
ref={ref}
className="py-6 text-center text-sm"
{...props}
/>
))
CommandEmpty.displayName = CommandPrimitive.Empty.displayName
const CommandGroup = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Group>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Group>
>(({ className, ...props }, ref) => (
<CommandPrimitive.Group
ref={ref}
className={cn(
"overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",
className
)}
{...props}
/>
))
CommandGroup.displayName = CommandPrimitive.Group.displayName
const CommandSeparator = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Separator>
>(({ className, ...props }, ref) => (
<CommandPrimitive.Separator
ref={ref}
className={cn("-mx-1 h-px bg-border", className)}
{...props}
/>
))
CommandSeparator.displayName = CommandPrimitive.Separator.displayName
const CommandItem = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Item>
>(({ className, ...props }, ref) => (
<CommandPrimitive.Item
ref={ref}
className={cn(
"relative flex cursor-default gap-2 select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
className
)}
{...props}
/>
))
CommandItem.displayName = CommandPrimitive.Item.displayName
const CommandShortcut = ({
className,
...props
}: React.HTMLAttributes<HTMLSpanElement>) => {
return (
<span
className={cn(
"ml-auto text-xs tracking-widest text-muted-foreground",
className
)}
{...props}
/>
)
}
CommandShortcut.displayName = "CommandShortcut"
export {
Command,
CommandDialog,
CommandInput,
CommandList,
CommandEmpty,
CommandGroup,
CommandItem,
CommandShortcut,
CommandSeparator,
}

View File

@ -0,0 +1,198 @@
import * as React from "react"
import * as ContextMenuPrimitive from "@radix-ui/react-context-menu"
import { Check, ChevronRight, Circle } from "lucide-react"
import { cn } from "@/lib/utils"
const ContextMenu = ContextMenuPrimitive.Root
const ContextMenuTrigger = ContextMenuPrimitive.Trigger
const ContextMenuGroup = ContextMenuPrimitive.Group
const ContextMenuPortal = ContextMenuPrimitive.Portal
const ContextMenuSub = ContextMenuPrimitive.Sub
const ContextMenuRadioGroup = ContextMenuPrimitive.RadioGroup
const ContextMenuSubTrigger = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.SubTrigger>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.SubTrigger> & {
inset?: boolean
}
>(({ className, inset, children, ...props }, ref) => (
<ContextMenuPrimitive.SubTrigger
ref={ref}
className={cn(
"flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",
inset && "pl-8",
className
)}
{...props}
>
{children}
<ChevronRight className="ml-auto h-4 w-4" />
</ContextMenuPrimitive.SubTrigger>
))
ContextMenuSubTrigger.displayName = ContextMenuPrimitive.SubTrigger.displayName
const ContextMenuSubContent = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.SubContent>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.SubContent>
>(({ className, ...props }, ref) => (
<ContextMenuPrimitive.SubContent
ref={ref}
className={cn(
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg 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 origin-[--radix-context-menu-content-transform-origin]",
className
)}
{...props}
/>
))
ContextMenuSubContent.displayName = ContextMenuPrimitive.SubContent.displayName
const ContextMenuContent = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Content>
>(({ className, ...props }, ref) => (
<ContextMenuPrimitive.Portal>
<ContextMenuPrimitive.Content
ref={ref}
className={cn(
"z-50 max-h-[--radix-context-menu-content-available-height] min-w-[8rem] overflow-y-auto overflow-x-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md 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 origin-[--radix-context-menu-content-transform-origin]",
className
)}
{...props}
/>
</ContextMenuPrimitive.Portal>
))
ContextMenuContent.displayName = ContextMenuPrimitive.Content.displayName
const ContextMenuItem = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Item> & {
inset?: boolean
}
>(({ className, inset, ...props }, ref) => (
<ContextMenuPrimitive.Item
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
inset && "pl-8",
className
)}
{...props}
/>
))
ContextMenuItem.displayName = ContextMenuPrimitive.Item.displayName
const ContextMenuCheckboxItem = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.CheckboxItem>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.CheckboxItem>
>(({ className, children, checked, ...props }, ref) => (
<ContextMenuPrimitive.CheckboxItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
checked={checked}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<ContextMenuPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</ContextMenuPrimitive.ItemIndicator>
</span>
{children}
</ContextMenuPrimitive.CheckboxItem>
))
ContextMenuCheckboxItem.displayName =
ContextMenuPrimitive.CheckboxItem.displayName
const ContextMenuRadioItem = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.RadioItem>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.RadioItem>
>(({ className, children, ...props }, ref) => (
<ContextMenuPrimitive.RadioItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<ContextMenuPrimitive.ItemIndicator>
<Circle className="h-4 w-4 fill-current" />
</ContextMenuPrimitive.ItemIndicator>
</span>
{children}
</ContextMenuPrimitive.RadioItem>
))
ContextMenuRadioItem.displayName = ContextMenuPrimitive.RadioItem.displayName
const ContextMenuLabel = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Label> & {
inset?: boolean
}
>(({ className, inset, ...props }, ref) => (
<ContextMenuPrimitive.Label
ref={ref}
className={cn(
"px-2 py-1.5 text-sm font-semibold text-foreground",
inset && "pl-8",
className
)}
{...props}
/>
))
ContextMenuLabel.displayName = ContextMenuPrimitive.Label.displayName
const ContextMenuSeparator = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Separator>
>(({ className, ...props }, ref) => (
<ContextMenuPrimitive.Separator
ref={ref}
className={cn("-mx-1 my-1 h-px bg-border", className)}
{...props}
/>
))
ContextMenuSeparator.displayName = ContextMenuPrimitive.Separator.displayName
const ContextMenuShortcut = ({
className,
...props
}: React.HTMLAttributes<HTMLSpanElement>) => {
return (
<span
className={cn(
"ml-auto text-xs tracking-widest text-muted-foreground",
className
)}
{...props}
/>
)
}
ContextMenuShortcut.displayName = "ContextMenuShortcut"
export {
ContextMenu,
ContextMenuTrigger,
ContextMenuContent,
ContextMenuItem,
ContextMenuCheckboxItem,
ContextMenuRadioItem,
ContextMenuLabel,
ContextMenuSeparator,
ContextMenuShortcut,
ContextMenuGroup,
ContextMenuPortal,
ContextMenuSub,
ContextMenuSubContent,
ContextMenuSubTrigger,
ContextMenuRadioGroup,
}

View File

@ -0,0 +1,120 @@
import * as React from "react"
import * as DialogPrimitive from "@radix-ui/react-dialog"
import { X } from "lucide-react"
import { cn } from "@/lib/utils"
const Dialog = DialogPrimitive.Root
const DialogTrigger = DialogPrimitive.Trigger
const DialogPortal = DialogPrimitive.Portal
const DialogClose = DialogPrimitive.Close
const DialogOverlay = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Overlay
ref={ref}
className={cn(
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className
)}
{...props}
/>
))
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
ref={ref}
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 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-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
className
)}
{...props}
>
{children}
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
</DialogPortal>
))
DialogContent.displayName = DialogPrimitive.Content.displayName
const DialogHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col space-y-1.5 text-center sm:text-left",
className
)}
{...props}
/>
)
DialogHeader.displayName = "DialogHeader"
const DialogFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
className
)}
{...props}
/>
)
DialogFooter.displayName = "DialogFooter"
const DialogTitle = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Title
ref={ref}
className={cn(
"text-lg font-semibold leading-none tracking-tight",
className
)}
{...props}
/>
))
DialogTitle.displayName = DialogPrimitive.Title.displayName
const DialogDescription = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Description
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
DialogDescription.displayName = DialogPrimitive.Description.displayName
export {
Dialog,
DialogPortal,
DialogOverlay,
DialogTrigger,
DialogClose,
DialogContent,
DialogHeader,
DialogFooter,
DialogTitle,
DialogDescription,
}

View File

@ -0,0 +1,116 @@
import * as React from "react"
import { Drawer as DrawerPrimitive } from "vaul"
import { cn } from "@/lib/utils"
const Drawer = ({
shouldScaleBackground = true,
...props
}: React.ComponentProps<typeof DrawerPrimitive.Root>) => (
<DrawerPrimitive.Root
shouldScaleBackground={shouldScaleBackground}
{...props}
/>
)
Drawer.displayName = "Drawer"
const DrawerTrigger = DrawerPrimitive.Trigger
const DrawerPortal = DrawerPrimitive.Portal
const DrawerClose = DrawerPrimitive.Close
const DrawerOverlay = React.forwardRef<
React.ElementRef<typeof DrawerPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DrawerPrimitive.Overlay
ref={ref}
className={cn("fixed inset-0 z-50 bg-black/80", className)}
{...props}
/>
))
DrawerOverlay.displayName = DrawerPrimitive.Overlay.displayName
const DrawerContent = React.forwardRef<
React.ElementRef<typeof DrawerPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<DrawerPortal>
<DrawerOverlay />
<DrawerPrimitive.Content
ref={ref}
className={cn(
"fixed inset-x-0 bottom-0 z-50 mt-24 flex h-auto flex-col rounded-t-[10px] border bg-background",
className
)}
{...props}
>
<div className="mx-auto mt-4 h-2 w-[100px] rounded-full bg-muted" />
{children}
</DrawerPrimitive.Content>
</DrawerPortal>
))
DrawerContent.displayName = "DrawerContent"
const DrawerHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn("grid gap-1.5 p-4 text-center sm:text-left", className)}
{...props}
/>
)
DrawerHeader.displayName = "DrawerHeader"
const DrawerFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
{...props}
/>
)
DrawerFooter.displayName = "DrawerFooter"
const DrawerTitle = React.forwardRef<
React.ElementRef<typeof DrawerPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Title>
>(({ className, ...props }, ref) => (
<DrawerPrimitive.Title
ref={ref}
className={cn(
"text-lg font-semibold leading-none tracking-tight",
className
)}
{...props}
/>
))
DrawerTitle.displayName = DrawerPrimitive.Title.displayName
const DrawerDescription = React.forwardRef<
React.ElementRef<typeof DrawerPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Description>
>(({ className, ...props }, ref) => (
<DrawerPrimitive.Description
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
DrawerDescription.displayName = DrawerPrimitive.Description.displayName
export {
Drawer,
DrawerPortal,
DrawerOverlay,
DrawerTrigger,
DrawerClose,
DrawerContent,
DrawerHeader,
DrawerFooter,
DrawerTitle,
DrawerDescription,
}

View File

@ -0,0 +1,201 @@
"use client"
import * as React from "react"
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"
import { Check, ChevronRight, Circle } from "lucide-react"
import { cn } from "@/lib/utils"
const DropdownMenu = DropdownMenuPrimitive.Root
const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger
const DropdownMenuGroup = DropdownMenuPrimitive.Group
const DropdownMenuPortal = DropdownMenuPrimitive.Portal
const DropdownMenuSub = DropdownMenuPrimitive.Sub
const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup
const DropdownMenuSubTrigger = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.SubTrigger>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubTrigger> & {
inset?: boolean
}
>(({ className, inset, children, ...props }, ref) => (
<DropdownMenuPrimitive.SubTrigger
ref={ref}
className={cn(
"flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
inset && "pl-8",
className
)}
{...props}
>
{children}
<ChevronRight className="ml-auto" />
</DropdownMenuPrimitive.SubTrigger>
))
DropdownMenuSubTrigger.displayName =
DropdownMenuPrimitive.SubTrigger.displayName
const DropdownMenuSubContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.SubContent>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubContent>
>(({ className, ...props }, ref) => (
<DropdownMenuPrimitive.SubContent
ref={ref}
className={cn(
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg 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 origin-[--radix-dropdown-menu-content-transform-origin]",
className
)}
{...props}
/>
))
DropdownMenuSubContent.displayName =
DropdownMenuPrimitive.SubContent.displayName
const DropdownMenuContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content>
>(({ className, sideOffset = 4, ...props }, ref) => (
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content
ref={ref}
sideOffset={sideOffset}
className={cn(
"z-50 max-h-[var(--radix-dropdown-menu-content-available-height)] min-w-[8rem] overflow-y-auto overflow-x-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md",
"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 origin-[--radix-dropdown-menu-content-transform-origin]",
className
)}
{...props}
/>
</DropdownMenuPrimitive.Portal>
))
DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName
const DropdownMenuItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean
}
>(({ className, inset, ...props }, ref) => (
<DropdownMenuPrimitive.Item
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&>svg]:size-4 [&>svg]:shrink-0",
inset && "pl-8",
className
)}
{...props}
/>
))
DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName
const DropdownMenuCheckboxItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.CheckboxItem>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.CheckboxItem>
>(({ className, children, checked, ...props }, ref) => (
<DropdownMenuPrimitive.CheckboxItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
checked={checked}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.CheckboxItem>
))
DropdownMenuCheckboxItem.displayName =
DropdownMenuPrimitive.CheckboxItem.displayName
const DropdownMenuRadioItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.RadioItem>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.RadioItem>
>(({ className, children, ...props }, ref) => (
<DropdownMenuPrimitive.RadioItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<Circle className="h-2 w-2 fill-current" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.RadioItem>
))
DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName
const DropdownMenuLabel = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Label> & {
inset?: boolean
}
>(({ className, inset, ...props }, ref) => (
<DropdownMenuPrimitive.Label
ref={ref}
className={cn(
"px-2 py-1.5 text-sm font-semibold",
inset && "pl-8",
className
)}
{...props}
/>
))
DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName
const DropdownMenuSeparator = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Separator>
>(({ className, ...props }, ref) => (
<DropdownMenuPrimitive.Separator
ref={ref}
className={cn("-mx-1 my-1 h-px bg-muted", className)}
{...props}
/>
))
DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName
const DropdownMenuShortcut = ({
className,
...props
}: React.HTMLAttributes<HTMLSpanElement>) => {
return (
<span
className={cn("ml-auto text-xs tracking-widest opacity-60", className)}
{...props}
/>
)
}
DropdownMenuShortcut.displayName = "DropdownMenuShortcut"
export {
DropdownMenu,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuCheckboxItem,
DropdownMenuRadioItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuGroup,
DropdownMenuPortal,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuRadioGroup,
}

View File

@ -0,0 +1,104 @@
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
function Empty({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="empty"
className={cn(
"flex min-w-0 flex-1 flex-col items-center justify-center gap-6 text-balance rounded-lg border-dashed p-6 text-center md:p-12",
className
)}
{...props}
/>
)
}
function EmptyHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="empty-header"
className={cn(
"flex max-w-sm flex-col items-center gap-2 text-center",
className
)}
{...props}
/>
)
}
const emptyMediaVariants = cva(
"mb-2 flex shrink-0 items-center justify-center [&_svg]:pointer-events-none [&_svg]:shrink-0",
{
variants: {
variant: {
default: "bg-transparent",
icon: "bg-muted text-foreground flex size-10 shrink-0 items-center justify-center rounded-lg [&_svg:not([class*='size-'])]:size-6",
},
},
defaultVariants: {
variant: "default",
},
}
)
function EmptyMedia({
className,
variant = "default",
...props
}: React.ComponentProps<"div"> & VariantProps<typeof emptyMediaVariants>) {
return (
<div
data-slot="empty-icon"
data-variant={variant}
className={cn(emptyMediaVariants({ variant, className }))}
{...props}
/>
)
}
function EmptyTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="empty-title"
className={cn("text-lg font-medium tracking-tight", className)}
{...props}
/>
)
}
function EmptyDescription({ className, ...props }: React.ComponentProps<"p">) {
return (
<div
data-slot="empty-description"
className={cn(
"text-muted-foreground [&>a:hover]:text-primary text-sm/relaxed [&>a]:underline [&>a]:underline-offset-4",
className
)}
{...props}
/>
)
}
function EmptyContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="empty-content"
className={cn(
"flex w-full min-w-0 max-w-sm flex-col items-center gap-4 text-balance text-sm",
className
)}
{...props}
/>
)
}
export {
Empty,
EmptyHeader,
EmptyTitle,
EmptyDescription,
EmptyContent,
EmptyMedia,
}

View File

@ -0,0 +1,244 @@
"use client"
import { useMemo } from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
import { Label } from "@/components/ui/label"
import { Separator } from "@/components/ui/separator"
function FieldSet({ className, ...props }: React.ComponentProps<"fieldset">) {
return (
<fieldset
data-slot="field-set"
className={cn(
"flex flex-col gap-6",
"has-[>[data-slot=checkbox-group]]:gap-3 has-[>[data-slot=radio-group]]:gap-3",
className
)}
{...props}
/>
)
}
function FieldLegend({
className,
variant = "legend",
...props
}: React.ComponentProps<"legend"> & { variant?: "legend" | "label" }) {
return (
<legend
data-slot="field-legend"
data-variant={variant}
className={cn(
"mb-3 font-medium",
"data-[variant=legend]:text-base",
"data-[variant=label]:text-sm",
className
)}
{...props}
/>
)
}
function FieldGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="field-group"
className={cn(
"group/field-group @container/field-group flex w-full flex-col gap-7 data-[slot=checkbox-group]:gap-3 [&>[data-slot=field-group]]:gap-4",
className
)}
{...props}
/>
)
}
const fieldVariants = cva(
"group/field data-[invalid=true]:text-destructive flex w-full gap-3",
{
variants: {
orientation: {
vertical: ["flex-col [&>*]:w-full [&>.sr-only]:w-auto"],
horizontal: [
"flex-row items-center",
"[&>[data-slot=field-label]]:flex-auto",
"has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px has-[>[data-slot=field-content]]:items-start",
],
responsive: [
"@md/field-group:flex-row @md/field-group:items-center @md/field-group:[&>*]:w-auto flex-col [&>*]:w-full [&>.sr-only]:w-auto",
"@md/field-group:[&>[data-slot=field-label]]:flex-auto",
"@md/field-group:has-[>[data-slot=field-content]]:items-start @md/field-group:has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
],
},
},
defaultVariants: {
orientation: "vertical",
},
}
)
function Field({
className,
orientation = "vertical",
...props
}: React.ComponentProps<"div"> & VariantProps<typeof fieldVariants>) {
return (
<div
role="group"
data-slot="field"
data-orientation={orientation}
className={cn(fieldVariants({ orientation }), className)}
{...props}
/>
)
}
function FieldContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="field-content"
className={cn(
"group/field-content flex flex-1 flex-col gap-1.5 leading-snug",
className
)}
{...props}
/>
)
}
function FieldLabel({
className,
...props
}: React.ComponentProps<typeof Label>) {
return (
<Label
data-slot="field-label"
className={cn(
"group/field-label peer/field-label flex w-fit gap-2 leading-snug group-data-[disabled=true]/field:opacity-50",
"has-[>[data-slot=field]]:w-full has-[>[data-slot=field]]:flex-col has-[>[data-slot=field]]:rounded-md has-[>[data-slot=field]]:border [&>[data-slot=field]]:p-4",
"has-data-[state=checked]:bg-primary/5 has-data-[state=checked]:border-primary dark:has-data-[state=checked]:bg-primary/10",
className
)}
{...props}
/>
)
}
function FieldTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="field-label"
className={cn(
"flex w-fit items-center gap-2 text-sm font-medium leading-snug group-data-[disabled=true]/field:opacity-50",
className
)}
{...props}
/>
)
}
function FieldDescription({ className, ...props }: React.ComponentProps<"p">) {
return (
<p
data-slot="field-description"
className={cn(
"text-muted-foreground text-sm font-normal leading-normal group-has-[[data-orientation=horizontal]]/field:text-balance",
"nth-last-2:-mt-1 last:mt-0 [[data-variant=legend]+&]:-mt-1.5",
"[&>a:hover]:text-primary [&>a]:underline [&>a]:underline-offset-4",
className
)}
{...props}
/>
)
}
function FieldSeparator({
children,
className,
...props
}: React.ComponentProps<"div"> & {
children?: React.ReactNode
}) {
return (
<div
data-slot="field-separator"
data-content={!!children}
className={cn(
"relative -my-2 h-5 text-sm group-data-[variant=outline]/field-group:-mb-2",
className
)}
{...props}
>
<Separator className="absolute inset-0 top-1/2" />
{children && (
<span
className="bg-background text-muted-foreground relative mx-auto block w-fit px-2"
data-slot="field-separator-content"
>
{children}
</span>
)}
</div>
)
}
function FieldError({
className,
children,
errors,
...props
}: React.ComponentProps<"div"> & {
errors?: Array<{ message?: string } | undefined>
}) {
const content = useMemo(() => {
if (children) {
return children
}
if (!errors) {
return null
}
if (errors?.length === 1 && errors[0]?.message) {
return errors[0].message
}
return (
<ul className="ml-4 flex list-disc flex-col gap-1">
{errors.map(
(error, index) =>
error?.message && <li key={index}>{error.message}</li>
)}
</ul>
)
}, [children, errors])
if (!content) {
return null
}
return (
<div
role="alert"
data-slot="field-error"
className={cn("text-destructive text-sm font-normal", className)}
{...props}
>
{content}
</div>
)
}
export {
Field,
FieldLabel,
FieldDescription,
FieldError,
FieldGroup,
FieldLegend,
FieldSeparator,
FieldSet,
FieldContent,
FieldTitle,
}

View File

@ -0,0 +1,176 @@
import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
import { Slot } from "@radix-ui/react-slot"
import {
Controller,
FormProvider,
useFormContext,
type ControllerProps,
type FieldPath,
type FieldValues,
} from "react-hook-form"
import { cn } from "@/lib/utils"
import { Label } from "@/components/ui/label"
const Form = FormProvider
type FormFieldContextValue<
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
> = {
name: TName
}
const FormFieldContext = React.createContext<FormFieldContextValue | null>(null)
const FormField = <
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
>({
...props
}: ControllerProps<TFieldValues, TName>) => {
return (
<FormFieldContext.Provider value={{ name: props.name }}>
<Controller {...props} />
</FormFieldContext.Provider>
)
}
const useFormField = () => {
const fieldContext = React.useContext(FormFieldContext)
const itemContext = React.useContext(FormItemContext)
const { getFieldState, formState } = useFormContext()
if (!fieldContext) {
throw new Error("useFormField should be used within <FormField>")
}
if (!itemContext) {
throw new Error("useFormField should be used within <FormItem>")
}
const fieldState = getFieldState(fieldContext.name, formState)
const { id } = itemContext
return {
id,
name: fieldContext.name,
formItemId: `${id}-form-item`,
formDescriptionId: `${id}-form-item-description`,
formMessageId: `${id}-form-item-message`,
...fieldState,
}
}
type FormItemContextValue = {
id: string
}
const FormItemContext = React.createContext<FormItemContextValue | null>(null)
const FormItem = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => {
const id = React.useId()
return (
<FormItemContext.Provider value={{ id }}>
<div ref={ref} className={cn("space-y-2", className)} {...props} />
</FormItemContext.Provider>
)
})
FormItem.displayName = "FormItem"
const FormLabel = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root>
>(({ className, ...props }, ref) => {
const { error, formItemId } = useFormField()
return (
<Label
ref={ref}
className={cn(error && "text-destructive", className)}
htmlFor={formItemId}
{...props}
/>
)
})
FormLabel.displayName = "FormLabel"
const FormControl = React.forwardRef<
React.ElementRef<typeof Slot>,
React.ComponentPropsWithoutRef<typeof Slot>
>(({ ...props }, ref) => {
const { error, formItemId, formDescriptionId, formMessageId } = useFormField()
return (
<Slot
ref={ref}
id={formItemId}
aria-describedby={
!error
? `${formDescriptionId}`
: `${formDescriptionId} ${formMessageId}`
}
aria-invalid={!!error}
{...props}
/>
)
})
FormControl.displayName = "FormControl"
const FormDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => {
const { formDescriptionId } = useFormField()
return (
<p
ref={ref}
id={formDescriptionId}
className={cn("text-[0.8rem] text-muted-foreground", className)}
{...props}
/>
)
})
FormDescription.displayName = "FormDescription"
const FormMessage = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, children, ...props }, ref) => {
const { error, formMessageId } = useFormField()
const body = error ? String(error?.message ?? "") : children
if (!body) {
return null
}
return (
<p
ref={ref}
id={formMessageId}
className={cn("text-[0.8rem] font-medium text-destructive", className)}
{...props}
>
{body}
</p>
)
})
FormMessage.displayName = "FormMessage"
export {
useFormField,
Form,
FormItem,
FormLabel,
FormControl,
FormDescription,
FormMessage,
FormField,
}

View File

@ -0,0 +1,27 @@
import * as React from "react"
import * as HoverCardPrimitive from "@radix-ui/react-hover-card"
import { cn } from "@/lib/utils"
const HoverCard = HoverCardPrimitive.Root
const HoverCardTrigger = HoverCardPrimitive.Trigger
const HoverCardContent = React.forwardRef<
React.ElementRef<typeof HoverCardPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof HoverCardPrimitive.Content>
>(({ className, align = "center", sideOffset = 4, ...props }, ref) => (
<HoverCardPrimitive.Content
ref={ref}
align={align}
sideOffset={sideOffset}
className={cn(
"z-50 w-64 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none 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 origin-[--radix-hover-card-content-transform-origin]",
className
)}
{...props}
/>
))
HoverCardContent.displayName = HoverCardPrimitive.Content.displayName
export { HoverCard, HoverCardTrigger, HoverCardContent }

View File

@ -0,0 +1,168 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
function InputGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="input-group"
role="group"
className={cn(
"group/input-group border-input dark:bg-input/30 shadow-xs relative flex w-full items-center rounded-md border outline-none transition-[color,box-shadow]",
"h-9 has-[>textarea]:h-auto",
// Variants based on alignment.
"has-[>[data-align=inline-start]]:[&>input]:pl-2",
"has-[>[data-align=inline-end]]:[&>input]:pr-2",
"has-[>[data-align=block-start]]:h-auto has-[>[data-align=block-start]]:flex-col has-[>[data-align=block-start]]:[&>input]:pb-3",
"has-[>[data-align=block-end]]:h-auto has-[>[data-align=block-end]]:flex-col has-[>[data-align=block-end]]:[&>input]:pt-3",
// Focus state.
"has-[[data-slot=input-group-control]:focus-visible]:ring-ring has-[[data-slot=input-group-control]:focus-visible]:ring-1",
// Error state.
"has-[[data-slot][aria-invalid=true]]:ring-destructive/20 has-[[data-slot][aria-invalid=true]]:border-destructive dark:has-[[data-slot][aria-invalid=true]]:ring-destructive/40",
className
)}
{...props}
/>
)
}
const inputGroupAddonVariants = cva(
"text-muted-foreground flex h-auto cursor-text select-none items-center justify-center gap-2 py-1.5 text-sm font-medium group-data-[disabled=true]/input-group:opacity-50 [&>kbd]:rounded-[calc(var(--radius)-5px)] [&>svg:not([class*='size-'])]:size-4",
{
variants: {
align: {
"inline-start":
"order-first pl-3 has-[>button]:ml-[-0.45rem] has-[>kbd]:ml-[-0.35rem]",
"inline-end":
"order-last pr-3 has-[>button]:mr-[-0.4rem] has-[>kbd]:mr-[-0.35rem]",
"block-start":
"[.border-b]:pb-3 order-first w-full justify-start px-3 pt-3 group-has-[>input]/input-group:pt-2.5",
"block-end":
"[.border-t]:pt-3 order-last w-full justify-start px-3 pb-3 group-has-[>input]/input-group:pb-2.5",
},
},
defaultVariants: {
align: "inline-start",
},
}
)
function InputGroupAddon({
className,
align = "inline-start",
...props
}: React.ComponentProps<"div"> & VariantProps<typeof inputGroupAddonVariants>) {
return (
<div
role="group"
data-slot="input-group-addon"
data-align={align}
className={cn(inputGroupAddonVariants({ align }), className)}
onClick={(e) => {
if ((e.target as HTMLElement).closest("button")) {
return
}
e.currentTarget.parentElement?.querySelector("input")?.focus()
}}
{...props}
/>
)
}
const inputGroupButtonVariants = cva(
"flex items-center gap-2 text-sm shadow-none",
{
variants: {
size: {
xs: "h-6 gap-1 rounded-[calc(var(--radius)-5px)] px-2 has-[>svg]:px-2 [&>svg:not([class*='size-'])]:size-3.5",
sm: "h-8 gap-1.5 rounded-md px-2.5 has-[>svg]:px-2.5",
"icon-xs":
"size-6 rounded-[calc(var(--radius)-5px)] p-0 has-[>svg]:p-0",
"icon-sm": "size-8 p-0 has-[>svg]:p-0",
},
},
defaultVariants: {
size: "xs",
},
}
)
function InputGroupButton({
className,
type = "button",
variant = "ghost",
size = "xs",
...props
}: Omit<React.ComponentProps<typeof Button>, "size"> &
VariantProps<typeof inputGroupButtonVariants>) {
return (
<Button
type={type}
data-size={size}
variant={variant}
className={cn(inputGroupButtonVariants({ size }), className)}
{...props}
/>
)
}
function InputGroupText({ className, ...props }: React.ComponentProps<"span">) {
return (
<span
className={cn(
"text-muted-foreground flex items-center gap-2 text-sm [&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none",
className
)}
{...props}
/>
)
}
function InputGroupInput({
className,
...props
}: React.ComponentProps<"input">) {
return (
<Input
data-slot="input-group-control"
className={cn(
"flex-1 rounded-none border-0 bg-transparent shadow-none focus-visible:ring-0 dark:bg-transparent",
className
)}
{...props}
/>
)
}
function InputGroupTextarea({
className,
...props
}: React.ComponentProps<"textarea">) {
return (
<Textarea
data-slot="input-group-control"
className={cn(
"flex-1 resize-none rounded-none border-0 bg-transparent py-3 shadow-none focus-visible:ring-0 dark:bg-transparent",
className
)}
{...props}
/>
)
}
export {
InputGroup,
InputGroupAddon,
InputGroupButton,
InputGroupText,
InputGroupInput,
InputGroupTextarea,
}

View File

@ -0,0 +1,69 @@
import * as React from "react"
import { OTPInput, OTPInputContext } from "input-otp"
import { Minus } from "lucide-react"
import { cn } from "@/lib/utils"
const InputOTP = React.forwardRef<
React.ElementRef<typeof OTPInput>,
React.ComponentPropsWithoutRef<typeof OTPInput>
>(({ className, containerClassName, ...props }, ref) => (
<OTPInput
ref={ref}
containerClassName={cn(
"flex items-center gap-2 has-[:disabled]:opacity-50",
containerClassName
)}
className={cn("disabled:cursor-not-allowed", className)}
{...props}
/>
))
InputOTP.displayName = "InputOTP"
const InputOTPGroup = React.forwardRef<
React.ElementRef<"div">,
React.ComponentPropsWithoutRef<"div">
>(({ className, ...props }, ref) => (
<div ref={ref} className={cn("flex items-center", className)} {...props} />
))
InputOTPGroup.displayName = "InputOTPGroup"
const InputOTPSlot = React.forwardRef<
React.ElementRef<"div">,
React.ComponentPropsWithoutRef<"div"> & { index: number }
>(({ index, className, ...props }, ref) => {
const inputOTPContext = React.useContext(OTPInputContext)
const { char, hasFakeCaret, isActive } = inputOTPContext.slots[index]
return (
<div
ref={ref}
className={cn(
"relative flex h-9 w-9 items-center justify-center border-y border-r border-input text-sm shadow-sm transition-all first:rounded-l-md first:border-l last:rounded-r-md",
isActive && "z-10 ring-1 ring-ring",
className
)}
{...props}
>
{char}
{hasFakeCaret && (
<div className="pointer-events-none absolute inset-0 flex items-center justify-center">
<div className="h-4 w-px animate-caret-blink bg-foreground duration-1000" />
</div>
)}
</div>
)
})
InputOTPSlot.displayName = "InputOTPSlot"
const InputOTPSeparator = React.forwardRef<
React.ElementRef<"div">,
React.ComponentPropsWithoutRef<"div">
>(({ ...props }, ref) => (
<div ref={ref} role="separator" {...props}>
<Minus />
</div>
))
InputOTPSeparator.displayName = "InputOTPSeparator"
export { InputOTP, InputOTPGroup, InputOTPSlot, InputOTPSeparator }

View File

@ -0,0 +1,22 @@
import * as React from "react"
import { cn } from "@/lib/utils"
const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<"input">>(
({ className, type, ...props }, ref) => {
return (
<input
type={type}
className={cn(
"flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
className
)}
ref={ref}
{...props}
/>
)
}
)
Input.displayName = "Input"
export { Input }

View File

@ -0,0 +1,193 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
import { Separator } from "@/components/ui/separator"
function ItemGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
role="list"
data-slot="item-group"
className={cn("group/item-group flex flex-col", className)}
{...props}
/>
)
}
function ItemSeparator({
className,
...props
}: React.ComponentProps<typeof Separator>) {
return (
<Separator
data-slot="item-separator"
orientation="horizontal"
className={cn("my-0", className)}
{...props}
/>
)
}
const itemVariants = cva(
"group/item [a]:hover:bg-accent/50 focus-visible:border-ring focus-visible:ring-ring/50 [a]:transition-colors flex flex-wrap items-center rounded-md border border-transparent text-sm outline-none transition-colors duration-100 focus-visible:ring-[3px]",
{
variants: {
variant: {
default: "bg-transparent",
outline: "border-border",
muted: "bg-muted/50",
},
size: {
default: "gap-4 p-4 ",
sm: "gap-2.5 px-4 py-3",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
function Item({
className,
variant = "default",
size = "default",
asChild = false,
...props
}: React.ComponentProps<"div"> &
VariantProps<typeof itemVariants> & { asChild?: boolean }) {
const Comp = asChild ? Slot : "div"
return (
<Comp
data-slot="item"
data-variant={variant}
data-size={size}
className={cn(itemVariants({ variant, size, className }))}
{...props}
/>
)
}
const itemMediaVariants = cva(
"flex shrink-0 items-center justify-center gap-2 group-has-[[data-slot=item-description]]/item:translate-y-0.5 group-has-[[data-slot=item-description]]/item:self-start [&_svg]:pointer-events-none",
{
variants: {
variant: {
default: "bg-transparent",
icon: "bg-muted size-8 rounded-sm border [&_svg:not([class*='size-'])]:size-4",
image:
"size-10 overflow-hidden rounded-sm [&_img]:size-full [&_img]:object-cover",
},
},
defaultVariants: {
variant: "default",
},
}
)
function ItemMedia({
className,
variant = "default",
...props
}: React.ComponentProps<"div"> & VariantProps<typeof itemMediaVariants>) {
return (
<div
data-slot="item-media"
data-variant={variant}
className={cn(itemMediaVariants({ variant, className }))}
{...props}
/>
)
}
function ItemContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="item-content"
className={cn(
"flex flex-1 flex-col gap-1 [&+[data-slot=item-content]]:flex-none",
className
)}
{...props}
/>
)
}
function ItemTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="item-title"
className={cn(
"flex w-fit items-center gap-2 text-sm font-medium leading-snug",
className
)}
{...props}
/>
)
}
function ItemDescription({ className, ...props }: React.ComponentProps<"p">) {
return (
<p
data-slot="item-description"
className={cn(
"text-muted-foreground line-clamp-2 text-balance text-sm font-normal leading-normal",
"[&>a:hover]:text-primary [&>a]:underline [&>a]:underline-offset-4",
className
)}
{...props}
/>
)
}
function ItemActions({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="item-actions"
className={cn("flex items-center gap-2", className)}
{...props}
/>
)
}
function ItemHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="item-header"
className={cn(
"flex basis-full items-center justify-between gap-2",
className
)}
{...props}
/>
)
}
function ItemFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="item-footer"
className={cn(
"flex basis-full items-center justify-between gap-2",
className
)}
{...props}
/>
)
}
export {
Item,
ItemMedia,
ItemContent,
ItemActions,
ItemGroup,
ItemSeparator,
ItemTitle,
ItemDescription,
ItemHeader,
ItemFooter,
}

View File

@ -0,0 +1,28 @@
import { cn } from "@/lib/utils"
function Kbd({ className, ...props }: React.ComponentProps<"kbd">) {
return (
<kbd
data-slot="kbd"
className={cn(
"bg-muted text-muted-foreground pointer-events-none inline-flex h-5 w-fit min-w-5 select-none items-center justify-center gap-1 rounded-sm px-1 font-sans text-xs font-medium",
"[&_svg:not([class*='size-'])]:size-3",
"[[data-slot=tooltip-content]_&]:bg-background/20 [[data-slot=tooltip-content]_&]:text-background dark:[[data-slot=tooltip-content]_&]:bg-background/10",
className
)}
{...props}
/>
)
}
function KbdGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<kbd
data-slot="kbd-group"
className={cn("inline-flex items-center gap-1", className)}
{...props}
/>
)
}
export { Kbd, KbdGroup }

View File

@ -0,0 +1,26 @@
"use client"
import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const labelVariants = cva(
"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
)
const Label = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &
VariantProps<typeof labelVariants>
>(({ className, ...props }, ref) => (
<LabelPrimitive.Root
ref={ref}
className={cn(labelVariants(), className)}
{...props}
/>
))
Label.displayName = LabelPrimitive.Root.displayName
export { Label }

View File

@ -0,0 +1,254 @@
import * as React from "react"
import * as MenubarPrimitive from "@radix-ui/react-menubar"
import { Check, ChevronRight, Circle } from "lucide-react"
import { cn } from "@/lib/utils"
function MenubarMenu({
...props
}: React.ComponentProps<typeof MenubarPrimitive.Menu>) {
return <MenubarPrimitive.Menu {...props} />
}
function MenubarGroup({
...props
}: React.ComponentProps<typeof MenubarPrimitive.Group>) {
return <MenubarPrimitive.Group {...props} />
}
function MenubarPortal({
...props
}: React.ComponentProps<typeof MenubarPrimitive.Portal>) {
return <MenubarPrimitive.Portal {...props} />
}
function MenubarRadioGroup({
...props
}: React.ComponentProps<typeof MenubarPrimitive.RadioGroup>) {
return <MenubarPrimitive.RadioGroup {...props} />
}
function MenubarSub({
...props
}: React.ComponentProps<typeof MenubarPrimitive.Sub>) {
return <MenubarPrimitive.Sub data-slot="menubar-sub" {...props} />
}
const Menubar = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.Root>
>(({ className, ...props }, ref) => (
<MenubarPrimitive.Root
ref={ref}
className={cn(
"flex h-9 items-center space-x-1 rounded-md border bg-background p-1 shadow-sm",
className
)}
{...props}
/>
))
Menubar.displayName = MenubarPrimitive.Root.displayName
const MenubarTrigger = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.Trigger>
>(({ className, ...props }, ref) => (
<MenubarPrimitive.Trigger
ref={ref}
className={cn(
"flex cursor-default select-none items-center rounded-sm px-3 py-1 text-sm font-medium outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",
className
)}
{...props}
/>
))
MenubarTrigger.displayName = MenubarPrimitive.Trigger.displayName
const MenubarSubTrigger = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.SubTrigger>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.SubTrigger> & {
inset?: boolean
}
>(({ className, inset, children, ...props }, ref) => (
<MenubarPrimitive.SubTrigger
ref={ref}
className={cn(
"flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",
inset && "pl-8",
className
)}
{...props}
>
{children}
<ChevronRight className="ml-auto h-4 w-4" />
</MenubarPrimitive.SubTrigger>
))
MenubarSubTrigger.displayName = MenubarPrimitive.SubTrigger.displayName
const MenubarSubContent = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.SubContent>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.SubContent>
>(({ className, ...props }, ref) => (
<MenubarPrimitive.SubContent
ref={ref}
className={cn(
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg 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 origin-[--radix-menubar-content-transform-origin]",
className
)}
{...props}
/>
))
MenubarSubContent.displayName = MenubarPrimitive.SubContent.displayName
const MenubarContent = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.Content>
>(
(
{ className, align = "start", alignOffset = -4, sideOffset = 8, ...props },
ref
) => (
<MenubarPrimitive.Portal>
<MenubarPrimitive.Content
ref={ref}
align={align}
alignOffset={alignOffset}
sideOffset={sideOffset}
className={cn(
"z-50 min-w-[12rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in 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 origin-[--radix-menubar-content-transform-origin]",
className
)}
{...props}
/>
</MenubarPrimitive.Portal>
)
)
MenubarContent.displayName = MenubarPrimitive.Content.displayName
const MenubarItem = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.Item> & {
inset?: boolean
}
>(({ className, inset, ...props }, ref) => (
<MenubarPrimitive.Item
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
inset && "pl-8",
className
)}
{...props}
/>
))
MenubarItem.displayName = MenubarPrimitive.Item.displayName
const MenubarCheckboxItem = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.CheckboxItem>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.CheckboxItem>
>(({ className, children, checked, ...props }, ref) => (
<MenubarPrimitive.CheckboxItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
checked={checked}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<MenubarPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</MenubarPrimitive.ItemIndicator>
</span>
{children}
</MenubarPrimitive.CheckboxItem>
))
MenubarCheckboxItem.displayName = MenubarPrimitive.CheckboxItem.displayName
const MenubarRadioItem = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.RadioItem>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.RadioItem>
>(({ className, children, ...props }, ref) => (
<MenubarPrimitive.RadioItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<MenubarPrimitive.ItemIndicator>
<Circle className="h-4 w-4 fill-current" />
</MenubarPrimitive.ItemIndicator>
</span>
{children}
</MenubarPrimitive.RadioItem>
))
MenubarRadioItem.displayName = MenubarPrimitive.RadioItem.displayName
const MenubarLabel = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.Label> & {
inset?: boolean
}
>(({ className, inset, ...props }, ref) => (
<MenubarPrimitive.Label
ref={ref}
className={cn(
"px-2 py-1.5 text-sm font-semibold",
inset && "pl-8",
className
)}
{...props}
/>
))
MenubarLabel.displayName = MenubarPrimitive.Label.displayName
const MenubarSeparator = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.Separator>
>(({ className, ...props }, ref) => (
<MenubarPrimitive.Separator
ref={ref}
className={cn("-mx-1 my-1 h-px bg-muted", className)}
{...props}
/>
))
MenubarSeparator.displayName = MenubarPrimitive.Separator.displayName
const MenubarShortcut = ({
className,
...props
}: React.HTMLAttributes<HTMLSpanElement>) => {
return (
<span
className={cn(
"ml-auto text-xs tracking-widest text-muted-foreground",
className
)}
{...props}
/>
)
}
MenubarShortcut.displayname = "MenubarShortcut"
export {
Menubar,
MenubarMenu,
MenubarTrigger,
MenubarContent,
MenubarItem,
MenubarSeparator,
MenubarLabel,
MenubarCheckboxItem,
MenubarRadioGroup,
MenubarRadioItem,
MenubarPortal,
MenubarSubContent,
MenubarSubTrigger,
MenubarGroup,
MenubarSub,
MenubarShortcut,
}

View File

@ -0,0 +1,128 @@
import * as React from "react"
import * as NavigationMenuPrimitive from "@radix-ui/react-navigation-menu"
import { cva } from "class-variance-authority"
import { ChevronDown } from "lucide-react"
import { cn } from "@/lib/utils"
const NavigationMenu = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Root>
>(({ className, children, ...props }, ref) => (
<NavigationMenuPrimitive.Root
ref={ref}
className={cn(
"relative z-10 flex max-w-max flex-1 items-center justify-center",
className
)}
{...props}
>
{children}
<NavigationMenuViewport />
</NavigationMenuPrimitive.Root>
))
NavigationMenu.displayName = NavigationMenuPrimitive.Root.displayName
const NavigationMenuList = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.List>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.List>
>(({ className, ...props }, ref) => (
<NavigationMenuPrimitive.List
ref={ref}
className={cn(
"group flex flex-1 list-none items-center justify-center space-x-1",
className
)}
{...props}
/>
))
NavigationMenuList.displayName = NavigationMenuPrimitive.List.displayName
const NavigationMenuItem = NavigationMenuPrimitive.Item
const navigationMenuTriggerStyle = cva(
"group inline-flex h-9 w-max items-center justify-center rounded-md bg-background px-4 py-2 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground focus:outline-none disabled:pointer-events-none disabled:opacity-50 data-[state=open]:text-accent-foreground data-[state=open]:bg-accent/50 data-[state=open]:hover:bg-accent data-[state=open]:focus:bg-accent"
)
const NavigationMenuTrigger = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
<NavigationMenuPrimitive.Trigger
ref={ref}
className={cn(navigationMenuTriggerStyle(), "group", className)}
{...props}
>
{children}{" "}
<ChevronDown
className="relative top-[1px] ml-1 h-3 w-3 transition duration-300 group-data-[state=open]:rotate-180"
aria-hidden="true"
/>
</NavigationMenuPrimitive.Trigger>
))
NavigationMenuTrigger.displayName = NavigationMenuPrimitive.Trigger.displayName
const NavigationMenuContent = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Content>
>(({ className, ...props }, ref) => (
<NavigationMenuPrimitive.Content
ref={ref}
className={cn(
"left-0 top-0 w-full data-[motion^=from-]:animate-in data-[motion^=to-]:animate-out data-[motion^=from-]:fade-in data-[motion^=to-]:fade-out data-[motion=from-end]:slide-in-from-right-52 data-[motion=from-start]:slide-in-from-left-52 data-[motion=to-end]:slide-out-to-right-52 data-[motion=to-start]:slide-out-to-left-52 md:absolute md:w-auto ",
className
)}
{...props}
/>
))
NavigationMenuContent.displayName = NavigationMenuPrimitive.Content.displayName
const NavigationMenuLink = NavigationMenuPrimitive.Link
const NavigationMenuViewport = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.Viewport>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Viewport>
>(({ className, ...props }, ref) => (
<div className={cn("absolute left-0 top-full flex justify-center")}>
<NavigationMenuPrimitive.Viewport
className={cn(
"origin-top-center relative mt-1.5 h-[var(--radix-navigation-menu-viewport-height)] w-full overflow-hidden rounded-md border bg-popover text-popover-foreground shadow data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-90 md:w-[var(--radix-navigation-menu-viewport-width)]",
className
)}
ref={ref}
{...props}
/>
</div>
))
NavigationMenuViewport.displayName =
NavigationMenuPrimitive.Viewport.displayName
const NavigationMenuIndicator = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.Indicator>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Indicator>
>(({ className, ...props }, ref) => (
<NavigationMenuPrimitive.Indicator
ref={ref}
className={cn(
"top-full z-[1] flex h-1.5 items-end justify-center overflow-hidden data-[state=visible]:animate-in data-[state=hidden]:animate-out data-[state=hidden]:fade-out data-[state=visible]:fade-in",
className
)}
{...props}
>
<div className="relative top-[60%] h-2 w-2 rotate-45 rounded-tl-sm bg-border shadow-md" />
</NavigationMenuPrimitive.Indicator>
))
NavigationMenuIndicator.displayName =
NavigationMenuPrimitive.Indicator.displayName
export {
navigationMenuTriggerStyle,
NavigationMenu,
NavigationMenuList,
NavigationMenuItem,
NavigationMenuContent,
NavigationMenuTrigger,
NavigationMenuLink,
NavigationMenuIndicator,
NavigationMenuViewport,
}

View File

@ -0,0 +1,117 @@
import * as React from "react"
import { ChevronLeft, ChevronRight, MoreHorizontal } from "lucide-react"
import { cn } from "@/lib/utils"
import { ButtonProps, buttonVariants } from "@/components/ui/button"
const Pagination = ({ className, ...props }: React.ComponentProps<"nav">) => (
<nav
role="navigation"
aria-label="pagination"
className={cn("mx-auto flex w-full justify-center", className)}
{...props}
/>
)
Pagination.displayName = "Pagination"
const PaginationContent = React.forwardRef<
HTMLUListElement,
React.ComponentProps<"ul">
>(({ className, ...props }, ref) => (
<ul
ref={ref}
className={cn("flex flex-row items-center gap-1", className)}
{...props}
/>
))
PaginationContent.displayName = "PaginationContent"
const PaginationItem = React.forwardRef<
HTMLLIElement,
React.ComponentProps<"li">
>(({ className, ...props }, ref) => (
<li ref={ref} className={cn("", className)} {...props} />
))
PaginationItem.displayName = "PaginationItem"
type PaginationLinkProps = {
isActive?: boolean
} & Pick<ButtonProps, "size"> &
React.ComponentProps<"a">
const PaginationLink = ({
className,
isActive,
size = "icon",
...props
}: PaginationLinkProps) => (
<a
aria-current={isActive ? "page" : undefined}
className={cn(
buttonVariants({
variant: isActive ? "outline" : "ghost",
size,
}),
className
)}
{...props}
/>
)
PaginationLink.displayName = "PaginationLink"
const PaginationPrevious = ({
className,
...props
}: React.ComponentProps<typeof PaginationLink>) => (
<PaginationLink
aria-label="Go to previous page"
size="default"
className={cn("gap-1 pl-2.5", className)}
{...props}
>
<ChevronLeft className="h-4 w-4" />
<span>Previous</span>
</PaginationLink>
)
PaginationPrevious.displayName = "PaginationPrevious"
const PaginationNext = ({
className,
...props
}: React.ComponentProps<typeof PaginationLink>) => (
<PaginationLink
aria-label="Go to next page"
size="default"
className={cn("gap-1 pr-2.5", className)}
{...props}
>
<span>Next</span>
<ChevronRight className="h-4 w-4" />
</PaginationLink>
)
PaginationNext.displayName = "PaginationNext"
const PaginationEllipsis = ({
className,
...props
}: React.ComponentProps<"span">) => (
<span
aria-hidden
className={cn("flex h-9 w-9 items-center justify-center", className)}
{...props}
>
<MoreHorizontal className="h-4 w-4" />
<span className="sr-only">More pages</span>
</span>
)
PaginationEllipsis.displayName = "PaginationEllipsis"
export {
Pagination,
PaginationContent,
PaginationLink,
PaginationItem,
PaginationPrevious,
PaginationNext,
PaginationEllipsis,
}

View File

@ -0,0 +1,31 @@
import * as React from "react"
import * as PopoverPrimitive from "@radix-ui/react-popover"
import { cn } from "@/lib/utils"
const Popover = PopoverPrimitive.Root
const PopoverTrigger = PopoverPrimitive.Trigger
const PopoverAnchor = PopoverPrimitive.Anchor
const PopoverContent = React.forwardRef<
React.ElementRef<typeof PopoverPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>
>(({ className, align = "center", sideOffset = 4, ...props }, ref) => (
<PopoverPrimitive.Portal>
<PopoverPrimitive.Content
ref={ref}
align={align}
sideOffset={sideOffset}
className={cn(
"z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none 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 origin-[--radix-popover-content-transform-origin]",
className
)}
{...props}
/>
</PopoverPrimitive.Portal>
))
PopoverContent.displayName = PopoverPrimitive.Content.displayName
export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor }

View File

@ -0,0 +1,28 @@
"use client"
import * as React from "react"
import * as ProgressPrimitive from "@radix-ui/react-progress"
import { cn } from "@/lib/utils"
const Progress = React.forwardRef<
React.ElementRef<typeof ProgressPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof ProgressPrimitive.Root>
>(({ className, value, ...props }, ref) => (
<ProgressPrimitive.Root
ref={ref}
className={cn(
"relative h-2 w-full overflow-hidden rounded-full bg-primary/20",
className
)}
{...props}
>
<ProgressPrimitive.Indicator
className="h-full w-full flex-1 bg-primary transition-all"
style={{ transform: `translateX(-${100 - (value || 0)}%)` }}
/>
</ProgressPrimitive.Root>
))
Progress.displayName = ProgressPrimitive.Root.displayName
export { Progress }

View File

@ -0,0 +1,42 @@
import * as React from "react"
import * as RadioGroupPrimitive from "@radix-ui/react-radio-group"
import { Circle } from "lucide-react"
import { cn } from "@/lib/utils"
const RadioGroup = React.forwardRef<
React.ElementRef<typeof RadioGroupPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof RadioGroupPrimitive.Root>
>(({ className, ...props }, ref) => {
return (
<RadioGroupPrimitive.Root
className={cn("grid gap-2", className)}
{...props}
ref={ref}
/>
)
})
RadioGroup.displayName = RadioGroupPrimitive.Root.displayName
const RadioGroupItem = React.forwardRef<
React.ElementRef<typeof RadioGroupPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof RadioGroupPrimitive.Item>
>(({ className, ...props }, ref) => {
return (
<RadioGroupPrimitive.Item
ref={ref}
className={cn(
"aspect-square h-4 w-4 rounded-full border border-primary text-primary shadow focus:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",
className
)}
{...props}
>
<RadioGroupPrimitive.Indicator className="flex items-center justify-center">
<Circle className="h-3.5 w-3.5 fill-primary" />
</RadioGroupPrimitive.Indicator>
</RadioGroupPrimitive.Item>
)
})
RadioGroupItem.displayName = RadioGroupPrimitive.Item.displayName
export { RadioGroup, RadioGroupItem }

View File

@ -0,0 +1,45 @@
"use client"
import { GripVertical } from "lucide-react"
import * as ResizablePrimitive from "react-resizable-panels"
import { cn } from "@/lib/utils"
const ResizablePanelGroup = ({
className,
...props
}: React.ComponentProps<typeof ResizablePrimitive.PanelGroup>) => (
<ResizablePrimitive.PanelGroup
className={cn(
"flex h-full w-full data-[panel-group-direction=vertical]:flex-col",
className
)}
{...props}
/>
)
const ResizablePanel = ResizablePrimitive.Panel
const ResizableHandle = ({
withHandle,
className,
...props
}: React.ComponentProps<typeof ResizablePrimitive.PanelResizeHandle> & {
withHandle?: boolean
}) => (
<ResizablePrimitive.PanelResizeHandle
className={cn(
"relative flex w-px items-center justify-center bg-border after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:-translate-y-1/2 data-[panel-group-direction=vertical]:after:translate-x-0 [&[data-panel-group-direction=vertical]>div]:rotate-90",
className
)}
{...props}
>
{withHandle && (
<div className="z-10 flex h-4 w-3 items-center justify-center rounded-sm border bg-border">
<GripVertical className="h-2.5 w-2.5" />
</div>
)}
</ResizablePrimitive.PanelResizeHandle>
)
export { ResizablePanelGroup, ResizablePanel, ResizableHandle }

View File

@ -0,0 +1,46 @@
import * as React from "react"
import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area"
import { cn } from "@/lib/utils"
const ScrollArea = React.forwardRef<
React.ElementRef<typeof ScrollAreaPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.Root>
>(({ className, children, ...props }, ref) => (
<ScrollAreaPrimitive.Root
ref={ref}
className={cn("relative overflow-hidden", className)}
{...props}
>
<ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]">
{children}
</ScrollAreaPrimitive.Viewport>
<ScrollBar />
<ScrollAreaPrimitive.Corner />
</ScrollAreaPrimitive.Root>
))
ScrollArea.displayName = ScrollAreaPrimitive.Root.displayName
const ScrollBar = React.forwardRef<
React.ElementRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>,
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>
>(({ className, orientation = "vertical", ...props }, ref) => (
<ScrollAreaPrimitive.ScrollAreaScrollbar
ref={ref}
orientation={orientation}
className={cn(
"flex touch-none select-none transition-colors",
orientation === "vertical" &&
"h-full w-2.5 border-l border-l-transparent p-[1px]",
orientation === "horizontal" &&
"h-2.5 flex-col border-t border-t-transparent p-[1px]",
className
)}
{...props}
>
<ScrollAreaPrimitive.ScrollAreaThumb className="relative flex-1 rounded-full bg-border" />
</ScrollAreaPrimitive.ScrollAreaScrollbar>
))
ScrollBar.displayName = ScrollAreaPrimitive.ScrollAreaScrollbar.displayName
export { ScrollArea, ScrollBar }

View File

@ -0,0 +1,159 @@
"use client"
import * as React from "react"
import * as SelectPrimitive from "@radix-ui/react-select"
import { Check, ChevronDown, ChevronUp } from "lucide-react"
import { cn } from "@/lib/utils"
const Select = SelectPrimitive.Root
const SelectGroup = SelectPrimitive.Group
const SelectValue = SelectPrimitive.Value
const SelectTrigger = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Trigger
ref={ref}
className={cn(
"flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background data-[placeholder]:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",
className
)}
{...props}
>
{children}
<SelectPrimitive.Icon asChild>
<ChevronDown className="h-4 w-4 opacity-50" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
))
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName
const SelectScrollUpButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollUpButton>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton>
>(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollUpButton
ref={ref}
className={cn(
"flex cursor-default items-center justify-center py-1",
className
)}
{...props}
>
<ChevronUp className="h-4 w-4" />
</SelectPrimitive.ScrollUpButton>
))
SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName
const SelectScrollDownButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollDownButton>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton>
>(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollDownButton
ref={ref}
className={cn(
"flex cursor-default items-center justify-center py-1",
className
)}
{...props}
>
<ChevronDown className="h-4 w-4" />
</SelectPrimitive.ScrollDownButton>
))
SelectScrollDownButton.displayName =
SelectPrimitive.ScrollDownButton.displayName
const SelectContent = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
>(({ className, children, position = "popper", ...props }, ref) => (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
ref={ref}
className={cn(
"relative z-50 max-h-[--radix-select-content-available-height] min-w-[8rem] overflow-y-auto overflow-x-hidden rounded-md border bg-popover text-popover-foreground shadow-md 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 origin-[--radix-select-content-transform-origin]",
position === "popper" &&
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
className
)}
position={position}
{...props}
>
<SelectScrollUpButton />
<SelectPrimitive.Viewport
className={cn(
"p-1",
position === "popper" &&
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"
)}
>
{children}
</SelectPrimitive.Viewport>
<SelectScrollDownButton />
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
))
SelectContent.displayName = SelectPrimitive.Content.displayName
const SelectLabel = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Label
ref={ref}
className={cn("px-2 py-1.5 text-sm font-semibold", className)}
{...props}
/>
))
SelectLabel.displayName = SelectPrimitive.Label.displayName
const SelectItem = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Item
ref={ref}
className={cn(
"relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
{...props}
>
<span className="absolute right-2 flex h-3.5 w-3.5 items-center justify-center">
<SelectPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</SelectPrimitive.ItemIndicator>
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
))
SelectItem.displayName = SelectPrimitive.Item.displayName
const SelectSeparator = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Separator
ref={ref}
className={cn("-mx-1 my-1 h-px bg-muted", className)}
{...props}
/>
))
SelectSeparator.displayName = SelectPrimitive.Separator.displayName
export {
Select,
SelectGroup,
SelectValue,
SelectTrigger,
SelectContent,
SelectLabel,
SelectItem,
SelectSeparator,
SelectScrollUpButton,
SelectScrollDownButton,
}

View File

@ -0,0 +1,29 @@
import * as React from "react"
import * as SeparatorPrimitive from "@radix-ui/react-separator"
import { cn } from "@/lib/utils"
const Separator = React.forwardRef<
React.ElementRef<typeof SeparatorPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof SeparatorPrimitive.Root>
>(
(
{ className, orientation = "horizontal", decorative = true, ...props },
ref
) => (
<SeparatorPrimitive.Root
ref={ref}
decorative={decorative}
orientation={orientation}
className={cn(
"shrink-0 bg-border",
orientation === "horizontal" ? "h-[1px] w-full" : "h-full w-[1px]",
className
)}
{...props}
/>
)
)
Separator.displayName = SeparatorPrimitive.Root.displayName
export { Separator }

View File

@ -0,0 +1,140 @@
"use client"
import * as React from "react"
import * as SheetPrimitive from "@radix-ui/react-dialog"
import { cva, type VariantProps } from "class-variance-authority"
import { X } from "lucide-react"
import { cn } from "@/lib/utils"
const Sheet = SheetPrimitive.Root
const SheetTrigger = SheetPrimitive.Trigger
const SheetClose = SheetPrimitive.Close
const SheetPortal = SheetPrimitive.Portal
const SheetOverlay = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<SheetPrimitive.Overlay
className={cn(
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className
)}
{...props}
ref={ref}
/>
))
SheetOverlay.displayName = SheetPrimitive.Overlay.displayName
const sheetVariants = cva(
"fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500 data-[state=open]:animate-in data-[state=closed]:animate-out",
{
variants: {
side: {
top: "inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",
bottom:
"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",
left: "inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",
right:
"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm",
},
},
defaultVariants: {
side: "right",
},
}
)
interface SheetContentProps
extends React.ComponentPropsWithoutRef<typeof SheetPrimitive.Content>,
VariantProps<typeof sheetVariants> {}
const SheetContent = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Content>,
SheetContentProps
>(({ side = "right", className, children, ...props }, ref) => (
<SheetPortal>
<SheetOverlay />
<SheetPrimitive.Content
ref={ref}
className={cn(sheetVariants({ side }), className)}
{...props}
>
<SheetPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</SheetPrimitive.Close>
{children}
</SheetPrimitive.Content>
</SheetPortal>
))
SheetContent.displayName = SheetPrimitive.Content.displayName
const SheetHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col space-y-2 text-center sm:text-left",
className
)}
{...props}
/>
)
SheetHeader.displayName = "SheetHeader"
const SheetFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
className
)}
{...props}
/>
)
SheetFooter.displayName = "SheetFooter"
const SheetTitle = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Title>
>(({ className, ...props }, ref) => (
<SheetPrimitive.Title
ref={ref}
className={cn("text-lg font-semibold text-foreground", className)}
{...props}
/>
))
SheetTitle.displayName = SheetPrimitive.Title.displayName
const SheetDescription = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Description>
>(({ className, ...props }, ref) => (
<SheetPrimitive.Description
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
SheetDescription.displayName = SheetPrimitive.Description.displayName
export {
Sheet,
SheetPortal,
SheetOverlay,
SheetTrigger,
SheetClose,
SheetContent,
SheetHeader,
SheetFooter,
SheetTitle,
SheetDescription,
}

View File

@ -0,0 +1,727 @@
"use client"
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, VariantProps } from "class-variance-authority"
import { PanelLeftIcon } from "lucide-react"
import { useIsMobile } from "@/hooks/use-mobile"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Separator } from "@/components/ui/separator"
import {
Sheet,
SheetContent,
SheetDescription,
SheetHeader,
SheetTitle,
} from "@/components/ui/sheet"
import { Skeleton } from "@/components/ui/skeleton"
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip"
const SIDEBAR_COOKIE_NAME = "sidebar_state"
const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7
const SIDEBAR_WIDTH = "16rem"
const SIDEBAR_WIDTH_MOBILE = "18rem"
const SIDEBAR_WIDTH_ICON = "3rem"
const SIDEBAR_KEYBOARD_SHORTCUT = "b"
type SidebarContextProps = {
state: "expanded" | "collapsed"
open: boolean
setOpen: (open: boolean) => void
openMobile: boolean
setOpenMobile: (open: boolean) => void
isMobile: boolean
toggleSidebar: () => void
}
const SidebarContext = React.createContext<SidebarContextProps | null>(null)
function useSidebar() {
const context = React.useContext(SidebarContext)
if (!context) {
throw new Error("useSidebar must be used within a SidebarProvider.")
}
return context
}
function SidebarProvider({
defaultOpen = true,
open: openProp,
onOpenChange: setOpenProp,
className,
style,
children,
...props
}: React.ComponentProps<"div"> & {
defaultOpen?: boolean
open?: boolean
onOpenChange?: (open: boolean) => void
}) {
const isMobile = useIsMobile()
const [openMobile, setOpenMobile] = React.useState(false)
// This is the internal state of the sidebar.
// We use openProp and setOpenProp for control from outside the component.
const [_open, _setOpen] = React.useState(defaultOpen)
const open = openProp ?? _open
const setOpen = React.useCallback(
(value: boolean | ((value: boolean) => boolean)) => {
const openState = typeof value === "function" ? value(open) : value
if (setOpenProp) {
setOpenProp(openState)
} else {
_setOpen(openState)
}
// This sets the cookie to keep the sidebar state.
document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`
},
[setOpenProp, open]
)
// Helper to toggle the sidebar.
const toggleSidebar = React.useCallback(() => {
return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open)
}, [isMobile, setOpen, setOpenMobile])
// Adds a keyboard shortcut to toggle the sidebar.
React.useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
if (
event.key === SIDEBAR_KEYBOARD_SHORTCUT &&
(event.metaKey || event.ctrlKey)
) {
event.preventDefault()
toggleSidebar()
}
}
window.addEventListener("keydown", handleKeyDown)
return () => window.removeEventListener("keydown", handleKeyDown)
}, [toggleSidebar])
// We add a state so that we can do data-state="expanded" or "collapsed".
// This makes it easier to style the sidebar with Tailwind classes.
const state = open ? "expanded" : "collapsed"
const contextValue = React.useMemo<SidebarContextProps>(
() => ({
state,
open,
setOpen,
isMobile,
openMobile,
setOpenMobile,
toggleSidebar,
}),
[state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar]
)
return (
<SidebarContext.Provider value={contextValue}>
<TooltipProvider delayDuration={0}>
<div
data-slot="sidebar-wrapper"
style={
{
"--sidebar-width": SIDEBAR_WIDTH,
"--sidebar-width-icon": SIDEBAR_WIDTH_ICON,
...style,
} as React.CSSProperties
}
className={cn(
"group/sidebar-wrapper has-data-[variant=inset]:bg-sidebar flex min-h-svh w-full",
className
)}
{...props}
>
{children}
</div>
</TooltipProvider>
</SidebarContext.Provider>
)
}
function Sidebar({
side = "left",
variant = "sidebar",
collapsible = "offcanvas",
className,
children,
...props
}: React.ComponentProps<"div"> & {
side?: "left" | "right"
variant?: "sidebar" | "floating" | "inset"
collapsible?: "offcanvas" | "icon" | "none"
}) {
const { isMobile, state, openMobile, setOpenMobile } = useSidebar()
if (collapsible === "none") {
return (
<div
data-slot="sidebar"
className={cn(
"bg-sidebar text-sidebar-foreground flex h-full w-[var(--sidebar-width)] flex-col",
className
)}
{...props}
>
{children}
</div>
)
}
if (isMobile) {
return (
<Sheet open={openMobile} onOpenChange={setOpenMobile} {...props}>
<SheetContent
data-sidebar="sidebar"
data-slot="sidebar"
data-mobile="true"
className="bg-sidebar text-sidebar-foreground w-[var(--sidebar-width)] p-0 [&>button]:hidden"
style={
{
"--sidebar-width": SIDEBAR_WIDTH_MOBILE,
} as React.CSSProperties
}
side={side}
>
<SheetHeader className="sr-only">
<SheetTitle>Sidebar</SheetTitle>
<SheetDescription>Displays the mobile sidebar.</SheetDescription>
</SheetHeader>
<div className="flex h-full w-full flex-col">{children}</div>
</SheetContent>
</Sheet>
)
}
return (
<div
className="group peer text-sidebar-foreground hidden md:block"
data-state={state}
data-collapsible={state === "collapsed" ? collapsible : ""}
data-variant={variant}
data-side={side}
data-slot="sidebar"
>
{/* This is what handles the sidebar gap on desktop */}
<div
data-slot="sidebar-gap"
className={cn(
"relative w-[var(--sidebar-width)] bg-transparent transition-[width] duration-200 ease-linear",
"group-data-[collapsible=offcanvas]:w-0",
"group-data-[side=right]:rotate-180",
variant === "floating" || variant === "inset"
? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+var(--spacing-4))]"
: "group-data-[collapsible=icon]:w-[var(--sidebar-width-icon)]"
)}
/>
<div
data-slot="sidebar-container"
className={cn(
"fixed inset-y-0 z-10 hidden h-svh w-[var(--sidebar-width)] transition-[left,right,width] duration-200 ease-linear md:flex",
side === "left"
? "left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]"
: "right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",
// Adjust the padding for floating and inset variants.
variant === "floating" || variant === "inset"
? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+var(--spacing-4)+2px)]"
: "group-data-[collapsible=icon]:w-[var(--sidebar-width-icon)] group-data-[side=left]:border-r group-data-[side=right]:border-l",
className
)}
{...props}
>
<div
data-sidebar="sidebar"
data-slot="sidebar-inner"
className="bg-sidebar group-data-[variant=floating]:border-sidebar-border flex h-full w-full flex-col group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:shadow-sm"
>
{children}
</div>
</div>
</div>
)
}
function SidebarTrigger({
className,
onClick,
...props
}: React.ComponentProps<typeof Button>) {
const { toggleSidebar } = useSidebar()
return (
<Button
data-sidebar="trigger"
data-slot="sidebar-trigger"
variant="ghost"
size="icon"
className={cn("h-7 w-7", className)}
onClick={(event) => {
onClick?.(event)
toggleSidebar()
}}
{...props}
>
<PanelLeftIcon />
<span className="sr-only">Toggle Sidebar</span>
</Button>
)
}
function SidebarRail({ className, ...props }: React.ComponentProps<"button">) {
const { toggleSidebar } = useSidebar()
// Note: Tailwind v3.4 doesn't support "in-" selectors. So the rail won't work perfectly.
return (
<button
data-sidebar="rail"
data-slot="sidebar-rail"
aria-label="Toggle Sidebar"
tabIndex={-1}
onClick={toggleSidebar}
title="Toggle Sidebar"
className={cn(
"hover:after:bg-sidebar-border absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear group-data-[side=left]:-right-4 group-data-[side=right]:left-0 after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] sm:flex",
"in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize",
"[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
"hover:group-data-[collapsible=offcanvas]:bg-sidebar group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full",
"[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
"[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
className
)}
{...props}
/>
)
}
function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {
return (
<main
data-slot="sidebar-inset"
className={cn(
"bg-background relative flex w-full flex-1 flex-col",
"md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2",
className
)}
{...props}
/>
)
}
function SidebarInput({
className,
...props
}: React.ComponentProps<typeof Input>) {
return (
<Input
data-slot="sidebar-input"
data-sidebar="input"
className={cn("bg-background h-8 w-full shadow-none", className)}
{...props}
/>
)
}
function SidebarHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-header"
data-sidebar="header"
className={cn("flex flex-col gap-2 p-2", className)}
{...props}
/>
)
}
function SidebarFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-footer"
data-sidebar="footer"
className={cn("flex flex-col gap-2 p-2", className)}
{...props}
/>
)
}
function SidebarSeparator({
className,
...props
}: React.ComponentProps<typeof Separator>) {
return (
<Separator
data-slot="sidebar-separator"
data-sidebar="separator"
className={cn("bg-sidebar-border mx-2 w-auto", className)}
{...props}
/>
)
}
function SidebarContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-content"
data-sidebar="content"
className={cn(
"flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",
className
)}
{...props}
/>
)
}
function SidebarGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-group"
data-sidebar="group"
className={cn("relative flex w-full min-w-0 flex-col p-2", className)}
{...props}
/>
)
}
function SidebarGroupLabel({
className,
asChild = false,
...props
}: React.ComponentProps<"div"> & { asChild?: boolean }) {
const Comp = asChild ? Slot : "div"
return (
<Comp
data-slot="sidebar-group-label"
data-sidebar="group-label"
className={cn(
"text-sidebar-foreground/70 ring-sidebar-ring flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium outline-hidden transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:h-4 [&>svg]:w-4 [&>svg]:shrink-0",
"group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",
className
)}
{...props}
/>
)
}
function SidebarGroupAction({
className,
asChild = false,
...props
}: React.ComponentProps<"button"> & { asChild?: boolean }) {
const Comp = asChild ? Slot : "button"
return (
<Comp
data-slot="sidebar-group-action"
data-sidebar="group-action"
className={cn(
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground absolute top-3.5 right-3 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
// Increases the hit area of the button on mobile.
"after:absolute after:-inset-2 md:after:hidden",
"group-data-[collapsible=icon]:hidden",
className
)}
{...props}
/>
)
}
function SidebarGroupContent({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-group-content"
data-sidebar="group-content"
className={cn("w-full text-sm", className)}
{...props}
/>
)
}
function SidebarMenu({ className, ...props }: React.ComponentProps<"ul">) {
return (
<ul
data-slot="sidebar-menu"
data-sidebar="menu"
className={cn("flex w-full min-w-0 flex-col gap-1", className)}
{...props}
/>
)
}
function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) {
return (
<li
data-slot="sidebar-menu-item"
data-sidebar="menu-item"
className={cn("group/menu-item relative", className)}
{...props}
/>
)
}
const sidebarMenuButtonVariants = cva(
"peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-hidden ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-data-[sidebar=menu-action]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:w-8! group-data-[collapsible=icon]:h-8! group-data-[collapsible=icon]:p-2! [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
{
variants: {
variant: {
default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
outline:
"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]",
},
size: {
default: "h-8 text-sm",
sm: "h-7 text-xs",
lg: "h-12 text-sm group-data-[collapsible=icon]:p-0!",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
function SidebarMenuButton({
asChild = false,
isActive = false,
variant = "default",
size = "default",
tooltip,
className,
...props
}: React.ComponentProps<"button"> & {
asChild?: boolean
isActive?: boolean
tooltip?: string | React.ComponentProps<typeof TooltipContent>
} & VariantProps<typeof sidebarMenuButtonVariants>) {
const Comp = asChild ? Slot : "button"
const { isMobile, state } = useSidebar()
const button = (
<Comp
data-slot="sidebar-menu-button"
data-sidebar="menu-button"
data-size={size}
data-active={isActive}
className={cn(sidebarMenuButtonVariants({ variant, size }), className)}
{...props}
/>
)
if (!tooltip) {
return button
}
if (typeof tooltip === "string") {
tooltip = {
children: tooltip,
}
}
return (
<Tooltip>
<TooltipTrigger asChild>{button}</TooltipTrigger>
<TooltipContent
side="right"
align="center"
hidden={state !== "collapsed" || isMobile}
{...tooltip}
/>
</Tooltip>
)
}
function SidebarMenuAction({
className,
asChild = false,
showOnHover = false,
...props
}: React.ComponentProps<"button"> & {
asChild?: boolean
showOnHover?: boolean
}) {
const Comp = asChild ? Slot : "button"
return (
<Comp
data-slot="sidebar-menu-action"
data-sidebar="menu-action"
className={cn(
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground peer-hover/menu-button:text-sidebar-accent-foreground absolute top-1.5 right-1 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
// Increases the hit area of the button on mobile.
"after:absolute after:-inset-2 md:after:hidden",
"peer-data-[size=sm]/menu-button:top-1",
"peer-data-[size=default]/menu-button:top-1.5",
"peer-data-[size=lg]/menu-button:top-2.5",
"group-data-[collapsible=icon]:hidden",
showOnHover &&
"peer-data-[active=true]/menu-button:text-sidebar-accent-foreground group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 md:opacity-0",
className
)}
{...props}
/>
)
}
function SidebarMenuBadge({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-menu-badge"
data-sidebar="menu-badge"
className={cn(
"text-sidebar-foreground pointer-events-none absolute right-1 flex h-5 min-w-5 items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums select-none",
"peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground",
"peer-data-[size=sm]/menu-button:top-1",
"peer-data-[size=default]/menu-button:top-1.5",
"peer-data-[size=lg]/menu-button:top-2.5",
"group-data-[collapsible=icon]:hidden",
className
)}
{...props}
/>
)
}
function SidebarMenuSkeleton({
className,
showIcon = false,
...props
}: React.ComponentProps<"div"> & {
showIcon?: boolean
}) {
// Random width between 50 to 90%.
const width = React.useMemo(() => {
return `${Math.floor(Math.random() * 40) + 50}%`
}, [])
return (
<div
data-slot="sidebar-menu-skeleton"
data-sidebar="menu-skeleton"
className={cn("flex h-8 items-center gap-2 rounded-md px-2", className)}
{...props}
>
{showIcon && (
<Skeleton
className="size-4 rounded-md"
data-sidebar="menu-skeleton-icon"
/>
)}
<Skeleton
className="h-4 max-w-[var(--skeleton-width)] flex-1"
data-sidebar="menu-skeleton-text"
style={
{
"--skeleton-width": width,
} as React.CSSProperties
}
/>
</div>
)
}
function SidebarMenuSub({ className, ...props }: React.ComponentProps<"ul">) {
return (
<ul
data-slot="sidebar-menu-sub"
data-sidebar="menu-sub"
className={cn(
"border-sidebar-border mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l px-2.5 py-0.5",
"group-data-[collapsible=icon]:hidden",
className
)}
{...props}
/>
)
}
function SidebarMenuSubItem({
className,
...props
}: React.ComponentProps<"li">) {
return (
<li
data-slot="sidebar-menu-sub-item"
data-sidebar="menu-sub-item"
className={cn("group/menu-sub-item relative", className)}
{...props}
/>
)
}
function SidebarMenuSubButton({
asChild = false,
size = "md",
isActive = false,
className,
...props
}: React.ComponentProps<"a"> & {
asChild?: boolean
size?: "sm" | "md"
isActive?: boolean
}) {
const Comp = asChild ? Slot : "a"
return (
<Comp
data-slot="sidebar-menu-sub-button"
data-sidebar="menu-sub-button"
data-size={size}
data-active={isActive}
className={cn(
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground active:bg-sidebar-accent active:text-sidebar-accent-foreground [&>svg]:text-sidebar-accent-foreground flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 outline outline-2 outline-transparent outline-offset-2 focus-visible:ring-2 disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
"data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",
size === "sm" && "text-xs",
size === "md" && "text-sm",
"group-data-[collapsible=icon]:hidden",
className
)}
{...props}
/>
)
}
export {
Sidebar,
SidebarContent,
SidebarFooter,
SidebarGroup,
SidebarGroupAction,
SidebarGroupContent,
SidebarGroupLabel,
SidebarHeader,
SidebarInput,
SidebarInset,
SidebarMenu,
SidebarMenuAction,
SidebarMenuBadge,
SidebarMenuButton,
SidebarMenuItem,
SidebarMenuSkeleton,
SidebarMenuSub,
SidebarMenuSubButton,
SidebarMenuSubItem,
SidebarProvider,
SidebarRail,
SidebarSeparator,
SidebarTrigger,
useSidebar,
}

View File

@ -0,0 +1,15 @@
import { cn } from "@/lib/utils"
function Skeleton({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) {
return (
<div
className={cn("animate-pulse rounded-md bg-primary/10", className)}
{...props}
/>
)
}
export { Skeleton }

View File

@ -0,0 +1,26 @@
import * as React from "react"
import * as SliderPrimitive from "@radix-ui/react-slider"
import { cn } from "@/lib/utils"
const Slider = React.forwardRef<
React.ElementRef<typeof SliderPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof SliderPrimitive.Root>
>(({ className, ...props }, ref) => (
<SliderPrimitive.Root
ref={ref}
className={cn(
"relative flex w-full touch-none select-none items-center",
className
)}
{...props}
>
<SliderPrimitive.Track className="relative h-1.5 w-full grow overflow-hidden rounded-full bg-primary/20">
<SliderPrimitive.Range className="absolute h-full bg-primary" />
</SliderPrimitive.Track>
<SliderPrimitive.Thumb className="block h-4 w-4 rounded-full border border-primary/50 bg-background shadow transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50" />
</SliderPrimitive.Root>
))
Slider.displayName = SliderPrimitive.Root.displayName
export { Slider }

View File

@ -0,0 +1,31 @@
"use client"
import { useTheme } from "next-themes"
import { Toaster as Sonner } from "sonner"
type ToasterProps = React.ComponentProps<typeof Sonner>
const Toaster = ({ ...props }: ToasterProps) => {
const { theme = "system" } = useTheme()
return (
<Sonner
theme={theme as ToasterProps["theme"]}
className="toaster group"
toastOptions={{
classNames: {
toast:
"group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",
description: "group-[.toast]:text-muted-foreground",
actionButton:
"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",
cancelButton:
"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground",
},
}}
{...props}
/>
)
}
export { Toaster }

View File

@ -0,0 +1,16 @@
import { Loader2Icon } from "lucide-react"
import { cn } from "@/lib/utils"
function Spinner({ className, ...props }: React.ComponentProps<"svg">) {
return (
<Loader2Icon
role="status"
aria-label="Loading"
className={cn("size-4 animate-spin", className)}
{...props}
/>
)
}
export { Spinner }

View File

@ -0,0 +1,27 @@
import * as React from "react"
import * as SwitchPrimitives from "@radix-ui/react-switch"
import { cn } from "@/lib/utils"
const Switch = React.forwardRef<
React.ElementRef<typeof SwitchPrimitives.Root>,
React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root>
>(({ className, ...props }, ref) => (
<SwitchPrimitives.Root
className={cn(
"peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",
className
)}
{...props}
ref={ref}
>
<SwitchPrimitives.Thumb
className={cn(
"pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0"
)}
/>
</SwitchPrimitives.Root>
))
Switch.displayName = SwitchPrimitives.Root.displayName
export { Switch }

View File

@ -0,0 +1,120 @@
import * as React from "react"
import { cn } from "@/lib/utils"
const Table = React.forwardRef<
HTMLTableElement,
React.HTMLAttributes<HTMLTableElement>
>(({ className, ...props }, ref) => (
<div className="relative w-full overflow-auto">
<table
ref={ref}
className={cn("w-full caption-bottom text-sm", className)}
{...props}
/>
</div>
))
Table.displayName = "Table"
const TableHeader = React.forwardRef<
HTMLTableSectionElement,
React.HTMLAttributes<HTMLTableSectionElement>
>(({ className, ...props }, ref) => (
<thead ref={ref} className={cn("[&_tr]:border-b", className)} {...props} />
))
TableHeader.displayName = "TableHeader"
const TableBody = React.forwardRef<
HTMLTableSectionElement,
React.HTMLAttributes<HTMLTableSectionElement>
>(({ className, ...props }, ref) => (
<tbody
ref={ref}
className={cn("[&_tr:last-child]:border-0", className)}
{...props}
/>
))
TableBody.displayName = "TableBody"
const TableFooter = React.forwardRef<
HTMLTableSectionElement,
React.HTMLAttributes<HTMLTableSectionElement>
>(({ className, ...props }, ref) => (
<tfoot
ref={ref}
className={cn(
"border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",
className
)}
{...props}
/>
))
TableFooter.displayName = "TableFooter"
const TableRow = React.forwardRef<
HTMLTableRowElement,
React.HTMLAttributes<HTMLTableRowElement>
>(({ className, ...props }, ref) => (
<tr
ref={ref}
className={cn(
"border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",
className
)}
{...props}
/>
))
TableRow.displayName = "TableRow"
const TableHead = React.forwardRef<
HTMLTableCellElement,
React.ThHTMLAttributes<HTMLTableCellElement>
>(({ className, ...props }, ref) => (
<th
ref={ref}
className={cn(
"h-10 px-2 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className
)}
{...props}
/>
))
TableHead.displayName = "TableHead"
const TableCell = React.forwardRef<
HTMLTableCellElement,
React.TdHTMLAttributes<HTMLTableCellElement>
>(({ className, ...props }, ref) => (
<td
ref={ref}
className={cn(
"p-2 align-middle [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className
)}
{...props}
/>
))
TableCell.displayName = "TableCell"
const TableCaption = React.forwardRef<
HTMLTableCaptionElement,
React.HTMLAttributes<HTMLTableCaptionElement>
>(({ className, ...props }, ref) => (
<caption
ref={ref}
className={cn("mt-4 text-sm text-muted-foreground", className)}
{...props}
/>
))
TableCaption.displayName = "TableCaption"
export {
Table,
TableHeader,
TableBody,
TableFooter,
TableHead,
TableRow,
TableCell,
TableCaption,
}

View File

@ -0,0 +1,53 @@
import * as React from "react"
import * as TabsPrimitive from "@radix-ui/react-tabs"
import { cn } from "@/lib/utils"
const Tabs = TabsPrimitive.Root
const TabsList = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.List>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.List>
>(({ className, ...props }, ref) => (
<TabsPrimitive.List
ref={ref}
className={cn(
"inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",
className
)}
{...props}
/>
))
TabsList.displayName = TabsPrimitive.List.displayName
const TabsTrigger = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Trigger>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Trigger
ref={ref}
className={cn(
"inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow",
className
)}
{...props}
/>
))
TabsTrigger.displayName = TabsPrimitive.Trigger.displayName
const TabsContent = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Content>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Content
ref={ref}
className={cn(
"mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
className
)}
{...props}
/>
))
TabsContent.displayName = TabsPrimitive.Content.displayName
export { Tabs, TabsList, TabsTrigger, TabsContent }

View File

@ -0,0 +1,22 @@
import * as React from "react"
import { cn } from "@/lib/utils"
const Textarea = React.forwardRef<
HTMLTextAreaElement,
React.ComponentProps<"textarea">
>(({ className, ...props }, ref) => {
return (
<textarea
className={cn(
"flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-base shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
className
)}
ref={ref}
{...props}
/>
)
})
Textarea.displayName = "Textarea"
export { Textarea }

View File

@ -0,0 +1,127 @@
import * as React from "react"
import * as ToastPrimitives from "@radix-ui/react-toast"
import { cva, type VariantProps } from "class-variance-authority"
import { X } from "lucide-react"
import { cn } from "@/lib/utils"
const ToastProvider = ToastPrimitives.Provider
const ToastViewport = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Viewport>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Viewport>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Viewport
ref={ref}
className={cn(
"fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",
className
)}
{...props}
/>
))
ToastViewport.displayName = ToastPrimitives.Viewport.displayName
const toastVariants = cva(
"group pointer-events-auto relative flex w-full items-center justify-between space-x-4 overflow-hidden rounded-md border p-6 pr-8 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",
{
variants: {
variant: {
default: "border bg-background text-foreground",
destructive:
"destructive group border-destructive bg-destructive text-destructive-foreground",
},
},
defaultVariants: {
variant: "default",
},
}
)
const Toast = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Root>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Root> &
VariantProps<typeof toastVariants>
>(({ className, variant, ...props }, ref) => {
return (
<ToastPrimitives.Root
ref={ref}
className={cn(toastVariants({ variant }), className)}
{...props}
/>
)
})
Toast.displayName = ToastPrimitives.Root.displayName
const ToastAction = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Action>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Action>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Action
ref={ref}
className={cn(
"inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium ring-offset-background transition-colors hover:bg-secondary focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",
className
)}
{...props}
/>
))
ToastAction.displayName = ToastPrimitives.Action.displayName
const ToastClose = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Close>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Close>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Close
ref={ref}
className={cn(
"absolute right-2 top-2 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-2 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",
className
)}
toast-close=""
{...props}
>
<X className="h-4 w-4" />
</ToastPrimitives.Close>
))
ToastClose.displayName = ToastPrimitives.Close.displayName
const ToastTitle = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Title>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Title>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Title
ref={ref}
className={cn("text-sm font-semibold", className)}
{...props}
/>
))
ToastTitle.displayName = ToastPrimitives.Title.displayName
const ToastDescription = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Description>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Description>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Description
ref={ref}
className={cn("text-sm opacity-90", className)}
{...props}
/>
))
ToastDescription.displayName = ToastPrimitives.Description.displayName
type ToastProps = React.ComponentPropsWithoutRef<typeof Toast>
type ToastActionElement = React.ReactElement<typeof ToastAction>
export {
type ToastProps,
type ToastActionElement,
ToastProvider,
ToastViewport,
Toast,
ToastTitle,
ToastDescription,
ToastClose,
ToastAction,
}

View File

@ -0,0 +1,33 @@
import { useToast } from "@/hooks/use-toast"
import {
Toast,
ToastClose,
ToastDescription,
ToastProvider,
ToastTitle,
ToastViewport,
} from "@/components/ui/toast"
export function Toaster() {
const { toasts } = useToast()
return (
<ToastProvider>
{toasts.map(function ({ id, title, description, action, ...props }) {
return (
<Toast key={id} {...props}>
<div className="grid gap-1">
{title && <ToastTitle>{title}</ToastTitle>}
{description && (
<ToastDescription>{description}</ToastDescription>
)}
</div>
{action}
<ToastClose />
</Toast>
)
})}
<ToastViewport />
</ToastProvider>
)
}

View File

@ -0,0 +1,61 @@
"use client"
import * as React from "react"
import * as ToggleGroupPrimitive from "@radix-ui/react-toggle-group"
import { type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
import { toggleVariants } from "@/components/ui/toggle"
const ToggleGroupContext = React.createContext<
VariantProps<typeof toggleVariants>
>({
size: "default",
variant: "default",
})
const ToggleGroup = React.forwardRef<
React.ElementRef<typeof ToggleGroupPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof ToggleGroupPrimitive.Root> &
VariantProps<typeof toggleVariants>
>(({ className, variant, size, children, ...props }, ref) => (
<ToggleGroupPrimitive.Root
ref={ref}
className={cn("flex items-center justify-center gap-1", className)}
{...props}
>
<ToggleGroupContext.Provider value={{ variant, size }}>
{children}
</ToggleGroupContext.Provider>
</ToggleGroupPrimitive.Root>
))
ToggleGroup.displayName = ToggleGroupPrimitive.Root.displayName
const ToggleGroupItem = React.forwardRef<
React.ElementRef<typeof ToggleGroupPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof ToggleGroupPrimitive.Item> &
VariantProps<typeof toggleVariants>
>(({ className, children, variant, size, ...props }, ref) => {
const context = React.useContext(ToggleGroupContext)
return (
<ToggleGroupPrimitive.Item
ref={ref}
className={cn(
toggleVariants({
variant: context.variant || variant,
size: context.size || size,
}),
className
)}
{...props}
>
{children}
</ToggleGroupPrimitive.Item>
)
})
ToggleGroupItem.displayName = ToggleGroupPrimitive.Item.displayName
export { ToggleGroup, ToggleGroupItem }

View File

@ -0,0 +1,43 @@
import * as React from "react"
import * as TogglePrimitive from "@radix-ui/react-toggle"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const toggleVariants = cva(
"inline-flex items-center justify-center gap-2 rounded-md text-sm font-medium transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
{
variants: {
variant: {
default: "bg-transparent",
outline:
"border border-input bg-transparent shadow-sm hover:bg-accent hover:text-accent-foreground",
},
size: {
default: "h-9 px-2 min-w-9",
sm: "h-8 px-1.5 min-w-8",
lg: "h-10 px-2.5 min-w-10",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
const Toggle = React.forwardRef<
React.ElementRef<typeof TogglePrimitive.Root>,
React.ComponentPropsWithoutRef<typeof TogglePrimitive.Root> &
VariantProps<typeof toggleVariants>
>(({ className, variant, size, ...props }, ref) => (
<TogglePrimitive.Root
ref={ref}
className={cn(toggleVariants({ variant, size, className }))}
{...props}
/>
))
Toggle.displayName = TogglePrimitive.Root.displayName
export { Toggle, toggleVariants }

View File

@ -0,0 +1,32 @@
"use client"
import * as React from "react"
import * as TooltipPrimitive from "@radix-ui/react-tooltip"
import { cn } from "@/lib/utils"
const TooltipProvider = TooltipPrimitive.Provider
const Tooltip = TooltipPrimitive.Root
const TooltipTrigger = TooltipPrimitive.Trigger
const TooltipContent = React.forwardRef<
React.ElementRef<typeof TooltipPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content>
>(({ className, sideOffset = 4, ...props }, ref) => (
<TooltipPrimitive.Portal>
<TooltipPrimitive.Content
ref={ref}
sideOffset={sideOffset}
className={cn(
"z-50 overflow-hidden rounded-md bg-primary px-3 py-1.5 text-xs text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-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 origin-[--radix-tooltip-content-transform-origin]",
className
)}
{...props}
/>
</TooltipPrimitive.Portal>
))
TooltipContent.displayName = TooltipPrimitive.Content.displayName
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }

View File

@ -0,0 +1,52 @@
import { createContext, useContext, useState, useEffect, ReactNode } from "react";
export type ErpProfile = "plus" | "erpnext";
interface ErpProfileContextType {
profile: ErpProfile;
setProfile: (profile: ErpProfile) => void;
usePlus: boolean;
useERPNext: boolean;
getApiUrl: (localPath: string, plusPath: string, erpnextPath?: string) => string;
}
const ErpProfileContext = createContext<ErpProfileContextType | null>(null);
export function ErpProfileProvider({ children }: { children: ReactNode }) {
const [profile, setProfileState] = useState<ErpProfile>(() => {
const saved = localStorage.getItem("arcadia_erp_profile");
return (saved as ErpProfile) || "plus";
});
const setProfile = (newProfile: ErpProfile) => {
setProfileState(newProfile);
localStorage.setItem("arcadia_erp_profile", newProfile);
};
const usePlus = profile === "plus";
const useERPNext = profile === "erpnext";
const getApiUrl = (localPath: string, plusPath: string, erpnextPath?: string): string => {
if (usePlus) {
return `/plus/api${plusPath}`;
}
if (useERPNext && erpnextPath) {
return erpnextPath;
}
return localPath;
};
return (
<ErpProfileContext.Provider value={{ profile, setProfile, usePlus, useERPNext, getApiUrl }}>
{children}
</ErpProfileContext.Provider>
);
}
export function useErpProfile() {
const context = useContext(ErpProfileContext);
if (!context) {
throw new Error("useErpProfile must be used within ErpProfileProvider");
}
return context;
}

View File

@ -0,0 +1,110 @@
import { createContext, ReactNode, useContext } from "react";
import {
useQuery,
useMutation,
UseMutationResult,
} from "@tanstack/react-query";
import { type User, type InsertUser } from "@shared/schema";
import { getQueryFn, apiRequest, queryClient } from "../lib/queryClient";
import { useToast } from "@/hooks/use-toast";
type AuthContextType = {
user: User | null;
isLoading: boolean;
error: Error | null;
loginMutation: UseMutationResult<User, Error, LoginData>;
logoutMutation: UseMutationResult<void, Error, void>;
registerMutation: UseMutationResult<User, Error, InsertUser>;
};
type LoginData = Pick<InsertUser, "username" | "password">;
export const AuthContext = createContext<AuthContextType | null>(null);
export function AuthProvider({ children }: { children: ReactNode }) {
const { toast } = useToast();
const {
data: user,
error,
isLoading,
} = useQuery<User | undefined, Error>({
queryKey: ["/api/user"],
queryFn: getQueryFn({ on401: "returnNull" }),
});
const loginMutation = useMutation({
mutationFn: async (credentials: LoginData) => {
const res = await apiRequest("POST", "/api/login", credentials);
return await res.json();
},
onSuccess: (user: User) => {
queryClient.setQueryData(["/api/user"], user);
queryClient.invalidateQueries({ queryKey: ["applications"] });
},
onError: (error: Error) => {
toast({
title: "Login failed",
description: "Invalid username or password",
variant: "destructive",
});
},
});
const registerMutation = useMutation({
mutationFn: async (credentials: InsertUser) => {
const res = await apiRequest("POST", "/api/register", credentials);
return await res.json();
},
onSuccess: (user: User) => {
queryClient.setQueryData(["/api/user"], user);
queryClient.invalidateQueries({ queryKey: ["applications"] });
},
onError: (error: Error) => {
toast({
title: "Registration failed",
description: error.message.includes("400") ? "Username already exists" : error.message,
variant: "destructive",
});
},
});
const logoutMutation = useMutation({
mutationFn: async () => {
await apiRequest("POST", "/api/logout");
},
onSuccess: () => {
queryClient.setQueryData(["/api/user"], null);
queryClient.invalidateQueries({ queryKey: ["applications"] });
},
onError: (error: Error) => {
toast({
title: "Logout failed",
description: error.message,
variant: "destructive",
});
},
});
return (
<AuthContext.Provider
value={{
user: user ?? null,
isLoading,
error,
loginMutation,
logoutMutation,
registerMutation,
}}
>
{children}
</AuthContext.Provider>
);
}
export function useAuth() {
const context = useContext(AuthContext);
if (!context) {
throw new Error("useAuth must be used within an AuthProvider");
}
return context;
}

View File

@ -0,0 +1,51 @@
import { useEffect } from "react";
import { useAuth } from "./use-auth";
import { knowledgeCollector, initKnowledgeCollector } from "@/lib/knowledge-collector";
export function useKnowledgeCollector() {
const { user } = useAuth();
useEffect(() => {
if (user) {
initKnowledgeCollector();
}
}, [user]);
return {
trackPageView: (pageName: string, route?: string) => {
if (user) knowledgeCollector.trackPageView(pageName, route);
},
trackAppOpen: (appName: string, appUrl?: string, category?: string) => {
if (user) knowledgeCollector.trackAppOpen(appName, appUrl, category);
},
trackSiteNavigation: (siteName: string, url: string) => {
if (user) knowledgeCollector.trackSiteNavigation(siteName, url);
},
trackSearch: (query: string, module: string, resultsCount?: number) => {
if (user) knowledgeCollector.trackSearch(query, module, resultsCount);
},
trackFormSubmit: (formName: string, module: string, fields?: string[]) => {
if (user) knowledgeCollector.trackFormSubmit(formName, module, fields);
},
trackButtonClick: (buttonName: string, module: string, context?: Record<string, any>) => {
if (user) knowledgeCollector.trackButtonClick(buttonName, module, context);
},
trackFileOpen: (fileName: string, fileType: string, source?: string) => {
if (user) knowledgeCollector.trackFileOpen(fileName, fileType, source);
},
trackDocumentView: (docName: string, docType: string, source?: string) => {
if (user) knowledgeCollector.trackDocumentView(docName, docType, source);
},
trackFeatureUse: (feature: string, module: string, details?: Record<string, any>) => {
if (user) knowledgeCollector.trackFeatureUse(feature, module, details);
},
trackContentCapture: (url: string, title: string, wordCount: number) => {
if (user) knowledgeCollector.trackContentCapture(url, title, wordCount);
},
trackIframeInteraction: (appName: string, url: string, interactionType: string) => {
if (user) knowledgeCollector.trackIframeInteraction(appName, url, interactionType);
},
getSessionId: () => knowledgeCollector.getSessionId(),
getQueueSize: () => knowledgeCollector.getQueueSize(),
};
}

View File

@ -0,0 +1,19 @@
import * as React from "react"
const MOBILE_BREAKPOINT = 768
export function useIsMobile() {
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined)
React.useEffect(() => {
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`)
const onChange = () => {
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
}
mql.addEventListener("change", onChange)
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
return () => mql.removeEventListener("change", onChange)
}, [])
return !!isMobile
}

View File

@ -0,0 +1,141 @@
import { useCallback, useRef } from "react";
import { useAuth } from "./use-auth";
interface TrackingData {
module: string;
action: string;
metadata?: Record<string, any>;
}
const DEBOUNCE_MS = 2000;
export function useNavigationTracking() {
const { user } = useAuth();
const lastTrack = useRef<string>("");
const lastTime = useRef<number>(0);
const track = useCallback(async (data: TrackingData) => {
if (!user) return;
const key = `${data.module}:${data.action}:${JSON.stringify(data.metadata || {})}`;
const now = Date.now();
if (key === lastTrack.current && now - lastTime.current < DEBOUNCE_MS) {
return;
}
lastTrack.current = key;
lastTime.current = now;
try {
await fetch("/api/learning/navigation", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
credentials: "include",
});
} catch (error) {
console.debug("[Tracking] Navigation track failed:", error);
}
}, [user]);
const trackPageView = useCallback((pageName: string, route?: string) => {
track({
module: pageName,
action: "page_view",
metadata: { route, timestamp: new Date().toISOString() },
});
}, [track]);
const trackAppOpen = useCallback((appName: string, appUrl?: string, category?: string) => {
track({
module: "applications",
action: "app_open",
metadata: { appName, appUrl, category, timestamp: new Date().toISOString() },
});
}, [track]);
const trackSiteNavigation = useCallback((siteName: string, url: string, domain?: string) => {
const extractedDomain = domain || new URL(url).hostname;
track({
module: "browser",
action: "site_navigation",
metadata: {
siteName,
url,
domain: extractedDomain,
timestamp: new Date().toISOString()
},
});
}, [track]);
const trackFeatureUse = useCallback((feature: string, details?: Record<string, any>) => {
track({
module: feature,
action: "feature_use",
metadata: { ...details, timestamp: new Date().toISOString() },
});
}, [track]);
const trackSearch = useCallback((query: string, module: string, resultsCount?: number) => {
track({
module,
action: "search",
metadata: { query, resultsCount, timestamp: new Date().toISOString() },
});
}, [track]);
const trackDocumentView = useCallback((docName: string, docType: string, source?: string) => {
track({
module: "documents",
action: "document_view",
metadata: { docName, docType, source, timestamp: new Date().toISOString() },
});
}, [track]);
const trackDigitalBook = useCallback((bookTitle: string, author?: string, chapter?: string) => {
track({
module: "digital_library",
action: "book_read",
metadata: { bookTitle, author, chapter, timestamp: new Date().toISOString() },
});
}, [track]);
const trackExternalConsult = useCallback((appName: string, consultType: string, query?: string) => {
track({
module: "external_consult",
action: "consult",
metadata: { appName, consultType, query, timestamp: new Date().toISOString() },
});
}, [track]);
const trackIframeInteraction = useCallback((appName: string, url: string, interactionType: string) => {
track({
module: "iframe_browser",
action: interactionType,
metadata: { appName, url, timestamp: new Date().toISOString() },
});
}, [track]);
const trackContentConsumption = useCallback((contentType: string, contentTitle: string, source: string, duration?: number) => {
track({
module: "content_consumption",
action: "consume",
metadata: { contentType, contentTitle, source, duration, timestamp: new Date().toISOString() },
});
}, [track]);
return {
track,
trackPageView,
trackAppOpen,
trackSiteNavigation,
trackFeatureUse,
trackSearch,
trackDocumentView,
trackDigitalBook,
trackExternalConsult,
trackIframeInteraction,
trackContentConsumption,
};
}

View File

@ -0,0 +1,191 @@
import * as React from "react"
import type {
ToastActionElement,
ToastProps,
} from "@/components/ui/toast"
const TOAST_LIMIT = 1
const TOAST_REMOVE_DELAY = 1000000
type ToasterToast = ToastProps & {
id: string
title?: React.ReactNode
description?: React.ReactNode
action?: ToastActionElement
}
const actionTypes = {
ADD_TOAST: "ADD_TOAST",
UPDATE_TOAST: "UPDATE_TOAST",
DISMISS_TOAST: "DISMISS_TOAST",
REMOVE_TOAST: "REMOVE_TOAST",
} as const
let count = 0
function genId() {
count = (count + 1) % Number.MAX_SAFE_INTEGER
return count.toString()
}
type ActionType = typeof actionTypes
type Action =
| {
type: ActionType["ADD_TOAST"]
toast: ToasterToast
}
| {
type: ActionType["UPDATE_TOAST"]
toast: Partial<ToasterToast>
}
| {
type: ActionType["DISMISS_TOAST"]
toastId?: ToasterToast["id"]
}
| {
type: ActionType["REMOVE_TOAST"]
toastId?: ToasterToast["id"]
}
interface State {
toasts: ToasterToast[]
}
const toastTimeouts = new Map<string, ReturnType<typeof setTimeout>>()
const addToRemoveQueue = (toastId: string) => {
if (toastTimeouts.has(toastId)) {
return
}
const timeout = setTimeout(() => {
toastTimeouts.delete(toastId)
dispatch({
type: "REMOVE_TOAST",
toastId: toastId,
})
}, TOAST_REMOVE_DELAY)
toastTimeouts.set(toastId, timeout)
}
export const reducer = (state: State, action: Action): State => {
switch (action.type) {
case "ADD_TOAST":
return {
...state,
toasts: [action.toast, ...state.toasts].slice(0, TOAST_LIMIT),
}
case "UPDATE_TOAST":
return {
...state,
toasts: state.toasts.map((t) =>
t.id === action.toast.id ? { ...t, ...action.toast } : t
),
}
case "DISMISS_TOAST": {
const { toastId } = action
// ! Side effects ! - This could be extracted into a dismissToast() action,
// but I'll keep it here for simplicity
if (toastId) {
addToRemoveQueue(toastId)
} else {
state.toasts.forEach((toast) => {
addToRemoveQueue(toast.id)
})
}
return {
...state,
toasts: state.toasts.map((t) =>
t.id === toastId || toastId === undefined
? {
...t,
open: false,
}
: t
),
}
}
case "REMOVE_TOAST":
if (action.toastId === undefined) {
return {
...state,
toasts: [],
}
}
return {
...state,
toasts: state.toasts.filter((t) => t.id !== action.toastId),
}
}
}
const listeners: Array<(state: State) => void> = []
let memoryState: State = { toasts: [] }
function dispatch(action: Action) {
memoryState = reducer(memoryState, action)
listeners.forEach((listener) => {
listener(memoryState)
})
}
type Toast = Omit<ToasterToast, "id">
function toast({ ...props }: Toast) {
const id = genId()
const update = (props: ToasterToast) =>
dispatch({
type: "UPDATE_TOAST",
toast: { ...props, id },
})
const dismiss = () => dispatch({ type: "DISMISS_TOAST", toastId: id })
dispatch({
type: "ADD_TOAST",
toast: {
...props,
id,
open: true,
onOpenChange: (open) => {
if (!open) dismiss()
},
},
})
return {
id: id,
dismiss,
update,
}
}
function useToast() {
const [state, setState] = React.useState<State>(memoryState)
React.useEffect(() => {
listeners.push(setState)
return () => {
const index = listeners.indexOf(setState)
if (index > -1) {
listeners.splice(index, 1)
}
}
}, [state])
return {
...state,
toast,
dismiss: (toastId?: string) => dispatch({ type: "DISMISS_TOAST", toastId }),
}
}
export { useToast, toast }

67
client/src/index.css Normal file
View File

@ -0,0 +1,67 @@
@import "tailwindcss";
@import "tw-animate-css";
@custom-variant dark (&:is(.dark *));
@theme inline {
--font-sans: 'Inter', sans-serif;
--font-mono: 'JetBrains Mono', monospace;
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
--color-background: hsl(220 20% 97%);
--color-foreground: hsl(220 40% 10%);
--color-card: hsl(0 0% 100%);
--color-card-foreground: hsl(220 40% 10%);
--color-popover: hsl(0 0% 100%);
--color-popover-foreground: hsl(220 40% 10%);
--color-primary: hsl(215 90% 52%);
--color-primary-foreground: hsl(0 0% 100%);
--color-secondary: hsl(220 15% 92%);
--color-secondary-foreground: hsl(220 40% 10%);
--color-muted: hsl(220 15% 92%);
--color-muted-foreground: hsl(220 10% 45%);
--color-accent: hsl(215 90% 96%);
--color-accent-foreground: hsl(215 90% 35%);
--color-destructive: hsl(0 84% 60%);
--color-destructive-foreground: hsl(0 0% 98%);
--color-border: hsl(220 15% 90%);
--color-input: hsl(220 15% 90%);
--color-ring: hsl(215 90% 52%);
--radius: 0.5rem;
}
@layer base {
* {
@apply border-border;
}
body {
@apply font-sans antialiased bg-background text-foreground overflow-hidden;
/* Prevent default scroll, let the 'browser' handle it */
}
#root {
@apply h-screen w-screen flex flex-col;
}
}
@layer utilities {
.scrollbar-hide {
-ms-overflow-style: none;
scrollbar-width: none;
}
.scrollbar-hide::-webkit-scrollbar {
display: none;
}
}

View File

@ -0,0 +1,274 @@
type EventType =
| 'page_view'
| 'page_dwell'
| 'app_open'
| 'site_navigation'
| 'search'
| 'form_submit'
| 'button_click'
| 'file_open'
| 'document_view'
| 'feature_use'
| 'content_capture'
| 'iframe_interaction';
interface CollectorEvent {
type: EventType;
module: string;
data: Record<string, any>;
timestamp: number;
sessionId: string;
}
interface DwellTracker {
url: string;
startTime: number;
module: string;
}
class KnowledgeCollector {
private queue: CollectorEvent[] = [];
private flushInterval = 5000;
private flushTimer: ReturnType<typeof setInterval> | null = null;
private sessionId: string;
private dwellTracker: DwellTracker | null = null;
private dwellThreshold = 30000;
private isInitialized = false;
constructor() {
this.sessionId = this.generateSessionId();
}
init() {
if (this.isInitialized) return;
this.isInitialized = true;
this.flushTimer = setInterval(() => this.flush(), this.flushInterval);
this.setupDwellTracking();
this.setupUnloadHandler();
this.setupVisibilityHandler();
console.debug('[KnowledgeCollector] Initialized with session:', this.sessionId);
}
private generateSessionId(): string {
return `session_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
}
private setupDwellTracking() {
this.startDwellTracking(window.location.pathname, this.getModuleFromPath(window.location.pathname));
window.addEventListener('popstate', () => {
this.checkAndEmitDwell();
this.startDwellTracking(window.location.pathname, this.getModuleFromPath(window.location.pathname));
});
}
private setupUnloadHandler() {
window.addEventListener('beforeunload', () => {
this.checkAndEmitDwell();
this.flushSync();
});
}
private setupVisibilityHandler() {
document.addEventListener('visibilitychange', () => {
if (document.hidden) {
this.checkAndEmitDwell();
} else {
this.startDwellTracking(window.location.pathname, this.getModuleFromPath(window.location.pathname));
}
});
}
private getModuleFromPath(path: string): string {
const segments = path.split('/').filter(Boolean);
if (segments.length === 0) return 'home';
const moduleMap: Record<string, string> = {
'agent': 'agent',
'compass': 'compass',
'insights': 'insights',
'admin': 'admin',
'app': 'applications',
'scientist': 'scientist',
'crm': 'crm',
'valuation': 'valuation',
'comunicacao': 'communication',
'ide': 'ide',
};
return moduleMap[segments[0]] || segments[0];
}
startDwellTracking(url: string, module: string) {
this.dwellTracker = {
url,
startTime: Date.now(),
module,
};
}
private checkAndEmitDwell() {
if (!this.dwellTracker) return;
const timeSpent = Date.now() - this.dwellTracker.startTime;
if (timeSpent >= this.dwellThreshold) {
this.track('page_dwell', this.dwellTracker.module, {
url: this.dwellTracker.url,
timeSpent,
timeSpentSeconds: Math.round(timeSpent / 1000),
});
}
this.dwellTracker = null;
}
track(type: EventType, module: string, data: Record<string, any> = {}) {
const event: CollectorEvent = {
type,
module,
data: {
...data,
path: window.location.pathname,
href: window.location.href,
},
timestamp: Date.now(),
sessionId: this.sessionId,
};
this.queue.push(event);
console.debug('[KnowledgeCollector] Event tracked:', type, module);
if (this.queue.length >= 20) {
this.flush();
}
}
trackPageView(pageName: string, route?: string) {
this.checkAndEmitDwell();
this.startDwellTracking(route || window.location.pathname, pageName);
this.track('page_view', pageName, { route });
}
trackAppOpen(appName: string, appUrl?: string, category?: string) {
this.track('app_open', 'applications', { appName, appUrl, category });
}
trackSiteNavigation(siteName: string, url: string) {
try {
const domain = new URL(url).hostname;
this.track('site_navigation', 'browser', { siteName, url, domain });
} catch {
this.track('site_navigation', 'browser', { siteName, url });
}
}
trackSearch(query: string, module: string, resultsCount?: number) {
this.track('search', module, { query, resultsCount });
}
trackFormSubmit(formName: string, module: string, fields?: string[]) {
this.track('form_submit', module, { formName, fields });
}
trackButtonClick(buttonName: string, module: string, context?: Record<string, any>) {
this.track('button_click', module, { buttonName, ...context });
}
trackFileOpen(fileName: string, fileType: string, source?: string) {
this.track('file_open', 'files', { fileName, fileType, source });
}
trackDocumentView(docName: string, docType: string, source?: string) {
this.track('document_view', 'documents', { docName, docType, source });
}
trackFeatureUse(feature: string, module: string, details?: Record<string, any>) {
this.track('feature_use', module, { feature, ...details });
}
trackContentCapture(url: string, title: string, wordCount: number) {
this.track('content_capture', 'knowledge', { url, title, wordCount });
}
trackIframeInteraction(appName: string, url: string, interactionType: string) {
this.track('iframe_interaction', 'iframe_browser', { appName, url, interactionType });
}
private async flush() {
if (this.queue.length === 0) return;
const events = [...this.queue];
this.queue = [];
try {
const response = await fetch('/api/collector/events', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ events }),
});
if (!response.ok) {
console.warn('[KnowledgeCollector] Flush failed, re-queueing events');
this.queue = [...events, ...this.queue];
} else {
console.debug('[KnowledgeCollector] Flushed', events.length, 'events');
}
} catch (error) {
console.warn('[KnowledgeCollector] Flush error:', error);
this.queue = [...events, ...this.queue];
}
}
private flushSync() {
if (this.queue.length === 0) return;
const events = [...this.queue];
this.queue = [];
const payload = JSON.stringify({ events });
try {
const blob = new Blob([payload], { type: 'application/json' });
const success = navigator.sendBeacon('/api/collector/events', blob);
if (!success) {
const xhr = new XMLHttpRequest();
xhr.open('POST', '/api/collector/events', false);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(payload);
}
} catch {
const xhr = new XMLHttpRequest();
xhr.open('POST', '/api/collector/events', false);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(payload);
}
}
getSessionId(): string {
return this.sessionId;
}
getQueueSize(): number {
return this.queue.length;
}
destroy() {
if (this.flushTimer) {
clearInterval(this.flushTimer);
this.flushTimer = null;
}
this.flushSync();
this.isInitialized = false;
}
}
export const knowledgeCollector = new KnowledgeCollector();
export function initKnowledgeCollector() {
knowledgeCollector.init();
}

View File

@ -0,0 +1,33 @@
import { useAuth } from "@/hooks/use-auth";
import { Loader2 } from "lucide-react";
import { Redirect, Route } from "wouter";
export function ProtectedRoute({
path,
component: Component,
}: {
path: string;
component: () => React.JSX.Element;
}) {
const { user, isLoading } = useAuth();
if (isLoading) {
return (
<Route path={path}>
<div className="flex items-center justify-center min-h-screen bg-slate-100">
<Loader2 className="h-8 w-8 animate-spin text-primary" />
</div>
</Route>
);
}
if (!user) {
return (
<Route path={path}>
<Redirect to="/auth" />
</Route>
);
}
return <Route path={path} component={Component} />;
}

View File

@ -0,0 +1,57 @@
import { QueryClient, QueryFunction } from "@tanstack/react-query";
async function throwIfResNotOk(res: Response) {
if (!res.ok) {
const text = (await res.text()) || res.statusText;
throw new Error(`${res.status}: ${text}`);
}
}
export async function apiRequest(
method: string,
url: string,
data?: unknown | undefined,
): Promise<Response> {
const res = await fetch(url, {
method,
headers: data ? { "Content-Type": "application/json" } : {},
body: data ? JSON.stringify(data) : undefined,
credentials: "include",
});
await throwIfResNotOk(res);
return res;
}
type UnauthorizedBehavior = "returnNull" | "throw";
export const getQueryFn: <T>(options: {
on401: UnauthorizedBehavior;
}) => QueryFunction<T> =
({ on401: unauthorizedBehavior }) =>
async ({ queryKey }) => {
const res = await fetch(queryKey.join("/") as string, {
credentials: "include",
});
if (unauthorizedBehavior === "returnNull" && res.status === 401) {
return null;
}
await throwIfResNotOk(res);
return await res.json();
};
export const queryClient = new QueryClient({
defaultOptions: {
queries: {
queryFn: getQueryFn({ on401: "throw" }),
refetchInterval: false,
refetchOnWindowFocus: false,
staleTime: Infinity,
retry: false,
},
mutations: {
retry: false,
},
},
});

6
client/src/lib/utils.ts Normal file
View File

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

5
client/src/main.tsx Normal file
View File

@ -0,0 +1,5 @@
import { createRoot } from "react-dom/client";
import App from "./App";
import "./index.css";
createRoot(document.getElementById("root")!).render(<App />);

View File

@ -0,0 +1,21 @@
import React from 'react';
import { Card } from 'shadcn/ui';
interface ServiceOrderReportProps {
reportData: Array<{ status: string; count: number; }>;
}
const ServiceOrderReport: React.FC<ServiceOrderReportProps> = ({ reportData }) => {
return (
<div className="flex flex-wrap gap-4">
{reportData.map(({ status, count }) => (
<Card key={status} className="p-4">
<h3 className="font-bold text-lg">{status}</h3>
<p className="text-xl">{count}</p>
</Card>
))}
</div>
);
};
export default ServiceOrderReport;

Some files were not shown because too many files have changed in this diff Show More