Refactor project structure to use pnpm monorepo; update Dockerfile and related configurations for frontend build process. Adjust .dockerignore and .gitignore to reflect new paths. Modify .env.example for cron job timing. Update CONTRIBUTING.md and README.md for new development instructions.
Build, Test, and Push CFDM Docker Image / test (push) Failing after 3h13m2s
Build, Test, and Push CFDM Docker Image / create-release (push) Has been cancelled
Build, Test, and Push CFDM Docker Image / build-and-push (push) Has been cancelled
Build, Test, and Push CFDM Docker Image / update-wiki (push) Has been cancelled
Build, Test, and Push CFDM Docker Image / test (push) Failing after 3h13m2s
Build, Test, and Push CFDM Docker Image / create-release (push) Has been cancelled
Build, Test, and Push CFDM Docker Image / build-and-push (push) Has been cancelled
Build, Test, and Push CFDM Docker Image / update-wiki (push) Has been cancelled
This commit is contained in:
@@ -0,0 +1,267 @@
|
||||
---
|
||||
name: shadcn
|
||||
description: Manages shadcn components and projects — adding, searching, fixing, debugging, styling, and composing UI. Provides project context, component docs, and usage examples. Applies when working with shadcn/ui, component registries, presets, --preset codes, or any project with a components.json file. Also triggers for "shadcn init", "create an app with --preset", or "switch to --preset".
|
||||
user-invocable: false
|
||||
allowed-tools: Bash(npx shadcn@latest *), Bash(pnpm dlx shadcn@latest *), Bash(bunx --bun shadcn@latest *)
|
||||
---
|
||||
|
||||
# shadcn/ui
|
||||
|
||||
A framework for building ui, components and design systems. Components are added as source code to the user's project via the CLI.
|
||||
|
||||
> **IMPORTANT:** Run all CLI commands using the project's package runner: `npx shadcn@latest`, `pnpm dlx shadcn@latest`, or `bunx --bun shadcn@latest` — based on the project's `packageManager`. Examples below use `npx shadcn@latest` but substitute the correct runner for the project.
|
||||
|
||||
## Current Project Context
|
||||
|
||||
```json
|
||||
!`npx shadcn@latest info --json`
|
||||
```
|
||||
|
||||
The JSON above contains the project config and installed components. Use `npx shadcn@latest docs <component>` to get documentation and example URLs for any component.
|
||||
|
||||
## Principles
|
||||
|
||||
1. **Use existing components first.** Use `npx shadcn@latest search` to check registries before writing custom UI. Check community registries too.
|
||||
2. **Compose, don't reinvent.** Settings page = Tabs + Card + form controls. Dashboard = Sidebar + Card + Chart + Table.
|
||||
3. **Use built-in variants before custom styles.** `variant="outline"`, `size="sm"`, etc.
|
||||
4. **Use semantic colors.** `bg-primary`, `text-muted-foreground` — never raw values like `bg-blue-500`.
|
||||
|
||||
## Critical Rules
|
||||
|
||||
These rules are **always enforced**. Each links to a file with Incorrect/Correct code pairs.
|
||||
|
||||
### Styling & Tailwind → [styling.md](./rules/styling.md)
|
||||
|
||||
- **`className` for layout, not styling.** Never override component colors or typography.
|
||||
- **No `space-x-*` or `space-y-*`.** Use `flex` with `gap-*`. For vertical stacks, `flex flex-col gap-*`.
|
||||
- **Use `size-*` when width and height are equal.** `size-10` not `w-10 h-10`.
|
||||
- **Use `truncate` shorthand.** Not `overflow-hidden text-ellipsis whitespace-nowrap`.
|
||||
- **No manual `dark:` color overrides.** Use semantic tokens (`bg-background`, `text-muted-foreground`).
|
||||
- **Use `cn()` for conditional classes.** Don't write manual template literal ternaries.
|
||||
- **No manual `z-index` on overlay components.** Dialog, Sheet, Popover, etc. handle their own stacking.
|
||||
|
||||
### Forms & Inputs → [forms.md](./rules/forms.md)
|
||||
|
||||
- **Forms use `FieldGroup` + `Field`.** Never use raw `div` with `space-y-*` or `grid gap-*` for form layout.
|
||||
- **`InputGroup` uses `InputGroupInput`/`InputGroupTextarea`.** Never raw `Input`/`Textarea` inside `InputGroup`.
|
||||
- **Buttons inside inputs use `InputGroup` + `InputGroupAddon`.**
|
||||
- **Option sets (2–7 choices) use `ToggleGroup`.** Don't loop `Button` with manual active state.
|
||||
- **`FieldSet` + `FieldLegend` for grouping related checkboxes/radios.** Don't use a `div` with a heading.
|
||||
- **Field validation uses `data-invalid` + `aria-invalid`.** `data-invalid` on `Field`, `aria-invalid` on the control. For disabled: `data-disabled` on `Field`, `disabled` on the control.
|
||||
|
||||
### Component Structure → [composition.md](./rules/composition.md)
|
||||
|
||||
- **Items always inside their Group.** `SelectItem` → `SelectGroup`. `DropdownMenuItem` → `DropdownMenuGroup`. `CommandItem` → `CommandGroup`.
|
||||
- **Use `asChild` (radix) or `render` (base) for custom triggers.** Check `base` field from `npx shadcn@latest info`. → [base-vs-radix.md](./rules/base-vs-radix.md)
|
||||
- **Dialog, Sheet, and Drawer always need a Title.** `DialogTitle`, `SheetTitle`, `DrawerTitle` required for accessibility. Use `className="sr-only"` if visually hidden.
|
||||
- **Use full Card composition.** `CardHeader`/`CardTitle`/`CardDescription`/`CardContent`/`CardFooter`. Don't dump everything in `CardContent`.
|
||||
- **Button has no `isPending`/`isLoading`.** Compose with `Spinner` + `data-icon` + `disabled`.
|
||||
- **`TabsTrigger` must be inside `TabsList`.** Never render triggers directly in `Tabs`.
|
||||
- **`Avatar` always needs `AvatarFallback`.** For when the image fails to load.
|
||||
|
||||
### Use Components, Not Custom Markup → [composition.md](./rules/composition.md)
|
||||
|
||||
- **Use existing components before custom markup.** Check if a component exists before writing a styled `div`.
|
||||
- **Callouts use `Alert`.** Don't build custom styled divs.
|
||||
- **Empty states use `Empty`.** Don't build custom empty state markup.
|
||||
- **Toast via `sonner`.** Use `toast()` from `sonner`.
|
||||
- **Use `Separator`** instead of `<hr>` or `<div className="border-t">`.
|
||||
- **Use `Skeleton`** for loading placeholders. No custom `animate-pulse` divs.
|
||||
- **Use `Badge`** instead of custom styled spans.
|
||||
|
||||
### Icons → [icons.md](./rules/icons.md)
|
||||
|
||||
- **Icons in `Button` use `data-icon`.** `data-icon="inline-start"` or `data-icon="inline-end"` on the icon.
|
||||
- **No sizing classes on icons inside components.** Components handle icon sizing via CSS. No `size-4` or `w-4 h-4`.
|
||||
- **Pass icons as objects, not string keys.** `icon={CheckIcon}`, not a string lookup.
|
||||
|
||||
### CLI
|
||||
|
||||
- **Never decode preset codes or build preset URLs manually.** Use `npx shadcn@latest preset decode <code>`, `preset url <code>`, or `preset open <code>`. For project-aware preset detection, use `npx shadcn@latest preset resolve`.
|
||||
- **Apply preset codes directly with the CLI.** Use `npx shadcn@latest apply <code>` for existing projects, or `npx shadcn@latest init --preset <code>` when initializing.
|
||||
|
||||
## Key Patterns
|
||||
|
||||
These are the most common patterns that differentiate correct shadcn/ui code. For edge cases, see the linked rule files above.
|
||||
|
||||
```tsx
|
||||
// Form layout: FieldGroup + Field, not div + Label.
|
||||
<FieldGroup>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="email">Email</FieldLabel>
|
||||
<Input id="email" />
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
|
||||
// Validation: data-invalid on Field, aria-invalid on the control.
|
||||
<Field data-invalid>
|
||||
<FieldLabel>Email</FieldLabel>
|
||||
<Input aria-invalid />
|
||||
<FieldDescription>Invalid email.</FieldDescription>
|
||||
</Field>
|
||||
|
||||
// Icons in buttons: data-icon, no sizing classes.
|
||||
<Button>
|
||||
<SearchIcon data-icon="inline-start" />
|
||||
Search
|
||||
</Button>
|
||||
|
||||
// Spacing: gap-*, not space-y-*.
|
||||
<div className="flex flex-col gap-4"> // correct
|
||||
<div className="space-y-4"> // wrong
|
||||
|
||||
// Equal dimensions: size-*, not w-* h-*.
|
||||
<Avatar className="size-10"> // correct
|
||||
<Avatar className="w-10 h-10"> // wrong
|
||||
|
||||
// Status colors: Badge variants or semantic tokens, not raw colors.
|
||||
<Badge variant="secondary">+20.1%</Badge> // correct
|
||||
<span className="text-emerald-600">+20.1%</span> // wrong
|
||||
```
|
||||
|
||||
## Component Selection
|
||||
|
||||
| Need | Use |
|
||||
| -------------------------- | --------------------------------------------------------------------------------------------------- |
|
||||
| Button/action | `Button` with appropriate variant |
|
||||
| Form inputs | `Input`, `Select`, `Combobox`, `Switch`, `Checkbox`, `RadioGroup`, `Textarea`, `InputOTP`, `Slider` |
|
||||
| Toggle between 2–5 options | `ToggleGroup` + `ToggleGroupItem` |
|
||||
| Data display | `Table`, `Card`, `Badge`, `Avatar` |
|
||||
| Navigation | `Sidebar`, `NavigationMenu`, `Breadcrumb`, `Tabs`, `Pagination` |
|
||||
| Overlays | `Dialog` (modal), `Sheet` (side panel), `Drawer` (bottom sheet), `AlertDialog` (confirmation) |
|
||||
| Feedback | `sonner` (toast), `Alert`, `Progress`, `Skeleton`, `Spinner` |
|
||||
| Command palette | `Command` inside `Dialog` |
|
||||
| Charts | `Chart` (wraps Recharts) |
|
||||
| Layout | `Card`, `Separator`, `Resizable`, `ScrollArea`, `Accordion`, `Collapsible` |
|
||||
| Empty states | `Empty` |
|
||||
| Menus | `DropdownMenu`, `ContextMenu`, `Menubar` |
|
||||
| Tooltips/info | `Tooltip`, `HoverCard`, `Popover` |
|
||||
|
||||
## Key Fields
|
||||
|
||||
The injected project context contains these key fields:
|
||||
|
||||
- **`aliases`** → use the actual alias prefix for imports (e.g. `@/`, `~/`), never hardcode.
|
||||
- **`isRSC`** → when `true`, components using `useState`, `useEffect`, event handlers, or browser APIs need `"use client"` at the top of the file. Always reference this field when advising on the directive.
|
||||
- **`tailwindVersion`** → `"v4"` uses `@theme inline` blocks; `"v3"` uses `tailwind.config.js`.
|
||||
- **`tailwindCssFile`** → the global CSS file where custom CSS variables are defined. Always edit this file, never create a new one.
|
||||
- **`style`** → component visual treatment (e.g. `nova`, `vega`).
|
||||
- **`base`** → primitive library (`radix` or `base`). Affects component APIs and available props.
|
||||
- **`iconLibrary`** → determines icon imports. Use `lucide-react` for `lucide`, `@tabler/icons-react` for `tabler`, etc. Never assume `lucide-react`.
|
||||
- **`resolvedPaths`** → exact file-system destinations for components, utils, hooks, etc.
|
||||
- **`framework`** → routing and file conventions (e.g. Next.js App Router vs Vite SPA).
|
||||
- **`packageManager`** → use this for any non-shadcn dependency installs (e.g. `pnpm add date-fns` vs `npm install date-fns`).
|
||||
- **`preset`** → resolved preset code and values for the current project. Use `npx shadcn@latest preset resolve --json` when you only need preset information.
|
||||
|
||||
See [cli.md — `info` command](./cli.md) for the full field reference.
|
||||
|
||||
## Component Docs, Examples, and Usage
|
||||
|
||||
Run `npx shadcn@latest docs <component>` to get the URLs for a component's documentation, examples, and API reference. Fetch these URLs to get the actual content.
|
||||
|
||||
```bash
|
||||
npx shadcn@latest docs button dialog select
|
||||
```
|
||||
|
||||
**When creating, fixing, debugging, or using a component, always run `npx shadcn@latest docs` and fetch the URLs first.** This ensures you're working with the correct API and usage patterns rather than guessing.
|
||||
|
||||
## Workflow
|
||||
|
||||
1. **Get project context** — already injected above. Run `npx shadcn@latest info` again if you need to refresh.
|
||||
2. **Check installed components first** — before running `add`, always check the `components` list from project context or list the `resolvedPaths.ui` directory. Don't import components that haven't been added, and don't re-add ones already installed.
|
||||
3. **Find components** — `npx shadcn@latest search`.
|
||||
4. **Get docs and examples** — run `npx shadcn@latest docs <component>` to get URLs, then fetch them. Use `npx shadcn@latest view` to browse registry items you haven't installed. To preview changes to installed components, use `npx shadcn@latest add --diff`.
|
||||
5. **Install or update** — `npx shadcn@latest add`. When updating existing components, use `--dry-run` and `--diff` to preview changes first (see [Updating Components](#updating-components) below).
|
||||
6. **Fix imports in third-party components** — After adding components from community registries (e.g. `@bundui`, `@magicui`), check the added non-UI files for hardcoded import paths like `@/components/ui/...`. These won't match the project's actual aliases. Use `npx shadcn@latest info` to get the correct `ui` alias (e.g. `@workspace/ui/components`) and rewrite the imports accordingly. The CLI rewrites imports for its own UI files, but third-party registry components may use default paths that don't match the project.
|
||||
7. **Review added components** — After adding a component or block from any registry, **always read the added files and verify they are correct**. Check for missing sub-components (e.g. `SelectItem` without `SelectGroup`), missing imports, incorrect composition, or violations of the [Critical Rules](#critical-rules). Also replace any icon imports with the project's `iconLibrary` from the project context (e.g. if the registry item uses `lucide-react` but the project uses `hugeicons`, swap the imports and icon names accordingly). Fix all issues before moving on.
|
||||
8. **Registry must be explicit** — When the user asks to add a block or component, **do not guess the registry**. If no registry is specified (e.g. user says "add a login block" without specifying `@shadcn`, `@tailark`, `owner/repo`, etc.), ask which registry to use. Never default to a registry on behalf of the user.
|
||||
9. **Switching presets** — Ask the user first: **overwrite**, **partial**, **merge**, or **skip**?
|
||||
- **Inspect current preset**: `npx shadcn@latest preset resolve`. Use `--json` when you need structured values.
|
||||
- **Inspect incoming preset**: `npx shadcn@latest preset decode <code>`. Use `preset url <code>` or `preset open <code>` to share or open the preset builder.
|
||||
- **Overwrite**: `npx shadcn@latest apply <code>`. Overwrites detected components, fonts, and CSS variables.
|
||||
- **Partial**: `npx shadcn@latest apply <code> --only theme,font`. Updates only the selected preset parts without reinstalling UI components. Supported values are `theme` and `font`; comma-separated combinations are allowed. `icon` is intentionally not supported, because icon changes may require full component reinstall and transforms.
|
||||
- **Merge**: `npx shadcn@latest init --preset <code> --force --no-reinstall`, then run `npx shadcn@latest info` to list installed components, then for each installed component use `--dry-run` and `--diff` to [smart merge](#updating-components) it individually.
|
||||
- **Skip**: `npx shadcn@latest init --preset <code> --force --no-reinstall`. Only updates config and CSS, leaves components as-is.
|
||||
- **Important**: Always run preset commands inside the user's project directory. `apply` only works in an existing project with a `components.json` file. The CLI automatically preserves the current base (`base` vs `radix`) from `components.json`. If you must use a scratch/temp directory (e.g. for `--dry-run` comparisons), pass `--base <current-base>` explicitly — preset codes do not encode the base.
|
||||
|
||||
## Updating Components
|
||||
|
||||
When the user asks to update a component from upstream while keeping their local changes, use `--dry-run` and `--diff` to intelligently merge. **NEVER fetch raw files from GitHub manually — always use the CLI.**
|
||||
|
||||
1. Run `npx shadcn@latest add <component> --dry-run` to see all files that would be affected.
|
||||
2. For each file, run `npx shadcn@latest add <component> --diff <file>` to see what changed upstream vs local.
|
||||
3. Decide per file based on the diff:
|
||||
- No local changes → safe to overwrite.
|
||||
- Has local changes → read the local file, analyze the diff, and apply upstream updates while preserving local modifications.
|
||||
- User says "just update everything" → use `--overwrite`, but confirm first.
|
||||
4. **Never use `--overwrite` without the user's explicit approval.**
|
||||
|
||||
## Quick Reference
|
||||
|
||||
```bash
|
||||
# Create a new project.
|
||||
npx shadcn@latest init --name my-app --preset base-nova
|
||||
npx shadcn@latest init --name my-app --preset a2r6bw --template vite
|
||||
|
||||
# Create a monorepo project.
|
||||
npx shadcn@latest init --name my-app --preset base-nova --monorepo
|
||||
npx shadcn@latest init --name my-app --preset base-nova --template next --monorepo
|
||||
|
||||
# Initialize existing project.
|
||||
npx shadcn@latest init --preset base-nova
|
||||
npx shadcn@latest init --defaults # shortcut: --template=next --preset=nova (base style implied)
|
||||
|
||||
# Apply a preset to an existing project.
|
||||
npx shadcn@latest apply a2r6bw
|
||||
npx shadcn@latest apply a2r6bw --only theme
|
||||
npx shadcn@latest apply a2r6bw --only font
|
||||
npx shadcn@latest apply a2r6bw --only theme,font
|
||||
|
||||
# Inspect preset codes and project preset state.
|
||||
npx shadcn@latest preset decode a2r6bw
|
||||
npx shadcn@latest preset url a2r6bw
|
||||
npx shadcn@latest preset open a2r6bw
|
||||
npx shadcn@latest preset resolve
|
||||
npx shadcn@latest preset resolve --json
|
||||
|
||||
# Add components.
|
||||
npx shadcn@latest add button card dialog
|
||||
npx shadcn@latest add @magicui/shimmer-button
|
||||
npx shadcn@latest add owner/repo/item
|
||||
npx shadcn@latest add --all
|
||||
|
||||
# Preview changes before adding/updating.
|
||||
npx shadcn@latest add button --dry-run
|
||||
npx shadcn@latest add button --diff button.tsx
|
||||
npx shadcn@latest add @acme/form --view button.tsx
|
||||
npx shadcn@latest add owner/repo/item --dry-run
|
||||
|
||||
# Search registries.
|
||||
npx shadcn@latest search @shadcn -q "sidebar"
|
||||
npx shadcn@latest search @tailark -q "stats"
|
||||
npx shadcn@latest search owner/repo -q "login"
|
||||
npx shadcn@latest search # all configured registries
|
||||
npx shadcn@latest search @shadcn -q "menu" -t ui # filter by item type
|
||||
|
||||
# Get component docs and example URLs.
|
||||
npx shadcn@latest docs button dialog select
|
||||
|
||||
# View registry item details (for items not yet installed).
|
||||
npx shadcn@latest view @shadcn/button
|
||||
npx shadcn@latest view owner/repo/item
|
||||
```
|
||||
|
||||
**Named presets:** `nova`, `vega`, `maia`, `lyra`, `mira`, `luma`
|
||||
**Templates:** `next`, `vite`, `start`, `react-router`, `astro` (all support `--monorepo`) and `laravel` (not supported for monorepo)
|
||||
**Preset codes:** Version-prefixed base62 strings (e.g. `a2r6bw` or `b0`), from [ui.shadcn.com](https://ui.shadcn.com).
|
||||
|
||||
## Detailed References
|
||||
|
||||
- [rules/forms.md](./rules/forms.md) — FieldGroup, Field, InputGroup, ToggleGroup, FieldSet, validation states
|
||||
- [rules/composition.md](./rules/composition.md) — Groups, overlays, Card, Tabs, Avatar, Alert, Empty, Toast, Separator, Skeleton, Badge, Button loading
|
||||
- [rules/icons.md](./rules/icons.md) — data-icon, icon sizing, passing icons as objects
|
||||
- [rules/styling.md](./rules/styling.md) — Semantic colors, variants, className, spacing, size, truncate, dark mode, cn(), z-index
|
||||
- [rules/base-vs-radix.md](./rules/base-vs-radix.md) — asChild vs render, Select, ToggleGroup, Slider, Accordion
|
||||
- [cli.md](./cli.md) — Commands, flags, presets, templates
|
||||
- [registry.md](./registry.md) — Authoring source registries, `include`, item definitions, dependencies, GitHub registry rules
|
||||
- [customization.md](./customization.md) — Theming, CSS variables, extending components
|
||||
@@ -0,0 +1,5 @@
|
||||
interface:
|
||||
display_name: "shadcn/ui"
|
||||
short_description: "Manages shadcn/ui components — adding, searching, fixing, debugging, styling, and composing UI."
|
||||
icon_small: "./assets/shadcn-small.png"
|
||||
icon_large: "./assets/shadcn.png"
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 1.0 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 3.8 KiB |
@@ -0,0 +1,290 @@
|
||||
# shadcn CLI Reference
|
||||
|
||||
Configuration is read from `components.json`.
|
||||
|
||||
> **IMPORTANT:** Always run commands using the project's package runner: `npx shadcn@latest`, `pnpm dlx shadcn@latest`, or `bunx --bun shadcn@latest`. Check `packageManager` from project context to choose the right one. Examples below use `npx shadcn@latest` but substitute the correct runner for the project.
|
||||
|
||||
> **IMPORTANT:** Only use the flags documented below. Do not invent or guess flags — if a flag isn't listed here, it doesn't exist. The CLI auto-detects the package manager from the project's lockfile; there is no `--package-manager` flag.
|
||||
|
||||
## Contents
|
||||
|
||||
- Commands: init, apply, add (dry-run, smart merge), search, view, docs, info, build
|
||||
- Templates: next, vite, start, react-router, astro
|
||||
- Presets: named, code, URL formats and fields
|
||||
- Switching presets
|
||||
|
||||
---
|
||||
|
||||
## Commands
|
||||
|
||||
### `init` — Initialize or create a project
|
||||
|
||||
```bash
|
||||
npx shadcn@latest init [components...] [options]
|
||||
```
|
||||
|
||||
Initializes shadcn/ui in an existing project or creates a new project (when `--name` is provided). Optionally installs components in the same step.
|
||||
|
||||
| Flag | Short | Description | Default |
|
||||
| ----------------------- | ----- | --------------------------------------------------------- | ------- |
|
||||
| `--template <template>` | `-t` | Template (next, start, vite, next-monorepo, react-router) | — |
|
||||
| `--preset [name]` | `-p` | Preset configuration (named, code, or URL) | — |
|
||||
| `--yes` | `-y` | Skip confirmation prompt | `true` |
|
||||
| `--defaults` | `-d` | Use defaults (`--template=next --preset=base-nova`) | `false` |
|
||||
| `--force` | `-f` | Force overwrite existing configuration | `false` |
|
||||
| `--cwd <cwd>` | `-c` | Working directory | current |
|
||||
| `--name <name>` | `-n` | Name for new project | — |
|
||||
| `--silent` | `-s` | Mute output | `false` |
|
||||
| `--rtl` | | Enable RTL support | — |
|
||||
| `--reinstall` | | Re-install existing UI components | `false` |
|
||||
| `--monorepo` | | Scaffold a monorepo project | — |
|
||||
| `--no-monorepo` | | Skip the monorepo prompt | — |
|
||||
|
||||
`npx shadcn@latest create` is an alias for `npx shadcn@latest init`.
|
||||
|
||||
### `apply` — Apply a preset to an existing project
|
||||
|
||||
```bash
|
||||
npx shadcn@latest apply [preset] [options]
|
||||
```
|
||||
|
||||
Applies a preset to an existing project, overwriting preset-driven config, fonts, CSS variables, and detected UI components.
|
||||
|
||||
| Flag | Short | Description | Default |
|
||||
| ------------------- | ----- | ------------------------------------------ | ------- |
|
||||
| `--preset <preset>` | — | Preset configuration (named, code, or URL) | — |
|
||||
| `--yes` | `-y` | Skip confirmation prompt | `false` |
|
||||
| `--cwd <cwd>` | `-c` | Working directory | current |
|
||||
| `--silent` | `-s` | Mute output | `false` |
|
||||
|
||||
`[preset]` is a shorthand for `--preset <preset>`. If both are provided, they must match.
|
||||
If no preset is provided, the CLI offers to open the custom preset builder on `ui.shadcn.com/create`.
|
||||
|
||||
### `add` — Add components
|
||||
|
||||
> **IMPORTANT:** To compare local components against upstream or to preview changes, ALWAYS use `npx shadcn@latest add <component> --dry-run`, `--diff`, or `--view`. NEVER fetch raw files from GitHub or other sources manually. The CLI handles registry resolution, file paths, and CSS diffing automatically.
|
||||
|
||||
```bash
|
||||
npx shadcn@latest add [components...] [options]
|
||||
```
|
||||
|
||||
Accepts component names, registry-prefixed names (`@magicui/shimmer-button`),
|
||||
GitHub item addresses (`owner/repo/item`), URLs, or local paths.
|
||||
|
||||
| Flag | Short | Description | Default |
|
||||
| --------------- | ----- | -------------------------------------------------------------------------------------------------------------------- | ------- |
|
||||
| `--yes` | `-y` | Skip confirmation prompt | `false` |
|
||||
| `--overwrite` | `-o` | Overwrite existing files | `false` |
|
||||
| `--cwd <cwd>` | `-c` | Working directory | current |
|
||||
| `--all` | `-a` | Add all available components | `false` |
|
||||
| `--path <path>` | `-p` | Target path for the component | — |
|
||||
| `--silent` | `-s` | Mute output | `false` |
|
||||
| `--dry-run` | | Preview all changes without writing files | `false` |
|
||||
| `--diff [path]` | | Show diffs. Without a path, shows the first 5 files. With a path, shows that file only (implies `--dry-run`) | — |
|
||||
| `--view [path]` | | Show file contents. Without a path, shows the first 5 files. With a path, shows that file only (implies `--dry-run`) | — |
|
||||
|
||||
#### Dry-Run Mode
|
||||
|
||||
Use `--dry-run` to preview what `add` would do without writing any files. `--diff` and `--view` both imply `--dry-run`.
|
||||
|
||||
```bash
|
||||
# Preview all changes.
|
||||
npx shadcn@latest add button --dry-run
|
||||
|
||||
# Show diffs for all files (top 5).
|
||||
npx shadcn@latest add button --diff
|
||||
|
||||
# Show the diff for a specific file.
|
||||
npx shadcn@latest add button --diff button.tsx
|
||||
|
||||
# Show contents for all files (top 5).
|
||||
npx shadcn@latest add button --view
|
||||
|
||||
# Show the full content of a specific file.
|
||||
npx shadcn@latest add button --view button.tsx
|
||||
|
||||
# Works with URLs too.
|
||||
npx shadcn@latest add https://api.npoint.io/abc123 --dry-run
|
||||
|
||||
# Works with public GitHub registries too.
|
||||
npx shadcn@latest add owner/repo/item --dry-run
|
||||
|
||||
# CSS diffs.
|
||||
npx shadcn@latest add button --diff globals.css
|
||||
```
|
||||
|
||||
**When to use dry-run:**
|
||||
|
||||
- When the user asks "what files will this add?" or "what will this change?" — use `--dry-run`.
|
||||
- Before overwriting existing components — use `--diff` to preview the changes first.
|
||||
- When the user wants to inspect component source code without installing — use `--view`.
|
||||
- When checking what CSS changes would be made to `globals.css` — use `--diff globals.css`.
|
||||
- When the user asks to review or audit third-party registry code before installing — use `--view` to inspect the source.
|
||||
|
||||
> **`npx shadcn@latest add --dry-run` vs `npx shadcn@latest view`:** Prefer `npx shadcn@latest add --dry-run/--diff/--view` over `npx shadcn@latest view` when the user wants to preview changes to their project. `npx shadcn@latest view` only shows raw registry metadata. `npx shadcn@latest add --dry-run` shows exactly what would happen in the user's project: resolved file paths, diffs against existing files, and CSS updates. Use `npx shadcn@latest view` only when the user wants to browse registry info without a project context.
|
||||
|
||||
#### Smart Merge from Upstream
|
||||
|
||||
See [Updating Components in SKILL.md](./SKILL.md#updating-components) for the full workflow.
|
||||
|
||||
### `search` — Search registries
|
||||
|
||||
```bash
|
||||
npx shadcn@latest search [registries...] [options]
|
||||
```
|
||||
|
||||
Fuzzy search across registries. Also aliased as `npx shadcn@latest list`.
|
||||
Supports namespaces (`@acme`), public GitHub registry sources (`owner/repo`),
|
||||
and registry catalog URLs. Without `-q`, lists all items. When no registries are
|
||||
passed, searches every registry configured in `components.json`.
|
||||
|
||||
| Flag | Short | Description | Default |
|
||||
| ------------------- | ----- | ------------------------------------------------- | ------- |
|
||||
| `--query <query>` | `-q` | Search query | — |
|
||||
| `--type <type>` | `-t` | Filter by item type (e.g. `ui`, `block`, `hook`); comma-separated | — |
|
||||
| `--limit <number>` | `-l` | Max items to display | `100` |
|
||||
| `--offset <number>` | `-o` | Items to skip | `0` |
|
||||
| `--json` | | Output as JSON | `false` |
|
||||
| `--cwd <cwd>` | `-c` | Working directory | current |
|
||||
|
||||
### `view` — View item details
|
||||
|
||||
```bash
|
||||
npx shadcn@latest view <items...> [options]
|
||||
```
|
||||
|
||||
Displays item info including file contents. Examples:
|
||||
`npx shadcn@latest view @shadcn/button`,
|
||||
`npx shadcn@latest view owner/repo/item`.
|
||||
|
||||
### `docs` — Get component documentation URLs
|
||||
|
||||
```bash
|
||||
npx shadcn@latest docs <components...> [options]
|
||||
```
|
||||
|
||||
Outputs resolved URLs for component documentation, examples, and API references. Accepts one or more component names. Fetch the URLs to get the actual content.
|
||||
|
||||
Example output for `npx shadcn@latest docs input button`:
|
||||
|
||||
```
|
||||
base radix
|
||||
|
||||
input
|
||||
docs https://ui.shadcn.com/docs/components/radix/input
|
||||
examples https://raw.githubusercontent.com/.../examples/input-example.tsx
|
||||
|
||||
button
|
||||
docs https://ui.shadcn.com/docs/components/radix/button
|
||||
examples https://raw.githubusercontent.com/.../examples/button-example.tsx
|
||||
```
|
||||
|
||||
Some components include an `api` link to the underlying library (e.g. `cmdk` for the command component).
|
||||
|
||||
### `diff` — Check for updates
|
||||
|
||||
Do not use this command. Use `npx shadcn@latest add --diff` instead.
|
||||
|
||||
### `info` — Project information
|
||||
|
||||
```bash
|
||||
npx shadcn@latest info [options]
|
||||
```
|
||||
|
||||
Displays project info and `components.json` configuration. Run this first to discover the project's framework, aliases, Tailwind version, and resolved paths.
|
||||
|
||||
| Flag | Short | Description | Default |
|
||||
| ------------- | ----- | ----------------- | ------- |
|
||||
| `--cwd <cwd>` | `-c` | Working directory | current |
|
||||
|
||||
**Project Info fields:**
|
||||
|
||||
| Field | Type | Meaning |
|
||||
| -------------------- | --------- | ------------------------------------------------------------------ |
|
||||
| `framework` | `string` | Detected framework (`next`, `vite`, `react-router`, `start`, etc.) |
|
||||
| `frameworkVersion` | `string` | Framework version (e.g. `15.2.4`) |
|
||||
| `isSrcDir` | `boolean` | Whether the project uses a `src/` directory |
|
||||
| `isRSC` | `boolean` | Whether React Server Components are enabled |
|
||||
| `isTsx` | `boolean` | Whether the project uses TypeScript |
|
||||
| `tailwindVersion` | `string` | `"v3"` or `"v4"` |
|
||||
| `tailwindConfigFile` | `string` | Path to the Tailwind config file |
|
||||
| `tailwindCssFile` | `string` | Path to the global CSS file |
|
||||
| `aliasPrefix` | `string` | Import alias prefix (e.g. `@`, `~`, `@/`) |
|
||||
| `packageManager` | `string` | Detected package manager (`npm`, `pnpm`, `yarn`, `bun`) |
|
||||
|
||||
**Components.json fields:**
|
||||
|
||||
| Field | Type | Meaning |
|
||||
| -------------------- | --------- | ------------------------------------------------------------------------------------------ |
|
||||
| `base` | `string` | Primitive library (`radix` or `base`) — determines component APIs and available props |
|
||||
| `style` | `string` | Visual style (e.g. `nova`, `vega`) |
|
||||
| `rsc` | `boolean` | RSC flag from config |
|
||||
| `tsx` | `boolean` | TypeScript flag |
|
||||
| `tailwind.config` | `string` | Tailwind config path |
|
||||
| `tailwind.css` | `string` | Global CSS path — this is where custom CSS variables go |
|
||||
| `iconLibrary` | `string` | Icon library — determines icon import package (e.g. `lucide-react`, `@tabler/icons-react`) |
|
||||
| `aliases.components` | `string` | Component import alias (e.g. `@/components`) |
|
||||
| `aliases.utils` | `string` | Utils import alias (e.g. `@/lib/utils`) |
|
||||
| `aliases.ui` | `string` | UI component alias (e.g. `@/components/ui`) |
|
||||
| `aliases.lib` | `string` | Lib alias (e.g. `@/lib`) |
|
||||
| `aliases.hooks` | `string` | Hooks alias (e.g. `@/hooks`) |
|
||||
| `resolvedPaths` | `object` | Absolute file-system paths for each alias |
|
||||
| `registries` | `object` | Configured custom registries |
|
||||
|
||||
**Links fields:**
|
||||
|
||||
The `info` output includes a **Links** section with templated URLs for component docs, source, and examples. For resolved URLs, use `npx shadcn@latest docs <component>` instead.
|
||||
|
||||
### `build` — Build a custom registry
|
||||
|
||||
```bash
|
||||
npx shadcn@latest build [registry] [options]
|
||||
```
|
||||
|
||||
Builds `registry.json` into individual JSON files for distribution. Default input: `./registry.json`, default output: `./public/r`.
|
||||
|
||||
For authoring rules, `include`, item definitions, `registryDependencies`, and
|
||||
GitHub registry behavior, see [registry.md](./registry.md).
|
||||
|
||||
| Flag | Short | Description | Default |
|
||||
| ----------------- | ----- | ----------------- | ------------ |
|
||||
| `--output <path>` | `-o` | Output directory | `./public/r` |
|
||||
| `--cwd <cwd>` | `-c` | Working directory | current |
|
||||
|
||||
---
|
||||
|
||||
## Templates
|
||||
|
||||
| Value | Framework | Monorepo support |
|
||||
| -------------- | -------------- | ---------------- |
|
||||
| `next` | Next.js | Yes |
|
||||
| `vite` | Vite | Yes |
|
||||
| `start` | TanStack Start | Yes |
|
||||
| `react-router` | React Router | Yes |
|
||||
| `astro` | Astro | Yes |
|
||||
| `laravel` | Laravel | No |
|
||||
|
||||
All templates support monorepo scaffolding via the `--monorepo` flag. When passed, the CLI uses a monorepo-specific template directory (e.g. `next-monorepo`, `vite-monorepo`). When neither `--monorepo` nor `--no-monorepo` is passed, the CLI prompts interactively. Laravel does not support monorepo scaffolding.
|
||||
|
||||
---
|
||||
|
||||
## Presets
|
||||
|
||||
Three ways to specify a preset via `--preset`:
|
||||
|
||||
1. **Named:** `--preset nova` or `--preset lyra`
|
||||
2. **Code:** `--preset a2r6bw` (version-prefixed base62 string, e.g. `a2r6bw` or `b0`)
|
||||
3. **URL:** `--preset "https://ui.shadcn.com/init?base=radix&style=nova&..."`
|
||||
|
||||
> **IMPORTANT:** Never try to decode, fetch, or resolve preset codes manually. Preset codes are opaque — pass them directly to `npx shadcn@latest init --preset <code>` and let the CLI handle resolution.
|
||||
> Use `npx shadcn@latest apply --preset <code>` when overwriting an existing project's preset.
|
||||
|
||||
## Switching Presets
|
||||
|
||||
Ask the user first: **overwrite**, **merge**, or **skip** existing components?
|
||||
|
||||
- **Overwrite / Re-install** → `npx shadcn@latest apply --preset <code>`. Overwrites all detected component files with the new preset styles. Use when the user hasn't customized components.
|
||||
- **Merge** → `npx shadcn@latest init --preset <code> --force --no-reinstall`, then run `npx shadcn@latest info` to get the list of installed components and use the [smart merge workflow](./SKILL.md#updating-components) to update them one by one, preserving local changes. Use when the user has customized components.
|
||||
- **Skip** → `npx shadcn@latest init --preset <code> --force --no-reinstall`. Only updates config and CSS variables, leaves existing components as-is.
|
||||
|
||||
Always run preset commands inside the user's project directory. `apply` only works in an existing project with a `components.json` file. The CLI automatically preserves the current base (`base` vs `radix`) from `components.json`. If you must use a scratch/temp directory (e.g. for `--dry-run` comparisons), pass `--base <current-base>` explicitly — preset codes do not encode the base.
|
||||
@@ -0,0 +1,209 @@
|
||||
# Customization & Theming
|
||||
|
||||
Components reference semantic CSS variable tokens. Change the variables to change every component.
|
||||
|
||||
## Contents
|
||||
|
||||
- How it works (CSS variables → Tailwind utilities → components)
|
||||
- Color variables and OKLCH format
|
||||
- Dark mode setup
|
||||
- Changing the theme (presets, CSS variables)
|
||||
- Adding custom colors (Tailwind v3 and v4)
|
||||
- Border radius
|
||||
- Customizing components (variants, className, wrappers)
|
||||
- Checking for updates
|
||||
|
||||
---
|
||||
|
||||
## How It Works
|
||||
|
||||
1. CSS variables defined in `:root` (light) and `.dark` (dark mode).
|
||||
2. Tailwind maps them to utilities: `bg-primary`, `text-muted-foreground`, etc.
|
||||
3. Components use these utilities — changing a variable changes all components that reference it.
|
||||
|
||||
---
|
||||
|
||||
## Color Variables
|
||||
|
||||
Every color follows the `name` / `name-foreground` convention. The base variable is for backgrounds, `-foreground` is for text/icons on that background.
|
||||
|
||||
| Variable | Purpose |
|
||||
| -------------------------------------------- | -------------------------------- |
|
||||
| `--background` / `--foreground` | Page background and default text |
|
||||
| `--card` / `--card-foreground` | Card surfaces |
|
||||
| `--primary` / `--primary-foreground` | Primary buttons and actions |
|
||||
| `--secondary` / `--secondary-foreground` | Secondary actions |
|
||||
| `--muted` / `--muted-foreground` | Muted/disabled states |
|
||||
| `--accent` / `--accent-foreground` | Hover and accent states |
|
||||
| `--destructive` / `--destructive-foreground` | Error and destructive actions |
|
||||
| `--border` | Default border color |
|
||||
| `--input` | Form input borders |
|
||||
| `--ring` | Focus ring color |
|
||||
| `--chart-1` through `--chart-5` | Chart/data visualization |
|
||||
| `--sidebar-*` | Sidebar-specific colors |
|
||||
| `--surface` / `--surface-foreground` | Secondary surface |
|
||||
|
||||
Colors use OKLCH: `--primary: oklch(0.205 0 0)` where values are lightness (0–1), chroma (0 = gray), and hue (0–360).
|
||||
|
||||
---
|
||||
|
||||
## Dark Mode
|
||||
|
||||
Class-based toggle via `.dark` on the root element. In Next.js, use `next-themes`:
|
||||
|
||||
```tsx
|
||||
import { ThemeProvider } from "next-themes"
|
||||
|
||||
<ThemeProvider attribute="class" defaultTheme="system" enableSystem>
|
||||
{children}
|
||||
</ThemeProvider>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Changing the Theme
|
||||
|
||||
```bash
|
||||
# Apply a preset code from ui.shadcn.com.
|
||||
npx shadcn@latest apply --preset a2r6bw
|
||||
|
||||
# Positional shorthand also works.
|
||||
npx shadcn@latest apply a2r6bw
|
||||
|
||||
# Switch to a named preset and overwrite existing components.
|
||||
npx shadcn@latest apply --preset nova
|
||||
|
||||
# Preserve existing components instead.
|
||||
npx shadcn@latest init --preset nova --force --no-reinstall
|
||||
|
||||
# Use a custom theme URL.
|
||||
npx shadcn@latest apply --preset "https://ui.shadcn.com/init?base=radix&style=nova&theme=blue&..."
|
||||
```
|
||||
|
||||
Or edit CSS variables directly in `globals.css`.
|
||||
|
||||
---
|
||||
|
||||
## Adding Custom Colors
|
||||
|
||||
Add variables to the file at `tailwindCssFile` from `npx shadcn@latest info` (typically `globals.css`). Never create a new CSS file for this.
|
||||
|
||||
```css
|
||||
/* 1. Define in the global CSS file. */
|
||||
:root {
|
||||
--warning: oklch(0.84 0.16 84);
|
||||
--warning-foreground: oklch(0.28 0.07 46);
|
||||
}
|
||||
.dark {
|
||||
--warning: oklch(0.41 0.11 46);
|
||||
--warning-foreground: oklch(0.99 0.02 95);
|
||||
}
|
||||
```
|
||||
|
||||
```css
|
||||
/* 2a. Register with Tailwind v4 (@theme inline). */
|
||||
@theme inline {
|
||||
--color-warning: var(--warning);
|
||||
--color-warning-foreground: var(--warning-foreground);
|
||||
}
|
||||
```
|
||||
|
||||
When `tailwindVersion` is `"v3"` (check via `npx shadcn@latest info`), register in `tailwind.config.js` instead:
|
||||
|
||||
```js
|
||||
// 2b. Register with Tailwind v3 (tailwind.config.js).
|
||||
module.exports = {
|
||||
theme: {
|
||||
extend: {
|
||||
colors: {
|
||||
warning: "oklch(var(--warning) / <alpha-value>)",
|
||||
"warning-foreground":
|
||||
"oklch(var(--warning-foreground) / <alpha-value>)",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
```tsx
|
||||
// 3. Use in components.
|
||||
<div className="bg-warning text-warning-foreground">Warning</div>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Border Radius
|
||||
|
||||
`--radius` controls border radius globally. Components derive values from it (`rounded-lg` = `var(--radius)`, `rounded-md` = `calc(var(--radius) - 2px)`).
|
||||
|
||||
---
|
||||
|
||||
## Customizing Components
|
||||
|
||||
See also: [rules/styling.md](./rules/styling.md) for Incorrect/Correct examples.
|
||||
|
||||
Prefer these approaches in order:
|
||||
|
||||
### 1. Built-in variants
|
||||
|
||||
```tsx
|
||||
<Button variant="outline" size="sm">
|
||||
Click
|
||||
</Button>
|
||||
```
|
||||
|
||||
### 2. Tailwind classes via `className`
|
||||
|
||||
```tsx
|
||||
<Card className="mx-auto max-w-md">...</Card>
|
||||
```
|
||||
|
||||
### 3. Add a new variant
|
||||
|
||||
Edit the component source to add a variant via `cva`:
|
||||
|
||||
```tsx
|
||||
// components/ui/button.tsx
|
||||
warning: "bg-warning text-warning-foreground hover:bg-warning/90",
|
||||
```
|
||||
|
||||
### 4. Wrapper components
|
||||
|
||||
Compose shadcn/ui primitives into higher-level components:
|
||||
|
||||
```tsx
|
||||
export function ConfirmDialog({ title, description, onConfirm, children }) {
|
||||
return (
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger asChild>{children}</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{title}</AlertDialogTitle>
|
||||
<AlertDialogDescription>{description}</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={onConfirm}>Confirm</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Checking for Updates
|
||||
|
||||
```bash
|
||||
npx shadcn@latest add button --diff
|
||||
```
|
||||
|
||||
To preview exactly what would change before updating, use `--dry-run` and `--diff`:
|
||||
|
||||
```bash
|
||||
npx shadcn@latest add button --dry-run # see all affected files
|
||||
npx shadcn@latest add button --diff button.tsx # see the diff for a specific file
|
||||
```
|
||||
|
||||
See [Updating Components in SKILL.md](./SKILL.md#updating-components) for the full smart merge workflow.
|
||||
@@ -0,0 +1,47 @@
|
||||
{
|
||||
"skill_name": "shadcn",
|
||||
"evals": [
|
||||
{
|
||||
"id": 1,
|
||||
"prompt": "I'm building a Next.js app with shadcn/ui (base-nova preset, lucide icons). Create a settings form component with fields for: full name, email address, and notification preferences (email, SMS, push notifications as toggle options). Add validation states for required fields.",
|
||||
"expected_output": "A React component using FieldGroup, Field, ToggleGroup, data-invalid/aria-invalid validation, gap-* spacing, and semantic colors.",
|
||||
"files": [],
|
||||
"expectations": [
|
||||
"Uses FieldGroup and Field components for form layout instead of raw div with space-y",
|
||||
"Uses Switch for independent on/off notification toggles (not looping Button with manual active state)",
|
||||
"Uses data-invalid on Field and aria-invalid on the input control for validation states",
|
||||
"Uses gap-* (e.g. gap-4, gap-6) instead of space-y-* or space-x-* for spacing",
|
||||
"Uses semantic color tokens (e.g. bg-background, text-muted-foreground, text-destructive) instead of raw colors like bg-red-500",
|
||||
"No manual dark: color overrides"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"prompt": "Create a dialog component for editing a user profile. It should have the user's avatar at the top, input fields for name and bio, and Save/Cancel buttons with appropriate icons. Using shadcn/ui with radix-nova preset and tabler icons.",
|
||||
"expected_output": "A React component with DialogTitle, Avatar+AvatarFallback, data-icon on icon buttons, no icon sizing classes, tabler icon imports.",
|
||||
"files": [],
|
||||
"expectations": [
|
||||
"Includes DialogTitle for accessibility (visible or with sr-only class)",
|
||||
"Avatar component includes AvatarFallback",
|
||||
"Icons on buttons use the data-icon attribute (data-icon=\"inline-start\" or data-icon=\"inline-end\")",
|
||||
"No sizing classes on icons inside components (no size-4, w-4, h-4, etc.)",
|
||||
"Uses tabler icons (@tabler/icons-react) instead of lucide-react",
|
||||
"Uses asChild for custom triggers (radix preset)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"prompt": "Create a dashboard component that shows 4 stat cards in a grid. Each card has a title, large number, percentage change badge, and a loading skeleton state. Using shadcn/ui with base-nova preset and lucide icons.",
|
||||
"expected_output": "A React component with full Card composition, Skeleton for loading, Badge for changes, semantic colors, gap-* spacing.",
|
||||
"files": [],
|
||||
"expectations": [
|
||||
"Uses full Card composition with CardHeader, CardTitle, CardContent (not dumping everything into CardContent)",
|
||||
"Uses Skeleton component for loading placeholders instead of custom animate-pulse divs",
|
||||
"Uses Badge component for percentage change instead of custom styled spans",
|
||||
"Uses semantic color tokens instead of raw color values like bg-green-500 or text-red-600",
|
||||
"Uses gap-* instead of space-y-* or space-x-* for spacing",
|
||||
"Uses size-* when width and height are equal instead of separate w-* h-*"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
# shadcn MCP Server
|
||||
|
||||
The CLI includes an MCP server that lets AI assistants search, browse, view, and install items from registries.
|
||||
|
||||
---
|
||||
|
||||
## Setup
|
||||
|
||||
```bash
|
||||
shadcn mcp # start the MCP server (stdio)
|
||||
shadcn mcp init # write config for your editor
|
||||
```
|
||||
|
||||
Editor config files:
|
||||
|
||||
| Editor | Config file |
|
||||
| ----------- | ------------------------------- |
|
||||
| Claude Code | `.mcp.json` |
|
||||
| Cursor | `.cursor/mcp.json` |
|
||||
| VS Code | `.vscode/mcp.json` |
|
||||
| OpenCode | `opencode.json` |
|
||||
| Codex | `~/.codex/config.toml` (manual) |
|
||||
|
||||
---
|
||||
|
||||
## Tools
|
||||
|
||||
> **Tip:** MCP tools handle registry operations (search, view, install). For project configuration (aliases, framework, Tailwind version), use `npx shadcn@latest info` — there is no MCP equivalent.
|
||||
|
||||
### `shadcn:get_project_registries`
|
||||
|
||||
Returns registry names from `components.json`. Errors if no `components.json` exists.
|
||||
|
||||
**Input:** none
|
||||
|
||||
### `shadcn:list_items_in_registries`
|
||||
|
||||
Lists all items from one or more registries. Registries can be configured
|
||||
namespaces such as `@acme`, public GitHub sources such as `owner/repo`, or
|
||||
registry catalog URLs. Omit `registries` to list from every registry configured
|
||||
in `components.json`.
|
||||
|
||||
**Input:** `registries` (string[], optional — omit for all configured), `types` (string[], optional — e.g. `["ui", "block"]`), `limit` (number, optional, defaults to 100), `offset` (number, optional)
|
||||
|
||||
### `shadcn:search_items_in_registries`
|
||||
|
||||
Fuzzy search across registries. Registries can be configured namespaces, public
|
||||
GitHub sources, or registry catalog URLs. Omit `registries` to search every
|
||||
registry configured in `components.json` — e.g. "find me a hero" across all
|
||||
configured registries.
|
||||
|
||||
**Input:** `registries` (string[], optional — omit for all configured), `query` (string), `types` (string[], optional — e.g. `["ui", "block"]`), `limit` (number, optional, defaults to 100), `offset` (number, optional)
|
||||
|
||||
### `shadcn:view_items_in_registries`
|
||||
|
||||
View item details including full file contents.
|
||||
|
||||
**Input:** `items` (string[]) — e.g.
|
||||
`["@shadcn/button", "@shadcn/card", "owner/repo/item"]`
|
||||
|
||||
### `shadcn:get_item_examples_from_registries`
|
||||
|
||||
Find usage examples and demos with source code. Omit `registries` to search
|
||||
every registry configured in `components.json`.
|
||||
|
||||
**Input:** `registries` (string[], optional — omit for all configured), `query` (string) — e.g. `"accordion-demo"`, `"button example"`
|
||||
|
||||
### `shadcn:get_add_command_for_items`
|
||||
|
||||
Returns the CLI install command.
|
||||
|
||||
**Input:** `items` (string[]) — e.g. `["@shadcn/button"]`
|
||||
|
||||
### `shadcn:get_audit_checklist`
|
||||
|
||||
Returns a checklist for verifying components (imports, deps, lint, TypeScript).
|
||||
|
||||
**Input:** none
|
||||
|
||||
---
|
||||
|
||||
## Configuring Registries
|
||||
|
||||
Namespaced and authenticated registries are set in `components.json`. The
|
||||
`@shadcn` registry is always built-in. Public GitHub registries can also be used
|
||||
directly as `owner/repo` registry sources when the repository has a root
|
||||
`registry.json`; they do not need `components.json` configuration.
|
||||
|
||||
```json
|
||||
{
|
||||
"registries": {
|
||||
"@acme": "https://acme.com/r/{name}.json",
|
||||
"@private": {
|
||||
"url": "https://private.com/r/{name}.json",
|
||||
"headers": { "Authorization": "Bearer ${MY_TOKEN}" }
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- Names must start with `@`.
|
||||
- URLs must contain `{name}`.
|
||||
- `${VAR}` references are resolved from environment variables.
|
||||
|
||||
Community registry index: `https://ui.shadcn.com/r/registries.json`
|
||||
@@ -0,0 +1,277 @@
|
||||
# Registry Authoring and Addresses
|
||||
|
||||
Use this reference when the user wants to create, fix, publish, or reason about
|
||||
a shadcn registry.
|
||||
|
||||
## Mental Model
|
||||
|
||||
A registry has two forms:
|
||||
|
||||
- **Source registry**: an authored `registry.json` in a project or repository.
|
||||
It may use `include` and file paths that point at source files.
|
||||
- **Built registry**: generated JSON files served to CLI consumers, usually
|
||||
from `public/r`. Use `npx shadcn@latest build` to create this form.
|
||||
|
||||
The CLI installer consumes registry item payloads. A source registry is a way to
|
||||
author those payloads from real files.
|
||||
|
||||
Registry items are not limited to React components. They can distribute
|
||||
components, hooks, utilities, design tokens, pages, config files, docs, rules,
|
||||
workflows, templates, MCP files, and other project files.
|
||||
|
||||
## Root `registry.json`
|
||||
|
||||
The root registry file should define registry metadata and either `items` or
|
||||
`include`.
|
||||
|
||||
```json
|
||||
{
|
||||
"$schema": "https://ui.shadcn.com/schema/registry.json",
|
||||
"name": "acme",
|
||||
"homepage": "https://acme.com",
|
||||
"items": [
|
||||
{
|
||||
"name": "absolute-url",
|
||||
"type": "registry:lib",
|
||||
"title": "Absolute URL",
|
||||
"description": "A utility to turn any path into an absolute URL.",
|
||||
"files": [
|
||||
{
|
||||
"path": "lib/absolute-url.ts",
|
||||
"type": "registry:lib"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Root registry rules:
|
||||
|
||||
- Root `registry.json` must include `name` and `homepage`.
|
||||
- `items` is an array of registry item definitions.
|
||||
- `include` may be used to split the source registry into multiple files.
|
||||
- Included registry files may omit `name` and `homepage`.
|
||||
|
||||
## Include
|
||||
|
||||
Use `include` to keep large registries modular.
|
||||
|
||||
```json
|
||||
{
|
||||
"$schema": "https://ui.shadcn.com/schema/registry.json",
|
||||
"name": "acme",
|
||||
"homepage": "https://acme.com",
|
||||
"include": ["registry/ui/registry.json", "registry/blocks/registry.json"]
|
||||
}
|
||||
```
|
||||
|
||||
Include rules:
|
||||
|
||||
- Include paths are relative to the `registry.json` that declares them.
|
||||
- Include paths must explicitly point to a `registry.json` file.
|
||||
- Do not use remote URLs, absolute paths, or parent traversal (`..`).
|
||||
- Item file paths are relative to the registry file that declares the item.
|
||||
- Duplicate item names fail across the resolved registry.
|
||||
|
||||
Example included file:
|
||||
|
||||
```json
|
||||
{
|
||||
"items": [
|
||||
{
|
||||
"name": "button",
|
||||
"type": "registry:ui",
|
||||
"files": [
|
||||
{
|
||||
"path": "button.tsx",
|
||||
"type": "registry:ui"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
If this file is at `registry/ui/registry.json`, then `button.tsx` is read from
|
||||
`registry/ui/button.tsx`, and the built item path is emitted relative to the
|
||||
root registry.
|
||||
|
||||
## Item Definitions
|
||||
|
||||
Common item fields:
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "login-form",
|
||||
"type": "registry:block",
|
||||
"title": "Login Form",
|
||||
"description": "A login form with email and password fields.",
|
||||
"dependencies": ["zod"],
|
||||
"registryDependencies": ["button", "input", "label"],
|
||||
"files": [
|
||||
{
|
||||
"path": "blocks/login-form.tsx",
|
||||
"type": "registry:block"
|
||||
}
|
||||
],
|
||||
"cssVars": {
|
||||
"light": {
|
||||
"brand": "oklch(0.62 0.18 250)"
|
||||
},
|
||||
"dark": {
|
||||
"brand": "oklch(0.72 0.16 250)"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Important fields:
|
||||
|
||||
- `name`: the installable item name. It is not necessarily a file path.
|
||||
- `type`: one of the registry item types, such as `registry:ui`,
|
||||
`registry:block`, `registry:lib`, `registry:hook`, `registry:file`,
|
||||
`registry:page`, `registry:theme`, `registry:style`, `registry:font`, or
|
||||
`registry:item`.
|
||||
- `files`: source files copied or generated by the item.
|
||||
- `dependencies`: npm runtime dependencies.
|
||||
- `devDependencies`: npm development dependencies.
|
||||
- `registryDependencies`: other registry items required by this item.
|
||||
- `cssVars`, `css`, `tailwind`, `envVars`, and `docs`: optional install-time
|
||||
additions.
|
||||
|
||||
File rules:
|
||||
|
||||
- File paths are relative to the declaring `registry.json`.
|
||||
- `registry:file` and `registry:page` files require a `target`.
|
||||
- Do not use remote file URLs in source registry file paths.
|
||||
- Keep source files copy-pasteable: no hidden app-only imports.
|
||||
|
||||
## Registry Dependencies
|
||||
|
||||
`registryDependencies` entries are item addresses, not file paths.
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "login-form",
|
||||
"type": "registry:block",
|
||||
"registryDependencies": ["button", "@acme/input", "acme/ui/card#v1.2.0"],
|
||||
"files": [
|
||||
{
|
||||
"path": "blocks/login-form.tsx",
|
||||
"type": "registry:block"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Dependency rules:
|
||||
|
||||
- Bare names such as `"button"` mean official shadcn items.
|
||||
- Bare names never mean same-registry or same-repository items.
|
||||
- Namespaced dependencies use `@namespace/item-name`.
|
||||
- GitHub dependencies use `owner/repo/item-name`.
|
||||
- Pin GitHub dependencies with `owner/repo/item-name#ref` when needed.
|
||||
- Refs are not inherited. If `owner/repo/foo#v2` depends on `bar` from the same
|
||||
repo at `v2`, write `owner/repo/bar#v2`.
|
||||
- Do not use relative dependencies such as `"./bar"`.
|
||||
|
||||
## Address Schemes
|
||||
|
||||
When reasoning about a registry item string, classify it first.
|
||||
|
||||
| Address | Scheme | Meaning |
|
||||
| ----------------------------------- | --------- | ------------------------------------------------------------ |
|
||||
| `button` | shadcn | Official shadcn item named `button`. |
|
||||
| `@acme/button` | namespace | Item `button` from configured registry `@acme`. |
|
||||
| `@acme/ui/button` | namespace | Item `ui/button` from configured registry `@acme`. |
|
||||
| `https://example.com/r/button.json` | url | Built registry item JSON at that URL. |
|
||||
| `./button.json` | file | Built registry item JSON on disk. |
|
||||
| `acme/ui/button` | github | Item `button` from GitHub repo `acme/ui`. |
|
||||
| `acme/ui/forms/login#main` | github | Item `forms/login` from GitHub repo `acme/ui` at ref `main`. |
|
||||
|
||||
For namespace and GitHub addresses, slashful item names are allowed and are item
|
||||
names, not file paths. Addresses ending in `.json` keep file-address
|
||||
precedence, so `acme/ui/data/schema.json` is treated as a file path, not a
|
||||
GitHub item address.
|
||||
|
||||
## GitHub Registries
|
||||
|
||||
A public GitHub repository can act as a source registry when it has a root
|
||||
`registry.json`.
|
||||
|
||||
```txt
|
||||
owner/repo/item-name[#ref]
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
- The first two path segments are GitHub owner and repo.
|
||||
- All remaining path segments are the registry item name.
|
||||
- The source entrypoint is always root `registry.json`.
|
||||
- GitHub registries are source registries consumed directly by the CLI. They do
|
||||
not require `shadcn build` or generated item JSON files.
|
||||
- `include` follows the same source-registry rules as local registries.
|
||||
- Currently, GitHub addresses support public `github.com` repositories only.
|
||||
- Private repos and GitHub Enterprise require explicit product decisions.
|
||||
|
||||
When implementing GitHub registry fetching, resolve refs to a commit SHA before
|
||||
reading source files. Do not read moving refs directly from
|
||||
`raw.githubusercontent.com`, because branch-like refs can be cached for several
|
||||
minutes.
|
||||
|
||||
Preferred flow:
|
||||
|
||||
```txt
|
||||
owner/repo[#ref]
|
||||
-> resolve ref with git ls-remote
|
||||
-> commit SHA
|
||||
-> read https://raw.githubusercontent.com/{owner}/{repo}/{sha}/registry.json
|
||||
-> read includes and item files from the same SHA
|
||||
```
|
||||
|
||||
This keeps a command on one consistent repository snapshot.
|
||||
|
||||
Full 40-character commit SHAs are already stable and can be used directly.
|
||||
Branches, tags, and short refs require Git so the CLI can resolve them to a
|
||||
commit SHA first.
|
||||
|
||||
## Build and Verify
|
||||
|
||||
Use the CLI to build source registries:
|
||||
|
||||
```bash
|
||||
npx shadcn@latest build
|
||||
npx shadcn@latest build registry.json --output public/r
|
||||
```
|
||||
|
||||
Use CLI commands to inspect the result:
|
||||
|
||||
```bash
|
||||
npx shadcn@latest list @acme
|
||||
npx shadcn@latest search @acme -q "login"
|
||||
npx shadcn@latest view @acme/login-form
|
||||
npx shadcn@latest add @acme/login-form --dry-run
|
||||
npx shadcn@latest registry validate ./registry.json
|
||||
```
|
||||
|
||||
Use GitHub addresses directly for public GitHub registries:
|
||||
|
||||
```bash
|
||||
npx shadcn@latest list owner/repo
|
||||
npx shadcn@latest search owner/repo -q "login"
|
||||
npx shadcn@latest view owner/repo/item
|
||||
npx shadcn@latest add owner/repo/item --dry-run
|
||||
npx shadcn@latest registry validate owner/repo
|
||||
```
|
||||
|
||||
When working on registry implementation in the shadcn/ui codebase:
|
||||
|
||||
- Keep address parsing pure and testable.
|
||||
- Do not add side effects to validators.
|
||||
- Preserve existing behavior for official shadcn, namespace, URL, and file
|
||||
schemes.
|
||||
- Add tests for address parsing, source loading, dependency resolution, list,
|
||||
search, view, and add paths.
|
||||
- Prefer small source-reader abstractions over a plugin system until there are
|
||||
multiple real providers.
|
||||
@@ -0,0 +1,306 @@
|
||||
# Base vs Radix
|
||||
|
||||
API differences between `base` and `radix`. Check the `base` field from `npx shadcn@latest info`.
|
||||
|
||||
## Contents
|
||||
|
||||
- Composition: asChild vs render
|
||||
- Button / trigger as non-button element
|
||||
- Select (items prop, placeholder, positioning, multiple, object values)
|
||||
- ToggleGroup (type vs multiple)
|
||||
- Slider (scalar vs array)
|
||||
- Accordion (type and defaultValue)
|
||||
|
||||
---
|
||||
|
||||
## Composition: asChild (radix) vs render (base)
|
||||
|
||||
Radix uses `asChild` to replace the default element. Base uses `render`. Don't wrap triggers in extra elements.
|
||||
|
||||
**Incorrect:**
|
||||
|
||||
```tsx
|
||||
<DialogTrigger>
|
||||
<div>
|
||||
<Button>Open</Button>
|
||||
</div>
|
||||
</DialogTrigger>
|
||||
```
|
||||
|
||||
**Correct (radix):**
|
||||
|
||||
```tsx
|
||||
<DialogTrigger asChild>
|
||||
<Button>Open</Button>
|
||||
</DialogTrigger>
|
||||
```
|
||||
|
||||
**Correct (base):**
|
||||
|
||||
```tsx
|
||||
<DialogTrigger render={<Button />}>Open</DialogTrigger>
|
||||
```
|
||||
|
||||
This applies to all trigger and close components: `DialogTrigger`, `SheetTrigger`, `AlertDialogTrigger`, `DropdownMenuTrigger`, `PopoverTrigger`, `TooltipTrigger`, `CollapsibleTrigger`, `DialogClose`, `SheetClose`, `NavigationMenuLink`, `BreadcrumbLink`, `SidebarMenuButton`, `Badge`, `Item`.
|
||||
|
||||
---
|
||||
|
||||
## Button / trigger as non-button element (base only)
|
||||
|
||||
When `render` changes an element to a non-button (`<a>`, `<span>`), add `nativeButton={false}`.
|
||||
|
||||
**Incorrect (base):** missing `nativeButton={false}`.
|
||||
|
||||
```tsx
|
||||
<Button render={<a href="/docs" />}>Read the docs</Button>
|
||||
```
|
||||
|
||||
**Correct (base):**
|
||||
|
||||
```tsx
|
||||
<Button render={<a href="/docs" />} nativeButton={false}>
|
||||
Read the docs
|
||||
</Button>
|
||||
```
|
||||
|
||||
**Correct (radix):**
|
||||
|
||||
```tsx
|
||||
<Button asChild>
|
||||
<a href="/docs">Read the docs</a>
|
||||
</Button>
|
||||
```
|
||||
|
||||
Same for triggers whose `render` is not a `Button`:
|
||||
|
||||
```tsx
|
||||
// base.
|
||||
<PopoverTrigger render={<InputGroupAddon />} nativeButton={false}>
|
||||
Pick date
|
||||
</PopoverTrigger>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Select
|
||||
|
||||
**items prop (base only).** Base requires an `items` prop on the root. Radix uses inline JSX only.
|
||||
|
||||
**Incorrect (base):**
|
||||
|
||||
```tsx
|
||||
<Select>
|
||||
<SelectTrigger><SelectValue placeholder="Select a fruit" /></SelectTrigger>
|
||||
</Select>
|
||||
```
|
||||
|
||||
**Correct (base):**
|
||||
|
||||
```tsx
|
||||
const items = [
|
||||
{ label: "Select a fruit", value: null },
|
||||
{ label: "Apple", value: "apple" },
|
||||
{ label: "Banana", value: "banana" },
|
||||
]
|
||||
|
||||
<Select items={items}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectGroup>
|
||||
{items.map((item) => (
|
||||
<SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>
|
||||
))}
|
||||
</SelectGroup>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
```
|
||||
|
||||
**Correct (radix):**
|
||||
|
||||
```tsx
|
||||
<Select>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select a fruit" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectGroup>
|
||||
<SelectItem value="apple">Apple</SelectItem>
|
||||
<SelectItem value="banana">Banana</SelectItem>
|
||||
</SelectGroup>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
```
|
||||
|
||||
**Placeholder.** Base uses a `{ value: null }` item in the items array. Radix uses `<SelectValue placeholder="...">`.
|
||||
|
||||
**Content positioning.** Base uses `alignItemWithTrigger`. Radix uses `position`.
|
||||
|
||||
```tsx
|
||||
// base.
|
||||
<SelectContent alignItemWithTrigger={false} side="bottom">
|
||||
|
||||
// radix.
|
||||
<SelectContent position="popper">
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Select — multiple selection and object values (base only)
|
||||
|
||||
Base supports `multiple`, render-function children on `SelectValue`, and object values with `itemToStringValue`. Radix is single-select with string values only.
|
||||
|
||||
**Correct (base — multiple selection):**
|
||||
|
||||
```tsx
|
||||
<Select items={items} multiple defaultValue={[]}>
|
||||
<SelectTrigger>
|
||||
<SelectValue>
|
||||
{(value: string[]) => value.length === 0 ? "Select fruits" : `${value.length} selected`}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
...
|
||||
</Select>
|
||||
```
|
||||
|
||||
**Correct (base — object values):**
|
||||
|
||||
```tsx
|
||||
<Select defaultValue={plans[0]} itemToStringValue={(plan) => plan.name}>
|
||||
<SelectTrigger>
|
||||
<SelectValue>{(value) => value.name}</SelectValue>
|
||||
</SelectTrigger>
|
||||
...
|
||||
</Select>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ToggleGroup
|
||||
|
||||
Base uses a `multiple` boolean prop. Radix uses `type="single"` or `type="multiple"`.
|
||||
|
||||
**Incorrect (base):**
|
||||
|
||||
```tsx
|
||||
<ToggleGroup type="single" defaultValue="daily">
|
||||
<ToggleGroupItem value="daily">Daily</ToggleGroupItem>
|
||||
</ToggleGroup>
|
||||
```
|
||||
|
||||
**Correct (base):**
|
||||
|
||||
```tsx
|
||||
// Single (no prop needed), defaultValue is always an array.
|
||||
<ToggleGroup defaultValue={["daily"]} spacing={2}>
|
||||
<ToggleGroupItem value="daily">Daily</ToggleGroupItem>
|
||||
<ToggleGroupItem value="weekly">Weekly</ToggleGroupItem>
|
||||
</ToggleGroup>
|
||||
|
||||
// Multi-selection.
|
||||
<ToggleGroup multiple>
|
||||
<ToggleGroupItem value="bold">Bold</ToggleGroupItem>
|
||||
<ToggleGroupItem value="italic">Italic</ToggleGroupItem>
|
||||
</ToggleGroup>
|
||||
```
|
||||
|
||||
**Correct (radix):**
|
||||
|
||||
```tsx
|
||||
// Single, defaultValue is a string.
|
||||
<ToggleGroup type="single" defaultValue="daily" spacing={2}>
|
||||
<ToggleGroupItem value="daily">Daily</ToggleGroupItem>
|
||||
<ToggleGroupItem value="weekly">Weekly</ToggleGroupItem>
|
||||
</ToggleGroup>
|
||||
|
||||
// Multi-selection.
|
||||
<ToggleGroup type="multiple">
|
||||
<ToggleGroupItem value="bold">Bold</ToggleGroupItem>
|
||||
<ToggleGroupItem value="italic">Italic</ToggleGroupItem>
|
||||
</ToggleGroup>
|
||||
```
|
||||
|
||||
**Controlled single value:**
|
||||
|
||||
```tsx
|
||||
// base — wrap/unwrap arrays.
|
||||
const [value, setValue] = React.useState("normal")
|
||||
<ToggleGroup value={[value]} onValueChange={(v) => setValue(v[0])}>
|
||||
|
||||
// radix — plain string.
|
||||
const [value, setValue] = React.useState("normal")
|
||||
<ToggleGroup type="single" value={value} onValueChange={setValue}>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Slider
|
||||
|
||||
Base accepts a plain number for a single thumb. Radix always requires an array.
|
||||
|
||||
**Incorrect (base):**
|
||||
|
||||
```tsx
|
||||
<Slider defaultValue={[50]} max={100} step={1} />
|
||||
```
|
||||
|
||||
**Correct (base):**
|
||||
|
||||
```tsx
|
||||
<Slider defaultValue={50} max={100} step={1} />
|
||||
```
|
||||
|
||||
**Correct (radix):**
|
||||
|
||||
```tsx
|
||||
<Slider defaultValue={[50]} max={100} step={1} />
|
||||
```
|
||||
|
||||
Both use arrays for range sliders. Controlled `onValueChange` in base may need a cast:
|
||||
|
||||
```tsx
|
||||
// base.
|
||||
const [value, setValue] = React.useState([0.3, 0.7])
|
||||
<Slider value={value} onValueChange={(v) => setValue(v as number[])} />
|
||||
|
||||
// radix.
|
||||
const [value, setValue] = React.useState([0.3, 0.7])
|
||||
<Slider value={value} onValueChange={setValue} />
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Accordion
|
||||
|
||||
Radix requires `type="single"` or `type="multiple"` and supports `collapsible`. `defaultValue` is a string. Base uses no `type` prop, uses `multiple` boolean, and `defaultValue` is always an array.
|
||||
|
||||
**Incorrect (base):**
|
||||
|
||||
```tsx
|
||||
<Accordion type="single" collapsible defaultValue="item-1">
|
||||
<AccordionItem value="item-1">...</AccordionItem>
|
||||
</Accordion>
|
||||
```
|
||||
|
||||
**Correct (base):**
|
||||
|
||||
```tsx
|
||||
<Accordion defaultValue={["item-1"]}>
|
||||
<AccordionItem value="item-1">...</AccordionItem>
|
||||
</Accordion>
|
||||
|
||||
// Multi-select.
|
||||
<Accordion multiple defaultValue={["item-1", "item-2"]}>
|
||||
<AccordionItem value="item-1">...</AccordionItem>
|
||||
<AccordionItem value="item-2">...</AccordionItem>
|
||||
</Accordion>
|
||||
```
|
||||
|
||||
**Correct (radix):**
|
||||
|
||||
```tsx
|
||||
<Accordion type="single" collapsible defaultValue="item-1">
|
||||
<AccordionItem value="item-1">...</AccordionItem>
|
||||
</Accordion>
|
||||
```
|
||||
@@ -0,0 +1,195 @@
|
||||
# Component Composition
|
||||
|
||||
## Contents
|
||||
|
||||
- Items always inside their Group component
|
||||
- Callouts use Alert
|
||||
- Empty states use Empty component
|
||||
- Toast notifications use sonner
|
||||
- Choosing between overlay components
|
||||
- Dialog, Sheet, and Drawer always need a Title
|
||||
- Card structure
|
||||
- Button has no isPending or isLoading prop
|
||||
- TabsTrigger must be inside TabsList
|
||||
- Avatar always needs AvatarFallback
|
||||
- Use Separator instead of raw hr or border divs
|
||||
- Use Skeleton for loading placeholders
|
||||
- Use Badge instead of custom styled spans
|
||||
|
||||
---
|
||||
|
||||
## Items always inside their Group component
|
||||
|
||||
Never render items directly inside the content container.
|
||||
|
||||
**Incorrect:**
|
||||
|
||||
```tsx
|
||||
<SelectContent>
|
||||
<SelectItem value="apple">Apple</SelectItem>
|
||||
<SelectItem value="banana">Banana</SelectItem>
|
||||
</SelectContent>
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```tsx
|
||||
<SelectContent>
|
||||
<SelectGroup>
|
||||
<SelectItem value="apple">Apple</SelectItem>
|
||||
<SelectItem value="banana">Banana</SelectItem>
|
||||
</SelectGroup>
|
||||
</SelectContent>
|
||||
```
|
||||
|
||||
This applies to all group-based components:
|
||||
|
||||
| Item | Group |
|
||||
|------|-------|
|
||||
| `SelectItem`, `SelectLabel` | `SelectGroup` |
|
||||
| `DropdownMenuItem`, `DropdownMenuLabel`, `DropdownMenuSub` | `DropdownMenuGroup` |
|
||||
| `MenubarItem` | `MenubarGroup` |
|
||||
| `ContextMenuItem` | `ContextMenuGroup` |
|
||||
| `CommandItem` | `CommandGroup` |
|
||||
|
||||
---
|
||||
|
||||
## Callouts use Alert
|
||||
|
||||
```tsx
|
||||
<Alert>
|
||||
<AlertTitle>Warning</AlertTitle>
|
||||
<AlertDescription>Something needs attention.</AlertDescription>
|
||||
</Alert>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Empty states use Empty component
|
||||
|
||||
```tsx
|
||||
<Empty>
|
||||
<EmptyHeader>
|
||||
<EmptyMedia variant="icon"><FolderIcon /></EmptyMedia>
|
||||
<EmptyTitle>No projects yet</EmptyTitle>
|
||||
<EmptyDescription>Get started by creating a new project.</EmptyDescription>
|
||||
</EmptyHeader>
|
||||
<EmptyContent>
|
||||
<Button>Create Project</Button>
|
||||
</EmptyContent>
|
||||
</Empty>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Toast notifications use sonner
|
||||
|
||||
```tsx
|
||||
import { toast } from "sonner"
|
||||
|
||||
toast.success("Changes saved.")
|
||||
toast.error("Something went wrong.")
|
||||
toast("File deleted.", {
|
||||
action: { label: "Undo", onClick: () => undoDelete() },
|
||||
})
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Choosing between overlay components
|
||||
|
||||
| Use case | Component |
|
||||
|----------|-----------|
|
||||
| Focused task that requires input | `Dialog` |
|
||||
| Destructive action confirmation | `AlertDialog` |
|
||||
| Side panel with details or filters | `Sheet` |
|
||||
| Mobile-first bottom panel | `Drawer` |
|
||||
| Quick info on hover | `HoverCard` |
|
||||
| Small contextual content on click | `Popover` |
|
||||
|
||||
---
|
||||
|
||||
## Dialog, Sheet, and Drawer always need a Title
|
||||
|
||||
`DialogTitle`, `SheetTitle`, `DrawerTitle` are required for accessibility. Use `className="sr-only"` if visually hidden.
|
||||
|
||||
```tsx
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Edit Profile</DialogTitle>
|
||||
<DialogDescription>Update your profile.</DialogDescription>
|
||||
</DialogHeader>
|
||||
...
|
||||
</DialogContent>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Card structure
|
||||
|
||||
Use full composition — don't dump everything into `CardContent`:
|
||||
|
||||
```tsx
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Team Members</CardTitle>
|
||||
<CardDescription>Manage your team.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>...</CardContent>
|
||||
<CardFooter>
|
||||
<Button>Invite</Button>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Button has no isPending or isLoading prop
|
||||
|
||||
Compose with `Spinner` + `data-icon` + `disabled`:
|
||||
|
||||
```tsx
|
||||
<Button disabled>
|
||||
<Spinner data-icon="inline-start" />
|
||||
Saving...
|
||||
</Button>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## TabsTrigger must be inside TabsList
|
||||
|
||||
Never render `TabsTrigger` directly inside `Tabs` — always wrap in `TabsList`:
|
||||
|
||||
```tsx
|
||||
<Tabs defaultValue="account">
|
||||
<TabsList>
|
||||
<TabsTrigger value="account">Account</TabsTrigger>
|
||||
<TabsTrigger value="password">Password</TabsTrigger>
|
||||
</TabsList>
|
||||
<TabsContent value="account">...</TabsContent>
|
||||
</Tabs>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Avatar always needs AvatarFallback
|
||||
|
||||
Always include `AvatarFallback` for when the image fails to load:
|
||||
|
||||
```tsx
|
||||
<Avatar>
|
||||
<AvatarImage src="/avatar.png" alt="User" />
|
||||
<AvatarFallback>JD</AvatarFallback>
|
||||
</Avatar>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Use existing components instead of custom markup
|
||||
|
||||
| Instead of | Use |
|
||||
|---|---|
|
||||
| `<hr>` or `<div className="border-t">` | `<Separator />` |
|
||||
| `<div className="animate-pulse">` with styled divs | `<Skeleton className="h-4 w-3/4" />` |
|
||||
| `<span className="rounded-full bg-green-100 ...">` | `<Badge variant="secondary">` |
|
||||
@@ -0,0 +1,192 @@
|
||||
# Forms & Inputs
|
||||
|
||||
## Contents
|
||||
|
||||
- Forms use FieldGroup + Field
|
||||
- InputGroup requires InputGroupInput/InputGroupTextarea
|
||||
- Buttons inside inputs use InputGroup + InputGroupAddon
|
||||
- Option sets (2–7 choices) use ToggleGroup
|
||||
- FieldSet + FieldLegend for grouping related fields
|
||||
- Field validation and disabled states
|
||||
|
||||
---
|
||||
|
||||
## Forms use FieldGroup + Field
|
||||
|
||||
Always use `FieldGroup` + `Field` — never raw `div` with `space-y-*`:
|
||||
|
||||
```tsx
|
||||
<FieldGroup>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="email">Email</FieldLabel>
|
||||
<Input id="email" type="email" />
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="password">Password</FieldLabel>
|
||||
<Input id="password" type="password" />
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
```
|
||||
|
||||
Use `Field orientation="horizontal"` for settings pages. Use `FieldLabel className="sr-only"` for visually hidden labels.
|
||||
|
||||
**Choosing form controls:**
|
||||
|
||||
- Simple text input → `Input`
|
||||
- Dropdown with predefined options → `Select`
|
||||
- Searchable dropdown → `Combobox`
|
||||
- Native HTML select (no JS) → `native-select`
|
||||
- Boolean toggle → `Switch` (for settings) or `Checkbox` (for forms)
|
||||
- Single choice from few options → `RadioGroup`
|
||||
- Toggle between 2–5 options → `ToggleGroup` + `ToggleGroupItem`
|
||||
- OTP/verification code → `InputOTP`
|
||||
- Multi-line text → `Textarea`
|
||||
|
||||
---
|
||||
|
||||
## InputGroup requires InputGroupInput/InputGroupTextarea
|
||||
|
||||
Never use raw `Input` or `Textarea` inside an `InputGroup`.
|
||||
|
||||
**Incorrect:**
|
||||
|
||||
```tsx
|
||||
<InputGroup>
|
||||
<Input placeholder="Search..." />
|
||||
</InputGroup>
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```tsx
|
||||
import { InputGroup, InputGroupInput } from "@/components/ui/input-group"
|
||||
|
||||
<InputGroup>
|
||||
<InputGroupInput placeholder="Search..." />
|
||||
</InputGroup>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Buttons inside inputs use InputGroup + InputGroupAddon
|
||||
|
||||
Never place a `Button` directly inside or adjacent to an `Input` with custom positioning.
|
||||
|
||||
**Incorrect:**
|
||||
|
||||
```tsx
|
||||
<div className="relative">
|
||||
<Input placeholder="Search..." className="pr-10" />
|
||||
<Button className="absolute right-0 top-0" size="icon">
|
||||
<SearchIcon />
|
||||
</Button>
|
||||
</div>
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```tsx
|
||||
import { InputGroup, InputGroupInput, InputGroupAddon } from "@/components/ui/input-group"
|
||||
|
||||
<InputGroup>
|
||||
<InputGroupInput placeholder="Search..." />
|
||||
<InputGroupAddon>
|
||||
<Button size="icon">
|
||||
<SearchIcon data-icon="inline-start" />
|
||||
</Button>
|
||||
</InputGroupAddon>
|
||||
</InputGroup>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Option sets (2–7 choices) use ToggleGroup
|
||||
|
||||
Don't manually loop `Button` components with active state.
|
||||
|
||||
**Incorrect:**
|
||||
|
||||
```tsx
|
||||
const [selected, setSelected] = useState("daily")
|
||||
|
||||
<div className="flex gap-2">
|
||||
{["daily", "weekly", "monthly"].map((option) => (
|
||||
<Button
|
||||
key={option}
|
||||
variant={selected === option ? "default" : "outline"}
|
||||
onClick={() => setSelected(option)}
|
||||
>
|
||||
{option}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```tsx
|
||||
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group"
|
||||
|
||||
<ToggleGroup spacing={2}>
|
||||
<ToggleGroupItem value="daily">Daily</ToggleGroupItem>
|
||||
<ToggleGroupItem value="weekly">Weekly</ToggleGroupItem>
|
||||
<ToggleGroupItem value="monthly">Monthly</ToggleGroupItem>
|
||||
</ToggleGroup>
|
||||
```
|
||||
|
||||
Combine with `Field` for labelled toggle groups:
|
||||
|
||||
```tsx
|
||||
<Field orientation="horizontal">
|
||||
<FieldTitle id="theme-label">Theme</FieldTitle>
|
||||
<ToggleGroup aria-labelledby="theme-label" spacing={2}>
|
||||
<ToggleGroupItem value="light">Light</ToggleGroupItem>
|
||||
<ToggleGroupItem value="dark">Dark</ToggleGroupItem>
|
||||
<ToggleGroupItem value="system">System</ToggleGroupItem>
|
||||
</ToggleGroup>
|
||||
</Field>
|
||||
```
|
||||
|
||||
> **Note:** `defaultValue` and `type`/`multiple` props differ between base and radix. See [base-vs-radix.md](./base-vs-radix.md#togglegroup).
|
||||
|
||||
---
|
||||
|
||||
## FieldSet + FieldLegend for grouping related fields
|
||||
|
||||
Use `FieldSet` + `FieldLegend` for related checkboxes, radios, or switches — not `div` with a heading:
|
||||
|
||||
```tsx
|
||||
<FieldSet>
|
||||
<FieldLegend variant="label">Preferences</FieldLegend>
|
||||
<FieldDescription>Select all that apply.</FieldDescription>
|
||||
<FieldGroup className="gap-3">
|
||||
<Field orientation="horizontal">
|
||||
<Checkbox id="dark" />
|
||||
<FieldLabel htmlFor="dark" className="font-normal">Dark mode</FieldLabel>
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
</FieldSet>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Field validation and disabled states
|
||||
|
||||
Both attributes are needed — `data-invalid`/`data-disabled` styles the field (label, description), while `aria-invalid`/`disabled` styles the control.
|
||||
|
||||
```tsx
|
||||
// Invalid.
|
||||
<Field data-invalid>
|
||||
<FieldLabel htmlFor="email">Email</FieldLabel>
|
||||
<Input id="email" aria-invalid />
|
||||
<FieldDescription>Invalid email address.</FieldDescription>
|
||||
</Field>
|
||||
|
||||
// Disabled.
|
||||
<Field data-disabled>
|
||||
<FieldLabel htmlFor="email">Email</FieldLabel>
|
||||
<Input id="email" disabled />
|
||||
</Field>
|
||||
```
|
||||
|
||||
Works for all controls: `Input`, `Textarea`, `Select`, `Checkbox`, `RadioGroupItem`, `Switch`, `Slider`, `NativeSelect`, `InputOTP`.
|
||||
@@ -0,0 +1,101 @@
|
||||
# Icons
|
||||
|
||||
**Always use the project's configured `iconLibrary` for imports.** Check the `iconLibrary` field from project context: `lucide` → `lucide-react`, `tabler` → `@tabler/icons-react`, etc. Never assume `lucide-react`.
|
||||
|
||||
---
|
||||
|
||||
## Icons in Button use data-icon attribute
|
||||
|
||||
Add `data-icon="inline-start"` (prefix) or `data-icon="inline-end"` (suffix) to the icon. No sizing classes on the icon.
|
||||
|
||||
**Incorrect:**
|
||||
|
||||
```tsx
|
||||
<Button>
|
||||
<SearchIcon className="mr-2 size-4" />
|
||||
Search
|
||||
</Button>
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```tsx
|
||||
<Button>
|
||||
<SearchIcon data-icon="inline-start"/>
|
||||
Search
|
||||
</Button>
|
||||
|
||||
<Button>
|
||||
Next
|
||||
<ArrowRightIcon data-icon="inline-end"/>
|
||||
</Button>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## No sizing classes on icons inside components
|
||||
|
||||
Components handle icon sizing via CSS. Don't add `size-4`, `w-4 h-4`, or other sizing classes to icons inside `Button`, `DropdownMenuItem`, `Alert`, `Sidebar*`, or other shadcn components. Unless the user explicitly asks for custom icon sizes.
|
||||
|
||||
**Incorrect:**
|
||||
|
||||
```tsx
|
||||
<Button>
|
||||
<SearchIcon className="size-4" data-icon="inline-start" />
|
||||
Search
|
||||
</Button>
|
||||
|
||||
<DropdownMenuItem>
|
||||
<SettingsIcon className="mr-2 size-4" />
|
||||
Settings
|
||||
</DropdownMenuItem>
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```tsx
|
||||
<Button>
|
||||
<SearchIcon data-icon="inline-start" />
|
||||
Search
|
||||
</Button>
|
||||
|
||||
<DropdownMenuItem>
|
||||
<SettingsIcon />
|
||||
Settings
|
||||
</DropdownMenuItem>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Pass icons as component objects, not string keys
|
||||
|
||||
Use `icon={CheckIcon}`, not a string key to a lookup map.
|
||||
|
||||
**Incorrect:**
|
||||
|
||||
```tsx
|
||||
const iconMap = {
|
||||
check: CheckIcon,
|
||||
alert: AlertIcon,
|
||||
}
|
||||
|
||||
function StatusBadge({ icon }: { icon: string }) {
|
||||
const Icon = iconMap[icon]
|
||||
return <Icon />
|
||||
}
|
||||
|
||||
<StatusBadge icon="check" />
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```tsx
|
||||
// Import from the project's configured iconLibrary (e.g. lucide-react, @tabler/icons-react).
|
||||
import { CheckIcon } from "lucide-react"
|
||||
|
||||
function StatusBadge({ icon: Icon }: { icon: React.ComponentType }) {
|
||||
return <Icon />
|
||||
}
|
||||
|
||||
<StatusBadge icon={CheckIcon} />
|
||||
```
|
||||
@@ -0,0 +1,162 @@
|
||||
# Styling & Customization
|
||||
|
||||
See [customization.md](../customization.md) for theming, CSS variables, and adding custom colors.
|
||||
|
||||
## Contents
|
||||
|
||||
- Semantic colors
|
||||
- Built-in variants first
|
||||
- className for layout only
|
||||
- No space-x-* / space-y-*
|
||||
- Prefer size-* over w-* h-* when equal
|
||||
- Prefer truncate shorthand
|
||||
- No manual dark: color overrides
|
||||
- Use cn() for conditional classes
|
||||
- No manual z-index on overlay components
|
||||
|
||||
---
|
||||
|
||||
## Semantic colors
|
||||
|
||||
**Incorrect:**
|
||||
|
||||
```tsx
|
||||
<div className="bg-blue-500 text-white">
|
||||
<p className="text-gray-600">Secondary text</p>
|
||||
</div>
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```tsx
|
||||
<div className="bg-primary text-primary-foreground">
|
||||
<p className="text-muted-foreground">Secondary text</p>
|
||||
</div>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## No raw color values for status/state indicators
|
||||
|
||||
For positive, negative, or status indicators, use Badge variants, semantic tokens like `text-destructive`, or define custom CSS variables — don't reach for raw Tailwind colors.
|
||||
|
||||
**Incorrect:**
|
||||
|
||||
```tsx
|
||||
<span className="text-emerald-600">+20.1%</span>
|
||||
<span className="text-green-500">Active</span>
|
||||
<span className="text-red-600">-3.2%</span>
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```tsx
|
||||
<Badge variant="secondary">+20.1%</Badge>
|
||||
<Badge>Active</Badge>
|
||||
<span className="text-destructive">-3.2%</span>
|
||||
```
|
||||
|
||||
If you need a success/positive color that doesn't exist as a semantic token, use a Badge variant or ask the user about adding a custom CSS variable to the theme (see [customization.md](../customization.md)).
|
||||
|
||||
---
|
||||
|
||||
## Built-in variants first
|
||||
|
||||
**Incorrect:**
|
||||
|
||||
```tsx
|
||||
<Button className="border border-input bg-transparent hover:bg-accent">
|
||||
Click me
|
||||
</Button>
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```tsx
|
||||
<Button variant="outline">Click me</Button>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## className for layout only
|
||||
|
||||
Use `className` for layout (e.g. `max-w-md`, `mx-auto`, `mt-4`), **not** for overriding component colors or typography. To change colors, use semantic tokens, built-in variants, or CSS variables.
|
||||
|
||||
**Incorrect:**
|
||||
|
||||
```tsx
|
||||
<Card className="bg-blue-100 text-blue-900 font-bold">
|
||||
<CardContent>Dashboard</CardContent>
|
||||
</Card>
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```tsx
|
||||
<Card className="max-w-md mx-auto">
|
||||
<CardContent>Dashboard</CardContent>
|
||||
</Card>
|
||||
```
|
||||
|
||||
To customize a component's appearance, prefer these approaches in order:
|
||||
1. **Built-in variants** — `variant="outline"`, `variant="destructive"`, etc.
|
||||
2. **Semantic color tokens** — `bg-primary`, `text-muted-foreground`.
|
||||
3. **CSS variables** — define custom colors in the global CSS file (see [customization.md](../customization.md)).
|
||||
|
||||
---
|
||||
|
||||
## No space-x-* / space-y-*
|
||||
|
||||
Use `gap-*` instead. `space-y-4` → `flex flex-col gap-4`. `space-x-2` → `flex gap-2`.
|
||||
|
||||
```tsx
|
||||
<div className="flex flex-col gap-4">
|
||||
<Input />
|
||||
<Input />
|
||||
<Button>Submit</Button>
|
||||
</div>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Prefer size-* over w-* h-* when equal
|
||||
|
||||
`size-10` not `w-10 h-10`. Applies to icons, avatars, skeletons, etc.
|
||||
|
||||
---
|
||||
|
||||
## Prefer truncate shorthand
|
||||
|
||||
`truncate` not `overflow-hidden text-ellipsis whitespace-nowrap`.
|
||||
|
||||
---
|
||||
|
||||
## No manual dark: color overrides
|
||||
|
||||
Use semantic tokens — they handle light/dark via CSS variables. `bg-background text-foreground` not `bg-white dark:bg-gray-950`.
|
||||
|
||||
---
|
||||
|
||||
## Use cn() for conditional classes
|
||||
|
||||
Use the `cn()` utility from the project for conditional or merged class names. Don't write manual ternaries in className strings.
|
||||
|
||||
**Incorrect:**
|
||||
|
||||
```tsx
|
||||
<div className={`flex items-center ${isActive ? "bg-primary text-primary-foreground" : "bg-muted"}`}>
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```tsx
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
<div className={cn("flex items-center", isActive ? "bg-primary text-primary-foreground" : "bg-muted")}>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## No manual z-index on overlay components
|
||||
|
||||
`Dialog`, `Sheet`, `Drawer`, `AlertDialog`, `DropdownMenu`, `Popover`, `Tooltip`, `HoverCard` handle their own stacking. Never add `z-50` or `z-[999]`.
|
||||
@@ -0,0 +1,16 @@
|
||||
# CodeGraph data files
|
||||
# These are local to each machine and should not be committed
|
||||
|
||||
# Database
|
||||
*.db
|
||||
*.db-wal
|
||||
*.db-shm
|
||||
|
||||
# Cache
|
||||
cache/
|
||||
|
||||
# Logs
|
||||
*.log
|
||||
|
||||
# Hook markers
|
||||
.dirty
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"pid": 35132,
|
||||
"version": "0.9.9",
|
||||
"socketPath": "\\\\.\\pipe\\codegraph-7bcc7a2b16d00925",
|
||||
"startedAt": 1781511807694
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
---
|
||||
description: Backend API — при изменениях, затрагивающих UI, строго следовать shadcn Components/Blocks
|
||||
globs: backend/**/*
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
# Backend API + shadcn/ui
|
||||
|
||||
Rust backend: `backend/src/` (Axum, sqlx). Frontend потребляет API через TanStack Query.
|
||||
|
||||
## Когда правило активно
|
||||
|
||||
Любое изменение в `backend/src/api/handlers/`, DTO, полей ответа, которые отображаются в UI.
|
||||
|
||||
## Обязательный порядок
|
||||
|
||||
1. **Backend** — handler, валидация, тесты API
|
||||
2. **Схемы frontend** — `apps/web/src/lib/schemas.ts`, `apps/web/src/queries/index.ts`
|
||||
3. **UI** — **только** [shadcn Components](https://ui.shadcn.com/docs/components) и [Blocks](https://ui.shadcn.com/blocks)
|
||||
|
||||
## Запрещено на frontend при доработке API
|
||||
|
||||
- Новые raw `<table>` / `<select>` / кастомные badge-цвета
|
||||
- Кастомный CSS для отображения новых полей
|
||||
- Самописные формы без `Field` + RHF + Zod
|
||||
|
||||
## Рекомендуемые shadcn-паттерны для типовых API
|
||||
|
||||
| API-данные | UI (из docs) |
|
||||
|------------|--------------|
|
||||
| Список сущностей | `Table` в `DataTableCard` или `data-table` block |
|
||||
| Создание записи | `Card` + `FieldGroup` + RHF |
|
||||
| Enum/фильтр | `Select` |
|
||||
| Статус | `StatusBadge` → shadcn `Badge` variants |
|
||||
| Ошибка мутации | `sonner` `toast.error` |
|
||||
| Пустой список | `Empty` |
|
||||
| Сводка/метрики | `Card` section-cards ([dashboard-01](https://ui.shadcn.com/blocks)) |
|
||||
|
||||
## Согласованность
|
||||
|
||||
- Имена полей JSON — camelCase или snake_case как в существующем API; типы в Zod должны совпадать
|
||||
- Новый endpoint → `queryOptions` factory в `apps/web/src/queries/`, не inline в route
|
||||
|
||||
Главное правило frontend: [`frontend-shadcn.mdc`](frontend-shadcn.mdc) · monorepo: [`frontend-monorepo.mdc`](frontend-monorepo.mdc) · обзор: [`shadcn-ui-production.mdc`](shadcn-ui-production.mdc)
|
||||
@@ -1,56 +0,0 @@
|
||||
---
|
||||
description: "Cursor rules for code development with guidelines integration."
|
||||
globs: **/*
|
||||
alwaysApply: false
|
||||
---
|
||||
1. **Verify Information**: Always verify information before presenting it. Do not make assumptions or speculate without clear evidence.
|
||||
|
||||
2. **File-by-File Changes**: Make changes file by file and give me a chance to spot mistakes.
|
||||
|
||||
3. **No Apologies**: Never use apologies.
|
||||
|
||||
4. **No Understanding Feedback**: Avoid giving feedback about understanding in comments or documentation.
|
||||
|
||||
5. **No Whitespace Suggestions**: Don't suggest whitespace changes.
|
||||
|
||||
6. **No Summaries**: Don't summarize changes made.
|
||||
|
||||
7. **No Inventions**: Don't invent changes other than what's explicitly requested.
|
||||
|
||||
8. **No Unnecessary Confirmations**: Don't ask for confirmation of information already provided in the context.
|
||||
|
||||
9. **Preserve Existing Code**: Don't remove unrelated code or functionalities. Pay attention to preserving existing structures.
|
||||
|
||||
10. **Single Chunk Edits**: Provide all edits in a single chunk instead of multiple-step instructions or explanations for the same file.
|
||||
|
||||
11. **No Implementation Checks**: Don't ask the user to verify implementations that are visible in the provided context.
|
||||
|
||||
12. **No Unnecessary Updates**: Don't suggest updates or changes to files when there are no actual modifications needed.
|
||||
|
||||
13. **Provide Real File Links**: Always provide links to the real files, not the context generated file.
|
||||
|
||||
14. **No Current Implementation**: Don't show or discuss the current implementation unless specifically requested.
|
||||
|
||||
15. **Check Context Generated File Content**: Remember to check the context generated file for the current file contents and implementations.
|
||||
|
||||
16. **Use Explicit Variable Names**: Prefer descriptive, explicit variable names over short, ambiguous ones to enhance code readability.
|
||||
|
||||
17. **Follow Consistent Coding Style**: Adhere to the existing coding style in the project for consistency.
|
||||
|
||||
18. **Prioritize Performance**: When suggesting changes, consider and prioritize code performance where applicable.
|
||||
|
||||
19. **Security-First Approach**: Always consider security implications when modifying or suggesting code changes.
|
||||
|
||||
20. **Test Coverage**: Suggest or include appropriate unit tests for new or modified code.
|
||||
|
||||
21. **Error Handling**: Implement robust error handling and logging where necessary.
|
||||
|
||||
22. **Modular Design**: Encourage modular design principles to improve code maintainability and reusability.
|
||||
|
||||
23. **Version Compatibility**: Ensure suggested changes are compatible with the project's specified language or framework versions.
|
||||
|
||||
24. **Avoid Magic Numbers**: Replace hardcoded values with named constants to improve code clarity and maintainability.
|
||||
|
||||
25. **Consider Edge Cases**: When implementing logic, always consider and handle potential edge cases.
|
||||
|
||||
26. **Use Assertions**: Include assertions wherever possible to validate assumptions and catch potential errors early.
|
||||
@@ -1,49 +0,0 @@
|
||||
---
|
||||
description: Code Quality Guidelines
|
||||
globs: **/*
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
# Code Quality Guidelines
|
||||
|
||||
## Verify Information
|
||||
Always verify information before presenting it. Do not make assumptions or speculate without clear evidence.
|
||||
|
||||
## File-by-File Changes
|
||||
Make changes file by file and give me a chance to spot mistakes.
|
||||
|
||||
## No Apologies
|
||||
Never use apologies.
|
||||
|
||||
## No Understanding Feedback
|
||||
Avoid giving feedback about understanding in comments or documentation.
|
||||
|
||||
## No Whitespace Suggestions
|
||||
Don't suggest whitespace changes.
|
||||
|
||||
## No Summaries
|
||||
Don't summarize changes made.
|
||||
|
||||
## No Inventions
|
||||
Don't invent changes other than what's explicitly requested.
|
||||
|
||||
## No Unnecessary Confirmations
|
||||
Don't ask for confirmation of information already provided in the context.
|
||||
|
||||
## Preserve Existing Code
|
||||
Don't remove unrelated code or functionalities. Pay attention to preserving existing structures.
|
||||
|
||||
## Single Chunk Edits
|
||||
Provide all edits in a single chunk instead of multiple-step instructions or explanations for the same file.
|
||||
|
||||
## No Implementation Checks
|
||||
Don't ask the user to verify implementations that are visible in the provided context.
|
||||
|
||||
## No Unnecessary Updates
|
||||
Don't suggest updates or changes to files when there are no actual modifications needed.
|
||||
|
||||
## Provide Real File Links
|
||||
Always provide links to the real files, not x.md.
|
||||
|
||||
## No Current Implementation
|
||||
Don't show or discuss the current implementation unless specifically requested.
|
||||
@@ -1,48 +0,0 @@
|
||||
---
|
||||
description: Code Quality Guidelines
|
||||
globs: ["**/*"]
|
||||
alwaysApply: false
|
||||
---
|
||||
# Code Quality Guidelines
|
||||
|
||||
## Verify Information
|
||||
Always verify information before presenting it. Do not make assumptions or speculate without clear evidence.
|
||||
|
||||
## File-by-File Changes
|
||||
Make changes file by file and give me a chance to spot mistakes.
|
||||
|
||||
## No Apologies
|
||||
Never use apologies.
|
||||
|
||||
## No Understanding Feedback
|
||||
Avoid giving feedback about understanding in comments or documentation.
|
||||
|
||||
## No Whitespace Suggestions
|
||||
Don't suggest whitespace changes.
|
||||
|
||||
## No Summaries
|
||||
Don't summarize changes made.
|
||||
|
||||
## No Inventions
|
||||
Don't invent changes other than what's explicitly requested.
|
||||
|
||||
## No Unnecessary Confirmations
|
||||
Don't ask for confirmation of information already provided in the context.
|
||||
|
||||
## Preserve Existing Code
|
||||
Don't remove unrelated code or functionalities. Pay attention to preserving existing structures.
|
||||
|
||||
## Single Chunk Edits
|
||||
Provide all edits in a single chunk instead of multiple-step instructions or explanations for the same file.
|
||||
|
||||
## No Implementation Checks
|
||||
Don't ask the user to verify implementations that are visible in the provided context.
|
||||
|
||||
## No Unnecessary Updates
|
||||
Don't suggest updates or changes to files when there are no actual modifications needed.
|
||||
|
||||
## Provide Real File Links
|
||||
Always provide links to the real files, not x.md.
|
||||
|
||||
## No Current Implementation
|
||||
Don't show or discuss the current implementation unless specifically requested.
|
||||
@@ -0,0 +1,36 @@
|
||||
---
|
||||
description: Conventional commits на русском языке
|
||||
globs: "**/*"
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
# Commit messages (русский)
|
||||
|
||||
Формат: `<type>[optional scope]: <описание>`
|
||||
|
||||
## Типы
|
||||
|
||||
- `feat` — только новая UX-фича для пользователя
|
||||
- `fix` — исправление бага
|
||||
- `chore` — конфиг, зависимости, правила, CI
|
||||
- `refactor` — рефакторинг без изменения поведения
|
||||
- `docs` — документация
|
||||
- `test` — тесты
|
||||
- `perf` — производительность
|
||||
|
||||
## Правила
|
||||
|
||||
- Subject в **императиве**, без точки в конце
|
||||
- Subject и body — **на русском**
|
||||
- Body (опционально) — что и зачем, не как
|
||||
- Scope в скобках при необходимости: `feat(domains): добавить фильтр по статусу`
|
||||
|
||||
## Примеры
|
||||
|
||||
```
|
||||
fix(frontend): заменить raw table на shadcn Table на странице доменов
|
||||
|
||||
feat(certificates): добавить предупреждение об истечении срока
|
||||
|
||||
chore(rules): консолидировать правила shadcn/ui для Cursor
|
||||
```
|
||||
@@ -1,24 +0,0 @@
|
||||
---
|
||||
description: "Cursor rules for Cursor AI development with React, TypeScript, and shadcn/ui integration."
|
||||
globs: **/*
|
||||
alwaysApply: false
|
||||
---
|
||||
You are an expert AI programming assistant that primarily focuses on producing clear, readable React and TypeScript code.
|
||||
|
||||
You always use the latest stable version of TypeScript, JavaScript, React, Node.js, Next.js App Router, Shadcn UI, Tailwind CSS and you are familiar with the latest features and best practices.
|
||||
|
||||
You carefully provide accurate, factual, thoughtful answers, and are a genius at reasoning AI to chat, to generate code.
|
||||
|
||||
Style and Structure
|
||||
|
||||
Naming Conventions
|
||||
|
||||
TypeScript Usage
|
||||
|
||||
UI and Styling
|
||||
|
||||
Performance Optimization
|
||||
|
||||
Other Rules need to follow:
|
||||
|
||||
Don't be lazy, write all the code to implement features I ask for.
|
||||
@@ -1,50 +0,0 @@
|
||||
---
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
You are a Senior Front-End Developer and an Expert in ReactJS, NextJS, JavaScript, TypeScript, HTML, CSS and modern UI/UX frameworks (e.g., TailwindCSS, Shadcn, Radix). You are thoughtful, give nuanced answers, and are brilliant at reasoning. You carefully provide accurate, factual, thoughtful answers, and are a genius at reasoning.
|
||||
|
||||
- Follow the user’s requirements carefully & to the letter.
|
||||
- First think step-by-step - describe your plan for what to build in pseudocode, written out in great detail.
|
||||
- Confirm, then write code!
|
||||
- Always write correct, best practice, DRY principle (Dont Repeat Yourself), bug free, fully functional and working code also it should be aligned to listed rules down below at Code Implementation Guidelines .
|
||||
- Focus on easy and readability code, over being performant.
|
||||
- Fully implement all requested functionality.
|
||||
- Leave NO todo’s, placeholders or missing pieces.
|
||||
- Ensure code is complete! Verify thoroughly finalised.
|
||||
- Include all required imports, and ensure proper naming of key components.
|
||||
- Be concise Minimize any other prose.
|
||||
- If you think there might not be a correct answer, you say so.
|
||||
- If you do not know the answer, say so, instead of guessing.
|
||||
|
||||
### Coding Environment
|
||||
The user asks questions about the following coding languages:
|
||||
- ReactJS
|
||||
- NextJS
|
||||
- JavaScript
|
||||
- TypeScript
|
||||
- TailwindCSS
|
||||
- HTML
|
||||
- CSS
|
||||
|
||||
### Code Implementation Guidelines
|
||||
Follow these rules when you write code:
|
||||
- Use early returns whenever possible to make the code more readable.
|
||||
- Always use Tailwind classes for styling HTML elements; avoid using CSS or tags.
|
||||
- Use “class:” instead of the tertiary operator in class tags whenever possible.
|
||||
- Use descriptive variable and function/const names. Also, event functions should be named with a “handle” prefix, like “handleClick” for onClick and “handleKeyDown” for onKeyDown.
|
||||
- Implement accessibility features on elements. For example, a tag should have a tabindex=“0”, aria-label, on:click, and on:keydown, and similar attributes.
|
||||
- Use consts instead of functions, for example, “const toggle = () =>”. Also, define a type if possible.
|
||||
- Don't use semicolons.
|
||||
|
||||
### Generate Commit Guidelines
|
||||
- The commit contains the following structural elements, to communicate intent to the consumers of your library:
|
||||
- fix: a commit of the type `fix` patches a bug in your codebase (this correlates with PATCH in semantic versioning).
|
||||
- feat: a commit of the type `feat` introduces a new feature to the codebase (this correlates with MINOR in semantic versioning).
|
||||
- Others: commit types other than `fix:` and `feat:` are allowed, for example `chore:`, `docs:`, `style:`, `refactor:`, `perf:`, `test:`, and others.
|
||||
- A scope may be provided to a commit’s type, to provide additional contextual information and is contained within parenthesis, e.g., `feat(parser): add ability to parse arrays`.
|
||||
- Commit messages should be written in the following format:
|
||||
- Do not end the subject line with a period.
|
||||
- Use the imperative mood in the subject line.
|
||||
- Use the body to explain what and why you have done something. In most cases, you can leave out details about how a change has been made.
|
||||
- The commit message should be structured as follows: `<type>[optional scope]: <description>`
|
||||
@@ -0,0 +1,102 @@
|
||||
---
|
||||
description: shadcn/ui Monorepo — структура apps/web + packages/ui, CLI workflow, импорты @cfdm/ui
|
||||
globs: apps/web/**/*,packages/ui/**/*
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
# Frontend Monorepo (shadcn/ui)
|
||||
|
||||
**Обязательный стандарт структуры** — [Monorepo docs](https://ui.shadcn.com/docs/monorepo).
|
||||
|
||||
## Layout
|
||||
|
||||
```
|
||||
apps/web/ # Vite SPA (routes, queries, domain components)
|
||||
packages/ui/ # @cfdm/ui — shadcn primitives, utils, hooks, globals.css
|
||||
```
|
||||
|
||||
`backend/` — Rust, **вне** npm workspaces.
|
||||
|
||||
## Два components.json
|
||||
|
||||
| Файл | Назначение |
|
||||
|------|------------|
|
||||
| [`apps/web/components.json`](apps/web/components.json) | App aliases; `ui` → `@cfdm/ui/components` |
|
||||
| [`packages/ui/components.json`](packages/ui/components.json) | UI package aliases |
|
||||
|
||||
**Синхронизировать:** `style`, `iconLibrary`, `baseColor` в обоих файлах.
|
||||
|
||||
## CLI — только из apps/web
|
||||
|
||||
```bash
|
||||
cd apps/web
|
||||
pnpm dlx shadcn@latest docs button
|
||||
pnpm dlx shadcn@latest add button
|
||||
pnpm dlx shadcn@latest add sidebar-07
|
||||
pnpm dlx shadcn@latest add login-03
|
||||
pnpm dlx shadcn@latest apply b2fA --only theme -y
|
||||
```
|
||||
|
||||
Перед обновлением существующих компонентов:
|
||||
|
||||
```bash
|
||||
pnpm dlx shadcn@latest add button --dry-run
|
||||
pnpm dlx shadcn@latest add button --diff
|
||||
pnpm dlx shadcn@latest info --json
|
||||
```
|
||||
|
||||
## Куда CLI кладёт файлы
|
||||
|
||||
| Команда | Куда |
|
||||
|---------|------|
|
||||
| `add button` | `packages/ui/src/components/button.tsx` |
|
||||
| `add login-03` | примитивы → `packages/ui`, block → `apps/web/src/components/` |
|
||||
|
||||
## Импорты
|
||||
|
||||
```tsx
|
||||
import { Button } from '@cfdm/ui/components/button'
|
||||
import { cn } from '@cfdm/ui/lib/utils'
|
||||
import { useIsMobile } from '@cfdm/ui/hooks/use-mobile'
|
||||
import '@cfdm/ui/globals.css' // только в main.tsx
|
||||
```
|
||||
|
||||
| Запрещено | Разрешено |
|
||||
|-----------|-----------|
|
||||
| `@/components/ui/*` | `@cfdm/ui/components/*` |
|
||||
| `apps/web/src/components/ui/` | `packages/ui/src/components/` |
|
||||
| Ручное редактирование `globals.css` | `pnpm dlx shadcn@latest apply b2fA --only theme` |
|
||||
|
||||
Community registry: переписывать импорты на `@cfdm/ui/...`.
|
||||
|
||||
## Разделение ответственности
|
||||
|
||||
- **`packages/ui`** — только output `shadcn add` (примитивы, registry hooks, `cn`)
|
||||
- **`apps/web/src/components`** — blocks, layout, domain (`login-form`, `app-shell`, `PageHeader`)
|
||||
|
||||
## Стили (Tailwind v4 monorepo)
|
||||
|
||||
`packages/ui/src/styles/globals.css` — единственный CSS-файл. **Обязательно** `@source` для обоих workspace:
|
||||
|
||||
```css
|
||||
@source "../"; /* packages/ui/src */
|
||||
@source "../../../apps/web/src"; /* apps/web/src */
|
||||
```
|
||||
|
||||
Без `@source` Tailwind не видит классы из `packages/ui` и `apps/web` — UI ломается (нет sidebar, card, и т.д.).
|
||||
|
||||
```bash
|
||||
pnpm install
|
||||
pnpm --filter web dev
|
||||
pnpm --filter web build
|
||||
```
|
||||
|
||||
## Чеклист
|
||||
|
||||
- [ ] Два `components.json` согласованы
|
||||
- [ ] `shadcn add` из `apps/web`
|
||||
- [ ] UI-импорты через `@cfdm/ui/components/*`
|
||||
- [ ] Нет `apps/web/src/components/ui/`
|
||||
- [ ] `pnpm --filter web build` без ошибок
|
||||
|
||||
См. также: [`frontend-shadcn.mdc`](frontend-shadcn.mdc), [`vite-tanstack-frontend.mdc`](vite-tanstack-frontend.mdc).
|
||||
@@ -0,0 +1,153 @@
|
||||
---
|
||||
description: Frontend — ТОЛЬКО shadcn/ui docs (Components, Blocks, Installation); best practices, CLI-first
|
||||
globs: apps/web/**/*,packages/ui/**/*
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
# Frontend — shadcn/ui (обязательно)
|
||||
|
||||
**Источник истины — только официальная документация.** Не выдумывать UI, не писать кастомный CSS, не обходить CLI.
|
||||
|
||||
Monorepo layout — [`frontend-monorepo.mdc`](frontend-monorepo.mdc).
|
||||
|
||||
| Документ | URL |
|
||||
|----------|-----|
|
||||
| **Components** | https://ui.shadcn.com/docs/components |
|
||||
| **Blocks** | https://ui.shadcn.com/blocks |
|
||||
| **Installation** | https://ui.shadcn.com/docs/installation |
|
||||
| **Monorepo** | https://ui.shadcn.com/docs/monorepo |
|
||||
| **Theming** | https://ui.shadcn.com/docs/theming |
|
||||
| **Dark Mode** | https://ui.shadcn.com/docs/dark-mode |
|
||||
| **Forms (RHF)** | https://ui.shadcn.com/docs/forms/react-hook-form |
|
||||
|
||||
## Шаг 0 — перед любым UI-кодом
|
||||
|
||||
1. Открыть **Components** или **Blocks** — найти готовое решение
|
||||
2. `cd apps/web && pnpm dlx shadcn@latest docs <component>` — API и примеры
|
||||
3. `cd apps/web && pnpm dlx shadcn@latest search "<query>"` — если компонент неочевиден
|
||||
4. Только потом писать код
|
||||
|
||||
**Новая страница** → сначала [Blocks](https://ui.shadcn.com/blocks), потом `pnpm dlx shadcn@latest add <block-id>`.
|
||||
|
||||
## Шаг 1 — CLI (обязательно)
|
||||
|
||||
```bash
|
||||
cd apps/web
|
||||
pnpm dlx shadcn@latest add table select badge card field input button ...
|
||||
pnpm dlx shadcn@latest add sidebar-07 # layout
|
||||
pnpm dlx shadcn@latest add dashboard-01 # dashboard
|
||||
pnpm dlx shadcn@latest add login-03 # auth
|
||||
pnpm dlx shadcn@latest apply b2fA --only theme -y # тема — ТОЛЬКО так
|
||||
```
|
||||
|
||||
- Копипаст с сайта **без** CLI — запрещено
|
||||
- `packages/ui/src/components/*` — только registry; domain-логика → `apps/web/src/components/<name>.tsx`
|
||||
|
||||
## Шаг 2 — композиция (best practices)
|
||||
|
||||
### Приоритет
|
||||
|
||||
1. Установленный `@cfdm/ui/components/*`
|
||||
2. Block из registry (адаптация под TanStack Router)
|
||||
3. Shared проекта: `PageHeader`, `StatusBadge`, `ResourceList`, `DataTableCard`
|
||||
4. Domain-обёртка — последний уровень кастомизации
|
||||
|
||||
### Запрещено
|
||||
|
||||
| ❌ | ✅ из [Components](https://ui.shadcn.com/docs/components) |
|
||||
|----|-----------------------------------------------------------|
|
||||
| `<table>`, `<select>`, `<hr>` | `Table`, `Select`, `Separator` |
|
||||
| `bg-emerald-*`, `text-blue-500`, hex в className | `bg-primary`, `text-muted-foreground`, `Badge variant` |
|
||||
| Ручной `globals.css`, `.css` модули | CLI `apply b2fA --only theme` |
|
||||
| `space-y-*` / `space-x-*` | `flex` + `gap-*` |
|
||||
| `w-10 h-10` | `size-10` |
|
||||
| `className` для цветов Button/Badge | `variant`, `size` |
|
||||
| `useState` для полей формы | `FieldGroup` + RHF + Zod |
|
||||
| Styled `<Link>` | `Button variant="link"` + `render={<Link />}` |
|
||||
| `inline style={{}}` в routes | layout Tailwind |
|
||||
| `animate-pulse` div | `Skeleton` |
|
||||
| кастомный toast | `sonner` → `toast()` |
|
||||
| `@/components/ui/*` | `@cfdm/ui/components/*` |
|
||||
|
||||
### Формы
|
||||
|
||||
По https://ui.shadcn.com/docs/forms/react-hook-form:
|
||||
|
||||
```tsx
|
||||
<FieldGroup>
|
||||
<Field data-invalid={!!errors.name}>
|
||||
<FieldLabel htmlFor="name">Имя</FieldLabel>
|
||||
<Input id="name" aria-invalid={!!errors.name} {...register('name')} />
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
```
|
||||
|
||||
### Card
|
||||
|
||||
`CardHeader` / `CardTitle` / `CardDescription` / `CardContent` / `CardFooter` — полная композиция из docs.
|
||||
|
||||
### Таблицы
|
||||
|
||||
`Table`, `TableHeader`, `TableBody`, `TableRow`, `TableHead`, `TableCell` — из docs.
|
||||
Сложная таблица → [Data Table](https://ui.shadcn.com/docs/components/data-table) + block `dashboard-01`.
|
||||
|
||||
### Графики
|
||||
|
||||
`Chart` + `ChartContainer` + `chartConfig` с `var(--chart-1)` — не raw recharts без обёртки.
|
||||
|
||||
### Иконки в Button
|
||||
|
||||
```tsx
|
||||
<Button>
|
||||
<PlusIcon data-icon="inline-start" />
|
||||
Создать
|
||||
</Button>
|
||||
```
|
||||
|
||||
Без `size-4` на иконке внутри shadcn-компонента.
|
||||
|
||||
## Стек (не shadcn, но обязателен)
|
||||
|
||||
TanStack Router + Query — [`vite-tanstack-frontend.mdc`](vite-tanstack-frontend.mdc).
|
||||
|
||||
- Preset: **base-nova** + **neutral** — [`apps/web/components.json`](apps/web/components.json), [`packages/ui/components.json`](packages/ui/components.json)
|
||||
- `@base-ui/react` → `render` prop (не Radix `asChild`)
|
||||
- **Не Next.js** — нет Server Components, `'use client'`
|
||||
|
||||
## Эталоны проекта
|
||||
|
||||
| Зона | Файл | Block |
|
||||
|------|------|-------|
|
||||
| Shell | `apps/web/src/components/layout/app-shell.tsx` | [sidebar-07](https://ui.shadcn.com/blocks) |
|
||||
| Login | `apps/web/src/routes/login.tsx` | [login-03](https://ui.shadcn.com/blocks) |
|
||||
| Dashboard | `apps/web/src/routes/_auth/index.tsx` | [dashboard-01](https://ui.shadcn.com/blocks) |
|
||||
| CRUD | `routes/_auth/services.tsx`, `domains/index.tsx` | Card + Field + Table |
|
||||
|
||||
## Структура файлов
|
||||
|
||||
```
|
||||
apps/web/src/
|
||||
components/ ← domain + layout + shared (blocks)
|
||||
routes/ ← страницы (композиция @cfdm/ui, без raw HTML)
|
||||
queries/ ← queryOptions (не inline в routes)
|
||||
lib/schemas.ts ← Zod для форм
|
||||
|
||||
packages/ui/src/
|
||||
components/ ← только CLI (не трогать под кейс)
|
||||
hooks/ ← registry hooks (use-mobile)
|
||||
lib/utils.ts ← cn()
|
||||
styles/globals.css ← только output shadcn CLI
|
||||
```
|
||||
|
||||
## Чеклист перед завершением задачи
|
||||
|
||||
- [ ] Решение есть в https://ui.shadcn.com/docs/components или /blocks
|
||||
- [ ] Компоненты добавлены через `pnpm dlx shadcn@latest add` из `apps/web`
|
||||
- [ ] Нет кастомного CSS и raw HTML-примитивов
|
||||
- [ ] Semantic tokens, `variant`/`size` вместо переопределения className
|
||||
- [ ] UI-импорты через `@cfdm/ui/components/*`
|
||||
- [ ] `pnpm --filter web build` без ошибок
|
||||
|
||||
## Язык
|
||||
|
||||
Ответы пользователю — русский. Commits — [`commit-messages-ru.mdc`](commit-messages-ru.mdc).
|
||||
@@ -1,56 +0,0 @@
|
||||
---
|
||||
description: Cursor rules for TypeScript, React, Node.js, clean architecture, testing, and WHY-oriented engineering guidance.
|
||||
globs: **/*
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
# Full-Stack Engineering Standards
|
||||
|
||||
You are a senior full-stack developer specializing in TypeScript, React, and Node.js.
|
||||
Every rule includes a WHY explanation for the reasoning behind it.
|
||||
|
||||
## Coding Standards
|
||||
|
||||
- Use strict TypeScript. Never use `any`. Use `unknown` for dynamic data.
|
||||
> WHY: Type safety prevents runtime errors and improves developer experience.
|
||||
- Max function length: 20 lines. Extract helpers for complex logic.
|
||||
> WHY: Improves testability, readability, and makes code review easier.
|
||||
- Naming: camelCase for variables/functions, PascalCase for classes/interfaces, UPPER_SNAKE for constants.
|
||||
> WHY: Consistent with TypeScript ecosystem standards.
|
||||
- Prefer interfaces over type aliases for objects.
|
||||
> WHY: Interfaces are extendable and produce better error messages.
|
||||
|
||||
## Architecture
|
||||
|
||||
- Clean Architecture with dependency inversion. Domain layer is framework-agnostic.
|
||||
> WHY: Testable business logic that survives framework changes.
|
||||
- Repository pattern for data access. Never call ORM directly from business logic.
|
||||
> WHY: Decouples persistence from domain, enables testing with in-memory implementations.
|
||||
- React Query for server state, Zustand for client state. No Redux.
|
||||
> WHY: Lighter weight, better TypeScript support, less boilerplate.
|
||||
|
||||
## Error Handling
|
||||
|
||||
- Custom AppError hierarchy with HTTP status codes. Throw for exceptional, return Result for expected failures.
|
||||
> WHY: Clear intent — callers know which errors to catch vs handle.
|
||||
- Structured logging with Winston. Never log sensitive data (passwords, tokens, PII).
|
||||
> WHY: Observability without security risk. Structured logs enable alerting.
|
||||
|
||||
## Testing
|
||||
|
||||
- 80% unit coverage, 100% critical paths. Use factory functions for test data.
|
||||
> WHY: Factory functions are maintainable and composable. Fixtures become stale.
|
||||
- Mock only external dependencies (APIs, DB). Never mock internal logic.
|
||||
> WHY: Tests should reflect reality. Over-mocking hides real bugs.
|
||||
|
||||
## Security
|
||||
|
||||
- Validate all input with Zod schemas at API boundaries.
|
||||
> WHY: Runtime validation catches what TypeScript can't — malformed external data.
|
||||
- Rate limit all public endpoints. Use helmet middleware.
|
||||
> WHY: Defense in depth against abuse and common web vulnerabilities.
|
||||
|
||||
## Git
|
||||
|
||||
- Max 400 lines per PR. Conventional commits: feat/fix/refactor/test/docs.
|
||||
> WHY: Small PRs get reviewed faster and have fewer bugs.
|
||||
@@ -1,40 +0,0 @@
|
||||
---
|
||||
description: "Cursor rules for React component creation and development."
|
||||
globs: **/*
|
||||
alwaysApply: false
|
||||
---
|
||||
# Cursor Rules
|
||||
|
||||
## Whenever you need a React component
|
||||
|
||||
1. Carefully consider the component's purpose, functionality, and design
|
||||
|
||||
2. Think slowly, step by step, and outline your reasoning
|
||||
|
||||
3. Check if a similar component already exists in any of the following locations
|
||||
1. packages/ui/src/components
|
||||
2. apps/spa/src/components
|
||||
|
||||
4. If it doesn't exist, generate a detailed prompt for the component, including:
|
||||
- Component name and purpose
|
||||
- Desired props and their types
|
||||
- Any specific styling or behavior requirements
|
||||
- Mention of using Tailwind CSS for styling
|
||||
- Request for TypeScript usage
|
||||
|
||||
5. URL encode the prompt.
|
||||
|
||||
6. Create a clickable link in this format:
|
||||
[ComponentName](https://v0.dev/chat?q={encoded_prompt})
|
||||
|
||||
7. After generating, adapt the component to fit our project structure:
|
||||
- Import
|
||||
- common shadcn/ui components from <ui_package_alias>@repo/ui/components/ui/</ui_package_alias>
|
||||
- app specific components from <app_package_alias>@/components</app_package_alias>
|
||||
- Ensure it follows our existing component patterns
|
||||
- Add any necessary custom logic or state management
|
||||
|
||||
Example prompt template:
|
||||
"Create a React component named {ComponentName} using TypeScript and Tailwind CSS. It should {description of functionality}. Props should include {list of props with types}. The component should {any specific styling or behavior notes}. Please provide the full component code."
|
||||
|
||||
Remember to replace placeholders like <ui_package_path> and <app_package_alias> with the actual values used in your project.
|
||||
@@ -1,273 +0,0 @@
|
||||
---
|
||||
description: "Cursor rules for React SPAs combining TanStack Router v1 and TanStack Query v5 for zero-loading-spinner routing and type-safe server state."
|
||||
globs: **/*
|
||||
alwaysApply: false
|
||||
---
|
||||
You are an expert in React, TanStack Router v1, TanStack Query v5, TypeScript, Vite, and building fully type-safe single-page applications.
|
||||
|
||||
# React + TanStack Router + TanStack Query Guidelines
|
||||
|
||||
## Architecture Overview
|
||||
- TanStack Router handles all routing, URL state, and navigation
|
||||
- TanStack Query manages all server state, caching, and async data
|
||||
- React components are pure UI — they read from Query cache and trigger mutations
|
||||
- Loaders bridge Router and Query: they prefetch into the Query cache before render
|
||||
- This eliminates loading spinners for route-level data; Suspense handles component-level loading
|
||||
|
||||
## Project Setup
|
||||
```
|
||||
src/
|
||||
routes/
|
||||
__root.tsx
|
||||
index.tsx
|
||||
posts/
|
||||
index.tsx
|
||||
$postId.tsx
|
||||
queries/ ← Query definitions (queryOptions factories)
|
||||
posts.ts
|
||||
users.ts
|
||||
api/ ← API client functions (fetchers)
|
||||
posts.ts
|
||||
users.ts
|
||||
lib/
|
||||
queryClient.ts
|
||||
router.ts
|
||||
main.tsx
|
||||
```
|
||||
|
||||
## QueryClient + Router Setup
|
||||
```ts
|
||||
// src/lib/queryClient.ts
|
||||
import { QueryClient } from '@tanstack/react-query'
|
||||
|
||||
export const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
staleTime: 1000 * 60,
|
||||
retry: (count, error: any) => error?.status !== 404 && count < 2,
|
||||
},
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
```tsx
|
||||
// src/lib/router.ts
|
||||
import { createRouter } from '@tanstack/react-router'
|
||||
import { routeTree } from '../routeTree.gen'
|
||||
import { queryClient } from './queryClient'
|
||||
|
||||
export const router = createRouter({
|
||||
routeTree,
|
||||
context: { queryClient },
|
||||
defaultPreload: 'intent',
|
||||
defaultPreloadStaleTime: 0,
|
||||
})
|
||||
|
||||
declare module '@tanstack/react-router' {
|
||||
interface Register {
|
||||
router: typeof router
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```tsx
|
||||
// src/main.tsx
|
||||
import { RouterProvider } from '@tanstack/react-router'
|
||||
import { QueryClientProvider } from '@tanstack/react-query'
|
||||
import { router } from './lib/router'
|
||||
import { queryClient } from './lib/queryClient'
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('root')!).render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<RouterProvider router={router} context={{ queryClient }} />
|
||||
</QueryClientProvider>
|
||||
)
|
||||
```
|
||||
|
||||
## Query Definitions (queryOptions factories)
|
||||
- Co-locate query key, fetcher, and staleTime in one place
|
||||
- Share between Router loaders and component hooks
|
||||
```ts
|
||||
// src/queries/posts.ts
|
||||
import { queryOptions, infiniteQueryOptions } from '@tanstack/react-query'
|
||||
import { fetchPost, fetchPosts } from '../api/posts'
|
||||
|
||||
export const postKeys = {
|
||||
all: ['posts'] as const,
|
||||
lists: () => [...postKeys.all, 'list'] as const,
|
||||
list: (filters?: PostFilters) => [...postKeys.lists(), filters] as const,
|
||||
details: () => [...postKeys.all, 'detail'] as const,
|
||||
detail: (id: string) => [...postKeys.details(), id] as const,
|
||||
}
|
||||
|
||||
export const postDetailQueryOptions = (id: string) =>
|
||||
queryOptions({
|
||||
queryKey: postKeys.detail(id),
|
||||
queryFn: () => fetchPost(id),
|
||||
staleTime: 1000 * 60 * 5,
|
||||
})
|
||||
|
||||
export const postsListQueryOptions = (filters?: PostFilters) =>
|
||||
queryOptions({
|
||||
queryKey: postKeys.list(filters),
|
||||
queryFn: () => fetchPosts(filters),
|
||||
staleTime: 1000 * 60,
|
||||
})
|
||||
```
|
||||
|
||||
## Router Loader + Query Integration
|
||||
- Loaders call `queryClient.ensureQueryData` — populates cache, renders immediately without spinner
|
||||
- Components then call `useQuery` with the same options — reads from cache synchronously
|
||||
```tsx
|
||||
// src/routes/posts/$postId.tsx
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { postDetailQueryOptions } from '../../queries/posts'
|
||||
|
||||
export const Route = createFileRoute('/posts/$postId')({
|
||||
loader: ({ context: { queryClient }, params }) =>
|
||||
queryClient.ensureQueryData(postDetailQueryOptions(params.postId)),
|
||||
|
||||
errorComponent: ({ error }) => <ErrorMessage error={error} />,
|
||||
pendingComponent: PostSkeleton,
|
||||
component: PostDetail,
|
||||
})
|
||||
|
||||
function PostDetail() {
|
||||
const { postId } = Route.useParams()
|
||||
// data is already in cache from loader — no loading state
|
||||
const { data: post } = useQuery(postDetailQueryOptions(postId))
|
||||
|
||||
return <article><h1>{post!.title}</h1></article>
|
||||
}
|
||||
```
|
||||
|
||||
## Search Params + Query Integration
|
||||
- Use TanStack Router search params as the source of truth for filter/pagination state
|
||||
- Pass search params into queryOptions to drive query key and fetcher
|
||||
```tsx
|
||||
// src/routes/posts/index.tsx
|
||||
import { createFileRoute, Link } from '@tanstack/react-router'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { z } from 'zod'
|
||||
import { postsListQueryOptions } from '../../queries/posts'
|
||||
|
||||
const searchSchema = z.object({
|
||||
page: z.number().int().min(1).default(1),
|
||||
category: z.string().optional(),
|
||||
})
|
||||
|
||||
export const Route = createFileRoute('/posts/')({
|
||||
validateSearch: searchSchema,
|
||||
loader: ({ context: { queryClient }, location: { search } }) =>
|
||||
queryClient.ensureQueryData(postsListQueryOptions(search)),
|
||||
component: PostsList,
|
||||
})
|
||||
|
||||
function PostsList() {
|
||||
const search = Route.useSearch()
|
||||
const navigate = Route.useNavigate()
|
||||
const { data: posts } = useQuery(postsListQueryOptions(search))
|
||||
|
||||
return (
|
||||
<div>
|
||||
{posts?.map(post => (
|
||||
<Link key={post.id} to="/posts/$postId" params={{ postId: post.id }}>
|
||||
{post.title}
|
||||
</Link>
|
||||
))}
|
||||
<button onClick={() => navigate({ search: { ...search, page: search.page + 1 } })}>
|
||||
Next Page
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
## Mutations
|
||||
```tsx
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { useNavigate } from '@tanstack/react-router'
|
||||
import { postKeys } from '../../queries/posts'
|
||||
|
||||
function CreatePostForm() {
|
||||
const queryClient = useQueryClient()
|
||||
const navigate = useNavigate()
|
||||
|
||||
const mutation = useMutation({
|
||||
mutationFn: createPost,
|
||||
onSuccess: (newPost) => {
|
||||
// Populate detail cache immediately
|
||||
queryClient.setQueryData(postKeys.detail(newPost.id), newPost)
|
||||
// Invalidate list queries
|
||||
queryClient.invalidateQueries({ queryKey: postKeys.lists() })
|
||||
// Navigate to new post (no loading — cache is warm)
|
||||
navigate({ to: '/posts/$postId', params: { postId: newPost.id } })
|
||||
},
|
||||
})
|
||||
|
||||
return (/* form JSX */)
|
||||
}
|
||||
```
|
||||
|
||||
## Authentication Pattern
|
||||
```tsx
|
||||
// src/routes/__root.tsx
|
||||
import { createRootRouteWithContext } from '@tanstack/react-router'
|
||||
|
||||
export interface RouterContext {
|
||||
queryClient: QueryClient
|
||||
auth: { isAuthenticated: boolean; user: User | null }
|
||||
}
|
||||
|
||||
export const Route = createRootRouteWithContext<RouterContext>()({
|
||||
component: RootLayout,
|
||||
})
|
||||
|
||||
// src/routes/_auth.tsx (pathless layout for protected routes)
|
||||
export const Route = createFileRoute('/_auth')({
|
||||
beforeLoad: ({ context }) => {
|
||||
if (!context.auth.isAuthenticated) {
|
||||
throw redirect({ to: '/login', search: { redirect: location.pathname } })
|
||||
}
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
## Prefetching on Hover
|
||||
```tsx
|
||||
function PostCard({ post }: { post: Post }) {
|
||||
const queryClient = useQueryClient()
|
||||
return (
|
||||
<Link
|
||||
to="/posts/$postId"
|
||||
params={{ postId: post.id }}
|
||||
onMouseEnter={() => queryClient.prefetchQuery(postDetailQueryOptions(post.id))}
|
||||
>
|
||||
{post.title}
|
||||
</Link>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
## DevTools (Development Only)
|
||||
```tsx
|
||||
// In __root.tsx
|
||||
import { TanStackRouterDevtools } from '@tanstack/router-devtools'
|
||||
import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
|
||||
|
||||
// Inside component
|
||||
{import.meta.env.DEV && (
|
||||
<>
|
||||
<TanStackRouterDevtools position="bottom-left" />
|
||||
<ReactQueryDevtools buttonPosition="bottom-right" />
|
||||
</>
|
||||
)}
|
||||
```
|
||||
|
||||
## Key Rules
|
||||
- Always define `queryOptions` outside of components — not inline in `useQuery()`
|
||||
- Never use `useEffect` to fetch data — use loaders or `useQuery`
|
||||
- Always type router context — `declare module '@tanstack/react-router'` registration is required
|
||||
- Search params are the only source of truth for URL-driven filter state
|
||||
- Mutations should `setQueryData` + `invalidateQueries`, not just invalidate, for instant UI feedback
|
||||
@@ -1,116 +0,0 @@
|
||||
---
|
||||
description: "React SPA with TanStack Router v1 + TanStack Query v5 — the definitive pattern for zero-loading-spinner routing, type-safe URLs, and cache-first data"
|
||||
globs: ["src/routes/**/*", "src/queries/**/*", "src/lib/router.ts", "src/lib/queryClient.ts"]
|
||||
alwaysApply: false
|
||||
---
|
||||
You are an expert in React, TanStack Router v1, TanStack Query v5, TypeScript, and Vite.
|
||||
|
||||
## Architecture
|
||||
- TanStack Router: routing, URL state, navigation
|
||||
- TanStack Query: server state, caching, mutations
|
||||
- Loader = bridge: prefetches into Query cache before render → zero loading spinners for route data
|
||||
- Components are pure UI: read from Query cache, trigger mutations
|
||||
|
||||
## Setup
|
||||
```ts
|
||||
// src/lib/queryClient.ts
|
||||
export const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { staleTime: 60_000 } },
|
||||
})
|
||||
|
||||
// src/lib/router.ts
|
||||
export const router = createRouter({
|
||||
routeTree,
|
||||
context: { queryClient },
|
||||
defaultPreload: 'intent',
|
||||
defaultPreloadStaleTime: 0,
|
||||
})
|
||||
|
||||
declare module '@tanstack/react-router' {
|
||||
interface Register { router: typeof router }
|
||||
}
|
||||
|
||||
// src/main.tsx
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<RouterProvider router={router} context={{ queryClient }} />
|
||||
</QueryClientProvider>
|
||||
```
|
||||
|
||||
## Query Definitions
|
||||
```ts
|
||||
// src/queries/posts.ts
|
||||
export const postKeys = {
|
||||
all: ['posts'] as const,
|
||||
detail: (id: string) => [...postKeys.all, 'detail', id] as const,
|
||||
list: (f?: PostFilters) => [...postKeys.all, 'list', f] as const,
|
||||
}
|
||||
|
||||
export const postQueryOptions = (id: string) =>
|
||||
queryOptions({ queryKey: postKeys.detail(id), queryFn: () => fetchPost(id) })
|
||||
|
||||
export const postsQueryOptions = (filters?: PostFilters) =>
|
||||
queryOptions({ queryKey: postKeys.list(filters), queryFn: () => fetchPosts(filters) })
|
||||
```
|
||||
|
||||
## Loader + Component (zero loading state)
|
||||
```tsx
|
||||
export const Route = createFileRoute('/posts/$postId')({
|
||||
loader: ({ context: { queryClient }, params }) =>
|
||||
queryClient.ensureQueryData(postQueryOptions(params.postId)),
|
||||
component: PostDetail,
|
||||
})
|
||||
|
||||
function PostDetail() {
|
||||
const { postId } = Route.useParams()
|
||||
const { data: post } = useQuery(postQueryOptions(postId)) // always in cache from loader
|
||||
return <h1>{post!.title}</h1>
|
||||
}
|
||||
```
|
||||
|
||||
## Search Params → Query Key
|
||||
```tsx
|
||||
const searchSchema = z.object({ page: z.number().default(1), q: z.string().optional() })
|
||||
|
||||
export const Route = createFileRoute('/posts/')({
|
||||
validateSearch: searchSchema,
|
||||
loader: ({ context: { queryClient }, location: { search } }) =>
|
||||
queryClient.ensureQueryData(postsQueryOptions(search)),
|
||||
component: PostsList,
|
||||
})
|
||||
|
||||
function PostsList() {
|
||||
const search = Route.useSearch()
|
||||
const { data } = useQuery(postsQueryOptions(search))
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
## Mutations
|
||||
```tsx
|
||||
const mutation = useMutation({
|
||||
mutationFn: createPost,
|
||||
onSuccess: (newPost) => {
|
||||
queryClient.setQueryData(postKeys.detail(newPost.id), newPost) // warm cache
|
||||
queryClient.invalidateQueries({ queryKey: postKeys.list() })
|
||||
navigate({ to: '/posts/$postId', params: { postId: newPost.id } }) // instant — no spinner
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
## Hover Prefetching
|
||||
```tsx
|
||||
<Link
|
||||
to="/posts/$postId"
|
||||
params={{ postId: post.id }}
|
||||
onMouseEnter={() => queryClient.prefetchQuery(postQueryOptions(post.id))}
|
||||
>
|
||||
{post.title}
|
||||
</Link>
|
||||
```
|
||||
|
||||
## Key Rules
|
||||
- Always define `queryOptions` outside components — never inline inside `useQuery()`
|
||||
- Never use `useEffect` for data fetching — use loaders or `useQuery`
|
||||
- Search params are the single source of truth for filter/pagination state
|
||||
- After mutations: `setQueryData` + `invalidateQueries` for instant UI feedback
|
||||
- `declare module '@tanstack/react-router'` router registration is required for full type safety
|
||||
@@ -1,310 +0,0 @@
|
||||
---
|
||||
description: Definitive best practices for shadcn/ui — organization, TypeScript, performance, and accessible components.
|
||||
globs: **/*
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
# shadcn Best Practices
|
||||
|
||||
Definitive guidelines for `shadcn/ui` development and integration. Application source lives under `src/`; components under `src/components/`.
|
||||
|
||||
## 1. Code Organization and Structure
|
||||
|
||||
Organize components to reflect UI hierarchy and promote discoverability.
|
||||
|
||||
**Rule:** Place domain-specific components under `src/components/<domain>` and reusable UI primitives under `src/components/ui`. One primary component per file; use kebab-case filenames for UI primitives (shadcn CLI default) and PascalCase for exported component names.
|
||||
|
||||
❌ BAD:
|
||||
```
|
||||
// src/components/Button.tsx
|
||||
// src/components/profile-card.tsx
|
||||
// src/components/user-settings/index.tsx (multiple components in one file)
|
||||
```
|
||||
|
||||
✅ GOOD:
|
||||
```
|
||||
// src/components/ui/button.tsx
|
||||
// src/components/forms/date-picker.tsx
|
||||
// src/components/layout/sidebar.tsx
|
||||
|
||||
// src/components/forms/index.ts
|
||||
export * from "./date-picker";
|
||||
export * from "./input";
|
||||
```
|
||||
|
||||
## 2. Component Architecture
|
||||
|
||||
Favor functional components, composition, and explicit prop definitions.
|
||||
|
||||
**Rule:** Use functional components with `React.forwardRef` and `asChild` for seamless integration with Radix primitives.
|
||||
|
||||
❌ BAD:
|
||||
```tsx
|
||||
// No ref forwarding, no asChild
|
||||
const Button = ({ children, onClick }) => (
|
||||
<button onClick={onClick}>{children}</button>
|
||||
);
|
||||
```
|
||||
|
||||
✅ GOOD:
|
||||
```tsx
|
||||
// src/components/ui/button.tsx
|
||||
import * as React from "react";
|
||||
import { Slot } from "@radix-ui/react-slot";
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const buttonVariants = cva(
|
||||
"inline-flex items-center justify-center rounded-md text-sm font-medium",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-primary text-primary-foreground hover:bg-primary/90",
|
||||
destructive: "bg-destructive text-destructive-foreground",
|
||||
},
|
||||
size: {
|
||||
default: "h-10 px-4 py-2",
|
||||
sm: "h-9 rounded-md px-3",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
export interface ButtonProps
|
||||
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
|
||||
VariantProps<typeof buttonVariants> {
|
||||
asChild?: boolean;
|
||||
}
|
||||
|
||||
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
|
||||
({ className, variant, size, asChild = false, ...props }, ref) => {
|
||||
const Comp = asChild ? Slot : "button";
|
||||
return (
|
||||
<Comp
|
||||
className={cn(buttonVariants({ variant, size, className }))}
|
||||
ref={ref}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
);
|
||||
Button.displayName = "Button";
|
||||
|
||||
export { Button, buttonVariants };
|
||||
```
|
||||
|
||||
## 3. TypeScript and API Design
|
||||
|
||||
Enforce strict TypeScript with clear interfaces and robust validation.
|
||||
|
||||
**Rule:** Use interfaces for component props. Validate form data with Zod schemas. Avoid `any` and prefer explicit types.
|
||||
|
||||
❌ BAD:
|
||||
```typescript
|
||||
// Vague props, no validation
|
||||
type UserFormProps = {
|
||||
data: any;
|
||||
onSubmit: (values: any) => void;
|
||||
};
|
||||
```
|
||||
|
||||
✅ GOOD:
|
||||
```typescript
|
||||
// src/components/forms/user-form.tsx
|
||||
import { z } from "zod";
|
||||
|
||||
export interface UserFormProps {
|
||||
initialData?: UserFormData;
|
||||
onSubmit: (values: UserFormData) => void;
|
||||
}
|
||||
|
||||
export const userFormSchema = z.object({
|
||||
id: z.string().optional(),
|
||||
name: z.string().min(2, "Name must be at least 2 characters."),
|
||||
email: z.string().email("Invalid email address."),
|
||||
});
|
||||
|
||||
export type UserFormData = z.infer<typeof userFormSchema>;
|
||||
```
|
||||
|
||||
## 4. Theming and Styling
|
||||
|
||||
Leverage Tailwind CSS and `class-variance-authority` (CVA) for consistent, maintainable styling.
|
||||
|
||||
**Rule:** Define component variants using CVA. Use the `cn` utility for conditional class merging. Centralize Tailwind configuration and design tokens.
|
||||
|
||||
❌ BAD:
|
||||
```tsx
|
||||
// Inconsistent inline styles or direct class manipulation
|
||||
<button className={`p-2 ${isActive ? "bg-blue-500" : "bg-gray-200"}`}>
|
||||
```
|
||||
|
||||
✅ GOOD:
|
||||
```tsx
|
||||
// src/components/ui/badge.tsx
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const badgeVariants = cva(
|
||||
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "border-transparent bg-primary text-primary-foreground",
|
||||
secondary: "border-transparent bg-secondary text-secondary-foreground",
|
||||
outline: "text-foreground",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
export interface BadgeProps
|
||||
extends React.HTMLAttributes<HTMLDivElement>,
|
||||
VariantProps<typeof badgeVariants> {}
|
||||
|
||||
function Badge({ className, variant, ...props }: BadgeProps) {
|
||||
return (
|
||||
<div className={cn(badgeVariants({ variant }), className)} {...props} />
|
||||
);
|
||||
}
|
||||
|
||||
export { Badge, badgeVariants };
|
||||
```
|
||||
|
||||
## 5. Common Patterns and Anti-patterns
|
||||
|
||||
**Rule:** Use React Hook Form with Zod for all forms. Implement early returns and guard clauses for error handling.
|
||||
|
||||
❌ BAD:
|
||||
```tsx
|
||||
// Deeply nested logic, manual form state
|
||||
if (data) {
|
||||
// ... many lines
|
||||
if (isValid) {
|
||||
// ... more lines
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
✅ GOOD:
|
||||
```tsx
|
||||
// Early return for invalid state
|
||||
if (!user) {
|
||||
return <p>User not found.</p>;
|
||||
}
|
||||
|
||||
// React Hook Form + Zod example
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { userFormSchema, type UserFormData, type UserFormProps } from "./user-form";
|
||||
|
||||
function UserProfileForm({ initialData, onSubmit }: UserFormProps) {
|
||||
const form = useForm<UserFormData>({
|
||||
resolver: zodResolver(userFormSchema),
|
||||
defaultValues: initialData,
|
||||
});
|
||||
|
||||
return (
|
||||
<form onSubmit={form.handleSubmit(onSubmit)}>
|
||||
{/* Form fields */}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## 6. Performance Considerations
|
||||
|
||||
Optimize for fast initial loads and smooth interactions.
|
||||
|
||||
**Rule:** Lazy-load heavy UI sections (dialogs, data tables) via `React.lazy` or dynamic imports. Memoize expensive components and callbacks.
|
||||
|
||||
❌ BAD:
|
||||
```tsx
|
||||
// Always loads heavy component
|
||||
import { BigComplexChart } from "./big-complex-chart";
|
||||
function Dashboard() {
|
||||
return <BigComplexChart data={...} />;
|
||||
}
|
||||
```
|
||||
|
||||
✅ GOOD:
|
||||
```tsx
|
||||
import React from "react";
|
||||
const LazyBigComplexChart = React.lazy(() => import("./big-complex-chart"));
|
||||
|
||||
function Dashboard() {
|
||||
const [showChart, setShowChart] = React.useState(false);
|
||||
|
||||
const handleToggleChart = React.useCallback(() => {
|
||||
setShowChart((prev) => !prev);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Button onClick={handleToggleChart}>Toggle Chart</Button>
|
||||
{showChart && (
|
||||
<React.Suspense fallback={<div>Loading chart...</div>}>
|
||||
<LazyBigComplexChart data={...} />
|
||||
</React.Suspense>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## 7. Accessibility
|
||||
|
||||
Build inclusive UIs by leveraging Radix primitives and ARIA attributes.
|
||||
|
||||
**Rule:** Prefer `shadcn/ui` components (Radix-based) for built-in accessibility. Ensure custom components pass ARIA attributes and manage focus correctly.
|
||||
|
||||
❌ BAD:
|
||||
```tsx
|
||||
// Custom button without ARIA attributes or proper semantics
|
||||
<div role="button" onClick={...}>Click me</div>
|
||||
```
|
||||
|
||||
✅ GOOD:
|
||||
```tsx
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
<Button onClick={() => alert("Action!")}>Perform Action</Button>
|
||||
```
|
||||
|
||||
## 8. Common Pitfalls and Gotchas
|
||||
|
||||
**Rule:** Never directly modify `shadcn/ui` component files for one-off styling — extend with `cn` or wrap in higher-level components. Avoid `dangerouslySetInnerHTML` unless content is sanitized.
|
||||
|
||||
❌ BAD:
|
||||
```tsx
|
||||
// Direct modification of a shadcn component (overwritten by CLI updates)
|
||||
// src/components/ui/button.tsx (modified for a single use case)
|
||||
```
|
||||
|
||||
```tsx
|
||||
// Security vulnerability
|
||||
<div dangerouslySetInnerHTML={{ __html: userProvidedContent }} />
|
||||
```
|
||||
|
||||
✅ GOOD:
|
||||
```tsx
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
<Button className="bg-red-500 hover:bg-red-600">Custom Red Button</Button>
|
||||
```
|
||||
|
||||
```tsx
|
||||
import DOMPurify from "dompurify";
|
||||
|
||||
const sanitizedContent = DOMPurify.sanitize(userProvidedContent);
|
||||
return <div className="prose" dangerouslySetInnerHTML={{ __html: sanitizedContent }} />;
|
||||
// Prefer rendering text directly when possible:
|
||||
// return <p>{userProvidedContent}</p>;
|
||||
```
|
||||
@@ -0,0 +1,29 @@
|
||||
---
|
||||
description: shadcn/ui — глобальные UI-принципы проекта; frontend см. frontend-shadcn.mdc
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# shadcn/ui — правила проекта
|
||||
|
||||
UI строится **исключительно** по [shadcn/ui](https://ui.shadcn.com/docs/installation): [Components](https://ui.shadcn.com/docs/components), [Blocks](https://ui.shadcn.com/blocks), [Monorepo](https://ui.shadcn.com/docs/monorepo).
|
||||
|
||||
## Разработка frontend
|
||||
|
||||
**Все правила frontend** — в [`frontend-shadcn.mdc`](frontend-shadcn.mdc) и [`frontend-monorepo.mdc`](frontend-monorepo.mdc) (globs: `apps/web/**`, `packages/ui/**`).
|
||||
|
||||
Кратко: docs → CLI из `apps/web` → Block → композиция → `pnpm --filter web build`. Кастомный CSS и самописные примитивы **запрещены**.
|
||||
|
||||
## Стек
|
||||
|
||||
- Monorepo: `apps/web` + `packages/ui` (`@cfdm/ui`), pnpm workspaces
|
||||
- Vite + TanStack Router/Query + shadcn **base-nova**
|
||||
- Конфиг: [`apps/web/components.json`](apps/web/components.json), [`packages/ui/components.json`](packages/ui/components.json)
|
||||
- Тема: `pnpm dlx shadcn@latest apply b2fA --only theme -y` — единственный способ менять `packages/ui/src/styles/globals.css`
|
||||
|
||||
## Backend → UI
|
||||
|
||||
При правках API с экранами: [`backend-api-ui.mdc`](backend-api-ui.mdc).
|
||||
|
||||
## Язык
|
||||
|
||||
Русский. Commits: [`commit-messages-ru.mdc`](commit-messages-ru.mdc).
|
||||
@@ -1,64 +0,0 @@
|
||||
---
|
||||
description: Cursor rules for Tailwind development with shadcn/ui integration.
|
||||
globs: **/*
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
# Tailwind + shadcn/ui Development
|
||||
|
||||
You are an expert AI programming assistant in VSCode that primarily focuses on producing clear, readable TypeScript Next.js code.
|
||||
|
||||
You are thoughtful, give nuanced answers, and are brilliant at reasoning. You carefully provide accurate, factual, thoughtful answers, and are a genius at reasoning.
|
||||
|
||||
Follow the user's requirements carefully & to the letter.
|
||||
|
||||
First think step-by-step — describe your plan for what to build in pseudocode, written out in great detail.
|
||||
|
||||
Confirm, then write code!
|
||||
|
||||
Always write correct, up-to-date, bug-free, fully functional and working, secure, performant and efficient code.
|
||||
|
||||
Focus on readability over being performant.
|
||||
|
||||
Fully implement all requested functionality.
|
||||
|
||||
Leave NO todo's, placeholders or missing pieces.
|
||||
|
||||
Ensure code is complete! Verify thoroughly finalized.
|
||||
|
||||
Include all required imports, and ensure proper naming of key components.
|
||||
|
||||
Be concise. Minimize any other prose.
|
||||
|
||||
If you think there might not be a correct answer, you say so. If you do not know the answer, say so instead of guessing.
|
||||
|
||||
## Tech Stack
|
||||
|
||||
- Next.js (App Router), React, TypeScript
|
||||
- Tailwind CSS for all styling
|
||||
- shadcn/ui + Radix UI for accessible components
|
||||
- Application source files live in the `src/` folder
|
||||
|
||||
## Tailwind CSS
|
||||
|
||||
- Use Tailwind utility classes for styling; avoid custom CSS unless necessary
|
||||
- Prefer design tokens (`bg-background`, `text-foreground`, `border-border`) over hardcoded colors
|
||||
- Use `cn()` from `@/lib/utils` to merge conditional classes
|
||||
- Compose with responsive and state variants (`sm:`, `md:`, `hover:`, `focus-visible:`)
|
||||
- Keep class lists readable; extract repeated patterns into components
|
||||
|
||||
## shadcn/ui
|
||||
|
||||
- Prefer existing shadcn components from `@/components/ui/` before building from scratch
|
||||
- Add new components with the shadcn CLI; do not copy-paste from docs without project setup
|
||||
- Extend shadcn components via `className` and composition, not by editing primitives unless required
|
||||
- Use Radix behavior and shadcn styling patterns for forms, dialogs, dropdowns, and toasts
|
||||
- Wire forms with `react-hook-form` + `zod` when using shadcn form components
|
||||
|
||||
## Code Guidelines
|
||||
|
||||
- Use early returns for readability
|
||||
- Prefix event handlers with `handle` (e.g. `handleClick`, `handleSubmit`)
|
||||
- Prefix booleans with verbs (`isLoading`, `hasError`, `canSubmit`)
|
||||
- Default to Server Components; use `'use client'` only when needed
|
||||
- Use semantic HTML and accessible labels, focus states, and keyboard support
|
||||
@@ -1,396 +0,0 @@
|
||||
---
|
||||
description: Definitive guidelines for using TanStack Query (formerly React Query) to manage server state efficiently, ensure type safety, and optimize performance in React applications.
|
||||
globs: **/*.{js,jsx,ts,tsx}
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
# TanStack Query (react-query) Best Practices
|
||||
|
||||
This document outlines the definitive best practices for using TanStack Query in our React applications. Adhering to these guidelines ensures consistent, performant, and maintainable data fetching and state management.
|
||||
|
||||
## 1. Query Keys: The Foundation of Caching
|
||||
|
||||
**ALWAYS** use stable, descriptive array keys. These are fundamental for caching, refetching, and invalidation. For dynamic data, embed parameters directly into the array.
|
||||
|
||||
### ✅ GOOD: Stable Array Keys & Key Factories
|
||||
|
||||
```typescript
|
||||
// 1. Simple, static key
|
||||
const USERS_KEY = ['users'];
|
||||
|
||||
// 2. Dynamic key with parameters
|
||||
const userKeys = {
|
||||
all: ['users'] as const,
|
||||
lists: () => [...userKeys.all, 'list'] as const,
|
||||
list: (filters: { status?: string; page?: number }) =>
|
||||
[...userKeys.lists(), { filters }] as const,
|
||||
details: () => [...userKeys.all, 'detail'] as const,
|
||||
detail: (id: string) => [...userKeys.details(), id] as const,
|
||||
};
|
||||
|
||||
// Usage:
|
||||
// useQuery(userKeys.all, fetchAllUsers);
|
||||
// useQuery(userKeys.list({ status: 'active', page: 1 }), fetchUsers);
|
||||
// useQuery(userKeys.detail(userId), fetchUserById);
|
||||
```
|
||||
|
||||
### ❌ BAD: Unstable or Generic Keys
|
||||
|
||||
```typescript
|
||||
// String keys are less flexible for dynamic data and filtering
|
||||
useQuery('users', fetchUsers);
|
||||
|
||||
// Anonymous object keys are unstable and break caching
|
||||
useQuery(['users', { id: userId }], fetchUserById); // Object literal creates new reference each render
|
||||
```
|
||||
|
||||
## 2. Custom Hooks: Encapsulate Logic
|
||||
|
||||
**ALWAYS** wrap `useQuery` and `useMutation` calls in custom hooks. This centralizes data fetching logic, improves reusability, enhances type safety, and keeps components clean.
|
||||
|
||||
### ✅ GOOD: Dedicated Custom Hooks
|
||||
|
||||
```typescript
|
||||
// hooks/useUsers.ts
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { fetchUsers, User } from '../api'; // Assume api.ts defines fetchUsers
|
||||
|
||||
const userKeys = {
|
||||
all: ['users'] as const,
|
||||
list: (filters: { status?: string }) => [...userKeys.all, { filters }] as const,
|
||||
};
|
||||
|
||||
export function useUsers(filters?: { status?: string }) {
|
||||
return useQuery<User[], Error>({
|
||||
queryKey: userKeys.list(filters || {}),
|
||||
queryFn: () => fetchUsers(filters),
|
||||
});
|
||||
}
|
||||
|
||||
// components/UserList.tsx
|
||||
import { useUsers } from '../hooks/useUsers';
|
||||
|
||||
function UserList({ statusFilter }: { statusFilter?: string }) {
|
||||
const { data: users, isLoading, error } = useUsers({ status: statusFilter });
|
||||
|
||||
if (isLoading) return <div>Loading users...</div>;
|
||||
if (error) return <div>Error: {error.message}</div>;
|
||||
|
||||
return (
|
||||
<ul>
|
||||
{users?.map((user) => (
|
||||
<li key={user.id}>{user.name}</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### ❌ BAD: Direct `useQuery` in Components
|
||||
|
||||
```typescript
|
||||
// components/UserList.tsx
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { fetchUsers } from '../api';
|
||||
|
||||
function UserList({ statusFilter }: { statusFilter?: string }) {
|
||||
// Logic is duplicated if another component needs users
|
||||
// Query key is less organized
|
||||
const { data: users, isLoading, error } = useQuery({
|
||||
queryKey: ['users', { status: statusFilter }],
|
||||
queryFn: () => fetchUsers({ status: statusFilter }),
|
||||
});
|
||||
|
||||
// ... rest of component
|
||||
}
|
||||
```
|
||||
|
||||
## 3. Query Functions: Separate and Stable
|
||||
|
||||
**NEVER** pass anonymous functions directly to `queryFn`. **ALWAYS** declare `queryFn` separately to ensure stability, prevent unnecessary re-renders, and improve testability.
|
||||
|
||||
### ✅ GOOD: Separated Query Functions
|
||||
|
||||
```typescript
|
||||
// api.ts
|
||||
export async function fetchUserById(id: string): Promise<User> {
|
||||
const response = await fetch(`/api/users/${id}`);
|
||||
if (!response.ok) throw new Error('Failed to fetch user');
|
||||
return response.json();
|
||||
}
|
||||
|
||||
// hooks/useUser.ts
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { fetchUserById } from '../api';
|
||||
|
||||
const userKeys = {
|
||||
detail: (id: string) => ['users', id] as const,
|
||||
};
|
||||
|
||||
export function useUser(userId: string) {
|
||||
return useQuery({
|
||||
queryKey: userKeys.detail(userId),
|
||||
queryFn: () => fetchUserById(userId), // Stable reference to fetchUserById
|
||||
enabled: !!userId, // Only run if userId exists
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### ❌ BAD: Anonymous Query Functions
|
||||
|
||||
```typescript
|
||||
// hooks/useUser.ts
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
|
||||
export function useUser(userId: string) {
|
||||
return useQuery({
|
||||
queryKey: ['users', userId],
|
||||
// This anonymous function is recreated on every render, potentially causing issues
|
||||
queryFn: async () => {
|
||||
const response = await fetch(`/api/users/${userId}`);
|
||||
if (!response.ok) throw new Error('Failed to fetch user');
|
||||
return response.json();
|
||||
},
|
||||
enabled: !!userId,
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
## 4. Conditional Fetching: Use `enabled`
|
||||
|
||||
**ALWAYS** use the `enabled` option for conditional fetching. This is the explicit and recommended way to control when a query runs.
|
||||
|
||||
### ✅ GOOD: Using `enabled`
|
||||
|
||||
```typescript
|
||||
// hooks/useUserProfile.ts
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { fetchUserProfile } from '../api';
|
||||
|
||||
export function useUserProfile(userId?: string) {
|
||||
return useQuery({
|
||||
queryKey: ['userProfile', userId],
|
||||
queryFn: () => fetchUserProfile(userId!),
|
||||
enabled: !!userId, // Query only runs if userId is truthy
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### ❌ BAD: Conditional Hook Calls
|
||||
|
||||
```typescript
|
||||
// components/UserProfile.tsx
|
||||
import { useUserProfile } from '../hooks/useUserProfile';
|
||||
|
||||
function UserProfile({ userId }: { userId?: string }) {
|
||||
// React Hook Rules: Hooks must be called unconditionally
|
||||
// This breaks the rules and will cause bugs
|
||||
if (!userId) {
|
||||
return null;
|
||||
}
|
||||
const { data: user, isLoading } = useUserProfile(userId);
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
## 5. Data Transformation: Use `select`
|
||||
|
||||
**ALWAYS** use the `select` option within `useQuery` for transforming or filtering data. This ensures the transformation happens once at the query level, optimizing performance and preventing redundant calculations in components.
|
||||
|
||||
### ✅ GOOD: `select` for Transformations
|
||||
|
||||
```typescript
|
||||
// hooks/useActiveUsers.ts
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { fetchUsers, User } from '../api';
|
||||
|
||||
export function useActiveUsers() {
|
||||
return useQuery<User[], Error, string[]>({ // Specify transformed data type
|
||||
queryKey: ['users', 'all'],
|
||||
queryFn: fetchUsers,
|
||||
select: (data) => data.filter(user => user.status === 'active').map(user => user.name),
|
||||
});
|
||||
}
|
||||
|
||||
// components/ActiveUserNames.tsx
|
||||
import { useActiveUsers } from '../hooks/useActiveUsers';
|
||||
|
||||
function ActiveUserNames() {
|
||||
const { data: activeUserNames, isLoading } = useActiveUsers();
|
||||
|
||||
if (isLoading) return <div>Loading active users...</div>;
|
||||
return (
|
||||
<ul>
|
||||
{activeUserNames?.map((name) => (
|
||||
<li key={name}>{name}</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### ❌ BAD: Transforming Data in Every Component
|
||||
|
||||
```typescript
|
||||
// components/ActiveUserNames.tsx
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { fetchUsers } from '../api';
|
||||
|
||||
function ActiveUserNames() {
|
||||
const { data: users, isLoading } = useQuery({
|
||||
queryKey: ['users', 'all'],
|
||||
queryFn: fetchUsers,
|
||||
});
|
||||
|
||||
// Transformation logic repeated or inefficiently placed
|
||||
const activeUserNames = users?.filter(user => user.status === 'active').map(user => user.name);
|
||||
|
||||
if (isLoading) return <div>Loading active users...</div>;
|
||||
return (
|
||||
<ul>
|
||||
{activeUserNames?.map((name) => (
|
||||
<li key={name}>{name}</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## 6. Mutations and Cache Invalidation
|
||||
|
||||
**ALWAYS** use `useMutation` for CUD (Create, Update, Delete) operations. After a successful mutation, **ALWAYS** invalidate relevant queries to ensure the UI reflects the latest server state. For immediate feedback, consider optimistic updates with `setQueryData`.
|
||||
|
||||
### ✅ GOOD: Invalidation after Mutation
|
||||
|
||||
```typescript
|
||||
// hooks/useCreateTodo.ts
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { createTodo, Todo } from '../api';
|
||||
|
||||
export function useCreateTodo() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation<Todo, Error, { title: string }>({
|
||||
mutationFn: createTodo,
|
||||
onSuccess: () => {
|
||||
// Invalidate all 'todos' queries to refetch fresh data
|
||||
queryClient.invalidateQueries({ queryKey: ['todos'] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// components/TodoForm.tsx
|
||||
import { useCreateTodo } from '../hooks/useCreateTodo';
|
||||
|
||||
function TodoForm() {
|
||||
const { mutate, isLoading } = useCreateTodo();
|
||||
|
||||
const handleSubmit = (event: React.FormEvent) => {
|
||||
event.preventDefault();
|
||||
const formData = new FormData(event.currentTarget as HTMLFormElement);
|
||||
const title = formData.get('title') as string;
|
||||
mutate({ title });
|
||||
};
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit}>
|
||||
<input name="title" placeholder="New todo" />
|
||||
<button type="submit" disabled={isLoading}>
|
||||
{isLoading ? 'Adding...' : 'Add Todo'}
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### ✅ GOOD: Optimistic Updates
|
||||
|
||||
```typescript
|
||||
// hooks/useUpdateTodo.ts
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { updateTodo, Todo } from '../api';
|
||||
|
||||
export function useUpdateTodo() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation<Todo, Error, Partial<Todo> & { id: string }>({
|
||||
mutationFn: updateTodo,
|
||||
// Optimistically update the cache
|
||||
onMutate: async (newTodo) => {
|
||||
await queryClient.cancelQueries({ queryKey: ['todos'] });
|
||||
const previousTodos = queryClient.getQueryData<Todo[]>(['todos']);
|
||||
queryClient.setQueryData<Todo[]>(['todos'], (old) =>
|
||||
old ? old.map((todo) => (todo.id === newTodo.id ? { ...todo, ...newTodo } : todo)) : []
|
||||
);
|
||||
return { previousTodos }; // Context for onError
|
||||
},
|
||||
onError: (err, newTodo, context) => {
|
||||
// Rollback on error
|
||||
queryClient.setQueryData(['todos'], context?.previousTodos);
|
||||
},
|
||||
onSettled: () => {
|
||||
// Always refetch after error or success to ensure data is in sync
|
||||
queryClient.invalidateQueries({ queryKey: ['todos'] });
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
## 7. Performance: Prefetching & Defaults
|
||||
|
||||
**LEVERAGE** TanStack Query's defaults (e.g., `staleTime: 0`, automatic retries, refetch on window focus) and **STRATEGICALLY** use prefetching for critical user flows.
|
||||
|
||||
### ✅ GOOD: Prefetching for Router Integration
|
||||
|
||||
```typescript
|
||||
// utils/routeLoaders.ts (Example with a router loader)
|
||||
import { QueryClient } from '@tanstack/react-query';
|
||||
import { fetchProjectById } from '../api';
|
||||
|
||||
export const projectLoader = (queryClient: QueryClient) => async ({ params }: { params: { projectId: string } }) => {
|
||||
const queryKey = ['projects', params.projectId];
|
||||
// Prefetch the project data during navigation
|
||||
await queryClient.prefetchQuery({
|
||||
queryKey,
|
||||
queryFn: () => fetchProjectById(params.projectId),
|
||||
});
|
||||
return null; // Or return initial data if needed
|
||||
};
|
||||
|
||||
// components/ProjectLink.tsx
|
||||
import { Link } from 'react-router-dom'; // Assuming react-router-dom
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { fetchProjectById } from '../api';
|
||||
|
||||
function ProjectLink({ projectId, projectName }: { projectId: string; projectName: string }) {
|
||||
const queryClient = useQueryClient();
|
||||
const handleMouseEnter = () => {
|
||||
// Prefetch on hover for instant page loads
|
||||
queryClient.prefetchQuery({
|
||||
queryKey: ['projects', projectId],
|
||||
queryFn: () => fetchProjectById(projectId),
|
||||
staleTime: 5 * 60 * 1000, // Keep data fresh for 5 minutes
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<Link to={`/projects/${projectId}`} onMouseEnter={handleMouseEnter}>
|
||||
{projectName}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## 8. ESLint Plugin: Enforce Standards
|
||||
|
||||
**ALWAYS** install and configure the `@tanstack/query-eslint-plugin`. It enforces many of these best practices automatically, catching common mistakes early.
|
||||
|
||||
```json
|
||||
// .eslintrc.json
|
||||
{
|
||||
"plugins": ["@tanstack/query"],
|
||||
"rules": {
|
||||
"@tanstack/query/exhaustive-deps": "error",
|
||||
"@tanstack/query/prefer-query-object": "error",
|
||||
"@tanstack/query/stable-query-client": "error"
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -1,107 +0,0 @@
|
||||
---
|
||||
description: "TanStack Query v5 (React Query) patterns including queryOptions helper, query key factories, mutations, optimistic updates, infinite queries, Suspense mode, and prefetching"
|
||||
globs: ["src/**/*.tsx", "src/**/*.ts", "src/queries/**/*"]
|
||||
alwaysApply: false
|
||||
---
|
||||
You are an expert in TanStack Query v5 (React Query), TypeScript, and async state management.
|
||||
|
||||
## Core Principles
|
||||
- TanStack Query manages server state — NOT a general client state manager
|
||||
- Every query needs a stable, serializable query key that uniquely describes the data
|
||||
- Mutations handle writes; queries handle reads — never blur this boundary
|
||||
- Use `queryOptions()` helper (v5) for reusable, co-located query definitions
|
||||
- v5 breaking change: `useQuery` only accepts options object form — no positional args
|
||||
|
||||
## QueryClient Setup
|
||||
```tsx
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
staleTime: 1000 * 60,
|
||||
retry: (count, error: any) => error?.status !== 404 && count < 2,
|
||||
},
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
## Query Key Factory Pattern
|
||||
```ts
|
||||
export const postKeys = {
|
||||
all: ['posts'] as const,
|
||||
lists: () => [...postKeys.all, 'list'] as const,
|
||||
list: (filters?: PostFilters) => [...postKeys.lists(), filters] as const,
|
||||
details: () => [...postKeys.all, 'detail'] as const,
|
||||
detail: (id: string) => [...postKeys.details(), id] as const,
|
||||
}
|
||||
```
|
||||
|
||||
## queryOptions Helper (v5)
|
||||
```ts
|
||||
export const postQueryOptions = (id: string) =>
|
||||
queryOptions({
|
||||
queryKey: postKeys.detail(id),
|
||||
queryFn: () => fetchPost(id),
|
||||
staleTime: 1000 * 60 * 5,
|
||||
})
|
||||
|
||||
// In component
|
||||
const { data } = useQuery(postQueryOptions(postId))
|
||||
|
||||
// In router loader
|
||||
loader: ({ params, context: { queryClient } }) =>
|
||||
queryClient.ensureQueryData(postQueryOptions(params.postId))
|
||||
```
|
||||
|
||||
## Mutations
|
||||
```tsx
|
||||
const { mutate, isPending } = useMutation({
|
||||
mutationFn: (input: CreatePostInput) => createPost(input),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: postKeys.lists() })
|
||||
},
|
||||
onError: (error) => toast.error(error.message),
|
||||
})
|
||||
```
|
||||
|
||||
## Optimistic Updates
|
||||
```tsx
|
||||
const mutation = useMutation({
|
||||
mutationFn: updatePost,
|
||||
onMutate: async (updated) => {
|
||||
await queryClient.cancelQueries({ queryKey: postKeys.detail(updated.id) })
|
||||
const previous = queryClient.getQueryData(postKeys.detail(updated.id))
|
||||
queryClient.setQueryData(postKeys.detail(updated.id), updated)
|
||||
return { previous }
|
||||
},
|
||||
onError: (_, updated, ctx) => {
|
||||
queryClient.setQueryData(postKeys.detail(updated.id), ctx?.previous)
|
||||
},
|
||||
onSettled: (_, __, updated) => {
|
||||
queryClient.invalidateQueries({ queryKey: postKeys.detail(updated.id) })
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
## Infinite Queries
|
||||
```tsx
|
||||
const { data, fetchNextPage, hasNextPage } = useInfiniteQuery({
|
||||
queryKey: postKeys.lists(),
|
||||
queryFn: ({ pageParam }) => fetchPosts({ cursor: pageParam }),
|
||||
initialPageParam: undefined as string | undefined,
|
||||
getNextPageParam: (lastPage) => lastPage.nextCursor,
|
||||
})
|
||||
const allPosts = data?.pages.flatMap((p) => p.items) ?? []
|
||||
```
|
||||
|
||||
## Suspense Mode (v5)
|
||||
```tsx
|
||||
// useSuspenseQuery — no isLoading needed, Suspense handles it
|
||||
const { data } = useSuspenseQuery(postQueryOptions(postId))
|
||||
// Wrap with <Suspense fallback={<Skeleton />}> + <ErrorBoundary>
|
||||
```
|
||||
|
||||
## Key Rules
|
||||
- Always define `queryOptions` outside components — never inline in `useQuery()`
|
||||
- Never use `useEffect` to fetch data — use loaders or `useQuery`
|
||||
- Use `placeholderData: keepPreviousData` for pagination to avoid layout shifts
|
||||
- Instantiate `QueryClient` once at app root — never inside a component
|
||||
@@ -1,98 +0,0 @@
|
||||
---
|
||||
description: "Type-safe routing with TanStack Router v1 for React apps, including file-based routing, loaders, search params validation, auth guards, and TanStack Query integration"
|
||||
globs: ["src/routes/**/*", "src/routeTree.gen.ts", "app.config.ts"]
|
||||
alwaysApply: false
|
||||
---
|
||||
You are an expert in TanStack Router v1, React, TypeScript, and type-safe client-side routing.
|
||||
|
||||
## Core Principles
|
||||
- TanStack Router is 100% type-safe — leverage TypeScript generics for params, search params, and loader data
|
||||
- Prefer file-based routing with `@tanstack/router-vite-plugin` for scalability
|
||||
- Always define routes with `createFileRoute` or `createRootRoute`
|
||||
- Route data loading belongs in `loader` functions, not in component `useEffect`
|
||||
- Search params are first-class — always define their schema with Zod for type safety
|
||||
|
||||
## File-Based Route Conventions
|
||||
```
|
||||
src/routes/
|
||||
__root.tsx ← Root layout
|
||||
index.tsx ← / route
|
||||
posts/
|
||||
index.tsx ← /posts
|
||||
$postId.tsx ← /posts/:postId (dynamic)
|
||||
_layout.tsx ← Layout route (no path segment)
|
||||
_auth/ ← Pathless auth layout group
|
||||
dashboard.tsx
|
||||
```
|
||||
|
||||
## Route Definition
|
||||
```tsx
|
||||
export const Route = createFileRoute('/posts/$postId')({
|
||||
loader: async ({ params }) => fetchPost(params.postId),
|
||||
component: PostComponent,
|
||||
errorComponent: ({ error }) => <ErrorBanner message={error.message} />,
|
||||
pendingComponent: () => <PostSkeleton />,
|
||||
})
|
||||
|
||||
function PostComponent() {
|
||||
const post = Route.useLoaderData() // type-safe
|
||||
const { postId } = Route.useParams() // type-safe
|
||||
return <div>{post.title}</div>
|
||||
}
|
||||
```
|
||||
|
||||
## Type-Safe Search Params
|
||||
- Always define search params with Zod and `validateSearch`
|
||||
- Access with `Route.useSearch()` — never read `window.location.search` directly
|
||||
```tsx
|
||||
const searchSchema = z.object({
|
||||
page: z.number().int().min(1).default(1),
|
||||
q: z.string().optional(),
|
||||
})
|
||||
|
||||
export const Route = createFileRoute('/search')({
|
||||
validateSearch: searchSchema,
|
||||
component: SearchPage,
|
||||
})
|
||||
```
|
||||
|
||||
## Navigation
|
||||
- Use `<Link>` for internal navigation — never `<a href>`
|
||||
- Always pass typed `params` and `search` — the compiler will catch mistakes
|
||||
```tsx
|
||||
<Link to="/posts/$postId" params={{ postId: '123' }}>View Post</Link>
|
||||
```
|
||||
|
||||
## Loaders + TanStack Query Integration
|
||||
```tsx
|
||||
export const Route = createFileRoute('/posts')({
|
||||
loader: ({ context: { queryClient } }) =>
|
||||
queryClient.ensureQueryData(postsQueryOptions()),
|
||||
component: PostsPage,
|
||||
})
|
||||
```
|
||||
|
||||
## Router Context for Dependency Injection
|
||||
```tsx
|
||||
// __root.tsx
|
||||
interface RouterContext { queryClient: QueryClient; auth: AuthState }
|
||||
export const Route = createRootRouteWithContext<RouterContext>()({ component: RootLayout })
|
||||
|
||||
// main.tsx
|
||||
const router = createRouter({ routeTree, context: { queryClient, auth } })
|
||||
```
|
||||
|
||||
## Auth Guards
|
||||
```tsx
|
||||
export const Route = createFileRoute('/_auth/dashboard')({
|
||||
beforeLoad: ({ context }) => {
|
||||
if (!context.auth.isAuthenticated) throw redirect({ to: '/login' })
|
||||
},
|
||||
component: Dashboard,
|
||||
})
|
||||
```
|
||||
|
||||
## Performance
|
||||
- Set `defaultPreload: 'intent'` on router for automatic prefetching on hover/focus
|
||||
- Use `React.lazy` for route component code splitting
|
||||
- Install `@tanstack/router-devtools` and render `<TanStackRouterDevtools />` in development
|
||||
@@ -1,123 +0,0 @@
|
||||
---
|
||||
description: "TanStack Start full-stack React framework using server functions, API routes, SSR, streaming with defer(), and multi-platform deployment via Vinxi/Nitro"
|
||||
globs: ["src/routes/**/*", "src/server/**/*", "app.config.ts"]
|
||||
alwaysApply: false
|
||||
---
|
||||
You are an expert in TanStack Start, TanStack Router, React, TypeScript, and full-stack type-safe web applications.
|
||||
|
||||
## Core Principles
|
||||
- TanStack Start = TanStack Router + Vinxi (Vite + Nitro) for full-stack React
|
||||
- `createServerFn` is the primary way to run server-side logic with end-to-end type safety
|
||||
- All TanStack Router conventions apply — file-based routing, loaders, search params, etc.
|
||||
- Server functions replace REST endpoints for most use cases
|
||||
- Streaming + Suspense are first-class — use `defer()` for non-critical data
|
||||
|
||||
## app.config.ts
|
||||
```ts
|
||||
import { defineConfig } from '@tanstack/start/config'
|
||||
import tsConfigPaths from 'vite-tsconfig-paths'
|
||||
|
||||
export default defineConfig({
|
||||
vite: { plugins: [tsConfigPaths()] },
|
||||
server: {
|
||||
preset: 'node-server', // or: 'vercel', 'netlify', 'bun', 'cloudflare-pages'
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
## Root Route HTML Shell
|
||||
```tsx
|
||||
// src/routes/__root.tsx
|
||||
export const Route = createRootRoute({
|
||||
component: () => (
|
||||
<html lang="en">
|
||||
<head />
|
||||
<body>
|
||||
<Outlet />
|
||||
<ScrollRestoration />
|
||||
<Scripts />
|
||||
</body>
|
||||
</html>
|
||||
),
|
||||
})
|
||||
```
|
||||
|
||||
## Server Functions
|
||||
```ts
|
||||
// src/server/functions/posts.ts
|
||||
export const getPost = createServerFn()
|
||||
.validator(z.object({ id: z.string() }))
|
||||
.handler(async ({ data }) => {
|
||||
const post = await db.post.findUnique({ where: { id: data.id } })
|
||||
if (!post) throw new Error('Post not found')
|
||||
return post
|
||||
})
|
||||
|
||||
export const createPost = createServerFn()
|
||||
.validator(z.object({ title: z.string().min(1), body: z.string() }))
|
||||
.handler(async ({ data }) => db.post.create({ data }))
|
||||
```
|
||||
|
||||
## Using Server Functions in Routes
|
||||
```tsx
|
||||
export const Route = createFileRoute('/posts/$postId')({
|
||||
loader: ({ params }) => getPost({ data: { id: params.postId } }),
|
||||
component: PostDetail,
|
||||
})
|
||||
```
|
||||
|
||||
## Mutations with Server Functions
|
||||
```tsx
|
||||
const mutation = useMutation({
|
||||
mutationFn: (input: { title: string; body: string }) => createPost({ data: input }),
|
||||
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['posts'] }),
|
||||
})
|
||||
```
|
||||
|
||||
## API Routes (for webhooks / raw HTTP)
|
||||
```ts
|
||||
// src/routes/api/webhook.ts
|
||||
export const Route = createAPIFileRoute('/api/webhook')({
|
||||
POST: async ({ request }) => {
|
||||
const body = await request.json()
|
||||
return Response.json({ received: true })
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
## Streaming with defer()
|
||||
```tsx
|
||||
export const Route = createFileRoute('/posts/$postId')({
|
||||
loader: async ({ params }) => {
|
||||
const post = await getPost({ data: { id: params.postId } }) // awaited = critical
|
||||
const comments = getComments({ data: { postId: params.postId } }) // not awaited
|
||||
return { post, comments: defer(comments) }
|
||||
},
|
||||
component: PostDetail,
|
||||
})
|
||||
|
||||
function PostDetail() {
|
||||
const { post, comments } = Route.useLoaderData()
|
||||
return (
|
||||
<div>
|
||||
<h1>{post.title}</h1>
|
||||
<Suspense fallback={<CommentsSkeleton />}>
|
||||
<Await promise={comments}>{(c) => <CommentsList comments={c} />}</Await>
|
||||
</Suspense>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
## Environment Variables
|
||||
- Access server-only vars via `process.env` inside server functions only
|
||||
- Use `import.meta.env.VITE_*` for client-exposed variables
|
||||
- Never access `process.env` in client components
|
||||
|
||||
## Deployment Targets
|
||||
Configure `server.preset` in `app.config.ts`:
|
||||
- `node-server` — default Node.js
|
||||
- `vercel` — Vercel serverless/edge
|
||||
- `netlify` — Netlify Functions
|
||||
- `bun` — Bun runtime
|
||||
- `cloudflare-pages` — Cloudflare Pages + Workers
|
||||
@@ -1,68 +0,0 @@
|
||||
---
|
||||
description: "Cursor rules for TypeScript development with Vite and Tailwind integration."
|
||||
globs: **/*
|
||||
alwaysApply: false
|
||||
---
|
||||
You are an expert in TypeScript, Node.js, Vite, Vue.js, Vue Router, Pinia, VueUse, DaisyUI, and Tailwind, with a deep understanding of best practices and performance optimization techniques in these technologies.
|
||||
|
||||
Code Style and Structure
|
||||
|
||||
- Write concise, maintainable, and technically accurate TypeScript code with relevant examples.
|
||||
- Use functional and declarative programming patterns; avoid classes.
|
||||
- Favor iteration and modularization to adhere to DRY principles and avoid code duplication.
|
||||
- Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError).
|
||||
- Organize files systematically: each file should contain only related content, such as exported components, subcomponents, helpers, static content, and types.
|
||||
|
||||
Naming Conventions
|
||||
|
||||
- Use lowercase with dashes for directories (e.g., components/auth-wizard).
|
||||
- Favor named exports for functions.
|
||||
|
||||
TypeScript Usage
|
||||
|
||||
- Use TypeScript for all code; prefer interfaces over types for their extendability and ability to merge.
|
||||
- Avoid enums; use maps instead for better type safety and flexibility.
|
||||
- Use functional components with TypeScript interfaces.
|
||||
|
||||
Syntax and Formatting
|
||||
|
||||
- Use the "function" keyword for pure functions to benefit from hoisting and clarity.
|
||||
- Always use the Vue Composition API script setup style.
|
||||
|
||||
UI and Styling
|
||||
|
||||
- Use DaisyUI, and Tailwind for components and styling.
|
||||
- Implement responsive design with Tailwind CSS; use a mobile-first approach.
|
||||
|
||||
Performance Optimization
|
||||
|
||||
- Leverage VueUse functions where applicable to enhance reactivity and performance.
|
||||
- Wrap asynchronous components in Suspense with a fallback UI.
|
||||
- Use dynamic loading for non-critical components.
|
||||
- Optimize images: use WebP format, include size data, implement lazy loading.
|
||||
- Implement an optimized chunking strategy during the Vite build process, such as code splitting, to generate smaller bundle sizes.
|
||||
|
||||
Key Conventions
|
||||
|
||||
- Optimize Web Vitals (LCP, CLS, FID) using tools like Lighthouse or WebPageTest.
|
||||
- Use the VueUse library for performance-enhancing functions.
|
||||
- Implement lazy loading for non-critical components.
|
||||
- Optimize images: use WebP format, include size data, implement lazy loading.
|
||||
- Implement an optimized chunking strategy during the Vite build process, such as code splitting, to generate smaller bundle sizes.
|
||||
|
||||
Code Review
|
||||
|
||||
- Review code for performance, readability, and adherence to best practices.
|
||||
- Ensure all components and functions are optimized for performance and maintainability.
|
||||
- Check for unnecessary re-renders and optimize them using VueUse functions.
|
||||
- Use the VueUse library for performance-enhancing functions.
|
||||
- Implement lazy loading for non-critical components.
|
||||
- Optimize images: use WebP format, include size data, implement lazy loading.
|
||||
- Implement an optimized chunking strategy during the Vite build process, such as code splitting, to generate smaller bundle sizes.
|
||||
|
||||
Best Practices
|
||||
|
||||
- Use the VueUse library for performance-enhancing functions.
|
||||
- Implement lazy loading for non-critical components.
|
||||
- Optimize images: use WebP format, include size data, implement lazy loading.
|
||||
- Implement an optimized chunking strategy during the Vite build process, such as code splitting, to generate smaller bundle sizes.
|
||||
@@ -1,137 +0,0 @@
|
||||
---
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# The Ultimate Frontend Development Guide: Principles, Patterns, and Practices
|
||||
|
||||
## Development Philosophy
|
||||
|
||||
- **First Principles**: Embrace SOLID principles, KISS (Keep It Simple, Stupid), and DRY (Don't Repeat Yourself)
|
||||
- **Functional Over Object-Oriented**: Favor functional and declarative programming patterns over imperative and OOP
|
||||
- **Component-Driven Development**: Build applications as compositions of well-defined, reusable components
|
||||
- **Type Safety**: Leverage TypeScript to its fullest potential for enhanced developer experience and code quality
|
||||
- **Think Then Code**: Begin with step-by-step planning and detailed pseudocode before implementation
|
||||
|
||||
## Code Architecture & Structure
|
||||
|
||||
### Project Organization
|
||||
- Use lowercase with dashes for directories (`components/auth-wizard/`)
|
||||
- Structure files consistently:
|
||||
1. Exported component/functionality
|
||||
2. Subcomponents/helpers
|
||||
3. Static content
|
||||
4. Types/interfaces
|
||||
|
||||
### Naming Conventions
|
||||
|
||||
- **PascalCase** for:
|
||||
- Components (`UserProfile`)
|
||||
- Type definitions/Interfaces (`UserData`)
|
||||
|
||||
- **kebab-case** for:
|
||||
- Directory names (`components/auth-wizard/`)
|
||||
- File names (`user-profile.tsx`)
|
||||
|
||||
- **camelCase** for:
|
||||
- Variables, functions, methods
|
||||
- Hooks, properties, props
|
||||
|
||||
- **Descriptive Prefixes**:
|
||||
- Prefix event handlers with 'handle': `handleClick`, `handleSubmit`
|
||||
- Prefix boolean variables with verbs: `isLoading`, `hasError`, `canSubmit`
|
||||
- Prefix custom hooks with 'use': `useAuth`, `useForm`
|
||||
|
||||
## TypeScript Implementation
|
||||
|
||||
- Enable strict mode
|
||||
- Prefer interfaces over types for object structures, especially when extending
|
||||
- Use type guards for null/undefined values
|
||||
- Apply generics for type flexibility
|
||||
- Leverage TypeScript utility types (`Partial<>`, `Pick<>`, `Omit<>`)
|
||||
- Avoid enums; use const objects/maps instead
|
||||
- Use discriminated unions for complex state management
|
||||
|
||||
## React & Next.js Best Practices
|
||||
|
||||
### Component Patterns
|
||||
|
||||
- Use functional components with explicit TypeScript interfaces
|
||||
- Use the `function` keyword for component definitions, not arrow functions
|
||||
- Extract reusable logic into custom hooks
|
||||
- Place static content in variables outside render functions
|
||||
- Implement proper cleanup in useEffect hooks
|
||||
|
||||
### Server Components First
|
||||
|
||||
- Default to Server Components
|
||||
- Use `'use client'` directive sparingly, only when necessary:
|
||||
- Event listeners
|
||||
- Browser APIs
|
||||
- State that must be client-side
|
||||
- Client-side-only libraries
|
||||
- Use URL query parameters for server state management
|
||||
- Implement proper data fetching using Next.js patterns
|
||||
|
||||
### Performance Optimizations
|
||||
|
||||
- Use React.memo() strategically
|
||||
- Implement useCallback for event handlers passed to child components
|
||||
- Use useMemo for expensive computations
|
||||
- Avoid inline function definitions in JSX
|
||||
- Implement code splitting using dynamic imports
|
||||
- Use proper key props in lists (avoid using index as key)
|
||||
- Wrap client components in Suspense with appropriate fallbacks
|
||||
|
||||
## UI and Styling
|
||||
|
||||
- Use Tailwind CSS for utility-first, maintainable styling
|
||||
- Leverage component libraries like Shadcn UI and Radix UI for accessible, composable UI
|
||||
- Design with mobile-first, responsive principles
|
||||
- Implement dark mode using CSS variables or Tailwind's dark mode features
|
||||
- Maintain consistent spacing values and design tokens
|
||||
- Use Framer Motion library for the animations of components
|
||||
|
||||
## Error Handling - The Art of Graceful Failures
|
||||
|
||||
### The Early Return Pattern
|
||||
|
||||
- Handle errors and edge cases at the beginning of functions
|
||||
- Use early returns for error conditions
|
||||
- Place the happy path last in the function
|
||||
- Avoid unnecessary else statements; use if-return pattern instead
|
||||
- Implement guard clauses to handle preconditions
|
||||
|
||||
### Structured Error Handling
|
||||
|
||||
- Use custom error types for consistent error handling
|
||||
- For Next.js Server Actions, model expected errors as return values
|
||||
- Implement error boundaries using error.tsx files
|
||||
- Provide user-friendly error messages
|
||||
- Log errors appropriately for debugging
|
||||
|
||||
## Form Validation
|
||||
|
||||
- Use Zod for schema validation
|
||||
- Implement proper error messages
|
||||
- Use react-hook-form for form state management
|
||||
- Combine with useActionState for server actions
|
||||
|
||||
## State Management
|
||||
|
||||
- Use useState for simple component-level state
|
||||
- Implement useReducer for complex local state
|
||||
- Use React Context for shared state within a component tree
|
||||
- For global state, choose appropriate tools:
|
||||
- Redux Toolkit for complex applications
|
||||
- Zustand for simpler state management
|
||||
- TanStack Query for server state
|
||||
|
||||
## Accessibility (a11y)
|
||||
|
||||
- Use semantic HTML elements
|
||||
- Apply appropriate ARIA attributes only when necessary
|
||||
- Ensure keyboard navigation support
|
||||
- Maintain accessible color contrast ratios
|
||||
- Follow a logical heading hierarchy
|
||||
- Provide clear and accessible error feedback
|
||||
- Test with screen readers
|
||||
@@ -0,0 +1,120 @@
|
||||
---
|
||||
description: Vite + TanStack Router v1 + TanStack Query v5 — routing, loaders, queries, mutations
|
||||
globs: apps/web/**/*.{tsx,ts}
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
# Vite + TanStack Router + Query
|
||||
|
||||
Фронтенд: **Vite SPA**, не Next.js. Нет Server Components, App Router, `'use client'`.
|
||||
|
||||
## Структура
|
||||
|
||||
```
|
||||
apps/web/src/
|
||||
routes/ # file-based routes (__root.tsx, _auth/, ...)
|
||||
queries/ # queryOptions factories + key factories
|
||||
lib/ # api-client, queryClient, auth, schemas
|
||||
components/ # domain + layout (UI primitives → @cfdm/ui)
|
||||
main.tsx
|
||||
```
|
||||
|
||||
## Архитектура
|
||||
|
||||
- **Router** — маршрутизация, URL state, navigation, loaders
|
||||
- **Query** — server state, cache, mutations
|
||||
- **Loader** — `queryClient.ensureQueryData()` до рендера → без спиннеров на route data
|
||||
- **Компоненты** — UI; данные из Query cache
|
||||
|
||||
## QueryClient + Router
|
||||
|
||||
```ts
|
||||
// lib/queryClient.ts
|
||||
export const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { staleTime: 60_000 } },
|
||||
})
|
||||
|
||||
// lib/router.ts
|
||||
export const router = createRouter({
|
||||
routeTree,
|
||||
context: { queryClient },
|
||||
defaultPreload: 'intent',
|
||||
})
|
||||
|
||||
declare module '@tanstack/react-router' {
|
||||
interface Register { router: typeof router }
|
||||
}
|
||||
```
|
||||
|
||||
## Query definitions
|
||||
|
||||
- `queryOptions` factories в `queries/`, не inline в компонентах
|
||||
- Key factories: `all` → `lists` / `details` → `list(filters)` / `detail(id)`
|
||||
|
||||
```ts
|
||||
export const serviceKeys = {
|
||||
all: ['services'] as const,
|
||||
list: () => [...serviceKeys.all, 'list'] as const,
|
||||
}
|
||||
|
||||
export const servicesQueryOptions = () =>
|
||||
queryOptions({
|
||||
queryKey: serviceKeys.list(),
|
||||
queryFn: () => api.get('/api/v1/services'),
|
||||
})
|
||||
```
|
||||
|
||||
## Loader + component
|
||||
|
||||
```tsx
|
||||
export const Route = createFileRoute('/_auth/services')({
|
||||
loader: ({ context: { queryClient } }) =>
|
||||
queryClient.ensureQueryData(servicesQueryOptions()),
|
||||
component: ServicesPage,
|
||||
})
|
||||
|
||||
function ServicesPage() {
|
||||
const { data } = useQuery(servicesQueryOptions()) // из cache loader
|
||||
return ...
|
||||
}
|
||||
```
|
||||
|
||||
## Search params
|
||||
|
||||
- Zod + `validateSearch`; доступ через `Route.useSearch()`
|
||||
- Search params = source of truth для фильтров/пагинации
|
||||
- Передавать в `queryOptions` для query key и fetcher
|
||||
|
||||
## Mutations
|
||||
|
||||
```ts
|
||||
onSuccess: (newItem) => {
|
||||
queryClient.setQueryData(keys.detail(newItem.id), newItem)
|
||||
queryClient.invalidateQueries({ queryKey: keys.lists() })
|
||||
}
|
||||
```
|
||||
|
||||
- `setQueryData` + `invalidateQueries`, не только invalidate
|
||||
- Навигация после create — когда cache уже тёплый
|
||||
|
||||
## Routing
|
||||
|
||||
- `createFileRoute` для file-based routes
|
||||
- `<Link>` для внутренней навигации, не `<a href>`
|
||||
- Pathless layouts: `_auth/` для protected routes
|
||||
- Auth guard в `beforeLoad` pathless route
|
||||
|
||||
## Запреты
|
||||
|
||||
- `useEffect` для fetch данных — только loader / `useQuery`
|
||||
- Inline `queryKey` в компонентах — только factories из `queries/`
|
||||
- `useQuery` с позиционными аргументами (v5 — только options object)
|
||||
- `window.location` для search params
|
||||
|
||||
## Prefetch
|
||||
|
||||
`onMouseEnter` на `<Link>` → `queryClient.prefetchQuery(detailOptions(id))`
|
||||
|
||||
## DevTools
|
||||
|
||||
Только в dev: `TanStackRouterDevtools`, `ReactQueryDevtools`
|
||||
@@ -1,300 +0,0 @@
|
||||
---
|
||||
description: This guide provides definitive best practices for developing high-performance, maintainable applications with Vite, focusing on optimal configuration, code structure, and testing.
|
||||
globs: **/*.{js,jsx}
|
||||
---
|
||||
# vite Best Practices
|
||||
|
||||
Vite is the modern standard for frontend tooling. Adhere to these principles to leverage its full potential, ensuring blazing-fast development and optimized production builds.
|
||||
|
||||
## 1. Code Organization and Structure
|
||||
|
||||
### Keep `vite.config.js` Minimal
|
||||
Vite's philosophy is a lean core. Avoid over-configuring. Only add plugins or options when absolutely necessary.
|
||||
|
||||
❌ **BAD** - Overly complex `vite.config.js`
|
||||
```javascript
|
||||
// vite.config.js
|
||||
import { defineConfig } from 'vite';
|
||||
import react from '@vitejs/plugin-react';
|
||||
import legacy from '@vitejs/plugin-legacy';
|
||||
import { visualizer } from 'rollup-plugin-visualizer';
|
||||
import { VitePWA } from 'vite-plugin-pwa';
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
react(),
|
||||
legacy({ targets: ['defaults', 'not IE 11'] }),
|
||||
visualizer({ filename: './dist/stats.html' }),
|
||||
VitePWA({ registerType: 'autoUpdate' }),
|
||||
// ... many more plugins
|
||||
],
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': '/src',
|
||||
'~': '/node_modules',
|
||||
},
|
||||
extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue'],
|
||||
},
|
||||
build: {
|
||||
target: 'es2015',
|
||||
minify: 'terser',
|
||||
sourcemap: true,
|
||||
rollupOptions: {
|
||||
output: {
|
||||
manualChunks: {
|
||||
vendor: ['react', 'react-dom'],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
server: {
|
||||
port: 3000,
|
||||
open: true,
|
||||
proxy: {
|
||||
'/api': 'http://localhost:8080',
|
||||
},
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
✅ **GOOD** - Lean and focused `vite.config.js`
|
||||
```javascript
|
||||
// vite.config.js
|
||||
import { defineConfig } from 'vite';
|
||||
import react from '@vitejs/plugin-react';
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
// Only add resolve.alias if absolutely needed for complex paths.
|
||||
// Avoid resolve.extensions unless you have specific non-standard file types.
|
||||
// Vite's defaults are usually sufficient.
|
||||
});
|
||||
```
|
||||
|
||||
### Use Explicit File Extensions
|
||||
Relying on `resolve.extensions` for implicit imports forces Vite to perform multiple filesystem checks, slowing down resolution. Be explicit.
|
||||
|
||||
❌ **BAD** - Implicit import
|
||||
```javascript
|
||||
// src/components/MyComponent.jsx
|
||||
import { util } from '../utils'; // Vite has to guess .js, .ts, .jsx etc.
|
||||
```
|
||||
|
||||
✅ **GOOD** - Explicit import
|
||||
```javascript
|
||||
// src/components/MyComponent.jsx
|
||||
import { util } from '../utils/index.js'; // Or .ts, .jsx, etc.
|
||||
```
|
||||
|
||||
### Avoid Barrel Files
|
||||
Barrel files (e.g., `index.js` re-exporting many modules) force Vite to fetch and transform all re-exported files, even if only one API is used. This hurts initial page load performance.
|
||||
|
||||
❌ **BAD** - Barrel file (`src/utils/index.js`)
|
||||
```javascript
|
||||
// src/utils/index.js
|
||||
export * from './color.js';
|
||||
export * from './dom.js';
|
||||
export * from './slash.js';
|
||||
|
||||
// src/app.js
|
||||
import { slash } from './utils'; // Loads color.js, dom.js, and slash.js
|
||||
```
|
||||
|
||||
✅ **GOOD** - Direct imports
|
||||
```javascript
|
||||
// src/app.js
|
||||
import { slash } from './utils/slash.js'; // Only loads slash.js
|
||||
```
|
||||
|
||||
## 2. Common Patterns and Anti-patterns
|
||||
|
||||
### Embrace Native ES Modules
|
||||
Vite is built on native ES Modules. Always write your client-side code using `import`/`export` syntax.
|
||||
|
||||
❌ **BAD** - CommonJS in client-side code
|
||||
```javascript
|
||||
// main.js
|
||||
const myModule = require('./my-module'); // Will fail in browser
|
||||
```
|
||||
|
||||
✅ **GOOD** - Native ES Modules
|
||||
```javascript
|
||||
// main.js
|
||||
import myModule from './my-module.js';
|
||||
```
|
||||
|
||||
### Use `import.meta.env` for Environment Variables
|
||||
Vite injects environment variables via `import.meta.env`. This is the correct way to access them in client-side code. `process.env` is for Node.js environments.
|
||||
|
||||
❌ **BAD** - Using `process.env` in client code
|
||||
```javascript
|
||||
// app.js
|
||||
console.log(process.env.VITE_API_URL); // `process` is not defined in browser
|
||||
```
|
||||
|
||||
✅ **GOOD** - Using `import.meta.env`
|
||||
```javascript
|
||||
// app.js
|
||||
console.log(import.meta.env.VITE_API_URL); // Correctly accesses Vite env vars
|
||||
```
|
||||
|
||||
### Optimize with Dynamic Imports
|
||||
For large components or libraries, use dynamic imports to load them only when needed, reducing initial bundle size and improving load times.
|
||||
|
||||
❌ **BAD** - Eagerly loading large component
|
||||
```javascript
|
||||
// App.jsx
|
||||
import LargeComponent from './LargeComponent'; // Always bundled
|
||||
function App() {
|
||||
return <LargeComponent />;
|
||||
}
|
||||
```
|
||||
|
||||
✅ **GOOD** - Dynamically importing
|
||||
```javascript
|
||||
// App.jsx (React example)
|
||||
import { lazy, Suspense } from 'react';
|
||||
const LargeComponent = lazy(() => import('./LargeComponent'));
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<Suspense fallback={<div>Loading...</div>}>
|
||||
<LargeComponent />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## 3. Performance Considerations
|
||||
|
||||
### Audit Custom Plugins
|
||||
Community plugins can introduce performance bottlenecks. Profile them using Vite's debug flags.
|
||||
|
||||
❌ **BAD** - Blindly adding plugins
|
||||
```javascript
|
||||
// vite.config.js
|
||||
import { defineConfig } from 'vite';
|
||||
import someHeavyPlugin from 'some-heavy-plugin'; // No profiling done
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [someHeavyPlugin()],
|
||||
});
|
||||
```
|
||||
|
||||
✅ **GOOD** - Profiling plugins
|
||||
```bash
|
||||
# Run Vite with debug flags to identify slow plugins
|
||||
vite --debug plugin-transform
|
||||
```
|
||||
Use `vite-plugin-inspect` to visualize the transform pipeline.
|
||||
|
||||
### Optimize Browser Setup
|
||||
Browser extensions and disabled cache settings can severely impact dev server performance.
|
||||
|
||||
❌ **BAD** - Developing with "Disable Cache" enabled in dev tools.
|
||||
```
|
||||
// Browser Dev Tools -> Network tab -> "Disable Cache" checked
|
||||
```
|
||||
|
||||
✅ **GOOD** - Use a clean browser profile or incognito mode.
|
||||
Ensure "Disable Cache" is **unchecked** in dev tools.
|
||||
|
||||
### Warm Up Critical Files
|
||||
For complex applications, pre-warming frequently used files can prevent request waterfalls.
|
||||
|
||||
❌ **BAD** - Relying solely on on-demand transformation for critical paths.
|
||||
```javascript
|
||||
// No explicit warmup configured
|
||||
```
|
||||
|
||||
✅ **GOOD** - Use `server.warmup` in `vite.config.js`
|
||||
```javascript
|
||||
// vite.config.js
|
||||
import { defineConfig } from 'vite';
|
||||
|
||||
export default defineConfig({
|
||||
server: {
|
||||
warmup: {
|
||||
clientFiles: ['./src/main.js', './src/App.jsx'],
|
||||
// Or use patterns: ['**/*.vue', '**/*.jsx']
|
||||
},
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
## 4. Common Pitfalls and Gotchas
|
||||
|
||||
### Incorrect Base Path for Deployment
|
||||
When deploying to a sub-path (e.g., `yourdomain.com/my-app/`), ensure `base` is correctly configured.
|
||||
|
||||
❌ **BAD** - Hardcoding absolute paths or missing `base`
|
||||
```javascript
|
||||
// vite.config.js
|
||||
// Default base: '/'
|
||||
// Assets might break when deployed to a sub-path
|
||||
```
|
||||
|
||||
✅ **GOOD** - Configure `base` for sub-path deployments
|
||||
```javascript
|
||||
// vite.config.js
|
||||
import { defineConfig } from 'vite';
|
||||
|
||||
export default defineConfig({
|
||||
base: '/my-app/', // For deploying to https://yourdomain.com/my-app/
|
||||
// Or use './' for relative paths if the base is unknown at build time
|
||||
// base: './',
|
||||
});
|
||||
```
|
||||
Access the base path in your code via `import.meta.env.BASE_URL`.
|
||||
|
||||
### Mismanaging `NODE_ENV` with API Usage
|
||||
When using Vite's JS API (`createServer`, `build`) in the same Node.js process, ensure `process.env.NODE_ENV` or the `mode` config option is consistent to prevent conflicts.
|
||||
|
||||
❌ **BAD** - Conflicting `NODE_ENV`
|
||||
```javascript
|
||||
// script.js
|
||||
process.env.NODE_ENV = 'production';
|
||||
await createServer(); // Might behave unexpectedly
|
||||
```
|
||||
|
||||
✅ **GOOD** - Explicitly set `mode` or spawn child processes
|
||||
```javascript
|
||||
// script.js
|
||||
import { createServer } from 'vite';
|
||||
// Option 1: Explicitly set mode
|
||||
const devServer = await createServer({ mode: 'development' });
|
||||
await devServer.listen();
|
||||
|
||||
// Option 2: Spawn child processes for separate contexts
|
||||
// (e.g., one for dev server, one for build)
|
||||
```
|
||||
|
||||
## 5. Testing Approaches
|
||||
|
||||
### Standardize on Vitest
|
||||
Vitest is the official testing framework for Vite projects, offering seamless integration with Vite's configuration and plugin ecosystem.
|
||||
|
||||
❌ **BAD** - Using a separate test runner (e.g., Jest) that requires its own complex configuration.
|
||||
```json
|
||||
// package.json
|
||||
"scripts": {
|
||||
"test": "jest" // Requires separate Babel/Webpack config
|
||||
}
|
||||
```
|
||||
|
||||
✅ **GOOD** - Integrate Vitest directly into `vite.config.ts`
|
||||
```typescript
|
||||
// vite.config.ts
|
||||
/// <reference types="vitest/config" />
|
||||
import { defineConfig } from 'vite';
|
||||
import react from '@vitejs/plugin-react';
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
test: {
|
||||
globals: true, // For global APIs like `describe`, `it`, `expect`
|
||||
environment: 'jsdom', // Or 'node'
|
||||
setupFiles: './src/setupTests.js', // Global setup for tests
|
||||
},
|
||||
});
|
||||
```
|
||||
+3
-1
@@ -3,7 +3,9 @@
|
||||
data
|
||||
**/target
|
||||
**/node_modules
|
||||
frontend/dist
|
||||
apps/web/dist
|
||||
.turbo
|
||||
frontend
|
||||
*.db
|
||||
*.db-shm
|
||||
*.db-wal
|
||||
|
||||
+1
-1
@@ -17,4 +17,4 @@ STATIC_DIR=
|
||||
RUST_LOG=info
|
||||
|
||||
# Certificate scheduler (cron)
|
||||
CERT_CHECK_CRON=0 */6 * * *
|
||||
CERT_CHECK_CRON=0 0 */6 * * *
|
||||
|
||||
+8
-4
@@ -2,10 +2,14 @@
|
||||
backend/target/
|
||||
**/*.rs.bk
|
||||
|
||||
# Node
|
||||
frontend/node_modules/
|
||||
frontend/dist/
|
||||
frontend/.tanstack/
|
||||
# Node / pnpm monorepo
|
||||
node_modules/
|
||||
.pnpm-store/
|
||||
.turbo/
|
||||
apps/web/node_modules/
|
||||
apps/web/dist/
|
||||
apps/web/.tanstack/
|
||||
packages/ui/node_modules/
|
||||
|
||||
# Data
|
||||
data/
|
||||
|
||||
+2
-3
@@ -46,9 +46,8 @@ cp ../.env.example ../.env
|
||||
cargo run
|
||||
|
||||
# Frontend (separate terminal)
|
||||
cd frontend
|
||||
npm install
|
||||
npm run dev
|
||||
pnpm install
|
||||
pnpm --filter web dev
|
||||
```
|
||||
|
||||
## Release process
|
||||
|
||||
+11
-7
@@ -1,11 +1,15 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
|
||||
FROM node:22-bookworm-slim AS frontend-builder
|
||||
WORKDIR /app/frontend
|
||||
COPY frontend/package.json frontend/package-lock.json ./
|
||||
RUN npm ci
|
||||
COPY frontend/ ./
|
||||
RUN npm run build
|
||||
WORKDIR /app
|
||||
RUN corepack enable
|
||||
COPY package.json pnpm-workspace.yaml pnpm-lock.yaml ./
|
||||
COPY apps/web/package.json apps/web/
|
||||
COPY packages/ui/package.json packages/ui/
|
||||
RUN pnpm install --frozen-lockfile
|
||||
COPY apps/web apps/web
|
||||
COPY packages/ui packages/ui
|
||||
RUN pnpm --filter web build
|
||||
|
||||
FROM rust:1.85-bookworm AS backend-builder
|
||||
WORKDIR /app
|
||||
@@ -13,7 +17,7 @@ RUN apt-get update && apt-get install -y pkg-config libssl-dev && rm -rf /var/li
|
||||
COPY backend/Cargo.toml backend/Cargo.lock* ./backend/
|
||||
COPY backend/migrations ./backend/migrations/
|
||||
COPY backend/src ./backend/src/
|
||||
COPY --from=frontend-builder /app/frontend/dist ./static/
|
||||
COPY --from=frontend-builder /app/apps/web/dist ./static/
|
||||
WORKDIR /app/backend
|
||||
ENV STATIC_DIR=/app/static
|
||||
RUN cargo build --release
|
||||
@@ -22,7 +26,7 @@ FROM debian:bookworm-slim AS runtime
|
||||
RUN apt-get update && apt-get install -y ca-certificates && rm -rf /var/lib/apt/lists/*
|
||||
WORKDIR /app
|
||||
COPY --from=backend-builder /app/backend/target/release/cfdm-backend /app/cfdm-backend
|
||||
COPY --from=frontend-builder /app/frontend/dist /app/static
|
||||
COPY --from=frontend-builder /app/apps/web/dist /app/static
|
||||
COPY VERSION /app/VERSION
|
||||
ENV STATIC_DIR=/app/static
|
||||
ENV DATABASE_URL=sqlite:/data/app.db
|
||||
|
||||
+11
-7
@@ -4,8 +4,9 @@ FROM rust:1.85-bookworm AS test
|
||||
WORKDIR /app
|
||||
RUN apt-get update && apt-get install -y pkg-config libssl-dev curl && rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Node for frontend tests
|
||||
# Node + pnpm for frontend tests
|
||||
RUN curl -fsSL https://deb.nodesource.com/setup_22.x | bash - && apt-get install -y nodejs
|
||||
RUN corepack enable
|
||||
|
||||
COPY backend/Cargo.toml backend/Cargo.lock* ./backend/
|
||||
COPY backend/migrations ./backend/migrations/
|
||||
@@ -13,10 +14,13 @@ COPY backend/src ./backend/src/
|
||||
WORKDIR /app/backend
|
||||
RUN cargo test --release
|
||||
|
||||
COPY frontend/package.json frontend/package-lock.json /app/frontend/
|
||||
WORKDIR /app/frontend
|
||||
RUN npm ci
|
||||
COPY frontend/ /app/frontend/
|
||||
RUN npm run test
|
||||
COPY package.json pnpm-workspace.yaml pnpm-lock.yaml /app/
|
||||
COPY apps/web/package.json /app/apps/web/
|
||||
COPY packages/ui/package.json /app/packages/ui/
|
||||
WORKDIR /app
|
||||
RUN pnpm install --frozen-lockfile
|
||||
COPY apps/web /app/apps/web
|
||||
COPY packages/ui /app/packages/ui
|
||||
RUN pnpm --filter web test
|
||||
|
||||
CMD ["sh", "-c", "cd /app/backend && cargo test && cd /app/frontend && npm run test"]
|
||||
CMD ["sh", "-c", "cd /app/backend && cargo test && cd /app && pnpm --filter web test"]
|
||||
|
||||
@@ -24,9 +24,19 @@ Open http://localhost:8080 — default login `admin` / `admin` (dev only).
|
||||
## Stack
|
||||
|
||||
- **Backend:** Rust, Axum, sqlx, SQLite
|
||||
- **Frontend:** React, Vite, TanStack Router/Query/Table, shadcn-style UI, Recharts
|
||||
- **Frontend:** pnpm monorepo (`apps/web` + `packages/ui`), React, Vite, TanStack Router/Query/Table, shadcn/ui (base-nova), Recharts
|
||||
- **CI:** Gitea Actions (Gitflow)
|
||||
|
||||
## Frontend development
|
||||
|
||||
```bash
|
||||
pnpm install
|
||||
pnpm --filter web dev # http://localhost:5173, proxies /api → :8080
|
||||
pnpm --filter web build
|
||||
```
|
||||
|
||||
shadcn CLI: `cd apps/web && pnpm dlx shadcn@latest add <component>`
|
||||
|
||||
## Documentation
|
||||
|
||||
See [docs/Home.md](docs/Home.md) and [CONTRIBUTING.md](CONTRIBUTING.md).
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"$schema": "https://ui.shadcn.com/schema.json",
|
||||
"style": "base-nova",
|
||||
"rsc": false,
|
||||
"tsx": true,
|
||||
"tailwind": {
|
||||
"config": "",
|
||||
"css": "../../packages/ui/src/styles/globals.css",
|
||||
"baseColor": "neutral",
|
||||
"cssVariables": true,
|
||||
"prefix": ""
|
||||
},
|
||||
"iconLibrary": "lucide",
|
||||
"rtl": false,
|
||||
"aliases": {
|
||||
"components": "@/components",
|
||||
"utils": "@cfdm/ui/lib/utils",
|
||||
"ui": "@cfdm/ui/components",
|
||||
"lib": "@/lib",
|
||||
"hooks": "@/hooks"
|
||||
},
|
||||
"menuColor": "default",
|
||||
"menuAccent": "subtle"
|
||||
}
|
||||
@@ -4,7 +4,7 @@
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>frontend</title>
|
||||
<title>Cloudflare Domain Manager</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"name": "cfdm-frontend",
|
||||
"name": "web",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
@@ -11,26 +11,21 @@
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@cfdm/ui": "workspace:*",
|
||||
"@hookform/resolvers": "^5.4.0",
|
||||
"@radix-ui/react-dialog": "^1.1.16",
|
||||
"@radix-ui/react-dropdown-menu": "^2.1.17",
|
||||
"@radix-ui/react-label": "^2.1.9",
|
||||
"@radix-ui/react-select": "^2.3.0",
|
||||
"@radix-ui/react-slot": "^1.2.5",
|
||||
"@radix-ui/react-tabs": "^1.1.14",
|
||||
"@tailwindcss/vite": "^4.3.1",
|
||||
"@tanstack/react-query": "^5.101.0",
|
||||
"@tanstack/react-router": "^1.170.15",
|
||||
"@tanstack/react-table": "^8.21.3",
|
||||
"@tanstack/router-vite-plugin": "^1.167.18",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"lucide-react": "^1.18.0",
|
||||
"next-themes": "^0.4.6",
|
||||
"react": "^19.2.6",
|
||||
"react-dom": "^19.2.6",
|
||||
"react-hook-form": "^7.79.0",
|
||||
"recharts": "^3.8.1",
|
||||
"tailwind-merge": "^3.6.0",
|
||||
"recharts": "^3.8.0",
|
||||
"sonner": "^2.0.7",
|
||||
"tailwindcss": "^4.3.1",
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
|
Before Width: | Height: | Size: 9.3 KiB After Width: | Height: | Size: 9.3 KiB |
|
Before Width: | Height: | Size: 4.9 KiB After Width: | Height: | Size: 4.9 KiB |
@@ -0,0 +1,74 @@
|
||||
import { Link } from '@tanstack/react-router'
|
||||
import {
|
||||
LayoutDashboardIcon,
|
||||
GlobeIcon,
|
||||
FolderTreeIcon,
|
||||
ServerIcon,
|
||||
ShieldCheckIcon,
|
||||
CloudIcon,
|
||||
} from 'lucide-react'
|
||||
import { NavUser } from '@/components/nav-user'
|
||||
import {
|
||||
Sidebar,
|
||||
SidebarContent,
|
||||
SidebarFooter,
|
||||
SidebarGroup,
|
||||
SidebarGroupLabel,
|
||||
SidebarHeader,
|
||||
SidebarMenu,
|
||||
SidebarMenuButton,
|
||||
SidebarMenuItem,
|
||||
SidebarRail,
|
||||
} from '@cfdm/ui/components/sidebar'
|
||||
|
||||
const navItems = [
|
||||
{ to: '/', label: 'Панель управления', icon: LayoutDashboardIcon },
|
||||
{ to: '/domains', label: 'Домены', icon: GlobeIcon },
|
||||
{ to: '/groups', label: 'Группы', icon: FolderTreeIcon },
|
||||
{ to: '/services', label: 'Сервисы', icon: ServerIcon },
|
||||
{ to: '/certificates', label: 'Сертификаты', icon: ShieldCheckIcon },
|
||||
] as const
|
||||
|
||||
export function AppSidebar() {
|
||||
return (
|
||||
<Sidebar collapsible="icon">
|
||||
<SidebarHeader>
|
||||
<SidebarMenu>
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton size="lg" render={<Link to="/" />}>
|
||||
<div className="flex aspect-square size-8 items-center justify-center rounded-lg bg-sidebar-primary text-sidebar-primary-foreground">
|
||||
<CloudIcon />
|
||||
</div>
|
||||
<div className="grid flex-1 text-left text-sm leading-tight">
|
||||
<span className="truncate font-medium">CF Domain Manager</span>
|
||||
<span className="truncate text-xs">Управление доменами</span>
|
||||
</div>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
</SidebarMenu>
|
||||
</SidebarHeader>
|
||||
<SidebarContent>
|
||||
<SidebarGroup>
|
||||
<SidebarGroupLabel>Навигация</SidebarGroupLabel>
|
||||
<SidebarMenu>
|
||||
{navItems.map((item) => (
|
||||
<SidebarMenuItem key={item.to}>
|
||||
<SidebarMenuButton
|
||||
tooltip={item.label}
|
||||
render={<Link to={item.to} activeOptions={{ exact: item.to === '/' }} />}
|
||||
>
|
||||
<item.icon />
|
||||
<span>{item.label}</span>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
))}
|
||||
</SidebarMenu>
|
||||
</SidebarGroup>
|
||||
</SidebarContent>
|
||||
<SidebarFooter>
|
||||
<NavUser />
|
||||
</SidebarFooter>
|
||||
<SidebarRail />
|
||||
</Sidebar>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from '@cfdm/ui/components/card'
|
||||
|
||||
interface DataTableCardProps {
|
||||
title: string
|
||||
description?: string
|
||||
children: React.ReactNode
|
||||
}
|
||||
|
||||
export function DataTableCard({
|
||||
title,
|
||||
description,
|
||||
children,
|
||||
}: DataTableCardProps) {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{title}</CardTitle>
|
||||
{description && <CardDescription>{description}</CardDescription>}
|
||||
</CardHeader>
|
||||
<CardContent className="p-0">{children}</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import { AppSidebar } from '@/components/app-sidebar'
|
||||
import { SiteHeader } from '@/components/layout/site-header'
|
||||
import { SidebarInset, SidebarProvider } from '@cfdm/ui/components/sidebar'
|
||||
|
||||
export function AppShell({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<SidebarProvider>
|
||||
<AppSidebar />
|
||||
<SidebarInset>
|
||||
<SiteHeader />
|
||||
<div className="flex flex-1 flex-col gap-4 p-4 pt-0">
|
||||
{children}
|
||||
</div>
|
||||
</SidebarInset>
|
||||
</SidebarProvider>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import { Link, useRouterState } from '@tanstack/react-router'
|
||||
import {
|
||||
Breadcrumb,
|
||||
BreadcrumbItem,
|
||||
BreadcrumbLink,
|
||||
BreadcrumbList,
|
||||
BreadcrumbPage,
|
||||
BreadcrumbSeparator,
|
||||
} from '@cfdm/ui/components/breadcrumb'
|
||||
import { Separator } from '@cfdm/ui/components/separator'
|
||||
import { SidebarTrigger } from '@cfdm/ui/components/sidebar'
|
||||
|
||||
const routeTitles: Record<string, string> = {
|
||||
'/': 'Панель управления',
|
||||
'/domains': 'Домены',
|
||||
'/groups': 'Группы',
|
||||
'/services': 'Сервисы',
|
||||
'/certificates': 'Сертификаты',
|
||||
}
|
||||
|
||||
function getBreadcrumbs(pathname: string) {
|
||||
if (pathname === '/') {
|
||||
return [{ label: 'Панель управления', href: '/' }]
|
||||
}
|
||||
|
||||
if (pathname.match(/^\/domains\/\d+\/dns$/)) {
|
||||
const domainId = pathname.split('/')[2]
|
||||
return [
|
||||
{ label: 'Домены', href: '/domains' },
|
||||
{ label: 'Домен', href: `/domains/${domainId}` },
|
||||
{ label: 'DNS', href: pathname },
|
||||
]
|
||||
}
|
||||
|
||||
if (pathname.match(/^\/domains\/\d+$/)) {
|
||||
return [
|
||||
{ label: 'Домены', href: '/domains' },
|
||||
{ label: 'Обзор домена', href: pathname },
|
||||
]
|
||||
}
|
||||
|
||||
const title = routeTitles[pathname]
|
||||
if (title) {
|
||||
return [{ label: title, href: pathname }]
|
||||
}
|
||||
|
||||
return [{ label: 'Панель управления', href: '/' }]
|
||||
}
|
||||
|
||||
export function SiteHeader() {
|
||||
const pathname = useRouterState({ select: (s) => s.location.pathname })
|
||||
const crumbs = getBreadcrumbs(pathname)
|
||||
|
||||
return (
|
||||
<header className="flex h-16 shrink-0 items-center gap-2 border-b transition-[width,height] ease-linear group-has-data-[collapsible=icon]/sidebar-wrapper:h-12">
|
||||
<div className="flex items-center gap-2 px-4">
|
||||
<SidebarTrigger className="-ml-1" />
|
||||
<Separator
|
||||
orientation="vertical"
|
||||
className="mr-2 data-[orientation=vertical]:h-4"
|
||||
/>
|
||||
<Breadcrumb>
|
||||
<BreadcrumbList>
|
||||
{crumbs.map((crumb, index) => {
|
||||
const isLast = index === crumbs.length - 1
|
||||
return (
|
||||
<span key={crumb.href} className="contents">
|
||||
{index > 0 && <BreadcrumbSeparator className="hidden md:block" />}
|
||||
<BreadcrumbItem className={index === 0 ? 'hidden md:block' : undefined}>
|
||||
{isLast ? (
|
||||
<BreadcrumbPage>{crumb.label}</BreadcrumbPage>
|
||||
) : (
|
||||
<BreadcrumbLink render={<Link to={crumb.href} />}>
|
||||
{crumb.label}
|
||||
</BreadcrumbLink>
|
||||
)}
|
||||
</BreadcrumbItem>
|
||||
</span>
|
||||
)
|
||||
})}
|
||||
</BreadcrumbList>
|
||||
</Breadcrumb>
|
||||
</div>
|
||||
</header>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { useNavigate } from '@tanstack/react-router'
|
||||
import { CircleAlertIcon } from 'lucide-react'
|
||||
import { cn } from '@cfdm/ui/lib/utils'
|
||||
import { api } from '@/lib/api-client'
|
||||
import { setToken } from '@/lib/auth'
|
||||
import { loginSchema, type LoginInput } from '@/lib/schemas'
|
||||
import { Button } from '@cfdm/ui/components/button'
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from '@cfdm/ui/components/card'
|
||||
import {
|
||||
Field,
|
||||
FieldGroup,
|
||||
FieldLabel,
|
||||
} from '@cfdm/ui/components/field'
|
||||
import { Input } from '@cfdm/ui/components/input'
|
||||
import { Alert, AlertDescription, AlertTitle } from '@cfdm/ui/components/alert'
|
||||
import { Spinner } from '@cfdm/ui/components/spinner'
|
||||
|
||||
type LoginFormProps = React.ComponentProps<'div'>
|
||||
|
||||
export function LoginForm({ className, ...props }: LoginFormProps) {
|
||||
const navigate = useNavigate()
|
||||
const form = useForm<LoginInput>({
|
||||
resolver: zodResolver(loginSchema),
|
||||
defaultValues: { username: 'admin', password: 'admin' },
|
||||
})
|
||||
|
||||
const handleSubmit = form.handleSubmit(async (values) => {
|
||||
try {
|
||||
const res = await api.post<{ token: string }>('/api/v1/auth/login', values)
|
||||
setToken(res.token)
|
||||
navigate({ to: '/' })
|
||||
} catch (err) {
|
||||
form.setError('root', {
|
||||
message: err instanceof Error ? err.message : 'Не удалось войти',
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
const rootError = form.formState.errors.root?.message
|
||||
const isLoading = form.formState.isSubmitting
|
||||
|
||||
return (
|
||||
<div className={cn('flex flex-col gap-6', className)} {...props}>
|
||||
<Card>
|
||||
<CardHeader className="text-center">
|
||||
<CardTitle className="text-xl">Вход в систему</CardTitle>
|
||||
<CardDescription>
|
||||
Введите учётные данные для доступа к панели управления
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<FieldGroup>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="username">Имя пользователя</FieldLabel>
|
||||
<Input
|
||||
id="username"
|
||||
placeholder="admin"
|
||||
autoComplete="username"
|
||||
{...form.register('username')}
|
||||
aria-invalid={!!form.formState.errors.username}
|
||||
/>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="password">Пароль</FieldLabel>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
{...form.register('password')}
|
||||
aria-invalid={!!form.formState.errors.password}
|
||||
/>
|
||||
</Field>
|
||||
{rootError && (
|
||||
<Alert variant="destructive">
|
||||
<CircleAlertIcon />
|
||||
<AlertTitle>Ошибка входа</AlertTitle>
|
||||
<AlertDescription>{rootError}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
<Field>
|
||||
<Button type="submit" className="w-full" disabled={isLoading}>
|
||||
{isLoading && <Spinner data-icon="inline-start" />}
|
||||
{isLoading ? 'Вход…' : 'Войти'}
|
||||
</Button>
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { useNavigate } from '@tanstack/react-router'
|
||||
import { Avatar, AvatarFallback } from '@cfdm/ui/components/avatar'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuGroup,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from '@cfdm/ui/components/dropdown-menu'
|
||||
import {
|
||||
SidebarMenu,
|
||||
SidebarMenuButton,
|
||||
SidebarMenuItem,
|
||||
useSidebar,
|
||||
} from '@cfdm/ui/components/sidebar'
|
||||
import { ChevronsUpDownIcon, LogOutIcon } from 'lucide-react'
|
||||
import { clearToken } from '@/lib/auth'
|
||||
|
||||
export function NavUser() {
|
||||
const navigate = useNavigate()
|
||||
const { isMobile } = useSidebar()
|
||||
|
||||
const handleLogout = () => {
|
||||
clearToken()
|
||||
navigate({ to: '/login' })
|
||||
}
|
||||
|
||||
return (
|
||||
<SidebarMenu>
|
||||
<SidebarMenuItem>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger
|
||||
render={
|
||||
<SidebarMenuButton size="lg" className="aria-expanded:bg-muted" />
|
||||
}
|
||||
>
|
||||
<Avatar>
|
||||
<AvatarFallback>АД</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="grid flex-1 text-left text-sm leading-tight">
|
||||
<span className="truncate font-medium">Администратор</span>
|
||||
<span className="truncate text-xs">admin</span>
|
||||
</div>
|
||||
<ChevronsUpDownIcon className="ml-auto size-4" />
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent
|
||||
className="w-56"
|
||||
side={isMobile ? 'bottom' : 'right'}
|
||||
align="end"
|
||||
sideOffset={4}
|
||||
>
|
||||
<DropdownMenuGroup>
|
||||
<DropdownMenuLabel className="p-0 font-normal">
|
||||
<div className="flex items-center gap-2 px-1 py-1.5 text-left text-sm">
|
||||
<Avatar>
|
||||
<AvatarFallback>АД</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="grid flex-1 text-left text-sm leading-tight">
|
||||
<span className="truncate font-medium">Администратор</span>
|
||||
<span className="truncate text-xs">admin</span>
|
||||
</div>
|
||||
</div>
|
||||
</DropdownMenuLabel>
|
||||
</DropdownMenuGroup>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onClick={handleLogout}>
|
||||
<LogOutIcon />
|
||||
Выйти
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</SidebarMenuItem>
|
||||
</SidebarMenu>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { Link } from '@tanstack/react-router'
|
||||
import { Button } from '@cfdm/ui/components/button'
|
||||
import { cn } from '@cfdm/ui/lib/utils'
|
||||
|
||||
interface PageHeaderBack {
|
||||
to: string
|
||||
label: string
|
||||
params?: Record<string, string>
|
||||
}
|
||||
|
||||
interface PageHeaderProps {
|
||||
title: string
|
||||
description?: string
|
||||
back?: PageHeaderBack
|
||||
actions?: React.ReactNode
|
||||
className?: string
|
||||
}
|
||||
|
||||
export function PageHeader({
|
||||
title,
|
||||
description,
|
||||
back,
|
||||
actions,
|
||||
className,
|
||||
}: PageHeaderProps) {
|
||||
return (
|
||||
<div className={cn('flex items-center justify-between gap-4', className)}>
|
||||
<div>
|
||||
{back && (
|
||||
<Button
|
||||
variant="link"
|
||||
className="h-auto p-0 text-muted-foreground"
|
||||
render={<Link to={back.to} params={back.params} />}
|
||||
>
|
||||
{back.label}
|
||||
</Button>
|
||||
)}
|
||||
<h1
|
||||
className={cn(
|
||||
'text-2xl font-bold tracking-tight',
|
||||
back && 'mt-2',
|
||||
)}
|
||||
>
|
||||
{title}
|
||||
</h1>
|
||||
{description && (
|
||||
<p className="text-muted-foreground">{description}</p>
|
||||
)}
|
||||
</div>
|
||||
{actions}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
} from '@cfdm/ui/components/card'
|
||||
import {
|
||||
Empty,
|
||||
EmptyDescription,
|
||||
EmptyHeader,
|
||||
EmptyTitle,
|
||||
} from '@cfdm/ui/components/empty'
|
||||
|
||||
export interface ResourceListItem {
|
||||
id: string | number
|
||||
primary: string
|
||||
secondary?: string
|
||||
}
|
||||
|
||||
interface ResourceListProps {
|
||||
items: ResourceListItem[]
|
||||
emptyTitle?: string
|
||||
emptyDescription?: string
|
||||
renderActions?: (item: ResourceListItem) => React.ReactNode
|
||||
}
|
||||
|
||||
export function ResourceList({
|
||||
items,
|
||||
emptyTitle = 'Нет записей',
|
||||
emptyDescription,
|
||||
renderActions,
|
||||
}: ResourceListProps) {
|
||||
if (!items.length) {
|
||||
return (
|
||||
<Empty className="border">
|
||||
<EmptyHeader>
|
||||
<EmptyTitle>{emptyTitle}</EmptyTitle>
|
||||
{emptyDescription && (
|
||||
<EmptyDescription>{emptyDescription}</EmptyDescription>
|
||||
)}
|
||||
</EmptyHeader>
|
||||
</Empty>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="p-0">
|
||||
<ul>
|
||||
{items.map((item) => (
|
||||
<li
|
||||
key={item.id}
|
||||
className="flex items-center justify-between gap-2 border-b px-4 py-3 last:border-b-0"
|
||||
>
|
||||
<span className="font-medium">{item.primary}</span>
|
||||
<div className="flex items-center gap-2">
|
||||
{item.secondary && (
|
||||
<span className="text-muted-foreground">{item.secondary}</span>
|
||||
)}
|
||||
{renderActions?.(item)}
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { Badge, badgeVariants } from '@cfdm/ui/components/badge'
|
||||
import type { VariantProps } from 'class-variance-authority'
|
||||
import { cn } from '@cfdm/ui/lib/utils'
|
||||
|
||||
type BadgeVariant = NonNullable<VariantProps<typeof badgeVariants>['variant']>
|
||||
|
||||
const statusVariants: Record<string, BadgeVariant> = {
|
||||
synced: 'default',
|
||||
ok: 'default',
|
||||
pending_push: 'secondary',
|
||||
warning: 'secondary',
|
||||
conflict: 'destructive',
|
||||
error: 'destructive',
|
||||
expired: 'destructive',
|
||||
unknown: 'outline',
|
||||
}
|
||||
|
||||
const labels: Record<string, string> = {
|
||||
synced: 'Синхронизировано',
|
||||
pending_push: 'Ожидает отправки',
|
||||
conflict: 'Конфликт',
|
||||
error: 'Ошибка',
|
||||
ok: 'OK',
|
||||
warning: 'Предупреждение',
|
||||
expired: 'Истёк',
|
||||
unknown: 'Неизвестно',
|
||||
}
|
||||
|
||||
interface StatusBadgeProps {
|
||||
status: string
|
||||
className?: string
|
||||
}
|
||||
|
||||
export function StatusBadge({ status, className }: StatusBadgeProps) {
|
||||
const variant = statusVariants[status] ?? 'outline'
|
||||
return (
|
||||
<Badge variant={variant} className={cn(className)}>
|
||||
{labels[status] ?? status}
|
||||
</Badge>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { ThemeProvider as NextThemesProvider } from 'next-themes'
|
||||
|
||||
export function ThemeProvider({
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof NextThemesProvider>) {
|
||||
return <NextThemesProvider {...props}>{children}</NextThemesProvider>
|
||||
}
|
||||
@@ -1,10 +1,3 @@
|
||||
import { type ClassValue, clsx } from 'clsx'
|
||||
import { twMerge } from 'tailwind-merge'
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs))
|
||||
}
|
||||
|
||||
export function getToken(): string | null {
|
||||
return localStorage.getItem('cfdm_token')
|
||||
}
|
||||
@@ -62,3 +62,37 @@ export type Service = z.infer<typeof serviceSchema>
|
||||
export type Domain = z.infer<typeof domainSchema>
|
||||
export type DnsRecord = z.infer<typeof dnsRecordSchema>
|
||||
export type Certificate = z.infer<typeof certificateSchema>
|
||||
|
||||
export const createGroupSchema = z.object({
|
||||
name: z.string().min(1, 'Укажите название'),
|
||||
slug: z.string().min(1, 'Укажите slug'),
|
||||
})
|
||||
|
||||
export const createServiceSchema = z.object({
|
||||
name: z.string().min(1, 'Укажите название'),
|
||||
slug: z.string().min(1, 'Укажите slug'),
|
||||
})
|
||||
|
||||
export const createDomainSchema = z.object({
|
||||
zone_name: z.string().min(1, 'Укажите имя зоны'),
|
||||
group_id: z.string(),
|
||||
})
|
||||
|
||||
export const loginSchema = z.object({
|
||||
username: z.string().min(1, 'Укажите имя пользователя'),
|
||||
password: z.string().min(1, 'Укажите пароль'),
|
||||
})
|
||||
|
||||
export const createDnsRecordSchema = z.object({
|
||||
record_type: z.enum(['A', 'AAAA', 'CNAME', 'TXT', 'MX']),
|
||||
name: z.string().min(1, 'Укажите имя'),
|
||||
content: z.string().min(1, 'Укажите значение'),
|
||||
ttl: z.number().int().min(1),
|
||||
proxied: z.boolean(),
|
||||
})
|
||||
|
||||
export type CreateGroupInput = z.infer<typeof createGroupSchema>
|
||||
export type CreateServiceInput = z.infer<typeof createServiceSchema>
|
||||
export type CreateDomainInput = z.infer<typeof createDomainSchema>
|
||||
export type LoginInput = z.infer<typeof loginSchema>
|
||||
export type CreateDnsRecordInput = z.infer<typeof createDnsRecordSchema>
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { cn } from './utils'
|
||||
import { cn } from '@cfdm/ui/lib/utils'
|
||||
|
||||
describe('cn', () => {
|
||||
it('merges classes', () => {
|
||||
@@ -2,9 +2,12 @@ import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { RouterProvider, createRouter } from '@tanstack/react-router'
|
||||
import { QueryClientProvider } from '@tanstack/react-query'
|
||||
import { TooltipProvider } from '@cfdm/ui/components/tooltip'
|
||||
import { ThemeProvider } from '@/components/theme-provider'
|
||||
import { Toaster } from '@cfdm/ui/components/sonner'
|
||||
import { routeTree } from './routeTree.gen'
|
||||
import { queryClient } from './lib/queryClient'
|
||||
import './index.css'
|
||||
import '@cfdm/ui/globals.css'
|
||||
|
||||
const router = createRouter({
|
||||
routeTree,
|
||||
@@ -21,7 +24,12 @@ declare module '@tanstack/react-router' {
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<RouterProvider router={router} context={{ queryClient }} />
|
||||
<ThemeProvider attribute="class" defaultTheme="system" enableSystem>
|
||||
<TooltipProvider>
|
||||
<RouterProvider router={router} context={{ queryClient }} />
|
||||
<Toaster />
|
||||
</TooltipProvider>
|
||||
</ThemeProvider>
|
||||
</QueryClientProvider>
|
||||
</StrictMode>,
|
||||
)
|
||||
@@ -1,6 +1,7 @@
|
||||
import { queryOptions } from '@tanstack/react-query'
|
||||
import { api } from '@/lib/api-client'
|
||||
import { certificateSchema, dnsRecordSchema, domainSchema, groupSchema, serviceSchema } from '@/lib/schemas'
|
||||
import { subdomainSchema } from '@/lib/schemas-ext'
|
||||
import { z } from 'zod'
|
||||
|
||||
export const groupKeys = {
|
||||
@@ -89,3 +90,17 @@ export const certSummaryQueryOptions = () =>
|
||||
queryKey: certKeys.summary,
|
||||
queryFn: () => api.get<[string, number][]>('/api/v1/certificates/summary'),
|
||||
})
|
||||
|
||||
export const subdomainKeys = {
|
||||
all: ['subdomains'] as const,
|
||||
list: (domainId: number) => [...subdomainKeys.all, domainId] as const,
|
||||
}
|
||||
|
||||
export const subdomainsListQueryOptions = (domainId: number) =>
|
||||
queryOptions({
|
||||
queryKey: subdomainKeys.list(domainId),
|
||||
queryFn: async () => {
|
||||
const data = await api.get<unknown[]>(`/api/v1/domains/${domainId}/subdomains`)
|
||||
return z.array(subdomainSchema).parse(data)
|
||||
},
|
||||
})
|
||||
@@ -1,6 +1,6 @@
|
||||
import { createRootRouteWithContext, Outlet, redirect } from '@tanstack/react-router'
|
||||
import type { QueryClient } from '@tanstack/react-query'
|
||||
import { getToken } from '@/lib/utils'
|
||||
import { getToken } from '@/lib/auth'
|
||||
|
||||
export interface RouterContext {
|
||||
queryClient: QueryClient
|
||||
@@ -0,0 +1,133 @@
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { Bar, BarChart, CartesianGrid, XAxis } from 'recharts'
|
||||
import { toast } from 'sonner'
|
||||
import { certificatesQueryOptions, certKeys, certSummaryQueryOptions } from '@/queries'
|
||||
import { api } from '@/lib/api-client'
|
||||
import { PageHeader } from '@/components/page-header'
|
||||
import { StatusBadge } from '@/components/status-badge'
|
||||
import { DataTableCard } from '@/components/data-table-card'
|
||||
import { Button } from '@cfdm/ui/components/button'
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from '@cfdm/ui/components/card'
|
||||
import {
|
||||
ChartContainer,
|
||||
ChartTooltip,
|
||||
ChartTooltipContent,
|
||||
type ChartConfig,
|
||||
} from '@cfdm/ui/components/chart'
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@cfdm/ui/components/table'
|
||||
import { Spinner } from '@cfdm/ui/components/spinner'
|
||||
|
||||
const chartConfig = {
|
||||
count: {
|
||||
label: 'Количество',
|
||||
color: 'var(--chart-1)',
|
||||
},
|
||||
} satisfies ChartConfig
|
||||
|
||||
export const Route = createFileRoute('/_auth/certificates')({
|
||||
loader: ({ context: { queryClient } }) =>
|
||||
Promise.all([
|
||||
queryClient.ensureQueryData(certificatesQueryOptions()),
|
||||
queryClient.ensureQueryData(certSummaryQueryOptions()),
|
||||
]),
|
||||
component: CertificatesPage,
|
||||
})
|
||||
|
||||
function CertificatesPage() {
|
||||
const queryClient = useQueryClient()
|
||||
const { data: certs } = useQuery(certificatesQueryOptions())
|
||||
const { data: summary } = useQuery(certSummaryQueryOptions())
|
||||
|
||||
const checkMutation = useMutation({
|
||||
mutationFn: () => api.post('/api/v1/certificates/check'),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: certKeys.all })
|
||||
queryClient.invalidateQueries({ queryKey: certKeys.summary })
|
||||
toast.success('Проверка сертификатов запущена')
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof Error ? err.message : 'Не удалось запустить проверку')
|
||||
},
|
||||
})
|
||||
|
||||
const chartData = summary?.map(([status, count]) => ({ status, count })) ?? []
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4 py-4 md:gap-6 md:py-6">
|
||||
<PageHeader
|
||||
title="Сертификаты"
|
||||
description="Мониторинг SSL-сертификатов"
|
||||
actions={
|
||||
<Button
|
||||
onClick={() => checkMutation.mutate()}
|
||||
disabled={checkMutation.isPending}
|
||||
>
|
||||
{checkMutation.isPending && (
|
||||
<Spinner data-icon="inline-start" />
|
||||
)}
|
||||
{checkMutation.isPending ? 'Проверка…' : 'Запустить проверку'}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Обзор статусов</CardTitle>
|
||||
<CardDescription>Распределение сертификатов по статусам</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<ChartContainer config={chartConfig} className="aspect-auto h-64 w-full">
|
||||
<BarChart data={chartData}>
|
||||
<CartesianGrid vertical={false} />
|
||||
<XAxis
|
||||
dataKey="status"
|
||||
tickLine={false}
|
||||
axisLine={false}
|
||||
tickMargin={8}
|
||||
/>
|
||||
<ChartTooltip content={<ChartTooltipContent />} />
|
||||
<Bar dataKey="count" fill="var(--color-count)" radius={4} />
|
||||
</BarChart>
|
||||
</ChartContainer>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<DataTableCard title="Сертификаты" description="Все отслеживаемые хосты">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Хост</TableHead>
|
||||
<TableHead>Статус</TableHead>
|
||||
<TableHead>Истекает</TableHead>
|
||||
<TableHead>Последняя проверка</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{certs?.map((c) => (
|
||||
<TableRow key={c.id}>
|
||||
<TableCell className="font-medium">{c.hostname}</TableCell>
|
||||
<TableCell>
|
||||
<StatusBadge status={c.status} />
|
||||
</TableCell>
|
||||
<TableCell>{c.expires_at ?? '—'}</TableCell>
|
||||
<TableCell>{c.last_checked_at ?? '—'}</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</DataTableCard>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { useForm, Controller } from 'react-hook-form'
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { toast } from 'sonner'
|
||||
import { domainDetailQueryOptions, dnsKeys, dnsListQueryOptions, subdomainKeys } from '@/queries'
|
||||
import { api } from '@/lib/api-client'
|
||||
import { createDnsRecordSchema, type CreateDnsRecordInput } from '@/lib/schemas'
|
||||
import { PageHeader } from '@/components/page-header'
|
||||
import { StatusBadge } from '@/components/status-badge'
|
||||
import { DataTableCard } from '@/components/data-table-card'
|
||||
import { Button } from '@cfdm/ui/components/button'
|
||||
import { Input } from '@cfdm/ui/components/input'
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from '@cfdm/ui/components/card'
|
||||
import {
|
||||
Field,
|
||||
FieldGroup,
|
||||
FieldLabel,
|
||||
} from '@cfdm/ui/components/field'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@cfdm/ui/components/select'
|
||||
import { Switch } from '@cfdm/ui/components/switch'
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@cfdm/ui/components/table'
|
||||
import { Spinner } from '@cfdm/ui/components/spinner'
|
||||
|
||||
const DNS_TYPES = ['A', 'AAAA', 'CNAME', 'TXT', 'MX'] as const
|
||||
|
||||
export const Route = createFileRoute('/_auth/domains/$domainId/dns')({
|
||||
loader: ({ context: { queryClient }, params }) => {
|
||||
const id = Number(params.domainId)
|
||||
return Promise.all([
|
||||
queryClient.ensureQueryData(domainDetailQueryOptions(id)),
|
||||
queryClient.ensureQueryData(dnsListQueryOptions(id)),
|
||||
])
|
||||
},
|
||||
component: DnsPage,
|
||||
})
|
||||
|
||||
function DnsPage() {
|
||||
const { domainId } = Route.useParams()
|
||||
const id = Number(domainId)
|
||||
const queryClient = useQueryClient()
|
||||
const { data: domain } = useQuery(domainDetailQueryOptions(id))
|
||||
const { data: records } = useQuery(dnsListQueryOptions(id))
|
||||
|
||||
const form = useForm<CreateDnsRecordInput>({
|
||||
resolver: zodResolver(createDnsRecordSchema),
|
||||
defaultValues: {
|
||||
record_type: 'A',
|
||||
name: '@',
|
||||
content: '',
|
||||
ttl: 1,
|
||||
proxied: false,
|
||||
},
|
||||
})
|
||||
|
||||
const syncMutation = useMutation({
|
||||
mutationFn: () => api.post(`/api/v1/domains/${id}/sync`),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: dnsKeys.list(id) })
|
||||
queryClient.invalidateQueries({ queryKey: subdomainKeys.list(id) })
|
||||
queryClient.invalidateQueries({ queryKey: ['domains'] })
|
||||
toast.success('Синхронизация завершена')
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof Error ? err.message : 'Ошибка синхронизации')
|
||||
},
|
||||
})
|
||||
|
||||
const createMutation = useMutation({
|
||||
mutationFn: (body: CreateDnsRecordInput) =>
|
||||
api.post(`/api/v1/domains/${id}/dns`, body),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: dnsKeys.list(id) })
|
||||
form.reset({
|
||||
record_type: 'A',
|
||||
name: '@',
|
||||
content: '',
|
||||
ttl: 1,
|
||||
proxied: false,
|
||||
})
|
||||
toast.success('DNS-запись создана')
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof Error ? err.message : 'Не удалось создать запись')
|
||||
},
|
||||
})
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (recordId: number) => api.delete(`/api/v1/domains/${id}/dns/${recordId}`),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: dnsKeys.list(id) })
|
||||
toast.success('DNS-запись удалена')
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof Error ? err.message : 'Не удалось удалить запись')
|
||||
},
|
||||
})
|
||||
|
||||
const handleCreate = form.handleSubmit((values) => {
|
||||
createMutation.mutate(values)
|
||||
})
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4 py-4 md:gap-6 md:py-6">
|
||||
<PageHeader
|
||||
title={`${domain?.zone_name ?? ''} — DNS`}
|
||||
description="Управление DNS-записями зоны"
|
||||
back={{ to: '/domains', label: '← К списку доменов' }}
|
||||
actions={
|
||||
<Button
|
||||
onClick={() => syncMutation.mutate()}
|
||||
disabled={syncMutation.isPending}
|
||||
>
|
||||
{syncMutation.isPending && (
|
||||
<Spinner data-icon="inline-start" />
|
||||
)}
|
||||
{syncMutation.isPending ? 'Синхронизация…' : 'Синхронизировать с Cloudflare'}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Новая запись</CardTitle>
|
||||
<CardDescription>Добавить DNS-запись в зону</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={handleCreate}>
|
||||
<FieldGroup className="grid gap-4 md:grid-cols-6">
|
||||
<Field>
|
||||
<FieldLabel htmlFor="record_type">Тип</FieldLabel>
|
||||
<Controller
|
||||
control={form.control}
|
||||
name="record_type"
|
||||
render={({ field }) => (
|
||||
<Select value={field.value} onValueChange={field.onChange}>
|
||||
<SelectTrigger id="record_type" className="w-full">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{DNS_TYPES.map((type) => (
|
||||
<SelectItem key={type} value={type}>
|
||||
{type}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
/>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="name">Имя</FieldLabel>
|
||||
<Input id="name" {...form.register('name')} />
|
||||
</Field>
|
||||
<Field className="md:col-span-2">
|
||||
<FieldLabel htmlFor="content">Значение</FieldLabel>
|
||||
<Input id="content" {...form.register('content')} />
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="ttl">TTL</FieldLabel>
|
||||
<Input
|
||||
id="ttl"
|
||||
type="number"
|
||||
{...form.register('ttl', { valueAsNumber: true })}
|
||||
/>
|
||||
</Field>
|
||||
<Field className="flex flex-col justify-end gap-2">
|
||||
<FieldLabel htmlFor="proxied">Прокси Cloudflare</FieldLabel>
|
||||
<Controller
|
||||
control={form.control}
|
||||
name="proxied"
|
||||
render={({ field }) => (
|
||||
<Switch
|
||||
id="proxied"
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</Field>
|
||||
<Field className="flex items-end">
|
||||
<Button type="submit" disabled={createMutation.isPending}>
|
||||
{createMutation.isPending && (
|
||||
<Spinner data-icon="inline-start" />
|
||||
)}
|
||||
{createMutation.isPending ? 'Создание…' : 'Создать'}
|
||||
</Button>
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<DataTableCard title="DNS-записи" description="Записи в зоне">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Тип</TableHead>
|
||||
<TableHead>Имя</TableHead>
|
||||
<TableHead>Значение</TableHead>
|
||||
<TableHead>TTL</TableHead>
|
||||
<TableHead>Синхронизация</TableHead>
|
||||
<TableHead className="w-24" />
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{records?.map((r) => (
|
||||
<TableRow key={r.id}>
|
||||
<TableCell>{r.record_type}</TableCell>
|
||||
<TableCell>{r.name}</TableCell>
|
||||
<TableCell className="max-w-xs truncate">{r.content}</TableCell>
|
||||
<TableCell>{r.ttl}</TableCell>
|
||||
<TableCell>
|
||||
<StatusBadge status={r.sync_status} />
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Button
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
onClick={() => deleteMutation.mutate(r.id)}
|
||||
disabled={deleteMutation.isPending}
|
||||
>
|
||||
Удалить
|
||||
</Button>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</DataTableCard>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
import { createFileRoute, Link } from '@tanstack/react-router'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { toast } from 'sonner'
|
||||
import { domainDetailQueryOptions, domainKeys, subdomainKeys, subdomainsListQueryOptions } from '@/queries'
|
||||
import { api } from '@/lib/api-client'
|
||||
import { PageHeader } from '@/components/page-header'
|
||||
import { Button } from '@cfdm/ui/components/button'
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from '@cfdm/ui/components/card'
|
||||
import {
|
||||
Empty,
|
||||
EmptyDescription,
|
||||
EmptyHeader,
|
||||
EmptyTitle,
|
||||
} from '@cfdm/ui/components/empty'
|
||||
import { Spinner } from '@cfdm/ui/components/spinner'
|
||||
|
||||
export const Route = createFileRoute('/_auth/domains/$domainId/')({
|
||||
loader: ({ context: { queryClient }, params }) => {
|
||||
const id = Number(params.domainId)
|
||||
return Promise.all([
|
||||
queryClient.ensureQueryData(domainDetailQueryOptions(id)),
|
||||
queryClient.ensureQueryData(subdomainsListQueryOptions(id)),
|
||||
])
|
||||
},
|
||||
component: DomainOverviewPage,
|
||||
})
|
||||
|
||||
function DomainOverviewPage() {
|
||||
const { domainId } = Route.useParams()
|
||||
const id = Number(domainId)
|
||||
const queryClient = useQueryClient()
|
||||
const { data: domain } = useQuery(domainDetailQueryOptions(id))
|
||||
const { data: subdomains } = useQuery(subdomainsListQueryOptions(id))
|
||||
|
||||
const syncMutation = useMutation({
|
||||
mutationFn: () => api.post(`/api/v1/domains/${id}/sync`),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: subdomainKeys.list(id) })
|
||||
queryClient.invalidateQueries({ queryKey: domainKeys.all })
|
||||
toast.success('Синхронизация завершена')
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof Error ? err.message : 'Ошибка синхронизации')
|
||||
},
|
||||
})
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4 py-4 md:gap-6 md:py-6">
|
||||
<PageHeader
|
||||
title={domain?.zone_name ?? ''}
|
||||
description="Обзор домена и поддоменов"
|
||||
back={{ to: '/domains', label: '← К списку доменов' }}
|
||||
actions={
|
||||
<>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => syncMutation.mutate()}
|
||||
disabled={syncMutation.isPending}
|
||||
>
|
||||
{syncMutation.isPending && (
|
||||
<Spinner data-icon="inline-start" />
|
||||
)}
|
||||
{syncMutation.isPending ? 'Синхронизация…' : 'Синхронизировать'}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
render={
|
||||
<Link
|
||||
to="/domains/$domainId/dns"
|
||||
params={{ domainId }}
|
||||
/>
|
||||
}
|
||||
>
|
||||
DNS-записи
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Поддомены</CardTitle>
|
||||
<CardDescription>Обнаруженные поддомены в зоне</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{subdomains?.length ? (
|
||||
<ul className="flex flex-col gap-1">
|
||||
{subdomains.map((s) => (
|
||||
<li key={s.id} className="text-sm">
|
||||
{s.fqdn}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<Empty className="border border-dashed p-4">
|
||||
<EmptyHeader>
|
||||
<EmptyTitle>Поддомены не найдены</EmptyTitle>
|
||||
<EmptyDescription>
|
||||
Нажмите «Синхронизировать» — поддомены извлекаются из DNS-записей Cloudflare
|
||||
</EmptyDescription>
|
||||
</EmptyHeader>
|
||||
</Empty>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
import { createFileRoute, Link } from '@tanstack/react-router'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { useMemo, useState } from 'react'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { toast } from 'sonner'
|
||||
import { api } from '@/lib/api-client'
|
||||
import { createDomainSchema, type CreateDomainInput } from '@/lib/schemas'
|
||||
import { domainKeys, domainsListQueryOptions, groupsQueryOptions } from '@/queries'
|
||||
import { PageHeader } from '@/components/page-header'
|
||||
import { StatusBadge } from '@/components/status-badge'
|
||||
import { DataTableCard } from '@/components/data-table-card'
|
||||
import { Button } from '@cfdm/ui/components/button'
|
||||
import { Input } from '@cfdm/ui/components/input'
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from '@cfdm/ui/components/card'
|
||||
import {
|
||||
Field,
|
||||
FieldGroup,
|
||||
FieldLabel,
|
||||
} from '@cfdm/ui/components/field'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@cfdm/ui/components/select'
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@cfdm/ui/components/table'
|
||||
import { Spinner } from '@cfdm/ui/components/spinner'
|
||||
|
||||
export const Route = createFileRoute('/_auth/domains/')({
|
||||
loader: ({ context: { queryClient } }) =>
|
||||
Promise.all([
|
||||
queryClient.ensureQueryData(domainsListQueryOptions()),
|
||||
queryClient.ensureQueryData(groupsQueryOptions()),
|
||||
]),
|
||||
component: DomainsPage,
|
||||
})
|
||||
|
||||
function DomainsPage() {
|
||||
const [groupId, setGroupId] = useState('')
|
||||
const filterGroupId = groupId ? Number(groupId) : undefined
|
||||
const queryClient = useQueryClient()
|
||||
const { data: domains } = useQuery(domainsListQueryOptions(filterGroupId))
|
||||
const { data: groups } = useQuery(groupsQueryOptions())
|
||||
|
||||
const groupItems = useMemo(
|
||||
() => [
|
||||
{ label: 'Без группы', value: 'none' },
|
||||
...(groups?.map((g) => ({ label: g.name, value: String(g.id) })) ?? []),
|
||||
],
|
||||
[groups],
|
||||
)
|
||||
|
||||
const form = useForm<CreateDomainInput>({
|
||||
resolver: zodResolver(createDomainSchema),
|
||||
defaultValues: { zone_name: '', group_id: '' },
|
||||
})
|
||||
|
||||
const createMutation = useMutation({
|
||||
mutationFn: (body: { zone_name: string; group_id?: number }) =>
|
||||
api.post('/api/v1/domains', body),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: domainKeys.all })
|
||||
form.reset({ zone_name: '', group_id: groupId })
|
||||
toast.success('Домен импортирован')
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof Error ? err.message : 'Не удалось импортировать домен')
|
||||
},
|
||||
})
|
||||
|
||||
const handleCreate = form.handleSubmit((values) => {
|
||||
createMutation.mutate({
|
||||
zone_name: values.zone_name.trim(),
|
||||
group_id: groupId ? Number(groupId) : undefined,
|
||||
})
|
||||
})
|
||||
|
||||
const handleGroupChange = (value: string | null) => {
|
||||
const next = value === 'none' || !value ? '' : value
|
||||
setGroupId(next)
|
||||
form.setValue('group_id', next)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4 py-4 md:gap-6 md:py-6">
|
||||
<PageHeader
|
||||
title="Домены"
|
||||
description="Импорт и управление зонами Cloudflare"
|
||||
/>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Добавить домен</CardTitle>
|
||||
<CardDescription>Импортировать зону из Cloudflare</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={handleCreate}>
|
||||
<FieldGroup className="flex flex-row flex-wrap items-end gap-2">
|
||||
<Field className="max-w-xs flex-1">
|
||||
<FieldLabel htmlFor="zone_name">Имя зоны</FieldLabel>
|
||||
<Input
|
||||
id="zone_name"
|
||||
placeholder="example.com"
|
||||
{...form.register('zone_name')}
|
||||
aria-invalid={!!form.formState.errors.zone_name}
|
||||
/>
|
||||
</Field>
|
||||
<Field className="w-48">
|
||||
<FieldLabel htmlFor="group_id">Группа</FieldLabel>
|
||||
<Select
|
||||
items={groupItems}
|
||||
value={groupId || 'none'}
|
||||
onValueChange={handleGroupChange}
|
||||
>
|
||||
<SelectTrigger id="group_id" className="w-full">
|
||||
<SelectValue placeholder="Без группы" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{groupItems.map((item) => (
|
||||
<SelectItem key={item.value} value={item.value}>
|
||||
{item.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</Field>
|
||||
<Button type="submit" disabled={createMutation.isPending}>
|
||||
{createMutation.isPending && (
|
||||
<Spinner data-icon="inline-start" />
|
||||
)}
|
||||
{createMutation.isPending ? 'Импорт…' : 'Импортировать'}
|
||||
</Button>
|
||||
</FieldGroup>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<DataTableCard title="Список доменов" description="Импортированные зоны">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Зона</TableHead>
|
||||
<TableHead>Статус</TableHead>
|
||||
<TableHead>Последняя синхронизация</TableHead>
|
||||
<TableHead>Действия</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{domains?.map((d) => (
|
||||
<TableRow key={d.id}>
|
||||
<TableCell className="font-medium">{d.zone_name}</TableCell>
|
||||
<TableCell>
|
||||
<StatusBadge status={d.status} />
|
||||
</TableCell>
|
||||
<TableCell>{d.last_synced_at ?? '—'}</TableCell>
|
||||
<TableCell>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="link"
|
||||
className="h-auto p-0"
|
||||
render={
|
||||
<Link
|
||||
to="/domains/$domainId"
|
||||
params={{ domainId: String(d.id) }}
|
||||
/>
|
||||
}
|
||||
>
|
||||
Обзор
|
||||
</Button>
|
||||
<Button
|
||||
variant="link"
|
||||
className="h-auto p-0"
|
||||
render={
|
||||
<Link
|
||||
to="/domains/$domainId/dns"
|
||||
params={{ domainId: String(d.id) }}
|
||||
/>
|
||||
}
|
||||
>
|
||||
DNS
|
||||
</Button>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</DataTableCard>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { toast } from 'sonner'
|
||||
import { groupsQueryOptions, groupKeys, domainKeys } from '@/queries'
|
||||
import { api } from '@/lib/api-client'
|
||||
import { createGroupSchema, type CreateGroupInput } from '@/lib/schemas'
|
||||
import { PageHeader } from '@/components/page-header'
|
||||
import { ResourceList } from '@/components/resource-list'
|
||||
import { Button } from '@cfdm/ui/components/button'
|
||||
import { Input } from '@cfdm/ui/components/input'
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from '@cfdm/ui/components/card'
|
||||
import {
|
||||
Field,
|
||||
FieldGroup,
|
||||
FieldLabel,
|
||||
} from '@cfdm/ui/components/field'
|
||||
import { Spinner } from '@cfdm/ui/components/spinner'
|
||||
|
||||
export const Route = createFileRoute('/_auth/groups')({
|
||||
loader: ({ context: { queryClient } }) => queryClient.ensureQueryData(groupsQueryOptions()),
|
||||
component: GroupsPage,
|
||||
})
|
||||
|
||||
function GroupsPage() {
|
||||
const queryClient = useQueryClient()
|
||||
const { data: groups } = useQuery(groupsQueryOptions())
|
||||
|
||||
const form = useForm<CreateGroupInput>({
|
||||
resolver: zodResolver(createGroupSchema),
|
||||
defaultValues: { name: '', slug: '' },
|
||||
})
|
||||
|
||||
const createMutation = useMutation({
|
||||
mutationFn: (body: CreateGroupInput) => api.post('/api/v1/groups', body),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: groupKeys.all })
|
||||
form.reset()
|
||||
toast.success('Группа создана')
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof Error ? err.message : 'Не удалось создать группу')
|
||||
},
|
||||
})
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (id: number) => api.delete(`/api/v1/groups/${id}`),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: groupKeys.all })
|
||||
queryClient.invalidateQueries({ queryKey: domainKeys.all })
|
||||
toast.success('Группа удалена')
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof Error ? err.message : 'Не удалось удалить группу')
|
||||
},
|
||||
})
|
||||
|
||||
const handleSubmit = form.handleSubmit((values) => {
|
||||
createMutation.mutate(values)
|
||||
})
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4 py-4 md:gap-6 md:py-6">
|
||||
<PageHeader
|
||||
title="Группы"
|
||||
description="Группировка доменов для удобного управления"
|
||||
/>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Создать группу</CardTitle>
|
||||
<CardDescription>Добавить новую группу доменов</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<FieldGroup className="flex flex-row flex-wrap items-end gap-2">
|
||||
<Field className="flex-1">
|
||||
<FieldLabel htmlFor="name">Название</FieldLabel>
|
||||
<Input
|
||||
id="name"
|
||||
placeholder="Название"
|
||||
{...form.register('name')}
|
||||
aria-invalid={!!form.formState.errors.name}
|
||||
/>
|
||||
</Field>
|
||||
<Field className="flex-1">
|
||||
<FieldLabel htmlFor="slug">Slug</FieldLabel>
|
||||
<Input
|
||||
id="slug"
|
||||
placeholder="slug"
|
||||
{...form.register('slug')}
|
||||
aria-invalid={!!form.formState.errors.slug}
|
||||
/>
|
||||
</Field>
|
||||
<Button type="submit" disabled={createMutation.isPending}>
|
||||
{createMutation.isPending && (
|
||||
<Spinner data-icon="inline-start" />
|
||||
)}
|
||||
{createMutation.isPending ? 'Создание…' : 'Создать'}
|
||||
</Button>
|
||||
</FieldGroup>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<ResourceList
|
||||
items={
|
||||
groups?.map((g) => ({
|
||||
id: g.id,
|
||||
primary: g.name,
|
||||
secondary: `(${g.slug})`,
|
||||
})) ?? []
|
||||
}
|
||||
emptyTitle="Группы не найдены"
|
||||
emptyDescription="Создайте первую группу в форме выше"
|
||||
renderActions={(item) => (
|
||||
<Button
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
onClick={() => deleteMutation.mutate(item.id as number)}
|
||||
disabled={deleteMutation.isPending}
|
||||
>
|
||||
Удалить
|
||||
</Button>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import { createFileRoute, Link } from '@tanstack/react-router'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardFooter,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from '@cfdm/ui/components/card'
|
||||
import { Button } from '@cfdm/ui/components/button'
|
||||
import { certificatesQueryOptions, certSummaryQueryOptions, domainsListQueryOptions } from '@/queries'
|
||||
import { PageHeader } from '@/components/page-header'
|
||||
|
||||
export const Route = createFileRoute('/_auth/')({
|
||||
loader: ({ context: { queryClient } }) =>
|
||||
Promise.all([
|
||||
queryClient.ensureQueryData(domainsListQueryOptions()),
|
||||
queryClient.ensureQueryData(certSummaryQueryOptions()),
|
||||
]),
|
||||
component: DashboardPage,
|
||||
})
|
||||
|
||||
function DashboardPage() {
|
||||
const { data: domains } = useQuery(domainsListQueryOptions())
|
||||
const { data: summary } = useQuery(certSummaryQueryOptions())
|
||||
const { data: certs } = useQuery(certificatesQueryOptions())
|
||||
|
||||
return (
|
||||
<div className="@container/main flex flex-col gap-4 py-4 md:gap-6 md:py-6">
|
||||
<PageHeader
|
||||
title="Панель управления"
|
||||
description="Обзор доменов и сертификатов Cloudflare"
|
||||
/>
|
||||
<div className="grid gap-4 md:grid-cols-3">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardDescription>Домены</CardDescription>
|
||||
<CardTitle className="text-3xl font-semibold tabular-nums">
|
||||
{domains?.length ?? 0}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardFooter>
|
||||
<Button
|
||||
variant="link"
|
||||
className="h-auto p-0"
|
||||
render={<Link to="/domains" />}
|
||||
>
|
||||
Управление доменами
|
||||
</Button>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardDescription>Сертификаты</CardDescription>
|
||||
<CardTitle className="text-3xl font-semibold tabular-nums">
|
||||
{certs?.length ?? 0}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardFooter>
|
||||
<Button
|
||||
variant="link"
|
||||
className="h-auto p-0"
|
||||
render={<Link to="/certificates" />}
|
||||
>
|
||||
Мониторинг сертификатов
|
||||
</Button>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardDescription>Статусы сертификатов</CardDescription>
|
||||
<CardTitle className="text-base font-medium">Сводка</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<ul className="flex flex-col gap-1 text-sm">
|
||||
{summary?.map(([status, count]) => (
|
||||
<li key={status} className="flex justify-between">
|
||||
<span className="text-muted-foreground">{status}</span>
|
||||
<span className="font-medium tabular-nums">{count}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { toast } from 'sonner'
|
||||
import { servicesQueryOptions, serviceKeys } from '@/queries'
|
||||
import { api } from '@/lib/api-client'
|
||||
import { createServiceSchema, type CreateServiceInput } from '@/lib/schemas'
|
||||
import { PageHeader } from '@/components/page-header'
|
||||
import { ResourceList } from '@/components/resource-list'
|
||||
import { Button } from '@cfdm/ui/components/button'
|
||||
import { Input } from '@cfdm/ui/components/input'
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from '@cfdm/ui/components/card'
|
||||
import {
|
||||
Field,
|
||||
FieldGroup,
|
||||
FieldLabel,
|
||||
} from '@cfdm/ui/components/field'
|
||||
import { Spinner } from '@cfdm/ui/components/spinner'
|
||||
|
||||
export const Route = createFileRoute('/_auth/services')({
|
||||
loader: ({ context: { queryClient } }) => queryClient.ensureQueryData(servicesQueryOptions()),
|
||||
component: ServicesPage,
|
||||
})
|
||||
|
||||
function ServicesPage() {
|
||||
const queryClient = useQueryClient()
|
||||
const { data: services } = useQuery(servicesQueryOptions())
|
||||
|
||||
const form = useForm<CreateServiceInput>({
|
||||
resolver: zodResolver(createServiceSchema),
|
||||
defaultValues: { name: '', slug: '' },
|
||||
})
|
||||
|
||||
const createMutation = useMutation({
|
||||
mutationFn: (body: CreateServiceInput) => api.post('/api/v1/services', body),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: serviceKeys.all })
|
||||
form.reset()
|
||||
toast.success('Сервис создан')
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof Error ? err.message : 'Не удалось создать сервис')
|
||||
},
|
||||
})
|
||||
|
||||
const handleSubmit = form.handleSubmit((values) => {
|
||||
createMutation.mutate(values)
|
||||
})
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4 py-4 md:gap-6 md:py-6">
|
||||
<PageHeader
|
||||
title="Сервисы"
|
||||
description="Справочник сервисов для привязки к доменам"
|
||||
/>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Создать сервис</CardTitle>
|
||||
<CardDescription>Добавить новый сервис в справочник</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<FieldGroup className="flex flex-row flex-wrap items-end gap-2">
|
||||
<Field className="flex-1">
|
||||
<FieldLabel htmlFor="name">Название</FieldLabel>
|
||||
<Input
|
||||
id="name"
|
||||
placeholder="Название"
|
||||
{...form.register('name')}
|
||||
aria-invalid={!!form.formState.errors.name}
|
||||
/>
|
||||
</Field>
|
||||
<Field className="flex-1">
|
||||
<FieldLabel htmlFor="slug">Slug</FieldLabel>
|
||||
<Input
|
||||
id="slug"
|
||||
placeholder="slug"
|
||||
{...form.register('slug')}
|
||||
aria-invalid={!!form.formState.errors.slug}
|
||||
/>
|
||||
</Field>
|
||||
<Button type="submit" disabled={createMutation.isPending}>
|
||||
{createMutation.isPending && (
|
||||
<Spinner data-icon="inline-start" />
|
||||
)}
|
||||
{createMutation.isPending ? 'Создание…' : 'Создать'}
|
||||
</Button>
|
||||
</FieldGroup>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<ResourceList
|
||||
items={
|
||||
services?.map((s) => ({
|
||||
id: s.id,
|
||||
primary: s.name,
|
||||
secondary: `(${s.slug})`,
|
||||
})) ?? []
|
||||
}
|
||||
emptyTitle="Сервисы не найдены"
|
||||
emptyDescription="Создайте первый сервис в форме выше"
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
import { CloudIcon } from 'lucide-react'
|
||||
import { LoginForm } from '@/components/login-form'
|
||||
|
||||
export const Route = createFileRoute('/login')({
|
||||
component: LoginPage,
|
||||
})
|
||||
|
||||
function LoginPage() {
|
||||
return (
|
||||
<div className="flex min-h-svh flex-col items-center justify-center gap-6 bg-muted p-6 md:p-10">
|
||||
<div className="flex w-full max-w-sm flex-col gap-6">
|
||||
<div className="flex items-center gap-2 self-center font-medium">
|
||||
<div className="flex size-6 items-center justify-center rounded-md bg-primary text-primary-foreground">
|
||||
<CloudIcon className="size-4" />
|
||||
</div>
|
||||
CF Domain Manager
|
||||
</div>
|
||||
<LoginForm />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -16,6 +16,9 @@ export default defineConfig({
|
||||
},
|
||||
},
|
||||
server: {
|
||||
fs: {
|
||||
allow: [path.resolve(__dirname, '../..')],
|
||||
},
|
||||
proxy: {
|
||||
'/api': 'http://localhost:8080',
|
||||
'/health': 'http://localhost:8080',
|
||||
Generated
+3302
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,6 @@
|
||||
use crate::cloudflare::retry::{parse_retry_after, with_retry};
|
||||
use crate::cloudflare::types::{
|
||||
CfDnsRecord, CfListResult, CfResponse, CfZone, CreateDnsRecordPayload,
|
||||
CfDnsRecord, CfResponse, CfZone, CreateDnsRecordPayload,
|
||||
};
|
||||
use crate::error::{AppError, AppResult};
|
||||
use reqwest::Client;
|
||||
@@ -74,22 +74,38 @@ impl CloudflareClient {
|
||||
let http = http.clone();
|
||||
let token = token.clone();
|
||||
async move {
|
||||
let response = http
|
||||
.get(format!("{BASE_URL}/zones"))
|
||||
.bearer_auth(token)
|
||||
.query(&[("per_page", "50")])
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| AppError::Cloudflare(e.to_string()))?;
|
||||
let client = Self {
|
||||
http: http.clone(),
|
||||
token: token.clone(),
|
||||
};
|
||||
let mut all = Vec::new();
|
||||
let mut page = 1u32;
|
||||
loop {
|
||||
let response = http
|
||||
.get(format!("{BASE_URL}/zones"))
|
||||
.bearer_auth(&token)
|
||||
.query(&[("per_page", "50"), ("page", &page.to_string())])
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| AppError::Cloudflare(e.to_string()))?;
|
||||
|
||||
if response.status().is_server_error() || response.status().as_u16() == 429 {
|
||||
return Err(AppError::Cloudflare(response.status().to_string()));
|
||||
if response.status().is_server_error() || response.status().as_u16() == 429 {
|
||||
return Err(AppError::Cloudflare(response.status().to_string()));
|
||||
}
|
||||
|
||||
let batch: Vec<CfZone> =
|
||||
client.handle_response(response, "list_zones").await?;
|
||||
if batch.is_empty() {
|
||||
break;
|
||||
}
|
||||
let batch_len = batch.len();
|
||||
all.extend(batch);
|
||||
if batch_len < 50 {
|
||||
break;
|
||||
}
|
||||
page += 1;
|
||||
}
|
||||
|
||||
let list: CfListResult<CfZone> = response.json().await.map_err(|e| {
|
||||
AppError::Cloudflare(e.to_string())
|
||||
})?;
|
||||
Ok(list.result)
|
||||
Ok(all)
|
||||
}
|
||||
})
|
||||
.await
|
||||
@@ -129,13 +145,17 @@ impl CloudflareClient {
|
||||
return Err(AppError::Cloudflare(response.status().to_string()));
|
||||
}
|
||||
|
||||
let list: CfListResult<CfDnsRecord> = response.json().await.map_err(|e| {
|
||||
AppError::Cloudflare(e.to_string())
|
||||
})?;
|
||||
if list.result.is_empty() {
|
||||
let client = Self {
|
||||
http: http.clone(),
|
||||
token: token.clone(),
|
||||
};
|
||||
let batch: Vec<CfDnsRecord> = client
|
||||
.handle_response(response, "list_dns_records")
|
||||
.await?;
|
||||
if batch.is_empty() {
|
||||
break;
|
||||
}
|
||||
all.extend(list.result);
|
||||
all.extend(batch);
|
||||
page += 1;
|
||||
if page > 50 {
|
||||
break;
|
||||
|
||||
@@ -37,11 +37,6 @@ pub struct CfResponse<T> {
|
||||
pub errors: Option<Vec<CfApiError>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct CfListResult<T> {
|
||||
pub result: Vec<T>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct CfApiError {
|
||||
pub code: i64,
|
||||
|
||||
@@ -20,7 +20,9 @@ impl Config {
|
||||
database_url: std::env::var("DATABASE_URL")
|
||||
.unwrap_or_else(|_| "sqlite:data/app.db".into()),
|
||||
cloudflare_api_token: std::env::var("CLOUDFLARE_API_TOKEN")
|
||||
.unwrap_or_default(),
|
||||
.unwrap_or_default()
|
||||
.trim()
|
||||
.to_string(),
|
||||
jwt_secret: std::env::var("JWT_SECRET")
|
||||
.unwrap_or_else(|_| "dev-secret-change-me".into()),
|
||||
jwt_ttl_hours: std::env::var("JWT_TTL_HOURS")
|
||||
@@ -30,17 +32,16 @@ impl Config {
|
||||
admin_username: std::env::var("ADMIN_USERNAME")
|
||||
.unwrap_or_else(|_| "admin".into()),
|
||||
admin_password_hash: std::env::var("ADMIN_PASSWORD_HASH")
|
||||
.unwrap_or_else(|_| {
|
||||
// default password: admin (for dev only)
|
||||
"$argon2id$v=19$m=19456,t=2,p=1$devplaceholder$dev".into()
|
||||
}),
|
||||
.ok()
|
||||
.filter(|s| !s.trim().is_empty())
|
||||
.unwrap_or_else(|| "devplaceholder".into()),
|
||||
server_port: std::env::var("SERVER_PORT")
|
||||
.ok()
|
||||
.and_then(|v| v.parse().ok())
|
||||
.unwrap_or(8080),
|
||||
static_dir: std::env::var("STATIC_DIR").ok().map(PathBuf::from),
|
||||
cert_check_cron: std::env::var("CERT_CHECK_CRON")
|
||||
.unwrap_or_else(|_| "0 */6 * * *".into()),
|
||||
.unwrap_or_else(|_| "0 0 */6 * * *".into()),
|
||||
rust_log: std::env::var("RUST_LOG").unwrap_or_else(|_| "info".into()),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
pub mod entities;
|
||||
pub mod subdomain;
|
||||
pub mod validators;
|
||||
|
||||
pub use entities::*;
|
||||
pub use subdomain::*;
|
||||
pub use validators::*;
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
/// Преобразует имя DNS-записи Cloudflare в метку поддомена в зоне.
|
||||
pub fn dns_name_to_subdomain_label(record_name: &str, zone_name: &str) -> Option<String> {
|
||||
let record_name = record_name.trim().trim_end_matches('.');
|
||||
let zone_name = zone_name.trim().trim_end_matches('.');
|
||||
if record_name.is_empty() || zone_name.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
if record_name == "*" {
|
||||
return Some("*".to_string());
|
||||
}
|
||||
|
||||
let wildcard_fqdn = format!("*.{zone_name}");
|
||||
if record_name.eq_ignore_ascii_case(&wildcard_fqdn) {
|
||||
return Some("*".to_string());
|
||||
}
|
||||
|
||||
if record_name.eq_ignore_ascii_case(zone_name) {
|
||||
return Some("@".to_string());
|
||||
}
|
||||
|
||||
let zone_suffix = format!(".{zone_name}");
|
||||
if record_name
|
||||
.to_ascii_lowercase()
|
||||
.ends_with(&zone_suffix.to_ascii_lowercase())
|
||||
{
|
||||
let prefix_len = record_name.len() - zone_suffix.len();
|
||||
let prefix = &record_name[..prefix_len];
|
||||
if prefix.is_empty() {
|
||||
return Some("@".to_string());
|
||||
}
|
||||
return Some(prefix.to_string());
|
||||
}
|
||||
|
||||
if !record_name.contains('.') {
|
||||
return Some(record_name.to_string());
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
pub fn subdomain_label_to_fqdn(label: &str, zone_name: &str) -> String {
|
||||
if label == "@" {
|
||||
zone_name.to_string()
|
||||
} else {
|
||||
format!("{label}.{zone_name}")
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn apex_record_maps_to_at() {
|
||||
assert_eq!(
|
||||
dns_name_to_subdomain_label("ivx.su", "ivx.su").as_deref(),
|
||||
Some("@")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn www_maps_to_label() {
|
||||
assert_eq!(
|
||||
dns_name_to_subdomain_label("www.ivx.su", "ivx.su").as_deref(),
|
||||
Some("www")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_subdomain() {
|
||||
assert_eq!(
|
||||
dns_name_to_subdomain_label("api.staging.ivx.su", "ivx.su").as_deref(),
|
||||
Some("api.staging")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relative_name() {
|
||||
assert_eq!(
|
||||
dns_name_to_subdomain_label("mail", "ivx.su").as_deref(),
|
||||
Some("mail")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wildcard() {
|
||||
assert_eq!(
|
||||
dns_name_to_subdomain_label("*.ivx.su", "ivx.su").as_deref(),
|
||||
Some("*")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fqdn_from_label() {
|
||||
assert_eq!(subdomain_label_to_fqdn("@", "ivx.su"), "ivx.su");
|
||||
assert_eq!(subdomain_label_to_fqdn("www", "ivx.su"), "www.ivx.su");
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,63 @@
|
||||
use crate::error::{AppError, AppResult};
|
||||
use regex::Regex;
|
||||
use std::sync::LazyLock;
|
||||
|
||||
static NAME_RE: LazyLock<Regex> =
|
||||
LazyLock::new(|| Regex::new(r"^(@|\*|[a-zA-Z0-9_]([a-zA-Z0-9_-]*[a-zA-Z0-9_])?(\.[a-zA-Z0-9_]([a-zA-Z0-9_-]*[a-zA-Z0-9_])?)*)$").unwrap());
|
||||
static IPV4_RE: LazyLock<Regex> =
|
||||
LazyLock::new(|| Regex::new(r"^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$").unwrap());
|
||||
static IPV6_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^([0-9a-fA-F]{0,4}:){2,7}[0-9a-fA-F]{0,4}$").unwrap());
|
||||
|
||||
const ALLOWED_TYPES: &[&str] = &["A", "AAAA", "CNAME", "TXT", "MX", "NS", "SRV", "CAA"];
|
||||
|
||||
pub fn validate_dns_record(
|
||||
record_type: &str,
|
||||
name: &str,
|
||||
content: &str,
|
||||
ttl: i64,
|
||||
proxied: bool,
|
||||
) -> AppResult<()> {
|
||||
let rt = record_type.to_uppercase();
|
||||
if !ALLOWED_TYPES.contains(&rt.as_str()) {
|
||||
return Err(AppError::Validation(format!("unsupported record type: {record_type}")));
|
||||
}
|
||||
if !NAME_RE.is_match(name) {
|
||||
return Err(AppError::Validation(format!("invalid record name: {name}")));
|
||||
}
|
||||
if ttl != 1 && !(60..=86400).contains(&ttl) {
|
||||
return Err(AppError::Validation("ttl must be 1 (auto) or 60-86400".into()));
|
||||
}
|
||||
if proxied && !matches!(rt.as_str(), "A" | "AAAA" | "CNAME") {
|
||||
return Err(AppError::Validation("proxied only allowed for A, AAAA, CNAME".into()));
|
||||
}
|
||||
match rt.as_str() {
|
||||
"A" if !IPV4_RE.is_match(content) => {
|
||||
return Err(AppError::Validation("A record requires valid IPv4".into()));
|
||||
}
|
||||
"AAAA" if !IPV6_RE.is_match(content) => {
|
||||
return Err(AppError::Validation("AAAA record requires valid IPv6".into()));
|
||||
}
|
||||
"CNAME" | "NS" if content.is_empty() || content.contains(' ') => {
|
||||
return Err(AppError::Validation("CNAME/NS requires valid hostname".into()));
|
||||
}
|
||||
"TXT" if content.is_empty() || content.len() > 2048 => {
|
||||
return Err(AppError::Validation("TXT content length 1-2048".into()));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn cert_status_from_expiry(days_left: i64) -> &'static str {
|
||||
if days_left < 0 {
|
||||
crate::domain::CERT_EXPIRED
|
||||
} else if days_left <= 30 {
|
||||
crate::domain::CERT_WARNING
|
||||
} else {
|
||||
crate::domain::CERT_OK
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
+23
-2
@@ -17,18 +17,29 @@ use tracing_subscriber::EnvFilter;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
dotenvy::dotenv().ok();
|
||||
load_dotenv();
|
||||
let config = Config::from_env().map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?;
|
||||
|
||||
tracing_subscriber::fmt()
|
||||
.with_env_filter(EnvFilter::new(&config.rust_log))
|
||||
.init();
|
||||
|
||||
if config.cloudflare_api_token.is_empty() {
|
||||
tracing::warn!("CLOUDFLARE_API_TOKEN не задан — импорт доменов из Cloudflare недоступен");
|
||||
} else {
|
||||
tracing::info!(
|
||||
token_len = config.cloudflare_api_token.len(),
|
||||
"CLOUDFLARE_API_TOKEN загружен"
|
||||
);
|
||||
}
|
||||
|
||||
let pool = create_pool(&config.database_url).await?;
|
||||
run_migrations(&pool).await?;
|
||||
|
||||
let state = AppState::new(pool.clone(), config.clone());
|
||||
start_cert_scheduler(pool, config.cert_check_cron.clone()).await?;
|
||||
start_cert_scheduler(pool, config.cert_check_cron.clone()).await.unwrap_or_else(|e| {
|
||||
tracing::warn!(error = %e, "certificate scheduler disabled");
|
||||
});
|
||||
|
||||
let app = create_router(state);
|
||||
let addr = SocketAddr::from(([0, 0, 0, 0], config.server_port));
|
||||
@@ -38,6 +49,16 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn load_dotenv() {
|
||||
let manifest_env = concat!(env!("CARGO_MANIFEST_DIR"), "/../.env");
|
||||
for path in [manifest_env, ".env", "../.env"] {
|
||||
if dotenvy::from_filename(path).is_ok() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
dotenvy::dotenv().ok();
|
||||
}
|
||||
|
||||
async fn start_cert_scheduler(
|
||||
pool: sqlx::SqlitePool,
|
||||
cron: String,
|
||||
|
||||
@@ -26,6 +26,6 @@ pub async fn create_pool(database_url: &str) -> Result<SqlitePool, sqlx::Error>
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn run_migrations(pool: &SqlitePool) -> Result<(), sqlx::Error> {
|
||||
pub async fn run_migrations(pool: &SqlitePool) -> Result<(), sqlx::migrate::MigrateError> {
|
||||
sqlx::migrate!("./migrations").run(pool).await
|
||||
}
|
||||
|
||||
@@ -19,6 +19,27 @@ pub async fn get(pool: &SqlitePool, id: i64) -> AppResult<Subdomain> {
|
||||
.ok_or_else(|| AppError::NotFound(format!("subdomain {id}")))
|
||||
}
|
||||
|
||||
pub async fn upsert(
|
||||
pool: &SqlitePool,
|
||||
domain_id: i64,
|
||||
name: &str,
|
||||
fqdn: &str,
|
||||
) -> AppResult<()> {
|
||||
sqlx::query(
|
||||
r#"INSERT INTO subdomains (domain_id, name, fqdn)
|
||||
VALUES (?, ?, ?)
|
||||
ON CONFLICT(domain_id, name) DO UPDATE SET
|
||||
fqdn = excluded.fqdn,
|
||||
updated_at = datetime('now')"#,
|
||||
)
|
||||
.bind(domain_id)
|
||||
.bind(name)
|
||||
.bind(fqdn)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn create(
|
||||
pool: &SqlitePool,
|
||||
domain_id: i64,
|
||||
|
||||
@@ -24,7 +24,7 @@ pub struct LoginResponse {
|
||||
}
|
||||
|
||||
pub fn verify_password(config: &Config, password: &str) -> AppResult<()> {
|
||||
if config.admin_password_hash.contains("devplaceholder") {
|
||||
if config.admin_password_hash == "devplaceholder" {
|
||||
if password == "admin" {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::cloudflare::types::CreateDnsRecordPayload;
|
||||
use crate::cloudflare::CloudflareClient;
|
||||
use crate::domain::{DnsRecord, Domain, SYNC_CONFLICT, SYNC_ERROR, SYNC_PENDING_DELETE, SYNC_PENDING_PUSH, SYNC_SYNCED};
|
||||
use crate::domain::{DnsRecord, Domain, SYNC_CONFLICT, SYNC_ERROR, SYNC_PENDING_PUSH, SYNC_SYNCED};
|
||||
use crate::domain::validate_dns_record;
|
||||
use crate::error::{AppError, AppResult};
|
||||
use crate::repositories::{dns_records, domains};
|
||||
|
||||
@@ -18,11 +18,24 @@ pub async fn create_domain(
|
||||
group_id: Option<i64>,
|
||||
zone_name: &str,
|
||||
) -> AppResult<Domain> {
|
||||
let zone_name = zone_name.trim();
|
||||
let zones = cf.list_zones().await?;
|
||||
if zones.is_empty() {
|
||||
return Err(AppError::NotFound(
|
||||
"нет доступных зон в Cloudflare — проверьте CLOUDFLARE_API_TOKEN и права Zone:Read"
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
let zone = zones
|
||||
.into_iter()
|
||||
.find(|z| z.name == zone_name)
|
||||
.ok_or_else(|| AppError::NotFound(format!("cloudflare zone {zone_name}")))?;
|
||||
.iter()
|
||||
.find(|z| z.name.eq_ignore_ascii_case(zone_name))
|
||||
.ok_or_else(|| {
|
||||
let names: Vec<&str> = zones.iter().map(|z| z.name.as_str()).collect();
|
||||
AppError::NotFound(format!(
|
||||
"зона «{zone_name}» не найдена в Cloudflare. Доступные: {}",
|
||||
names.join(", ")
|
||||
))
|
||||
})?;
|
||||
domains::create(pool, group_id, &zone.name, &zone.id).await
|
||||
}
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user