Mbu react
React/TypeScript frontend development standards for MBU ID ui-backoffice. Use for any frontend work — component structure, TanStack Router, Zustand/TanStack Query state, React Hook Form + Zod, Axios API client, Tailwind styling, S3 uploads. Enforces type safety, project-specific patterns, and the exact directory structure used in ui-backoffice.From its SKILL.md
npx -y skills add mbu-id/claude-plugins --skill mbu-reactAssembled from the repository path, not quoted from the project. Check it against their README if it does not work.
2 things to look at
- no licenseNo license file was found in the repository. Code published without one is not open source by default, so using it at work is a question for whoever answers licensing questions where you are.
- 0 stars0 stars. Stars are a popularity signal and not a quality one, but at this level it is likely that nobody has read this closely except its author, and you would be relying on your own review.
SKILL.md
20.0 KB, as published. Nobody here has run it
MBU React/TypeScript Standards (ui-backoffice)
React/TypeScript coding standards for frontend/ui-backoffice. This is the single source of truth — follow these patterns over generic React guides.
1. Tech Stack
- Framework: React 19 + TypeScript 6
- Build: Vite 8
- Router: TanStack Router v1 (file-based,
src/routes/) - Data Fetching: TanStack Query v5
- State: Zustand v5 (with persist middleware)
- Forms: react-hook-form + zod v4 + @hookform/resolvers
- HTTP Client: Axios (with interceptors)
- Styling: Tailwind CSS v4
- UI Library: shadcn/ui (via
@mbu/ui-corebarrel fromsrc/ui-core-index.ts) - Tables: TanStack Table v8
- Icons: lucide-react
- Notifications: sonner
2. Project Structure (Modular Feature-Driven)
src/
├── lib/ # Global service instances (api-client, query-client, utils)
├── store/ # Global Zustand stores (auth.store, app.store)
├── components/ # App-level components
│ ├── layout/ # app-shell, app-sidebar, app-header
│ ├── ui/ # shadcn/ui primitives (kebab-case: button.tsx, data-table.tsx, dialog.tsx, etc.)
│ ├── Can.tsx # Permission guard component
│ ├── page-container.tsx # Page layout wrapper
│ └── Sidebar.tsx
├── core/ # App core — config, registry
│ ├── nav.config.ts # Navigation tree definition (sidebar menu hierarchy)
│ └── registry/
│ ├── types.ts # ModuleRegistration type
│ └── index.ts # ComponentRegistry singleton
├── hooks/ # Shared hooks (useNavMeta, useDebounce)
├── modules/ # Feature modules (domain-driven)
│ ├── core/ # Master data module
│ │ ├── manifest.ts # Page registry — lazy-loaded page imports
│ │ ├── pages/ # Page components (branches.tsx, companies.tsx, ...)
│ │ ├── components/ # Module-specific form sheets, overlays
│ │ │ └── selects/ # Entity search/select dropdowns
│ │ └── services/ # API service layer
│ │ ├── service.core.branch.ts
│ │ ├── service.core.company.ts
│ │ └── service.core.meta.ts
│ └── manbu/
│ ├── intake_plans/
│ │ ├── index.ts
│ │ ├── pages/ # intake-plans.tsx, intake-plan-detail.tsx
│ │ ├── components/ # -intake-plan-form-sheet.tsx
│ │ └── services/ # service.manbu.intake-plan.ts
│ └── purchasing/
│ ├── pages/
│ ├── components/
│ └── services/
├── routes/ # TanStack Router filesystem route tree
│ ├── __root.tsx # Root layout — QueryClientProvider + Toaster
│ ├── _authenticated.tsx # Auth guard + AppShell
│ └── login.tsx
├── routeTree.gen.ts # Auto-generated by TanStack Router
├── ui-core-index.ts # Re-exports for @mbu/ui-core package
└── main.tsx # App entry — imports module manifests
Module Directory Convention
Each feature gets: modules/{domain}/{feature}/{pages,components,services}/. The domain groups related features together (core for master data, manbu for MANBU-specific ops).
3. Naming Conventions
Files & Directories
- kebab-case — Components, pages, services:
data-table.tsx,intake-plans.tsx,service.core.branch.ts - camelCase — Hooks, utilities, stores:
useAuth.ts,useDebounce,auth.store.ts - PascalCase — React component functions:
export function IntakePlansPage() - Leading dash — Form-sheet components (not stand-alone pages):
-branch-form-sheet.tsx,-intake-plan-form-sheet.tsx
Service Files
Pattern: service.{domain}.{entity}.ts — dot-separated hierarchy:
service.core.branch.ts → service-core / branch
service.manbu.intake-plan.ts → service-manbu-ops / intake-plan
service.manbu.purchasing.ts → multiple entities in purchasing domain
Components
// ✅ Correct — named export
export function Button() { ... }
export const Button = () => { ... }
// ❌ Wrong — default export
export default function Button() { ... }
Hooks
// ✅ Correct — camelCase, starts with "use"
export const useDebounce = (value: string, delay: number) => { ... }
export const useNavMeta = () => { ... }
4. Routing — TanStack Router
- Filesystem-based routing via
@tanstack/react-router src/routes/directory — route files map to URL pathsrouteTree.gen.tsauto-generated by Vite plugin (must come beforereact()in vite.config.ts)- Auth guard in
_authenticated.tsx:beforeLoad: redirects unauthenticated →/login?redirect=, hydrates permissions/metadata, applies dynamic brand color (--brand-colorCSS custom property fromuser.company.brand_color)fetchSession()before allowing child routes
// src/routes/__root.tsx — providers + toaster
createRootRoute({
component: () => (
<QueryClientProvider client={queryClient}>
<Outlet />
<Toaster position="bottom-right" />
</QueryClientProvider>
),
});
// src/routes/_authenticated.tsx — auth guard + app shell
createFileRoute("/_authenticated")({
beforeLoad: async () => {
const state = useAuthStore.getState();
if (!state.isAuthenticated) throw redirect({ to: "/login" });
if (!state.isSessionLoaded) await state.fetchSession();
await useAppStore.getState().fetchMeta();
},
component: () => (
<AppShell sidebar={<Sidebar />}><Outlet /></AppShell>
),
});
Navigation Config (core/nav.config.ts)
export const navConfig: NavConfig = {
items: [
{ route: "/", title: "Overview", icon: LayoutDashboard },
{
route: "/master",
title: "Master Data",
children: [
{
route: "/master/organization",
title: "Organization",
children: [
{ route: "/master/organization/branches", title: "Branches", permission: "service-core.branch.read" },
],
},
],
},
],
utility: [{ id: "help", title: "Help", icon: HelpCircle }],
};
5. State Management — Strict Separation
Zustand (Global App State)
Auth tokens, user profile, app meta, session — singletons.
export const useAuthStore = create<AuthState>()(
persist(
(set, get) => ({
user: null, accessToken: null, isAuthenticated: false,
hasPermission: (slug: string) => {
const user = get().user;
if (!user?.permissions) return false;
if (user.permissions.includes(slug)) return true;
// Wildcard: "service-core.*.read" → /^service-core\..*\.read$/
return user.permissions.some(p => {
if (!p.includes('*')) return false;
return new RegExp('^' + p.split('.').map(s => s === '*' ? '.*' : s).join('\\.') + '$').test(slug);
});
},
}),
{
name: 'manbu-auth-storage',
partialize: (state) => ({
accessToken: state.accessToken,
refreshToken: state.refreshToken,
user: state.user ? { id: state.user.id, email: state.user.email, full_name: state.user.full_name } : null,
isAuthenticated: state.isAuthenticated,
}),
}
)
);
TanStack Query (Server Cache)
All remote data fetching and mutations. Never store server data in Zustand.
useState (Local UI State)
Dialog open states, pagination, sorting — component-scoped only.
6. API Client — Axios
// lib/api-client.ts
export const apiClient = axios.create({
baseURL: import.meta.env.VITE_API_URL || '/api',
timeout: 30000,
});
- Request interceptor: Attach
Bearertoken fromuseAuthStore.getState().accessToken - Response interceptor: On 401 → attempt silent token refresh → retry original request. On refresh fail →
clearSession()+ redirect/login
TanStack Query Config
export const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 1000 * 60 * 1, // 1 min before background refetch
refetchOnWindowFocus: false, // ERP: no spurious refetch on tab switch
retry: 1,
},
},
});
7. Service Layer Pattern
Every domain entity gets a service file in modules/{domain}/{feature}/services/service.{domain}.{entity}.ts.
Follows clean CRUD pattern with typed request/response:
import { apiClient } from "@/lib/api-client";
import type { ApiResponse, PaginationMeta, QueryParams } from "@/modules/core/services/service.core.types";
export interface Entity { id: string; name: string; /* ... */ }
export interface CreateEntityRequest { name: string; /* ... */ }
export interface EntityListParams extends QueryParams { status?: string; }
const BASE = "/domain/entities";
export const entityService = {
async list(params?: EntityListParams): Promise<{ items: Entity[]; meta: PaginationMeta }> {
const { data } = await apiClient.get<ApiResponse<Entity[]>>(BASE, { params });
if (!data.success) throw new Error(data.message || "Failed to fetch");
return { items: data.data ?? [], meta: data.meta as PaginationMeta };
},
async show(id: string): Promise<Entity> { /* ... */ },
async create(payload: CreateEntityRequest): Promise<Entity> { /* ... */ },
async update(id: string, payload: UpdateEntityRequest): Promise<Entity> { /* ... */ },
async delete(id: string): Promise<void> { /* ... */ },
};
API response envelope:
interface ApiResponse<T> {
success: boolean;
data: T | null;
message: string;
meta?: { total: number; total_pages: number; page: number; per_page: number };
}
Server Error → Form Field Mapping
onError: (error: any) => {
if (isAxiosError(error) && error.response?.data?.errors) {
Object.keys(error.response.data.errors).forEach((key) => {
form.setError(key as any, { type: "server", message: error.response.data.errors[key] });
});
} else {
toast.error(error.message || "An unexpected error occurred.");
}
}
8. Component Patterns
Page Pattern (DataTable Page)
Use PageContainer wrapper + DataTable + server-side pagination/sorting/search:
import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import type { ColumnDef, PaginationState, SortingState } from "@tanstack/react-table";
import { DataTable, Button, PageContainer, Dialog, toast } from "@mbu/ui-core";
import { Plus } from "lucide-react";
import { Can } from "@/components/Can";
import { entityService, type Entity } from "./services/service.{domain}.{entity}";
export function EntitiesPage() {
const queryClient = useQueryClient();
const [pagination, setPagination] = useState<PaginationState>({ pageIndex: 0, pageSize: 25 });
const [sorting, setSorting] = useState<SortingState>([]);
const [searchTerm, setSearchTerm] = useState("");
const { data, isLoading } = useQuery({
queryKey: ["entities", pagination.pageIndex, pagination.pageSize, sorting, searchTerm],
queryFn: () => entityService.list({ page: pagination.pageIndex + 1, per_page: pagination.pageSize, search: searchTerm }),
});
return (
<PageContainer
title="Entities"
description="Manage entities."
actions={
<Can perform="service-domain.entity.manage">
<Button variant="brand" onClick={() => {}}><Plus /> Add</Button>
</Can>
}
>
<DataTable
columns={getColumns(/* onEdit, onDelete, onView */)}
data={data?.items ?? []}
isLoading={isLoading}
pageCount={data?.meta?.total_pages ?? -1}
totalCount={data?.meta?.total ?? 0}
pagination={pagination}
onPaginationChange={setPagination}
sorting={sorting}
onSortingChange={setSorting}
searchValue={searchTerm}
onSearchChange={setSearchTerm}
/>
</PageContainer>
);
}
Form Sheet Pattern (Create/Edit in Slide-Out Panel)
Forms live in a Sheet (slide-out panel from shadcn/ui), not a Dialog or separate page:
// -entity-form-sheet.tsx
import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetDescription } from "@mbu/ui-core";
interface Props {
open: boolean;
onOpenChange: (open: boolean) => void;
entityId?: string;
}
export function EntityFormSheet({ open, onOpenChange, entityId }: Props) {
const isEdit = !!entityId;
const mutation = useMutation({
mutationFn: isEdit ? (data) => entityService.update(entityId, data) : entityService.create,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["entities"] });
toast.success(isEdit ? "Updated" : "Created");
onOpenChange(false);
},
onError: (err) => toast.error(err.message),
});
return (
<Sheet open={open} onOpenChange={onOpenChange}>
<SheetContent>
<SheetHeader><SheetTitle>{isEdit ? "Edit" : "Create"} Entity</SheetTitle></SheetHeader>
<EntityForm onSubmit={mutation.mutate} />
</SheetContent>
</Sheet>
);
}
Delete Confirmation Dialog
Use a Dialog inline in the page, not a separate component:
<Dialog open={!!deletingId} onOpenChange={(o) => !o && setDeletingId(null)}>
<DialogContent>
<DialogHeader><DialogTitle>Delete Entity</DialogTitle></DialogHeader>
<DialogDescription>This action cannot be undone.</DialogDescription>
<DialogFooter>
<Button variant="outline" onClick={() => setDeletingId(null)}>Cancel</Button>
<Button variant="destructive" onClick={() => deleteMutation.mutate(deletingId)}>Delete</Button>
</DialogFooter>
</DialogContent>
</Dialog>
Loading, Error, Empty States
Always handle all three before rendering:
if (isLoading) return <PageContainer title="..." description=""><LoadingSpinner /></PageContainer>;
if (error) return <ErrorMessage error={error} />;
if (!data?.items?.length) return <PageContainer title="..." description=""><EmptyState /></PageContainer>;
Confirm/Action Sheet Pattern
For status transitions that need validation feedback but no form, use a dedicated status dialog:
// Trigger from action column dropdown
const confirmMutation = useMutation({
mutationFn: entityService.confirm,
onSuccess: (result) => {
if (result.metadata?.house_overlap) { /* show warning */ }
queryClient.invalidateQueries({ queryKey: ["entities"] });
toast.success("Confirmed");
},
});
9. Permission & Access Control
<Can> Component
export function Can({ perform, fallback = null, children }: CanProps) {
const hasPermission = useAuthStore((s) => s.hasPermission);
if (!hasPermission(perform)) return fallback;
return <>{children}</>;
}
Usage
<Can perform="service-core.branch.read">
<Button>View</Button>
</Can>
// Guard action columns
{
id: "actions",
cell: () => (
<Can perform="service-core.branch.manage">
<DropdownMenu>...</DropdownMenu>
</Can>
),
}
Permission slugs: {service}.{entity}.{action} — service-core.branch.read, service-core.branch.manage. Wildcards supported.
10. Component Registry & Module Manifest
Registry
// core/registry/index.ts
class Registry {
private items: Map<string, ModuleRegistration> = new Map();
register(reg: ModuleRegistration) { this.items.set(reg.key, reg); }
getBySlot(slot: string) {
return Array.from(this.items.values())
.filter(r => r.slot === slot)
.sort((a, b) => (a.order ?? 999) - (b.order ?? 999));
}
}
export const ComponentRegistry = new Registry();
ModuleRegistration type
export type ModuleRegistration = {
key: string; // "core.branches.page"
module: string; // "core"
slot: string; // slot identifier for dynamic rendering
load: () => Promise<{ default: React.ComponentType<any> }>;
};
Manifest
// modules/core/manifest.ts
import { ComponentRegistry } from "@/core/registry";
ComponentRegistry.registerAll([
{ key: "core.branches.page", module: "core", slot: "master.organization.branches.page",
load: () => import("./pages/branches").then(m => ({ default: m.BranchesPage })) },
]);
Imported once from main.tsx:
import './modules/core/manifest';
11. Forms — React Hook Form + Zod
const formSchema = z.object({
full_name: z.string().min(1, "Full name is required"),
phone: z.string().optional().nullable(),
});
type FormData = z.infer<typeof formSchema>;
export function EntityForm({ onSubmit }: { onSubmit: (data: FormData) => void }) {
const form = useForm<FormData>({ resolver: zodResolver(formSchema) });
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)}>
<FormField control={form.control} name="full_name" render={({ field }) => (
<FormItem><FormLabel>Name</FormLabel><FormControl><Input {...field} /></FormControl><FormMessage /></FormItem>
)} />
<Button type="submit">Submit</Button>
</form>
</Form>
);
}
- Reset on modal open:
useEffecthooked toopenprop →form.reset(defaultValues) - Server error mapping: map validation errors via
form.setError() - Zod schemas at top of file, explicit and typed
12. Styling — Tailwind CSS (No CSS Modules)
cn() Utility
import { clsx } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)); }
Use cn() for conditional classes:
<div className={cn("p-4", isActive && "bg-blue-50", className)} />
Brand Color
Dynamic CSS variable from company profile:
// In _authenticated.tsx
<div style={{ "--brand-color": brandColor } as React.CSSProperties}>
Used in Tailwind via bg-[var(--brand-color)].
Premium Aesthetics
- Smooth hover states:
hover:bg-gray-50/50 transition-colors - Harmonized palettes:
bg-blue-50/20 text-blue-600 border border-blue-100/30 - Icons: fixed identical wrapper sizes (
h-3.5 w-3.5 shrink-0) - Overflow:
truncate,line-clamp-Xon all dynamic labels
13. Metadata Constants (Core/Meta)
Backend returns all enum values at GET /meta. Cached in useAppStore:
useAppStore.getState().fetchMeta(); // in _authenticated beforeLoad
const meta = useAppStore((s) => s.meta);
meta?.branch?.type → ["farm", "flock", "henhouse", ...]
meta?.branch?.status → ["project", "operational", "inactive"]
14. Image/File Upload — 3-Step S3 Protocol
- Request presigned:
uploadService.requestPresigned({ file_name, file_size, mime_type, entity, entity_id }) - Upload to S3:
axios.put(presigned.url, file)— savepresigned.url.split("?")[0] - Confirm on form submit:
uploadService.confirm({ upload_id: presigned.upload_id })
15. Imports
- Barrel import:
import { Button, DataTable, Dialog, toast } from "@mbu/ui-core"(never import UI components from relative@/components/ui/unless outside ui-backoffice) - Alias:
import { entityService } from "@/modules/{domain}/services/service.{domain}.{entity}" - Store:
import { useAuthStore } from "@/store/auth.store"
16. Quality & Linting
- TypeScript:
strictNullChecks,noUnusedLocals,noUnusedParameters,verbatimModuleSyntax - Import aliases:
@/*forsrc/,@mbu/ui-corefor shared component kit - ESLint:
eslint:recommended,typescript-eslint,react-hooks/recommended,react-refresh/vite - No
any, no default exports, no untyped handlers, no hardcoded config