mirror of
https://github.com/andwati/cymelle.git
synced 2026-11-28 10:48:46 +00:00
paystack
This commit is contained in:
@@ -0,0 +1,24 @@
|
|||||||
|
POSTGRES_DB=cymelle
|
||||||
|
POSTGRES_USER=cymelle
|
||||||
|
POSTGRES_PASSWORD=cymelle
|
||||||
|
POSTGRES_PORT=5432
|
||||||
|
|
||||||
|
API_PORT=8080
|
||||||
|
WEB_PORT=3000
|
||||||
|
VITE_API_BASE_URL=http://localhost:8080/api
|
||||||
|
APP_CORS_ALLOWED_ORIGINS=http://localhost:3000
|
||||||
|
SEED_DATA=true
|
||||||
|
|
||||||
|
LOW_STOCK_THRESHOLD=10
|
||||||
|
|
||||||
|
FARE_BASE_FARE=100.00
|
||||||
|
FARE_PER_KM_RATE=50.00
|
||||||
|
FARE_MINIMUM_FARE=150.00
|
||||||
|
FARE_DEFAULT_SURGE_MULTIPLIER=1.0
|
||||||
|
FARE_CURRENCY=KES
|
||||||
|
|
||||||
|
PAYSTACK_SECRET_KEY=
|
||||||
|
PAYSTACK_PUBLIC_KEY=
|
||||||
|
PAYSTACK_CALLBACK_URL=http://localhost:3000/payments/paystack/callback
|
||||||
|
PAYSTACK_WEBHOOK_SECRET=
|
||||||
|
PAYSTACK_API_BASE_URL=https://api.paystack.co
|
||||||
Generated
+1
@@ -1,5 +1,6 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<project version="4">
|
<project version="4">
|
||||||
|
<component name="GradleMigrationSettings" migrationVersion="1" />
|
||||||
<component name="GradleSettings">
|
<component name="GradleSettings">
|
||||||
<option name="linkedExternalProjectsSettings">
|
<option name="linkedExternalProjectsSettings">
|
||||||
<GradleProjectSettings>
|
<GradleProjectSettings>
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
# Render deployment
|
||||||
|
|
||||||
|
This repository is configured for two Docker-backed Render web services:
|
||||||
|
|
||||||
|
- `cymelle-api`: Spring Boot API
|
||||||
|
- `cymelle-web`: TanStack/Nitro frontend
|
||||||
|
|
||||||
|
No PostgreSQL container or Render database is created. Use your Neon database connection string.
|
||||||
|
|
||||||
|
## Render setup
|
||||||
|
|
||||||
|
1. Create a new Blueprint on Render using `render.yaml`.
|
||||||
|
2. When Render asks for `DATABASE_URL`, paste your Neon pooled PostgreSQL connection string.
|
||||||
|
- A Neon URL like `postgresql://user:password@host/db?sslmode=require` is accepted.
|
||||||
|
- A Neon JDBC URL like `jdbc:postgresql://host/db?user=...&password=...&sslmode=require` is also accepted.
|
||||||
|
3. Deploy both services.
|
||||||
|
4. If Render assigns different service URLs than the defaults in `render.yaml`, update:
|
||||||
|
- `cymelle-api` -> `APP_CORS_ALLOWED_ORIGINS` to the frontend URL.
|
||||||
|
- `cymelle-web` -> `VITE_API_BASE_URL` to the API URL plus `/api`.
|
||||||
|
5. Configure Paystack on `cymelle-api`:
|
||||||
|
- `PAYSTACK_SECRET_KEY`: your Paystack secret key.
|
||||||
|
- `PAYSTACK_PUBLIC_KEY`: your Paystack public key, kept for operational visibility.
|
||||||
|
- `PAYSTACK_CALLBACK_URL`: frontend callback URL, for example `https://cymelle-web.onrender.com/payments/paystack/callback`.
|
||||||
|
- `PAYSTACK_WEBHOOK_SECRET`: optional override for webhook HMAC verification; when omitted, the secret key is used.
|
||||||
|
|
||||||
|
## Local Docker builds
|
||||||
|
|
||||||
|
Build the API:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker build -t cymelle-api ./orders-backend
|
||||||
|
```
|
||||||
|
|
||||||
|
Run the API with Neon:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker run --rm -p 8080:8080 \
|
||||||
|
-e DATABASE_URL='postgresql://user:password@host/db?sslmode=require' \
|
||||||
|
-e APP_CORS_ALLOWED_ORIGINS='http://localhost:3000' \
|
||||||
|
cymelle-api
|
||||||
|
```
|
||||||
|
|
||||||
|
Build the frontend:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker build -t cymelle-web \
|
||||||
|
--build-arg VITE_API_BASE_URL=http://localhost:8080/api \
|
||||||
|
./orders-frontend
|
||||||
|
```
|
||||||
|
|
||||||
|
Run the frontend:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker run --rm -p 3000:3000 cymelle-web
|
||||||
|
```
|
||||||
@@ -1 +1,37 @@
|
|||||||
# readme
|
# Cymelle
|
||||||
|
|
||||||
|
## Local Docker Compose
|
||||||
|
|
||||||
|
Run the full local development stack with Postgres 18, Spring Boot API, and TanStack/Vite web app:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cp .env.example .env
|
||||||
|
docker compose up
|
||||||
|
```
|
||||||
|
|
||||||
|
Services:
|
||||||
|
|
||||||
|
- Web: `http://localhost:3000`
|
||||||
|
- API: `http://localhost:8080/api`
|
||||||
|
- Swagger UI: `http://localhost:8080/swagger-ui.html`
|
||||||
|
- Postgres: `localhost:5432`, database/user/password `cymelle`
|
||||||
|
|
||||||
|
Paystack checkout requires test keys in `.env`:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
PAYSTACK_SECRET_KEY=sk_test_...
|
||||||
|
PAYSTACK_PUBLIC_KEY=pk_test_...
|
||||||
|
PAYSTACK_CALLBACK_URL=http://localhost:3000/payments/paystack/callback
|
||||||
|
```
|
||||||
|
|
||||||
|
Useful commands:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker compose logs -f api
|
||||||
|
docker compose logs -f web
|
||||||
|
docker compose restart api
|
||||||
|
docker compose down
|
||||||
|
docker compose down -v
|
||||||
|
```
|
||||||
|
|
||||||
|
The web service runs Vite from mounted source, so frontend edits reload without rebuilding. Restart `api` after backend code changes. Use `docker compose down -v` only when you want to delete the local Postgres and dependency cache volumes.
|
||||||
|
|||||||
+74
@@ -0,0 +1,74 @@
|
|||||||
|
name: cymelle
|
||||||
|
|
||||||
|
services:
|
||||||
|
db:
|
||||||
|
image: postgres:18-alpine
|
||||||
|
environment:
|
||||||
|
POSTGRES_DB: ${POSTGRES_DB:-cymelle}
|
||||||
|
POSTGRES_USER: ${POSTGRES_USER:-cymelle}
|
||||||
|
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-cymelle}
|
||||||
|
ports:
|
||||||
|
- "${POSTGRES_PORT:-5432}:5432"
|
||||||
|
volumes:
|
||||||
|
- postgres-data:/var/lib/postgresql/data
|
||||||
|
healthcheck:
|
||||||
|
test:
|
||||||
|
[
|
||||||
|
"CMD-SHELL",
|
||||||
|
"pg_isready -U ${POSTGRES_USER:-cymelle} -d ${POSTGRES_DB:-cymelle}",
|
||||||
|
]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 10
|
||||||
|
|
||||||
|
api:
|
||||||
|
image: eclipse-temurin:17-jdk-jammy
|
||||||
|
working_dir: /workspace
|
||||||
|
command: ./gradlew --no-daemon bootRun
|
||||||
|
environment:
|
||||||
|
PORT: 8080
|
||||||
|
SPRING_DATASOURCE_URL: jdbc:postgresql://db:5432/${POSTGRES_DB:-cymelle}
|
||||||
|
SPRING_DATASOURCE_USERNAME: ${POSTGRES_USER:-cymelle}
|
||||||
|
SPRING_DATASOURCE_PASSWORD: ${POSTGRES_PASSWORD:-cymelle}
|
||||||
|
APP_CORS_ALLOWED_ORIGINS: ${APP_CORS_ALLOWED_ORIGINS:-http://localhost:3000}
|
||||||
|
SEED_DATA: ${SEED_DATA:-true}
|
||||||
|
LOW_STOCK_THRESHOLD: ${LOW_STOCK_THRESHOLD:-10}
|
||||||
|
FARE_BASE_FARE: ${FARE_BASE_FARE:-100.00}
|
||||||
|
FARE_PER_KM_RATE: ${FARE_PER_KM_RATE:-50.00}
|
||||||
|
FARE_MINIMUM_FARE: ${FARE_MINIMUM_FARE:-150.00}
|
||||||
|
FARE_DEFAULT_SURGE_MULTIPLIER: ${FARE_DEFAULT_SURGE_MULTIPLIER:-1.0}
|
||||||
|
FARE_CURRENCY: ${FARE_CURRENCY:-KES}
|
||||||
|
PAYSTACK_SECRET_KEY: ${PAYSTACK_SECRET_KEY:-}
|
||||||
|
PAYSTACK_PUBLIC_KEY: ${PAYSTACK_PUBLIC_KEY:-}
|
||||||
|
PAYSTACK_CALLBACK_URL: ${PAYSTACK_CALLBACK_URL:-http://localhost:3000/payments/paystack/callback}
|
||||||
|
PAYSTACK_WEBHOOK_SECRET: ${PAYSTACK_WEBHOOK_SECRET:-}
|
||||||
|
PAYSTACK_API_BASE_URL: ${PAYSTACK_API_BASE_URL:-https://api.paystack.co}
|
||||||
|
ports:
|
||||||
|
- "${API_PORT:-8080}:8080"
|
||||||
|
volumes:
|
||||||
|
- ./orders-backend:/workspace
|
||||||
|
- gradle-cache:/root/.gradle
|
||||||
|
depends_on:
|
||||||
|
db:
|
||||||
|
condition: service_healthy
|
||||||
|
|
||||||
|
web:
|
||||||
|
image: node:24-bookworm-slim
|
||||||
|
working_dir: /app
|
||||||
|
command: sh -c "corepack enable && pnpm install --frozen-lockfile && pnpm dev --host 0.0.0.0"
|
||||||
|
environment:
|
||||||
|
HOST: 0.0.0.0
|
||||||
|
PORT: 3000
|
||||||
|
VITE_API_BASE_URL: ${VITE_API_BASE_URL:-http://localhost:8080/api}
|
||||||
|
ports:
|
||||||
|
- "${WEB_PORT:-3000}:3000"
|
||||||
|
volumes:
|
||||||
|
- ./orders-frontend:/app
|
||||||
|
- frontend-node-modules:/app/node_modules
|
||||||
|
depends_on:
|
||||||
|
- api
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
postgres-data:
|
||||||
|
gradle-cache:
|
||||||
|
frontend-node-modules:
|
||||||
@@ -10,4 +10,10 @@ FARE_MINIMUM_FARE=150.00
|
|||||||
FARE_DEFAULT_SURGE_MULTIPLIER=1.0
|
FARE_DEFAULT_SURGE_MULTIPLIER=1.0
|
||||||
FARE_CURRENCY=KES
|
FARE_CURRENCY=KES
|
||||||
|
|
||||||
|
PAYSTACK_SECRET_KEY=
|
||||||
|
PAYSTACK_PUBLIC_KEY=
|
||||||
|
PAYSTACK_CALLBACK_URL=http://localhost:3000/payments/paystack/callback
|
||||||
|
PAYSTACK_WEBHOOK_SECRET=
|
||||||
|
PAYSTACK_API_BASE_URL=https://api.paystack.co
|
||||||
|
|
||||||
SEED_DATA=true
|
SEED_DATA=true
|
||||||
@@ -2,6 +2,7 @@ package com.andwati.orders;
|
|||||||
|
|
||||||
import com.andwati.orders.config.FareProperties;
|
import com.andwati.orders.config.FareProperties;
|
||||||
import com.andwati.orders.config.InventoryProperties;
|
import com.andwati.orders.config.InventoryProperties;
|
||||||
|
import com.andwati.orders.config.PaystackProperties;
|
||||||
import io.github.cdimascio.dotenv.Dotenv;
|
import io.github.cdimascio.dotenv.Dotenv;
|
||||||
import org.springframework.boot.SpringApplication;
|
import org.springframework.boot.SpringApplication;
|
||||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
@@ -10,7 +11,8 @@ import org.springframework.boot.context.properties.EnableConfigurationProperties
|
|||||||
@SpringBootApplication
|
@SpringBootApplication
|
||||||
@EnableConfigurationProperties({
|
@EnableConfigurationProperties({
|
||||||
FareProperties.class,
|
FareProperties.class,
|
||||||
InventoryProperties.class
|
InventoryProperties.class,
|
||||||
|
PaystackProperties.class
|
||||||
})
|
})
|
||||||
public class OrdersBackendApplication {
|
public class OrdersBackendApplication {
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
package com.andwati.orders.config;
|
||||||
|
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
|
|
||||||
|
@ConfigurationProperties(prefix = "paystack")
|
||||||
|
public record PaystackProperties(
|
||||||
|
String secretKey,
|
||||||
|
String publicKey,
|
||||||
|
String callbackUrl,
|
||||||
|
String webhookSecret,
|
||||||
|
String apiBaseUrl
|
||||||
|
) {
|
||||||
|
public String resolvedApiBaseUrl() {
|
||||||
|
return hasText(apiBaseUrl) ? apiBaseUrl : "https://api.paystack.co";
|
||||||
|
}
|
||||||
|
|
||||||
|
public String resolvedWebhookSecret() {
|
||||||
|
return hasText(webhookSecret) ? webhookSecret : secretKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean hasSecretKey() {
|
||||||
|
return hasText(secretKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean hasCallbackUrl() {
|
||||||
|
return hasText(callbackUrl);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean hasText(String value) {
|
||||||
|
return value != null && !value.isBlank();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,6 +14,7 @@ import org.springframework.security.config.annotation.web.configurers.AbstractHt
|
|||||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
import org.springframework.security.web.SecurityFilterChain;
|
import org.springframework.security.web.SecurityFilterChain;
|
||||||
|
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
|
||||||
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
|
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
|
||||||
import org.springframework.security.web.csrf.CsrfTokenRequestAttributeHandler;
|
import org.springframework.security.web.csrf.CsrfTokenRequestAttributeHandler;
|
||||||
|
|
||||||
@@ -31,6 +32,7 @@ public class SecurityConfig {
|
|||||||
.csrf(csrf -> csrf
|
.csrf(csrf -> csrf
|
||||||
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
|
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
|
||||||
.csrfTokenRequestHandler(csrfRequestHandler)
|
.csrfTokenRequestHandler(csrfRequestHandler)
|
||||||
|
.ignoringRequestMatchers(new AntPathRequestMatcher("/api/payments/paystack/webhook", "POST"))
|
||||||
)
|
)
|
||||||
.formLogin(AbstractHttpConfigurer::disable)
|
.formLogin(AbstractHttpConfigurer::disable)
|
||||||
.httpBasic(AbstractHttpConfigurer::disable)
|
.httpBasic(AbstractHttpConfigurer::disable)
|
||||||
@@ -40,6 +42,8 @@ public class SecurityConfig {
|
|||||||
.requestMatchers(HttpMethod.POST, "/api/auth/login", "/api/auth/register").permitAll()
|
.requestMatchers(HttpMethod.POST, "/api/auth/login", "/api/auth/register").permitAll()
|
||||||
.requestMatchers("/api-docs/**", "/swagger-ui.html", "/swagger-ui/**").permitAll()
|
.requestMatchers("/api-docs/**", "/swagger-ui.html", "/swagger-ui/**").permitAll()
|
||||||
.requestMatchers(HttpMethod.GET, "/api/products/**").permitAll()
|
.requestMatchers(HttpMethod.GET, "/api/products/**").permitAll()
|
||||||
|
.requestMatchers(HttpMethod.POST, "/api/checkout/quote").permitAll()
|
||||||
|
.requestMatchers(HttpMethod.POST, "/api/payments/paystack/webhook").permitAll()
|
||||||
.requestMatchers(HttpMethod.POST, "/api/products/**").hasRole("ADMIN")
|
.requestMatchers(HttpMethod.POST, "/api/products/**").hasRole("ADMIN")
|
||||||
.requestMatchers(HttpMethod.PUT, "/api/products/**").hasRole("ADMIN")
|
.requestMatchers(HttpMethod.PUT, "/api/products/**").hasRole("ADMIN")
|
||||||
.requestMatchers(HttpMethod.PATCH, "/api/products/**").hasRole("ADMIN")
|
.requestMatchers(HttpMethod.PATCH, "/api/products/**").hasRole("ADMIN")
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
package com.andwati.orders.controller;
|
||||||
|
|
||||||
|
import com.andwati.orders.dto.request.CheckoutQuoteRequest;
|
||||||
|
import com.andwati.orders.dto.response.CheckoutQuoteResponse;
|
||||||
|
import com.andwati.orders.services.PaymentService;
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import jakarta.validation.Valid;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
@Tag(name = "Checkout", description = "Quote ecommerce checkout totals")
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/checkout")
|
||||||
|
public class CheckoutController {
|
||||||
|
|
||||||
|
private final PaymentService paymentService;
|
||||||
|
|
||||||
|
public CheckoutController(PaymentService paymentService) {
|
||||||
|
this.paymentService = paymentService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(
|
||||||
|
summary = "Quote checkout totals",
|
||||||
|
description = "Calculates product subtotal, optional delivery ride fare, and grand total from current backend data."
|
||||||
|
)
|
||||||
|
@PostMapping("/quote")
|
||||||
|
public CheckoutQuoteResponse quote(@Valid @RequestBody CheckoutQuoteRequest request) {
|
||||||
|
return paymentService.quote(request);
|
||||||
|
}
|
||||||
|
}
|
||||||
+51
@@ -0,0 +1,51 @@
|
|||||||
|
package com.andwati.orders.controller;
|
||||||
|
|
||||||
|
import com.andwati.orders.dto.request.PaystackInitializeRequest;
|
||||||
|
import com.andwati.orders.dto.response.PaystackInitializeResponse;
|
||||||
|
import com.andwati.orders.dto.response.PaystackVerifyResponse;
|
||||||
|
import com.andwati.orders.services.PaymentService;
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import jakarta.validation.Valid;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
@Tag(name = "Paystack Payments", description = "Initialize and verify Paystack checkout payments")
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/payments/paystack")
|
||||||
|
public class PaystackPaymentController {
|
||||||
|
|
||||||
|
private final PaymentService paymentService;
|
||||||
|
|
||||||
|
public PaystackPaymentController(PaymentService paymentService) {
|
||||||
|
this.paymentService = paymentService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(
|
||||||
|
summary = "Initialize Paystack checkout",
|
||||||
|
description = "Creates pending order, optional ride, payment record, and returns a Paystack authorization URL."
|
||||||
|
)
|
||||||
|
@PostMapping("/initialize")
|
||||||
|
public PaystackInitializeResponse initialize(@Valid @RequestBody PaystackInitializeRequest request) {
|
||||||
|
return paymentService.initialize(request);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(
|
||||||
|
summary = "Verify Paystack payment",
|
||||||
|
description = "Verifies the Paystack transaction and marks the payment paid only when reference, amount, and currency match."
|
||||||
|
)
|
||||||
|
@PostMapping("/verify/{reference}")
|
||||||
|
public PaystackVerifyResponse verify(@PathVariable String reference) {
|
||||||
|
return paymentService.verify(reference);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "Receive Paystack webhook events")
|
||||||
|
@PostMapping("/webhook")
|
||||||
|
@ResponseStatus(HttpStatus.NO_CONTENT)
|
||||||
|
public void webhook(
|
||||||
|
@RequestBody String body,
|
||||||
|
@RequestHeader(name = "x-paystack-signature", required = false) String signature
|
||||||
|
) {
|
||||||
|
paymentService.handleWebhook(body, signature);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package com.andwati.orders.dto.request;
|
||||||
|
|
||||||
|
import jakarta.validation.Valid;
|
||||||
|
import jakarta.validation.constraints.Size;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public record CheckoutQuoteRequest(
|
||||||
|
@Valid
|
||||||
|
@Size(min = 1, message = "items must contain at least one item")
|
||||||
|
List<CreateOrderItemRequest> items,
|
||||||
|
|
||||||
|
@Valid
|
||||||
|
CreateOrderRideRequest deliveryRide
|
||||||
|
) {
|
||||||
|
}
|
||||||
+19
@@ -0,0 +1,19 @@
|
|||||||
|
package com.andwati.orders.dto.request;
|
||||||
|
|
||||||
|
import jakarta.validation.Valid;
|
||||||
|
import jakarta.validation.constraints.Size;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public record PaystackInitializeRequest(
|
||||||
|
@Valid
|
||||||
|
@Size(min = 1, message = "items must contain at least one item")
|
||||||
|
List<CreateOrderItemRequest> items,
|
||||||
|
|
||||||
|
@Valid
|
||||||
|
CreateOrderRideRequest deliveryRide
|
||||||
|
) {
|
||||||
|
public CreateOrderRequest toCreateOrderRequest() {
|
||||||
|
return new CreateOrderRequest(items, deliveryRide);
|
||||||
|
}
|
||||||
|
}
|
||||||
+13
@@ -0,0 +1,13 @@
|
|||||||
|
package com.andwati.orders.dto.response;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.time.Instant;
|
||||||
|
|
||||||
|
public record CheckoutQuoteResponse(
|
||||||
|
BigDecimal productSubtotal,
|
||||||
|
BigDecimal rideFare,
|
||||||
|
BigDecimal grandTotal,
|
||||||
|
String currency,
|
||||||
|
Instant expiresAt
|
||||||
|
) {
|
||||||
|
}
|
||||||
+18
@@ -0,0 +1,18 @@
|
|||||||
|
package com.andwati.orders.dto.response;
|
||||||
|
|
||||||
|
import com.andwati.orders.model.PaymentStatus;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
public record PaystackInitializeResponse(
|
||||||
|
String authorizationUrl,
|
||||||
|
String accessCode,
|
||||||
|
String reference,
|
||||||
|
UUID orderId,
|
||||||
|
UUID rideId,
|
||||||
|
BigDecimal amount,
|
||||||
|
String currency,
|
||||||
|
PaymentStatus status
|
||||||
|
) {
|
||||||
|
}
|
||||||
+17
@@ -0,0 +1,17 @@
|
|||||||
|
package com.andwati.orders.dto.response;
|
||||||
|
|
||||||
|
import com.andwati.orders.model.PaymentStatus;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
public record PaystackVerifyResponse(
|
||||||
|
String reference,
|
||||||
|
PaymentStatus status,
|
||||||
|
UUID orderId,
|
||||||
|
UUID rideId,
|
||||||
|
BigDecimal amount,
|
||||||
|
String currency,
|
||||||
|
String message
|
||||||
|
) {
|
||||||
|
}
|
||||||
@@ -0,0 +1,250 @@
|
|||||||
|
package com.andwati.orders.model;
|
||||||
|
|
||||||
|
import jakarta.persistence.*;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
@Table(
|
||||||
|
name = "payments",
|
||||||
|
uniqueConstraints = {
|
||||||
|
@UniqueConstraint(name = "uk_payments_reference", columnNames = "reference")
|
||||||
|
}
|
||||||
|
)
|
||||||
|
public class Payment {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.UUID)
|
||||||
|
private UUID id;
|
||||||
|
|
||||||
|
@OneToOne(fetch = FetchType.LAZY, optional = false)
|
||||||
|
@JoinColumn(name = "order_id", nullable = false)
|
||||||
|
private Order order;
|
||||||
|
|
||||||
|
@OneToOne(fetch = FetchType.LAZY)
|
||||||
|
@JoinColumn(name = "ride_id")
|
||||||
|
private Ride ride;
|
||||||
|
|
||||||
|
@Column(nullable = false, length = 80)
|
||||||
|
private String reference;
|
||||||
|
|
||||||
|
@Column(nullable = false, precision = 12, scale = 2)
|
||||||
|
private BigDecimal productSubtotal;
|
||||||
|
|
||||||
|
@Column(nullable = false, precision = 12, scale = 2)
|
||||||
|
private BigDecimal rideFare;
|
||||||
|
|
||||||
|
@Column(nullable = false, precision = 12, scale = 2)
|
||||||
|
private BigDecimal amountMajor;
|
||||||
|
|
||||||
|
@Column(nullable = false)
|
||||||
|
private long amountSubunits;
|
||||||
|
|
||||||
|
@Column(nullable = false, length = 3)
|
||||||
|
private String currency;
|
||||||
|
|
||||||
|
@Enumerated(EnumType.STRING)
|
||||||
|
@Column(nullable = false, length = 30)
|
||||||
|
private PaymentStatus status = PaymentStatus.PENDING;
|
||||||
|
|
||||||
|
@Column(length = 512)
|
||||||
|
private String authorizationUrl;
|
||||||
|
|
||||||
|
@Column(length = 120)
|
||||||
|
private String accessCode;
|
||||||
|
|
||||||
|
@Lob
|
||||||
|
private String rawVerificationPayload;
|
||||||
|
|
||||||
|
@Column(nullable = false)
|
||||||
|
private Instant createdAt;
|
||||||
|
|
||||||
|
private Instant paidAt;
|
||||||
|
|
||||||
|
private Instant updatedAt;
|
||||||
|
|
||||||
|
@PrePersist
|
||||||
|
public void prePersist() {
|
||||||
|
Instant now = Instant.now();
|
||||||
|
if (createdAt == null) {
|
||||||
|
createdAt = now;
|
||||||
|
}
|
||||||
|
if (updatedAt == null) {
|
||||||
|
updatedAt = now;
|
||||||
|
}
|
||||||
|
if (status == null) {
|
||||||
|
status = PaymentStatus.PENDING;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@PreUpdate
|
||||||
|
public void preUpdate() {
|
||||||
|
updatedAt = Instant.now();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void markPaid(String rawPayload) {
|
||||||
|
if (status == PaymentStatus.PAID) {
|
||||||
|
this.rawVerificationPayload = rawPayload;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.status = PaymentStatus.PAID;
|
||||||
|
this.paidAt = Instant.now();
|
||||||
|
this.rawVerificationPayload = rawPayload;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void markFailed(PaymentStatus status, String rawPayload) {
|
||||||
|
if (this.status == PaymentStatus.PAID) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.status = status;
|
||||||
|
this.rawVerificationPayload = rawPayload;
|
||||||
|
}
|
||||||
|
|
||||||
|
public UUID getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Payment setId(UUID id) {
|
||||||
|
this.id = id;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Order getOrder() {
|
||||||
|
return order;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Payment setOrder(Order order) {
|
||||||
|
this.order = order;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Ride getRide() {
|
||||||
|
return ride;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Payment setRide(Ride ride) {
|
||||||
|
this.ride = ride;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getReference() {
|
||||||
|
return reference;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Payment setReference(String reference) {
|
||||||
|
this.reference = reference;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public BigDecimal getProductSubtotal() {
|
||||||
|
return productSubtotal;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Payment setProductSubtotal(BigDecimal productSubtotal) {
|
||||||
|
this.productSubtotal = productSubtotal;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public BigDecimal getRideFare() {
|
||||||
|
return rideFare;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Payment setRideFare(BigDecimal rideFare) {
|
||||||
|
this.rideFare = rideFare;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public BigDecimal getAmountMajor() {
|
||||||
|
return amountMajor;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Payment setAmountMajor(BigDecimal amountMajor) {
|
||||||
|
this.amountMajor = amountMajor;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public long getAmountSubunits() {
|
||||||
|
return amountSubunits;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Payment setAmountSubunits(long amountSubunits) {
|
||||||
|
this.amountSubunits = amountSubunits;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getCurrency() {
|
||||||
|
return currency;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Payment setCurrency(String currency) {
|
||||||
|
this.currency = currency;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public PaymentStatus getStatus() {
|
||||||
|
return status;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Payment setStatus(PaymentStatus status) {
|
||||||
|
this.status = status;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getAuthorizationUrl() {
|
||||||
|
return authorizationUrl;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Payment setAuthorizationUrl(String authorizationUrl) {
|
||||||
|
this.authorizationUrl = authorizationUrl;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getAccessCode() {
|
||||||
|
return accessCode;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Payment setAccessCode(String accessCode) {
|
||||||
|
this.accessCode = accessCode;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getRawVerificationPayload() {
|
||||||
|
return rawVerificationPayload;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Payment setRawVerificationPayload(String rawVerificationPayload) {
|
||||||
|
this.rawVerificationPayload = rawVerificationPayload;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Instant getCreatedAt() {
|
||||||
|
return createdAt;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Payment setCreatedAt(Instant createdAt) {
|
||||||
|
this.createdAt = createdAt;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Instant getPaidAt() {
|
||||||
|
return paidAt;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Payment setPaidAt(Instant paidAt) {
|
||||||
|
this.paidAt = paidAt;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Instant getUpdatedAt() {
|
||||||
|
return updatedAt;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Payment setUpdatedAt(Instant updatedAt) {
|
||||||
|
this.updatedAt = updatedAt;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
package com.andwati.orders.model;
|
||||||
|
|
||||||
|
public enum PaymentStatus {
|
||||||
|
PENDING,
|
||||||
|
PAID,
|
||||||
|
FAILED,
|
||||||
|
ABANDONED,
|
||||||
|
REFUNDED
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
package com.andwati.orders.repository;
|
||||||
|
|
||||||
|
import com.andwati.orders.model.Payment;
|
||||||
|
import org.springframework.data.jpa.repository.EntityGraph;
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
public interface PaymentRepository extends JpaRepository<Payment, UUID> {
|
||||||
|
|
||||||
|
@EntityGraph(attributePaths = {"order", "order.customer", "ride"})
|
||||||
|
Optional<Payment> findByReference(String reference);
|
||||||
|
}
|
||||||
@@ -57,6 +57,18 @@ public class OrderService {
|
|||||||
@Transactional
|
@Transactional
|
||||||
public OrderResponse placeOrder(CreateOrderRequest request) {
|
public OrderResponse placeOrder(CreateOrderRequest request) {
|
||||||
AppUser customer = appUserService.getCurrentUser();
|
AppUser customer = appUserService.getCurrentUser();
|
||||||
|
|
||||||
|
PendingOrderResult result = createPendingOrder(customer, request, null, null);
|
||||||
|
return orderMapper.toResponse(result.order());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public PendingOrderResult createPendingOrder(
|
||||||
|
AppUser customer,
|
||||||
|
CreateOrderRequest request,
|
||||||
|
java.math.BigDecimal rideFare,
|
||||||
|
String rideCurrency
|
||||||
|
) {
|
||||||
if (customer.getRole() != Role.CUSTOMER) {
|
if (customer.getRole() != Role.CUSTOMER) {
|
||||||
throw new IllegalArgumentException("Only customers can place orders");
|
throw new IllegalArgumentException("Only customers can place orders");
|
||||||
}
|
}
|
||||||
@@ -103,6 +115,7 @@ public class OrderService {
|
|||||||
order.recalculateTotal();
|
order.recalculateTotal();
|
||||||
|
|
||||||
Order savedOrder = orderRepository.save(order);
|
Order savedOrder = orderRepository.save(order);
|
||||||
|
Ride savedRide = null;
|
||||||
|
|
||||||
if (request.deliveryRide() != null) {
|
if (request.deliveryRide() != null) {
|
||||||
Ride ride = new Ride()
|
Ride ride = new Ride()
|
||||||
@@ -111,12 +124,14 @@ public class OrderService {
|
|||||||
.setPickupLocation(request.deliveryRide().pickupLocation().trim())
|
.setPickupLocation(request.deliveryRide().pickupLocation().trim())
|
||||||
.setDropoffLocation(request.deliveryRide().dropoffLocation().trim())
|
.setDropoffLocation(request.deliveryRide().dropoffLocation().trim())
|
||||||
.setDistanceKm(request.deliveryRide().distanceKm())
|
.setDistanceKm(request.deliveryRide().distanceKm())
|
||||||
|
.setFareAmount(rideFare)
|
||||||
|
.setCurrency(rideCurrency == null ? "KES" : rideCurrency)
|
||||||
.setStatus(RideStatus.REQUESTED);
|
.setStatus(RideStatus.REQUESTED);
|
||||||
|
|
||||||
rideRepository.save(ride);
|
savedRide = rideRepository.save(ride);
|
||||||
}
|
}
|
||||||
|
|
||||||
return orderMapper.toResponse(savedOrder);
|
return new PendingOrderResult(savedOrder, savedRide);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
|
|||||||
@@ -0,0 +1,412 @@
|
|||||||
|
package com.andwati.orders.services;
|
||||||
|
|
||||||
|
import com.andwati.orders.config.PaystackProperties;
|
||||||
|
import com.andwati.orders.dto.request.CheckoutQuoteRequest;
|
||||||
|
import com.andwati.orders.dto.request.CreateOrderRequest;
|
||||||
|
import com.andwati.orders.dto.request.PaystackInitializeRequest;
|
||||||
|
import com.andwati.orders.dto.response.CheckoutQuoteResponse;
|
||||||
|
import com.andwati.orders.dto.response.FareCalculationResponse;
|
||||||
|
import com.andwati.orders.dto.response.PaystackInitializeResponse;
|
||||||
|
import com.andwati.orders.dto.response.PaystackVerifyResponse;
|
||||||
|
import com.andwati.orders.exception.InsufficientStockException;
|
||||||
|
import com.andwati.orders.exception.InventoryNotFoundException;
|
||||||
|
import com.andwati.orders.exception.ProductNotFoundException;
|
||||||
|
import com.andwati.orders.model.*;
|
||||||
|
import com.andwati.orders.repository.InventoryItemRepository;
|
||||||
|
import com.andwati.orders.repository.PaymentRepository;
|
||||||
|
import com.andwati.orders.repository.ProductRepository;
|
||||||
|
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||||
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
import javax.crypto.Mac;
|
||||||
|
import javax.crypto.spec.SecretKeySpec;
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.math.RoundingMode;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.HexFormat;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.UUID;
|
||||||
|
import java.util.function.Function;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class PaymentService {
|
||||||
|
|
||||||
|
private static final String DEFAULT_CURRENCY = "KES";
|
||||||
|
private static final int QUOTE_TTL_MINUTES = 15;
|
||||||
|
|
||||||
|
private final ProductRepository productRepository;
|
||||||
|
private final InventoryItemRepository inventoryItemRepository;
|
||||||
|
private final PaymentRepository paymentRepository;
|
||||||
|
private final FareCalculationService fareCalculationService;
|
||||||
|
private final OrderService orderService;
|
||||||
|
private final AppUserService appUserService;
|
||||||
|
private final PaystackClient paystackClient;
|
||||||
|
private final PaystackProperties paystackProperties;
|
||||||
|
private final ObjectMapper objectMapper;
|
||||||
|
|
||||||
|
public PaymentService(
|
||||||
|
ProductRepository productRepository,
|
||||||
|
InventoryItemRepository inventoryItemRepository,
|
||||||
|
PaymentRepository paymentRepository,
|
||||||
|
FareCalculationService fareCalculationService,
|
||||||
|
OrderService orderService,
|
||||||
|
AppUserService appUserService,
|
||||||
|
PaystackClient paystackClient,
|
||||||
|
PaystackProperties paystackProperties,
|
||||||
|
ObjectMapper objectMapper
|
||||||
|
) {
|
||||||
|
this.productRepository = productRepository;
|
||||||
|
this.inventoryItemRepository = inventoryItemRepository;
|
||||||
|
this.paymentRepository = paymentRepository;
|
||||||
|
this.fareCalculationService = fareCalculationService;
|
||||||
|
this.orderService = orderService;
|
||||||
|
this.appUserService = appUserService;
|
||||||
|
this.paystackClient = paystackClient;
|
||||||
|
this.paystackProperties = paystackProperties;
|
||||||
|
this.objectMapper = objectMapper;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public CheckoutQuoteResponse quote(CheckoutQuoteRequest request) {
|
||||||
|
CheckoutQuote quote = calculateQuote(request.items(), request.deliveryRide());
|
||||||
|
return toQuoteResponse(quote);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public PaystackInitializeResponse initialize(PaystackInitializeRequest request) {
|
||||||
|
AppUser customer = appUserService.getCurrentUser();
|
||||||
|
if (customer.getRole() != Role.CUSTOMER) {
|
||||||
|
throw new IllegalArgumentException("Only customers can checkout");
|
||||||
|
}
|
||||||
|
|
||||||
|
CheckoutQuote quote = calculateQuote(request.items(), request.deliveryRide());
|
||||||
|
PendingOrderResult pendingOrder = orderService.createPendingOrder(
|
||||||
|
customer,
|
||||||
|
request.toCreateOrderRequest(),
|
||||||
|
quote.rideFare(),
|
||||||
|
quote.currency()
|
||||||
|
);
|
||||||
|
|
||||||
|
String reference = generateReference();
|
||||||
|
Payment payment = new Payment()
|
||||||
|
.setOrder(pendingOrder.order())
|
||||||
|
.setRide(pendingOrder.ride())
|
||||||
|
.setReference(reference)
|
||||||
|
.setProductSubtotal(quote.productSubtotal())
|
||||||
|
.setRideFare(quote.rideFare())
|
||||||
|
.setAmountMajor(quote.grandTotal())
|
||||||
|
.setAmountSubunits(toSubunits(quote.grandTotal()))
|
||||||
|
.setCurrency(quote.currency())
|
||||||
|
.setStatus(PaymentStatus.PENDING);
|
||||||
|
|
||||||
|
paymentRepository.save(payment);
|
||||||
|
|
||||||
|
JsonNode paystackData = paystackClient.initializeTransaction(
|
||||||
|
customer.getUsername(),
|
||||||
|
payment.getAmountSubunits(),
|
||||||
|
payment.getCurrency(),
|
||||||
|
payment.getReference(),
|
||||||
|
buildMetadata(customer, payment)
|
||||||
|
);
|
||||||
|
|
||||||
|
payment
|
||||||
|
.setAuthorizationUrl(paystackData.path("authorization_url").asText())
|
||||||
|
.setAccessCode(paystackData.path("access_code").asText());
|
||||||
|
|
||||||
|
return toInitializeResponse(payment);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public PaystackVerifyResponse verify(String reference) {
|
||||||
|
Payment payment = getPayment(reference);
|
||||||
|
assertCanAccess(payment);
|
||||||
|
|
||||||
|
return verifyPayment(payment);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public void handleWebhook(String body, String signature) {
|
||||||
|
verifyWebhookSignature(body, signature);
|
||||||
|
|
||||||
|
JsonNode event;
|
||||||
|
try {
|
||||||
|
event = objectMapper.readTree(body);
|
||||||
|
} catch (JsonProcessingException exception) {
|
||||||
|
throw new IllegalArgumentException("Webhook payload is not valid JSON");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!"charge.success".equals(event.path("event").asText())) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
String reference = event.path("data").path("reference").asText(null);
|
||||||
|
if (reference == null || reference.isBlank()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
paymentRepository.findByReference(reference).ifPresent(this::verifyPayment);
|
||||||
|
}
|
||||||
|
|
||||||
|
private PaystackVerifyResponse verifyPayment(Payment payment) {
|
||||||
|
JsonNode verification = paystackClient.verifyTransaction(payment.getReference());
|
||||||
|
JsonNode data = verification.path("data");
|
||||||
|
String rawPayload = toJson(verification);
|
||||||
|
|
||||||
|
boolean success = "success".equals(data.path("status").asText());
|
||||||
|
boolean matchesReference = payment.getReference().equals(data.path("reference").asText());
|
||||||
|
boolean matchesAmount = payment.getAmountSubunits() == data.path("amount").asLong();
|
||||||
|
boolean matchesCurrency = payment.getCurrency().equalsIgnoreCase(data.path("currency").asText());
|
||||||
|
|
||||||
|
if (success && matchesReference && matchesAmount && matchesCurrency) {
|
||||||
|
payment.markPaid(rawPayload);
|
||||||
|
return toVerifyResponse(payment, "Payment verified");
|
||||||
|
}
|
||||||
|
|
||||||
|
PaymentStatus nextStatus = mapPaystackStatus(data.path("status").asText());
|
||||||
|
payment.markFailed(nextStatus, rawPayload);
|
||||||
|
|
||||||
|
if (!success) {
|
||||||
|
return toVerifyResponse(payment, data.path("gateway_response").asText("Payment was not successful"));
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new IllegalArgumentException("Paystack verification did not match the stored payment");
|
||||||
|
}
|
||||||
|
|
||||||
|
private CheckoutQuote calculateQuote(
|
||||||
|
java.util.List<com.andwati.orders.dto.request.CreateOrderItemRequest> items,
|
||||||
|
com.andwati.orders.dto.request.CreateOrderRideRequest deliveryRide
|
||||||
|
) {
|
||||||
|
if (items == null || items.isEmpty()) {
|
||||||
|
throw new IllegalArgumentException("items must contain at least one item");
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<UUID, Integer> requestedQuantities = items.stream()
|
||||||
|
.collect(Collectors.toMap(
|
||||||
|
com.andwati.orders.dto.request.CreateOrderItemRequest::productId,
|
||||||
|
com.andwati.orders.dto.request.CreateOrderItemRequest::quantity,
|
||||||
|
Integer::sum,
|
||||||
|
LinkedHashMap::new
|
||||||
|
));
|
||||||
|
|
||||||
|
Map<UUID, Product> productsById = productRepository.findByIdIn(requestedQuantities.keySet())
|
||||||
|
.stream()
|
||||||
|
.collect(Collectors.toMap(Product::getId, Function.identity()));
|
||||||
|
|
||||||
|
for (UUID productId : requestedQuantities.keySet()) {
|
||||||
|
Product product = productsById.get(productId);
|
||||||
|
if (product == null) {
|
||||||
|
throw new ProductNotFoundException(productId);
|
||||||
|
}
|
||||||
|
if (!product.isActive()) {
|
||||||
|
throw new IllegalArgumentException("Product " + product.getName() + " is not active");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<UUID, InventoryItem> inventoryByProductId = inventoryItemRepository
|
||||||
|
.findByProduct_IdIn(requestedQuantities.keySet())
|
||||||
|
.stream()
|
||||||
|
.collect(Collectors.toMap(
|
||||||
|
inventory -> inventory.getProduct().getId(),
|
||||||
|
Function.identity()
|
||||||
|
));
|
||||||
|
|
||||||
|
BigDecimal productSubtotal = BigDecimal.ZERO;
|
||||||
|
String currency = null;
|
||||||
|
|
||||||
|
for (Map.Entry<UUID, Integer> entry : requestedQuantities.entrySet()) {
|
||||||
|
UUID productId = entry.getKey();
|
||||||
|
int quantity = entry.getValue();
|
||||||
|
if (quantity < 1) {
|
||||||
|
throw new IllegalArgumentException("quantity must be at least 1");
|
||||||
|
}
|
||||||
|
|
||||||
|
Product product = productsById.get(productId);
|
||||||
|
InventoryItem inventory = inventoryByProductId.get(productId);
|
||||||
|
if (inventory == null) {
|
||||||
|
throw new InventoryNotFoundException(productId);
|
||||||
|
}
|
||||||
|
if (!inventory.hasEnoughStock(quantity)) {
|
||||||
|
throw new InsufficientStockException(
|
||||||
|
productId,
|
||||||
|
product.getName(),
|
||||||
|
quantity,
|
||||||
|
inventory.getAvailableQuantity()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (currency == null) {
|
||||||
|
currency = product.getCurrency();
|
||||||
|
} else if (!currency.equals(product.getCurrency())) {
|
||||||
|
throw new IllegalArgumentException("Cart items must use one currency");
|
||||||
|
}
|
||||||
|
|
||||||
|
productSubtotal = productSubtotal.add(product.getPrice().multiply(BigDecimal.valueOf(quantity)));
|
||||||
|
}
|
||||||
|
|
||||||
|
BigDecimal rideFare = BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP);
|
||||||
|
if (deliveryRide != null) {
|
||||||
|
FareCalculationResponse fare = fareCalculationService.calculateFare(deliveryRide.distanceKm(), null);
|
||||||
|
if (currency != null && !currency.equals(fare.currency())) {
|
||||||
|
throw new IllegalArgumentException("Ride fare currency must match cart currency");
|
||||||
|
}
|
||||||
|
currency = fare.currency();
|
||||||
|
rideFare = fare.calculatedFare();
|
||||||
|
}
|
||||||
|
|
||||||
|
String resolvedCurrency = currency == null ? DEFAULT_CURRENCY : currency;
|
||||||
|
BigDecimal normalizedSubtotal = productSubtotal.setScale(2, RoundingMode.HALF_UP);
|
||||||
|
BigDecimal normalizedRideFare = rideFare.setScale(2, RoundingMode.HALF_UP);
|
||||||
|
|
||||||
|
return new CheckoutQuote(
|
||||||
|
normalizedSubtotal,
|
||||||
|
normalizedRideFare,
|
||||||
|
normalizedSubtotal.add(normalizedRideFare).setScale(2, RoundingMode.HALF_UP),
|
||||||
|
resolvedCurrency
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private CheckoutQuoteResponse toQuoteResponse(CheckoutQuote quote) {
|
||||||
|
return new CheckoutQuoteResponse(
|
||||||
|
quote.productSubtotal(),
|
||||||
|
quote.rideFare(),
|
||||||
|
quote.grandTotal(),
|
||||||
|
quote.currency(),
|
||||||
|
Instant.now().plusSeconds(QUOTE_TTL_MINUTES * 60L)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private PaystackInitializeResponse toInitializeResponse(Payment payment) {
|
||||||
|
return new PaystackInitializeResponse(
|
||||||
|
payment.getAuthorizationUrl(),
|
||||||
|
payment.getAccessCode(),
|
||||||
|
payment.getReference(),
|
||||||
|
payment.getOrder().getId(),
|
||||||
|
payment.getRide() == null ? null : payment.getRide().getId(),
|
||||||
|
payment.getAmountMajor(),
|
||||||
|
payment.getCurrency(),
|
||||||
|
payment.getStatus()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private PaystackVerifyResponse toVerifyResponse(Payment payment, String message) {
|
||||||
|
return new PaystackVerifyResponse(
|
||||||
|
payment.getReference(),
|
||||||
|
payment.getStatus(),
|
||||||
|
payment.getOrder().getId(),
|
||||||
|
payment.getRide() == null ? null : payment.getRide().getId(),
|
||||||
|
payment.getAmountMajor(),
|
||||||
|
payment.getCurrency(),
|
||||||
|
message
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, Object> buildMetadata(AppUser customer, Payment payment) {
|
||||||
|
Map<String, Object> metadata = new LinkedHashMap<>();
|
||||||
|
metadata.put("orderId", payment.getOrder().getId().toString());
|
||||||
|
metadata.put("rideId", payment.getRide() == null ? null : payment.getRide().getId().toString());
|
||||||
|
metadata.put("userId", customer.getId().toString());
|
||||||
|
metadata.put("productSubtotal", payment.getProductSubtotal());
|
||||||
|
metadata.put("rideFare", payment.getRideFare());
|
||||||
|
metadata.put("grandTotal", payment.getAmountMajor());
|
||||||
|
metadata.put("currency", payment.getCurrency());
|
||||||
|
return metadata;
|
||||||
|
}
|
||||||
|
|
||||||
|
private long toSubunits(BigDecimal amount) {
|
||||||
|
return amount.setScale(2, RoundingMode.HALF_UP)
|
||||||
|
.movePointRight(2)
|
||||||
|
.longValueExact();
|
||||||
|
}
|
||||||
|
|
||||||
|
private String generateReference() {
|
||||||
|
return "CYM-" + UUID.randomUUID();
|
||||||
|
}
|
||||||
|
|
||||||
|
private Payment getPayment(String reference) {
|
||||||
|
return paymentRepository.findByReference(reference)
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Payment reference was not found"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void assertCanAccess(Payment payment) {
|
||||||
|
AppUser currentUser = appUserService.getCurrentUser();
|
||||||
|
if (currentUser.getRole() == Role.ADMIN) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
AppUser customer = payment.getOrder().getCustomer();
|
||||||
|
if (currentUser.getRole() == Role.CUSTOMER
|
||||||
|
&& customer != null
|
||||||
|
&& currentUser.getId().equals(customer.getId())) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new IllegalArgumentException("You cannot access this payment");
|
||||||
|
}
|
||||||
|
|
||||||
|
private PaymentStatus mapPaystackStatus(String status) {
|
||||||
|
return switch (status) {
|
||||||
|
case "abandoned" -> PaymentStatus.ABANDONED;
|
||||||
|
case "reversed" -> PaymentStatus.REFUNDED;
|
||||||
|
default -> PaymentStatus.FAILED;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private void verifyWebhookSignature(String body, String signature) {
|
||||||
|
String secret = paystackProperties.resolvedWebhookSecret();
|
||||||
|
if (secret == null || secret.isBlank()) {
|
||||||
|
throw new IllegalStateException("PAYSTACK_WEBHOOK_SECRET or PAYSTACK_SECRET_KEY is not configured");
|
||||||
|
}
|
||||||
|
if (signature == null || signature.isBlank()) {
|
||||||
|
throw new IllegalArgumentException("Paystack signature is required");
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
Mac mac = Mac.getInstance("HmacSHA512");
|
||||||
|
mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA512"));
|
||||||
|
String expected = HexFormat.of().formatHex(mac.doFinal(body.getBytes(StandardCharsets.UTF_8)));
|
||||||
|
if (!constantTimeEquals(expected, signature)) {
|
||||||
|
throw new IllegalArgumentException("Invalid Paystack signature");
|
||||||
|
}
|
||||||
|
} catch (IllegalArgumentException exception) {
|
||||||
|
throw exception;
|
||||||
|
} catch (Exception exception) {
|
||||||
|
throw new IllegalStateException("Could not verify Paystack signature", exception);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean constantTimeEquals(String expected, String actual) {
|
||||||
|
byte[] expectedBytes = expected.getBytes(StandardCharsets.UTF_8);
|
||||||
|
byte[] actualBytes = actual.getBytes(StandardCharsets.UTF_8);
|
||||||
|
if (expectedBytes.length != actualBytes.length) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
int result = 0;
|
||||||
|
for (int index = 0; index < expectedBytes.length; index++) {
|
||||||
|
result |= expectedBytes[index] ^ actualBytes[index];
|
||||||
|
}
|
||||||
|
return result == 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String toJson(JsonNode node) {
|
||||||
|
try {
|
||||||
|
return objectMapper.writeValueAsString(node);
|
||||||
|
} catch (JsonProcessingException exception) {
|
||||||
|
throw new IllegalStateException("Could not serialize Paystack verification payload", exception);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private record CheckoutQuote(
|
||||||
|
BigDecimal productSubtotal,
|
||||||
|
BigDecimal rideFare,
|
||||||
|
BigDecimal grandTotal,
|
||||||
|
String currency
|
||||||
|
) {
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
package com.andwati.orders.services;
|
||||||
|
|
||||||
|
import com.andwati.orders.config.PaystackProperties;
|
||||||
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.web.client.RestClient;
|
||||||
|
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class PaystackClient {
|
||||||
|
|
||||||
|
private final PaystackProperties paystackProperties;
|
||||||
|
private final RestClient restClient;
|
||||||
|
|
||||||
|
public PaystackClient(PaystackProperties paystackProperties, RestClient.Builder restClientBuilder) {
|
||||||
|
this.paystackProperties = paystackProperties;
|
||||||
|
this.restClient = restClientBuilder
|
||||||
|
.baseUrl(paystackProperties.resolvedApiBaseUrl())
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
public JsonNode initializeTransaction(
|
||||||
|
String email,
|
||||||
|
long amountSubunits,
|
||||||
|
String currency,
|
||||||
|
String reference,
|
||||||
|
Map<String, Object> metadata
|
||||||
|
) {
|
||||||
|
assertConfigured();
|
||||||
|
|
||||||
|
Map<String, Object> body = new LinkedHashMap<>();
|
||||||
|
body.put("email", email);
|
||||||
|
body.put("amount", String.valueOf(amountSubunits));
|
||||||
|
body.put("currency", currency);
|
||||||
|
body.put("reference", reference);
|
||||||
|
body.put("metadata", metadata);
|
||||||
|
|
||||||
|
if (paystackProperties.hasCallbackUrl()) {
|
||||||
|
body.put("callback_url", paystackProperties.callbackUrl());
|
||||||
|
}
|
||||||
|
|
||||||
|
JsonNode response = restClient.post()
|
||||||
|
.uri("/transaction/initialize")
|
||||||
|
.headers(headers -> headers.setBearerAuth(paystackProperties.secretKey()))
|
||||||
|
.body(body)
|
||||||
|
.retrieve()
|
||||||
|
.body(JsonNode.class);
|
||||||
|
|
||||||
|
assertSuccessful(response, "Paystack transaction initialization failed");
|
||||||
|
return response.path("data");
|
||||||
|
}
|
||||||
|
|
||||||
|
public JsonNode verifyTransaction(String reference) {
|
||||||
|
assertConfigured();
|
||||||
|
|
||||||
|
JsonNode response = restClient.get()
|
||||||
|
.uri("/transaction/verify/{reference}", reference)
|
||||||
|
.headers(headers -> headers.setBearerAuth(paystackProperties.secretKey()))
|
||||||
|
.retrieve()
|
||||||
|
.body(JsonNode.class);
|
||||||
|
|
||||||
|
assertSuccessful(response, "Paystack transaction verification failed");
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void assertConfigured() {
|
||||||
|
if (!paystackProperties.hasSecretKey()) {
|
||||||
|
throw new IllegalStateException("PAYSTACK_SECRET_KEY is not configured");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void assertSuccessful(JsonNode response, String fallbackMessage) {
|
||||||
|
if (response == null || !response.path("status").asBoolean(false)) {
|
||||||
|
String message = response == null ? fallbackMessage : response.path("message").asText(fallbackMessage);
|
||||||
|
throw new IllegalStateException(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package com.andwati.orders.services;
|
||||||
|
|
||||||
|
import com.andwati.orders.model.Order;
|
||||||
|
import com.andwati.orders.model.Ride;
|
||||||
|
|
||||||
|
public record PendingOrderResult(Order order, Ride ride) {
|
||||||
|
}
|
||||||
@@ -20,6 +20,12 @@ fare.minimum-fare=${FARE_MINIMUM_FARE:150.00}
|
|||||||
fare.default-surge-multiplier=${FARE_DEFAULT_SURGE_MULTIPLIER:1.0}
|
fare.default-surge-multiplier=${FARE_DEFAULT_SURGE_MULTIPLIER:1.0}
|
||||||
fare.currency=${FARE_CURRENCY:KES}
|
fare.currency=${FARE_CURRENCY:KES}
|
||||||
|
|
||||||
|
paystack.secret-key=${PAYSTACK_SECRET_KEY:}
|
||||||
|
paystack.public-key=${PAYSTACK_PUBLIC_KEY:}
|
||||||
|
paystack.callback-url=${PAYSTACK_CALLBACK_URL:}
|
||||||
|
paystack.webhook-secret=${PAYSTACK_WEBHOOK_SECRET:}
|
||||||
|
paystack.api-base-url=${PAYSTACK_API_BASE_URL:https://api.paystack.co}
|
||||||
|
|
||||||
app.seed-data=${SEED_DATA:true}
|
app.seed-data=${SEED_DATA:true}
|
||||||
app.cors.allowed-origins=${APP_CORS_ALLOWED_ORIGINS:http://localhost:3000}
|
app.cors.allowed-origins=${APP_CORS_ALLOWED_ORIGINS:http://localhost:3000}
|
||||||
springdoc.api-docs.path=/api-docs
|
springdoc.api-docs.path=/api-docs
|
||||||
|
|||||||
+33
-33
@@ -1,35 +1,35 @@
|
|||||||
{
|
{
|
||||||
"files.watcherExclude": {
|
"files.watcherExclude": {
|
||||||
"**/routeTree.gen.ts": true
|
"**/routeTree.gen.ts": true
|
||||||
},
|
},
|
||||||
"search.exclude": {
|
"search.exclude": {
|
||||||
"**/routeTree.gen.ts": true
|
"**/routeTree.gen.ts": true
|
||||||
},
|
},
|
||||||
"files.readonlyInclude": {
|
"files.readonlyInclude": {
|
||||||
"**/routeTree.gen.ts": true
|
"**/routeTree.gen.ts": true
|
||||||
},
|
},
|
||||||
"[javascript]": {
|
"[javascript]": {
|
||||||
"editor.defaultFormatter": "biomejs.biome"
|
"editor.defaultFormatter": "biomejs.biome"
|
||||||
},
|
},
|
||||||
"[javascriptreact]": {
|
"[javascriptreact]": {
|
||||||
"editor.defaultFormatter": "biomejs.biome"
|
"editor.defaultFormatter": "biomejs.biome"
|
||||||
},
|
},
|
||||||
"[typescript]": {
|
"[typescript]": {
|
||||||
"editor.defaultFormatter": "biomejs.biome"
|
"editor.defaultFormatter": "biomejs.biome"
|
||||||
},
|
},
|
||||||
"[typescriptreact]": {
|
"[typescriptreact]": {
|
||||||
"editor.defaultFormatter": "biomejs.biome"
|
"editor.defaultFormatter": "biomejs.biome"
|
||||||
},
|
},
|
||||||
"[json]": {
|
"[json]": {
|
||||||
"editor.defaultFormatter": "biomejs.biome"
|
"editor.defaultFormatter": "biomejs.biome"
|
||||||
},
|
},
|
||||||
"[jsonc]": {
|
"[jsonc]": {
|
||||||
"editor.defaultFormatter": "biomejs.biome"
|
"editor.defaultFormatter": "biomejs.biome"
|
||||||
},
|
},
|
||||||
"[css]": {
|
"[css]": {
|
||||||
"editor.defaultFormatter": "biomejs.biome"
|
"editor.defaultFormatter": "biomejs.biome"
|
||||||
},
|
},
|
||||||
"editor.codeActionsOnSave": {
|
"editor.codeActionsOnSave": {
|
||||||
"source.organizeImports.biome": "explicit"
|
"source.organizeImports.biome": "explicit"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
FROM node:22-bookworm-slim AS build
|
FROM node:24-bookworm-slim AS build
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
@@ -14,7 +14,7 @@ ENV VITE_API_BASE_URL=$VITE_API_BASE_URL
|
|||||||
|
|
||||||
RUN pnpm build
|
RUN pnpm build
|
||||||
|
|
||||||
FROM node:22-bookworm-slim
|
FROM node:24-bookworm-slim
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
{
|
{
|
||||||
"$schema": "https://biomejs.dev/schemas/2.2.4/schema.json",
|
"$schema": "https://biomejs.dev/schemas/2.4.5/schema.json",
|
||||||
"vcs": {
|
"vcs": {
|
||||||
"enabled": false,
|
"enabled": false,
|
||||||
"clientKind": "git",
|
"clientKind": "git",
|
||||||
@@ -33,4 +33,3 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,25 +1,25 @@
|
|||||||
import {apiRequest, clearRequestSecurity} from "#/api/client";
|
import { apiRequest, clearRequestSecurity } from "#/api/client";
|
||||||
import type {AuthUser, LoginRequest, RegisterRequest} from "#/types/auth";
|
import type { AuthUser, LoginRequest, RegisterRequest } from "#/types/auth";
|
||||||
|
|
||||||
export function getCurrentUser(signal?: AbortSignal) {
|
export function getCurrentUser(signal?: AbortSignal) {
|
||||||
return apiRequest<AuthUser>("/auth/me", {signal});
|
return apiRequest<AuthUser>("/auth/me", { signal });
|
||||||
}
|
}
|
||||||
|
|
||||||
export function login(request: LoginRequest) {
|
export function login(request: LoginRequest) {
|
||||||
return apiRequest<AuthUser>("/auth/login", {
|
return apiRequest<AuthUser>("/auth/login", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
body: request,
|
body: request,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function register(request: RegisterRequest) {
|
export function register(request: RegisterRequest) {
|
||||||
return apiRequest<AuthUser>("/auth/register", {
|
return apiRequest<AuthUser>("/auth/register", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
body: request,
|
body: request,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function logout() {
|
export async function logout() {
|
||||||
await apiRequest<void>("/auth/logout", {method: "POST"});
|
await apiRequest<void>("/auth/logout", { method: "POST" });
|
||||||
clearRequestSecurity();
|
clearRequestSecurity();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,110 +1,112 @@
|
|||||||
import type {ApiErrorResponse} from "#/types/api";
|
import type { ApiErrorResponse } from "#/types/api";
|
||||||
|
|
||||||
const API_BASE_URL =
|
const API_BASE_URL =
|
||||||
import.meta.env.VITE_API_BASE_URL ?? "http://localhost:8080/api";
|
import.meta.env.VITE_API_BASE_URL ?? "http://localhost:8080/api";
|
||||||
|
|
||||||
let csrfToken: string | null = null;
|
let csrfToken: string | null = null;
|
||||||
let csrfHeaderName = "X-XSRF-TOKEN";
|
let csrfHeaderName = "X-XSRF-TOKEN";
|
||||||
|
|
||||||
export class ApiError extends Error {
|
export class ApiError extends Error {
|
||||||
status: number;
|
status: number;
|
||||||
code: string;
|
code: string;
|
||||||
details: unknown;
|
details: unknown;
|
||||||
|
|
||||||
constructor(status: number, error: ApiErrorResponse) {
|
constructor(status: number, error: ApiErrorResponse) {
|
||||||
super(error.message || "Request failed");
|
super(error.message || "Request failed");
|
||||||
this.name = "ApiError";
|
this.name = "ApiError";
|
||||||
this.status = status;
|
this.status = status;
|
||||||
this.code = error.error;
|
this.code = error.error;
|
||||||
this.details = error.details;
|
this.details = error.details;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type RequestOptions = {
|
type RequestOptions = {
|
||||||
method?: "GET" | "POST" | "DELETE" | "PUT" | "PATCH";
|
method?: "GET" | "POST" | "DELETE" | "PUT" | "PATCH";
|
||||||
body?: unknown;
|
body?: unknown;
|
||||||
signal?: AbortSignal;
|
signal?: AbortSignal;
|
||||||
};
|
};
|
||||||
|
|
||||||
type CsrfResponse = {
|
type CsrfResponse = {
|
||||||
headerName: string;
|
headerName: string;
|
||||||
parameterName: string;
|
parameterName: string;
|
||||||
token: string;
|
token: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
async function loadCsrfToken() {
|
async function loadCsrfToken() {
|
||||||
const response = await fetch(`${API_BASE_URL}/auth/csrf`, {
|
const response = await fetch(`${API_BASE_URL}/auth/csrf`, {
|
||||||
credentials: "include",
|
credentials: "include",
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
throw new Error("Could not initialize request security");
|
throw new Error("Could not initialize request security");
|
||||||
}
|
}
|
||||||
|
|
||||||
const data = (await response.json()) as CsrfResponse;
|
const data = (await response.json()) as CsrfResponse;
|
||||||
csrfToken = data.token;
|
csrfToken = data.token;
|
||||||
csrfHeaderName = data.headerName;
|
csrfHeaderName = data.headerName;
|
||||||
}
|
}
|
||||||
|
|
||||||
function isMutating(method: string) {
|
function isMutating(method: string) {
|
||||||
return method !== "GET";
|
return method !== "GET";
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function apiRequest<T>(
|
export async function apiRequest<T>(
|
||||||
path: string,
|
path: string,
|
||||||
options: RequestOptions = {},
|
options: RequestOptions = {},
|
||||||
): Promise<T> {
|
): Promise<T> {
|
||||||
const method = options.method ?? "GET";
|
const method = options.method ?? "GET";
|
||||||
|
|
||||||
if (isMutating(method) && !csrfToken) {
|
if (isMutating(method) && !csrfToken) {
|
||||||
await loadCsrfToken();
|
await loadCsrfToken();
|
||||||
}
|
}
|
||||||
|
|
||||||
const response = await fetch(`${API_BASE_URL}${path}`, {
|
const response = await fetch(`${API_BASE_URL}${path}`, {
|
||||||
method,
|
method,
|
||||||
credentials: "include",
|
credentials: "include",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
...(isMutating(method) && csrfToken ? {[csrfHeaderName]: csrfToken} : {}),
|
...(isMutating(method) && csrfToken
|
||||||
},
|
? { [csrfHeaderName]: csrfToken }
|
||||||
body: options.body ? JSON.stringify(options.body) : undefined,
|
: {}),
|
||||||
signal: options.signal,
|
},
|
||||||
});
|
body: options.body ? JSON.stringify(options.body) : undefined,
|
||||||
|
signal: options.signal,
|
||||||
|
});
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
let errorBody: ApiErrorResponse;
|
let errorBody: ApiErrorResponse;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
errorBody = await response.json();
|
errorBody = await response.json();
|
||||||
} catch {
|
} catch {
|
||||||
errorBody = {
|
errorBody = {
|
||||||
error: "REQUEST_FAILED",
|
error: "REQUEST_FAILED",
|
||||||
message: `Request failed with status ${response.status}`,
|
message: `Request failed with status ${response.status}`,
|
||||||
details: null,
|
details: null,
|
||||||
timestamp: new Date().toISOString(),
|
timestamp: new Date().toISOString(),
|
||||||
path,
|
path,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
throw new ApiError(response.status, errorBody);
|
throw new ApiError(response.status, errorBody);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (response.status === 204) {
|
if (response.status === 204) {
|
||||||
return undefined as T;
|
return undefined as T;
|
||||||
}
|
}
|
||||||
|
|
||||||
const text = await response.text();
|
const text = await response.text();
|
||||||
if (!text) {
|
if (!text) {
|
||||||
return undefined as T;
|
return undefined as T;
|
||||||
}
|
}
|
||||||
|
|
||||||
return JSON.parse(text) as T;
|
return JSON.parse(text) as T;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function clearRequestSecurity() {
|
export function clearRequestSecurity() {
|
||||||
csrfToken = null;
|
csrfToken = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function initializeRequestSecurity() {
|
export async function initializeRequestSecurity() {
|
||||||
await loadCsrfToken();
|
await loadCsrfToken();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,20 +1,20 @@
|
|||||||
import {apiRequest} from "#/api/client";
|
import { apiRequest } from "#/api/client";
|
||||||
import type {FareCalculationResponse} from "#/types/fare";
|
import type { FareCalculationResponse } from "#/types/fare";
|
||||||
|
|
||||||
export function calculateFare(
|
export function calculateFare(
|
||||||
distanceKm: number,
|
distanceKm: number,
|
||||||
surgeMultiplier?: number,
|
surgeMultiplier?: number,
|
||||||
signal?: AbortSignal,
|
signal?: AbortSignal,
|
||||||
) {
|
) {
|
||||||
const params = new URLSearchParams();
|
const params = new URLSearchParams();
|
||||||
params.set("distanceKm", String(distanceKm));
|
params.set("distanceKm", String(distanceKm));
|
||||||
|
|
||||||
if (surgeMultiplier !== undefined) {
|
if (surgeMultiplier !== undefined) {
|
||||||
params.set("surgeMultiplier", String(surgeMultiplier));
|
params.set("surgeMultiplier", String(surgeMultiplier));
|
||||||
}
|
}
|
||||||
|
|
||||||
return apiRequest<FareCalculationResponse>(
|
return apiRequest<FareCalculationResponse>(
|
||||||
`/fare/calculate?${params.toString()}`,
|
`/fare/calculate?${params.toString()}`,
|
||||||
{signal},
|
{ signal },
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1,24 +1,24 @@
|
|||||||
import {apiRequest} from "#/api/client";
|
import { apiRequest } from "#/api/client";
|
||||||
import type {InventoryResponse, LowStockInventoryResponse,} from "#/types/inventory";
|
import type {
|
||||||
|
InventoryResponse,
|
||||||
|
LowStockInventoryResponse,
|
||||||
|
} from "#/types/inventory";
|
||||||
|
|
||||||
export function getInventory(signal?: AbortSignal) {
|
export function getInventory(signal?: AbortSignal) {
|
||||||
return apiRequest<InventoryResponse>("/inventory", {signal});
|
return apiRequest<InventoryResponse>("/inventory", { signal });
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getLowStockInventory(
|
export function getLowStockInventory(threshold?: number, signal?: AbortSignal) {
|
||||||
threshold?: number,
|
const params = new URLSearchParams();
|
||||||
signal?: AbortSignal,
|
|
||||||
) {
|
|
||||||
const params = new URLSearchParams();
|
|
||||||
|
|
||||||
if (threshold !== undefined) {
|
if (threshold !== undefined) {
|
||||||
params.set("threshold", String(threshold));
|
params.set("threshold", String(threshold));
|
||||||
}
|
}
|
||||||
|
|
||||||
const query = params.toString();
|
const query = params.toString();
|
||||||
|
|
||||||
return apiRequest<LowStockInventoryResponse>(
|
return apiRequest<LowStockInventoryResponse>(
|
||||||
`/inventory/low-stock${query ? `?${query}` : ""}`,
|
`/inventory/low-stock${query ? `?${query}` : ""}`,
|
||||||
{signal},
|
{ signal },
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1,62 +1,65 @@
|
|||||||
import {apiRequest} from "#/api/client";
|
import { apiRequest } from "#/api/client";
|
||||||
import type {PageResponse} from "#/types/api";
|
import type { PageResponse } from "#/types/api";
|
||||||
import type {
|
import type {
|
||||||
CancelOrderResponse,
|
CancelOrderResponse,
|
||||||
CreateOrderRequest,
|
CreateOrderRequest,
|
||||||
Order,
|
Order,
|
||||||
OrderFilters,
|
OrderFilters,
|
||||||
OrderStatus,
|
OrderStatus,
|
||||||
OrderSummary,
|
OrderSummary,
|
||||||
} from "#/types/order";
|
} from "#/types/order";
|
||||||
|
|
||||||
export function getOrders(
|
export function getOrders(
|
||||||
filters: OrderFilters,
|
filters: OrderFilters,
|
||||||
page = 0,
|
page = 0,
|
||||||
size = 20,
|
size = 20,
|
||||||
signal?: AbortSignal,
|
signal?: AbortSignal,
|
||||||
) {
|
) {
|
||||||
const params = new URLSearchParams();
|
const params = new URLSearchParams();
|
||||||
|
|
||||||
if (filters.status) {
|
if (filters.status) {
|
||||||
params.set("status", filters.status);
|
params.set("status", filters.status);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (filters.from) {
|
if (filters.from) {
|
||||||
params.set("from", filters.from);
|
params.set("from", filters.from);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (filters.to) {
|
if (filters.to) {
|
||||||
params.set("to", filters.to);
|
params.set("to", filters.to);
|
||||||
}
|
}
|
||||||
|
|
||||||
params.set("page", String(page));
|
params.set("page", String(page));
|
||||||
params.set("size", String(size));
|
params.set("size", String(size));
|
||||||
|
|
||||||
return apiRequest<PageResponse<OrderSummary>>(`/orders?${params.toString()}`, {
|
return apiRequest<PageResponse<OrderSummary>>(
|
||||||
signal,
|
`/orders?${params.toString()}`,
|
||||||
});
|
{
|
||||||
|
signal,
|
||||||
|
},
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getOrder(id: string, signal?: AbortSignal) {
|
export function getOrder(id: string, signal?: AbortSignal) {
|
||||||
return apiRequest<Order>(`/orders/${id}`, {signal});
|
return apiRequest<Order>(`/orders/${id}`, { signal });
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createOrder(request: CreateOrderRequest) {
|
export function createOrder(request: CreateOrderRequest) {
|
||||||
return apiRequest<Order>("/orders", {
|
return apiRequest<Order>("/orders", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
body: request,
|
body: request,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function cancelOrder(id: string) {
|
export function cancelOrder(id: string) {
|
||||||
return apiRequest<CancelOrderResponse>(`/orders/${id}`, {
|
return apiRequest<CancelOrderResponse>(`/orders/${id}`, {
|
||||||
method: "DELETE",
|
method: "DELETE",
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function updateOrderStatus(id: string, status: OrderStatus) {
|
export function updateOrderStatus(id: string, status: OrderStatus) {
|
||||||
return apiRequest<Order>(`/orders/${id}/status`, {
|
return apiRequest<Order>(`/orders/${id}/status`, {
|
||||||
method: "PATCH",
|
method: "PATCH",
|
||||||
body: {status},
|
body: { status },
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import { apiRequest } from "#/api/client";
|
||||||
|
import type {
|
||||||
|
CheckoutQuote,
|
||||||
|
CheckoutQuoteRequest,
|
||||||
|
PaystackInitializeRequest,
|
||||||
|
PaystackInitializeResponse,
|
||||||
|
PaystackVerifyResponse,
|
||||||
|
} from "#/types/payment";
|
||||||
|
|
||||||
|
export function getCheckoutQuote(
|
||||||
|
request: CheckoutQuoteRequest,
|
||||||
|
signal?: AbortSignal,
|
||||||
|
) {
|
||||||
|
return apiRequest<CheckoutQuote>("/checkout/quote", {
|
||||||
|
method: "POST",
|
||||||
|
body: request,
|
||||||
|
signal,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function initializePaystackPayment(request: PaystackInitializeRequest) {
|
||||||
|
return apiRequest<PaystackInitializeResponse>(
|
||||||
|
"/payments/paystack/initialize",
|
||||||
|
{
|
||||||
|
method: "POST",
|
||||||
|
body: request,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function verifyPaystackPayment(reference: string) {
|
||||||
|
return apiRequest<PaystackVerifyResponse>(
|
||||||
|
`/payments/paystack/verify/${encodeURIComponent(reference)}`,
|
||||||
|
{
|
||||||
|
method: "POST",
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,28 +1,28 @@
|
|||||||
import {apiRequest} from "#/api/client";
|
import { apiRequest } from "#/api/client";
|
||||||
import type {Product, ProductRequest} from "#/types/product";
|
import type { Product, ProductRequest } from "#/types/product";
|
||||||
|
|
||||||
export function getProducts(signal?: AbortSignal) {
|
export function getProducts(signal?: AbortSignal) {
|
||||||
return apiRequest<Product[]>("/products", {signal});
|
return apiRequest<Product[]>("/products", { signal });
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getProduct(id: string, signal?: AbortSignal) {
|
export function getProduct(id: string, signal?: AbortSignal) {
|
||||||
return apiRequest<Product>(`/products/${id}`, {signal});
|
return apiRequest<Product>(`/products/${id}`, { signal });
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createProduct(request: ProductRequest) {
|
export function createProduct(request: ProductRequest) {
|
||||||
return apiRequest<Product>("/products", {
|
return apiRequest<Product>("/products", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
body: request,
|
body: request,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function updateProduct(id: string, request: ProductRequest) {
|
export function updateProduct(id: string, request: ProductRequest) {
|
||||||
return apiRequest<Product>(`/products/${id}`, {
|
return apiRequest<Product>(`/products/${id}`, {
|
||||||
method: "PUT",
|
method: "PUT",
|
||||||
body: request,
|
body: request,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function deactivateProduct(id: string) {
|
export function deactivateProduct(id: string) {
|
||||||
return apiRequest<Product>(`/products/${id}`, {method: "DELETE"});
|
return apiRequest<Product>(`/products/${id}`, { method: "DELETE" });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,32 +1,32 @@
|
|||||||
import {apiRequest} from "#/api/client";
|
import { apiRequest } from "#/api/client";
|
||||||
import type {CreateRideRequest, Ride, RideStatus} from "#/types/ride";
|
import type { CreateRideRequest, Ride, RideStatus } from "#/types/ride";
|
||||||
|
|
||||||
export function getRides(signal?: AbortSignal) {
|
export function getRides(signal?: AbortSignal) {
|
||||||
return apiRequest<Ride[]>("/rides", {signal});
|
return apiRequest<Ride[]>("/rides", { signal });
|
||||||
}
|
}
|
||||||
|
|
||||||
export function requestRide(request: CreateRideRequest) {
|
export function requestRide(request: CreateRideRequest) {
|
||||||
return apiRequest<Ride>("/rides", {
|
return apiRequest<Ride>("/rides", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
body: request,
|
body: request,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function acceptRide(id: string) {
|
export function acceptRide(id: string) {
|
||||||
return apiRequest<Ride>(`/rides/${id}/accept`, {method: "POST"});
|
return apiRequest<Ride>(`/rides/${id}/accept`, { method: "POST" });
|
||||||
}
|
}
|
||||||
|
|
||||||
export function completeRide(id: string) {
|
export function completeRide(id: string) {
|
||||||
return apiRequest<Ride>(`/rides/${id}/complete`, {method: "POST"});
|
return apiRequest<Ride>(`/rides/${id}/complete`, { method: "POST" });
|
||||||
}
|
}
|
||||||
|
|
||||||
export function cancelRide(id: string) {
|
export function cancelRide(id: string) {
|
||||||
return apiRequest<Ride>(`/rides/${id}`, {method: "DELETE"});
|
return apiRequest<Ride>(`/rides/${id}`, { method: "DELETE" });
|
||||||
}
|
}
|
||||||
|
|
||||||
export function updateRideStatus(id: string, status: RideStatus) {
|
export function updateRideStatus(id: string, status: RideStatus) {
|
||||||
return apiRequest<Ride>(`/rides/${id}/status`, {
|
return apiRequest<Ride>(`/rides/${id}/status`, {
|
||||||
method: "PATCH",
|
method: "PATCH",
|
||||||
body: {status},
|
body: { status },
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,32 +1,32 @@
|
|||||||
import {apiRequest} from "#/api/client";
|
import { apiRequest } from "#/api/client";
|
||||||
import type {AdminUserRequest, UserSummary} from "#/types/user";
|
import type { AdminUserRequest, UserSummary } from "#/types/user";
|
||||||
|
|
||||||
export function getUsers(signal?: AbortSignal) {
|
export function getUsers(signal?: AbortSignal) {
|
||||||
return apiRequest<UserSummary[]>("/users", {signal});
|
return apiRequest<UserSummary[]>("/users", { signal });
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getCustomers(signal?: AbortSignal) {
|
export function getCustomers(signal?: AbortSignal) {
|
||||||
return apiRequest<UserSummary[]>("/users/customers", {signal});
|
return apiRequest<UserSummary[]>("/users/customers", { signal });
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getDrivers(signal?: AbortSignal) {
|
export function getDrivers(signal?: AbortSignal) {
|
||||||
return apiRequest<UserSummary[]>("/users/drivers", {signal});
|
return apiRequest<UserSummary[]>("/users/drivers", { signal });
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createUser(request: AdminUserRequest) {
|
export function createUser(request: AdminUserRequest) {
|
||||||
return apiRequest<UserSummary>("/users", {
|
return apiRequest<UserSummary>("/users", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
body: request,
|
body: request,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function updateUser(id: string, request: AdminUserRequest) {
|
export function updateUser(id: string, request: AdminUserRequest) {
|
||||||
return apiRequest<UserSummary>(`/users/${id}`, {
|
return apiRequest<UserSummary>(`/users/${id}`, {
|
||||||
method: "PUT",
|
method: "PUT",
|
||||||
body: request,
|
body: request,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function disableUser(id: string) {
|
export function disableUser(id: string) {
|
||||||
return apiRequest<UserSummary>(`/users/${id}`, {method: "DELETE"});
|
return apiRequest<UserSummary>(`/users/${id}`, { method: "DELETE" });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,199 +1,202 @@
|
|||||||
"use client"
|
"use client";
|
||||||
|
|
||||||
import * as React from "react"
|
|
||||||
import {
|
import {
|
||||||
Boxes,
|
Boxes,
|
||||||
Car,
|
Car,
|
||||||
GalleryVerticalEnd,
|
GalleryVerticalEnd,
|
||||||
LayoutDashboard,
|
LayoutDashboard,
|
||||||
ReceiptText,
|
ReceiptText,
|
||||||
ShoppingCart,
|
ShoppingCart,
|
||||||
Store,
|
Store,
|
||||||
Truck,
|
Truck,
|
||||||
Users,
|
Users,
|
||||||
} from "lucide-react"
|
} from "lucide-react";
|
||||||
|
import type * as React from "react";
|
||||||
|
|
||||||
import { NavMain } from "#/components/nav-main.tsx"
|
import { NavMain } from "#/components/nav-main.tsx";
|
||||||
import { NavUser } from "#/components/nav-user.tsx"
|
import { NavUser } from "#/components/nav-user.tsx";
|
||||||
import { TeamSwitcher } from "#/components/team-switcher.tsx"
|
import { TeamSwitcher } from "#/components/team-switcher.tsx";
|
||||||
import {
|
import {
|
||||||
Sidebar,
|
Sidebar,
|
||||||
SidebarContent,
|
SidebarContent,
|
||||||
SidebarFooter,
|
SidebarFooter,
|
||||||
SidebarHeader,
|
SidebarHeader,
|
||||||
SidebarRail,
|
SidebarRail,
|
||||||
} from "#/components/ui/sidebar.tsx"
|
} from "#/components/ui/sidebar.tsx";
|
||||||
import type { AuthUser, Role } from "#/types/auth.ts"
|
import type { AuthUser, Role } from "#/types/auth.ts";
|
||||||
|
|
||||||
const roleLabels: Record<Role, string> = {
|
const roleLabels: Record<Role, string> = {
|
||||||
ADMIN: "Admin workspace",
|
ADMIN: "Admin workspace",
|
||||||
CUSTOMER: "Customer store",
|
CUSTOMER: "Customer store",
|
||||||
DRIVER: "Driver workspace",
|
DRIVER: "Driver workspace",
|
||||||
}
|
};
|
||||||
|
|
||||||
const navMainByRole: Record<Role, React.ComponentProps<typeof NavMain>["items"]> = {
|
const navMainByRole: Record<
|
||||||
ADMIN: [
|
Role,
|
||||||
{
|
React.ComponentProps<typeof NavMain>["items"]
|
||||||
title: "Overview",
|
> = {
|
||||||
url: "/admin",
|
ADMIN: [
|
||||||
icon: LayoutDashboard,
|
{
|
||||||
isActive: true,
|
title: "Overview",
|
||||||
items: [
|
url: "/admin",
|
||||||
{ title: "Operations", url: "/admin" },
|
icon: LayoutDashboard,
|
||||||
{ title: "Inventory health", url: "/admin/inventory" },
|
isActive: true,
|
||||||
],
|
items: [
|
||||||
},
|
{ title: "Operations", url: "/admin" },
|
||||||
{
|
{ title: "Inventory health", url: "/admin/inventory" },
|
||||||
title: "Products",
|
],
|
||||||
url: "/admin/products",
|
},
|
||||||
icon: Boxes,
|
{
|
||||||
items: [
|
title: "Products",
|
||||||
{ title: "Product catalog", url: "/admin/products" },
|
url: "/admin/products",
|
||||||
{ title: "Create product", url: "/admin/products/new" },
|
icon: Boxes,
|
||||||
],
|
items: [
|
||||||
},
|
{ title: "Product catalog", url: "/admin/products" },
|
||||||
{
|
{ title: "Create product", url: "/admin/products/new" },
|
||||||
title: "Orders",
|
],
|
||||||
url: "/admin/orders",
|
},
|
||||||
icon: ReceiptText,
|
{
|
||||||
items: [
|
title: "Orders",
|
||||||
{ title: "Pending orders", url: "/admin/orders/pending" },
|
url: "/admin/orders",
|
||||||
{ title: "Shipment status", url: "/admin/orders" },
|
icon: ReceiptText,
|
||||||
],
|
items: [
|
||||||
},
|
{ title: "Pending orders", url: "/admin/orders/pending" },
|
||||||
{
|
{ title: "Shipment status", url: "/admin/orders" },
|
||||||
title: "Rides",
|
],
|
||||||
url: "/admin/rides",
|
},
|
||||||
icon: Car,
|
{
|
||||||
items: [
|
title: "Rides",
|
||||||
{ title: "Ride requests", url: "/admin/rides/requested" },
|
url: "/admin/rides",
|
||||||
{ title: "Driver assignments", url: "/admin/rides/accepted" },
|
icon: Car,
|
||||||
],
|
items: [
|
||||||
},
|
{ title: "Ride requests", url: "/admin/rides/requested" },
|
||||||
{
|
{ title: "Driver assignments", url: "/admin/rides/accepted" },
|
||||||
title: "Users",
|
],
|
||||||
url: "/admin/users",
|
},
|
||||||
icon: Users,
|
{
|
||||||
items: [
|
title: "Users",
|
||||||
{ title: "All users", url: "/admin/users" },
|
url: "/admin/users",
|
||||||
{ title: "Customers", url: "/admin/customers" },
|
icon: Users,
|
||||||
{ title: "Drivers", url: "/admin/drivers" },
|
items: [
|
||||||
],
|
{ title: "All users", url: "/admin/users" },
|
||||||
},
|
{ title: "Customers", url: "/admin/customers" },
|
||||||
],
|
{ title: "Drivers", url: "/admin/drivers" },
|
||||||
CUSTOMER: [
|
],
|
||||||
{
|
},
|
||||||
title: "Overview",
|
],
|
||||||
url: "/",
|
CUSTOMER: [
|
||||||
icon: LayoutDashboard,
|
{
|
||||||
isActive: true,
|
title: "Overview",
|
||||||
items: [
|
url: "/",
|
||||||
{ title: "Dashboard", url: "/" },
|
icon: LayoutDashboard,
|
||||||
{ title: "Order history", url: "/orders" },
|
isActive: true,
|
||||||
],
|
items: [
|
||||||
},
|
{ title: "Dashboard", url: "/" },
|
||||||
{
|
{ title: "Order history", url: "/orders" },
|
||||||
title: "Storefront",
|
],
|
||||||
url: "/products",
|
},
|
||||||
icon: Store,
|
{
|
||||||
items: [
|
title: "Storefront",
|
||||||
{ title: "Product listing", url: "/products" },
|
url: "/products",
|
||||||
{ title: "Featured inventory", url: "/products/featured" },
|
icon: Store,
|
||||||
],
|
items: [
|
||||||
},
|
{ title: "Product listing", url: "/products" },
|
||||||
{
|
{ title: "Featured inventory", url: "/products/featured" },
|
||||||
title: "Cart",
|
],
|
||||||
url: "/cart",
|
},
|
||||||
icon: ShoppingCart,
|
{
|
||||||
items: [
|
title: "Cart",
|
||||||
{ title: "Review cart", url: "/cart" },
|
url: "/cart",
|
||||||
{ title: "Checkout", url: "/cart" },
|
icon: ShoppingCart,
|
||||||
],
|
items: [
|
||||||
},
|
{ title: "Review cart", url: "/cart" },
|
||||||
{
|
{ title: "Checkout", url: "/cart" },
|
||||||
title: "Orders",
|
],
|
||||||
url: "/orders",
|
},
|
||||||
icon: ReceiptText,
|
{
|
||||||
items: [
|
title: "Orders",
|
||||||
{ title: "Order history", url: "/orders" },
|
url: "/orders",
|
||||||
{ title: "Delivery status", url: "/orders/status" },
|
icon: ReceiptText,
|
||||||
],
|
items: [
|
||||||
},
|
{ title: "Order history", url: "/orders" },
|
||||||
{
|
{ title: "Delivery status", url: "/orders/status" },
|
||||||
title: "Rides",
|
],
|
||||||
url: "/rides",
|
},
|
||||||
icon: Car,
|
{
|
||||||
items: [
|
title: "Rides",
|
||||||
{ title: "Request a ride", url: "/rides/new" },
|
url: "/rides",
|
||||||
{ title: "Ride history", url: "/rides" },
|
icon: Car,
|
||||||
],
|
items: [
|
||||||
},
|
{ title: "Request a ride", url: "/rides/new" },
|
||||||
],
|
{ title: "Ride history", url: "/rides" },
|
||||||
DRIVER: [
|
],
|
||||||
{
|
},
|
||||||
title: "Overview",
|
],
|
||||||
url: "/",
|
DRIVER: [
|
||||||
icon: LayoutDashboard,
|
{
|
||||||
isActive: true,
|
title: "Overview",
|
||||||
items: [
|
url: "/",
|
||||||
{ title: "Dashboard", url: "/" },
|
icon: LayoutDashboard,
|
||||||
{ title: "Completed rides", url: "/driver/rides/completed" },
|
isActive: true,
|
||||||
],
|
items: [
|
||||||
},
|
{ title: "Dashboard", url: "/" },
|
||||||
{
|
{ title: "Completed rides", url: "/driver/rides/completed" },
|
||||||
title: "Ride board",
|
],
|
||||||
url: "/driver/rides",
|
},
|
||||||
icon: Car,
|
{
|
||||||
items: [
|
title: "Ride board",
|
||||||
{ title: "Requested rides", url: "/driver/rides/requested" },
|
url: "/driver/rides",
|
||||||
{ title: "Accepted rides", url: "/driver/rides/accepted" },
|
icon: Car,
|
||||||
],
|
items: [
|
||||||
},
|
{ title: "Requested rides", url: "/driver/rides/requested" },
|
||||||
{
|
{ title: "Accepted rides", url: "/driver/rides/accepted" },
|
||||||
title: "Routes",
|
],
|
||||||
url: "/driver/rides/accepted",
|
},
|
||||||
icon: Truck,
|
{
|
||||||
items: [
|
title: "Routes",
|
||||||
{ title: "Active route", url: "/driver/rides/accepted" },
|
url: "/driver/rides/accepted",
|
||||||
{ title: "Completed rides", url: "/driver/rides/completed" },
|
icon: Truck,
|
||||||
],
|
items: [
|
||||||
},
|
{ title: "Active route", url: "/driver/rides/accepted" },
|
||||||
],
|
{ title: "Completed rides", url: "/driver/rides/completed" },
|
||||||
}
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
type AppSidebarProps = React.ComponentProps<typeof Sidebar> & {
|
type AppSidebarProps = React.ComponentProps<typeof Sidebar> & {
|
||||||
user: AuthUser
|
user: AuthUser;
|
||||||
onLogout?: () => void
|
onLogout?: () => void;
|
||||||
}
|
};
|
||||||
|
|
||||||
export function AppSidebar({ user, onLogout, ...props }: AppSidebarProps) {
|
export function AppSidebar({ user, onLogout, ...props }: AppSidebarProps) {
|
||||||
return (
|
return (
|
||||||
<Sidebar collapsible="icon" {...props}>
|
<Sidebar collapsible="icon" {...props}>
|
||||||
<SidebarHeader>
|
<SidebarHeader>
|
||||||
<TeamSwitcher
|
<TeamSwitcher
|
||||||
teams={[
|
teams={[
|
||||||
{
|
{
|
||||||
name: "Cymelle",
|
name: "Cymelle",
|
||||||
logo: GalleryVerticalEnd,
|
logo: GalleryVerticalEnd,
|
||||||
plan: roleLabels[user.role],
|
plan: roleLabels[user.role],
|
||||||
},
|
},
|
||||||
]}
|
]}
|
||||||
/>
|
/>
|
||||||
</SidebarHeader>
|
</SidebarHeader>
|
||||||
<SidebarContent>
|
<SidebarContent>
|
||||||
<NavMain items={navMainByRole[user.role]} />
|
<NavMain items={navMainByRole[user.role]} />
|
||||||
</SidebarContent>
|
</SidebarContent>
|
||||||
<SidebarFooter>
|
<SidebarFooter>
|
||||||
<NavUser
|
<NavUser
|
||||||
user={{
|
user={{
|
||||||
name: user.displayName,
|
name: user.displayName,
|
||||||
email: user.username,
|
email: user.username,
|
||||||
avatar: "",
|
avatar: "",
|
||||||
}}
|
}}
|
||||||
onLogout={onLogout}
|
onLogout={onLogout}
|
||||||
/>
|
/>
|
||||||
</SidebarFooter>
|
</SidebarFooter>
|
||||||
<SidebarRail />
|
<SidebarRail />
|
||||||
</Sidebar>
|
</Sidebar>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,81 +1,94 @@
|
|||||||
import {AppSidebar} from "#/components/app-sidebar";
|
import type { CSSProperties, ReactNode } from "react";
|
||||||
import {SiteHeader} from "#/components/site-header";
|
import { AppSidebar } from "#/components/app-sidebar";
|
||||||
import {StoreHome} from "#/components/store/StoreHome";
|
import { SiteHeader } from "#/components/site-header";
|
||||||
import {Card, CardContent, CardHeader} from "#/components/ui/card";
|
import { StoreHome } from "#/components/store/StoreHome";
|
||||||
import {Skeleton} from "#/components/ui/skeleton";
|
import { Card, CardContent, CardHeader } from "#/components/ui/card";
|
||||||
import {SidebarInset, SidebarProvider} from "#/components/ui/sidebar";
|
import { SidebarInset, SidebarProvider } from "#/components/ui/sidebar";
|
||||||
import {useAuth} from "#/hooks/useAuth";
|
import { Skeleton } from "#/components/ui/skeleton";
|
||||||
import type {Role} from "#/types/auth";
|
import { useAuth } from "#/hooks/useAuth";
|
||||||
import type {CSSProperties, ReactNode} from "react";
|
import type { Role } from "#/types/auth";
|
||||||
|
|
||||||
type AppShellProps = {
|
type AppShellProps = {
|
||||||
title: string;
|
title: string;
|
||||||
allowedRoles?: Role[];
|
allowedRoles?: Role[];
|
||||||
showCart?: boolean;
|
showCart?: boolean;
|
||||||
children: ReactNode;
|
children: ReactNode;
|
||||||
};
|
};
|
||||||
|
|
||||||
export function AppShell({title, allowedRoles, showCart = false, children}: AppShellProps) {
|
export function AppShell({
|
||||||
const {user, isLoading, logout} = useAuth();
|
title,
|
||||||
|
allowedRoles,
|
||||||
|
showCart = false,
|
||||||
|
children,
|
||||||
|
}: AppShellProps) {
|
||||||
|
const { user, isLoading, logout } = useAuth();
|
||||||
|
|
||||||
if (isLoading && !user) {
|
if (isLoading && !user) {
|
||||||
return <WorkspaceSkeleton/>;
|
return <WorkspaceSkeleton />;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!user) {
|
if (!user) {
|
||||||
return <StoreHome/>;
|
return <StoreHome />;
|
||||||
}
|
}
|
||||||
|
|
||||||
const allowed = !allowedRoles || allowedRoles.includes(user.role);
|
const allowed = !allowedRoles || allowedRoles.includes(user.role);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<SidebarProvider
|
<SidebarProvider
|
||||||
style={{
|
style={
|
||||||
"--sidebar-width": "18rem",
|
{
|
||||||
"--header-height": "3.5rem",
|
"--sidebar-width": "18rem",
|
||||||
} as CSSProperties}
|
"--header-height": "3.5rem",
|
||||||
>
|
} as CSSProperties
|
||||||
<AppSidebar user={user} onLogout={logout} variant="inset"/>
|
}
|
||||||
<SidebarInset>
|
>
|
||||||
<SiteHeader title={title} onLogout={logout} showCart={showCart || user.role === "CUSTOMER"}/>
|
<AppSidebar user={user} onLogout={logout} variant="inset" />
|
||||||
<main className="@container/main flex flex-1 flex-col gap-4 p-4 md:gap-6 md:p-6">
|
<SidebarInset>
|
||||||
{allowed ? children : <AccessDenied/>}
|
<SiteHeader
|
||||||
</main>
|
title={title}
|
||||||
</SidebarInset>
|
onLogout={logout}
|
||||||
</SidebarProvider>
|
showCart={showCart || user.role === "CUSTOMER"}
|
||||||
);
|
/>
|
||||||
|
<main className="@container/main flex flex-1 flex-col gap-4 p-4 md:gap-6 md:p-6">
|
||||||
|
{allowed ? children : <AccessDenied />}
|
||||||
|
</main>
|
||||||
|
</SidebarInset>
|
||||||
|
</SidebarProvider>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function WorkspaceSkeleton() {
|
function WorkspaceSkeleton() {
|
||||||
return (
|
return (
|
||||||
<main className="min-h-screen bg-background p-4 md:p-6">
|
<main className="min-h-screen bg-background p-4 md:p-6">
|
||||||
<div className="mx-auto max-w-6xl space-y-4">
|
<div className="mx-auto max-w-6xl space-y-4">
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<Skeleton className="h-8 w-48"/>
|
<Skeleton className="h-8 w-48" />
|
||||||
<Skeleton className="h-9 w-32"/>
|
<Skeleton className="h-9 w-32" />
|
||||||
</div>
|
</div>
|
||||||
<div className="grid gap-4 md:grid-cols-3">
|
<div className="grid gap-4 md:grid-cols-3">
|
||||||
<Skeleton className="h-28"/>
|
<Skeleton className="h-28" />
|
||||||
<Skeleton className="h-28"/>
|
<Skeleton className="h-28" />
|
||||||
<Skeleton className="h-28"/>
|
<Skeleton className="h-28" />
|
||||||
</div>
|
</div>
|
||||||
<Skeleton className="h-80"/>
|
<Skeleton className="h-80" />
|
||||||
</div>
|
</div>
|
||||||
</main>
|
</main>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function AccessDenied() {
|
function AccessDenied() {
|
||||||
return (
|
return (
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<h2 className="text-lg font-semibold">This page is not available for your role</h2>
|
<h2 className="text-lg font-semibold">
|
||||||
</CardHeader>
|
This page is not available for your role
|
||||||
<CardContent>
|
</h2>
|
||||||
<p className="text-sm text-muted-foreground">
|
</CardHeader>
|
||||||
Switch to the correct account type to view this workspace.
|
<CardContent>
|
||||||
</p>
|
<p className="text-sm text-muted-foreground">
|
||||||
</CardContent>
|
Switch to the correct account type to view this workspace.
|
||||||
</Card>
|
</p>
|
||||||
);
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -1,291 +1,287 @@
|
|||||||
"use client"
|
"use client";
|
||||||
|
|
||||||
import * as React from "react"
|
import * as React from "react";
|
||||||
import { Area, AreaChart, CartesianGrid, XAxis } from "recharts"
|
import { Area, AreaChart, CartesianGrid, XAxis } from "recharts";
|
||||||
|
import {
|
||||||
|
Card,
|
||||||
|
CardAction,
|
||||||
|
CardContent,
|
||||||
|
CardDescription,
|
||||||
|
CardHeader,
|
||||||
|
CardTitle,
|
||||||
|
} from "#/components/ui/card.tsx";
|
||||||
|
import {
|
||||||
|
type ChartConfig,
|
||||||
|
ChartContainer,
|
||||||
|
ChartTooltip,
|
||||||
|
ChartTooltipContent,
|
||||||
|
} from "#/components/ui/chart.tsx";
|
||||||
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
} from "#/components/ui/select.tsx";
|
||||||
|
import { ToggleGroup, ToggleGroupItem } from "#/components/ui/toggle-group.tsx";
|
||||||
|
import { useIsMobile } from "#/hooks/use-mobile.ts";
|
||||||
|
|
||||||
import { useIsMobile } from "#/hooks/use-mobile.ts"
|
export const description = "An interactive area chart";
|
||||||
import {
|
|
||||||
Card,
|
|
||||||
CardAction,
|
|
||||||
CardContent,
|
|
||||||
CardDescription,
|
|
||||||
CardHeader,
|
|
||||||
CardTitle,
|
|
||||||
} from "#/components/ui/card.tsx"
|
|
||||||
import {
|
|
||||||
ChartContainer,
|
|
||||||
ChartTooltip,
|
|
||||||
ChartTooltipContent,
|
|
||||||
type ChartConfig,
|
|
||||||
} from "#/components/ui/chart.tsx"
|
|
||||||
import {
|
|
||||||
Select,
|
|
||||||
SelectContent,
|
|
||||||
SelectItem,
|
|
||||||
SelectTrigger,
|
|
||||||
SelectValue,
|
|
||||||
} from "#/components/ui/select.tsx"
|
|
||||||
import {
|
|
||||||
ToggleGroup,
|
|
||||||
ToggleGroupItem,
|
|
||||||
} from "#/components/ui/toggle-group.tsx"
|
|
||||||
|
|
||||||
export const description = "An interactive area chart"
|
|
||||||
|
|
||||||
const chartData = [
|
const chartData = [
|
||||||
{ date: "2024-04-01", desktop: 222, mobile: 150 },
|
{ date: "2024-04-01", desktop: 222, mobile: 150 },
|
||||||
{ date: "2024-04-02", desktop: 97, mobile: 180 },
|
{ date: "2024-04-02", desktop: 97, mobile: 180 },
|
||||||
{ date: "2024-04-03", desktop: 167, mobile: 120 },
|
{ date: "2024-04-03", desktop: 167, mobile: 120 },
|
||||||
{ date: "2024-04-04", desktop: 242, mobile: 260 },
|
{ date: "2024-04-04", desktop: 242, mobile: 260 },
|
||||||
{ date: "2024-04-05", desktop: 373, mobile: 290 },
|
{ date: "2024-04-05", desktop: 373, mobile: 290 },
|
||||||
{ date: "2024-04-06", desktop: 301, mobile: 340 },
|
{ date: "2024-04-06", desktop: 301, mobile: 340 },
|
||||||
{ date: "2024-04-07", desktop: 245, mobile: 180 },
|
{ date: "2024-04-07", desktop: 245, mobile: 180 },
|
||||||
{ date: "2024-04-08", desktop: 409, mobile: 320 },
|
{ date: "2024-04-08", desktop: 409, mobile: 320 },
|
||||||
{ date: "2024-04-09", desktop: 59, mobile: 110 },
|
{ date: "2024-04-09", desktop: 59, mobile: 110 },
|
||||||
{ date: "2024-04-10", desktop: 261, mobile: 190 },
|
{ date: "2024-04-10", desktop: 261, mobile: 190 },
|
||||||
{ date: "2024-04-11", desktop: 327, mobile: 350 },
|
{ date: "2024-04-11", desktop: 327, mobile: 350 },
|
||||||
{ date: "2024-04-12", desktop: 292, mobile: 210 },
|
{ date: "2024-04-12", desktop: 292, mobile: 210 },
|
||||||
{ date: "2024-04-13", desktop: 342, mobile: 380 },
|
{ date: "2024-04-13", desktop: 342, mobile: 380 },
|
||||||
{ date: "2024-04-14", desktop: 137, mobile: 220 },
|
{ date: "2024-04-14", desktop: 137, mobile: 220 },
|
||||||
{ date: "2024-04-15", desktop: 120, mobile: 170 },
|
{ date: "2024-04-15", desktop: 120, mobile: 170 },
|
||||||
{ date: "2024-04-16", desktop: 138, mobile: 190 },
|
{ date: "2024-04-16", desktop: 138, mobile: 190 },
|
||||||
{ date: "2024-04-17", desktop: 446, mobile: 360 },
|
{ date: "2024-04-17", desktop: 446, mobile: 360 },
|
||||||
{ date: "2024-04-18", desktop: 364, mobile: 410 },
|
{ date: "2024-04-18", desktop: 364, mobile: 410 },
|
||||||
{ date: "2024-04-19", desktop: 243, mobile: 180 },
|
{ date: "2024-04-19", desktop: 243, mobile: 180 },
|
||||||
{ date: "2024-04-20", desktop: 89, mobile: 150 },
|
{ date: "2024-04-20", desktop: 89, mobile: 150 },
|
||||||
{ date: "2024-04-21", desktop: 137, mobile: 200 },
|
{ date: "2024-04-21", desktop: 137, mobile: 200 },
|
||||||
{ date: "2024-04-22", desktop: 224, mobile: 170 },
|
{ date: "2024-04-22", desktop: 224, mobile: 170 },
|
||||||
{ date: "2024-04-23", desktop: 138, mobile: 230 },
|
{ date: "2024-04-23", desktop: 138, mobile: 230 },
|
||||||
{ date: "2024-04-24", desktop: 387, mobile: 290 },
|
{ date: "2024-04-24", desktop: 387, mobile: 290 },
|
||||||
{ date: "2024-04-25", desktop: 215, mobile: 250 },
|
{ date: "2024-04-25", desktop: 215, mobile: 250 },
|
||||||
{ date: "2024-04-26", desktop: 75, mobile: 130 },
|
{ date: "2024-04-26", desktop: 75, mobile: 130 },
|
||||||
{ date: "2024-04-27", desktop: 383, mobile: 420 },
|
{ date: "2024-04-27", desktop: 383, mobile: 420 },
|
||||||
{ date: "2024-04-28", desktop: 122, mobile: 180 },
|
{ date: "2024-04-28", desktop: 122, mobile: 180 },
|
||||||
{ date: "2024-04-29", desktop: 315, mobile: 240 },
|
{ date: "2024-04-29", desktop: 315, mobile: 240 },
|
||||||
{ date: "2024-04-30", desktop: 454, mobile: 380 },
|
{ date: "2024-04-30", desktop: 454, mobile: 380 },
|
||||||
{ date: "2024-05-01", desktop: 165, mobile: 220 },
|
{ date: "2024-05-01", desktop: 165, mobile: 220 },
|
||||||
{ date: "2024-05-02", desktop: 293, mobile: 310 },
|
{ date: "2024-05-02", desktop: 293, mobile: 310 },
|
||||||
{ date: "2024-05-03", desktop: 247, mobile: 190 },
|
{ date: "2024-05-03", desktop: 247, mobile: 190 },
|
||||||
{ date: "2024-05-04", desktop: 385, mobile: 420 },
|
{ date: "2024-05-04", desktop: 385, mobile: 420 },
|
||||||
{ date: "2024-05-05", desktop: 481, mobile: 390 },
|
{ date: "2024-05-05", desktop: 481, mobile: 390 },
|
||||||
{ date: "2024-05-06", desktop: 498, mobile: 520 },
|
{ date: "2024-05-06", desktop: 498, mobile: 520 },
|
||||||
{ date: "2024-05-07", desktop: 388, mobile: 300 },
|
{ date: "2024-05-07", desktop: 388, mobile: 300 },
|
||||||
{ date: "2024-05-08", desktop: 149, mobile: 210 },
|
{ date: "2024-05-08", desktop: 149, mobile: 210 },
|
||||||
{ date: "2024-05-09", desktop: 227, mobile: 180 },
|
{ date: "2024-05-09", desktop: 227, mobile: 180 },
|
||||||
{ date: "2024-05-10", desktop: 293, mobile: 330 },
|
{ date: "2024-05-10", desktop: 293, mobile: 330 },
|
||||||
{ date: "2024-05-11", desktop: 335, mobile: 270 },
|
{ date: "2024-05-11", desktop: 335, mobile: 270 },
|
||||||
{ date: "2024-05-12", desktop: 197, mobile: 240 },
|
{ date: "2024-05-12", desktop: 197, mobile: 240 },
|
||||||
{ date: "2024-05-13", desktop: 197, mobile: 160 },
|
{ date: "2024-05-13", desktop: 197, mobile: 160 },
|
||||||
{ date: "2024-05-14", desktop: 448, mobile: 490 },
|
{ date: "2024-05-14", desktop: 448, mobile: 490 },
|
||||||
{ date: "2024-05-15", desktop: 473, mobile: 380 },
|
{ date: "2024-05-15", desktop: 473, mobile: 380 },
|
||||||
{ date: "2024-05-16", desktop: 338, mobile: 400 },
|
{ date: "2024-05-16", desktop: 338, mobile: 400 },
|
||||||
{ date: "2024-05-17", desktop: 499, mobile: 420 },
|
{ date: "2024-05-17", desktop: 499, mobile: 420 },
|
||||||
{ date: "2024-05-18", desktop: 315, mobile: 350 },
|
{ date: "2024-05-18", desktop: 315, mobile: 350 },
|
||||||
{ date: "2024-05-19", desktop: 235, mobile: 180 },
|
{ date: "2024-05-19", desktop: 235, mobile: 180 },
|
||||||
{ date: "2024-05-20", desktop: 177, mobile: 230 },
|
{ date: "2024-05-20", desktop: 177, mobile: 230 },
|
||||||
{ date: "2024-05-21", desktop: 82, mobile: 140 },
|
{ date: "2024-05-21", desktop: 82, mobile: 140 },
|
||||||
{ date: "2024-05-22", desktop: 81, mobile: 120 },
|
{ date: "2024-05-22", desktop: 81, mobile: 120 },
|
||||||
{ date: "2024-05-23", desktop: 252, mobile: 290 },
|
{ date: "2024-05-23", desktop: 252, mobile: 290 },
|
||||||
{ date: "2024-05-24", desktop: 294, mobile: 220 },
|
{ date: "2024-05-24", desktop: 294, mobile: 220 },
|
||||||
{ date: "2024-05-25", desktop: 201, mobile: 250 },
|
{ date: "2024-05-25", desktop: 201, mobile: 250 },
|
||||||
{ date: "2024-05-26", desktop: 213, mobile: 170 },
|
{ date: "2024-05-26", desktop: 213, mobile: 170 },
|
||||||
{ date: "2024-05-27", desktop: 420, mobile: 460 },
|
{ date: "2024-05-27", desktop: 420, mobile: 460 },
|
||||||
{ date: "2024-05-28", desktop: 233, mobile: 190 },
|
{ date: "2024-05-28", desktop: 233, mobile: 190 },
|
||||||
{ date: "2024-05-29", desktop: 78, mobile: 130 },
|
{ date: "2024-05-29", desktop: 78, mobile: 130 },
|
||||||
{ date: "2024-05-30", desktop: 340, mobile: 280 },
|
{ date: "2024-05-30", desktop: 340, mobile: 280 },
|
||||||
{ date: "2024-05-31", desktop: 178, mobile: 230 },
|
{ date: "2024-05-31", desktop: 178, mobile: 230 },
|
||||||
{ date: "2024-06-01", desktop: 178, mobile: 200 },
|
{ date: "2024-06-01", desktop: 178, mobile: 200 },
|
||||||
{ date: "2024-06-02", desktop: 470, mobile: 410 },
|
{ date: "2024-06-02", desktop: 470, mobile: 410 },
|
||||||
{ date: "2024-06-03", desktop: 103, mobile: 160 },
|
{ date: "2024-06-03", desktop: 103, mobile: 160 },
|
||||||
{ date: "2024-06-04", desktop: 439, mobile: 380 },
|
{ date: "2024-06-04", desktop: 439, mobile: 380 },
|
||||||
{ date: "2024-06-05", desktop: 88, mobile: 140 },
|
{ date: "2024-06-05", desktop: 88, mobile: 140 },
|
||||||
{ date: "2024-06-06", desktop: 294, mobile: 250 },
|
{ date: "2024-06-06", desktop: 294, mobile: 250 },
|
||||||
{ date: "2024-06-07", desktop: 323, mobile: 370 },
|
{ date: "2024-06-07", desktop: 323, mobile: 370 },
|
||||||
{ date: "2024-06-08", desktop: 385, mobile: 320 },
|
{ date: "2024-06-08", desktop: 385, mobile: 320 },
|
||||||
{ date: "2024-06-09", desktop: 438, mobile: 480 },
|
{ date: "2024-06-09", desktop: 438, mobile: 480 },
|
||||||
{ date: "2024-06-10", desktop: 155, mobile: 200 },
|
{ date: "2024-06-10", desktop: 155, mobile: 200 },
|
||||||
{ date: "2024-06-11", desktop: 92, mobile: 150 },
|
{ date: "2024-06-11", desktop: 92, mobile: 150 },
|
||||||
{ date: "2024-06-12", desktop: 492, mobile: 420 },
|
{ date: "2024-06-12", desktop: 492, mobile: 420 },
|
||||||
{ date: "2024-06-13", desktop: 81, mobile: 130 },
|
{ date: "2024-06-13", desktop: 81, mobile: 130 },
|
||||||
{ date: "2024-06-14", desktop: 426, mobile: 380 },
|
{ date: "2024-06-14", desktop: 426, mobile: 380 },
|
||||||
{ date: "2024-06-15", desktop: 307, mobile: 350 },
|
{ date: "2024-06-15", desktop: 307, mobile: 350 },
|
||||||
{ date: "2024-06-16", desktop: 371, mobile: 310 },
|
{ date: "2024-06-16", desktop: 371, mobile: 310 },
|
||||||
{ date: "2024-06-17", desktop: 475, mobile: 520 },
|
{ date: "2024-06-17", desktop: 475, mobile: 520 },
|
||||||
{ date: "2024-06-18", desktop: 107, mobile: 170 },
|
{ date: "2024-06-18", desktop: 107, mobile: 170 },
|
||||||
{ date: "2024-06-19", desktop: 341, mobile: 290 },
|
{ date: "2024-06-19", desktop: 341, mobile: 290 },
|
||||||
{ date: "2024-06-20", desktop: 408, mobile: 450 },
|
{ date: "2024-06-20", desktop: 408, mobile: 450 },
|
||||||
{ date: "2024-06-21", desktop: 169, mobile: 210 },
|
{ date: "2024-06-21", desktop: 169, mobile: 210 },
|
||||||
{ date: "2024-06-22", desktop: 317, mobile: 270 },
|
{ date: "2024-06-22", desktop: 317, mobile: 270 },
|
||||||
{ date: "2024-06-23", desktop: 480, mobile: 530 },
|
{ date: "2024-06-23", desktop: 480, mobile: 530 },
|
||||||
{ date: "2024-06-24", desktop: 132, mobile: 180 },
|
{ date: "2024-06-24", desktop: 132, mobile: 180 },
|
||||||
{ date: "2024-06-25", desktop: 141, mobile: 190 },
|
{ date: "2024-06-25", desktop: 141, mobile: 190 },
|
||||||
{ date: "2024-06-26", desktop: 434, mobile: 380 },
|
{ date: "2024-06-26", desktop: 434, mobile: 380 },
|
||||||
{ date: "2024-06-27", desktop: 448, mobile: 490 },
|
{ date: "2024-06-27", desktop: 448, mobile: 490 },
|
||||||
{ date: "2024-06-28", desktop: 149, mobile: 200 },
|
{ date: "2024-06-28", desktop: 149, mobile: 200 },
|
||||||
{ date: "2024-06-29", desktop: 103, mobile: 160 },
|
{ date: "2024-06-29", desktop: 103, mobile: 160 },
|
||||||
{ date: "2024-06-30", desktop: 446, mobile: 400 },
|
{ date: "2024-06-30", desktop: 446, mobile: 400 },
|
||||||
]
|
];
|
||||||
|
|
||||||
const chartConfig = {
|
const chartConfig = {
|
||||||
visitors: {
|
visitors: {
|
||||||
label: "Visitors",
|
label: "Visitors",
|
||||||
},
|
},
|
||||||
desktop: {
|
desktop: {
|
||||||
label: "Desktop",
|
label: "Desktop",
|
||||||
color: "var(--primary)",
|
color: "var(--primary)",
|
||||||
},
|
},
|
||||||
mobile: {
|
mobile: {
|
||||||
label: "Mobile",
|
label: "Mobile",
|
||||||
color: "var(--primary)",
|
color: "var(--primary)",
|
||||||
},
|
},
|
||||||
} satisfies ChartConfig
|
} satisfies ChartConfig;
|
||||||
|
|
||||||
export function ChartAreaInteractive() {
|
export function ChartAreaInteractive() {
|
||||||
const isMobile = useIsMobile()
|
const isMobile = useIsMobile();
|
||||||
const [timeRange, setTimeRange] = React.useState("90d")
|
const [timeRange, setTimeRange] = React.useState("90d");
|
||||||
|
|
||||||
React.useEffect(() => {
|
React.useEffect(() => {
|
||||||
if (isMobile) {
|
if (isMobile) {
|
||||||
setTimeRange("7d")
|
setTimeRange("7d");
|
||||||
}
|
}
|
||||||
}, [isMobile])
|
}, [isMobile]);
|
||||||
|
|
||||||
const filteredData = chartData.filter((item) => {
|
const filteredData = chartData.filter((item) => {
|
||||||
const date = new Date(item.date)
|
const date = new Date(item.date);
|
||||||
const referenceDate = new Date("2024-06-30")
|
const referenceDate = new Date("2024-06-30");
|
||||||
let daysToSubtract = 90
|
let daysToSubtract = 90;
|
||||||
if (timeRange === "30d") {
|
if (timeRange === "30d") {
|
||||||
daysToSubtract = 30
|
daysToSubtract = 30;
|
||||||
} else if (timeRange === "7d") {
|
} else if (timeRange === "7d") {
|
||||||
daysToSubtract = 7
|
daysToSubtract = 7;
|
||||||
}
|
}
|
||||||
const startDate = new Date(referenceDate)
|
const startDate = new Date(referenceDate);
|
||||||
startDate.setDate(startDate.getDate() - daysToSubtract)
|
startDate.setDate(startDate.getDate() - daysToSubtract);
|
||||||
return date >= startDate
|
return date >= startDate;
|
||||||
})
|
});
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card className="@container/card">
|
<Card className="@container/card">
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle>Total Visitors</CardTitle>
|
<CardTitle>Total Visitors</CardTitle>
|
||||||
<CardDescription>
|
<CardDescription>
|
||||||
<span className="hidden @[540px]/card:block">
|
<span className="hidden @[540px]/card:block">
|
||||||
Total for the last 3 months
|
Total for the last 3 months
|
||||||
</span>
|
</span>
|
||||||
<span className="@[540px]/card:hidden">Last 3 months</span>
|
<span className="@[540px]/card:hidden">Last 3 months</span>
|
||||||
</CardDescription>
|
</CardDescription>
|
||||||
<CardAction>
|
<CardAction>
|
||||||
<ToggleGroup
|
<ToggleGroup
|
||||||
type="single"
|
type="single"
|
||||||
value={timeRange}
|
value={timeRange}
|
||||||
onValueChange={setTimeRange}
|
onValueChange={setTimeRange}
|
||||||
variant="outline"
|
variant="outline"
|
||||||
className="hidden *:data-[slot=toggle-group-item]:px-4! @[767px]/card:flex"
|
className="hidden *:data-[slot=toggle-group-item]:px-4! @[767px]/card:flex"
|
||||||
>
|
>
|
||||||
<ToggleGroupItem value="90d">Last 3 months</ToggleGroupItem>
|
<ToggleGroupItem value="90d">Last 3 months</ToggleGroupItem>
|
||||||
<ToggleGroupItem value="30d">Last 30 days</ToggleGroupItem>
|
<ToggleGroupItem value="30d">Last 30 days</ToggleGroupItem>
|
||||||
<ToggleGroupItem value="7d">Last 7 days</ToggleGroupItem>
|
<ToggleGroupItem value="7d">Last 7 days</ToggleGroupItem>
|
||||||
</ToggleGroup>
|
</ToggleGroup>
|
||||||
<Select value={timeRange} onValueChange={setTimeRange}>
|
<Select value={timeRange} onValueChange={setTimeRange}>
|
||||||
<SelectTrigger
|
<SelectTrigger
|
||||||
className="flex w-40 **:data-[slot=select-value]:block **:data-[slot=select-value]:truncate @[767px]/card:hidden"
|
className="flex w-40 **:data-[slot=select-value]:block **:data-[slot=select-value]:truncate @[767px]/card:hidden"
|
||||||
size="sm"
|
size="sm"
|
||||||
aria-label="Select a value"
|
aria-label="Select a value"
|
||||||
>
|
>
|
||||||
<SelectValue placeholder="Last 3 months" />
|
<SelectValue placeholder="Last 3 months" />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
<SelectContent className="rounded-xl">
|
<SelectContent className="rounded-xl">
|
||||||
<SelectItem value="90d" className="rounded-lg">
|
<SelectItem value="90d" className="rounded-lg">
|
||||||
Last 3 months
|
Last 3 months
|
||||||
</SelectItem>
|
</SelectItem>
|
||||||
<SelectItem value="30d" className="rounded-lg">
|
<SelectItem value="30d" className="rounded-lg">
|
||||||
Last 30 days
|
Last 30 days
|
||||||
</SelectItem>
|
</SelectItem>
|
||||||
<SelectItem value="7d" className="rounded-lg">
|
<SelectItem value="7d" className="rounded-lg">
|
||||||
Last 7 days
|
Last 7 days
|
||||||
</SelectItem>
|
</SelectItem>
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
</CardAction>
|
</CardAction>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="px-2 pt-4 sm:px-6 sm:pt-6">
|
<CardContent className="px-2 pt-4 sm:px-6 sm:pt-6">
|
||||||
<ChartContainer
|
<ChartContainer
|
||||||
config={chartConfig}
|
config={chartConfig}
|
||||||
className="aspect-auto h-[250px] w-full"
|
className="aspect-auto h-[250px] w-full"
|
||||||
>
|
>
|
||||||
<AreaChart data={filteredData}>
|
<AreaChart data={filteredData}>
|
||||||
<defs>
|
<defs>
|
||||||
<linearGradient id="fillDesktop" x1="0" y1="0" x2="0" y2="1">
|
<linearGradient id="fillDesktop" x1="0" y1="0" x2="0" y2="1">
|
||||||
<stop
|
<stop
|
||||||
offset="5%"
|
offset="5%"
|
||||||
stopColor="var(--color-desktop)"
|
stopColor="var(--color-desktop)"
|
||||||
stopOpacity={1.0}
|
stopOpacity={1.0}
|
||||||
/>
|
/>
|
||||||
<stop
|
<stop
|
||||||
offset="95%"
|
offset="95%"
|
||||||
stopColor="var(--color-desktop)"
|
stopColor="var(--color-desktop)"
|
||||||
stopOpacity={0.1}
|
stopOpacity={0.1}
|
||||||
/>
|
/>
|
||||||
</linearGradient>
|
</linearGradient>
|
||||||
<linearGradient id="fillMobile" x1="0" y1="0" x2="0" y2="1">
|
<linearGradient id="fillMobile" x1="0" y1="0" x2="0" y2="1">
|
||||||
<stop
|
<stop
|
||||||
offset="5%"
|
offset="5%"
|
||||||
stopColor="var(--color-mobile)"
|
stopColor="var(--color-mobile)"
|
||||||
stopOpacity={0.8}
|
stopOpacity={0.8}
|
||||||
/>
|
/>
|
||||||
<stop
|
<stop
|
||||||
offset="95%"
|
offset="95%"
|
||||||
stopColor="var(--color-mobile)"
|
stopColor="var(--color-mobile)"
|
||||||
stopOpacity={0.1}
|
stopOpacity={0.1}
|
||||||
/>
|
/>
|
||||||
</linearGradient>
|
</linearGradient>
|
||||||
</defs>
|
</defs>
|
||||||
<CartesianGrid vertical={false} />
|
<CartesianGrid vertical={false} />
|
||||||
<XAxis
|
<XAxis
|
||||||
dataKey="date"
|
dataKey="date"
|
||||||
tickLine={false}
|
tickLine={false}
|
||||||
axisLine={false}
|
axisLine={false}
|
||||||
tickMargin={8}
|
tickMargin={8}
|
||||||
minTickGap={32}
|
minTickGap={32}
|
||||||
tickFormatter={(value) => {
|
tickFormatter={(value) => {
|
||||||
const date = new Date(value)
|
const date = new Date(value);
|
||||||
return date.toLocaleDateString("en-US", {
|
return date.toLocaleDateString("en-US", {
|
||||||
month: "short",
|
month: "short",
|
||||||
day: "numeric",
|
day: "numeric",
|
||||||
})
|
});
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<ChartTooltip
|
<ChartTooltip
|
||||||
cursor={false}
|
cursor={false}
|
||||||
content={
|
content={
|
||||||
<ChartTooltipContent
|
<ChartTooltipContent
|
||||||
labelFormatter={(value) => {
|
labelFormatter={(value) => {
|
||||||
return new Date(value).toLocaleDateString("en-US", {
|
return new Date(value).toLocaleDateString("en-US", {
|
||||||
month: "short",
|
month: "short",
|
||||||
day: "numeric",
|
day: "numeric",
|
||||||
})
|
});
|
||||||
}}
|
}}
|
||||||
indicator="dot"
|
indicator="dot"
|
||||||
/>
|
/>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
<Area
|
<Area
|
||||||
dataKey="mobile"
|
dataKey="mobile"
|
||||||
type="natural"
|
type="natural"
|
||||||
fill="url(#fillMobile)"
|
fill="url(#fillMobile)"
|
||||||
stroke="var(--color-mobile)"
|
stroke="var(--color-mobile)"
|
||||||
stackId="a"
|
stackId="a"
|
||||||
/>
|
/>
|
||||||
<Area
|
<Area
|
||||||
dataKey="desktop"
|
dataKey="desktop"
|
||||||
type="natural"
|
type="natural"
|
||||||
fill="url(#fillDesktop)"
|
fill="url(#fillDesktop)"
|
||||||
stroke="var(--color-desktop)"
|
stroke="var(--color-desktop)"
|
||||||
stackId="a"
|
stackId="a"
|
||||||
/>
|
/>
|
||||||
</AreaChart>
|
</AreaChart>
|
||||||
</ChartContainer>
|
</ChartContainer>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,100 +1,100 @@
|
|||||||
import { cn } from "#/lib/utils.ts"
|
import { Button } from "#/components/ui/button.tsx";
|
||||||
import { Button } from "#/components/ui/button.tsx"
|
|
||||||
import {
|
import {
|
||||||
Card,
|
Card,
|
||||||
CardContent,
|
CardContent,
|
||||||
CardDescription,
|
CardDescription,
|
||||||
CardHeader,
|
CardHeader,
|
||||||
CardTitle,
|
CardTitle,
|
||||||
} from "#/components/ui/card.tsx"
|
} from "#/components/ui/card.tsx";
|
||||||
import {
|
import {
|
||||||
Field,
|
Field,
|
||||||
FieldDescription,
|
FieldDescription,
|
||||||
FieldError,
|
FieldError,
|
||||||
FieldGroup,
|
FieldGroup,
|
||||||
FieldLabel,
|
FieldLabel,
|
||||||
} from "#/components/ui/field.tsx"
|
} from "#/components/ui/field.tsx";
|
||||||
import { Input } from "#/components/ui/input.tsx"
|
import { Input } from "#/components/ui/input.tsx";
|
||||||
|
import { cn } from "#/lib/utils.ts";
|
||||||
|
|
||||||
type LoginFormProps = React.ComponentProps<"div"> & {
|
type LoginFormProps = Omit<React.ComponentProps<"div">, "onSubmit"> & {
|
||||||
username: string
|
username: string;
|
||||||
password: string
|
password: string;
|
||||||
error?: string | null
|
error?: string | null;
|
||||||
pending?: boolean
|
pending?: boolean;
|
||||||
onUsernameChange: (value: string) => void
|
onUsernameChange: (value: string) => void;
|
||||||
onPasswordChange: (value: string) => void
|
onPasswordChange: (value: string) => void;
|
||||||
onSubmit: (event: React.FormEvent<HTMLFormElement>) => void
|
onSubmit: (event: React.FormEvent<HTMLFormElement>) => void | Promise<void>;
|
||||||
onSignupClick: () => void
|
onSignupClick: () => void;
|
||||||
}
|
};
|
||||||
|
|
||||||
export function LoginForm({
|
export function LoginForm({
|
||||||
className,
|
className,
|
||||||
username,
|
username,
|
||||||
password,
|
password,
|
||||||
error,
|
error,
|
||||||
pending = false,
|
pending = false,
|
||||||
onUsernameChange,
|
onUsernameChange,
|
||||||
onPasswordChange,
|
onPasswordChange,
|
||||||
onSubmit,
|
onSubmit,
|
||||||
onSignupClick,
|
onSignupClick,
|
||||||
...props
|
...props
|
||||||
}: LoginFormProps) {
|
}: LoginFormProps) {
|
||||||
return (
|
return (
|
||||||
<div className={cn("flex flex-col gap-6", className)} {...props}>
|
<div className={cn("flex flex-col gap-6", className)} {...props}>
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle>Sign in to Cymelle</CardTitle>
|
<CardTitle>Sign in to Cymelle</CardTitle>
|
||||||
<CardDescription>
|
<CardDescription>
|
||||||
Use your username and password to continue.
|
Use your username and password to continue.
|
||||||
</CardDescription>
|
</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<form onSubmit={onSubmit}>
|
<form onSubmit={onSubmit}>
|
||||||
<FieldGroup>
|
<FieldGroup>
|
||||||
<Field>
|
<Field>
|
||||||
<FieldLabel htmlFor="login-username">Username</FieldLabel>
|
<FieldLabel htmlFor="login-username">Username</FieldLabel>
|
||||||
<Input
|
<Input
|
||||||
id="login-username"
|
id="login-username"
|
||||||
type="text"
|
type="text"
|
||||||
autoComplete="username"
|
autoComplete="username"
|
||||||
value={username}
|
value={username}
|
||||||
onChange={(event) => onUsernameChange(event.target.value)}
|
onChange={(event) => onUsernameChange(event.target.value)}
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
</Field>
|
</Field>
|
||||||
<Field>
|
<Field>
|
||||||
<div className="flex items-center">
|
<div className="flex items-center">
|
||||||
<FieldLabel htmlFor="login-password">Password</FieldLabel>
|
<FieldLabel htmlFor="login-password">Password</FieldLabel>
|
||||||
</div>
|
</div>
|
||||||
<Input
|
<Input
|
||||||
id="login-password"
|
id="login-password"
|
||||||
type="password"
|
type="password"
|
||||||
autoComplete="current-password"
|
autoComplete="current-password"
|
||||||
value={password}
|
value={password}
|
||||||
onChange={(event) => onPasswordChange(event.target.value)}
|
onChange={(event) => onPasswordChange(event.target.value)}
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
</Field>
|
</Field>
|
||||||
{error ? <FieldError>{error}</FieldError> : null}
|
{error ? <FieldError>{error}</FieldError> : null}
|
||||||
<Field>
|
<Field>
|
||||||
<Button type="submit" disabled={pending}>
|
<Button type="submit" disabled={pending}>
|
||||||
{pending ? "Signing in..." : "Sign in"}
|
{pending ? "Signing in..." : "Sign in"}
|
||||||
</Button>
|
</Button>
|
||||||
<FieldDescription className="text-center">
|
<FieldDescription className="text-center">
|
||||||
Don't have an account?{" "}
|
Don't have an account?{" "}
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
className="underline underline-offset-4 hover:text-primary"
|
className="underline underline-offset-4 hover:text-primary"
|
||||||
onClick={onSignupClick}
|
onClick={onSignupClick}
|
||||||
>
|
>
|
||||||
Sign up
|
Sign up
|
||||||
</button>
|
</button>
|
||||||
</FieldDescription>
|
</FieldDescription>
|
||||||
</Field>
|
</Field>
|
||||||
</FieldGroup>
|
</FieldGroup>
|
||||||
</form>
|
</form>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,92 +1,92 @@
|
|||||||
"use client"
|
"use client";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
IconDots,
|
type Icon,
|
||||||
IconFolder,
|
IconDots,
|
||||||
IconShare3,
|
IconFolder,
|
||||||
IconTrash,
|
IconShare3,
|
||||||
type Icon,
|
IconTrash,
|
||||||
} from "@tabler/icons-react"
|
} from "@tabler/icons-react";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
DropdownMenu,
|
DropdownMenu,
|
||||||
DropdownMenuContent,
|
DropdownMenuContent,
|
||||||
DropdownMenuItem,
|
DropdownMenuItem,
|
||||||
DropdownMenuSeparator,
|
DropdownMenuSeparator,
|
||||||
DropdownMenuTrigger,
|
DropdownMenuTrigger,
|
||||||
} from "#/components/ui/dropdown-menu.tsx"
|
} from "#/components/ui/dropdown-menu.tsx";
|
||||||
import {
|
import {
|
||||||
SidebarGroup,
|
SidebarGroup,
|
||||||
SidebarGroupLabel,
|
SidebarGroupLabel,
|
||||||
SidebarMenu,
|
SidebarMenu,
|
||||||
SidebarMenuAction,
|
SidebarMenuAction,
|
||||||
SidebarMenuButton,
|
SidebarMenuButton,
|
||||||
SidebarMenuItem,
|
SidebarMenuItem,
|
||||||
useSidebar,
|
useSidebar,
|
||||||
} from "#/components/ui/sidebar.tsx"
|
} from "#/components/ui/sidebar.tsx";
|
||||||
|
|
||||||
export function NavDocuments({
|
export function NavDocuments({
|
||||||
items,
|
items,
|
||||||
}: {
|
}: {
|
||||||
items: {
|
items: {
|
||||||
name: string
|
name: string;
|
||||||
url: string
|
url: string;
|
||||||
icon: Icon
|
icon: Icon;
|
||||||
}[]
|
}[];
|
||||||
}) {
|
}) {
|
||||||
const { isMobile } = useSidebar()
|
const { isMobile } = useSidebar();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<SidebarGroup className="group-data-[collapsible=icon]:hidden">
|
<SidebarGroup className="group-data-[collapsible=icon]:hidden">
|
||||||
<SidebarGroupLabel>Documents</SidebarGroupLabel>
|
<SidebarGroupLabel>Documents</SidebarGroupLabel>
|
||||||
<SidebarMenu>
|
<SidebarMenu>
|
||||||
{items.map((item) => (
|
{items.map((item) => (
|
||||||
<SidebarMenuItem key={item.name}>
|
<SidebarMenuItem key={item.name}>
|
||||||
<SidebarMenuButton asChild>
|
<SidebarMenuButton asChild>
|
||||||
<a href={item.url}>
|
<a href={item.url}>
|
||||||
<item.icon />
|
<item.icon />
|
||||||
<span>{item.name}</span>
|
<span>{item.name}</span>
|
||||||
</a>
|
</a>
|
||||||
</SidebarMenuButton>
|
</SidebarMenuButton>
|
||||||
<DropdownMenu>
|
<DropdownMenu>
|
||||||
<DropdownMenuTrigger asChild>
|
<DropdownMenuTrigger asChild>
|
||||||
<SidebarMenuAction
|
<SidebarMenuAction
|
||||||
showOnHover
|
showOnHover
|
||||||
className="rounded-sm data-[state=open]:bg-accent"
|
className="rounded-sm data-[state=open]:bg-accent"
|
||||||
>
|
>
|
||||||
<IconDots />
|
<IconDots />
|
||||||
<span className="sr-only">More</span>
|
<span className="sr-only">More</span>
|
||||||
</SidebarMenuAction>
|
</SidebarMenuAction>
|
||||||
</DropdownMenuTrigger>
|
</DropdownMenuTrigger>
|
||||||
<DropdownMenuContent
|
<DropdownMenuContent
|
||||||
className="w-24 rounded-lg"
|
className="w-24 rounded-lg"
|
||||||
side={isMobile ? "bottom" : "right"}
|
side={isMobile ? "bottom" : "right"}
|
||||||
align={isMobile ? "end" : "start"}
|
align={isMobile ? "end" : "start"}
|
||||||
>
|
>
|
||||||
<DropdownMenuItem>
|
<DropdownMenuItem>
|
||||||
<IconFolder />
|
<IconFolder />
|
||||||
<span>Open</span>
|
<span>Open</span>
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
<DropdownMenuItem>
|
<DropdownMenuItem>
|
||||||
<IconShare3 />
|
<IconShare3 />
|
||||||
<span>Share</span>
|
<span>Share</span>
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
<DropdownMenuSeparator />
|
<DropdownMenuSeparator />
|
||||||
<DropdownMenuItem variant="destructive">
|
<DropdownMenuItem variant="destructive">
|
||||||
<IconTrash />
|
<IconTrash />
|
||||||
<span>Delete</span>
|
<span>Delete</span>
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
</DropdownMenuContent>
|
</DropdownMenuContent>
|
||||||
</DropdownMenu>
|
</DropdownMenu>
|
||||||
</SidebarMenuItem>
|
</SidebarMenuItem>
|
||||||
))}
|
))}
|
||||||
<SidebarMenuItem>
|
<SidebarMenuItem>
|
||||||
<SidebarMenuButton className="text-sidebar-foreground/70">
|
<SidebarMenuButton className="text-sidebar-foreground/70">
|
||||||
<IconDots className="text-sidebar-foreground/70" />
|
<IconDots className="text-sidebar-foreground/70" />
|
||||||
<span>More</span>
|
<span>More</span>
|
||||||
</SidebarMenuButton>
|
</SidebarMenuButton>
|
||||||
</SidebarMenuItem>
|
</SidebarMenuItem>
|
||||||
</SidebarMenu>
|
</SidebarMenu>
|
||||||
</SidebarGroup>
|
</SidebarGroup>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,164 +1,170 @@
|
|||||||
import { ChevronRight, type LucideIcon } from "lucide-react"
|
import { Link, useLocation } from "@tanstack/react-router";
|
||||||
import { Link, useLocation } from "@tanstack/react-router"
|
import { ChevronRight, type LucideIcon } from "lucide-react";
|
||||||
import { useEffect, useRef, useState } from "react"
|
import { useEffect, useRef, useState } from "react";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
Collapsible,
|
Collapsible,
|
||||||
CollapsibleContent,
|
CollapsibleContent,
|
||||||
CollapsibleTrigger,
|
CollapsibleTrigger,
|
||||||
} from "#/components/ui/collapsible.tsx"
|
} from "#/components/ui/collapsible.tsx";
|
||||||
import {
|
import {
|
||||||
SidebarGroup,
|
SidebarGroup,
|
||||||
SidebarGroupLabel,
|
SidebarGroupLabel,
|
||||||
SidebarMenu,
|
SidebarMenu,
|
||||||
SidebarMenuButton,
|
SidebarMenuButton,
|
||||||
SidebarMenuItem,
|
SidebarMenuItem,
|
||||||
SidebarMenuSub,
|
SidebarMenuSub,
|
||||||
SidebarMenuSubButton,
|
SidebarMenuSubButton,
|
||||||
SidebarMenuSubItem,
|
SidebarMenuSubItem,
|
||||||
} from "#/components/ui/sidebar.tsx"
|
} from "#/components/ui/sidebar.tsx";
|
||||||
|
|
||||||
const openSectionsStorageKey = "cymelle.sidebar.open-sections"
|
const openSectionsStorageKey = "cymelle.sidebar.open-sections";
|
||||||
|
|
||||||
export function NavMain({
|
export function NavMain({
|
||||||
items,
|
items,
|
||||||
}: {
|
}: {
|
||||||
items: {
|
items: {
|
||||||
title: string
|
title: string;
|
||||||
url: string
|
url: string;
|
||||||
icon?: LucideIcon
|
icon?: LucideIcon;
|
||||||
isActive?: boolean
|
isActive?: boolean;
|
||||||
items?: {
|
items?: {
|
||||||
title: string
|
title: string;
|
||||||
url: string
|
url: string;
|
||||||
}[]
|
}[];
|
||||||
}[]
|
}[];
|
||||||
}) {
|
}) {
|
||||||
const location = useLocation()
|
const location = useLocation();
|
||||||
const previousPath = useRef<string | null>(null)
|
const previousPath = useRef<string | null>(null);
|
||||||
const [openSections, setOpenSections] = useState<Set<string>>(() => {
|
const [openSections, setOpenSections] = useState<Set<string>>(() => {
|
||||||
const itemTitles = new Set(items.map((item) => item.title))
|
const itemTitles = new Set(items.map((item) => item.title));
|
||||||
const storedSections = readOpenSections().filter((title) => itemTitles.has(title))
|
const storedSections = readOpenSections().filter((title) =>
|
||||||
|
itemTitles.has(title),
|
||||||
|
);
|
||||||
|
|
||||||
if (storedSections.length > 0) {
|
if (storedSections.length > 0) {
|
||||||
return new Set(storedSections)
|
return new Set(storedSections);
|
||||||
}
|
}
|
||||||
|
|
||||||
return new Set(
|
return new Set(
|
||||||
items
|
items
|
||||||
.filter((item) => isItemActive(item, location.pathname))
|
.filter((item) => isItemActive(item, location.pathname))
|
||||||
.map((item) => item.title)
|
.map((item) => item.title),
|
||||||
)
|
);
|
||||||
})
|
});
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
writeOpenSections([...openSections])
|
writeOpenSections([...openSections]);
|
||||||
}, [openSections])
|
}, [openSections]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (previousPath.current === location.pathname) {
|
if (previousPath.current === location.pathname) {
|
||||||
return
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
previousPath.current = location.pathname
|
previousPath.current = location.pathname;
|
||||||
setOpenSections((current) => {
|
setOpenSections((current) => {
|
||||||
const next = new Set(current)
|
const next = new Set(current);
|
||||||
items
|
items
|
||||||
.filter((item) => isItemActive(item, location.pathname))
|
.filter((item) => isItemActive(item, location.pathname))
|
||||||
.forEach((item) => next.add(item.title))
|
.forEach((item) => {
|
||||||
return next
|
next.add(item.title);
|
||||||
})
|
});
|
||||||
}, [items, location.pathname])
|
return next;
|
||||||
|
});
|
||||||
|
}, [items, location.pathname]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<SidebarGroup>
|
<SidebarGroup>
|
||||||
<SidebarGroupLabel>Commerce</SidebarGroupLabel>
|
<SidebarGroupLabel>Commerce</SidebarGroupLabel>
|
||||||
<SidebarMenu>
|
<SidebarMenu>
|
||||||
{items.map((item) => (
|
{items.map((item) => (
|
||||||
<Collapsible
|
<Collapsible
|
||||||
key={item.title}
|
key={item.title}
|
||||||
asChild
|
asChild
|
||||||
open={openSections.has(item.title)}
|
open={openSections.has(item.title)}
|
||||||
onOpenChange={(open) => {
|
onOpenChange={(open) => {
|
||||||
setOpenSections((current) => {
|
setOpenSections((current) => {
|
||||||
const next = new Set(current)
|
const next = new Set(current);
|
||||||
if (open) {
|
if (open) {
|
||||||
next.add(item.title)
|
next.add(item.title);
|
||||||
} else {
|
} else {
|
||||||
next.delete(item.title)
|
next.delete(item.title);
|
||||||
}
|
}
|
||||||
return next
|
return next;
|
||||||
})
|
});
|
||||||
}}
|
}}
|
||||||
className="group/collapsible"
|
className="group/collapsible"
|
||||||
>
|
>
|
||||||
<SidebarMenuItem>
|
<SidebarMenuItem>
|
||||||
<CollapsibleTrigger asChild>
|
<CollapsibleTrigger asChild>
|
||||||
<SidebarMenuButton tooltip={item.title}>
|
<SidebarMenuButton tooltip={item.title}>
|
||||||
{item.icon && <item.icon />}
|
{item.icon && <item.icon />}
|
||||||
<span>{item.title}</span>
|
<span>{item.title}</span>
|
||||||
<ChevronRight className="ml-auto transition-transform duration-200 group-data-[state=open]/collapsible:rotate-90" />
|
<ChevronRight className="ml-auto transition-transform duration-200 group-data-[state=open]/collapsible:rotate-90" />
|
||||||
</SidebarMenuButton>
|
</SidebarMenuButton>
|
||||||
</CollapsibleTrigger>
|
</CollapsibleTrigger>
|
||||||
<CollapsibleContent>
|
<CollapsibleContent>
|
||||||
<SidebarMenuSub>
|
<SidebarMenuSub>
|
||||||
{item.items?.map((subItem) => (
|
{item.items?.map((subItem) => (
|
||||||
<SidebarMenuSubItem key={subItem.title}>
|
<SidebarMenuSubItem key={subItem.title}>
|
||||||
<SidebarMenuSubButton asChild>
|
<SidebarMenuSubButton asChild>
|
||||||
<Link to={subItem.url}>
|
<Link to={subItem.url}>
|
||||||
<span>{subItem.title}</span>
|
<span>{subItem.title}</span>
|
||||||
</Link>
|
</Link>
|
||||||
</SidebarMenuSubButton>
|
</SidebarMenuSubButton>
|
||||||
</SidebarMenuSubItem>
|
</SidebarMenuSubItem>
|
||||||
))}
|
))}
|
||||||
</SidebarMenuSub>
|
</SidebarMenuSub>
|
||||||
</CollapsibleContent>
|
</CollapsibleContent>
|
||||||
</SidebarMenuItem>
|
</SidebarMenuItem>
|
||||||
</Collapsible>
|
</Collapsible>
|
||||||
))}
|
))}
|
||||||
</SidebarMenu>
|
</SidebarMenu>
|
||||||
</SidebarGroup>
|
</SidebarGroup>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function readOpenSections() {
|
function readOpenSections() {
|
||||||
if (typeof window === "undefined") {
|
if (typeof window === "undefined") {
|
||||||
return []
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
const raw = window.localStorage.getItem(openSectionsStorageKey)
|
const raw = window.localStorage.getItem(openSectionsStorageKey);
|
||||||
if (!raw) {
|
if (!raw) {
|
||||||
return []
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const value = JSON.parse(raw)
|
const value = JSON.parse(raw);
|
||||||
return Array.isArray(value) ? value.filter((item) => typeof item === "string") : []
|
return Array.isArray(value)
|
||||||
} catch {
|
? value.filter((item) => typeof item === "string")
|
||||||
window.localStorage.removeItem(openSectionsStorageKey)
|
: [];
|
||||||
return []
|
} catch {
|
||||||
}
|
window.localStorage.removeItem(openSectionsStorageKey);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function writeOpenSections(sections: string[]) {
|
function writeOpenSections(sections: string[]) {
|
||||||
if (typeof window === "undefined") {
|
if (typeof window === "undefined") {
|
||||||
return
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
window.localStorage.setItem(openSectionsStorageKey, JSON.stringify(sections))
|
window.localStorage.setItem(openSectionsStorageKey, JSON.stringify(sections));
|
||||||
}
|
}
|
||||||
|
|
||||||
function isItemActive(
|
function isItemActive(
|
||||||
item: {
|
item: {
|
||||||
url: string
|
url: string;
|
||||||
isActive?: boolean
|
isActive?: boolean;
|
||||||
items?: { url: string }[]
|
items?: { url: string }[];
|
||||||
},
|
},
|
||||||
pathname: string
|
pathname: string,
|
||||||
) {
|
) {
|
||||||
if (item.items?.some((subItem) => pathname === subItem.url)) {
|
if (item.items?.some((subItem) => pathname === subItem.url)) {
|
||||||
return true
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
return pathname === item.url || (Boolean(item.isActive) && pathname === "/")
|
return pathname === item.url || (Boolean(item.isActive) && pathname === "/");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,79 +1,75 @@
|
|||||||
"use client"
|
"use client";
|
||||||
|
|
||||||
|
import { Folder, type LucideIcon, MoreHorizontal } from "lucide-react";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
Folder,
|
DropdownMenu,
|
||||||
MoreHorizontal,
|
DropdownMenuContent,
|
||||||
type LucideIcon,
|
DropdownMenuItem,
|
||||||
} from "lucide-react"
|
DropdownMenuTrigger,
|
||||||
|
} from "#/components/ui/dropdown-menu.tsx";
|
||||||
import {
|
import {
|
||||||
DropdownMenu,
|
SidebarGroup,
|
||||||
DropdownMenuContent,
|
SidebarGroupLabel,
|
||||||
DropdownMenuItem,
|
SidebarMenu,
|
||||||
DropdownMenuTrigger,
|
SidebarMenuAction,
|
||||||
} from "#/components/ui/dropdown-menu.tsx"
|
SidebarMenuButton,
|
||||||
import {
|
SidebarMenuItem,
|
||||||
SidebarGroup,
|
useSidebar,
|
||||||
SidebarGroupLabel,
|
} from "#/components/ui/sidebar.tsx";
|
||||||
SidebarMenu,
|
|
||||||
SidebarMenuAction,
|
|
||||||
SidebarMenuButton,
|
|
||||||
SidebarMenuItem,
|
|
||||||
useSidebar,
|
|
||||||
} from "#/components/ui/sidebar.tsx"
|
|
||||||
|
|
||||||
export function NavProjects({
|
export function NavProjects({
|
||||||
projects,
|
projects,
|
||||||
}: {
|
}: {
|
||||||
projects: {
|
projects: {
|
||||||
name: string
|
name: string;
|
||||||
url: string
|
url: string;
|
||||||
icon: LucideIcon
|
icon: LucideIcon;
|
||||||
}[]
|
}[];
|
||||||
}) {
|
}) {
|
||||||
const { isMobile } = useSidebar()
|
const { isMobile } = useSidebar();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<SidebarGroup className="group-data-[collapsible=icon]:hidden">
|
<SidebarGroup className="group-data-[collapsible=icon]:hidden">
|
||||||
<SidebarGroupLabel>Shortcuts</SidebarGroupLabel>
|
<SidebarGroupLabel>Shortcuts</SidebarGroupLabel>
|
||||||
<SidebarMenu>
|
<SidebarMenu>
|
||||||
{projects.map((item) => (
|
{projects.map((item) => (
|
||||||
<SidebarMenuItem key={item.name}>
|
<SidebarMenuItem key={item.name}>
|
||||||
<SidebarMenuButton asChild>
|
<SidebarMenuButton asChild>
|
||||||
<a href={item.url}>
|
<a href={item.url}>
|
||||||
<item.icon />
|
<item.icon />
|
||||||
<span>{item.name}</span>
|
<span>{item.name}</span>
|
||||||
</a>
|
</a>
|
||||||
</SidebarMenuButton>
|
</SidebarMenuButton>
|
||||||
<DropdownMenu>
|
<DropdownMenu>
|
||||||
<DropdownMenuTrigger asChild>
|
<DropdownMenuTrigger asChild>
|
||||||
<SidebarMenuAction showOnHover>
|
<SidebarMenuAction showOnHover>
|
||||||
<MoreHorizontal />
|
<MoreHorizontal />
|
||||||
<span className="sr-only">More</span>
|
<span className="sr-only">More</span>
|
||||||
</SidebarMenuAction>
|
</SidebarMenuAction>
|
||||||
</DropdownMenuTrigger>
|
</DropdownMenuTrigger>
|
||||||
<DropdownMenuContent
|
<DropdownMenuContent
|
||||||
className="w-48 rounded-lg"
|
className="w-48 rounded-lg"
|
||||||
side={isMobile ? "bottom" : "right"}
|
side={isMobile ? "bottom" : "right"}
|
||||||
align={isMobile ? "end" : "start"}
|
align={isMobile ? "end" : "start"}
|
||||||
>
|
>
|
||||||
<DropdownMenuItem asChild>
|
<DropdownMenuItem asChild>
|
||||||
<a href={item.url}>
|
<a href={item.url}>
|
||||||
<Folder className="text-muted-foreground" />
|
<Folder className="text-muted-foreground" />
|
||||||
<span>Open</span>
|
<span>Open</span>
|
||||||
</a>
|
</a>
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
</DropdownMenuContent>
|
</DropdownMenuContent>
|
||||||
</DropdownMenu>
|
</DropdownMenu>
|
||||||
</SidebarMenuItem>
|
</SidebarMenuItem>
|
||||||
))}
|
))}
|
||||||
<SidebarMenuItem>
|
<SidebarMenuItem>
|
||||||
<SidebarMenuButton className="text-sidebar-foreground/70">
|
<SidebarMenuButton className="text-sidebar-foreground/70">
|
||||||
<MoreHorizontal className="text-sidebar-foreground/70" />
|
<MoreHorizontal className="text-sidebar-foreground/70" />
|
||||||
<span>More</span>
|
<span>More</span>
|
||||||
</SidebarMenuButton>
|
</SidebarMenuButton>
|
||||||
</SidebarMenuItem>
|
</SidebarMenuItem>
|
||||||
</SidebarMenu>
|
</SidebarMenu>
|
||||||
</SidebarGroup>
|
</SidebarGroup>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,42 +1,42 @@
|
|||||||
"use client"
|
"use client";
|
||||||
|
|
||||||
import * as React from "react"
|
import type { Icon } from "@tabler/icons-react";
|
||||||
import { type Icon } from "@tabler/icons-react"
|
import type * as React from "react";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
SidebarGroup,
|
SidebarGroup,
|
||||||
SidebarGroupContent,
|
SidebarGroupContent,
|
||||||
SidebarMenu,
|
SidebarMenu,
|
||||||
SidebarMenuButton,
|
SidebarMenuButton,
|
||||||
SidebarMenuItem,
|
SidebarMenuItem,
|
||||||
} from "#/components/ui/sidebar.tsx"
|
} from "#/components/ui/sidebar.tsx";
|
||||||
|
|
||||||
export function NavSecondary({
|
export function NavSecondary({
|
||||||
items,
|
items,
|
||||||
...props
|
...props
|
||||||
}: {
|
}: {
|
||||||
items: {
|
items: {
|
||||||
title: string
|
title: string;
|
||||||
url: string
|
url: string;
|
||||||
icon: Icon
|
icon: Icon;
|
||||||
}[]
|
}[];
|
||||||
} & React.ComponentPropsWithoutRef<typeof SidebarGroup>) {
|
} & React.ComponentPropsWithoutRef<typeof SidebarGroup>) {
|
||||||
return (
|
return (
|
||||||
<SidebarGroup {...props}>
|
<SidebarGroup {...props}>
|
||||||
<SidebarGroupContent>
|
<SidebarGroupContent>
|
||||||
<SidebarMenu>
|
<SidebarMenu>
|
||||||
{items.map((item) => (
|
{items.map((item) => (
|
||||||
<SidebarMenuItem key={item.title}>
|
<SidebarMenuItem key={item.title}>
|
||||||
<SidebarMenuButton asChild>
|
<SidebarMenuButton asChild>
|
||||||
<a href={item.url}>
|
<a href={item.url}>
|
||||||
<item.icon />
|
<item.icon />
|
||||||
<span>{item.title}</span>
|
<span>{item.title}</span>
|
||||||
</a>
|
</a>
|
||||||
</SidebarMenuButton>
|
</SidebarMenuButton>
|
||||||
</SidebarMenuItem>
|
</SidebarMenuItem>
|
||||||
))}
|
))}
|
||||||
</SidebarMenu>
|
</SidebarMenu>
|
||||||
</SidebarGroupContent>
|
</SidebarGroupContent>
|
||||||
</SidebarGroup>
|
</SidebarGroup>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,109 +1,109 @@
|
|||||||
import {
|
import { BadgeCheck, ChevronsUpDown, LogOut } from "lucide-react";
|
||||||
BadgeCheck,
|
|
||||||
ChevronsUpDown,
|
|
||||||
LogOut,
|
|
||||||
} from "lucide-react"
|
|
||||||
|
|
||||||
import {
|
import {
|
||||||
Avatar,
|
Avatar,
|
||||||
AvatarFallback,
|
AvatarFallback,
|
||||||
AvatarImage,
|
AvatarImage,
|
||||||
} from "#/components/ui/avatar.tsx"
|
} from "#/components/ui/avatar.tsx";
|
||||||
import {
|
import {
|
||||||
DropdownMenu,
|
DropdownMenu,
|
||||||
DropdownMenuContent,
|
DropdownMenuContent,
|
||||||
DropdownMenuGroup,
|
DropdownMenuGroup,
|
||||||
DropdownMenuItem,
|
DropdownMenuItem,
|
||||||
DropdownMenuLabel,
|
DropdownMenuLabel,
|
||||||
DropdownMenuSeparator,
|
DropdownMenuSeparator,
|
||||||
DropdownMenuTrigger,
|
DropdownMenuTrigger,
|
||||||
} from "#/components/ui/dropdown-menu.tsx"
|
} from "#/components/ui/dropdown-menu.tsx";
|
||||||
import {
|
import {
|
||||||
SidebarMenu,
|
SidebarMenu,
|
||||||
SidebarMenuButton,
|
SidebarMenuButton,
|
||||||
SidebarMenuItem,
|
SidebarMenuItem,
|
||||||
useSidebar,
|
useSidebar,
|
||||||
} from "#/components/ui/sidebar.tsx"
|
} from "#/components/ui/sidebar.tsx";
|
||||||
|
|
||||||
export function NavUser({
|
export function NavUser({
|
||||||
user,
|
user,
|
||||||
onLogout,
|
onLogout,
|
||||||
}: {
|
}: {
|
||||||
user: {
|
user: {
|
||||||
name: string
|
name: string;
|
||||||
email: string
|
email: string;
|
||||||
avatar: string
|
avatar: string;
|
||||||
}
|
};
|
||||||
onLogout?: () => void
|
onLogout?: () => void;
|
||||||
}) {
|
}) {
|
||||||
const { isMobile } = useSidebar()
|
const { isMobile } = useSidebar();
|
||||||
const initials = user.name
|
const initials =
|
||||||
.split(/\s+/)
|
user.name
|
||||||
.filter(Boolean)
|
.split(/\s+/)
|
||||||
.map((part) => part[0])
|
.filter(Boolean)
|
||||||
.join("")
|
.map((part) => part[0])
|
||||||
.slice(0, 2)
|
.join("")
|
||||||
.toUpperCase()
|
.slice(0, 2)
|
||||||
|| "CY"
|
.toUpperCase() || "CY";
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<SidebarMenu>
|
<SidebarMenu>
|
||||||
<SidebarMenuItem>
|
<SidebarMenuItem>
|
||||||
<DropdownMenu>
|
<DropdownMenu>
|
||||||
<DropdownMenuTrigger asChild>
|
<DropdownMenuTrigger asChild>
|
||||||
<SidebarMenuButton
|
<SidebarMenuButton
|
||||||
size="lg"
|
size="lg"
|
||||||
className="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground"
|
className="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground"
|
||||||
>
|
>
|
||||||
<Avatar className="h-8 w-8 rounded-lg">
|
<Avatar className="h-8 w-8 rounded-lg">
|
||||||
<AvatarImage src={user.avatar} alt={user.name} />
|
<AvatarImage src={user.avatar} alt={user.name} />
|
||||||
<AvatarFallback className="rounded-lg">{initials}</AvatarFallback>
|
<AvatarFallback className="rounded-lg">
|
||||||
</Avatar>
|
{initials}
|
||||||
<div className="grid flex-1 text-left text-sm leading-tight">
|
</AvatarFallback>
|
||||||
<span className="truncate font-medium">{user.name}</span>
|
</Avatar>
|
||||||
<span className="truncate text-xs">{user.email}</span>
|
<div className="grid flex-1 text-left text-sm leading-tight">
|
||||||
</div>
|
<span className="truncate font-medium">{user.name}</span>
|
||||||
<ChevronsUpDown className="ml-auto size-4" />
|
<span className="truncate text-xs">{user.email}</span>
|
||||||
</SidebarMenuButton>
|
</div>
|
||||||
</DropdownMenuTrigger>
|
<ChevronsUpDown className="ml-auto size-4" />
|
||||||
<DropdownMenuContent
|
</SidebarMenuButton>
|
||||||
className="w-(--radix-dropdown-menu-trigger-width) min-w-56 rounded-lg"
|
</DropdownMenuTrigger>
|
||||||
side={isMobile ? "bottom" : "right"}
|
<DropdownMenuContent
|
||||||
align="end"
|
className="w-(--radix-dropdown-menu-trigger-width) min-w-56 rounded-lg"
|
||||||
sideOffset={4}
|
side={isMobile ? "bottom" : "right"}
|
||||||
>
|
align="end"
|
||||||
<DropdownMenuLabel className="p-0 font-normal">
|
sideOffset={4}
|
||||||
<div className="flex items-center gap-2 px-1 py-1.5 text-left text-sm">
|
>
|
||||||
<Avatar className="h-8 w-8 rounded-lg">
|
<DropdownMenuLabel className="p-0 font-normal">
|
||||||
<AvatarImage src={user.avatar} alt={user.name} />
|
<div className="flex items-center gap-2 px-1 py-1.5 text-left text-sm">
|
||||||
<AvatarFallback className="rounded-lg">{initials}</AvatarFallback>
|
<Avatar className="h-8 w-8 rounded-lg">
|
||||||
</Avatar>
|
<AvatarImage src={user.avatar} alt={user.name} />
|
||||||
<div className="grid flex-1 text-left text-sm leading-tight">
|
<AvatarFallback className="rounded-lg">
|
||||||
<span className="truncate font-medium">{user.name}</span>
|
{initials}
|
||||||
<span className="truncate text-xs">{user.email}</span>
|
</AvatarFallback>
|
||||||
</div>
|
</Avatar>
|
||||||
</div>
|
<div className="grid flex-1 text-left text-sm leading-tight">
|
||||||
</DropdownMenuLabel>
|
<span className="truncate font-medium">{user.name}</span>
|
||||||
<DropdownMenuSeparator />
|
<span className="truncate text-xs">{user.email}</span>
|
||||||
<DropdownMenuGroup>
|
</div>
|
||||||
<DropdownMenuItem>
|
</div>
|
||||||
<BadgeCheck />
|
</DropdownMenuLabel>
|
||||||
Account session
|
<DropdownMenuSeparator />
|
||||||
</DropdownMenuItem>
|
<DropdownMenuGroup>
|
||||||
</DropdownMenuGroup>
|
<DropdownMenuItem>
|
||||||
<DropdownMenuSeparator />
|
<BadgeCheck />
|
||||||
<DropdownMenuItem
|
Account session
|
||||||
onSelect={(event) => {
|
</DropdownMenuItem>
|
||||||
event.preventDefault()
|
</DropdownMenuGroup>
|
||||||
void onLogout?.()
|
<DropdownMenuSeparator />
|
||||||
}}
|
<DropdownMenuItem
|
||||||
>
|
onSelect={(event) => {
|
||||||
<LogOut />
|
event.preventDefault();
|
||||||
Log out
|
void onLogout?.();
|
||||||
</DropdownMenuItem>
|
}}
|
||||||
</DropdownMenuContent>
|
>
|
||||||
</DropdownMenu>
|
<LogOut />
|
||||||
</SidebarMenuItem>
|
Log out
|
||||||
</SidebarMenu>
|
</DropdownMenuItem>
|
||||||
)
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
</SidebarMenuItem>
|
||||||
|
</SidebarMenu>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,102 +1,102 @@
|
|||||||
import { IconTrendingDown, IconTrendingUp } from "@tabler/icons-react"
|
import { IconTrendingDown, IconTrendingUp } from "@tabler/icons-react";
|
||||||
|
|
||||||
import { Badge } from "#/components/ui/badge.tsx"
|
import { Badge } from "#/components/ui/badge.tsx";
|
||||||
import {
|
import {
|
||||||
Card,
|
Card,
|
||||||
CardAction,
|
CardAction,
|
||||||
CardDescription,
|
CardDescription,
|
||||||
CardFooter,
|
CardFooter,
|
||||||
CardHeader,
|
CardHeader,
|
||||||
CardTitle,
|
CardTitle,
|
||||||
} from "#/components/ui/card.tsx"
|
} from "#/components/ui/card.tsx";
|
||||||
|
|
||||||
export function SectionCards() {
|
export function SectionCards() {
|
||||||
return (
|
return (
|
||||||
<div className="grid grid-cols-1 gap-4 px-4 *:data-[slot=card]:bg-gradient-to-t *:data-[slot=card]:from-primary/5 *:data-[slot=card]:to-card *:data-[slot=card]:shadow-xs lg:px-6 @xl/main:grid-cols-2 @5xl/main:grid-cols-4 dark:*:data-[slot=card]:bg-card">
|
<div className="grid grid-cols-1 gap-4 px-4 *:data-[slot=card]:bg-gradient-to-t *:data-[slot=card]:from-primary/5 *:data-[slot=card]:to-card *:data-[slot=card]:shadow-xs lg:px-6 @xl/main:grid-cols-2 @5xl/main:grid-cols-4 dark:*:data-[slot=card]:bg-card">
|
||||||
<Card className="@container/card">
|
<Card className="@container/card">
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardDescription>Total Revenue</CardDescription>
|
<CardDescription>Total Revenue</CardDescription>
|
||||||
<CardTitle className="text-2xl font-semibold tabular-nums @[250px]/card:text-3xl">
|
<CardTitle className="text-2xl font-semibold tabular-nums @[250px]/card:text-3xl">
|
||||||
$1,250.00
|
$1,250.00
|
||||||
</CardTitle>
|
</CardTitle>
|
||||||
<CardAction>
|
<CardAction>
|
||||||
<Badge variant="outline">
|
<Badge variant="outline">
|
||||||
<IconTrendingUp />
|
<IconTrendingUp />
|
||||||
+12.5%
|
+12.5%
|
||||||
</Badge>
|
</Badge>
|
||||||
</CardAction>
|
</CardAction>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardFooter className="flex-col items-start gap-1.5 text-sm">
|
<CardFooter className="flex-col items-start gap-1.5 text-sm">
|
||||||
<div className="line-clamp-1 flex gap-2 font-medium">
|
<div className="line-clamp-1 flex gap-2 font-medium">
|
||||||
Trending up this month <IconTrendingUp className="size-4" />
|
Trending up this month <IconTrendingUp className="size-4" />
|
||||||
</div>
|
</div>
|
||||||
<div className="text-muted-foreground">
|
<div className="text-muted-foreground">
|
||||||
Visitors for the last 6 months
|
Visitors for the last 6 months
|
||||||
</div>
|
</div>
|
||||||
</CardFooter>
|
</CardFooter>
|
||||||
</Card>
|
</Card>
|
||||||
<Card className="@container/card">
|
<Card className="@container/card">
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardDescription>New Customers</CardDescription>
|
<CardDescription>New Customers</CardDescription>
|
||||||
<CardTitle className="text-2xl font-semibold tabular-nums @[250px]/card:text-3xl">
|
<CardTitle className="text-2xl font-semibold tabular-nums @[250px]/card:text-3xl">
|
||||||
1,234
|
1,234
|
||||||
</CardTitle>
|
</CardTitle>
|
||||||
<CardAction>
|
<CardAction>
|
||||||
<Badge variant="outline">
|
<Badge variant="outline">
|
||||||
<IconTrendingDown />
|
<IconTrendingDown />
|
||||||
-20%
|
-20%
|
||||||
</Badge>
|
</Badge>
|
||||||
</CardAction>
|
</CardAction>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardFooter className="flex-col items-start gap-1.5 text-sm">
|
<CardFooter className="flex-col items-start gap-1.5 text-sm">
|
||||||
<div className="line-clamp-1 flex gap-2 font-medium">
|
<div className="line-clamp-1 flex gap-2 font-medium">
|
||||||
Down 20% this period <IconTrendingDown className="size-4" />
|
Down 20% this period <IconTrendingDown className="size-4" />
|
||||||
</div>
|
</div>
|
||||||
<div className="text-muted-foreground">
|
<div className="text-muted-foreground">
|
||||||
Acquisition needs attention
|
Acquisition needs attention
|
||||||
</div>
|
</div>
|
||||||
</CardFooter>
|
</CardFooter>
|
||||||
</Card>
|
</Card>
|
||||||
<Card className="@container/card">
|
<Card className="@container/card">
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardDescription>Active Accounts</CardDescription>
|
<CardDescription>Active Accounts</CardDescription>
|
||||||
<CardTitle className="text-2xl font-semibold tabular-nums @[250px]/card:text-3xl">
|
<CardTitle className="text-2xl font-semibold tabular-nums @[250px]/card:text-3xl">
|
||||||
45,678
|
45,678
|
||||||
</CardTitle>
|
</CardTitle>
|
||||||
<CardAction>
|
<CardAction>
|
||||||
<Badge variant="outline">
|
<Badge variant="outline">
|
||||||
<IconTrendingUp />
|
<IconTrendingUp />
|
||||||
+12.5%
|
+12.5%
|
||||||
</Badge>
|
</Badge>
|
||||||
</CardAction>
|
</CardAction>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardFooter className="flex-col items-start gap-1.5 text-sm">
|
<CardFooter className="flex-col items-start gap-1.5 text-sm">
|
||||||
<div className="line-clamp-1 flex gap-2 font-medium">
|
<div className="line-clamp-1 flex gap-2 font-medium">
|
||||||
Strong user retention <IconTrendingUp className="size-4" />
|
Strong user retention <IconTrendingUp className="size-4" />
|
||||||
</div>
|
</div>
|
||||||
<div className="text-muted-foreground">Engagement exceed targets</div>
|
<div className="text-muted-foreground">Engagement exceed targets</div>
|
||||||
</CardFooter>
|
</CardFooter>
|
||||||
</Card>
|
</Card>
|
||||||
<Card className="@container/card">
|
<Card className="@container/card">
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardDescription>Growth Rate</CardDescription>
|
<CardDescription>Growth Rate</CardDescription>
|
||||||
<CardTitle className="text-2xl font-semibold tabular-nums @[250px]/card:text-3xl">
|
<CardTitle className="text-2xl font-semibold tabular-nums @[250px]/card:text-3xl">
|
||||||
4.5%
|
4.5%
|
||||||
</CardTitle>
|
</CardTitle>
|
||||||
<CardAction>
|
<CardAction>
|
||||||
<Badge variant="outline">
|
<Badge variant="outline">
|
||||||
<IconTrendingUp />
|
<IconTrendingUp />
|
||||||
+4.5%
|
+4.5%
|
||||||
</Badge>
|
</Badge>
|
||||||
</CardAction>
|
</CardAction>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardFooter className="flex-col items-start gap-1.5 text-sm">
|
<CardFooter className="flex-col items-start gap-1.5 text-sm">
|
||||||
<div className="line-clamp-1 flex gap-2 font-medium">
|
<div className="line-clamp-1 flex gap-2 font-medium">
|
||||||
Steady performance increase <IconTrendingUp className="size-4" />
|
Steady performance increase <IconTrendingUp className="size-4" />
|
||||||
</div>
|
</div>
|
||||||
<div className="text-muted-foreground">Meets growth projections</div>
|
<div className="text-muted-foreground">Meets growth projections</div>
|
||||||
</CardFooter>
|
</CardFooter>
|
||||||
</Card>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,135 +1,139 @@
|
|||||||
import { Button } from "#/components/ui/button.tsx"
|
import { Button } from "#/components/ui/button.tsx";
|
||||||
import {
|
import {
|
||||||
Card,
|
Card,
|
||||||
CardContent,
|
CardContent,
|
||||||
CardDescription,
|
CardDescription,
|
||||||
CardHeader,
|
CardHeader,
|
||||||
CardTitle,
|
CardTitle,
|
||||||
} from "#/components/ui/card.tsx"
|
} from "#/components/ui/card.tsx";
|
||||||
import {
|
import {
|
||||||
Field,
|
Field,
|
||||||
FieldDescription,
|
FieldDescription,
|
||||||
FieldError,
|
FieldError,
|
||||||
FieldGroup,
|
FieldGroup,
|
||||||
FieldLabel,
|
FieldLabel,
|
||||||
} from "#/components/ui/field.tsx"
|
} from "#/components/ui/field.tsx";
|
||||||
import { Input } from "#/components/ui/input.tsx"
|
import { Input } from "#/components/ui/input.tsx";
|
||||||
|
|
||||||
type SignupFormProps = React.ComponentProps<typeof Card> & {
|
type SignupFormProps = Omit<React.ComponentProps<typeof Card>, "onSubmit"> & {
|
||||||
displayName: string
|
displayName: string;
|
||||||
username: string
|
username: string;
|
||||||
password: string
|
password: string;
|
||||||
confirmPassword: string
|
confirmPassword: string;
|
||||||
error?: string | null
|
error?: string | null;
|
||||||
pending?: boolean
|
pending?: boolean;
|
||||||
onDisplayNameChange: (value: string) => void
|
onDisplayNameChange: (value: string) => void;
|
||||||
onUsernameChange: (value: string) => void
|
onUsernameChange: (value: string) => void;
|
||||||
onPasswordChange: (value: string) => void
|
onPasswordChange: (value: string) => void;
|
||||||
onConfirmPasswordChange: (value: string) => void
|
onConfirmPasswordChange: (value: string) => void;
|
||||||
onSubmit: (event: React.FormEvent<HTMLFormElement>) => void
|
onSubmit: (event: React.FormEvent<HTMLFormElement>) => void | Promise<void>;
|
||||||
onLoginClick: () => void
|
onLoginClick: () => void;
|
||||||
}
|
};
|
||||||
|
|
||||||
export function SignupForm({
|
export function SignupForm({
|
||||||
displayName,
|
displayName,
|
||||||
username,
|
username,
|
||||||
password,
|
password,
|
||||||
confirmPassword,
|
confirmPassword,
|
||||||
error,
|
error,
|
||||||
pending = false,
|
pending = false,
|
||||||
onDisplayNameChange,
|
onDisplayNameChange,
|
||||||
onUsernameChange,
|
onUsernameChange,
|
||||||
onPasswordChange,
|
onPasswordChange,
|
||||||
onConfirmPasswordChange,
|
onConfirmPasswordChange,
|
||||||
onSubmit,
|
onSubmit,
|
||||||
onLoginClick,
|
onLoginClick,
|
||||||
...props
|
...props
|
||||||
}: SignupFormProps) {
|
}: SignupFormProps) {
|
||||||
return (
|
return (
|
||||||
<Card {...props}>
|
<Card {...props}>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle>Create an account</CardTitle>
|
<CardTitle>Create an account</CardTitle>
|
||||||
<CardDescription>
|
<CardDescription>
|
||||||
Create a customer account to place orders and request rides.
|
Create a customer account to place orders and request rides.
|
||||||
</CardDescription>
|
</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<form onSubmit={onSubmit}>
|
<form onSubmit={onSubmit}>
|
||||||
<FieldGroup>
|
<FieldGroup>
|
||||||
<Field>
|
<Field>
|
||||||
<FieldLabel htmlFor="signup-display-name">Display name</FieldLabel>
|
<FieldLabel htmlFor="signup-display-name">
|
||||||
<Input
|
Display name
|
||||||
id="signup-display-name"
|
</FieldLabel>
|
||||||
type="text"
|
<Input
|
||||||
autoComplete="name"
|
id="signup-display-name"
|
||||||
value={displayName}
|
type="text"
|
||||||
onChange={(event) => onDisplayNameChange(event.target.value)}
|
autoComplete="name"
|
||||||
required
|
value={displayName}
|
||||||
/>
|
onChange={(event) => onDisplayNameChange(event.target.value)}
|
||||||
</Field>
|
required
|
||||||
<Field>
|
/>
|
||||||
<FieldLabel htmlFor="signup-username">Username</FieldLabel>
|
</Field>
|
||||||
<Input
|
<Field>
|
||||||
id="signup-username"
|
<FieldLabel htmlFor="signup-username">Username</FieldLabel>
|
||||||
type="text"
|
<Input
|
||||||
autoComplete="username"
|
id="signup-username"
|
||||||
value={username}
|
type="text"
|
||||||
onChange={(event) => onUsernameChange(event.target.value)}
|
autoComplete="username"
|
||||||
required
|
value={username}
|
||||||
/>
|
onChange={(event) => onUsernameChange(event.target.value)}
|
||||||
<FieldDescription>
|
required
|
||||||
This is what you will use when signing in.
|
/>
|
||||||
</FieldDescription>
|
<FieldDescription>
|
||||||
</Field>
|
This is what you will use when signing in.
|
||||||
<Field>
|
</FieldDescription>
|
||||||
<FieldLabel htmlFor="signup-password">Password</FieldLabel>
|
</Field>
|
||||||
<Input
|
<Field>
|
||||||
id="signup-password"
|
<FieldLabel htmlFor="signup-password">Password</FieldLabel>
|
||||||
type="password"
|
<Input
|
||||||
autoComplete="new-password"
|
id="signup-password"
|
||||||
value={password}
|
type="password"
|
||||||
onChange={(event) => onPasswordChange(event.target.value)}
|
autoComplete="new-password"
|
||||||
required
|
value={password}
|
||||||
/>
|
onChange={(event) => onPasswordChange(event.target.value)}
|
||||||
<FieldDescription>
|
required
|
||||||
Must be at least 8 characters long.
|
/>
|
||||||
</FieldDescription>
|
<FieldDescription>
|
||||||
</Field>
|
Must be at least 8 characters long.
|
||||||
<Field>
|
</FieldDescription>
|
||||||
<FieldLabel htmlFor="signup-confirm-password">
|
</Field>
|
||||||
Confirm Password
|
<Field>
|
||||||
</FieldLabel>
|
<FieldLabel htmlFor="signup-confirm-password">
|
||||||
<Input
|
Confirm Password
|
||||||
id="signup-confirm-password"
|
</FieldLabel>
|
||||||
type="password"
|
<Input
|
||||||
autoComplete="new-password"
|
id="signup-confirm-password"
|
||||||
value={confirmPassword}
|
type="password"
|
||||||
onChange={(event) => onConfirmPasswordChange(event.target.value)}
|
autoComplete="new-password"
|
||||||
required
|
value={confirmPassword}
|
||||||
/>
|
onChange={(event) =>
|
||||||
<FieldDescription>Please confirm your password.</FieldDescription>
|
onConfirmPasswordChange(event.target.value)
|
||||||
</Field>
|
}
|
||||||
{error ? <FieldError>{error}</FieldError> : null}
|
required
|
||||||
<FieldGroup>
|
/>
|
||||||
<Field>
|
<FieldDescription>Please confirm your password.</FieldDescription>
|
||||||
<Button type="submit" disabled={pending}>
|
</Field>
|
||||||
{pending ? "Creating account..." : "Create account"}
|
{error ? <FieldError>{error}</FieldError> : null}
|
||||||
</Button>
|
<FieldGroup>
|
||||||
<FieldDescription className="px-6 text-center">
|
<Field>
|
||||||
Already have an account?{" "}
|
<Button type="submit" disabled={pending}>
|
||||||
<button
|
{pending ? "Creating account..." : "Create account"}
|
||||||
type="button"
|
</Button>
|
||||||
className="underline underline-offset-4 hover:text-primary"
|
<FieldDescription className="px-6 text-center">
|
||||||
onClick={onLoginClick}
|
Already have an account?{" "}
|
||||||
>
|
<button
|
||||||
Sign in
|
type="button"
|
||||||
</button>
|
className="underline underline-offset-4 hover:text-primary"
|
||||||
</FieldDescription>
|
onClick={onLoginClick}
|
||||||
</Field>
|
>
|
||||||
</FieldGroup>
|
Sign in
|
||||||
</FieldGroup>
|
</button>
|
||||||
</form>
|
</FieldDescription>
|
||||||
</CardContent>
|
</Field>
|
||||||
</Card>
|
</FieldGroup>
|
||||||
)
|
</FieldGroup>
|
||||||
|
</form>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,42 +1,48 @@
|
|||||||
import { Link } from "@tanstack/react-router"
|
import { Link } from "@tanstack/react-router";
|
||||||
import { ShoppingCart } from "lucide-react"
|
import { ShoppingCart } from "lucide-react";
|
||||||
|
import { ThemeToggle } from "#/components/theme-toggle.tsx";
|
||||||
import { Button } from "#/components/ui/button.tsx"
|
import { Button } from "#/components/ui/button.tsx";
|
||||||
import { Separator } from "#/components/ui/separator.tsx"
|
import { Separator } from "#/components/ui/separator.tsx";
|
||||||
import { SidebarTrigger } from "#/components/ui/sidebar.tsx"
|
import { SidebarTrigger } from "#/components/ui/sidebar.tsx";
|
||||||
import { ThemeToggle } from "#/components/theme-toggle.tsx"
|
import { useCart } from "#/hooks/useCart.tsx";
|
||||||
import { useCart } from "#/hooks/useCart.tsx"
|
|
||||||
|
|
||||||
type SiteHeaderProps = {
|
type SiteHeaderProps = {
|
||||||
title: string
|
title: string;
|
||||||
onLogout: () => void
|
onLogout: () => void;
|
||||||
showCart?: boolean
|
showCart?: boolean;
|
||||||
}
|
};
|
||||||
|
|
||||||
export function SiteHeader({ title, onLogout, showCart = false }: SiteHeaderProps) {
|
export function SiteHeader({
|
||||||
const cart = useCart()
|
title,
|
||||||
|
onLogout,
|
||||||
|
showCart = false,
|
||||||
|
}: SiteHeaderProps) {
|
||||||
|
const cart = useCart();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<header className="flex h-(--header-height) shrink-0 items-center gap-2 border-b transition-[width,height] ease-linear group-has-data-[collapsible=icon]/sidebar-wrapper:h-(--header-height)">
|
<header className="flex h-(--header-height) shrink-0 items-center gap-2 border-b transition-[width,height] ease-linear group-has-data-[collapsible=icon]/sidebar-wrapper:h-(--header-height)">
|
||||||
<div className="flex w-full items-center gap-1 px-4 lg:gap-2 lg:px-6">
|
<div className="flex w-full items-center gap-1 px-4 lg:gap-2 lg:px-6">
|
||||||
<SidebarTrigger className="-ml-1" />
|
<SidebarTrigger className="-ml-1" />
|
||||||
<Separator orientation="vertical" className="mx-2 data-[orientation=vertical]:h-4" />
|
<Separator
|
||||||
<h1 className="text-base font-medium">{title}</h1>
|
orientation="vertical"
|
||||||
<div className="ml-auto flex items-center gap-2">
|
className="mx-2 data-[orientation=vertical]:h-4"
|
||||||
<ThemeToggle />
|
/>
|
||||||
{showCart ? (
|
<h1 className="text-base font-medium">{title}</h1>
|
||||||
<Button asChild variant="outline" size="sm">
|
<div className="ml-auto flex items-center gap-2">
|
||||||
<Link to="/cart">
|
<ThemeToggle />
|
||||||
<ShoppingCart />
|
{showCart ? (
|
||||||
Cart ({cart.itemCount})
|
<Button asChild variant="outline" size="sm">
|
||||||
</Link>
|
<Link to="/cart">
|
||||||
</Button>
|
<ShoppingCart />
|
||||||
) : null}
|
Cart ({cart.itemCount})
|
||||||
<Button type="button" variant="outline" size="sm" onClick={onLogout}>
|
</Link>
|
||||||
Sign out
|
</Button>
|
||||||
</Button>
|
) : null}
|
||||||
</div>
|
<Button type="button" variant="outline" size="sm" onClick={onLogout}>
|
||||||
</div>
|
Sign out
|
||||||
</header>
|
</Button>
|
||||||
)
|
</div>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,128 +1,133 @@
|
|||||||
import { LoginForm } from "#/components/login-form.tsx"
|
import { useEffect, useState } from "react";
|
||||||
import { SignupForm } from "#/components/signup-form.tsx"
|
import { LoginForm } from "#/components/login-form.tsx";
|
||||||
import { Dialog, DialogContent } from "#/components/ui/dialog.tsx"
|
import { SignupForm } from "#/components/signup-form.tsx";
|
||||||
import { useEffect, useState } from "react"
|
import { Dialog, DialogContent } from "#/components/ui/dialog.tsx";
|
||||||
|
|
||||||
type AuthDialogProps = {
|
type AuthDialogProps = {
|
||||||
open: boolean
|
open: boolean;
|
||||||
initialMode: "login" | "register"
|
initialMode: "login" | "register";
|
||||||
onOpenChange: (open: boolean) => void
|
onOpenChange: (open: boolean) => void;
|
||||||
onLogin: (request: { username: string; password: string }) => Promise<unknown>
|
onLogin: (request: {
|
||||||
onRegister: (request: {
|
username: string;
|
||||||
username: string
|
password: string;
|
||||||
password: string
|
}) => Promise<unknown>;
|
||||||
displayName: string
|
onRegister: (request: {
|
||||||
}) => Promise<unknown>
|
username: string;
|
||||||
}
|
password: string;
|
||||||
|
displayName: string;
|
||||||
|
}) => Promise<unknown>;
|
||||||
|
};
|
||||||
|
|
||||||
export function AuthDialog({
|
export function AuthDialog({
|
||||||
open,
|
open,
|
||||||
initialMode,
|
initialMode,
|
||||||
onOpenChange,
|
onOpenChange,
|
||||||
onLogin,
|
onLogin,
|
||||||
onRegister,
|
onRegister,
|
||||||
}: AuthDialogProps) {
|
}: AuthDialogProps) {
|
||||||
return (
|
return (
|
||||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||||
<DialogContent className="max-w-md border-0 bg-transparent p-0 shadow-none">
|
<DialogContent className="max-w-md border-0 bg-transparent p-0 shadow-none">
|
||||||
<AuthForm
|
<AuthForm
|
||||||
initialMode={initialMode}
|
initialMode={initialMode}
|
||||||
onLogin={onLogin}
|
onLogin={onLogin}
|
||||||
onRegister={onRegister}
|
onRegister={onRegister}
|
||||||
/>
|
/>
|
||||||
</DialogContent>
|
</DialogContent>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function AuthForm({
|
export function AuthForm({
|
||||||
initialMode,
|
initialMode,
|
||||||
onLogin,
|
onLogin,
|
||||||
onRegister,
|
onRegister,
|
||||||
}: Omit<AuthDialogProps, "open" | "onOpenChange">) {
|
}: Omit<AuthDialogProps, "open" | "onOpenChange">) {
|
||||||
const [mode, setMode] = useState<"login" | "register">(initialMode)
|
const [mode, setMode] = useState<"login" | "register">(initialMode);
|
||||||
const [username, setUsername] = useState("")
|
const [username, setUsername] = useState("");
|
||||||
const [displayName, setDisplayName] = useState("")
|
const [displayName, setDisplayName] = useState("");
|
||||||
const [password, setPassword] = useState("")
|
const [password, setPassword] = useState("");
|
||||||
const [confirmPassword, setConfirmPassword] = useState("")
|
const [confirmPassword, setConfirmPassword] = useState("");
|
||||||
const [error, setError] = useState<string | null>(null)
|
const [error, setError] = useState<string | null>(null);
|
||||||
const [pending, setPending] = useState(false)
|
const [pending, setPending] = useState(false);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setMode(initialMode)
|
setMode(initialMode);
|
||||||
setError(null)
|
setError(null);
|
||||||
}, [initialMode])
|
}, [initialMode]);
|
||||||
|
|
||||||
async function handleLogin(event: React.FormEvent<HTMLFormElement>) {
|
async function handleLogin(event: React.FormEvent<HTMLFormElement>) {
|
||||||
event.preventDefault()
|
event.preventDefault();
|
||||||
setError(null)
|
setError(null);
|
||||||
setPending(true)
|
setPending(true);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await onLogin({ username, password })
|
await onLogin({ username, password });
|
||||||
} catch (caught) {
|
} catch (caught) {
|
||||||
setError(caught instanceof Error ? caught.message : "Sign in failed")
|
setError(caught instanceof Error ? caught.message : "Sign in failed");
|
||||||
} finally {
|
} finally {
|
||||||
setPending(false)
|
setPending(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function handleSignup(event: React.FormEvent<HTMLFormElement>) {
|
async function handleSignup(event: React.FormEvent<HTMLFormElement>) {
|
||||||
event.preventDefault()
|
event.preventDefault();
|
||||||
setError(null)
|
setError(null);
|
||||||
|
|
||||||
if (password !== confirmPassword) {
|
if (password !== confirmPassword) {
|
||||||
setError("Passwords do not match")
|
setError("Passwords do not match");
|
||||||
return
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
setPending(true)
|
setPending(true);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await onRegister({ username, displayName, password })
|
await onRegister({ username, displayName, password });
|
||||||
await onLogin({ username, password })
|
await onLogin({ username, password });
|
||||||
} catch (caught) {
|
} catch (caught) {
|
||||||
setError(caught instanceof Error ? caught.message : "Account creation failed")
|
setError(
|
||||||
} finally {
|
caught instanceof Error ? caught.message : "Account creation failed",
|
||||||
setPending(false)
|
);
|
||||||
}
|
} finally {
|
||||||
}
|
setPending(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (mode === "register") {
|
if (mode === "register") {
|
||||||
return (
|
return (
|
||||||
<SignupForm
|
<SignupForm
|
||||||
displayName={displayName}
|
displayName={displayName}
|
||||||
username={username}
|
username={username}
|
||||||
password={password}
|
password={password}
|
||||||
confirmPassword={confirmPassword}
|
confirmPassword={confirmPassword}
|
||||||
error={error}
|
error={error}
|
||||||
pending={pending}
|
pending={pending}
|
||||||
onDisplayNameChange={setDisplayName}
|
onDisplayNameChange={setDisplayName}
|
||||||
onUsernameChange={setUsername}
|
onUsernameChange={setUsername}
|
||||||
onPasswordChange={setPassword}
|
onPasswordChange={setPassword}
|
||||||
onConfirmPasswordChange={setConfirmPassword}
|
onConfirmPasswordChange={setConfirmPassword}
|
||||||
onSubmit={handleSignup}
|
onSubmit={handleSignup}
|
||||||
onLoginClick={() => {
|
onLoginClick={() => {
|
||||||
setMode("login")
|
setMode("login");
|
||||||
setError(null)
|
setError(null);
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<LoginForm
|
<LoginForm
|
||||||
username={username}
|
username={username}
|
||||||
password={password}
|
password={password}
|
||||||
error={error}
|
error={error}
|
||||||
pending={pending}
|
pending={pending}
|
||||||
onUsernameChange={setUsername}
|
onUsernameChange={setUsername}
|
||||||
onPasswordChange={setPassword}
|
onPasswordChange={setPassword}
|
||||||
onSubmit={handleLogin}
|
onSubmit={handleLogin}
|
||||||
onSignupClick={() => {
|
onSignupClick={() => {
|
||||||
setMode("register")
|
setMode("register");
|
||||||
setError(null)
|
setError(null);
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,69 +1,82 @@
|
|||||||
import {QuantityStepper} from "#/components/store/QuantityStepper";
|
import { Link } from "@tanstack/react-router";
|
||||||
import {Button} from "#/components/ui/button";
|
import { ShoppingCart } from "lucide-react";
|
||||||
import {Card, CardContent, CardFooter, CardHeader, CardTitle} from "#/components/ui/card";
|
import { useState } from "react";
|
||||||
import {StatusBadge} from "#/components/ui/status-badge";
|
import { toast } from "sonner";
|
||||||
import {formatCurrency} from "#/hooks/formatCurrency";
|
import { QuantityStepper } from "#/components/store/QuantityStepper";
|
||||||
import type {Product} from "#/types/product";
|
import { Button } from "#/components/ui/button";
|
||||||
import {Link} from "@tanstack/react-router";
|
import {
|
||||||
import {ShoppingCart} from "lucide-react";
|
Card,
|
||||||
import {useState} from "react";
|
CardContent,
|
||||||
import {toast} from "sonner";
|
CardFooter,
|
||||||
|
CardHeader,
|
||||||
|
CardTitle,
|
||||||
|
} from "#/components/ui/card";
|
||||||
|
import { StatusBadge } from "#/components/ui/status-badge";
|
||||||
|
import { formatCurrency } from "#/hooks/formatCurrency";
|
||||||
|
import type { Product } from "#/types/product";
|
||||||
|
|
||||||
type ProductCardProps = {
|
type ProductCardProps = {
|
||||||
product: Product;
|
product: Product;
|
||||||
onAddToCart?: (product: Product, quantity: number) => void;
|
onAddToCart?: (product: Product, quantity: number) => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
export function ProductCard({product, onAddToCart}: ProductCardProps) {
|
export function ProductCard({ product, onAddToCart }: ProductCardProps) {
|
||||||
const [quantity, setQuantity] = useState(1);
|
const [quantity, setQuantity] = useState(1);
|
||||||
const inStock = product.availableQuantity > 0;
|
const inStock = product.availableQuantity > 0;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card className="gap-4">
|
<Card className="gap-4">
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<div className="flex items-start justify-between gap-3">
|
<div className="flex items-start justify-between gap-3">
|
||||||
<div>
|
<div>
|
||||||
<CardTitle>{product.name}</CardTitle>
|
<CardTitle>{product.name}</CardTitle>
|
||||||
<p className="mt-1 text-xs text-muted-foreground">{product.sku}</p>
|
<p className="mt-1 text-xs text-muted-foreground">{product.sku}</p>
|
||||||
</div>
|
</div>
|
||||||
<StatusBadge status={inStock ? "IN_STOCK" : "OUT_OF_STOCK"} label={inStock ? "In stock" : "Out"}/>
|
<StatusBadge
|
||||||
</div>
|
status={inStock ? "IN_STOCK" : "OUT_OF_STOCK"}
|
||||||
</CardHeader>
|
label={inStock ? "In stock" : "Out"}
|
||||||
<CardContent className="space-y-4">
|
/>
|
||||||
<p className="text-2xl font-semibold">{formatCurrency(product.price, product.currency)}</p>
|
</div>
|
||||||
<p className="text-sm text-muted-foreground">{product.availableQuantity} available</p>
|
</CardHeader>
|
||||||
{onAddToCart ? (
|
<CardContent className="space-y-4">
|
||||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
<p className="text-2xl font-semibold">
|
||||||
<QuantityStepper
|
{formatCurrency(product.price, product.currency)}
|
||||||
value={Math.min(quantity, Math.max(product.availableQuantity, 1))}
|
</p>
|
||||||
min={1}
|
<p className="text-sm text-muted-foreground">
|
||||||
max={Math.max(product.availableQuantity, 1)}
|
{product.availableQuantity} available
|
||||||
disabled={!inStock}
|
</p>
|
||||||
onChange={setQuantity}
|
{onAddToCart ? (
|
||||||
/>
|
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||||
<Button
|
<QuantityStepper
|
||||||
type="button"
|
value={Math.min(quantity, Math.max(product.availableQuantity, 1))}
|
||||||
disabled={!inStock}
|
min={1}
|
||||||
onClick={() => {
|
max={Math.max(product.availableQuantity, 1)}
|
||||||
onAddToCart(product, quantity);
|
disabled={!inStock}
|
||||||
toast.success("Added to cart", {
|
onChange={setQuantity}
|
||||||
description: `${quantity} x ${product.name}`,
|
/>
|
||||||
});
|
<Button
|
||||||
}}
|
type="button"
|
||||||
>
|
disabled={!inStock}
|
||||||
<ShoppingCart/>
|
onClick={() => {
|
||||||
Add
|
onAddToCart(product, quantity);
|
||||||
</Button>
|
toast.success("Added to cart", {
|
||||||
</div>
|
description: `${quantity} x ${product.name}`,
|
||||||
) : null}
|
});
|
||||||
</CardContent>
|
}}
|
||||||
<CardFooter>
|
>
|
||||||
<Button asChild variant="outline" className="w-full">
|
<ShoppingCart />
|
||||||
<Link to="/products/$productId" params={{productId: product.id}}>
|
Add
|
||||||
View details
|
</Button>
|
||||||
</Link>
|
</div>
|
||||||
</Button>
|
) : null}
|
||||||
</CardFooter>
|
</CardContent>
|
||||||
</Card>
|
<CardFooter>
|
||||||
);
|
<Button asChild variant="outline" className="w-full">
|
||||||
|
<Link to="/products/$productId" params={{ productId: product.id }}>
|
||||||
|
View details
|
||||||
|
</Link>
|
||||||
|
</Button>
|
||||||
|
</CardFooter>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,31 +1,39 @@
|
|||||||
import {ProductCard} from "#/components/store/ProductCard";
|
import { ProductCard } from "#/components/store/ProductCard";
|
||||||
import {LoadingState} from "#/components/ui/LoadingState";
|
import { LoadingState } from "#/components/ui/LoadingState";
|
||||||
import type {Product} from "#/types/product";
|
import type { Product } from "#/types/product";
|
||||||
|
|
||||||
type ProductGridProps = {
|
type ProductGridProps = {
|
||||||
products: Product[];
|
products: Product[];
|
||||||
isLoading: boolean;
|
isLoading: boolean;
|
||||||
onAddToCart?: (product: Product, quantity: number) => void;
|
onAddToCart?: (product: Product, quantity: number) => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
export function ProductGrid({products, isLoading, onAddToCart}: ProductGridProps) {
|
export function ProductGrid({
|
||||||
if (isLoading) {
|
products,
|
||||||
return <LoadingState title="Loading products"/>;
|
isLoading,
|
||||||
}
|
onAddToCart,
|
||||||
|
}: ProductGridProps) {
|
||||||
|
if (isLoading) {
|
||||||
|
return <LoadingState title="Loading products" />;
|
||||||
|
}
|
||||||
|
|
||||||
if (products.length === 0) {
|
if (products.length === 0) {
|
||||||
return (
|
return (
|
||||||
<div className="rounded-lg border border-dashed border-border bg-card p-8 text-center text-sm text-muted-foreground">
|
<div className="rounded-lg border border-dashed border-border bg-card p-8 text-center text-sm text-muted-foreground">
|
||||||
No products available.
|
No products available.
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
|
<div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
|
||||||
{products.map((product) => (
|
{products.map((product) => (
|
||||||
<ProductCard key={product.id} product={product} onAddToCart={onAddToCart}/>
|
<ProductCard
|
||||||
))}
|
key={product.id}
|
||||||
</div>
|
product={product}
|
||||||
);
|
onAddToCart={onAddToCart}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,61 +1,61 @@
|
|||||||
import {Button} from "#/components/ui/button";
|
import { Button } from "#/components/ui/button";
|
||||||
import {Input} from "#/components/ui/input";
|
import { Input } from "#/components/ui/input";
|
||||||
|
|
||||||
type QuantityStepperProps = {
|
type QuantityStepperProps = {
|
||||||
value: number;
|
value: number;
|
||||||
min?: number;
|
min?: number;
|
||||||
max: number;
|
max: number;
|
||||||
disabled?: boolean;
|
disabled?: boolean;
|
||||||
onChange: (value: number) => void;
|
onChange: (value: number) => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
export function QuantityStepper({
|
export function QuantityStepper({
|
||||||
value,
|
value,
|
||||||
min = 1,
|
min = 1,
|
||||||
max,
|
max,
|
||||||
disabled = false,
|
disabled = false,
|
||||||
onChange,
|
onChange,
|
||||||
}: QuantityStepperProps) {
|
}: QuantityStepperProps) {
|
||||||
const normalizedMax = Math.max(max, min);
|
const normalizedMax = Math.max(max, min);
|
||||||
|
|
||||||
function setQuantity(nextValue: number) {
|
function setQuantity(nextValue: number) {
|
||||||
if (Number.isNaN(nextValue)) {
|
if (Number.isNaN(nextValue)) {
|
||||||
onChange(min);
|
onChange(min);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
onChange(Math.min(Math.max(nextValue, min), normalizedMax));
|
onChange(Math.min(Math.max(nextValue, min), normalizedMax));
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="inline-grid grid-cols-[2.25rem_4rem_2.25rem] overflow-hidden rounded-md border border-input">
|
<div className="inline-grid grid-cols-[2.25rem_4rem_2.25rem] overflow-hidden rounded-md border border-input">
|
||||||
<Button
|
<Button
|
||||||
type="button"
|
type="button"
|
||||||
variant="secondary"
|
variant="secondary"
|
||||||
disabled={disabled || value <= min}
|
disabled={disabled || value <= min}
|
||||||
onClick={() => setQuantity(value - 1)}
|
onClick={() => setQuantity(value - 1)}
|
||||||
className="h-9 rounded-none border-0 shadow-none"
|
className="h-9 rounded-none border-0 shadow-none"
|
||||||
>
|
>
|
||||||
-
|
-
|
||||||
</Button>
|
</Button>
|
||||||
<Input
|
<Input
|
||||||
type="number"
|
type="number"
|
||||||
min={min}
|
min={min}
|
||||||
max={normalizedMax}
|
max={normalizedMax}
|
||||||
value={value}
|
value={value}
|
||||||
disabled={disabled}
|
disabled={disabled}
|
||||||
onChange={(event) => setQuantity(Number(event.target.value))}
|
onChange={(event) => setQuantity(Number(event.target.value))}
|
||||||
className="h-9 rounded-none border-y-0 px-2 text-center shadow-none"
|
className="h-9 rounded-none border-y-0 px-2 text-center shadow-none"
|
||||||
/>
|
/>
|
||||||
<Button
|
<Button
|
||||||
type="button"
|
type="button"
|
||||||
variant="secondary"
|
variant="secondary"
|
||||||
disabled={disabled || value >= normalizedMax}
|
disabled={disabled || value >= normalizedMax}
|
||||||
onClick={() => setQuantity(value + 1)}
|
onClick={() => setQuantity(value + 1)}
|
||||||
className="h-9 rounded-none border-0 shadow-none"
|
className="h-9 rounded-none border-0 shadow-none"
|
||||||
>
|
>
|
||||||
+
|
+
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,54 +1,67 @@
|
|||||||
import {Button} from "#/components/ui/button";
|
import { Link } from "@tanstack/react-router";
|
||||||
import {ThemeToggle} from "#/components/theme-toggle";
|
import { LogOut, ShoppingCart, User } from "lucide-react";
|
||||||
import {useCart} from "#/hooks/useCart";
|
import { ThemeToggle } from "#/components/theme-toggle";
|
||||||
import type {AuthUser} from "#/types/auth";
|
import { Button } from "#/components/ui/button";
|
||||||
import {Link} from "@tanstack/react-router";
|
import { useCart } from "#/hooks/useCart";
|
||||||
import {LogOut, ShoppingCart, User} from "lucide-react";
|
import type { AuthUser } from "#/types/auth";
|
||||||
|
|
||||||
type SiteHeaderProps = {
|
type SiteHeaderProps = {
|
||||||
user?: AuthUser | null;
|
user?: AuthUser | null;
|
||||||
onLogin?: () => void;
|
onLogin?: () => void;
|
||||||
onRegister?: () => void;
|
onRegister?: () => void;
|
||||||
onLogout?: () => void;
|
onLogout?: () => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
export function SiteHeader({user, onLogin, onRegister, onLogout}: SiteHeaderProps) {
|
export function SiteHeader({
|
||||||
const cart = useCart();
|
user,
|
||||||
|
onLogin,
|
||||||
|
onRegister,
|
||||||
|
onLogout,
|
||||||
|
}: SiteHeaderProps) {
|
||||||
|
const cart = useCart();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<header className="sticky top-0 z-30 border-b border-border bg-background/95 backdrop-blur">
|
<header className="sticky top-0 z-30 border-b border-border bg-background/95 backdrop-blur">
|
||||||
<div className="mx-auto flex max-w-7xl flex-col gap-4 px-4 py-4 md:flex-row md:items-center md:justify-between">
|
<div className="mx-auto flex max-w-7xl flex-col gap-4 px-4 py-4 md:flex-row md:items-center md:justify-between">
|
||||||
<div>
|
<div>
|
||||||
<Link to="/" className="text-2xl font-bold text-foreground">Cymelle</Link>
|
<Link to="/" className="text-2xl font-bold text-foreground">
|
||||||
<p className="text-sm text-muted-foreground">Commerce, delivery, and rides</p>
|
Cymelle
|
||||||
</div>
|
</Link>
|
||||||
<div className="flex flex-wrap items-center gap-2">
|
<p className="text-sm text-muted-foreground">
|
||||||
<ThemeToggle/>
|
Commerce, delivery, and rides
|
||||||
<Button asChild variant="outline">
|
</p>
|
||||||
<Link to="/cart">
|
</div>
|
||||||
<ShoppingCart/>
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
Cart ({cart.itemCount})
|
<ThemeToggle />
|
||||||
</Link>
|
<Button asChild variant="outline">
|
||||||
</Button>
|
<Link to="/cart">
|
||||||
{user ? (
|
<ShoppingCart />
|
||||||
<>
|
Cart ({cart.itemCount})
|
||||||
<div className="inline-flex items-center gap-2 rounded-md border border-border bg-card px-3 py-2 text-sm">
|
</Link>
|
||||||
<User className="size-4"/>
|
</Button>
|
||||||
<span>{user.displayName}</span>
|
{user ? (
|
||||||
</div>
|
<>
|
||||||
<Button type="button" variant="outline" onClick={onLogout}>
|
<div className="inline-flex items-center gap-2 rounded-md border border-border bg-card px-3 py-2 text-sm">
|
||||||
<LogOut/>
|
<User className="size-4" />
|
||||||
Sign out
|
<span>{user.displayName}</span>
|
||||||
</Button>
|
</div>
|
||||||
</>
|
<Button type="button" variant="outline" onClick={onLogout}>
|
||||||
) : (
|
<LogOut />
|
||||||
<>
|
Sign out
|
||||||
<Button type="button" onClick={onLogin}>Sign in</Button>
|
</Button>
|
||||||
<Button type="button" variant="outline" onClick={onRegister}>Create account</Button>
|
</>
|
||||||
</>
|
) : (
|
||||||
)}
|
<>
|
||||||
</div>
|
<Button type="button" onClick={onLogin}>
|
||||||
</div>
|
Sign in
|
||||||
</header>
|
</Button>
|
||||||
);
|
<Button type="button" variant="outline" onClick={onRegister}>
|
||||||
|
Create account
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,60 +1,68 @@
|
|||||||
import {AuthDialog} from "#/components/store/AuthDialog";
|
import { useNavigate } from "@tanstack/react-router";
|
||||||
import {ProductGrid} from "#/components/store/ProductGrid";
|
import { useState } from "react";
|
||||||
import {SiteHeader} from "#/components/store/SiteHeader";
|
import { AuthDialog } from "#/components/store/AuthDialog";
|
||||||
import {useAuth} from "#/hooks/useAuth";
|
import { ProductGrid } from "#/components/store/ProductGrid";
|
||||||
import {useCart} from "#/hooks/useCart";
|
import { SiteHeader } from "#/components/store/SiteHeader";
|
||||||
import {useProducts} from "#/hooks/useProducts";
|
import { useAuth } from "#/hooks/useAuth";
|
||||||
import {navigateToRoleHome} from "#/lib/auth-navigation";
|
import { useCart } from "#/hooks/useCart";
|
||||||
import {useNavigate} from "@tanstack/react-router";
|
import { useProducts } from "#/hooks/useProducts";
|
||||||
import {useState} from "react";
|
import { navigateToRoleHome } from "#/lib/auth-navigation";
|
||||||
|
|
||||||
export function StoreHome() {
|
export function StoreHome() {
|
||||||
const {user, login, register, logout} = useAuth();
|
const { user, login, register, logout } = useAuth();
|
||||||
const productsQuery = useProducts();
|
const productsQuery = useProducts();
|
||||||
const cart = useCart();
|
const cart = useCart();
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const [authMode, setAuthMode] = useState<"login" | "register" | null>(null);
|
const [authMode, setAuthMode] = useState<"login" | "register" | null>(null);
|
||||||
|
|
||||||
async function handleLogin(request: {username: string; password: string}) {
|
async function handleLogin(request: { username: string; password: string }) {
|
||||||
const user = await login(request);
|
const user = await login(request);
|
||||||
setAuthMode(null);
|
setAuthMode(null);
|
||||||
await navigateToRoleHome(navigate, user);
|
await navigateToRoleHome(navigate, user);
|
||||||
return user;
|
return user;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function handleRegister(request: {username: string; password: string; displayName: string}) {
|
async function handleRegister(request: {
|
||||||
const user = await register(request);
|
username: string;
|
||||||
setAuthMode(null);
|
password: string;
|
||||||
await navigateToRoleHome(navigate, user);
|
displayName: string;
|
||||||
return user;
|
}) {
|
||||||
}
|
const user = await register(request);
|
||||||
|
setAuthMode(null);
|
||||||
|
await navigateToRoleHome(navigate, user);
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="min-h-screen bg-background">
|
<main className="min-h-screen bg-background">
|
||||||
<SiteHeader
|
<SiteHeader
|
||||||
user={user}
|
user={user}
|
||||||
onLogin={() => setAuthMode("login")}
|
onLogin={() => setAuthMode("login")}
|
||||||
onRegister={() => setAuthMode("register")}
|
onRegister={() => setAuthMode("register")}
|
||||||
onLogout={logout}
|
onLogout={logout}
|
||||||
/>
|
/>
|
||||||
<section className="mx-auto max-w-7xl px-4 py-8">
|
<section className="mx-auto max-w-7xl px-4 py-8">
|
||||||
<div className="mb-6 max-w-2xl">
|
<div className="mb-6 max-w-2xl">
|
||||||
<p className="text-sm font-medium uppercase text-muted-foreground">Store</p>
|
<p className="text-sm font-medium uppercase text-muted-foreground">
|
||||||
<h1 className="mt-2 text-4xl font-bold tracking-normal text-foreground">Shop Cymelle products</h1>
|
Store
|
||||||
</div>
|
</p>
|
||||||
<ProductGrid
|
<h1 className="mt-2 text-4xl font-bold tracking-normal text-foreground">
|
||||||
products={productsQuery.data ?? []}
|
Shop Cymelle products
|
||||||
isLoading={productsQuery.isLoading}
|
</h1>
|
||||||
onAddToCart={cart.addItem}
|
</div>
|
||||||
/>
|
<ProductGrid
|
||||||
</section>
|
products={productsQuery.data ?? []}
|
||||||
<AuthDialog
|
isLoading={productsQuery.isLoading}
|
||||||
open={authMode !== null}
|
onAddToCart={cart.addItem}
|
||||||
initialMode={authMode ?? "login"}
|
/>
|
||||||
onOpenChange={(open) => !open && setAuthMode(null)}
|
</section>
|
||||||
onLogin={handleLogin}
|
<AuthDialog
|
||||||
onRegister={handleRegister}
|
open={authMode !== null}
|
||||||
/>
|
initialMode={authMode ?? "login"}
|
||||||
</main>
|
onOpenChange={(open) => !open && setAuthMode(null)}
|
||||||
);
|
onLogin={handleLogin}
|
||||||
|
onRegister={handleRegister}
|
||||||
|
/>
|
||||||
|
</main>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,81 +1,81 @@
|
|||||||
"use client"
|
"use client";
|
||||||
|
|
||||||
import * as React from "react"
|
import { ChevronsUpDown } from "lucide-react";
|
||||||
import { ChevronsUpDown } from "lucide-react"
|
import * as React from "react";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
DropdownMenu,
|
DropdownMenu,
|
||||||
DropdownMenuContent,
|
DropdownMenuContent,
|
||||||
DropdownMenuItem,
|
DropdownMenuItem,
|
||||||
DropdownMenuLabel,
|
DropdownMenuLabel,
|
||||||
DropdownMenuTrigger,
|
DropdownMenuTrigger,
|
||||||
} from "#/components/ui/dropdown-menu.tsx"
|
} from "#/components/ui/dropdown-menu.tsx";
|
||||||
import {
|
import {
|
||||||
SidebarMenu,
|
SidebarMenu,
|
||||||
SidebarMenuButton,
|
SidebarMenuButton,
|
||||||
SidebarMenuItem,
|
SidebarMenuItem,
|
||||||
useSidebar,
|
useSidebar,
|
||||||
} from "#/components/ui/sidebar.tsx"
|
} from "#/components/ui/sidebar.tsx";
|
||||||
|
|
||||||
export function TeamSwitcher({
|
export function TeamSwitcher({
|
||||||
teams,
|
teams,
|
||||||
}: {
|
}: {
|
||||||
teams: {
|
teams: {
|
||||||
name: string
|
name: string;
|
||||||
logo: React.ElementType
|
logo: React.ElementType;
|
||||||
plan: string
|
plan: string;
|
||||||
}[]
|
}[];
|
||||||
}) {
|
}) {
|
||||||
const { isMobile } = useSidebar()
|
const { isMobile } = useSidebar();
|
||||||
const [activeTeam, setActiveTeam] = React.useState(teams[0])
|
const [activeTeam, setActiveTeam] = React.useState(teams[0]);
|
||||||
|
|
||||||
if (!activeTeam) {
|
if (!activeTeam) {
|
||||||
return null
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<SidebarMenu>
|
<SidebarMenu>
|
||||||
<SidebarMenuItem>
|
<SidebarMenuItem>
|
||||||
<DropdownMenu>
|
<DropdownMenu>
|
||||||
<DropdownMenuTrigger asChild>
|
<DropdownMenuTrigger asChild>
|
||||||
<SidebarMenuButton
|
<SidebarMenuButton
|
||||||
size="lg"
|
size="lg"
|
||||||
className="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground"
|
className="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground"
|
||||||
>
|
>
|
||||||
<div className="flex aspect-square size-8 items-center justify-center rounded-lg bg-sidebar-primary text-sidebar-primary-foreground">
|
<div className="flex aspect-square size-8 items-center justify-center rounded-lg bg-sidebar-primary text-sidebar-primary-foreground">
|
||||||
<activeTeam.logo className="size-4" />
|
<activeTeam.logo className="size-4" />
|
||||||
</div>
|
</div>
|
||||||
<div className="grid flex-1 text-left text-sm leading-tight">
|
<div className="grid flex-1 text-left text-sm leading-tight">
|
||||||
<span className="truncate font-medium">{activeTeam.name}</span>
|
<span className="truncate font-medium">{activeTeam.name}</span>
|
||||||
<span className="truncate text-xs">{activeTeam.plan}</span>
|
<span className="truncate text-xs">{activeTeam.plan}</span>
|
||||||
</div>
|
</div>
|
||||||
<ChevronsUpDown className="ml-auto" />
|
<ChevronsUpDown className="ml-auto" />
|
||||||
</SidebarMenuButton>
|
</SidebarMenuButton>
|
||||||
</DropdownMenuTrigger>
|
</DropdownMenuTrigger>
|
||||||
<DropdownMenuContent
|
<DropdownMenuContent
|
||||||
className="w-(--radix-dropdown-menu-trigger-width) min-w-56 rounded-lg"
|
className="w-(--radix-dropdown-menu-trigger-width) min-w-56 rounded-lg"
|
||||||
align="start"
|
align="start"
|
||||||
side={isMobile ? "bottom" : "right"}
|
side={isMobile ? "bottom" : "right"}
|
||||||
sideOffset={4}
|
sideOffset={4}
|
||||||
>
|
>
|
||||||
<DropdownMenuLabel className="text-xs text-muted-foreground">
|
<DropdownMenuLabel className="text-xs text-muted-foreground">
|
||||||
Workspace
|
Workspace
|
||||||
</DropdownMenuLabel>
|
</DropdownMenuLabel>
|
||||||
{teams.map((team, index) => (
|
{teams.map((team) => (
|
||||||
<DropdownMenuItem
|
<DropdownMenuItem
|
||||||
key={team.name}
|
key={team.name}
|
||||||
onClick={() => setActiveTeam(team)}
|
onClick={() => setActiveTeam(team)}
|
||||||
className="gap-2 p-2"
|
className="gap-2 p-2"
|
||||||
>
|
>
|
||||||
<div className="flex size-6 items-center justify-center rounded-md border">
|
<div className="flex size-6 items-center justify-center rounded-md border">
|
||||||
<team.logo className="size-3.5 shrink-0" />
|
<team.logo className="size-3.5 shrink-0" />
|
||||||
</div>
|
</div>
|
||||||
{team.name}
|
{team.name}
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
))}
|
))}
|
||||||
</DropdownMenuContent>
|
</DropdownMenuContent>
|
||||||
</DropdownMenu>
|
</DropdownMenu>
|
||||||
</SidebarMenuItem>
|
</SidebarMenuItem>
|
||||||
</SidebarMenu>
|
</SidebarMenu>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,14 @@
|
|||||||
import {ThemeProvider as NextThemesProvider} from "next-themes";
|
import { ThemeProvider as NextThemesProvider } from "next-themes";
|
||||||
|
|
||||||
export function ThemeProvider({children}: {children: React.ReactNode}) {
|
export function ThemeProvider({ children }: { children: React.ReactNode }) {
|
||||||
return (
|
return (
|
||||||
<NextThemesProvider
|
<NextThemesProvider
|
||||||
attribute="class"
|
attribute="class"
|
||||||
defaultTheme="system"
|
defaultTheme="system"
|
||||||
enableSystem
|
enableSystem
|
||||||
disableTransitionOnChange
|
disableTransitionOnChange
|
||||||
>
|
>
|
||||||
{children}
|
{children}
|
||||||
</NextThemesProvider>
|
</NextThemesProvider>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,38 +1,38 @@
|
|||||||
import {Button} from "#/components/ui/button";
|
import { Monitor, Moon, Sun } from "lucide-react";
|
||||||
|
import { useTheme } from "next-themes";
|
||||||
|
import { Button } from "#/components/ui/button";
|
||||||
import {
|
import {
|
||||||
DropdownMenu,
|
DropdownMenu,
|
||||||
DropdownMenuContent,
|
DropdownMenuContent,
|
||||||
DropdownMenuItem,
|
DropdownMenuItem,
|
||||||
DropdownMenuTrigger,
|
DropdownMenuTrigger,
|
||||||
} from "#/components/ui/dropdown-menu";
|
} from "#/components/ui/dropdown-menu";
|
||||||
import {Monitor, Moon, Sun} from "lucide-react";
|
|
||||||
import {useTheme} from "next-themes";
|
|
||||||
|
|
||||||
export function ThemeToggle() {
|
export function ThemeToggle() {
|
||||||
const {setTheme} = useTheme();
|
const { setTheme } = useTheme();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<DropdownMenu>
|
<DropdownMenu>
|
||||||
<DropdownMenuTrigger asChild>
|
<DropdownMenuTrigger asChild>
|
||||||
<Button variant="outline" size="icon" aria-label="Toggle theme">
|
<Button variant="outline" size="icon" aria-label="Toggle theme">
|
||||||
<Sun className="size-4 scale-100 rotate-0 transition-all dark:scale-0 dark:-rotate-90"/>
|
<Sun className="size-4 scale-100 rotate-0 transition-all dark:scale-0 dark:-rotate-90" />
|
||||||
<Moon className="absolute size-4 scale-0 rotate-90 transition-all dark:scale-100 dark:rotate-0"/>
|
<Moon className="absolute size-4 scale-0 rotate-90 transition-all dark:scale-100 dark:rotate-0" />
|
||||||
</Button>
|
</Button>
|
||||||
</DropdownMenuTrigger>
|
</DropdownMenuTrigger>
|
||||||
<DropdownMenuContent align="end">
|
<DropdownMenuContent align="end">
|
||||||
<DropdownMenuItem onClick={() => setTheme("light")}>
|
<DropdownMenuItem onClick={() => setTheme("light")}>
|
||||||
<Sun/>
|
<Sun />
|
||||||
Light
|
Light
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
<DropdownMenuItem onClick={() => setTheme("dark")}>
|
<DropdownMenuItem onClick={() => setTheme("dark")}>
|
||||||
<Moon/>
|
<Moon />
|
||||||
Dark
|
Dark
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
<DropdownMenuItem onClick={() => setTheme("system")}>
|
<DropdownMenuItem onClick={() => setTheme("system")}>
|
||||||
<Monitor/>
|
<Monitor />
|
||||||
System
|
System
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
</DropdownMenuContent>
|
</DropdownMenuContent>
|
||||||
</DropdownMenu>
|
</DropdownMenu>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
type EmptyStateProps = {
|
type EmptyStateProps = {
|
||||||
title: string;
|
title: string;
|
||||||
description: string;
|
description: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export function EmptyState({title, description}: EmptyStateProps) {
|
export function EmptyState({ title, description }: EmptyStateProps) {
|
||||||
return (
|
return (
|
||||||
<div className="rounded-xl border border-dashed border-slate-300 bg-white p-8 text-center">
|
<div className="rounded-xl border border-dashed border-slate-300 bg-white p-8 text-center">
|
||||||
<h3 className="font-semibold text-slate-900">{title}</h3>
|
<h3 className="font-semibold text-slate-900">{title}</h3>
|
||||||
<p className="mt-1 text-sm text-slate-500">{description}</p>
|
<p className="mt-1 text-sm text-slate-500">{description}</p>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1,28 +1,28 @@
|
|||||||
type ErrorStateProps = {
|
type ErrorStateProps = {
|
||||||
title?: string;
|
title?: string;
|
||||||
message: string;
|
message: string;
|
||||||
onRetry?: () => void;
|
onRetry?: () => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
export function ErrorState({
|
export function ErrorState({
|
||||||
title = "Something went wrong",
|
title = "Something went wrong",
|
||||||
message,
|
message,
|
||||||
onRetry,
|
onRetry,
|
||||||
}: ErrorStateProps) {
|
}: ErrorStateProps) {
|
||||||
return (
|
return (
|
||||||
<div className="rounded-xl border border-red-200 bg-red-50 p-8 text-center">
|
<div className="rounded-xl border border-red-200 bg-red-50 p-8 text-center">
|
||||||
<h3 className="font-semibold text-red-900">{title}</h3>
|
<h3 className="font-semibold text-red-900">{title}</h3>
|
||||||
<p className="mt-1 text-sm text-red-700">{message}</p>
|
<p className="mt-1 text-sm text-red-700">{message}</p>
|
||||||
|
|
||||||
{onRetry ? (
|
{onRetry ? (
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={onRetry}
|
onClick={onRetry}
|
||||||
className="mt-4 rounded-lg bg-red-700 px-4 py-2 text-sm font-medium text-white hover:bg-red-800"
|
className="mt-4 rounded-lg bg-red-700 px-4 py-2 text-sm font-medium text-white hover:bg-red-800"
|
||||||
>
|
>
|
||||||
Try again
|
Try again
|
||||||
</button>
|
</button>
|
||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1,21 +1,22 @@
|
|||||||
type LoadingStateProps = {
|
type LoadingStateProps = {
|
||||||
title?: string;
|
title?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export function LoadingState({
|
export function LoadingState({ title = "Loading" }: LoadingStateProps) {
|
||||||
title = "Loading",
|
return (
|
||||||
}: LoadingStateProps) {
|
<output
|
||||||
return (
|
className="rounded-lg border bg-card p-6 text-card-foreground shadow-sm"
|
||||||
<div className="rounded-lg border bg-card p-6 text-card-foreground shadow-sm" aria-label={title}>
|
aria-label={title}
|
||||||
<div className="space-y-3">
|
>
|
||||||
<div className="h-4 w-36 animate-pulse rounded-md bg-muted"/>
|
<div className="space-y-3">
|
||||||
<div className="h-8 w-full animate-pulse rounded-md bg-muted"/>
|
<div className="h-4 w-36 animate-pulse rounded-md bg-muted" />
|
||||||
<div className="grid gap-3 md:grid-cols-3">
|
<div className="h-8 w-full animate-pulse rounded-md bg-muted" />
|
||||||
<div className="h-16 animate-pulse rounded-md bg-muted"/>
|
<div className="grid gap-3 md:grid-cols-3">
|
||||||
<div className="h-16 animate-pulse rounded-md bg-muted"/>
|
<div className="h-16 animate-pulse rounded-md bg-muted" />
|
||||||
<div className="h-16 animate-pulse rounded-md bg-muted"/>
|
<div className="h-16 animate-pulse rounded-md bg-muted" />
|
||||||
</div>
|
<div className="h-16 animate-pulse rounded-md bg-muted" />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
</output>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,109 +1,109 @@
|
|||||||
"use client"
|
"use client";
|
||||||
|
|
||||||
import * as React from "react"
|
import { Avatar as AvatarPrimitive } from "radix-ui";
|
||||||
import { Avatar as AvatarPrimitive } from "radix-ui"
|
import type * as React from "react";
|
||||||
|
|
||||||
import { cn } from "#/lib/utils.ts"
|
import { cn } from "#/lib/utils.ts";
|
||||||
|
|
||||||
function Avatar({
|
function Avatar({
|
||||||
className,
|
className,
|
||||||
size = "default",
|
size = "default",
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof AvatarPrimitive.Root> & {
|
}: React.ComponentProps<typeof AvatarPrimitive.Root> & {
|
||||||
size?: "default" | "sm" | "lg"
|
size?: "default" | "sm" | "lg";
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<AvatarPrimitive.Root
|
<AvatarPrimitive.Root
|
||||||
data-slot="avatar"
|
data-slot="avatar"
|
||||||
data-size={size}
|
data-size={size}
|
||||||
className={cn(
|
className={cn(
|
||||||
"group/avatar relative flex size-8 shrink-0 overflow-hidden rounded-full select-none data-[size=lg]:size-10 data-[size=sm]:size-6",
|
"group/avatar relative flex size-8 shrink-0 overflow-hidden rounded-full select-none data-[size=lg]:size-10 data-[size=sm]:size-6",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function AvatarImage({
|
function AvatarImage({
|
||||||
className,
|
className,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof AvatarPrimitive.Image>) {
|
}: React.ComponentProps<typeof AvatarPrimitive.Image>) {
|
||||||
return (
|
return (
|
||||||
<AvatarPrimitive.Image
|
<AvatarPrimitive.Image
|
||||||
data-slot="avatar-image"
|
data-slot="avatar-image"
|
||||||
className={cn("aspect-square size-full", className)}
|
className={cn("aspect-square size-full", className)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function AvatarFallback({
|
function AvatarFallback({
|
||||||
className,
|
className,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof AvatarPrimitive.Fallback>) {
|
}: React.ComponentProps<typeof AvatarPrimitive.Fallback>) {
|
||||||
return (
|
return (
|
||||||
<AvatarPrimitive.Fallback
|
<AvatarPrimitive.Fallback
|
||||||
data-slot="avatar-fallback"
|
data-slot="avatar-fallback"
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex size-full items-center justify-center rounded-full bg-muted text-sm text-muted-foreground group-data-[size=sm]/avatar:text-xs",
|
"flex size-full items-center justify-center rounded-full bg-muted text-sm text-muted-foreground group-data-[size=sm]/avatar:text-xs",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function AvatarBadge({ className, ...props }: React.ComponentProps<"span">) {
|
function AvatarBadge({ className, ...props }: React.ComponentProps<"span">) {
|
||||||
return (
|
return (
|
||||||
<span
|
<span
|
||||||
data-slot="avatar-badge"
|
data-slot="avatar-badge"
|
||||||
className={cn(
|
className={cn(
|
||||||
"absolute right-0 bottom-0 z-10 inline-flex items-center justify-center rounded-full bg-primary text-primary-foreground ring-2 ring-background select-none",
|
"absolute right-0 bottom-0 z-10 inline-flex items-center justify-center rounded-full bg-primary text-primary-foreground ring-2 ring-background select-none",
|
||||||
"group-data-[size=sm]/avatar:size-2 group-data-[size=sm]/avatar:[&>svg]:hidden",
|
"group-data-[size=sm]/avatar:size-2 group-data-[size=sm]/avatar:[&>svg]:hidden",
|
||||||
"group-data-[size=default]/avatar:size-2.5 group-data-[size=default]/avatar:[&>svg]:size-2",
|
"group-data-[size=default]/avatar:size-2.5 group-data-[size=default]/avatar:[&>svg]:size-2",
|
||||||
"group-data-[size=lg]/avatar:size-3 group-data-[size=lg]/avatar:[&>svg]:size-2",
|
"group-data-[size=lg]/avatar:size-3 group-data-[size=lg]/avatar:[&>svg]:size-2",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function AvatarGroup({ className, ...props }: React.ComponentProps<"div">) {
|
function AvatarGroup({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
data-slot="avatar-group"
|
data-slot="avatar-group"
|
||||||
className={cn(
|
className={cn(
|
||||||
"group/avatar-group flex -space-x-2 *:data-[slot=avatar]:ring-2 *:data-[slot=avatar]:ring-background",
|
"group/avatar-group flex -space-x-2 *:data-[slot=avatar]:ring-2 *:data-[slot=avatar]:ring-background",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function AvatarGroupCount({
|
function AvatarGroupCount({
|
||||||
className,
|
className,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<"div">) {
|
}: React.ComponentProps<"div">) {
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
data-slot="avatar-group-count"
|
data-slot="avatar-group-count"
|
||||||
className={cn(
|
className={cn(
|
||||||
"relative flex size-8 shrink-0 items-center justify-center rounded-full bg-muted text-sm text-muted-foreground ring-2 ring-background group-has-data-[size=lg]/avatar-group:size-10 group-has-data-[size=sm]/avatar-group:size-6 [&>svg]:size-4 group-has-data-[size=lg]/avatar-group:[&>svg]:size-5 group-has-data-[size=sm]/avatar-group:[&>svg]:size-3",
|
"relative flex size-8 shrink-0 items-center justify-center rounded-full bg-muted text-sm text-muted-foreground ring-2 ring-background group-has-data-[size=lg]/avatar-group:size-10 group-has-data-[size=sm]/avatar-group:size-6 [&>svg]:size-4 group-has-data-[size=lg]/avatar-group:[&>svg]:size-5 group-has-data-[size=sm]/avatar-group:[&>svg]:size-3",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export {
|
export {
|
||||||
Avatar,
|
Avatar,
|
||||||
AvatarImage,
|
AvatarImage,
|
||||||
AvatarFallback,
|
AvatarFallback,
|
||||||
AvatarBadge,
|
AvatarBadge,
|
||||||
AvatarGroup,
|
AvatarGroup,
|
||||||
AvatarGroupCount,
|
AvatarGroupCount,
|
||||||
}
|
};
|
||||||
|
|||||||
@@ -1,48 +1,48 @@
|
|||||||
import * as React from "react"
|
import { cva, type VariantProps } from "class-variance-authority";
|
||||||
import { cva, type VariantProps } from "class-variance-authority"
|
import { Slot } from "radix-ui";
|
||||||
import { Slot } from "radix-ui"
|
import type * as React from "react";
|
||||||
|
|
||||||
import { cn } from "#/lib/utils.ts"
|
import { cn } from "#/lib/utils.ts";
|
||||||
|
|
||||||
const badgeVariants = cva(
|
const badgeVariants = cva(
|
||||||
"inline-flex w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-full border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3",
|
"inline-flex w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-full border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3",
|
||||||
{
|
{
|
||||||
variants: {
|
variants: {
|
||||||
variant: {
|
variant: {
|
||||||
default: "bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
|
default: "bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
|
||||||
secondary:
|
secondary:
|
||||||
"bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
|
"bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
|
||||||
destructive:
|
destructive:
|
||||||
"bg-destructive text-white focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40 [a&]:hover:bg-destructive/90",
|
"bg-destructive text-white focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40 [a&]:hover:bg-destructive/90",
|
||||||
outline:
|
outline:
|
||||||
"border-border text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
|
"border-border text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
|
||||||
ghost: "[a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
|
ghost: "[a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
|
||||||
link: "text-primary underline-offset-4 [a&]:hover:underline",
|
link: "text-primary underline-offset-4 [a&]:hover:underline",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
defaultVariants: {
|
defaultVariants: {
|
||||||
variant: "default",
|
variant: "default",
|
||||||
},
|
},
|
||||||
}
|
},
|
||||||
)
|
);
|
||||||
|
|
||||||
function Badge({
|
function Badge({
|
||||||
className,
|
className,
|
||||||
variant = "default",
|
variant = "default",
|
||||||
asChild = false,
|
asChild = false,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<"span"> &
|
}: React.ComponentProps<"span"> &
|
||||||
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
|
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
|
||||||
const Comp = asChild ? Slot.Root : "span"
|
const Comp = asChild ? Slot.Root : "span";
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Comp
|
<Comp
|
||||||
data-slot="badge"
|
data-slot="badge"
|
||||||
data-variant={variant}
|
data-variant={variant}
|
||||||
className={cn(badgeVariants({ variant }), className)}
|
className={cn(badgeVariants({ variant }), className)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export { Badge, badgeVariants }
|
export { Badge, badgeVariants };
|
||||||
|
|||||||
@@ -1,109 +1,107 @@
|
|||||||
import * as React from "react"
|
import { ChevronRight, MoreHorizontal } from "lucide-react";
|
||||||
import { ChevronRight, MoreHorizontal } from "lucide-react"
|
import { Slot } from "radix-ui";
|
||||||
import { Slot } from "radix-ui"
|
import type * as React from "react";
|
||||||
|
|
||||||
import { cn } from "#/lib/utils.ts"
|
import { cn } from "#/lib/utils.ts";
|
||||||
|
|
||||||
function Breadcrumb({ ...props }: React.ComponentProps<"nav">) {
|
function Breadcrumb({ ...props }: React.ComponentProps<"nav">) {
|
||||||
return <nav aria-label="breadcrumb" data-slot="breadcrumb" {...props} />
|
return <nav aria-label="breadcrumb" data-slot="breadcrumb" {...props} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
function BreadcrumbList({ className, ...props }: React.ComponentProps<"ol">) {
|
function BreadcrumbList({ className, ...props }: React.ComponentProps<"ol">) {
|
||||||
return (
|
return (
|
||||||
<ol
|
<ol
|
||||||
data-slot="breadcrumb-list"
|
data-slot="breadcrumb-list"
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex flex-wrap items-center gap-1.5 text-sm break-words text-muted-foreground sm:gap-2.5",
|
"flex flex-wrap items-center gap-1.5 text-sm break-words text-muted-foreground sm:gap-2.5",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function BreadcrumbItem({ className, ...props }: React.ComponentProps<"li">) {
|
function BreadcrumbItem({ className, ...props }: React.ComponentProps<"li">) {
|
||||||
return (
|
return (
|
||||||
<li
|
<li
|
||||||
data-slot="breadcrumb-item"
|
data-slot="breadcrumb-item"
|
||||||
className={cn("inline-flex items-center gap-1.5", className)}
|
className={cn("inline-flex items-center gap-1.5", className)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function BreadcrumbLink({
|
function BreadcrumbLink({
|
||||||
asChild,
|
asChild,
|
||||||
className,
|
className,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<"a"> & {
|
}: React.ComponentProps<"a"> & {
|
||||||
asChild?: boolean
|
asChild?: boolean;
|
||||||
}) {
|
}) {
|
||||||
const Comp = asChild ? Slot.Root : "a"
|
const Comp = asChild ? Slot.Root : "a";
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Comp
|
<Comp
|
||||||
data-slot="breadcrumb-link"
|
data-slot="breadcrumb-link"
|
||||||
className={cn("transition-colors hover:text-foreground", className)}
|
className={cn("transition-colors hover:text-foreground", className)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function BreadcrumbPage({ className, ...props }: React.ComponentProps<"span">) {
|
function BreadcrumbPage({ className, ...props }: React.ComponentProps<"span">) {
|
||||||
return (
|
return (
|
||||||
<span
|
<span
|
||||||
data-slot="breadcrumb-page"
|
data-slot="breadcrumb-page"
|
||||||
role="link"
|
aria-current="page"
|
||||||
aria-disabled="true"
|
className={cn("font-normal text-foreground", className)}
|
||||||
aria-current="page"
|
{...props}
|
||||||
className={cn("font-normal text-foreground", className)}
|
/>
|
||||||
{...props}
|
);
|
||||||
/>
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function BreadcrumbSeparator({
|
function BreadcrumbSeparator({
|
||||||
children,
|
children,
|
||||||
className,
|
className,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<"li">) {
|
}: React.ComponentProps<"li">) {
|
||||||
return (
|
return (
|
||||||
<li
|
<li
|
||||||
data-slot="breadcrumb-separator"
|
data-slot="breadcrumb-separator"
|
||||||
role="presentation"
|
role="presentation"
|
||||||
aria-hidden="true"
|
aria-hidden="true"
|
||||||
className={cn("[&>svg]:size-3.5", className)}
|
className={cn("[&>svg]:size-3.5", className)}
|
||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
{children ?? <ChevronRight />}
|
{children ?? <ChevronRight />}
|
||||||
</li>
|
</li>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function BreadcrumbEllipsis({
|
function BreadcrumbEllipsis({
|
||||||
className,
|
className,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<"span">) {
|
}: React.ComponentProps<"span">) {
|
||||||
return (
|
return (
|
||||||
<span
|
<span
|
||||||
data-slot="breadcrumb-ellipsis"
|
data-slot="breadcrumb-ellipsis"
|
||||||
role="presentation"
|
role="presentation"
|
||||||
aria-hidden="true"
|
aria-hidden="true"
|
||||||
className={cn("flex size-9 items-center justify-center", className)}
|
className={cn("flex size-9 items-center justify-center", className)}
|
||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
<MoreHorizontal className="size-4" />
|
<MoreHorizontal className="size-4" />
|
||||||
<span className="sr-only">More</span>
|
<span className="sr-only">More</span>
|
||||||
</span>
|
</span>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export {
|
export {
|
||||||
Breadcrumb,
|
Breadcrumb,
|
||||||
BreadcrumbList,
|
BreadcrumbList,
|
||||||
BreadcrumbItem,
|
BreadcrumbItem,
|
||||||
BreadcrumbLink,
|
BreadcrumbLink,
|
||||||
BreadcrumbPage,
|
BreadcrumbPage,
|
||||||
BreadcrumbSeparator,
|
BreadcrumbSeparator,
|
||||||
BreadcrumbEllipsis,
|
BreadcrumbEllipsis,
|
||||||
}
|
};
|
||||||
|
|||||||
@@ -1,64 +1,64 @@
|
|||||||
import * as React from "react"
|
import { cva, type VariantProps } from "class-variance-authority";
|
||||||
import { cva, type VariantProps } from "class-variance-authority"
|
import { Slot } from "radix-ui";
|
||||||
import { Slot } from "radix-ui"
|
import type * as React from "react";
|
||||||
|
|
||||||
import { cn } from "#/lib/utils.ts"
|
import { cn } from "#/lib/utils.ts";
|
||||||
|
|
||||||
const buttonVariants = cva(
|
const buttonVariants = cva(
|
||||||
"inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-all outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
"inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-all outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
{
|
{
|
||||||
variants: {
|
variants: {
|
||||||
variant: {
|
variant: {
|
||||||
default: "bg-primary text-primary-foreground hover:bg-primary/90",
|
default: "bg-primary text-primary-foreground hover:bg-primary/90",
|
||||||
destructive:
|
destructive:
|
||||||
"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40",
|
"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40",
|
||||||
outline:
|
outline:
|
||||||
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",
|
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",
|
||||||
secondary:
|
secondary:
|
||||||
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
||||||
ghost:
|
ghost:
|
||||||
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
|
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
|
||||||
link: "text-primary underline-offset-4 hover:underline",
|
link: "text-primary underline-offset-4 hover:underline",
|
||||||
},
|
},
|
||||||
size: {
|
size: {
|
||||||
default: "h-9 px-4 py-2 has-[>svg]:px-3",
|
default: "h-9 px-4 py-2 has-[>svg]:px-3",
|
||||||
xs: "h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3",
|
xs: "h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3",
|
||||||
sm: "h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5",
|
sm: "h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5",
|
||||||
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
|
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
|
||||||
icon: "size-9",
|
icon: "size-9",
|
||||||
"icon-xs": "size-6 rounded-md [&_svg:not([class*='size-'])]:size-3",
|
"icon-xs": "size-6 rounded-md [&_svg:not([class*='size-'])]:size-3",
|
||||||
"icon-sm": "size-8",
|
"icon-sm": "size-8",
|
||||||
"icon-lg": "size-10",
|
"icon-lg": "size-10",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
defaultVariants: {
|
defaultVariants: {
|
||||||
variant: "default",
|
variant: "default",
|
||||||
size: "default",
|
size: "default",
|
||||||
},
|
},
|
||||||
}
|
},
|
||||||
)
|
);
|
||||||
|
|
||||||
function Button({
|
function Button({
|
||||||
className,
|
className,
|
||||||
variant = "default",
|
variant = "default",
|
||||||
size = "default",
|
size = "default",
|
||||||
asChild = false,
|
asChild = false,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<"button"> &
|
}: React.ComponentProps<"button"> &
|
||||||
VariantProps<typeof buttonVariants> & {
|
VariantProps<typeof buttonVariants> & {
|
||||||
asChild?: boolean
|
asChild?: boolean;
|
||||||
}) {
|
}) {
|
||||||
const Comp = asChild ? Slot.Root : "button"
|
const Comp = asChild ? Slot.Root : "button";
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Comp
|
<Comp
|
||||||
data-slot="button"
|
data-slot="button"
|
||||||
data-variant={variant}
|
data-variant={variant}
|
||||||
data-size={size}
|
data-size={size}
|
||||||
className={cn(buttonVariants({ variant, size, className }))}
|
className={cn(buttonVariants({ variant, size, className }))}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export { Button, buttonVariants }
|
export { Button, buttonVariants };
|
||||||
|
|||||||
@@ -1,92 +1,92 @@
|
|||||||
import * as React from "react"
|
import type * as React from "react";
|
||||||
|
|
||||||
import { cn } from "#/lib/utils.ts"
|
import { cn } from "#/lib/utils.ts";
|
||||||
|
|
||||||
function Card({ className, ...props }: React.ComponentProps<"div">) {
|
function Card({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
data-slot="card"
|
data-slot="card"
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex flex-col gap-6 rounded-xl border bg-card py-6 text-card-foreground shadow-sm",
|
"flex flex-col gap-6 rounded-xl border bg-card py-6 text-card-foreground shadow-sm",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
|
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
data-slot="card-header"
|
data-slot="card-header"
|
||||||
className={cn(
|
className={cn(
|
||||||
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
|
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
|
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
data-slot="card-title"
|
data-slot="card-title"
|
||||||
className={cn("leading-none font-semibold", className)}
|
className={cn("leading-none font-semibold", className)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
|
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
data-slot="card-description"
|
data-slot="card-description"
|
||||||
className={cn("text-sm text-muted-foreground", className)}
|
className={cn("text-sm text-muted-foreground", className)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
|
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
data-slot="card-action"
|
data-slot="card-action"
|
||||||
className={cn(
|
className={cn(
|
||||||
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
|
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
|
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
data-slot="card-content"
|
data-slot="card-content"
|
||||||
className={cn("px-6", className)}
|
className={cn("px-6", className)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
|
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
data-slot="card-footer"
|
data-slot="card-footer"
|
||||||
className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
|
className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export {
|
export {
|
||||||
Card,
|
Card,
|
||||||
CardHeader,
|
CardHeader,
|
||||||
CardFooter,
|
CardFooter,
|
||||||
CardTitle,
|
CardTitle,
|
||||||
CardAction,
|
CardAction,
|
||||||
CardDescription,
|
CardDescription,
|
||||||
CardContent,
|
CardContent,
|
||||||
}
|
};
|
||||||
|
|||||||
@@ -1,372 +1,370 @@
|
|||||||
import * as React from "react"
|
import * as React from "react";
|
||||||
import * as RechartsPrimitive from "recharts"
|
import type { TooltipValueType } from "recharts";
|
||||||
import type { TooltipValueType } from "recharts"
|
import * as RechartsPrimitive from "recharts";
|
||||||
|
|
||||||
import { cn } from "#/lib/utils.ts"
|
import { cn } from "#/lib/utils.ts";
|
||||||
|
|
||||||
// Format: { THEME_NAME: CSS_SELECTOR }
|
// Format: { THEME_NAME: CSS_SELECTOR }
|
||||||
const THEMES = { light: "", dark: ".dark" } as const
|
const THEMES = { light: "", dark: ".dark" } as const;
|
||||||
|
|
||||||
const INITIAL_DIMENSION = { width: 320, height: 200 } as const
|
const INITIAL_DIMENSION = { width: 320, height: 200 } as const;
|
||||||
type TooltipNameType = number | string
|
type TooltipNameType = number | string;
|
||||||
|
|
||||||
export type ChartConfig = Record<
|
export type ChartConfig = Record<
|
||||||
string,
|
string,
|
||||||
{
|
{
|
||||||
label?: React.ReactNode
|
label?: React.ReactNode;
|
||||||
icon?: React.ComponentType
|
icon?: React.ComponentType;
|
||||||
} & (
|
} & (
|
||||||
| { color?: string; theme?: never }
|
| { color?: string; theme?: never }
|
||||||
| { color?: never; theme: Record<keyof typeof THEMES, string> }
|
| { color?: never; theme: Record<keyof typeof THEMES, string> }
|
||||||
)
|
)
|
||||||
>
|
>;
|
||||||
|
|
||||||
type ChartContextProps = {
|
type ChartContextProps = {
|
||||||
config: ChartConfig
|
config: ChartConfig;
|
||||||
}
|
};
|
||||||
|
|
||||||
const ChartContext = React.createContext<ChartContextProps | null>(null)
|
const ChartContext = React.createContext<ChartContextProps | null>(null);
|
||||||
|
|
||||||
function useChart() {
|
function useChart() {
|
||||||
const context = React.useContext(ChartContext)
|
const context = React.useContext(ChartContext);
|
||||||
|
|
||||||
if (!context) {
|
if (!context) {
|
||||||
throw new Error("useChart must be used within a <ChartContainer />")
|
throw new Error("useChart must be used within a <ChartContainer />");
|
||||||
}
|
}
|
||||||
|
|
||||||
return context
|
return context;
|
||||||
}
|
}
|
||||||
|
|
||||||
function ChartContainer({
|
function ChartContainer({
|
||||||
id,
|
id,
|
||||||
className,
|
className,
|
||||||
children,
|
children,
|
||||||
config,
|
config,
|
||||||
initialDimension = INITIAL_DIMENSION,
|
initialDimension = INITIAL_DIMENSION,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<"div"> & {
|
}: React.ComponentProps<"div"> & {
|
||||||
config: ChartConfig
|
config: ChartConfig;
|
||||||
children: React.ComponentProps<
|
children: React.ComponentProps<
|
||||||
typeof RechartsPrimitive.ResponsiveContainer
|
typeof RechartsPrimitive.ResponsiveContainer
|
||||||
>["children"]
|
>["children"];
|
||||||
initialDimension?: {
|
initialDimension?: {
|
||||||
width: number
|
width: number;
|
||||||
height: number
|
height: number;
|
||||||
}
|
};
|
||||||
}) {
|
}) {
|
||||||
const uniqueId = React.useId()
|
const uniqueId = React.useId();
|
||||||
const chartId = `chart-${id ?? uniqueId.replace(/:/g, "")}`
|
const chartId = `chart-${id ?? uniqueId.replace(/:/g, "")}`;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ChartContext.Provider value={{ config }}>
|
<ChartContext.Provider value={{ config }}>
|
||||||
<div
|
<div
|
||||||
data-slot="chart"
|
data-slot="chart"
|
||||||
data-chart={chartId}
|
data-chart={chartId}
|
||||||
className={cn(
|
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-hidden [&_.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]:outline-hidden [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-surface]:outline-hidden",
|
"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-hidden [&_.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]:outline-hidden [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-surface]:outline-hidden",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
<ChartStyle id={chartId} config={config} />
|
<ChartStyle id={chartId} config={config} />
|
||||||
<RechartsPrimitive.ResponsiveContainer
|
<RechartsPrimitive.ResponsiveContainer
|
||||||
initialDimension={initialDimension}
|
initialDimension={initialDimension}
|
||||||
>
|
>
|
||||||
{children}
|
{children}
|
||||||
</RechartsPrimitive.ResponsiveContainer>
|
</RechartsPrimitive.ResponsiveContainer>
|
||||||
</div>
|
</div>
|
||||||
</ChartContext.Provider>
|
</ChartContext.Provider>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => {
|
const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => {
|
||||||
const colorConfig = Object.entries(config).filter(
|
const colorConfig = Object.entries(config).filter(
|
||||||
([, config]) => config.theme ?? config.color
|
([, config]) => config.theme ?? config.color,
|
||||||
)
|
);
|
||||||
|
|
||||||
if (!colorConfig.length) {
|
if (!colorConfig.length) {
|
||||||
return null
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
const css = Object.entries(THEMES)
|
||||||
<style
|
.map(
|
||||||
dangerouslySetInnerHTML={{
|
([theme, prefix]) => `
|
||||||
__html: Object.entries(THEMES)
|
|
||||||
.map(
|
|
||||||
([theme, prefix]) => `
|
|
||||||
${prefix} [data-chart=${id}] {
|
${prefix} [data-chart=${id}] {
|
||||||
${colorConfig
|
${colorConfig
|
||||||
.map(([key, itemConfig]) => {
|
.map(([key, itemConfig]) => {
|
||||||
const color =
|
const color =
|
||||||
itemConfig.theme?.[theme as keyof typeof itemConfig.theme] ??
|
itemConfig.theme?.[theme as keyof typeof itemConfig.theme] ??
|
||||||
itemConfig.color
|
itemConfig.color;
|
||||||
return color ? ` --color-${key}: ${color};` : null
|
return color ? ` --color-${key}: ${color};` : null;
|
||||||
})
|
})
|
||||||
.join("\n")}
|
.join("\n")}
|
||||||
}
|
|
||||||
`
|
|
||||||
)
|
|
||||||
.join("\n"),
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
`,
|
||||||
|
)
|
||||||
|
.join("\n");
|
||||||
|
|
||||||
const ChartTooltip = RechartsPrimitive.Tooltip
|
return <style>{css}</style>;
|
||||||
|
};
|
||||||
|
|
||||||
|
const ChartTooltip = RechartsPrimitive.Tooltip;
|
||||||
|
|
||||||
function ChartTooltipContent({
|
function ChartTooltipContent({
|
||||||
active,
|
active,
|
||||||
payload,
|
payload,
|
||||||
className,
|
className,
|
||||||
indicator = "dot",
|
indicator = "dot",
|
||||||
hideLabel = false,
|
hideLabel = false,
|
||||||
hideIndicator = false,
|
hideIndicator = false,
|
||||||
label,
|
label,
|
||||||
labelFormatter,
|
labelFormatter,
|
||||||
labelClassName,
|
labelClassName,
|
||||||
formatter,
|
formatter,
|
||||||
color,
|
color,
|
||||||
nameKey,
|
nameKey,
|
||||||
labelKey,
|
labelKey,
|
||||||
}: React.ComponentProps<typeof RechartsPrimitive.Tooltip> &
|
}: React.ComponentProps<typeof RechartsPrimitive.Tooltip> &
|
||||||
React.ComponentProps<"div"> & {
|
React.ComponentProps<"div"> & {
|
||||||
hideLabel?: boolean
|
hideLabel?: boolean;
|
||||||
hideIndicator?: boolean
|
hideIndicator?: boolean;
|
||||||
indicator?: "line" | "dot" | "dashed"
|
indicator?: "line" | "dot" | "dashed";
|
||||||
nameKey?: string
|
nameKey?: string;
|
||||||
labelKey?: string
|
labelKey?: string;
|
||||||
} & Omit<
|
} & Omit<
|
||||||
RechartsPrimitive.DefaultTooltipContentProps<
|
RechartsPrimitive.DefaultTooltipContentProps<
|
||||||
TooltipValueType,
|
TooltipValueType,
|
||||||
TooltipNameType
|
TooltipNameType
|
||||||
>,
|
>,
|
||||||
"accessibilityLayer"
|
"accessibilityLayer"
|
||||||
>) {
|
>) {
|
||||||
const { config } = useChart()
|
const { config } = useChart();
|
||||||
|
|
||||||
const tooltipLabel = React.useMemo(() => {
|
const tooltipLabel = React.useMemo(() => {
|
||||||
if (hideLabel || !payload?.length) {
|
if (hideLabel || !payload?.length) {
|
||||||
return null
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const [item] = payload
|
const [item] = payload;
|
||||||
const key = `${labelKey ?? item?.dataKey ?? item?.name ?? "value"}`
|
const key = `${labelKey ?? item?.dataKey ?? item?.name ?? "value"}`;
|
||||||
const itemConfig = getPayloadConfigFromPayload(config, item, key)
|
const itemConfig = getPayloadConfigFromPayload(config, item, key);
|
||||||
const value =
|
const value =
|
||||||
!labelKey && typeof label === "string"
|
!labelKey && typeof label === "string"
|
||||||
? (config[label]?.label ?? label)
|
? (config[label]?.label ?? label)
|
||||||
: itemConfig?.label
|
: itemConfig?.label;
|
||||||
|
|
||||||
if (labelFormatter) {
|
if (labelFormatter) {
|
||||||
return (
|
return (
|
||||||
<div className={cn("font-medium", labelClassName)}>
|
<div className={cn("font-medium", labelClassName)}>
|
||||||
{labelFormatter(value, payload)}
|
{labelFormatter(value, payload)}
|
||||||
</div>
|
</div>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!value) {
|
if (!value) {
|
||||||
return null
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
return <div className={cn("font-medium", labelClassName)}>{value}</div>
|
return <div className={cn("font-medium", labelClassName)}>{value}</div>;
|
||||||
}, [
|
}, [
|
||||||
label,
|
label,
|
||||||
labelFormatter,
|
labelFormatter,
|
||||||
payload,
|
payload,
|
||||||
hideLabel,
|
hideLabel,
|
||||||
labelClassName,
|
labelClassName,
|
||||||
config,
|
config,
|
||||||
labelKey,
|
labelKey,
|
||||||
])
|
]);
|
||||||
|
|
||||||
if (!active || !payload?.length) {
|
if (!active || !payload?.length) {
|
||||||
return null
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const nestLabel = payload.length === 1 && indicator !== "dot"
|
const nestLabel = payload.length === 1 && indicator !== "dot";
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className={cn(
|
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",
|
"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
|
className,
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{!nestLabel ? tooltipLabel : null}
|
{!nestLabel ? tooltipLabel : null}
|
||||||
<div className="grid gap-1.5">
|
<div className="grid gap-1.5">
|
||||||
{payload
|
{payload
|
||||||
.filter((item) => item.type !== "none")
|
.filter((item) => item.type !== "none")
|
||||||
.map((item, index) => {
|
.map((item, index) => {
|
||||||
const key = `${nameKey ?? item.name ?? item.dataKey ?? "value"}`
|
const key = `${nameKey ?? item.name ?? item.dataKey ?? "value"}`;
|
||||||
const itemConfig = getPayloadConfigFromPayload(config, item, key)
|
const itemKey = `${key}-${String(item.value ?? item.color ?? "")}`;
|
||||||
const indicatorColor = color ?? item.payload?.fill ?? item.color
|
const itemConfig = getPayloadConfigFromPayload(config, item, key);
|
||||||
|
const indicatorColor = color ?? item.payload?.fill ?? item.color;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
key={index}
|
key={itemKey}
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground",
|
"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"
|
indicator === "dot" && "items-center",
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{formatter && item?.value !== undefined && item.name ? (
|
{formatter && item?.value !== undefined && item.name ? (
|
||||||
formatter(item.value, item.name, item, index, item.payload)
|
formatter(item.value, item.name, item, index, item.payload)
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
{itemConfig?.icon ? (
|
{itemConfig?.icon ? (
|
||||||
<itemConfig.icon />
|
<itemConfig.icon />
|
||||||
) : (
|
) : (
|
||||||
!hideIndicator && (
|
!hideIndicator && (
|
||||||
<div
|
<div
|
||||||
className={cn(
|
className={cn(
|
||||||
"shrink-0 rounded-[2px] border-(--color-border) bg-(--color-bg)",
|
"shrink-0 rounded-[2px] border-(--color-border) bg-(--color-bg)",
|
||||||
{
|
{
|
||||||
"h-2.5 w-2.5": indicator === "dot",
|
"h-2.5 w-2.5": indicator === "dot",
|
||||||
"w-1": indicator === "line",
|
"w-1": indicator === "line",
|
||||||
"w-0 border-[1.5px] border-dashed bg-transparent":
|
"w-0 border-[1.5px] border-dashed bg-transparent":
|
||||||
indicator === "dashed",
|
indicator === "dashed",
|
||||||
"my-0.5": nestLabel && indicator === "dashed",
|
"my-0.5": nestLabel && indicator === "dashed",
|
||||||
}
|
},
|
||||||
)}
|
)}
|
||||||
style={
|
style={
|
||||||
{
|
{
|
||||||
"--color-bg": indicatorColor,
|
"--color-bg": indicatorColor,
|
||||||
"--color-border": indicatorColor,
|
"--color-border": indicatorColor,
|
||||||
} as React.CSSProperties
|
} as React.CSSProperties
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
)
|
)
|
||||||
)}
|
)}
|
||||||
<div
|
<div
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex flex-1 justify-between leading-none",
|
"flex flex-1 justify-between leading-none",
|
||||||
nestLabel ? "items-end" : "items-center"
|
nestLabel ? "items-end" : "items-center",
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<div className="grid gap-1.5">
|
<div className="grid gap-1.5">
|
||||||
{nestLabel ? tooltipLabel : null}
|
{nestLabel ? tooltipLabel : null}
|
||||||
<span className="text-muted-foreground">
|
<span className="text-muted-foreground">
|
||||||
{itemConfig?.label ?? item.name}
|
{itemConfig?.label ?? item.name}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
{item.value != null && (
|
{item.value != null && (
|
||||||
<span className="font-mono font-medium text-foreground tabular-nums">
|
<span className="font-mono font-medium text-foreground tabular-nums">
|
||||||
{typeof item.value === "number"
|
{typeof item.value === "number"
|
||||||
? item.value.toLocaleString()
|
? item.value.toLocaleString()
|
||||||
: String(item.value)}
|
: String(item.value)}
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
)
|
);
|
||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const ChartLegend = RechartsPrimitive.Legend
|
const ChartLegend = RechartsPrimitive.Legend;
|
||||||
|
|
||||||
function ChartLegendContent({
|
function ChartLegendContent({
|
||||||
className,
|
className,
|
||||||
hideIcon = false,
|
hideIcon = false,
|
||||||
payload,
|
payload,
|
||||||
verticalAlign = "bottom",
|
verticalAlign = "bottom",
|
||||||
nameKey,
|
nameKey,
|
||||||
}: React.ComponentProps<"div"> & {
|
}: React.ComponentProps<"div"> & {
|
||||||
hideIcon?: boolean
|
hideIcon?: boolean;
|
||||||
nameKey?: string
|
nameKey?: string;
|
||||||
} & RechartsPrimitive.DefaultLegendContentProps) {
|
} & RechartsPrimitive.DefaultLegendContentProps) {
|
||||||
const { config } = useChart()
|
const { config } = useChart();
|
||||||
|
|
||||||
if (!payload?.length) {
|
if (!payload?.length) {
|
||||||
return null
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex items-center justify-center gap-4",
|
"flex items-center justify-center gap-4",
|
||||||
verticalAlign === "top" ? "pb-3" : "pt-3",
|
verticalAlign === "top" ? "pb-3" : "pt-3",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{payload
|
{payload
|
||||||
.filter((item) => item.type !== "none")
|
.filter((item) => item.type !== "none")
|
||||||
.map((item, index) => {
|
.map((item) => {
|
||||||
const key = `${nameKey ?? item.dataKey ?? "value"}`
|
const key = `${nameKey ?? item.dataKey ?? "value"}`;
|
||||||
const itemConfig = getPayloadConfigFromPayload(config, item, key)
|
const itemKey = `${key}-${String(item.value ?? item.color ?? "")}`;
|
||||||
|
const itemConfig = getPayloadConfigFromPayload(config, item, key);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
key={index}
|
key={itemKey}
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground"
|
"flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground",
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{itemConfig?.icon && !hideIcon ? (
|
{itemConfig?.icon && !hideIcon ? (
|
||||||
<itemConfig.icon />
|
<itemConfig.icon />
|
||||||
) : (
|
) : (
|
||||||
<div
|
<div
|
||||||
className="h-2 w-2 shrink-0 rounded-[2px]"
|
className="h-2 w-2 shrink-0 rounded-[2px]"
|
||||||
style={{
|
style={{
|
||||||
backgroundColor: item.color,
|
backgroundColor: item.color,
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
{itemConfig?.label}
|
{itemConfig?.label}
|
||||||
</div>
|
</div>
|
||||||
)
|
);
|
||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Helper to extract item config from a payload.
|
// Helper to extract item config from a payload.
|
||||||
function getPayloadConfigFromPayload(
|
function getPayloadConfigFromPayload(
|
||||||
config: ChartConfig,
|
config: ChartConfig,
|
||||||
payload: unknown,
|
payload: unknown,
|
||||||
key: string
|
key: string,
|
||||||
) {
|
) {
|
||||||
if (typeof payload !== "object" || payload === null) {
|
if (typeof payload !== "object" || payload === null) {
|
||||||
return undefined
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
const payloadPayload =
|
const payloadPayload =
|
||||||
"payload" in payload &&
|
"payload" in payload &&
|
||||||
typeof payload.payload === "object" &&
|
typeof payload.payload === "object" &&
|
||||||
payload.payload !== null
|
payload.payload !== null
|
||||||
? payload.payload
|
? payload.payload
|
||||||
: undefined
|
: undefined;
|
||||||
|
|
||||||
let configLabelKey: string = key
|
let configLabelKey: string = key;
|
||||||
|
|
||||||
if (
|
if (
|
||||||
key in payload &&
|
key in payload &&
|
||||||
typeof payload[key as keyof typeof payload] === "string"
|
typeof payload[key as keyof typeof payload] === "string"
|
||||||
) {
|
) {
|
||||||
configLabelKey = payload[key as keyof typeof payload] as string
|
configLabelKey = payload[key as keyof typeof payload] as string;
|
||||||
} else if (
|
} else if (
|
||||||
payloadPayload &&
|
payloadPayload &&
|
||||||
key in payloadPayload &&
|
key in payloadPayload &&
|
||||||
typeof payloadPayload[key as keyof typeof payloadPayload] === "string"
|
typeof payloadPayload[key as keyof typeof payloadPayload] === "string"
|
||||||
) {
|
) {
|
||||||
configLabelKey = payloadPayload[
|
configLabelKey = payloadPayload[
|
||||||
key as keyof typeof payloadPayload
|
key as keyof typeof payloadPayload
|
||||||
] as string
|
] as string;
|
||||||
}
|
}
|
||||||
|
|
||||||
return configLabelKey in config ? config[configLabelKey] : config[key]
|
return configLabelKey in config ? config[configLabelKey] : config[key];
|
||||||
}
|
}
|
||||||
|
|
||||||
export {
|
export {
|
||||||
ChartContainer,
|
ChartContainer,
|
||||||
ChartTooltip,
|
ChartTooltip,
|
||||||
ChartTooltipContent,
|
ChartTooltipContent,
|
||||||
ChartLegend,
|
ChartLegend,
|
||||||
ChartLegendContent,
|
ChartLegendContent,
|
||||||
ChartStyle,
|
ChartStyle,
|
||||||
}
|
};
|
||||||
|
|||||||
@@ -1,30 +1,30 @@
|
|||||||
import * as React from "react"
|
import { CheckIcon } from "lucide-react";
|
||||||
import { CheckIcon } from "lucide-react"
|
import { Checkbox as CheckboxPrimitive } from "radix-ui";
|
||||||
import { Checkbox as CheckboxPrimitive } from "radix-ui"
|
import type * as React from "react";
|
||||||
|
|
||||||
import { cn } from "#/lib/utils.ts"
|
import { cn } from "#/lib/utils.ts";
|
||||||
|
|
||||||
function Checkbox({
|
function Checkbox({
|
||||||
className,
|
className,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
|
}: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
|
||||||
return (
|
return (
|
||||||
<CheckboxPrimitive.Root
|
<CheckboxPrimitive.Root
|
||||||
data-slot="checkbox"
|
data-slot="checkbox"
|
||||||
className={cn(
|
className={cn(
|
||||||
"peer size-4 shrink-0 rounded-[4px] border border-input shadow-xs transition-shadow outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-[state=checked]:border-primary data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:bg-input/30 dark:aria-invalid:ring-destructive/40 dark:data-[state=checked]:bg-primary",
|
"peer size-4 shrink-0 rounded-[4px] border border-input shadow-xs transition-shadow outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-[state=checked]:border-primary data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:bg-input/30 dark:aria-invalid:ring-destructive/40 dark:data-[state=checked]:bg-primary",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
<CheckboxPrimitive.Indicator
|
<CheckboxPrimitive.Indicator
|
||||||
data-slot="checkbox-indicator"
|
data-slot="checkbox-indicator"
|
||||||
className="grid place-content-center text-current transition-none"
|
className="grid place-content-center text-current transition-none"
|
||||||
>
|
>
|
||||||
<CheckIcon className="size-3.5" />
|
<CheckIcon className="size-3.5" />
|
||||||
</CheckboxPrimitive.Indicator>
|
</CheckboxPrimitive.Indicator>
|
||||||
</CheckboxPrimitive.Root>
|
</CheckboxPrimitive.Root>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export { Checkbox }
|
export { Checkbox };
|
||||||
|
|||||||
@@ -1,33 +1,33 @@
|
|||||||
"use client"
|
"use client";
|
||||||
|
|
||||||
import { Collapsible as CollapsiblePrimitive } from "radix-ui"
|
import { Collapsible as CollapsiblePrimitive } from "radix-ui";
|
||||||
|
|
||||||
function Collapsible({
|
function Collapsible({
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof CollapsiblePrimitive.Root>) {
|
}: React.ComponentProps<typeof CollapsiblePrimitive.Root>) {
|
||||||
return <CollapsiblePrimitive.Root data-slot="collapsible" {...props} />
|
return <CollapsiblePrimitive.Root data-slot="collapsible" {...props} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
function CollapsibleTrigger({
|
function CollapsibleTrigger({
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleTrigger>) {
|
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleTrigger>) {
|
||||||
return (
|
return (
|
||||||
<CollapsiblePrimitive.CollapsibleTrigger
|
<CollapsiblePrimitive.CollapsibleTrigger
|
||||||
data-slot="collapsible-trigger"
|
data-slot="collapsible-trigger"
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function CollapsibleContent({
|
function CollapsibleContent({
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleContent>) {
|
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleContent>) {
|
||||||
return (
|
return (
|
||||||
<CollapsiblePrimitive.CollapsibleContent
|
<CollapsiblePrimitive.CollapsibleContent
|
||||||
data-slot="collapsible-content"
|
data-slot="collapsible-content"
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export { Collapsible, CollapsibleTrigger, CollapsibleContent }
|
export { Collapsible, CollapsibleTrigger, CollapsibleContent };
|
||||||
|
|||||||
@@ -1,158 +1,157 @@
|
|||||||
"use client"
|
"use client";
|
||||||
|
|
||||||
import * as React from "react"
|
import { XIcon } from "lucide-react";
|
||||||
import { XIcon } from "lucide-react"
|
import { Dialog as DialogPrimitive } from "radix-ui";
|
||||||
import { Dialog as DialogPrimitive } from "radix-ui"
|
import type * as React from "react";
|
||||||
|
import { Button } from "#/components/ui/button.tsx";
|
||||||
import { cn } from "#/lib/utils.ts"
|
import { cn } from "#/lib/utils.ts";
|
||||||
import { Button } from "#/components/ui/button.tsx"
|
|
||||||
|
|
||||||
function Dialog({
|
function Dialog({
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
|
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
|
||||||
return <DialogPrimitive.Root data-slot="dialog" {...props} />
|
return <DialogPrimitive.Root data-slot="dialog" {...props} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
function DialogTrigger({
|
function DialogTrigger({
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
|
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
|
||||||
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
|
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
function DialogPortal({
|
function DialogPortal({
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
|
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
|
||||||
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
|
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
function DialogClose({
|
function DialogClose({
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
|
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
|
||||||
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
|
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
function DialogOverlay({
|
function DialogOverlay({
|
||||||
className,
|
className,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
|
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
|
||||||
return (
|
return (
|
||||||
<DialogPrimitive.Overlay
|
<DialogPrimitive.Overlay
|
||||||
data-slot="dialog-overlay"
|
data-slot="dialog-overlay"
|
||||||
className={cn(
|
className={cn(
|
||||||
"fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",
|
"fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function DialogContent({
|
function DialogContent({
|
||||||
className,
|
className,
|
||||||
children,
|
children,
|
||||||
showCloseButton = true,
|
showCloseButton = true,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
|
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
|
||||||
showCloseButton?: boolean
|
showCloseButton?: boolean;
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<DialogPortal data-slot="dialog-portal">
|
<DialogPortal data-slot="dialog-portal">
|
||||||
<DialogOverlay />
|
<DialogOverlay />
|
||||||
<DialogPrimitive.Content
|
<DialogPrimitive.Content
|
||||||
data-slot="dialog-content"
|
data-slot="dialog-content"
|
||||||
className={cn(
|
className={cn(
|
||||||
"fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg",
|
"fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
{children}
|
{children}
|
||||||
{showCloseButton && (
|
{showCloseButton && (
|
||||||
<DialogPrimitive.Close
|
<DialogPrimitive.Close
|
||||||
data-slot="dialog-close"
|
data-slot="dialog-close"
|
||||||
className="absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
|
className="absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
|
||||||
>
|
>
|
||||||
<XIcon />
|
<XIcon />
|
||||||
<span className="sr-only">Close</span>
|
<span className="sr-only">Close</span>
|
||||||
</DialogPrimitive.Close>
|
</DialogPrimitive.Close>
|
||||||
)}
|
)}
|
||||||
</DialogPrimitive.Content>
|
</DialogPrimitive.Content>
|
||||||
</DialogPortal>
|
</DialogPortal>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
|
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
data-slot="dialog-header"
|
data-slot="dialog-header"
|
||||||
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
|
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function DialogFooter({
|
function DialogFooter({
|
||||||
className,
|
className,
|
||||||
showCloseButton = false,
|
showCloseButton = false,
|
||||||
children,
|
children,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<"div"> & {
|
}: React.ComponentProps<"div"> & {
|
||||||
showCloseButton?: boolean
|
showCloseButton?: boolean;
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
data-slot="dialog-footer"
|
data-slot="dialog-footer"
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
|
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
{children}
|
{children}
|
||||||
{showCloseButton && (
|
{showCloseButton && (
|
||||||
<DialogPrimitive.Close asChild>
|
<DialogPrimitive.Close asChild>
|
||||||
<Button variant="outline">Close</Button>
|
<Button variant="outline">Close</Button>
|
||||||
</DialogPrimitive.Close>
|
</DialogPrimitive.Close>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function DialogTitle({
|
function DialogTitle({
|
||||||
className,
|
className,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
|
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
|
||||||
return (
|
return (
|
||||||
<DialogPrimitive.Title
|
<DialogPrimitive.Title
|
||||||
data-slot="dialog-title"
|
data-slot="dialog-title"
|
||||||
className={cn("text-lg leading-none font-semibold", className)}
|
className={cn("text-lg leading-none font-semibold", className)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function DialogDescription({
|
function DialogDescription({
|
||||||
className,
|
className,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
|
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
|
||||||
return (
|
return (
|
||||||
<DialogPrimitive.Description
|
<DialogPrimitive.Description
|
||||||
data-slot="dialog-description"
|
data-slot="dialog-description"
|
||||||
className={cn("text-sm text-muted-foreground", className)}
|
className={cn("text-sm text-muted-foreground", className)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export {
|
export {
|
||||||
Dialog,
|
Dialog,
|
||||||
DialogClose,
|
DialogClose,
|
||||||
DialogContent,
|
DialogContent,
|
||||||
DialogDescription,
|
DialogDescription,
|
||||||
DialogFooter,
|
DialogFooter,
|
||||||
DialogHeader,
|
DialogHeader,
|
||||||
DialogOverlay,
|
DialogOverlay,
|
||||||
DialogPortal,
|
DialogPortal,
|
||||||
DialogTitle,
|
DialogTitle,
|
||||||
DialogTrigger,
|
DialogTrigger,
|
||||||
}
|
};
|
||||||
|
|||||||
@@ -1,133 +1,133 @@
|
|||||||
import * as React from "react"
|
import type * as React from "react";
|
||||||
import { Drawer as DrawerPrimitive } from "vaul"
|
import { Drawer as DrawerPrimitive } from "vaul";
|
||||||
|
|
||||||
import { cn } from "#/lib/utils.ts"
|
import { cn } from "#/lib/utils.ts";
|
||||||
|
|
||||||
function Drawer({
|
function Drawer({
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof DrawerPrimitive.Root>) {
|
}: React.ComponentProps<typeof DrawerPrimitive.Root>) {
|
||||||
return <DrawerPrimitive.Root data-slot="drawer" {...props} />
|
return <DrawerPrimitive.Root data-slot="drawer" {...props} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
function DrawerTrigger({
|
function DrawerTrigger({
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof DrawerPrimitive.Trigger>) {
|
}: React.ComponentProps<typeof DrawerPrimitive.Trigger>) {
|
||||||
return <DrawerPrimitive.Trigger data-slot="drawer-trigger" {...props} />
|
return <DrawerPrimitive.Trigger data-slot="drawer-trigger" {...props} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
function DrawerPortal({
|
function DrawerPortal({
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof DrawerPrimitive.Portal>) {
|
}: React.ComponentProps<typeof DrawerPrimitive.Portal>) {
|
||||||
return <DrawerPrimitive.Portal data-slot="drawer-portal" {...props} />
|
return <DrawerPrimitive.Portal data-slot="drawer-portal" {...props} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
function DrawerClose({
|
function DrawerClose({
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof DrawerPrimitive.Close>) {
|
}: React.ComponentProps<typeof DrawerPrimitive.Close>) {
|
||||||
return <DrawerPrimitive.Close data-slot="drawer-close" {...props} />
|
return <DrawerPrimitive.Close data-slot="drawer-close" {...props} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
function DrawerOverlay({
|
function DrawerOverlay({
|
||||||
className,
|
className,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof DrawerPrimitive.Overlay>) {
|
}: React.ComponentProps<typeof DrawerPrimitive.Overlay>) {
|
||||||
return (
|
return (
|
||||||
<DrawerPrimitive.Overlay
|
<DrawerPrimitive.Overlay
|
||||||
data-slot="drawer-overlay"
|
data-slot="drawer-overlay"
|
||||||
className={cn(
|
className={cn(
|
||||||
"fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",
|
"fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function DrawerContent({
|
function DrawerContent({
|
||||||
className,
|
className,
|
||||||
children,
|
children,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof DrawerPrimitive.Content>) {
|
}: React.ComponentProps<typeof DrawerPrimitive.Content>) {
|
||||||
return (
|
return (
|
||||||
<DrawerPortal data-slot="drawer-portal">
|
<DrawerPortal data-slot="drawer-portal">
|
||||||
<DrawerOverlay />
|
<DrawerOverlay />
|
||||||
<DrawerPrimitive.Content
|
<DrawerPrimitive.Content
|
||||||
data-slot="drawer-content"
|
data-slot="drawer-content"
|
||||||
className={cn(
|
className={cn(
|
||||||
"group/drawer-content fixed z-50 flex h-auto flex-col bg-background",
|
"group/drawer-content fixed z-50 flex h-auto flex-col bg-background",
|
||||||
"data-[vaul-drawer-direction=top]:inset-x-0 data-[vaul-drawer-direction=top]:top-0 data-[vaul-drawer-direction=top]:mb-24 data-[vaul-drawer-direction=top]:max-h-[80vh] data-[vaul-drawer-direction=top]:rounded-b-lg data-[vaul-drawer-direction=top]:border-b",
|
"data-[vaul-drawer-direction=top]:inset-x-0 data-[vaul-drawer-direction=top]:top-0 data-[vaul-drawer-direction=top]:mb-24 data-[vaul-drawer-direction=top]:max-h-[80vh] data-[vaul-drawer-direction=top]:rounded-b-lg data-[vaul-drawer-direction=top]:border-b",
|
||||||
"data-[vaul-drawer-direction=bottom]:inset-x-0 data-[vaul-drawer-direction=bottom]:bottom-0 data-[vaul-drawer-direction=bottom]:mt-24 data-[vaul-drawer-direction=bottom]:max-h-[80vh] data-[vaul-drawer-direction=bottom]:rounded-t-lg data-[vaul-drawer-direction=bottom]:border-t",
|
"data-[vaul-drawer-direction=bottom]:inset-x-0 data-[vaul-drawer-direction=bottom]:bottom-0 data-[vaul-drawer-direction=bottom]:mt-24 data-[vaul-drawer-direction=bottom]:max-h-[80vh] data-[vaul-drawer-direction=bottom]:rounded-t-lg data-[vaul-drawer-direction=bottom]:border-t",
|
||||||
"data-[vaul-drawer-direction=right]:inset-y-0 data-[vaul-drawer-direction=right]:right-0 data-[vaul-drawer-direction=right]:w-3/4 data-[vaul-drawer-direction=right]:border-l data-[vaul-drawer-direction=right]:sm:max-w-sm",
|
"data-[vaul-drawer-direction=right]:inset-y-0 data-[vaul-drawer-direction=right]:right-0 data-[vaul-drawer-direction=right]:w-3/4 data-[vaul-drawer-direction=right]:border-l data-[vaul-drawer-direction=right]:sm:max-w-sm",
|
||||||
"data-[vaul-drawer-direction=left]:inset-y-0 data-[vaul-drawer-direction=left]:left-0 data-[vaul-drawer-direction=left]:w-3/4 data-[vaul-drawer-direction=left]:border-r data-[vaul-drawer-direction=left]:sm:max-w-sm",
|
"data-[vaul-drawer-direction=left]:inset-y-0 data-[vaul-drawer-direction=left]:left-0 data-[vaul-drawer-direction=left]:w-3/4 data-[vaul-drawer-direction=left]:border-r data-[vaul-drawer-direction=left]:sm:max-w-sm",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
<div className="mx-auto mt-4 hidden h-2 w-[100px] shrink-0 rounded-full bg-muted group-data-[vaul-drawer-direction=bottom]/drawer-content:block" />
|
<div className="mx-auto mt-4 hidden h-2 w-[100px] shrink-0 rounded-full bg-muted group-data-[vaul-drawer-direction=bottom]/drawer-content:block" />
|
||||||
{children}
|
{children}
|
||||||
</DrawerPrimitive.Content>
|
</DrawerPrimitive.Content>
|
||||||
</DrawerPortal>
|
</DrawerPortal>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function DrawerHeader({ className, ...props }: React.ComponentProps<"div">) {
|
function DrawerHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
data-slot="drawer-header"
|
data-slot="drawer-header"
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex flex-col gap-0.5 p-4 group-data-[vaul-drawer-direction=bottom]/drawer-content:text-center group-data-[vaul-drawer-direction=top]/drawer-content:text-center md:gap-1.5 md:text-left",
|
"flex flex-col gap-0.5 p-4 group-data-[vaul-drawer-direction=bottom]/drawer-content:text-center group-data-[vaul-drawer-direction=top]/drawer-content:text-center md:gap-1.5 md:text-left",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function DrawerFooter({ className, ...props }: React.ComponentProps<"div">) {
|
function DrawerFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
data-slot="drawer-footer"
|
data-slot="drawer-footer"
|
||||||
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
|
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function DrawerTitle({
|
function DrawerTitle({
|
||||||
className,
|
className,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof DrawerPrimitive.Title>) {
|
}: React.ComponentProps<typeof DrawerPrimitive.Title>) {
|
||||||
return (
|
return (
|
||||||
<DrawerPrimitive.Title
|
<DrawerPrimitive.Title
|
||||||
data-slot="drawer-title"
|
data-slot="drawer-title"
|
||||||
className={cn("font-semibold text-foreground", className)}
|
className={cn("font-semibold text-foreground", className)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function DrawerDescription({
|
function DrawerDescription({
|
||||||
className,
|
className,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof DrawerPrimitive.Description>) {
|
}: React.ComponentProps<typeof DrawerPrimitive.Description>) {
|
||||||
return (
|
return (
|
||||||
<DrawerPrimitive.Description
|
<DrawerPrimitive.Description
|
||||||
data-slot="drawer-description"
|
data-slot="drawer-description"
|
||||||
className={cn("text-sm text-muted-foreground", className)}
|
className={cn("text-sm text-muted-foreground", className)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export {
|
export {
|
||||||
Drawer,
|
Drawer,
|
||||||
DrawerPortal,
|
DrawerPortal,
|
||||||
DrawerOverlay,
|
DrawerOverlay,
|
||||||
DrawerTrigger,
|
DrawerTrigger,
|
||||||
DrawerClose,
|
DrawerClose,
|
||||||
DrawerContent,
|
DrawerContent,
|
||||||
DrawerHeader,
|
DrawerHeader,
|
||||||
DrawerFooter,
|
DrawerFooter,
|
||||||
DrawerTitle,
|
DrawerTitle,
|
||||||
DrawerDescription,
|
DrawerDescription,
|
||||||
}
|
};
|
||||||
|
|||||||
@@ -1,255 +1,255 @@
|
|||||||
import * as React from "react"
|
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react";
|
||||||
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
|
import { DropdownMenu as DropdownMenuPrimitive } from "radix-ui";
|
||||||
import { DropdownMenu as DropdownMenuPrimitive } from "radix-ui"
|
import type * as React from "react";
|
||||||
|
|
||||||
import { cn } from "#/lib/utils.ts"
|
import { cn } from "#/lib/utils.ts";
|
||||||
|
|
||||||
function DropdownMenu({
|
function DropdownMenu({
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
|
||||||
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />
|
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
function DropdownMenuPortal({
|
function DropdownMenuPortal({
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
|
||||||
return (
|
return (
|
||||||
<DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
|
<DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function DropdownMenuTrigger({
|
function DropdownMenuTrigger({
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
|
||||||
return (
|
return (
|
||||||
<DropdownMenuPrimitive.Trigger
|
<DropdownMenuPrimitive.Trigger
|
||||||
data-slot="dropdown-menu-trigger"
|
data-slot="dropdown-menu-trigger"
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function DropdownMenuContent({
|
function DropdownMenuContent({
|
||||||
className,
|
className,
|
||||||
sideOffset = 4,
|
sideOffset = 4,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {
|
||||||
return (
|
return (
|
||||||
<DropdownMenuPrimitive.Portal>
|
<DropdownMenuPrimitive.Portal>
|
||||||
<DropdownMenuPrimitive.Content
|
<DropdownMenuPrimitive.Content
|
||||||
data-slot="dropdown-menu-content"
|
data-slot="dropdown-menu-content"
|
||||||
sideOffset={sideOffset}
|
sideOffset={sideOffset}
|
||||||
className={cn(
|
className={cn(
|
||||||
"z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md 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 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",
|
"z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md 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 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
</DropdownMenuPrimitive.Portal>
|
</DropdownMenuPrimitive.Portal>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function DropdownMenuGroup({
|
function DropdownMenuGroup({
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
|
||||||
return (
|
return (
|
||||||
<DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
|
<DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function DropdownMenuItem({
|
function DropdownMenuItem({
|
||||||
className,
|
className,
|
||||||
inset,
|
inset,
|
||||||
variant = "default",
|
variant = "default",
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
|
||||||
inset?: boolean
|
inset?: boolean;
|
||||||
variant?: "default" | "destructive"
|
variant?: "default" | "destructive";
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<DropdownMenuPrimitive.Item
|
<DropdownMenuPrimitive.Item
|
||||||
data-slot="dropdown-menu-item"
|
data-slot="dropdown-menu-item"
|
||||||
data-inset={inset}
|
data-inset={inset}
|
||||||
data-variant={variant}
|
data-variant={variant}
|
||||||
className={cn(
|
className={cn(
|
||||||
"relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",
|
"relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function DropdownMenuCheckboxItem({
|
function DropdownMenuCheckboxItem({
|
||||||
className,
|
className,
|
||||||
children,
|
children,
|
||||||
checked,
|
checked,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem>) {
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem>) {
|
||||||
return (
|
return (
|
||||||
<DropdownMenuPrimitive.CheckboxItem
|
<DropdownMenuPrimitive.CheckboxItem
|
||||||
data-slot="dropdown-menu-checkbox-item"
|
data-slot="dropdown-menu-checkbox-item"
|
||||||
className={cn(
|
className={cn(
|
||||||
"relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
"relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
checked={checked}
|
checked={checked}
|
||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||||
<DropdownMenuPrimitive.ItemIndicator>
|
<DropdownMenuPrimitive.ItemIndicator>
|
||||||
<CheckIcon className="size-4" />
|
<CheckIcon className="size-4" />
|
||||||
</DropdownMenuPrimitive.ItemIndicator>
|
</DropdownMenuPrimitive.ItemIndicator>
|
||||||
</span>
|
</span>
|
||||||
{children}
|
{children}
|
||||||
</DropdownMenuPrimitive.CheckboxItem>
|
</DropdownMenuPrimitive.CheckboxItem>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function DropdownMenuRadioGroup({
|
function DropdownMenuRadioGroup({
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
|
||||||
return (
|
return (
|
||||||
<DropdownMenuPrimitive.RadioGroup
|
<DropdownMenuPrimitive.RadioGroup
|
||||||
data-slot="dropdown-menu-radio-group"
|
data-slot="dropdown-menu-radio-group"
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function DropdownMenuRadioItem({
|
function DropdownMenuRadioItem({
|
||||||
className,
|
className,
|
||||||
children,
|
children,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem>) {
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem>) {
|
||||||
return (
|
return (
|
||||||
<DropdownMenuPrimitive.RadioItem
|
<DropdownMenuPrimitive.RadioItem
|
||||||
data-slot="dropdown-menu-radio-item"
|
data-slot="dropdown-menu-radio-item"
|
||||||
className={cn(
|
className={cn(
|
||||||
"relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
"relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||||
<DropdownMenuPrimitive.ItemIndicator>
|
<DropdownMenuPrimitive.ItemIndicator>
|
||||||
<CircleIcon className="size-2 fill-current" />
|
<CircleIcon className="size-2 fill-current" />
|
||||||
</DropdownMenuPrimitive.ItemIndicator>
|
</DropdownMenuPrimitive.ItemIndicator>
|
||||||
</span>
|
</span>
|
||||||
{children}
|
{children}
|
||||||
</DropdownMenuPrimitive.RadioItem>
|
</DropdownMenuPrimitive.RadioItem>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function DropdownMenuLabel({
|
function DropdownMenuLabel({
|
||||||
className,
|
className,
|
||||||
inset,
|
inset,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
|
||||||
inset?: boolean
|
inset?: boolean;
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<DropdownMenuPrimitive.Label
|
<DropdownMenuPrimitive.Label
|
||||||
data-slot="dropdown-menu-label"
|
data-slot="dropdown-menu-label"
|
||||||
data-inset={inset}
|
data-inset={inset}
|
||||||
className={cn(
|
className={cn(
|
||||||
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
|
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function DropdownMenuSeparator({
|
function DropdownMenuSeparator({
|
||||||
className,
|
className,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
|
||||||
return (
|
return (
|
||||||
<DropdownMenuPrimitive.Separator
|
<DropdownMenuPrimitive.Separator
|
||||||
data-slot="dropdown-menu-separator"
|
data-slot="dropdown-menu-separator"
|
||||||
className={cn("-mx-1 my-1 h-px bg-border", className)}
|
className={cn("-mx-1 my-1 h-px bg-border", className)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function DropdownMenuShortcut({
|
function DropdownMenuShortcut({
|
||||||
className,
|
className,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<"span">) {
|
}: React.ComponentProps<"span">) {
|
||||||
return (
|
return (
|
||||||
<span
|
<span
|
||||||
data-slot="dropdown-menu-shortcut"
|
data-slot="dropdown-menu-shortcut"
|
||||||
className={cn(
|
className={cn(
|
||||||
"ml-auto text-xs tracking-widest text-muted-foreground",
|
"ml-auto text-xs tracking-widest text-muted-foreground",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function DropdownMenuSub({
|
function DropdownMenuSub({
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
|
||||||
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />
|
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
function DropdownMenuSubTrigger({
|
function DropdownMenuSubTrigger({
|
||||||
className,
|
className,
|
||||||
inset,
|
inset,
|
||||||
children,
|
children,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
|
||||||
inset?: boolean
|
inset?: boolean;
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<DropdownMenuPrimitive.SubTrigger
|
<DropdownMenuPrimitive.SubTrigger
|
||||||
data-slot="dropdown-menu-sub-trigger"
|
data-slot="dropdown-menu-sub-trigger"
|
||||||
data-inset={inset}
|
data-inset={inset}
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[inset]:pl-8 data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",
|
"flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[inset]:pl-8 data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
{children}
|
{children}
|
||||||
<ChevronRightIcon className="ml-auto size-4" />
|
<ChevronRightIcon className="ml-auto size-4" />
|
||||||
</DropdownMenuPrimitive.SubTrigger>
|
</DropdownMenuPrimitive.SubTrigger>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function DropdownMenuSubContent({
|
function DropdownMenuSubContent({
|
||||||
className,
|
className,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {
|
||||||
return (
|
return (
|
||||||
<DropdownMenuPrimitive.SubContent
|
<DropdownMenuPrimitive.SubContent
|
||||||
data-slot="dropdown-menu-sub-content"
|
data-slot="dropdown-menu-sub-content"
|
||||||
className={cn(
|
className={cn(
|
||||||
"z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg 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 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",
|
"z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg 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 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export {
|
export {
|
||||||
DropdownMenu,
|
DropdownMenu,
|
||||||
DropdownMenuPortal,
|
DropdownMenuPortal,
|
||||||
DropdownMenuTrigger,
|
DropdownMenuTrigger,
|
||||||
DropdownMenuContent,
|
DropdownMenuContent,
|
||||||
DropdownMenuGroup,
|
DropdownMenuGroup,
|
||||||
DropdownMenuLabel,
|
DropdownMenuLabel,
|
||||||
DropdownMenuItem,
|
DropdownMenuItem,
|
||||||
DropdownMenuCheckboxItem,
|
DropdownMenuCheckboxItem,
|
||||||
DropdownMenuRadioGroup,
|
DropdownMenuRadioGroup,
|
||||||
DropdownMenuRadioItem,
|
DropdownMenuRadioItem,
|
||||||
DropdownMenuSeparator,
|
DropdownMenuSeparator,
|
||||||
DropdownMenuShortcut,
|
DropdownMenuShortcut,
|
||||||
DropdownMenuSub,
|
DropdownMenuSub,
|
||||||
DropdownMenuSubTrigger,
|
DropdownMenuSubTrigger,
|
||||||
DropdownMenuSubContent,
|
DropdownMenuSubContent,
|
||||||
}
|
};
|
||||||
|
|||||||
@@ -1,246 +1,244 @@
|
|||||||
import { useMemo } from "react"
|
import { cva, type VariantProps } from "class-variance-authority";
|
||||||
import { cva, type VariantProps } from "class-variance-authority"
|
import { useMemo } from "react";
|
||||||
|
import { Label } from "#/components/ui/label.tsx";
|
||||||
import { cn } from "#/lib/utils.ts"
|
import { Separator } from "#/components/ui/separator.tsx";
|
||||||
import { Label } from "#/components/ui/label.tsx"
|
import { cn } from "#/lib/utils.ts";
|
||||||
import { Separator } from "#/components/ui/separator.tsx"
|
|
||||||
|
|
||||||
function FieldSet({ className, ...props }: React.ComponentProps<"fieldset">) {
|
function FieldSet({ className, ...props }: React.ComponentProps<"fieldset">) {
|
||||||
return (
|
return (
|
||||||
<fieldset
|
<fieldset
|
||||||
data-slot="field-set"
|
data-slot="field-set"
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex flex-col gap-6",
|
"flex flex-col gap-6",
|
||||||
"has-[>[data-slot=checkbox-group]]:gap-3 has-[>[data-slot=radio-group]]:gap-3",
|
"has-[>[data-slot=checkbox-group]]:gap-3 has-[>[data-slot=radio-group]]:gap-3",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function FieldLegend({
|
function FieldLegend({
|
||||||
className,
|
className,
|
||||||
variant = "legend",
|
variant = "legend",
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<"legend"> & { variant?: "legend" | "label" }) {
|
}: React.ComponentProps<"legend"> & { variant?: "legend" | "label" }) {
|
||||||
return (
|
return (
|
||||||
<legend
|
<legend
|
||||||
data-slot="field-legend"
|
data-slot="field-legend"
|
||||||
data-variant={variant}
|
data-variant={variant}
|
||||||
className={cn(
|
className={cn(
|
||||||
"mb-3 font-medium",
|
"mb-3 font-medium",
|
||||||
"data-[variant=legend]:text-base",
|
"data-[variant=legend]:text-base",
|
||||||
"data-[variant=label]:text-sm",
|
"data-[variant=label]:text-sm",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function FieldGroup({ className, ...props }: React.ComponentProps<"div">) {
|
function FieldGroup({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
data-slot="field-group"
|
data-slot="field-group"
|
||||||
className={cn(
|
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",
|
"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
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const fieldVariants = cva(
|
const fieldVariants = cva(
|
||||||
"group/field flex w-full gap-3 data-[invalid=true]:text-destructive",
|
"group/field flex w-full gap-3 data-[invalid=true]:text-destructive",
|
||||||
{
|
{
|
||||||
variants: {
|
variants: {
|
||||||
orientation: {
|
orientation: {
|
||||||
vertical: ["flex-col [&>*]:w-full [&>.sr-only]:w-auto"],
|
vertical: ["flex-col [&>*]:w-full [&>.sr-only]:w-auto"],
|
||||||
horizontal: [
|
horizontal: [
|
||||||
"flex-row items-center",
|
"flex-row items-center",
|
||||||
"[&>[data-slot=field-label]]:flex-auto",
|
"[&>[data-slot=field-label]]:flex-auto",
|
||||||
"has-[>[data-slot=field-content]]:items-start has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
|
"has-[>[data-slot=field-content]]:items-start has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
|
||||||
],
|
],
|
||||||
responsive: [
|
responsive: [
|
||||||
"flex-col @md/field-group:flex-row @md/field-group:items-center [&>*]:w-full @md/field-group:[&>*]:w-auto [&>.sr-only]:w-auto",
|
"flex-col @md/field-group:flex-row @md/field-group:items-center [&>*]:w-full @md/field-group:[&>*]:w-auto [&>.sr-only]:w-auto",
|
||||||
"@md/field-group:[&>[data-slot=field-label]]:flex-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",
|
"@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: {
|
defaultVariants: {
|
||||||
orientation: "vertical",
|
orientation: "vertical",
|
||||||
},
|
},
|
||||||
}
|
},
|
||||||
)
|
);
|
||||||
|
|
||||||
function Field({
|
function Field({
|
||||||
className,
|
className,
|
||||||
orientation = "vertical",
|
orientation = "vertical",
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<"div"> & VariantProps<typeof fieldVariants>) {
|
}: React.ComponentProps<"fieldset"> & VariantProps<typeof fieldVariants>) {
|
||||||
return (
|
return (
|
||||||
<div
|
<fieldset
|
||||||
role="group"
|
data-slot="field"
|
||||||
data-slot="field"
|
data-orientation={orientation}
|
||||||
data-orientation={orientation}
|
className={cn(fieldVariants({ orientation }), className)}
|
||||||
className={cn(fieldVariants({ orientation }), className)}
|
{...props}
|
||||||
{...props}
|
/>
|
||||||
/>
|
);
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function FieldContent({ className, ...props }: React.ComponentProps<"div">) {
|
function FieldContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
data-slot="field-content"
|
data-slot="field-content"
|
||||||
className={cn(
|
className={cn(
|
||||||
"group/field-content flex flex-1 flex-col gap-1.5 leading-snug",
|
"group/field-content flex flex-1 flex-col gap-1.5 leading-snug",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function FieldLabel({
|
function FieldLabel({
|
||||||
className,
|
className,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof Label>) {
|
}: React.ComponentProps<typeof Label>) {
|
||||||
return (
|
return (
|
||||||
<Label
|
<Label
|
||||||
data-slot="field-label"
|
data-slot="field-label"
|
||||||
className={cn(
|
className={cn(
|
||||||
"group/field-label peer/field-label flex w-fit gap-2 leading-snug group-data-[disabled=true]/field:opacity-50",
|
"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-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]:border-primary has-data-[state=checked]:bg-primary/5 dark:has-data-[state=checked]:bg-primary/10",
|
"has-data-[state=checked]:border-primary has-data-[state=checked]:bg-primary/5 dark:has-data-[state=checked]:bg-primary/10",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function FieldTitle({ className, ...props }: React.ComponentProps<"div">) {
|
function FieldTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
data-slot="field-label"
|
data-slot="field-label"
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex w-fit items-center gap-2 text-sm leading-snug font-medium group-data-[disabled=true]/field:opacity-50",
|
"flex w-fit items-center gap-2 text-sm leading-snug font-medium group-data-[disabled=true]/field:opacity-50",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function FieldDescription({ className, ...props }: React.ComponentProps<"p">) {
|
function FieldDescription({ className, ...props }: React.ComponentProps<"p">) {
|
||||||
return (
|
return (
|
||||||
<p
|
<p
|
||||||
data-slot="field-description"
|
data-slot="field-description"
|
||||||
className={cn(
|
className={cn(
|
||||||
"text-sm leading-normal font-normal text-muted-foreground group-has-[[data-orientation=horizontal]]/field:text-balance",
|
"text-sm leading-normal font-normal text-muted-foreground group-has-[[data-orientation=horizontal]]/field:text-balance",
|
||||||
"last:mt-0 nth-last-2:-mt-1 [[data-variant=legend]+&]:-mt-1.5",
|
"last:mt-0 nth-last-2:-mt-1 [[data-variant=legend]+&]:-mt-1.5",
|
||||||
"[&>a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary",
|
"[&>a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function FieldSeparator({
|
function FieldSeparator({
|
||||||
children,
|
children,
|
||||||
className,
|
className,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<"div"> & {
|
}: React.ComponentProps<"div"> & {
|
||||||
children?: React.ReactNode
|
children?: React.ReactNode;
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
data-slot="field-separator"
|
data-slot="field-separator"
|
||||||
data-content={!!children}
|
data-content={!!children}
|
||||||
className={cn(
|
className={cn(
|
||||||
"relative -my-2 h-5 text-sm group-data-[variant=outline]/field-group:-mb-2",
|
"relative -my-2 h-5 text-sm group-data-[variant=outline]/field-group:-mb-2",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
<Separator className="absolute inset-0 top-1/2" />
|
<Separator className="absolute inset-0 top-1/2" />
|
||||||
{children && (
|
{children && (
|
||||||
<span
|
<span
|
||||||
className="relative mx-auto block w-fit bg-background px-2 text-muted-foreground"
|
className="relative mx-auto block w-fit bg-background px-2 text-muted-foreground"
|
||||||
data-slot="field-separator-content"
|
data-slot="field-separator-content"
|
||||||
>
|
>
|
||||||
{children}
|
{children}
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function FieldError({
|
function FieldError({
|
||||||
className,
|
className,
|
||||||
children,
|
children,
|
||||||
errors,
|
errors,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<"div"> & {
|
}: React.ComponentProps<"div"> & {
|
||||||
errors?: Array<{ message?: string } | undefined>
|
errors?: Array<{ message?: string } | undefined>;
|
||||||
}) {
|
}) {
|
||||||
const content = useMemo(() => {
|
const content = useMemo(() => {
|
||||||
if (children) {
|
if (children) {
|
||||||
return children
|
return children;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!errors?.length) {
|
if (!errors?.length) {
|
||||||
return null
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const uniqueErrors = [
|
const uniqueErrors = [
|
||||||
...new Map(errors.map((error) => [error?.message, error])).values(),
|
...new Map(errors.map((error) => [error?.message, error])).values(),
|
||||||
]
|
];
|
||||||
|
|
||||||
if (uniqueErrors?.length == 1) {
|
if (uniqueErrors?.length === 1) {
|
||||||
return uniqueErrors[0]?.message
|
return uniqueErrors[0]?.message;
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ul className="ml-4 flex list-disc flex-col gap-1">
|
<ul className="ml-4 flex list-disc flex-col gap-1">
|
||||||
{uniqueErrors.map(
|
{uniqueErrors.map(
|
||||||
(error, index) =>
|
(error) =>
|
||||||
error?.message && <li key={index}>{error.message}</li>
|
error?.message && <li key={error.message}>{error.message}</li>,
|
||||||
)}
|
)}
|
||||||
</ul>
|
</ul>
|
||||||
)
|
);
|
||||||
}, [children, errors])
|
}, [children, errors]);
|
||||||
|
|
||||||
if (!content) {
|
if (!content) {
|
||||||
return null
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
role="alert"
|
role="alert"
|
||||||
data-slot="field-error"
|
data-slot="field-error"
|
||||||
className={cn("text-sm font-normal text-destructive", className)}
|
className={cn("text-sm font-normal text-destructive", className)}
|
||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
{content}
|
{content}
|
||||||
</div>
|
</div>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export {
|
export {
|
||||||
Field,
|
Field,
|
||||||
FieldLabel,
|
FieldLabel,
|
||||||
FieldDescription,
|
FieldDescription,
|
||||||
FieldError,
|
FieldError,
|
||||||
FieldGroup,
|
FieldGroup,
|
||||||
FieldLegend,
|
FieldLegend,
|
||||||
FieldSeparator,
|
FieldSeparator,
|
||||||
FieldSet,
|
FieldSet,
|
||||||
FieldContent,
|
FieldContent,
|
||||||
FieldTitle,
|
FieldTitle,
|
||||||
}
|
};
|
||||||
|
|||||||
@@ -1,21 +1,21 @@
|
|||||||
import * as React from "react"
|
import type * as React from "react";
|
||||||
|
|
||||||
import { cn } from "#/lib/utils.ts"
|
import { cn } from "#/lib/utils.ts";
|
||||||
|
|
||||||
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
|
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
|
||||||
return (
|
return (
|
||||||
<input
|
<input
|
||||||
type={type}
|
type={type}
|
||||||
data-slot="input"
|
data-slot="input"
|
||||||
className={cn(
|
className={cn(
|
||||||
"h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none selection:bg-primary selection:text-primary-foreground file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm dark:bg-input/30",
|
"h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none selection:bg-primary selection:text-primary-foreground file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm dark:bg-input/30",
|
||||||
"focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50",
|
"focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50",
|
||||||
"aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40",
|
"aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export { Input }
|
export { Input };
|
||||||
|
|||||||
@@ -1,22 +1,22 @@
|
|||||||
import * as React from "react"
|
import { Label as LabelPrimitive } from "radix-ui";
|
||||||
import { Label as LabelPrimitive } from "radix-ui"
|
import type * as React from "react";
|
||||||
|
|
||||||
import { cn } from "#/lib/utils.ts"
|
import { cn } from "#/lib/utils.ts";
|
||||||
|
|
||||||
function Label({
|
function Label({
|
||||||
className,
|
className,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
|
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
|
||||||
return (
|
return (
|
||||||
<LabelPrimitive.Root
|
<LabelPrimitive.Root
|
||||||
data-slot="label"
|
data-slot="label"
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
|
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export { Label }
|
export { Label };
|
||||||
|
|||||||
@@ -1,188 +1,188 @@
|
|||||||
import * as React from "react"
|
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react";
|
||||||
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react"
|
import { Select as SelectPrimitive } from "radix-ui";
|
||||||
import { Select as SelectPrimitive } from "radix-ui"
|
import type * as React from "react";
|
||||||
|
|
||||||
import { cn } from "#/lib/utils.ts"
|
import { cn } from "#/lib/utils.ts";
|
||||||
|
|
||||||
function Select({
|
function Select({
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof SelectPrimitive.Root>) {
|
}: React.ComponentProps<typeof SelectPrimitive.Root>) {
|
||||||
return <SelectPrimitive.Root data-slot="select" {...props} />
|
return <SelectPrimitive.Root data-slot="select" {...props} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
function SelectGroup({
|
function SelectGroup({
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof SelectPrimitive.Group>) {
|
}: React.ComponentProps<typeof SelectPrimitive.Group>) {
|
||||||
return <SelectPrimitive.Group data-slot="select-group" {...props} />
|
return <SelectPrimitive.Group data-slot="select-group" {...props} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
function SelectValue({
|
function SelectValue({
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof SelectPrimitive.Value>) {
|
}: React.ComponentProps<typeof SelectPrimitive.Value>) {
|
||||||
return <SelectPrimitive.Value data-slot="select-value" {...props} />
|
return <SelectPrimitive.Value data-slot="select-value" {...props} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
function SelectTrigger({
|
function SelectTrigger({
|
||||||
className,
|
className,
|
||||||
size = "default",
|
size = "default",
|
||||||
children,
|
children,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
|
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
|
||||||
size?: "sm" | "default"
|
size?: "sm" | "default";
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<SelectPrimitive.Trigger
|
<SelectPrimitive.Trigger
|
||||||
data-slot="select-trigger"
|
data-slot="select-trigger"
|
||||||
data-size={size}
|
data-size={size}
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex w-fit items-center justify-between gap-2 rounded-md border border-input bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-[placeholder]:text-muted-foreground data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",
|
"flex w-fit items-center justify-between gap-2 rounded-md border border-input bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-[placeholder]:text-muted-foreground data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
{children}
|
{children}
|
||||||
<SelectPrimitive.Icon asChild>
|
<SelectPrimitive.Icon asChild>
|
||||||
<ChevronDownIcon className="size-4 opacity-50" />
|
<ChevronDownIcon className="size-4 opacity-50" />
|
||||||
</SelectPrimitive.Icon>
|
</SelectPrimitive.Icon>
|
||||||
</SelectPrimitive.Trigger>
|
</SelectPrimitive.Trigger>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function SelectContent({
|
function SelectContent({
|
||||||
className,
|
className,
|
||||||
children,
|
children,
|
||||||
position = "item-aligned",
|
position = "item-aligned",
|
||||||
align = "center",
|
align = "center",
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof SelectPrimitive.Content>) {
|
}: React.ComponentProps<typeof SelectPrimitive.Content>) {
|
||||||
return (
|
return (
|
||||||
<SelectPrimitive.Portal>
|
<SelectPrimitive.Portal>
|
||||||
<SelectPrimitive.Content
|
<SelectPrimitive.Content
|
||||||
data-slot="select-content"
|
data-slot="select-content"
|
||||||
className={cn(
|
className={cn(
|
||||||
"relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover text-popover-foreground shadow-md 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 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",
|
"relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover text-popover-foreground shadow-md 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 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",
|
||||||
position === "popper" &&
|
position === "popper" &&
|
||||||
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
|
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
position={position}
|
position={position}
|
||||||
align={align}
|
align={align}
|
||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
<SelectScrollUpButton />
|
<SelectScrollUpButton />
|
||||||
<SelectPrimitive.Viewport
|
<SelectPrimitive.Viewport
|
||||||
className={cn(
|
className={cn(
|
||||||
"p-1",
|
"p-1",
|
||||||
position === "popper" &&
|
position === "popper" &&
|
||||||
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"
|
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1",
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{children}
|
{children}
|
||||||
</SelectPrimitive.Viewport>
|
</SelectPrimitive.Viewport>
|
||||||
<SelectScrollDownButton />
|
<SelectScrollDownButton />
|
||||||
</SelectPrimitive.Content>
|
</SelectPrimitive.Content>
|
||||||
</SelectPrimitive.Portal>
|
</SelectPrimitive.Portal>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function SelectLabel({
|
function SelectLabel({
|
||||||
className,
|
className,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof SelectPrimitive.Label>) {
|
}: React.ComponentProps<typeof SelectPrimitive.Label>) {
|
||||||
return (
|
return (
|
||||||
<SelectPrimitive.Label
|
<SelectPrimitive.Label
|
||||||
data-slot="select-label"
|
data-slot="select-label"
|
||||||
className={cn("px-2 py-1.5 text-xs text-muted-foreground", className)}
|
className={cn("px-2 py-1.5 text-xs text-muted-foreground", className)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function SelectItem({
|
function SelectItem({
|
||||||
className,
|
className,
|
||||||
children,
|
children,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof SelectPrimitive.Item>) {
|
}: React.ComponentProps<typeof SelectPrimitive.Item>) {
|
||||||
return (
|
return (
|
||||||
<SelectPrimitive.Item
|
<SelectPrimitive.Item
|
||||||
data-slot="select-item"
|
data-slot="select-item"
|
||||||
className={cn(
|
className={cn(
|
||||||
"relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
|
"relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
<span
|
<span
|
||||||
data-slot="select-item-indicator"
|
data-slot="select-item-indicator"
|
||||||
className="absolute right-2 flex size-3.5 items-center justify-center"
|
className="absolute right-2 flex size-3.5 items-center justify-center"
|
||||||
>
|
>
|
||||||
<SelectPrimitive.ItemIndicator>
|
<SelectPrimitive.ItemIndicator>
|
||||||
<CheckIcon className="size-4" />
|
<CheckIcon className="size-4" />
|
||||||
</SelectPrimitive.ItemIndicator>
|
</SelectPrimitive.ItemIndicator>
|
||||||
</span>
|
</span>
|
||||||
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
|
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
|
||||||
</SelectPrimitive.Item>
|
</SelectPrimitive.Item>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function SelectSeparator({
|
function SelectSeparator({
|
||||||
className,
|
className,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof SelectPrimitive.Separator>) {
|
}: React.ComponentProps<typeof SelectPrimitive.Separator>) {
|
||||||
return (
|
return (
|
||||||
<SelectPrimitive.Separator
|
<SelectPrimitive.Separator
|
||||||
data-slot="select-separator"
|
data-slot="select-separator"
|
||||||
className={cn("pointer-events-none -mx-1 my-1 h-px bg-border", className)}
|
className={cn("pointer-events-none -mx-1 my-1 h-px bg-border", className)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function SelectScrollUpButton({
|
function SelectScrollUpButton({
|
||||||
className,
|
className,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
|
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
|
||||||
return (
|
return (
|
||||||
<SelectPrimitive.ScrollUpButton
|
<SelectPrimitive.ScrollUpButton
|
||||||
data-slot="select-scroll-up-button"
|
data-slot="select-scroll-up-button"
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex cursor-default items-center justify-center py-1",
|
"flex cursor-default items-center justify-center py-1",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
<ChevronUpIcon className="size-4" />
|
<ChevronUpIcon className="size-4" />
|
||||||
</SelectPrimitive.ScrollUpButton>
|
</SelectPrimitive.ScrollUpButton>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function SelectScrollDownButton({
|
function SelectScrollDownButton({
|
||||||
className,
|
className,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {
|
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {
|
||||||
return (
|
return (
|
||||||
<SelectPrimitive.ScrollDownButton
|
<SelectPrimitive.ScrollDownButton
|
||||||
data-slot="select-scroll-down-button"
|
data-slot="select-scroll-down-button"
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex cursor-default items-center justify-center py-1",
|
"flex cursor-default items-center justify-center py-1",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
<ChevronDownIcon className="size-4" />
|
<ChevronDownIcon className="size-4" />
|
||||||
</SelectPrimitive.ScrollDownButton>
|
</SelectPrimitive.ScrollDownButton>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export {
|
export {
|
||||||
Select,
|
Select,
|
||||||
SelectContent,
|
SelectContent,
|
||||||
SelectGroup,
|
SelectGroup,
|
||||||
SelectItem,
|
SelectItem,
|
||||||
SelectLabel,
|
SelectLabel,
|
||||||
SelectScrollDownButton,
|
SelectScrollDownButton,
|
||||||
SelectScrollUpButton,
|
SelectScrollUpButton,
|
||||||
SelectSeparator,
|
SelectSeparator,
|
||||||
SelectTrigger,
|
SelectTrigger,
|
||||||
SelectValue,
|
SelectValue,
|
||||||
}
|
};
|
||||||
|
|||||||
@@ -1,28 +1,28 @@
|
|||||||
"use client"
|
"use client";
|
||||||
|
|
||||||
import * as React from "react"
|
import { Separator as SeparatorPrimitive } from "radix-ui";
|
||||||
import { Separator as SeparatorPrimitive } from "radix-ui"
|
import type * as React from "react";
|
||||||
|
|
||||||
import { cn } from "#/lib/utils.ts"
|
import { cn } from "#/lib/utils.ts";
|
||||||
|
|
||||||
function Separator({
|
function Separator({
|
||||||
className,
|
className,
|
||||||
orientation = "horizontal",
|
orientation = "horizontal",
|
||||||
decorative = true,
|
decorative = true,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
|
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
|
||||||
return (
|
return (
|
||||||
<SeparatorPrimitive.Root
|
<SeparatorPrimitive.Root
|
||||||
data-slot="separator"
|
data-slot="separator"
|
||||||
decorative={decorative}
|
decorative={decorative}
|
||||||
orientation={orientation}
|
orientation={orientation}
|
||||||
className={cn(
|
className={cn(
|
||||||
"shrink-0 bg-border data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",
|
"shrink-0 bg-border data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export { Separator }
|
export { Separator };
|
||||||
|
|||||||
@@ -1,143 +1,143 @@
|
|||||||
"use client"
|
"use client";
|
||||||
|
|
||||||
import * as React from "react"
|
import { XIcon } from "lucide-react";
|
||||||
import { XIcon } from "lucide-react"
|
import { Dialog as SheetPrimitive } from "radix-ui";
|
||||||
import { Dialog as SheetPrimitive } from "radix-ui"
|
import type * as React from "react";
|
||||||
|
|
||||||
import { cn } from "#/lib/utils.ts"
|
import { cn } from "#/lib/utils.ts";
|
||||||
|
|
||||||
function Sheet({ ...props }: React.ComponentProps<typeof SheetPrimitive.Root>) {
|
function Sheet({ ...props }: React.ComponentProps<typeof SheetPrimitive.Root>) {
|
||||||
return <SheetPrimitive.Root data-slot="sheet" {...props} />
|
return <SheetPrimitive.Root data-slot="sheet" {...props} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
function SheetTrigger({
|
function SheetTrigger({
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof SheetPrimitive.Trigger>) {
|
}: React.ComponentProps<typeof SheetPrimitive.Trigger>) {
|
||||||
return <SheetPrimitive.Trigger data-slot="sheet-trigger" {...props} />
|
return <SheetPrimitive.Trigger data-slot="sheet-trigger" {...props} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
function SheetClose({
|
function SheetClose({
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof SheetPrimitive.Close>) {
|
}: React.ComponentProps<typeof SheetPrimitive.Close>) {
|
||||||
return <SheetPrimitive.Close data-slot="sheet-close" {...props} />
|
return <SheetPrimitive.Close data-slot="sheet-close" {...props} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
function SheetPortal({
|
function SheetPortal({
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof SheetPrimitive.Portal>) {
|
}: React.ComponentProps<typeof SheetPrimitive.Portal>) {
|
||||||
return <SheetPrimitive.Portal data-slot="sheet-portal" {...props} />
|
return <SheetPrimitive.Portal data-slot="sheet-portal" {...props} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
function SheetOverlay({
|
function SheetOverlay({
|
||||||
className,
|
className,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof SheetPrimitive.Overlay>) {
|
}: React.ComponentProps<typeof SheetPrimitive.Overlay>) {
|
||||||
return (
|
return (
|
||||||
<SheetPrimitive.Overlay
|
<SheetPrimitive.Overlay
|
||||||
data-slot="sheet-overlay"
|
data-slot="sheet-overlay"
|
||||||
className={cn(
|
className={cn(
|
||||||
"fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",
|
"fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function SheetContent({
|
function SheetContent({
|
||||||
className,
|
className,
|
||||||
children,
|
children,
|
||||||
side = "right",
|
side = "right",
|
||||||
showCloseButton = true,
|
showCloseButton = true,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof SheetPrimitive.Content> & {
|
}: React.ComponentProps<typeof SheetPrimitive.Content> & {
|
||||||
side?: "top" | "right" | "bottom" | "left"
|
side?: "top" | "right" | "bottom" | "left";
|
||||||
showCloseButton?: boolean
|
showCloseButton?: boolean;
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<SheetPortal>
|
<SheetPortal>
|
||||||
<SheetOverlay />
|
<SheetOverlay />
|
||||||
<SheetPrimitive.Content
|
<SheetPrimitive.Content
|
||||||
data-slot="sheet-content"
|
data-slot="sheet-content"
|
||||||
className={cn(
|
className={cn(
|
||||||
"fixed z-50 flex flex-col gap-4 bg-background shadow-lg transition ease-in-out data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:animate-in data-[state=open]:duration-500",
|
"fixed z-50 flex flex-col gap-4 bg-background shadow-lg transition ease-in-out data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:animate-in data-[state=open]:duration-500",
|
||||||
side === "right" &&
|
side === "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",
|
"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",
|
||||||
side === "left" &&
|
side === "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",
|
"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",
|
||||||
side === "top" &&
|
side === "top" &&
|
||||||
"inset-x-0 top-0 h-auto border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",
|
"inset-x-0 top-0 h-auto border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",
|
||||||
side === "bottom" &&
|
side === "bottom" &&
|
||||||
"inset-x-0 bottom-0 h-auto border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",
|
"inset-x-0 bottom-0 h-auto border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
{children}
|
{children}
|
||||||
{showCloseButton && (
|
{showCloseButton && (
|
||||||
<SheetPrimitive.Close className="absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-secondary">
|
<SheetPrimitive.Close className="absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-secondary">
|
||||||
<XIcon className="size-4" />
|
<XIcon className="size-4" />
|
||||||
<span className="sr-only">Close</span>
|
<span className="sr-only">Close</span>
|
||||||
</SheetPrimitive.Close>
|
</SheetPrimitive.Close>
|
||||||
)}
|
)}
|
||||||
</SheetPrimitive.Content>
|
</SheetPrimitive.Content>
|
||||||
</SheetPortal>
|
</SheetPortal>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function SheetHeader({ className, ...props }: React.ComponentProps<"div">) {
|
function SheetHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
data-slot="sheet-header"
|
data-slot="sheet-header"
|
||||||
className={cn("flex flex-col gap-1.5 p-4", className)}
|
className={cn("flex flex-col gap-1.5 p-4", className)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function SheetFooter({ className, ...props }: React.ComponentProps<"div">) {
|
function SheetFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
data-slot="sheet-footer"
|
data-slot="sheet-footer"
|
||||||
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
|
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function SheetTitle({
|
function SheetTitle({
|
||||||
className,
|
className,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof SheetPrimitive.Title>) {
|
}: React.ComponentProps<typeof SheetPrimitive.Title>) {
|
||||||
return (
|
return (
|
||||||
<SheetPrimitive.Title
|
<SheetPrimitive.Title
|
||||||
data-slot="sheet-title"
|
data-slot="sheet-title"
|
||||||
className={cn("font-semibold text-foreground", className)}
|
className={cn("font-semibold text-foreground", className)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function SheetDescription({
|
function SheetDescription({
|
||||||
className,
|
className,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof SheetPrimitive.Description>) {
|
}: React.ComponentProps<typeof SheetPrimitive.Description>) {
|
||||||
return (
|
return (
|
||||||
<SheetPrimitive.Description
|
<SheetPrimitive.Description
|
||||||
data-slot="sheet-description"
|
data-slot="sheet-description"
|
||||||
className={cn("text-sm text-muted-foreground", className)}
|
className={cn("text-sm text-muted-foreground", className)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export {
|
export {
|
||||||
Sheet,
|
Sheet,
|
||||||
SheetTrigger,
|
SheetTrigger,
|
||||||
SheetClose,
|
SheetClose,
|
||||||
SheetContent,
|
SheetContent,
|
||||||
SheetHeader,
|
SheetHeader,
|
||||||
SheetFooter,
|
SheetFooter,
|
||||||
SheetTitle,
|
SheetTitle,
|
||||||
SheetDescription,
|
SheetDescription,
|
||||||
}
|
};
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -1,13 +1,13 @@
|
|||||||
import { cn } from "#/lib/utils.ts"
|
import { cn } from "#/lib/utils.ts";
|
||||||
|
|
||||||
function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
|
function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
data-slot="skeleton"
|
data-slot="skeleton"
|
||||||
className={cn("animate-pulse rounded-md bg-accent", className)}
|
className={cn("animate-pulse rounded-md bg-accent", className)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export { Skeleton }
|
export { Skeleton };
|
||||||
|
|||||||
@@ -1,38 +1,38 @@
|
|||||||
import {
|
import {
|
||||||
CircleCheckIcon,
|
CircleCheckIcon,
|
||||||
InfoIcon,
|
InfoIcon,
|
||||||
Loader2Icon,
|
Loader2Icon,
|
||||||
OctagonXIcon,
|
OctagonXIcon,
|
||||||
TriangleAlertIcon,
|
TriangleAlertIcon,
|
||||||
} from "lucide-react"
|
} from "lucide-react";
|
||||||
import { useTheme } from "next-themes"
|
import { useTheme } from "next-themes";
|
||||||
import { Toaster as Sonner, type ToasterProps } from "sonner"
|
import { Toaster as Sonner, type ToasterProps } from "sonner";
|
||||||
|
|
||||||
const Toaster = ({ ...props }: ToasterProps) => {
|
const Toaster = ({ ...props }: ToasterProps) => {
|
||||||
const { theme = "system" } = useTheme()
|
const { theme = "system" } = useTheme();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Sonner
|
<Sonner
|
||||||
theme={theme as ToasterProps["theme"]}
|
theme={theme as ToasterProps["theme"]}
|
||||||
className="toaster group"
|
className="toaster group"
|
||||||
icons={{
|
icons={{
|
||||||
success: <CircleCheckIcon className="size-4" />,
|
success: <CircleCheckIcon className="size-4" />,
|
||||||
info: <InfoIcon className="size-4" />,
|
info: <InfoIcon className="size-4" />,
|
||||||
warning: <TriangleAlertIcon className="size-4" />,
|
warning: <TriangleAlertIcon className="size-4" />,
|
||||||
error: <OctagonXIcon className="size-4" />,
|
error: <OctagonXIcon className="size-4" />,
|
||||||
loading: <Loader2Icon className="size-4 animate-spin" />,
|
loading: <Loader2Icon className="size-4 animate-spin" />,
|
||||||
}}
|
}}
|
||||||
style={
|
style={
|
||||||
{
|
{
|
||||||
"--normal-bg": "var(--popover)",
|
"--normal-bg": "var(--popover)",
|
||||||
"--normal-text": "var(--popover-foreground)",
|
"--normal-text": "var(--popover-foreground)",
|
||||||
"--normal-border": "var(--border)",
|
"--normal-border": "var(--border)",
|
||||||
"--border-radius": "var(--radius)",
|
"--border-radius": "var(--radius)",
|
||||||
} as React.CSSProperties
|
} as React.CSSProperties
|
||||||
}
|
}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
};
|
||||||
|
|
||||||
export { Toaster }
|
export { Toaster };
|
||||||
|
|||||||
@@ -1,46 +1,49 @@
|
|||||||
import {Badge} from "#/components/ui/badge";
|
import { Badge } from "#/components/ui/badge";
|
||||||
import {cn} from "#/lib/utils";
|
import { cn } from "#/lib/utils";
|
||||||
|
|
||||||
type StatusBadgeProps = {
|
type StatusBadgeProps = {
|
||||||
status: string;
|
status: string;
|
||||||
label?: string;
|
label?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export function StatusBadge({status, label = status}: StatusBadgeProps) {
|
export function StatusBadge({ status, label = status }: StatusBadgeProps) {
|
||||||
return (
|
return (
|
||||||
<Badge variant="outline" className={cn("border font-semibold", statusColorClass(status))}>
|
<Badge
|
||||||
{label}
|
variant="outline"
|
||||||
</Badge>
|
className={cn("border font-semibold", statusColorClass(status))}
|
||||||
);
|
>
|
||||||
|
{label}
|
||||||
|
</Badge>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function statusColorClass(status: string) {
|
export function statusColorClass(status: string) {
|
||||||
switch (status) {
|
switch (status) {
|
||||||
case "ACTIVE":
|
case "ACTIVE":
|
||||||
case "ENABLED":
|
case "ENABLED":
|
||||||
case "IN_STOCK":
|
case "IN_STOCK":
|
||||||
case "DELIVERED":
|
case "DELIVERED":
|
||||||
case "COMPLETED":
|
case "COMPLETED":
|
||||||
return "border-emerald-200 bg-emerald-50 text-emerald-700 dark:border-emerald-900/60 dark:bg-emerald-950/50 dark:text-emerald-300";
|
return "border-emerald-200 bg-emerald-50 text-emerald-700 dark:border-emerald-900/60 dark:bg-emerald-950/50 dark:text-emerald-300";
|
||||||
case "PENDING":
|
case "PENDING":
|
||||||
case "REQUESTED":
|
case "REQUESTED":
|
||||||
case "LOW_STOCK":
|
case "LOW_STOCK":
|
||||||
return "border-amber-200 bg-amber-50 text-amber-800 dark:border-amber-900/60 dark:bg-amber-950/50 dark:text-amber-300";
|
return "border-amber-200 bg-amber-50 text-amber-800 dark:border-amber-900/60 dark:bg-amber-950/50 dark:text-amber-300";
|
||||||
case "SHIPPED":
|
case "SHIPPED":
|
||||||
case "ACCEPTED":
|
case "ACCEPTED":
|
||||||
return "border-sky-200 bg-sky-50 text-sky-700 dark:border-sky-900/60 dark:bg-sky-950/50 dark:text-sky-300";
|
return "border-sky-200 bg-sky-50 text-sky-700 dark:border-sky-900/60 dark:bg-sky-950/50 dark:text-sky-300";
|
||||||
case "ADMIN":
|
case "ADMIN":
|
||||||
return "border-violet-200 bg-violet-50 text-violet-700 dark:border-violet-900/60 dark:bg-violet-950/50 dark:text-violet-300";
|
return "border-violet-200 bg-violet-50 text-violet-700 dark:border-violet-900/60 dark:bg-violet-950/50 dark:text-violet-300";
|
||||||
case "CUSTOMER":
|
case "CUSTOMER":
|
||||||
return "border-cyan-200 bg-cyan-50 text-cyan-700 dark:border-cyan-900/60 dark:bg-cyan-950/50 dark:text-cyan-300";
|
return "border-cyan-200 bg-cyan-50 text-cyan-700 dark:border-cyan-900/60 dark:bg-cyan-950/50 dark:text-cyan-300";
|
||||||
case "DRIVER":
|
case "DRIVER":
|
||||||
return "border-indigo-200 bg-indigo-50 text-indigo-700 dark:border-indigo-900/60 dark:bg-indigo-950/50 dark:text-indigo-300";
|
return "border-indigo-200 bg-indigo-50 text-indigo-700 dark:border-indigo-900/60 dark:bg-indigo-950/50 dark:text-indigo-300";
|
||||||
case "CANCELLED":
|
case "CANCELLED":
|
||||||
case "INACTIVE":
|
case "INACTIVE":
|
||||||
case "DISABLED":
|
case "DISABLED":
|
||||||
case "OUT_OF_STOCK":
|
case "OUT_OF_STOCK":
|
||||||
return "border-red-200 bg-red-50 text-red-700 dark:border-red-900/60 dark:bg-red-950/50 dark:text-red-300";
|
return "border-red-200 bg-red-50 text-red-700 dark:border-red-900/60 dark:bg-red-950/50 dark:text-red-300";
|
||||||
default:
|
default:
|
||||||
return "border-border bg-muted text-muted-foreground";
|
return "border-border bg-muted text-muted-foreground";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,114 +1,114 @@
|
|||||||
import * as React from "react"
|
import type * as React from "react";
|
||||||
|
|
||||||
import { cn } from "#/lib/utils.ts"
|
import { cn } from "#/lib/utils.ts";
|
||||||
|
|
||||||
function Table({ className, ...props }: React.ComponentProps<"table">) {
|
function Table({ className, ...props }: React.ComponentProps<"table">) {
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
data-slot="table-container"
|
data-slot="table-container"
|
||||||
className="relative w-full overflow-x-auto"
|
className="relative w-full overflow-x-auto"
|
||||||
>
|
>
|
||||||
<table
|
<table
|
||||||
data-slot="table"
|
data-slot="table"
|
||||||
className={cn("w-full caption-bottom text-sm", className)}
|
className={cn("w-full caption-bottom text-sm", className)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
|
function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
|
||||||
return (
|
return (
|
||||||
<thead
|
<thead
|
||||||
data-slot="table-header"
|
data-slot="table-header"
|
||||||
className={cn("[&_tr]:border-b", className)}
|
className={cn("[&_tr]:border-b", className)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
|
function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
|
||||||
return (
|
return (
|
||||||
<tbody
|
<tbody
|
||||||
data-slot="table-body"
|
data-slot="table-body"
|
||||||
className={cn("[&_tr:last-child]:border-0", className)}
|
className={cn("[&_tr:last-child]:border-0", className)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
|
function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
|
||||||
return (
|
return (
|
||||||
<tfoot
|
<tfoot
|
||||||
data-slot="table-footer"
|
data-slot="table-footer"
|
||||||
className={cn(
|
className={cn(
|
||||||
"border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",
|
"border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
|
function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
|
||||||
return (
|
return (
|
||||||
<tr
|
<tr
|
||||||
data-slot="table-row"
|
data-slot="table-row"
|
||||||
className={cn(
|
className={cn(
|
||||||
"border-b transition-colors hover:bg-muted/50 has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted",
|
"border-b transition-colors hover:bg-muted/50 has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function TableHead({ className, ...props }: React.ComponentProps<"th">) {
|
function TableHead({ className, ...props }: React.ComponentProps<"th">) {
|
||||||
return (
|
return (
|
||||||
<th
|
<th
|
||||||
data-slot="table-head"
|
data-slot="table-head"
|
||||||
className={cn(
|
className={cn(
|
||||||
"h-10 px-2 text-left align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
|
"h-10 px-2 text-left align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function TableCell({ className, ...props }: React.ComponentProps<"td">) {
|
function TableCell({ className, ...props }: React.ComponentProps<"td">) {
|
||||||
return (
|
return (
|
||||||
<td
|
<td
|
||||||
data-slot="table-cell"
|
data-slot="table-cell"
|
||||||
className={cn(
|
className={cn(
|
||||||
"p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
|
"p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function TableCaption({
|
function TableCaption({
|
||||||
className,
|
className,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<"caption">) {
|
}: React.ComponentProps<"caption">) {
|
||||||
return (
|
return (
|
||||||
<caption
|
<caption
|
||||||
data-slot="table-caption"
|
data-slot="table-caption"
|
||||||
className={cn("mt-4 text-sm text-muted-foreground", className)}
|
className={cn("mt-4 text-sm text-muted-foreground", className)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export {
|
export {
|
||||||
Table,
|
Table,
|
||||||
TableHeader,
|
TableHeader,
|
||||||
TableBody,
|
TableBody,
|
||||||
TableFooter,
|
TableFooter,
|
||||||
TableHead,
|
TableHead,
|
||||||
TableRow,
|
TableRow,
|
||||||
TableCell,
|
TableCell,
|
||||||
TableCaption,
|
TableCaption,
|
||||||
}
|
};
|
||||||
|
|||||||
@@ -1,91 +1,91 @@
|
|||||||
"use client"
|
"use client";
|
||||||
|
|
||||||
import * as React from "react"
|
import { cva, type VariantProps } from "class-variance-authority";
|
||||||
import { cva, type VariantProps } from "class-variance-authority"
|
import { Tabs as TabsPrimitive } from "radix-ui";
|
||||||
import { Tabs as TabsPrimitive } from "radix-ui"
|
import type * as React from "react";
|
||||||
|
|
||||||
import { cn } from "#/lib/utils.ts"
|
import { cn } from "#/lib/utils.ts";
|
||||||
|
|
||||||
function Tabs({
|
function Tabs({
|
||||||
className,
|
className,
|
||||||
orientation = "horizontal",
|
orientation = "horizontal",
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof TabsPrimitive.Root>) {
|
}: React.ComponentProps<typeof TabsPrimitive.Root>) {
|
||||||
return (
|
return (
|
||||||
<TabsPrimitive.Root
|
<TabsPrimitive.Root
|
||||||
data-slot="tabs"
|
data-slot="tabs"
|
||||||
data-orientation={orientation}
|
data-orientation={orientation}
|
||||||
orientation={orientation}
|
orientation={orientation}
|
||||||
className={cn(
|
className={cn(
|
||||||
"group/tabs flex gap-2 data-[orientation=horizontal]:flex-col",
|
"group/tabs flex gap-2 data-[orientation=horizontal]:flex-col",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const tabsListVariants = cva(
|
const tabsListVariants = cva(
|
||||||
"group/tabs-list inline-flex w-fit items-center justify-center rounded-lg p-[3px] text-muted-foreground group-data-[orientation=horizontal]/tabs:h-9 group-data-[orientation=vertical]/tabs:h-fit group-data-[orientation=vertical]/tabs:flex-col data-[variant=line]:rounded-none",
|
"group/tabs-list inline-flex w-fit items-center justify-center rounded-lg p-[3px] text-muted-foreground group-data-[orientation=horizontal]/tabs:h-9 group-data-[orientation=vertical]/tabs:h-fit group-data-[orientation=vertical]/tabs:flex-col data-[variant=line]:rounded-none",
|
||||||
{
|
{
|
||||||
variants: {
|
variants: {
|
||||||
variant: {
|
variant: {
|
||||||
default: "bg-muted",
|
default: "bg-muted",
|
||||||
line: "gap-1 bg-transparent",
|
line: "gap-1 bg-transparent",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
defaultVariants: {
|
defaultVariants: {
|
||||||
variant: "default",
|
variant: "default",
|
||||||
},
|
},
|
||||||
}
|
},
|
||||||
)
|
);
|
||||||
|
|
||||||
function TabsList({
|
function TabsList({
|
||||||
className,
|
className,
|
||||||
variant = "default",
|
variant = "default",
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof TabsPrimitive.List> &
|
}: React.ComponentProps<typeof TabsPrimitive.List> &
|
||||||
VariantProps<typeof tabsListVariants>) {
|
VariantProps<typeof tabsListVariants>) {
|
||||||
return (
|
return (
|
||||||
<TabsPrimitive.List
|
<TabsPrimitive.List
|
||||||
data-slot="tabs-list"
|
data-slot="tabs-list"
|
||||||
data-variant={variant}
|
data-variant={variant}
|
||||||
className={cn(tabsListVariants({ variant }), className)}
|
className={cn(tabsListVariants({ variant }), className)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function TabsTrigger({
|
function TabsTrigger({
|
||||||
className,
|
className,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof TabsPrimitive.Trigger>) {
|
}: React.ComponentProps<typeof TabsPrimitive.Trigger>) {
|
||||||
return (
|
return (
|
||||||
<TabsPrimitive.Trigger
|
<TabsPrimitive.Trigger
|
||||||
data-slot="tabs-trigger"
|
data-slot="tabs-trigger"
|
||||||
className={cn(
|
className={cn(
|
||||||
"relative inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap text-foreground/60 transition-all group-data-[orientation=vertical]/tabs:w-full group-data-[orientation=vertical]/tabs:justify-start hover:text-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1 focus-visible:outline-ring disabled:pointer-events-none disabled:opacity-50 group-data-[variant=default]/tabs-list:data-[state=active]:shadow-sm group-data-[variant=line]/tabs-list:data-[state=active]:shadow-none dark:text-muted-foreground dark:hover:text-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
"relative inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap text-foreground/60 transition-all group-data-[orientation=vertical]/tabs:w-full group-data-[orientation=vertical]/tabs:justify-start hover:text-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1 focus-visible:outline-ring disabled:pointer-events-none disabled:opacity-50 group-data-[variant=default]/tabs-list:data-[state=active]:shadow-sm group-data-[variant=line]/tabs-list:data-[state=active]:shadow-none dark:text-muted-foreground dark:hover:text-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
"group-data-[variant=line]/tabs-list:bg-transparent group-data-[variant=line]/tabs-list:data-[state=active]:bg-transparent dark:group-data-[variant=line]/tabs-list:data-[state=active]:border-transparent dark:group-data-[variant=line]/tabs-list:data-[state=active]:bg-transparent",
|
"group-data-[variant=line]/tabs-list:bg-transparent group-data-[variant=line]/tabs-list:data-[state=active]:bg-transparent dark:group-data-[variant=line]/tabs-list:data-[state=active]:border-transparent dark:group-data-[variant=line]/tabs-list:data-[state=active]:bg-transparent",
|
||||||
"data-[state=active]:bg-background data-[state=active]:text-foreground dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 dark:data-[state=active]:text-foreground",
|
"data-[state=active]:bg-background data-[state=active]:text-foreground dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 dark:data-[state=active]:text-foreground",
|
||||||
"after:absolute after:bg-foreground after:opacity-0 after:transition-opacity group-data-[orientation=horizontal]/tabs:after:inset-x-0 group-data-[orientation=horizontal]/tabs:after:bottom-[-5px] group-data-[orientation=horizontal]/tabs:after:h-0.5 group-data-[orientation=vertical]/tabs:after:inset-y-0 group-data-[orientation=vertical]/tabs:after:-right-1 group-data-[orientation=vertical]/tabs:after:w-0.5 group-data-[variant=line]/tabs-list:data-[state=active]:after:opacity-100",
|
"after:absolute after:bg-foreground after:opacity-0 after:transition-opacity group-data-[orientation=horizontal]/tabs:after:inset-x-0 group-data-[orientation=horizontal]/tabs:after:bottom-[-5px] group-data-[orientation=horizontal]/tabs:after:h-0.5 group-data-[orientation=vertical]/tabs:after:inset-y-0 group-data-[orientation=vertical]/tabs:after:-right-1 group-data-[orientation=vertical]/tabs:after:w-0.5 group-data-[variant=line]/tabs-list:data-[state=active]:after:opacity-100",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function TabsContent({
|
function TabsContent({
|
||||||
className,
|
className,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof TabsPrimitive.Content>) {
|
}: React.ComponentProps<typeof TabsPrimitive.Content>) {
|
||||||
return (
|
return (
|
||||||
<TabsPrimitive.Content
|
<TabsPrimitive.Content
|
||||||
data-slot="tabs-content"
|
data-slot="tabs-content"
|
||||||
className={cn("flex-1 outline-none", className)}
|
className={cn("flex-1 outline-none", className)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export { Tabs, TabsList, TabsTrigger, TabsContent, tabsListVariants }
|
export { Tabs, TabsList, TabsTrigger, TabsContent, tabsListVariants };
|
||||||
|
|||||||
@@ -1,83 +1,82 @@
|
|||||||
"use client"
|
"use client";
|
||||||
|
|
||||||
import * as React from "react"
|
import type { VariantProps } from "class-variance-authority";
|
||||||
import { type VariantProps } from "class-variance-authority"
|
import { ToggleGroup as ToggleGroupPrimitive } from "radix-ui";
|
||||||
import { ToggleGroup as ToggleGroupPrimitive } from "radix-ui"
|
import * as React from "react";
|
||||||
|
import { toggleVariants } from "#/components/ui/toggle.tsx";
|
||||||
import { cn } from "#/lib/utils.ts"
|
import { cn } from "#/lib/utils.ts";
|
||||||
import { toggleVariants } from "#/components/ui/toggle.tsx"
|
|
||||||
|
|
||||||
const ToggleGroupContext = React.createContext<
|
const ToggleGroupContext = React.createContext<
|
||||||
VariantProps<typeof toggleVariants> & {
|
VariantProps<typeof toggleVariants> & {
|
||||||
spacing?: number
|
spacing?: number;
|
||||||
}
|
}
|
||||||
>({
|
>({
|
||||||
size: "default",
|
size: "default",
|
||||||
variant: "default",
|
variant: "default",
|
||||||
spacing: 0,
|
spacing: 0,
|
||||||
})
|
});
|
||||||
|
|
||||||
function ToggleGroup({
|
function ToggleGroup({
|
||||||
className,
|
className,
|
||||||
variant,
|
variant,
|
||||||
size,
|
size,
|
||||||
spacing = 0,
|
spacing = 0,
|
||||||
children,
|
children,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof ToggleGroupPrimitive.Root> &
|
}: React.ComponentProps<typeof ToggleGroupPrimitive.Root> &
|
||||||
VariantProps<typeof toggleVariants> & {
|
VariantProps<typeof toggleVariants> & {
|
||||||
spacing?: number
|
spacing?: number;
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<ToggleGroupPrimitive.Root
|
<ToggleGroupPrimitive.Root
|
||||||
data-slot="toggle-group"
|
data-slot="toggle-group"
|
||||||
data-variant={variant}
|
data-variant={variant}
|
||||||
data-size={size}
|
data-size={size}
|
||||||
data-spacing={spacing}
|
data-spacing={spacing}
|
||||||
style={{ "--gap": spacing } as React.CSSProperties}
|
style={{ "--gap": spacing } as React.CSSProperties}
|
||||||
className={cn(
|
className={cn(
|
||||||
"group/toggle-group flex w-fit items-center gap-[--spacing(var(--gap))] rounded-md data-[spacing=default]:data-[variant=outline]:shadow-xs",
|
"group/toggle-group flex w-fit items-center gap-[--spacing(var(--gap))] rounded-md data-[spacing=default]:data-[variant=outline]:shadow-xs",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
<ToggleGroupContext.Provider value={{ variant, size, spacing }}>
|
<ToggleGroupContext.Provider value={{ variant, size, spacing }}>
|
||||||
{children}
|
{children}
|
||||||
</ToggleGroupContext.Provider>
|
</ToggleGroupContext.Provider>
|
||||||
</ToggleGroupPrimitive.Root>
|
</ToggleGroupPrimitive.Root>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function ToggleGroupItem({
|
function ToggleGroupItem({
|
||||||
className,
|
className,
|
||||||
children,
|
children,
|
||||||
variant,
|
variant,
|
||||||
size,
|
size,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof ToggleGroupPrimitive.Item> &
|
}: React.ComponentProps<typeof ToggleGroupPrimitive.Item> &
|
||||||
VariantProps<typeof toggleVariants>) {
|
VariantProps<typeof toggleVariants>) {
|
||||||
const context = React.useContext(ToggleGroupContext)
|
const context = React.useContext(ToggleGroupContext);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ToggleGroupPrimitive.Item
|
<ToggleGroupPrimitive.Item
|
||||||
data-slot="toggle-group-item"
|
data-slot="toggle-group-item"
|
||||||
data-variant={context.variant || variant}
|
data-variant={context.variant || variant}
|
||||||
data-size={context.size || size}
|
data-size={context.size || size}
|
||||||
data-spacing={context.spacing}
|
data-spacing={context.spacing}
|
||||||
className={cn(
|
className={cn(
|
||||||
toggleVariants({
|
toggleVariants({
|
||||||
variant: context.variant || variant,
|
variant: context.variant || variant,
|
||||||
size: context.size || size,
|
size: context.size || size,
|
||||||
}),
|
}),
|
||||||
"w-auto min-w-0 shrink-0 px-3 focus:z-10 focus-visible:z-10",
|
"w-auto min-w-0 shrink-0 px-3 focus:z-10 focus-visible:z-10",
|
||||||
"data-[spacing=0]:rounded-none data-[spacing=0]:shadow-none data-[spacing=0]:first:rounded-l-md data-[spacing=0]:last:rounded-r-md data-[spacing=0]:data-[variant=outline]:border-l-0 data-[spacing=0]:data-[variant=outline]:first:border-l",
|
"data-[spacing=0]:rounded-none data-[spacing=0]:shadow-none data-[spacing=0]:first:rounded-l-md data-[spacing=0]:last:rounded-r-md data-[spacing=0]:data-[variant=outline]:border-l-0 data-[spacing=0]:data-[variant=outline]:first:border-l",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
{children}
|
{children}
|
||||||
</ToggleGroupPrimitive.Item>
|
</ToggleGroupPrimitive.Item>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export { ToggleGroup, ToggleGroupItem }
|
export { ToggleGroup, ToggleGroupItem };
|
||||||
|
|||||||
@@ -1,47 +1,47 @@
|
|||||||
"use client"
|
"use client";
|
||||||
|
|
||||||
import * as React from "react"
|
import { cva, type VariantProps } from "class-variance-authority";
|
||||||
import { cva, type VariantProps } from "class-variance-authority"
|
import { Toggle as TogglePrimitive } from "radix-ui";
|
||||||
import { Toggle as TogglePrimitive } from "radix-ui"
|
import type * as React from "react";
|
||||||
|
|
||||||
import { cn } from "#/lib/utils.ts"
|
import { cn } from "#/lib/utils.ts";
|
||||||
|
|
||||||
const toggleVariants = cva(
|
const toggleVariants = cva(
|
||||||
"inline-flex items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-[color,box-shadow] outline-none hover:bg-muted hover:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
"inline-flex items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-[color,box-shadow] outline-none hover:bg-muted hover:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
{
|
{
|
||||||
variants: {
|
variants: {
|
||||||
variant: {
|
variant: {
|
||||||
default: "bg-transparent",
|
default: "bg-transparent",
|
||||||
outline:
|
outline:
|
||||||
"border border-input bg-transparent shadow-xs hover:bg-accent hover:text-accent-foreground",
|
"border border-input bg-transparent shadow-xs hover:bg-accent hover:text-accent-foreground",
|
||||||
},
|
},
|
||||||
size: {
|
size: {
|
||||||
default: "h-9 min-w-9 px-2",
|
default: "h-9 min-w-9 px-2",
|
||||||
sm: "h-8 min-w-8 px-1.5",
|
sm: "h-8 min-w-8 px-1.5",
|
||||||
lg: "h-10 min-w-10 px-2.5",
|
lg: "h-10 min-w-10 px-2.5",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
defaultVariants: {
|
defaultVariants: {
|
||||||
variant: "default",
|
variant: "default",
|
||||||
size: "default",
|
size: "default",
|
||||||
},
|
},
|
||||||
}
|
},
|
||||||
)
|
);
|
||||||
|
|
||||||
function Toggle({
|
function Toggle({
|
||||||
className,
|
className,
|
||||||
variant,
|
variant,
|
||||||
size,
|
size,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof TogglePrimitive.Root> &
|
}: React.ComponentProps<typeof TogglePrimitive.Root> &
|
||||||
VariantProps<typeof toggleVariants>) {
|
VariantProps<typeof toggleVariants>) {
|
||||||
return (
|
return (
|
||||||
<TogglePrimitive.Root
|
<TogglePrimitive.Root
|
||||||
data-slot="toggle"
|
data-slot="toggle"
|
||||||
className={cn(toggleVariants({ variant, size, className }))}
|
className={cn(toggleVariants({ variant, size, className }))}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export { Toggle, toggleVariants }
|
export { Toggle, toggleVariants };
|
||||||
|
|||||||
@@ -1,55 +1,55 @@
|
|||||||
import * as React from "react"
|
import { Tooltip as TooltipPrimitive } from "radix-ui";
|
||||||
import { Tooltip as TooltipPrimitive } from "radix-ui"
|
import type * as React from "react";
|
||||||
|
|
||||||
import { cn } from "#/lib/utils.ts"
|
import { cn } from "#/lib/utils.ts";
|
||||||
|
|
||||||
function TooltipProvider({
|
function TooltipProvider({
|
||||||
delayDuration = 0,
|
delayDuration = 0,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
|
}: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
|
||||||
return (
|
return (
|
||||||
<TooltipPrimitive.Provider
|
<TooltipPrimitive.Provider
|
||||||
data-slot="tooltip-provider"
|
data-slot="tooltip-provider"
|
||||||
delayDuration={delayDuration}
|
delayDuration={delayDuration}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function Tooltip({
|
function Tooltip({
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof TooltipPrimitive.Root>) {
|
}: React.ComponentProps<typeof TooltipPrimitive.Root>) {
|
||||||
return <TooltipPrimitive.Root data-slot="tooltip" {...props} />
|
return <TooltipPrimitive.Root data-slot="tooltip" {...props} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
function TooltipTrigger({
|
function TooltipTrigger({
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
|
}: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
|
||||||
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />
|
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
function TooltipContent({
|
function TooltipContent({
|
||||||
className,
|
className,
|
||||||
sideOffset = 0,
|
sideOffset = 0,
|
||||||
children,
|
children,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof TooltipPrimitive.Content>) {
|
}: React.ComponentProps<typeof TooltipPrimitive.Content>) {
|
||||||
return (
|
return (
|
||||||
<TooltipPrimitive.Portal>
|
<TooltipPrimitive.Portal>
|
||||||
<TooltipPrimitive.Content
|
<TooltipPrimitive.Content
|
||||||
data-slot="tooltip-content"
|
data-slot="tooltip-content"
|
||||||
sideOffset={sideOffset}
|
sideOffset={sideOffset}
|
||||||
className={cn(
|
className={cn(
|
||||||
"z-50 w-fit origin-(--radix-tooltip-content-transform-origin) animate-in rounded-md bg-foreground px-3 py-1.5 text-xs text-balance text-background fade-in-0 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 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95",
|
"z-50 w-fit origin-(--radix-tooltip-content-transform-origin) animate-in rounded-md bg-foreground px-3 py-1.5 text-xs text-balance text-background fade-in-0 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 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
{children}
|
{children}
|
||||||
<TooltipPrimitive.Arrow className="z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground" />
|
<TooltipPrimitive.Arrow className="z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground" />
|
||||||
</TooltipPrimitive.Content>
|
</TooltipPrimitive.Content>
|
||||||
</TooltipPrimitive.Portal>
|
</TooltipPrimitive.Portal>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }
|
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider };
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
export function formatCurrency(amount: number, currency = "KES") {
|
export function formatCurrency(amount: number, currency = "KES") {
|
||||||
return new Intl.NumberFormat("en-KE", {
|
return new Intl.NumberFormat("en-KE", {
|
||||||
style: "currency",
|
style: "currency",
|
||||||
currency,
|
currency,
|
||||||
maximumFractionDigits: 2,
|
maximumFractionDigits: 2,
|
||||||
}).format(amount);
|
}).format(amount);
|
||||||
}
|
}
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
export function formatDate(value: string | null | undefined) {
|
export function formatDate(value: string | null | undefined) {
|
||||||
if (!value) {
|
if (!value) {
|
||||||
return "—";
|
return "—";
|
||||||
}
|
}
|
||||||
|
|
||||||
return new Intl.DateTimeFormat("en-KE", {
|
return new Intl.DateTimeFormat("en-KE", {
|
||||||
dateStyle: "medium",
|
dateStyle: "medium",
|
||||||
timeStyle: "short",
|
timeStyle: "short",
|
||||||
}).format(new Date(value));
|
}).format(new Date(value));
|
||||||
}
|
}
|
||||||
@@ -1,19 +1,21 @@
|
|||||||
import * as React from "react"
|
import * as React from "react";
|
||||||
|
|
||||||
const MOBILE_BREAKPOINT = 768
|
const MOBILE_BREAKPOINT = 768;
|
||||||
|
|
||||||
export function useIsMobile() {
|
export function useIsMobile() {
|
||||||
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined)
|
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(
|
||||||
|
undefined,
|
||||||
|
);
|
||||||
|
|
||||||
React.useEffect(() => {
|
React.useEffect(() => {
|
||||||
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`)
|
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
|
||||||
const onChange = () => {
|
const onChange = () => {
|
||||||
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
|
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
|
||||||
}
|
};
|
||||||
mql.addEventListener("change", onChange)
|
mql.addEventListener("change", onChange);
|
||||||
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
|
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
|
||||||
return () => mql.removeEventListener("change", onChange)
|
return () => mql.removeEventListener("change", onChange);
|
||||||
}, [])
|
}, []);
|
||||||
|
|
||||||
return !!isMobile
|
return !!isMobile;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,111 +1,111 @@
|
|||||||
import {login, logout, register} from "#/api/auth";
|
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
import type {AuthUser, LoginRequest, RegisterRequest} from "#/types/auth";
|
import { createContext, useContext, useState } from "react";
|
||||||
import {useMutation, useQueryClient} from "@tanstack/react-query";
|
import { login, logout, register } from "#/api/auth";
|
||||||
import {createContext, useContext, useState} from "react";
|
import type { AuthUser, LoginRequest, RegisterRequest } from "#/types/auth";
|
||||||
|
|
||||||
type AuthContextValue = {
|
type AuthContextValue = {
|
||||||
user: AuthUser | null;
|
user: AuthUser | null;
|
||||||
isLoading: boolean;
|
isLoading: boolean;
|
||||||
login: (request: LoginRequest) => Promise<AuthUser>;
|
login: (request: LoginRequest) => Promise<AuthUser>;
|
||||||
register: (request: RegisterRequest) => Promise<AuthUser>;
|
register: (request: RegisterRequest) => Promise<AuthUser>;
|
||||||
logout: () => Promise<void>;
|
logout: () => Promise<void>;
|
||||||
};
|
};
|
||||||
|
|
||||||
const AuthContext = createContext<AuthContextValue | null>(null);
|
const AuthContext = createContext<AuthContextValue | null>(null);
|
||||||
const storedUserKey = "cymelle.auth.user";
|
const storedUserKey = "cymelle.auth.user";
|
||||||
|
|
||||||
export const authQueryKeys = {
|
export const authQueryKeys = {
|
||||||
me: ["auth", "me"] as const,
|
me: ["auth", "me"] as const,
|
||||||
};
|
};
|
||||||
|
|
||||||
export function AuthProvider({children}: {children: React.ReactNode}) {
|
export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
const [user, setUser] = useState<AuthUser | null>(() => readStoredUser());
|
const [user, setUser] = useState<AuthUser | null>(() => readStoredUser());
|
||||||
|
|
||||||
const loginMutation = useMutation({
|
const loginMutation = useMutation({
|
||||||
mutationFn: login,
|
mutationFn: login,
|
||||||
onSuccess: (user) => {
|
onSuccess: (user) => {
|
||||||
queryClient.clear();
|
queryClient.clear();
|
||||||
persistUser(user);
|
persistUser(user);
|
||||||
setUser(user);
|
setUser(user);
|
||||||
queryClient.setQueryData(authQueryKeys.me, user);
|
queryClient.setQueryData(authQueryKeys.me, user);
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const registerMutation = useMutation({
|
const registerMutation = useMutation({
|
||||||
mutationFn: register,
|
mutationFn: register,
|
||||||
onSuccess: (user) => {
|
onSuccess: (user) => {
|
||||||
queryClient.clear();
|
queryClient.clear();
|
||||||
persistUser(user);
|
persistUser(user);
|
||||||
setUser(user);
|
setUser(user);
|
||||||
queryClient.setQueryData(authQueryKeys.me, user);
|
queryClient.setQueryData(authQueryKeys.me, user);
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const logoutMutation = useMutation({
|
const logoutMutation = useMutation({
|
||||||
mutationFn: logout,
|
mutationFn: logout,
|
||||||
onSettled: () => {
|
onSettled: () => {
|
||||||
persistUser(null);
|
persistUser(null);
|
||||||
setUser(null);
|
setUser(null);
|
||||||
queryClient.clear();
|
queryClient.clear();
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
async function logoutUser() {
|
async function logoutUser() {
|
||||||
persistUser(null);
|
persistUser(null);
|
||||||
setUser(null);
|
setUser(null);
|
||||||
queryClient.clear();
|
queryClient.clear();
|
||||||
await logoutMutation.mutateAsync().catch(() => undefined);
|
await logoutMutation.mutateAsync().catch(() => undefined);
|
||||||
}
|
}
|
||||||
|
|
||||||
const value: AuthContextValue = {
|
const value: AuthContextValue = {
|
||||||
user,
|
user,
|
||||||
isLoading: false,
|
isLoading: false,
|
||||||
login: loginMutation.mutateAsync,
|
login: loginMutation.mutateAsync,
|
||||||
register: registerMutation.mutateAsync,
|
register: registerMutation.mutateAsync,
|
||||||
logout: logoutUser,
|
logout: logoutUser,
|
||||||
};
|
};
|
||||||
|
|
||||||
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
|
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useAuth() {
|
export function useAuth() {
|
||||||
const context = useContext(AuthContext);
|
const context = useContext(AuthContext);
|
||||||
|
|
||||||
if (!context) {
|
if (!context) {
|
||||||
throw new Error("useAuth must be used within AuthProvider");
|
throw new Error("useAuth must be used within AuthProvider");
|
||||||
}
|
}
|
||||||
|
|
||||||
return context;
|
return context;
|
||||||
}
|
}
|
||||||
|
|
||||||
function readStoredUser() {
|
function readStoredUser() {
|
||||||
if (typeof window === "undefined") {
|
if (typeof window === "undefined") {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const raw = window.localStorage.getItem(storedUserKey);
|
const raw = window.localStorage.getItem(storedUserKey);
|
||||||
if (!raw) {
|
if (!raw) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
return JSON.parse(raw) as AuthUser;
|
return JSON.parse(raw) as AuthUser;
|
||||||
} catch {
|
} catch {
|
||||||
window.localStorage.removeItem(storedUserKey);
|
window.localStorage.removeItem(storedUserKey);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function persistUser(user: AuthUser | null) {
|
function persistUser(user: AuthUser | null) {
|
||||||
if (typeof window === "undefined") {
|
if (typeof window === "undefined") {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!user) {
|
if (!user) {
|
||||||
window.localStorage.removeItem(storedUserKey);
|
window.localStorage.removeItem(storedUserKey);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
window.localStorage.setItem(storedUserKey, JSON.stringify(user));
|
window.localStorage.setItem(storedUserKey, JSON.stringify(user));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,121 +1,140 @@
|
|||||||
import type {Product} from "#/types/product";
|
import { createContext, useContext, useEffect, useMemo, useState } from "react";
|
||||||
import {createContext, useContext, useEffect, useMemo, useState} from "react";
|
import type { Product } from "#/types/product";
|
||||||
|
|
||||||
export type CartItem = {
|
export type CartItem = {
|
||||||
product: Product;
|
product: Product;
|
||||||
quantity: number;
|
quantity: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
type CartContextValue = {
|
type CartContextValue = {
|
||||||
items: CartItem[];
|
items: CartItem[];
|
||||||
itemCount: number;
|
itemCount: number;
|
||||||
totalAmount: number;
|
totalAmount: number;
|
||||||
currency: string;
|
currency: string;
|
||||||
addItem: (product: Product, quantity: number) => void;
|
addItem: (product: Product, quantity: number) => void;
|
||||||
updateQuantity: (productId: string, quantity: number) => void;
|
updateQuantity: (productId: string, quantity: number) => void;
|
||||||
removeItem: (productId: string) => void;
|
removeItem: (productId: string) => void;
|
||||||
clearCart: () => void;
|
clearCart: () => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
const CartContext = createContext<CartContextValue | null>(null);
|
const CartContext = createContext<CartContextValue | null>(null);
|
||||||
const CART_STORAGE_KEY = "cymelle_cart";
|
const CART_STORAGE_KEY = "cymelle_cart";
|
||||||
|
|
||||||
export function CartProvider({children}: {children: React.ReactNode}) {
|
export function CartProvider({ children }: { children: React.ReactNode }) {
|
||||||
const [items, setItems] = useState<CartItem[]>(() => {
|
const [items, setItems] = useState<CartItem[]>(() => {
|
||||||
if (typeof window === "undefined") {
|
if (typeof window === "undefined") {
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
return JSON.parse(window.localStorage.getItem(CART_STORAGE_KEY) ?? "[]") as CartItem[];
|
return JSON.parse(
|
||||||
} catch {
|
window.localStorage.getItem(CART_STORAGE_KEY) ?? "[]",
|
||||||
return [];
|
) as CartItem[];
|
||||||
}
|
} catch {
|
||||||
});
|
return [];
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
const itemCount = useMemo(
|
const itemCount = useMemo(
|
||||||
() => items.reduce((total, item) => total + item.quantity, 0),
|
() => items.reduce((total, item) => total + item.quantity, 0),
|
||||||
[items],
|
[items],
|
||||||
);
|
);
|
||||||
|
|
||||||
const totalAmount = useMemo(
|
const totalAmount = useMemo(
|
||||||
() => items.reduce((total, item) => total + item.product.price * item.quantity, 0),
|
() =>
|
||||||
[items],
|
items.reduce(
|
||||||
);
|
(total, item) => total + item.product.price * item.quantity,
|
||||||
|
0,
|
||||||
|
),
|
||||||
|
[items],
|
||||||
|
);
|
||||||
|
|
||||||
const currency = items[0]?.product.currency ?? "KES";
|
const currency = items[0]?.product.currency ?? "KES";
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
window.localStorage.setItem(CART_STORAGE_KEY, JSON.stringify(items));
|
window.localStorage.setItem(CART_STORAGE_KEY, JSON.stringify(items));
|
||||||
}, [items]);
|
}, [items]);
|
||||||
|
|
||||||
function addItem(product: Product, quantity: number) {
|
function addItem(product: Product, quantity: number) {
|
||||||
const safeQuantity = Math.min(Math.max(quantity, 1), product.availableQuantity);
|
const safeQuantity = Math.min(
|
||||||
|
Math.max(quantity, 1),
|
||||||
|
product.availableQuantity,
|
||||||
|
);
|
||||||
|
|
||||||
setItems((currentItems) => {
|
setItems((currentItems) => {
|
||||||
const existing = currentItems.find((item) => item.product.id === product.id);
|
const existing = currentItems.find(
|
||||||
|
(item) => item.product.id === product.id,
|
||||||
|
);
|
||||||
|
|
||||||
if (existing) {
|
if (existing) {
|
||||||
return currentItems.map((item) =>
|
return currentItems.map((item) =>
|
||||||
item.product.id === product.id
|
item.product.id === product.id
|
||||||
? {
|
? {
|
||||||
...item,
|
...item,
|
||||||
product,
|
product,
|
||||||
quantity: Math.min(item.quantity + safeQuantity, product.availableQuantity),
|
quantity: Math.min(
|
||||||
}
|
item.quantity + safeQuantity,
|
||||||
: item,
|
product.availableQuantity,
|
||||||
);
|
),
|
||||||
}
|
}
|
||||||
|
: item,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return [...currentItems, {product, quantity: safeQuantity}];
|
return [...currentItems, { product, quantity: safeQuantity }];
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function updateQuantity(productId: string, quantity: number) {
|
function updateQuantity(productId: string, quantity: number) {
|
||||||
setItems((currentItems) =>
|
setItems((currentItems) =>
|
||||||
currentItems.flatMap((item) => {
|
currentItems.flatMap((item) => {
|
||||||
if (item.product.id !== productId) {
|
if (item.product.id !== productId) {
|
||||||
return [item];
|
return [item];
|
||||||
}
|
}
|
||||||
|
|
||||||
const nextQuantity = Math.min(Math.max(quantity, 0), item.product.availableQuantity);
|
const nextQuantity = Math.min(
|
||||||
return nextQuantity === 0 ? [] : [{...item, quantity: nextQuantity}];
|
Math.max(quantity, 0),
|
||||||
}),
|
item.product.availableQuantity,
|
||||||
);
|
);
|
||||||
}
|
return nextQuantity === 0 ? [] : [{ ...item, quantity: nextQuantity }];
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
function removeItem(productId: string) {
|
function removeItem(productId: string) {
|
||||||
setItems((currentItems) => currentItems.filter((item) => item.product.id !== productId));
|
setItems((currentItems) =>
|
||||||
}
|
currentItems.filter((item) => item.product.id !== productId),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
function clearCart() {
|
function clearCart() {
|
||||||
setItems([]);
|
setItems([]);
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<CartContext.Provider
|
<CartContext.Provider
|
||||||
value={{
|
value={{
|
||||||
items,
|
items,
|
||||||
itemCount,
|
itemCount,
|
||||||
totalAmount,
|
totalAmount,
|
||||||
currency,
|
currency,
|
||||||
addItem,
|
addItem,
|
||||||
updateQuantity,
|
updateQuantity,
|
||||||
removeItem,
|
removeItem,
|
||||||
clearCart,
|
clearCart,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{children}
|
{children}
|
||||||
</CartContext.Provider>
|
</CartContext.Provider>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useCart() {
|
export function useCart() {
|
||||||
const context = useContext(CartContext);
|
const context = useContext(CartContext);
|
||||||
|
|
||||||
if (!context) {
|
if (!context) {
|
||||||
throw new Error("useCart must be used within CartProvider");
|
throw new Error("useCart must be used within CartProvider");
|
||||||
}
|
}
|
||||||
|
|
||||||
return context;
|
return context;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,14 @@
|
|||||||
import {calculateFare} from "#/api/fare";
|
import { useMutation } from "@tanstack/react-query";
|
||||||
import {useMutation} from "@tanstack/react-query";
|
import { calculateFare } from "#/api/fare";
|
||||||
|
|
||||||
type FareCalculationInput = {
|
type FareCalculationInput = {
|
||||||
distanceKm: number;
|
distanceKm: number;
|
||||||
surgeMultiplier?: number;
|
surgeMultiplier?: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
export function useFareCalculation() {
|
export function useFareCalculation() {
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: ({distanceKm, surgeMultiplier}: FareCalculationInput) =>
|
mutationFn: ({ distanceKm, surgeMultiplier }: FareCalculationInput) =>
|
||||||
calculateFare(distanceKm, surgeMultiplier),
|
calculateFare(distanceKm, surgeMultiplier),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -1,23 +1,23 @@
|
|||||||
import {getInventory, getLowStockInventory} from "#/api/inventory";
|
import { useQuery } from "@tanstack/react-query";
|
||||||
import {useQuery} from "@tanstack/react-query";
|
import { getInventory, getLowStockInventory } from "#/api/inventory";
|
||||||
|
|
||||||
export const inventoryQueryKeys = {
|
export const inventoryQueryKeys = {
|
||||||
all: ["inventory"] as const,
|
all: ["inventory"] as const,
|
||||||
list: () => [...inventoryQueryKeys.all, "list"] as const,
|
list: () => [...inventoryQueryKeys.all, "list"] as const,
|
||||||
lowStock: (threshold?: number) =>
|
lowStock: (threshold?: number) =>
|
||||||
[...inventoryQueryKeys.all, "low-stock", threshold ?? "default"] as const,
|
[...inventoryQueryKeys.all, "low-stock", threshold ?? "default"] as const,
|
||||||
};
|
};
|
||||||
|
|
||||||
export function useInventory() {
|
export function useInventory() {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: inventoryQueryKeys.list(),
|
queryKey: inventoryQueryKeys.list(),
|
||||||
queryFn: ({signal}) => getInventory(signal),
|
queryFn: ({ signal }) => getInventory(signal),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useLowStockInventory(threshold?: number) {
|
export function useLowStockInventory(threshold?: number) {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: inventoryQueryKeys.lowStock(threshold),
|
queryKey: inventoryQueryKeys.lowStock(threshold),
|
||||||
queryFn: ({signal}) => getLowStockInventory(threshold, signal),
|
queryFn: ({ signal }) => getLowStockInventory(threshold, signal),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -1,64 +1,75 @@
|
|||||||
import {cancelOrder, createOrder, getOrders, updateOrderStatus} from "#/api/orders";
|
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
import {inventoryQueryKeys} from "#/hooks/useInventory";
|
import {
|
||||||
import {productQueryKeys} from "#/hooks/useProducts";
|
cancelOrder,
|
||||||
import type {OrderFilters} from "#/types/order";
|
createOrder,
|
||||||
import {useMutation, useQuery, useQueryClient} from "@tanstack/react-query";
|
getOrders,
|
||||||
|
updateOrderStatus,
|
||||||
|
} from "#/api/orders";
|
||||||
|
import { inventoryQueryKeys } from "#/hooks/useInventory";
|
||||||
|
import { productQueryKeys } from "#/hooks/useProducts";
|
||||||
|
import type { OrderFilters } from "#/types/order";
|
||||||
|
|
||||||
export const orderQueryKeys = {
|
export const orderQueryKeys = {
|
||||||
all: ["orders"] as const,
|
all: ["orders"] as const,
|
||||||
list: (filters: OrderFilters, page = 0, size = 20) =>
|
list: (filters: OrderFilters, page = 0, size = 20) =>
|
||||||
[...orderQueryKeys.all, "list", filters, page, size] as const,
|
[...orderQueryKeys.all, "list", filters, page, size] as const,
|
||||||
};
|
};
|
||||||
|
|
||||||
export function useOrders(filters: OrderFilters, page = 0, size = 20) {
|
export function useOrders(filters: OrderFilters, page = 0, size = 20) {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: orderQueryKeys.list(filters, page, size),
|
queryKey: orderQueryKeys.list(filters, page, size),
|
||||||
queryFn: ({signal}) => getOrders(filters, page, size, signal),
|
queryFn: ({ signal }) => getOrders(filters, page, size, signal),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useCancelOrder() {
|
export function useCancelOrder() {
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: cancelOrder,
|
mutationFn: cancelOrder,
|
||||||
onSuccess: async () => {
|
onSuccess: async () => {
|
||||||
await Promise.all([
|
await Promise.all([
|
||||||
queryClient.invalidateQueries({
|
queryClient.invalidateQueries({
|
||||||
queryKey: orderQueryKeys.all,
|
queryKey: orderQueryKeys.all,
|
||||||
}),
|
}),
|
||||||
queryClient.invalidateQueries({
|
queryClient.invalidateQueries({
|
||||||
queryKey: inventoryQueryKeys.all,
|
queryKey: inventoryQueryKeys.all,
|
||||||
}),
|
}),
|
||||||
queryClient.invalidateQueries({
|
queryClient.invalidateQueries({
|
||||||
queryKey: productQueryKeys.all,
|
queryKey: productQueryKeys.all,
|
||||||
}),
|
}),
|
||||||
]);
|
]);
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useCreateOrder() {
|
export function useCreateOrder() {
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: createOrder,
|
mutationFn: createOrder,
|
||||||
onSuccess: async () => {
|
onSuccess: async () => {
|
||||||
await Promise.all([
|
await Promise.all([
|
||||||
queryClient.invalidateQueries({queryKey: orderQueryKeys.all}),
|
queryClient.invalidateQueries({ queryKey: orderQueryKeys.all }),
|
||||||
queryClient.invalidateQueries({queryKey: inventoryQueryKeys.all}),
|
queryClient.invalidateQueries({ queryKey: inventoryQueryKeys.all }),
|
||||||
queryClient.invalidateQueries({queryKey: productQueryKeys.all}),
|
queryClient.invalidateQueries({ queryKey: productQueryKeys.all }),
|
||||||
]);
|
]);
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useUpdateOrderStatus() {
|
export function useUpdateOrderStatus() {
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: ({id, status}: {id: string; status: import("#/types/order").OrderStatus}) =>
|
mutationFn: ({
|
||||||
updateOrderStatus(id, status),
|
id,
|
||||||
onSuccess: () => queryClient.invalidateQueries({queryKey: orderQueryKeys.all}),
|
status,
|
||||||
});
|
}: {
|
||||||
|
id: string;
|
||||||
|
status: import("#/types/order").OrderStatus;
|
||||||
|
}) => updateOrderStatus(id, status),
|
||||||
|
onSuccess: () =>
|
||||||
|
queryClient.invalidateQueries({ queryKey: orderQueryKeys.all }),
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,61 @@
|
|||||||
|
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import {
|
||||||
|
getCheckoutQuote,
|
||||||
|
initializePaystackPayment,
|
||||||
|
verifyPaystackPayment,
|
||||||
|
} from "#/api/payments";
|
||||||
|
import { inventoryQueryKeys } from "#/hooks/useInventory";
|
||||||
|
import { orderQueryKeys } from "#/hooks/useOrders";
|
||||||
|
import { productQueryKeys } from "#/hooks/useProducts";
|
||||||
|
import type {
|
||||||
|
CheckoutQuoteRequest,
|
||||||
|
PaystackInitializeRequest,
|
||||||
|
} from "#/types/payment";
|
||||||
|
|
||||||
|
export const paymentQueryKeys = {
|
||||||
|
all: ["payments"] as const,
|
||||||
|
quote: (request: CheckoutQuoteRequest) =>
|
||||||
|
[...paymentQueryKeys.all, "quote", request] as const,
|
||||||
|
};
|
||||||
|
|
||||||
|
export function useCheckoutQuote(
|
||||||
|
request: CheckoutQuoteRequest,
|
||||||
|
enabled: boolean,
|
||||||
|
) {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: paymentQueryKeys.quote(request),
|
||||||
|
queryFn: ({ signal }) => getCheckoutQuote(request, signal),
|
||||||
|
enabled,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useInitializePaystackPayment() {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: (request: PaystackInitializeRequest) =>
|
||||||
|
initializePaystackPayment(request),
|
||||||
|
onSuccess: async () => {
|
||||||
|
await Promise.all([
|
||||||
|
queryClient.invalidateQueries({ queryKey: orderQueryKeys.all }),
|
||||||
|
queryClient.invalidateQueries({ queryKey: inventoryQueryKeys.all }),
|
||||||
|
queryClient.invalidateQueries({ queryKey: productQueryKeys.all }),
|
||||||
|
]);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useVerifyPaystackPayment() {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: verifyPaystackPayment,
|
||||||
|
onSuccess: async () => {
|
||||||
|
await Promise.all([
|
||||||
|
queryClient.invalidateQueries({ queryKey: orderQueryKeys.all }),
|
||||||
|
queryClient.invalidateQueries({ queryKey: inventoryQueryKeys.all }),
|
||||||
|
queryClient.invalidateQueries({ queryKey: productQueryKeys.all }),
|
||||||
|
]);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -1,50 +1,59 @@
|
|||||||
import {createProduct, deactivateProduct, getProduct, getProducts, updateProduct} from "#/api/products";
|
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
import type {ProductRequest} from "#/types/product";
|
import {
|
||||||
import {useMutation, useQuery, useQueryClient} from "@tanstack/react-query";
|
createProduct,
|
||||||
|
deactivateProduct,
|
||||||
|
getProduct,
|
||||||
|
getProducts,
|
||||||
|
updateProduct,
|
||||||
|
} from "#/api/products";
|
||||||
|
import type { ProductRequest } from "#/types/product";
|
||||||
|
|
||||||
export const productQueryKeys = {
|
export const productQueryKeys = {
|
||||||
all: ["products"] as const,
|
all: ["products"] as const,
|
||||||
detail: (id: string) => [...productQueryKeys.all, "detail", id] as const,
|
detail: (id: string) => [...productQueryKeys.all, "detail", id] as const,
|
||||||
};
|
};
|
||||||
|
|
||||||
export function useProducts() {
|
export function useProducts() {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: productQueryKeys.all,
|
queryKey: productQueryKeys.all,
|
||||||
queryFn: ({signal}) => getProducts(signal),
|
queryFn: ({ signal }) => getProducts(signal),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useProduct(id: string) {
|
export function useProduct(id: string) {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: productQueryKeys.detail(id),
|
queryKey: productQueryKeys.detail(id),
|
||||||
queryFn: ({signal}) => getProduct(id, signal),
|
queryFn: ({ signal }) => getProduct(id, signal),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useCreateProduct() {
|
export function useCreateProduct() {
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: createProduct,
|
mutationFn: createProduct,
|
||||||
onSuccess: () => queryClient.invalidateQueries({queryKey: productQueryKeys.all}),
|
onSuccess: () =>
|
||||||
});
|
queryClient.invalidateQueries({ queryKey: productQueryKeys.all }),
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useUpdateProduct() {
|
export function useUpdateProduct() {
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: ({id, request}: {id: string; request: ProductRequest}) =>
|
mutationFn: ({ id, request }: { id: string; request: ProductRequest }) =>
|
||||||
updateProduct(id, request),
|
updateProduct(id, request),
|
||||||
onSuccess: () => queryClient.invalidateQueries({queryKey: productQueryKeys.all}),
|
onSuccess: () =>
|
||||||
});
|
queryClient.invalidateQueries({ queryKey: productQueryKeys.all }),
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useDeactivateProduct() {
|
export function useDeactivateProduct() {
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: deactivateProduct,
|
mutationFn: deactivateProduct,
|
||||||
onSuccess: () => queryClient.invalidateQueries({queryKey: productQueryKeys.all}),
|
onSuccess: () =>
|
||||||
});
|
queryClient.invalidateQueries({ queryKey: productQueryKeys.all }),
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,67 +1,72 @@
|
|||||||
|
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
import {
|
import {
|
||||||
acceptRide,
|
acceptRide,
|
||||||
cancelRide,
|
cancelRide,
|
||||||
completeRide,
|
completeRide,
|
||||||
getRides,
|
getRides,
|
||||||
requestRide,
|
requestRide,
|
||||||
updateRideStatus,
|
updateRideStatus,
|
||||||
} from "#/api/rides";
|
} from "#/api/rides";
|
||||||
import type {CreateRideRequest, RideStatus} from "#/types/ride";
|
import type { CreateRideRequest, RideStatus } from "#/types/ride";
|
||||||
import {useMutation, useQuery, useQueryClient} from "@tanstack/react-query";
|
|
||||||
|
|
||||||
export const rideQueryKeys = {
|
export const rideQueryKeys = {
|
||||||
all: ["rides"] as const,
|
all: ["rides"] as const,
|
||||||
};
|
};
|
||||||
|
|
||||||
export function useRides() {
|
export function useRides() {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: rideQueryKeys.all,
|
queryKey: rideQueryKeys.all,
|
||||||
queryFn: ({signal}) => getRides(signal),
|
queryFn: ({ signal }) => getRides(signal),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useRequestRide() {
|
export function useRequestRide() {
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (request: CreateRideRequest) => requestRide(request),
|
mutationFn: (request: CreateRideRequest) => requestRide(request),
|
||||||
onSuccess: () => queryClient.invalidateQueries({queryKey: rideQueryKeys.all}),
|
onSuccess: () =>
|
||||||
});
|
queryClient.invalidateQueries({ queryKey: rideQueryKeys.all }),
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useAcceptRide() {
|
export function useAcceptRide() {
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: acceptRide,
|
mutationFn: acceptRide,
|
||||||
onSuccess: () => queryClient.invalidateQueries({queryKey: rideQueryKeys.all}),
|
onSuccess: () =>
|
||||||
});
|
queryClient.invalidateQueries({ queryKey: rideQueryKeys.all }),
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useCompleteRide() {
|
export function useCompleteRide() {
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: completeRide,
|
mutationFn: completeRide,
|
||||||
onSuccess: () => queryClient.invalidateQueries({queryKey: rideQueryKeys.all}),
|
onSuccess: () =>
|
||||||
});
|
queryClient.invalidateQueries({ queryKey: rideQueryKeys.all }),
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useCancelRide() {
|
export function useCancelRide() {
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: cancelRide,
|
mutationFn: cancelRide,
|
||||||
onSuccess: () => queryClient.invalidateQueries({queryKey: rideQueryKeys.all}),
|
onSuccess: () =>
|
||||||
});
|
queryClient.invalidateQueries({ queryKey: rideQueryKeys.all }),
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useUpdateRideStatus() {
|
export function useUpdateRideStatus() {
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: ({id, status}: {id: string; status: RideStatus}) =>
|
mutationFn: ({ id, status }: { id: string; status: RideStatus }) =>
|
||||||
updateRideStatus(id, status),
|
updateRideStatus(id, status),
|
||||||
onSuccess: () => queryClient.invalidateQueries({queryKey: rideQueryKeys.all}),
|
onSuccess: () =>
|
||||||
});
|
queryClient.invalidateQueries({ queryKey: rideQueryKeys.all }),
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user