Docyrus App Dev React
Build Docyrus React TypeScript applications end-to-end. This skill combines app architecture, authentication, data access, query patterns, and production-grade UI guidance in one place.
Recommended Tech Stack
- React 19 + TypeScript + Vite
- TanStack Router (code-based), TanStack Query (server state), TanStack Form
- Tailwind CSS v4, shadcn/ui components
@docyrus/api-client + @docyrus/signin + @docyrus/app-utils
@docyrus/devtools — recommended in-app developer panel for every Docyrus app during development (network, errors, issues, console, iframe messages, OpenAPI request explorer, DOM element picker); gate it to non-production builds
- Auto-generated collections from OpenAPI spec
- Preferred UI libraries: shadcn, diceui, animate-ui, docyrus-ui, reui
When to Use This Skill
Use this skill when you are:
- Building or modifying a Docyrus-backed React app
- Setting up authentication with
@docyrus/signin
- Bootstrapping tenant-aware runtime utilities with
@docyrus/app-utils
- Fetching or mutating data with generated collections or
@docyrus/api-client
- Persisting app-level config or user-level config or saved grid views with
AppConfig, UserAppConfig, and DataViews
- Building record sharing, role management, or ACL-driven UI flows
- Designing feature UIs such as dashboards, forms, tables, layouts, dialogs, analytics, or detail pages
- Selecting between shadcn, diceui, animate-ui, docyrus-ui, and reui components
- Implementing complete feature flows that combine data access and polished UI
End-to-End Feature Workflow
- Set up app auth, routing, and query providers.
@docyrus/signin already fetches the signed-in user from /v1/users/me — read it from useDocyrusAuth().user, do not add your own user call.
- Mount
@docyrus/devtools near the root (dev builds only) and register the authenticated client so requests, errors, and console are instrumented from the start.
- After sign-in, create one shared
InventoryClient (createInventoryClient) and load() it behind a progress bar to warm apps, data sources, users, brands, preferences, and this app's config.
- Bootstrap
TenantPreferences, date/number utilities, and shared app runtime helpers from @docyrus/app-utils, wiring the shared inventory into every app-utils client.
- Use generated Docyrus collection hooks or the REST client for data access.
- Define
columns, filters, formulas, child queries, and mutations correctly.
- Use
AppConfig for per-app persisted settings, UserAppConfig for per-user per-app settings, and DataViews for saved grid views.
- Check preferred UI components before building anything custom.
- Use Docyrus form and detail patterns for create, edit, item detail, and editable grid flows.
- Connect UI actions to TanStack Query mutations and invalidate relevant queries.
Quick Start: App Bootstrap
Root provider setup
import { DocyrusAuthProvider } from '@docyrus/signin'
<DocyrusAuthProvider
apiUrl={import.meta.env.VITE_API_BASE_URL}
clientId={import.meta.env.VITE_OAUTH2_CLIENT_ID}
redirectUri={import.meta.env.VITE_OAUTH2_REDIRECT_URI}
scopes={['offline_access', 'Read.All', 'DS.ReadWrite.All', 'Users.Read']}
callbackPath="/auth/callback"
>
<QueryClientProvider client={queryClient}>
<RouterProvider router={router} />
</QueryClientProvider>
</DocyrusAuthProvider>
Auth gate and current-user access
const { status, user, hasRole, hasPermission } = useDocyrusAuth()
if (status === 'loading') return <Spinner />
if (status === 'unauthenticated') return <SignInButton />
// user is auto-fetched from /v1/users/me after authentication
// hasRole('super_admin') — check role by slug or uid
// hasPermission('edit', dataSourceId) — check ACL permission on a data source
@docyrus/signin already fetches the signed-in user. On authentication it calls /v1/users/me once and exposes the result (roles, permissions, aclRules, identity) as useDocyrusAuth().user. Read the current user and do all auth/role/permission checks from there — never add your own /v1/users/me request. Call refreshUser() to re-fetch after a role change. Only reach for useUsersCollection().getMyInfo() when you need profile fields that are not on the auth user.
Inventory cache warm-up after sign-in
Right after @docyrus/signin reports an authenticated session, create one shared InventoryClient from @docyrus/app-utils and load() it behind a progress bar. The inventory is a tenant-wide in-memory cache of apps, data sources (with embedded views/forms/fields), users, brands, tenant preferences, and this app's config/user-config. Warming it once turns nearly every later metadata read across the app into a cache hit (no network), and the same instance backs every app-utils client you pass it to.
Create the single instance at bootstrap and wire every app-utils client to it:
// services/docyrus.ts — one cache, shared by every client
import {
createInventoryClient,
createDataSourceClient,
createBrandClient,
createAppConfigClient,
createUserAppConfigClient,
createDataViewClient,
} from '@docyrus/app-utils'
const appId = import.meta.env.VITE_APP_ID
export const inventory = createInventoryClient(apiClient)
export const dataSources = createDataSourceClient(apiClient, { inventory })
export const brands = createBrandClient(apiClient, { inventory })
export const appConfig = createAppConfigClient(apiClient, appId, { inventory })
export const userAppConfig = createUserAppConfigClient(apiClient, appId, { inventory })
// View/form clients are per data source — construct on demand, always sharing `inventory`
export const viewsFor = (appSlug: string, dsSlug: string) =>
createDataViewClient(apiClient, appSlug, dsSlug, { inventory })
Warm the cache once, after sign-in, before routing to the home page:
// Runs after useDocyrusAuth() reports an authenticated session.
async function bootstrapAfterSignIn(setProgress: (p: { label: string; value: number }) => void) {
await inventory.load({
// Drop 'users' from `include` if the signed-in user may lack the Users.Read.All scope.
onProgress: ({ message, ratio, phase }) => {
setProgress({ label: message, value: Math.round(ratio * 100) })
if (phase === 'complete') setProgress({ label: 'Ready', value: 100 })
},
})
}
- Create the inventory after sign-in — it needs the authenticated
apiClient.
- Pass the same
inventory to every app-utils client so they share one cache; mutations through those clients patch the cache automatically.
load() warms apps, data sources, users, brands, and preferences, plus this app's config/user-config when VITE_APP_ID is set; it emits progress events for a post-sign-in progress bar.
- A full page reload starts cold — that is why
load() runs after each sign-in. On a tenant switch without reload, call inventory.refresh() so the new tenant's data replaces the old.
See references/app-utils-readme.md (the "createInventoryClient" section) for load() options, scope handling, and cache-invalidation helpers.
Tenant-aware app utilities
Use @docyrus/app-utils as the default runtime layer for tenant-level formatting and persisted app/grid preferences.
import {
createAppConfigClient,
createUserAppConfigClient,
createDataViewClient,
createDateUtils,
createNumberUtils,
getTenantPreferences,
} from '@docyrus/app-utils'
function useAppRuntime(appId: string) {
const client = useDocyrusClient()
const { getMyInfo } = useUsersCollection()
return useQuery({
queryKey: ['app-runtime', appId],
enabled: !!client && !!appId,
queryFn: async () => {
const [preferences, me] = await Promise.all([
getTenantPreferences(client!),
getMyInfo(),
])
return {
preferences,
me,
dateUtils: createDateUtils({
preferences,
userTimezone: me.timeZone?.id,
}),
numberUtils: createNumberUtils({ preferences }),
appConfig: createAppConfigClient(client!, appId),
userConfig: createUserAppConfigClient(client!, appId),
dataViews: createDataViewClient(client!, appId),
}
},
})
}
Use this runtime to:
- Format dates and datetimes with tenant format strings and the user's timezone.
- Format numbers, currency-like values, and decimals using tenant separators and precision.
- Read and upsert the app's single persisted
AppConfig document.
- Read and upsert the current user's
UserAppConfig document (per-user per-app settings).
- Read and persist saved grid views through
DataViews.
When you have warmed a shared inventory (see above), pass { inventory } to each of these clients and read preferences from inventory.getPreferences() instead of a fresh getTenantPreferences(client) call — every read then resolves from the warmed cache.
Data fetching with generated collections
const { list } = useBaseProjectCollection()
const { data: projects } = useQuery({
queryKey: ['projects'],
queryFn: () =>
list({
columns: ['name', 'status', 'record_owner(firstname,lastname)'],
filters: { rules: [{ field: 'status', operator: '!=', value: 'archived' }] },
orderBy: 'created_on DESC',
limit: 50,
}),
})
ACL, roles, and record sharing
Use direct useDocyrusClient() calls for ACL features. These routes may be hidden from generated OpenAPI output, so they are typically not available through generated collection hooks.
const client = useDocyrusClient()
const { data: roles } = useQuery({
queryKey: ['acl', 'roles'],
queryFn: () => client!.get('/v1/users/acl/roles'),
})
const replaceUserRoles = useMutation({
mutationFn: ({ userId, roleIds }: { userId: string; roleIds: string[] }) =>
client!.put(`/v1/users/acl/users/${userId}/roles`, { roleIds }),
})
const createRoleQuery = useMutation({
mutationFn: (payload: Record<string, unknown>) =>
client!.post('/v1/users/acl/role-queries', payload),
})
Prefer role uid values returned by the API when sending roleIds for user-role updates or role-query payloads.
Saved data grid views
Use DataGridViewSelect as the default saved-view UI for Docyrus grids, and persist those views with createDataViewClient(client, appId).
DataGridViewSelect is the default component for showing and editing saved grid views.
- Pass the TanStack table instance via
table so the selector/editor can read column definitions.
- Pass
fields when you want the built-in filter builder enabled in the editor.
- Back
views, onViewCreate, onViewSave, onViewDelete, onViewHide, and onViewUnhide with DataViews CRUD.
- Use
DataGridViewEditor separately only when you need a standalone editor outside the selector.
Dev tooling with @docyrus/devtools
Wire @docyrus/devtools into every Docyrus app. It mounts a floating trigger and a docked panel with Network, Errors, Issues, Explore, Console, and Messages tabs — instrumenting @docyrus/api-client requests (with duplicate/slow detection), TanStack Query issues, console output, and iframe ↔ host postMessage traffic, plus an OpenAPI-driven request explorer that replays endpoints through the app's authenticated client.
import { DocyrusDevtools, useRegisterDocyrusClient } from '@docyrus/devtools'
import { DocyrusAuthProvider, useDocyrusClient } from '@docyrus/signin'
function RegisterDevtoolsClient() {
// Register the auth-managed client once it exists so requests are instrumented.
useRegisterDocyrusClient(useDocyrusClient())
return null
}
export function App() {
return (
<QueryClientProvider client={queryClient}>
{/* enabled gates ALL instrumentation — keep devtools out of production */}
<DocyrusDevtools enabled={import.meta.env.DEV} queryClient={queryClient} openApiSpecPath="/openapi-spec.json">
<DocyrusAuthProvider apiUrl={/* … */} clientId={/* … */}>
<RegisterDevtoolsClient />
<YourRoutes />
</DocyrusAuthProvider>
</DocyrusDevtools>
</QueryClientProvider>
)
}
- Gate it with
enabled={import.meta.env.DEV} (or ship it dormant behind activationShortcut for on-demand use in production). When enabled is false, it only renders children — no listeners, no UI.
- Pass the existing
queryClient so TanStack Query issues surface in the Issues tab.
- Call
useRegisterDocyrusClient(useDocyrusClient()) after mount so the auth-managed client is instrumented as soon as it exists.
- Point
openApiSpecPath at the served spec to enable the request explorer.
See references/devtools-readme.md for the full prop list, host bridge, iframe-message tap, DOM element picker, and the CDP/agent in-page API.
Critical App/Data Rules
- Always send
columns in .list() and .get() calls. Without it, only id is returned.
- Collections are React hooks — call
useBaseProjectCollection(), useUsersCollection(), and similar hooks inside React components.
- Data source endpoints are dynamic — they only exist if the data source is defined in the tenant OpenAPI spec.
- Use
id for count calculations. Use actual field slugs for sum, avg, min, and max.
- Child query keys must appear in
columns.
- Formula keys must appear in
columns.
- Read the signed-in user from
useDocyrusAuth().user — @docyrus/signin already fetches it from /v1/users/me on sign-in (roles, permissions, aclRules, identity). Never add your own /v1/users/me call; use refreshUser() after a role change, and useUsersCollection().getMyInfo() only for profile fields not on the auth user.
- Initialize
TenantPreferences once per app runtime and create shared dateUtils / numberUtils instances from @docyrus/app-utils.
- Formatting functions from
@docyrus/app-utils are regionalized — do not hardcode locale, date format, decimal separator, thousand separator, or decimal precision when tenant preferences should drive them.
- Use
createAppConfigClient(client, appId) for the app's single persisted config document; upsert is the default write path.
- Use
createUserAppConfigClient(client, appId) for the current user's persisted config document scoped to an app (e.g. theme, layout preferences, sidebar state); upsert is the default write path.
- Use
createDataViewClient(client, appId) for saved grid-view CRUD.
- Use
DataViews with DataGridViewSelect to show, create, edit, reorder, hide, unhide, soft-delete, and hard-delete saved data grid views.
DataGridViewSelect needs a TanStack table instance and should receive fields when you want the built-in filter builder/editor experience.
- Data view creation requires
name and tenant_data_source_id.
- Use
dataViews.update(viewId, { archived: true }) for soft-delete and dataViews.remove(viewId) only for irreversible hard-delete.
- Regenerate collections after schema changes by rebuilding the tenant OpenAPI spec, downloading the latest
openapi.json, and re-running the collection generator.
- ACL endpoints are usually raw-client integrations — use
useDocyrusClient() or RestApiClient for roles, user-role assignments, role queries, record sharing, and ownership transfer.
- Prefer role
uid values for ACL role writes, user-role roleIds, and role-query roleIds.
- Treat
PUT /v1/users/acl/users/:userId/roles as full replacement and POST /v1/users/acl/users/:userId/roles as additive.
- Send role-query
query as raw JSON and omit tenantAppId when dataSourceId is present; backend derives it.
- After deleting a role, invalidate dependent app queries for role lists, user-role lists, role-query lists, and any UI that renders primary-role labels.
- Create one shared
InventoryClient after sign-in and load() it — pass that single instance to every app-utils client so they share the warmed cache; call inventory.refresh() on tenant switch.
- Mount
@docyrus/devtools in dev builds gated by enabled={import.meta.env.DEV}, pass the app's queryClient, and register the auth client with useRegisterDocyrusClient(useDocyrusClient()).
Critical UI/UX Rules
- Always check preferred components first before creating anything custom.
- Use
AwesomeCard for dashboards unless the user explicitly wants a different card style.
- Use animate-ui
Sidebar for app layouts unless another layout is requested.
- Prefer Recharts for charts in general feature UI. Exception — dashboards/analytics/reporting: use the docyrus-dashboard-design skill, which mandates Bklit UI charts,
AwesomeCard panels, and AwesomeStats KPI cards.
- Use icons in this order: hugeicons, then fontawesome light, then lucide.
- Use
AwesomeDialog for item create forms.
- Small/simple forms:
container="sheet" with side="right"
- Long/complex forms:
container="modal" or container="drawer"
- Choose detail containers based on item complexity.
- Large items: dedicated page
- Small items:
AwesomeDialog right sheet
- All forms must use TanStack Form + the Docyrus form system. Do not build feature forms with plain HTML forms or React Hook Form directly.
- Use
EditableRecordDetail for inline editing in item detail views.
- Always enable
trackChanges for editable detail and grid experiences.
- Use
DataGridViewSelect for saved grid views and back it with DataViews from @docyrus/app-utils.
- Prefer
DataGridViewEditor only when you need a standalone grid-view editor outside the selector component.
Default UI Choices
| Use Case |
Default Component |
Library |
| Item create form |
AwesomeDialog |
docyrus |
| Quick record create |
CreateRecordDialog |
docyrus |
| Item detail (small) |
AwesomeDialog sheet right |
docyrus |
| Item detail (large) |
Dedicated page |
— |
| Inline editing |
EditableRecordDetail |
docyrus |
| Dashboard card |
AwesomeCard |
docyrus |
| Stat dashboards |
AwesomeStats |
docyrus |
| App navigation |
Sidebar |
animate-ui |
| Data table |
DataTable |
diceui |
| Editable grid |
Data Grid |
docyrus |
| Grid saved views |
DataGridViewSelect + DataViews |
docyrus + @docyrus/app-utils |
| Forms |
Docyrus form fields + TanStack Form |
docyrus |
| Charts (general) |
shadcn chart + Recharts |
shadcn |
| Dashboards / analytics / KPIs |
Bklit charts + AwesomeCard + AwesomeStats (see docyrus-dashboard-design) |
bklit + docyrus |
| File upload |
File Upload |
diceui |
| Gantt/project scheduling |
Gantt |
docyrus |
| Resource scheduling |
ResourceSchedulerPanel |
docyrus |
| Team chat |
TeamChatChannel |
docyrus |
| AI interface |
DocyrusAgent |
docyrus |
| Pricing / quoting |
PricingEnginePanel |
docyrus |
| Analytics / pivot |
PivotGrid |
docyrus |
Quick UI Patterns
Item create form
<AwesomeDialog open={open} container="sheet" side="right" size="default">
<AwesomeDialogHeader title="Create Task" icon="far-plus" />
<AwesomeDialogBody>
<form.Field name="title">{(field) => <TextFormField field={field} label="Title" />}</form.Field>
<form.Field name="status">{(field) => <SelectFormField field={field} label="Status" />}</form.Field>
</AwesomeDialogBody>
<AwesomeDialogFooter>
<Button variant="outline" => setOpen(false)}>Cancel</Button>
<Button
</AwesomeDialogFooter>
</AwesomeDialog>
Item detail with inline editing
<AwesomeDialog open={open} container="sheet" side="right" size="lg" fullscreenable>
<AwesomeDialogHeader
title="Task Detail"
description="Review and edit task fields inline"
headerButtons={<Button variant="outline" size="sm" All</Button>}
/>
<AwesomeDialogBody>
<EditableRecordDetail fields={fields} record={record} trackChanges>
<EditableRecordDetailField slug="title" />
<EditableRecordDetailField slug="status" />
<EditableRecordDetailField slug="assignee" />
<EditableRecordDetailField slug="due_date" />
</EditableRecordDetail>
</AwesomeDialogBody>
</AwesomeDialog>
TanStack Query Pattern
function useProjects(params?: ICollectionListParams) {
const { list } = useBaseProjectCollection()
return useQuery({
queryKey: ['projects', 'list', params],
queryFn: () => list({ columns: PROJECT_COLUMNS, ...params }),
})
}
function useCreateProject() {
const { create } = useBaseProjectCollection()
const qc = useQueryClient()
return useMutation({
mutationFn: (data: Record<string, unknown>) => create(data),
onSuccess: () => {
void qc.invalidateQueries({ queryKey: ['projects'] })
},
})
}
Collection CRUD Methods
const { list, get, create, update, delete: deleteOne, deleteMany } = useBaseProjectCollection()
list(params?: ICollectionListParams)
get(id, { columns })
create(data)
update(id, data)
deleteOne(id)
deleteMany({ recordIds })
API endpoint pattern: /v1/apps/{appSlug}/data-sources/{slug}/items
Query Capabilities Summary
The .list() method supports:
columns
filters
filterKeyword
orderBy
limit and offset
fullCount
calculations
formulas
childQueries
pivot
expand
Component Installation Pattern
pnpm dlx shadcn@latest add button
pnpm dlx shadcn@latest add @diceui/data-table
pnpm dlx shadcn@latest add @animate-ui/sidebar
pnpm dlx @docyrus/cli add @docyrus/ui-awesome-card
pnpm dlx shadcn@latest add @reui/file-upload-default
References
For deep dives, read:
references/README.md — merged reference map for app development and UI design
references/api-client-and-auth.md
references/collections-and-patterns.md
references/signin-readme.md — full @docyrus/signin package README (auth provider, hooks, iframe/host bridge, SSR, roles & permissions). Published on npm as @docyrus/signin; source at docyrus-devkit/packages/signin
references/host-communication-integration.md — embedded-app ↔ host shell postMessage integration, excluding Guidy: host→app navigation (useDocyrusHostNavigation) & notifications (useDocyrusHostNotification), app→host route sync (syncRouteToHost / useDocyrusHostRouteSync / notifyRouteChange) and navigation requests (requestHostNavigation), origin validation, Vue equivalents
references/guidy-integration.md — make an embedded app Guidy-compatible (host AI assistant driving the app's UI): enableGuidyBridge, targetable controls (stable ids + accessible labels), and declared routes (guidyRoutes / useDocyrusGuidyRoutes); routes also need useDocyrusHostNavigation from the host-communication reference
references/app-utils-readme.md — full @docyrus/app-utils package README (tenant preferences, date/number formatting, app/user config, data views/forms, data-source metadata, and the Inventory Cache). Published on npm as @docyrus/app-utils; source at docyrus-devkit/packages/app-utils
references/devtools-readme.md — full @docyrus/devtools package README (in-app dev panel, request/console/message instrumentation, OpenAPI explorer, element picker, CDP/agent API). Published on npm as @docyrus/devtools; source at docyrus-devkit/packages/devtools
- the docyrus-app-settings skill — designing and using app-scoped (
AppConfig) and per-user (UserAppConfig) settings documents with createAppConfigClient / createUserAppConfigClient: scope choice, wholesale-replace and empty-document gotchas, and the REST/CLI contract
- the docyrus-acl-design skill — ACL roles, permissions, and role-queries (
docyrus acl); plus the ACL REST endpoints in docyrus-api-dev's SKILL.md
../docyrus-api-dev/references/data-source-query-guide.md
../docyrus-api-dev/references/formula-design-guide-llm.md
../docyrus-api-dev/references/query-guide.md
references/preferred-components-catalog.md
references/component-selection-guide.md
references/icon-usage-guide.md
1---
2name: docyrus-app-dev-react
3description: Build Docyrus React TypeScript web applications end-to-end, combining authentication, API access, @docyrus/app-utils runtime helpers, @docyrus/devtools in-app debugging, generated collections, TanStack Query/Form patterns, and production-grade UI implementation with preferred component libraries. Use when creating or modifying Docyrus-backed apps that use @docyrus/api-client, @docyrus/signin, @docyrus/app-utils, @docyrus/devtools, Docyrus collections, queries, dashboards, forms, tables, layouts, or Docyrus UI components.
4metadata:
5 source: https://skillmd.com/skills/docyrus/docyrus-app-dev-react
6---
7
8# Docyrus App Dev React
9
10Build Docyrus React TypeScript applications end-to-end. This skill combines app architecture, authentication, data access, query patterns, and production-grade UI guidance in one place.
11
12## Recommended Tech Stack
13
14- React 19 + TypeScript + Vite
15- TanStack Router (code-based), TanStack Query (server state), TanStack Form
16- Tailwind CSS v4, shadcn/ui components
17- `@docyrus/api-client` + `@docyrus/signin` + `@docyrus/app-utils`
18- `@docyrus/devtools` — recommended in-app developer panel for every Docyrus app during development (network, errors, issues, console, iframe messages, OpenAPI request explorer, DOM element picker); gate it to non-production builds
19- Auto-generated collections from OpenAPI spec
20- Preferred UI libraries: shadcn, diceui, animate-ui, docyrus-ui, reui
21
22## When to Use This Skill
23
24Use this skill when you are:
25
26- Building or modifying a Docyrus-backed React app
27- Setting up authentication with `@docyrus/signin`
28- Bootstrapping tenant-aware runtime utilities with `@docyrus/app-utils`
29- Fetching or mutating data with generated collections or `@docyrus/api-client`
30- Persisting app-level config or user-level config or saved grid views with `AppConfig`, `UserAppConfig`, and `DataViews`
31- Building record sharing, role management, or ACL-driven UI flows
32- Designing feature UIs such as dashboards, forms, tables, layouts, dialogs, analytics, or detail pages
33- Selecting between shadcn, diceui, animate-ui, docyrus-ui, and reui components
34- Implementing complete feature flows that combine data access and polished UI
35
36## End-to-End Feature Workflow
37
381. Set up app auth, routing, and query providers. `@docyrus/signin` already fetches the signed-in user from `/v1/users/me` — read it from `useDocyrusAuth().user`, do not add your own user call.
392. Mount `@docyrus/devtools` near the root (dev builds only) and register the authenticated client so requests, errors, and console are instrumented from the start.
403. After sign-in, create **one** shared `InventoryClient` (`createInventoryClient`) and `load()` it behind a progress bar to warm apps, data sources, users, brands, preferences, and this app's config.
414. Bootstrap `TenantPreferences`, date/number utilities, and shared app runtime helpers from `@docyrus/app-utils`, wiring the shared inventory into every app-utils client.
425. Use generated Docyrus collection hooks or the REST client for data access.
436. Define `columns`, filters, formulas, child queries, and mutations correctly.
447. Use `AppConfig` for per-app persisted settings, `UserAppConfig` for per-user per-app settings, and `DataViews` for saved grid views.
458. Check preferred UI components before building anything custom.
469. Use Docyrus form and detail patterns for create, edit, item detail, and editable grid flows.
4710. Connect UI actions to TanStack Query mutations and invalidate relevant queries.
48
49## Quick Start: App Bootstrap
50
51### Root provider setup
52
53```tsx
54import { DocyrusAuthProvider } from '@docyrus/signin'
55
56<DocyrusAuthProvider
57 apiUrl={import.meta.env.VITE_API_BASE_URL}
58 clientId={import.meta.env.VITE_OAUTH2_CLIENT_ID}
59 redirectUri={import.meta.env.VITE_OAUTH2_REDIRECT_URI}
60 scopes={['offline_access', 'Read.All', 'DS.ReadWrite.All', 'Users.Read']}
61 callbackPath="/auth/callback"
62>
63 <QueryClientProvider client={queryClient}>
64 <RouterProvider router={router} />
65 </QueryClientProvider>
66</DocyrusAuthProvider>
67```
68
69### Auth gate and current-user access
70
71```tsx
72const { status, user, hasRole, hasPermission } = useDocyrusAuth()
73
74if (status === 'loading') return <Spinner />
75if (status === 'unauthenticated') return <SignInButton />
76
77// user is auto-fetched from /v1/users/me after authentication
78// hasRole('super_admin') — check role by slug or uid
79// hasPermission('edit', dataSourceId) — check ACL permission on a data source
80```
81
82**`@docyrus/signin` already fetches the signed-in user.** On authentication it calls `/v1/users/me` once and exposes the result (roles, permissions, `aclRules`, identity) as `useDocyrusAuth().user`. Read the current user and do all auth/role/permission checks from there — **never add your own `/v1/users/me` request**. Call `refreshUser()` to re-fetch after a role change. Only reach for `useUsersCollection().getMyInfo()` when you need profile fields that are not on the auth user.
83
84### Inventory cache warm-up after sign-in
85
86Right after `@docyrus/signin` reports an authenticated session, create **one** shared `InventoryClient` from `@docyrus/app-utils` and `load()` it behind a progress bar. The inventory is a tenant-wide in-memory cache of apps, data sources (with embedded views/forms/fields), users, brands, tenant preferences, and this app's config/user-config. Warming it once turns nearly every later metadata read across the app into a cache hit (no network), and the same instance backs every app-utils client you pass it to.
87
88Create the single instance at bootstrap and wire every app-utils client to it:
89
90```ts
91// services/docyrus.ts — one cache, shared by every client
92import {
93 createInventoryClient,
94 createDataSourceClient,
95 createBrandClient,
96 createAppConfigClient,
97 createUserAppConfigClient,
98 createDataViewClient,
99} from '@docyrus/app-utils'
100
101const appId = import.meta.env.VITE_APP_ID
102
103export const inventory = createInventoryClient(apiClient)
104
105export const dataSources = createDataSourceClient(apiClient, { inventory })
106export const brands = createBrandClient(apiClient, { inventory })
107export const appConfig = createAppConfigClient(apiClient, appId, { inventory })
108export const userAppConfig = createUserAppConfigClient(apiClient, appId, { inventory })
109
110// View/form clients are per data source — construct on demand, always sharing `inventory`
111export const viewsFor = (appSlug: string, dsSlug: string) =>
112 createDataViewClient(apiClient, appSlug, dsSlug, { inventory })
113```
114
115Warm the cache once, after sign-in, before routing to the home page:
116
117```ts
118// Runs after useDocyrusAuth() reports an authenticated session.
119async function bootstrapAfterSignIn(setProgress: (p: { label: string; value: number }) => void) {
120 await inventory.load({
121 // Drop 'users' from `include` if the signed-in user may lack the Users.Read.All scope.
122 onProgress: ({ message, ratio, phase }) => {
123 setProgress({ label: message, value: Math.round(ratio * 100) })
124 if (phase === 'complete') setProgress({ label: 'Ready', value: 100 })
125 },
126 })
127}
128```
129
130- Create the inventory **after** sign-in — it needs the authenticated `apiClient`.
131- Pass the **same** `inventory` to every app-utils client so they share one cache; mutations through those clients patch the cache automatically.
132- `load()` warms apps, data sources, users, brands, and preferences, plus this app's config/user-config when `VITE_APP_ID` is set; it emits progress events for a post-sign-in progress bar.
133- A full page reload starts cold — that is why `load()` runs after each sign-in. On a **tenant switch** without reload, call `inventory.refresh()` so the new tenant's data replaces the old.
134
135See `references/app-utils-readme.md` (the "createInventoryClient" section) for `load()` options, scope handling, and cache-invalidation helpers.
136
137### Tenant-aware app utilities
138
139Use `@docyrus/app-utils` as the default runtime layer for tenant-level formatting and persisted app/grid preferences.
140
141```tsx
142import {
143 createAppConfigClient,
144 createUserAppConfigClient,
145 createDataViewClient,
146 createDateUtils,
147 createNumberUtils,
148 getTenantPreferences,
149} from '@docyrus/app-utils'
150
151function useAppRuntime(appId: string) {
152 const client = useDocyrusClient()
153 const { getMyInfo } = useUsersCollection()
154
155 return useQuery({
156 queryKey: ['app-runtime', appId],
157 enabled: !!client && !!appId,
158 queryFn: async () => {
159 const [preferences, me] = await Promise.all([
160 getTenantPreferences(client!),
161 getMyInfo(),
162 ])
163
164 return {
165 preferences,
166 me,
167 dateUtils: createDateUtils({
168 preferences,
169 userTimezone: me.timeZone?.id,
170 }),
171 numberUtils: createNumberUtils({ preferences }),
172 appConfig: createAppConfigClient(client!, appId),
173 userConfig: createUserAppConfigClient(client!, appId),
174 dataViews: createDataViewClient(client!, appId),
175 }
176 },
177 })
178}
179```
180
181Use this runtime to:
182
183- Format dates and datetimes with tenant format strings and the user's timezone.
184- Format numbers, currency-like values, and decimals using tenant separators and precision.
185- Read and upsert the app's single persisted `AppConfig` document.
186- Read and upsert the current user's `UserAppConfig` document (per-user per-app settings).
187- Read and persist saved grid views through `DataViews`.
188
189When you have warmed a shared inventory (see above), pass `{ inventory }` to each of these clients and read `preferences` from `inventory.getPreferences()` instead of a fresh `getTenantPreferences(client)` call — every read then resolves from the warmed cache.
190
191### Data fetching with generated collections
192
193```tsx
194const { list } = useBaseProjectCollection()
195
196const { data: projects } = useQuery({
197 queryKey: ['projects'],
198 queryFn: () =>
199 list({
200 columns: ['name', 'status', 'record_owner(firstname,lastname)'],
201 filters: { rules: [{ field: 'status', operator: '!=', value: 'archived' }] },
202 orderBy: 'created_on DESC',
203 limit: 50,
204 }),
205})
206```
207
208### ACL, roles, and record sharing
209
210Use direct `useDocyrusClient()` calls for ACL features. These routes may be hidden from generated OpenAPI output, so they are typically not available through generated collection hooks.
211
212```tsx
213const client = useDocyrusClient()
214
215const { data: roles } = useQuery({
216 queryKey: ['acl', 'roles'],
217 queryFn: () => client!.get('/v1/users/acl/roles'),
218})
219
220const replaceUserRoles = useMutation({
221 mutationFn: ({ userId, roleIds }: { userId: string; roleIds: string[] }) =>
222 client!.put(`/v1/users/acl/users/${userId}/roles`, { roleIds }),
223})
224
225const createRoleQuery = useMutation({
226 mutationFn: (payload: Record<string, unknown>) =>
227 client!.post('/v1/users/acl/role-queries', payload),
228})
229```
230
231Prefer role `uid` values returned by the API when sending `roleIds` for user-role updates or role-query payloads.
232
233### Saved data grid views
234
235Use `DataGridViewSelect` as the default saved-view UI for Docyrus grids, and persist those views with `createDataViewClient(client, appId)`.
236
237- `DataGridViewSelect` is the default component for showing and editing saved grid views.
238- Pass the TanStack table instance via `table` so the selector/editor can read column definitions.
239- Pass `fields` when you want the built-in filter builder enabled in the editor.
240- Back `views`, `onViewCreate`, `onViewSave`, `onViewDelete`, `onViewHide`, and `onViewUnhide` with `DataViews` CRUD.
241- Use `DataGridViewEditor` separately only when you need a standalone editor outside the selector.
242
243### Dev tooling with `@docyrus/devtools`
244
245Wire `@docyrus/devtools` into every Docyrus app. It mounts a floating trigger and a docked panel with `Network`, `Errors`, `Issues`, `Explore`, `Console`, and `Messages` tabs — instrumenting `@docyrus/api-client` requests (with duplicate/slow detection), TanStack Query issues, console output, and iframe ↔ host `postMessage` traffic, plus an OpenAPI-driven request explorer that replays endpoints through the app's authenticated client.
246
247```tsx
248import { DocyrusDevtools, useRegisterDocyrusClient } from '@docyrus/devtools'
249import { DocyrusAuthProvider, useDocyrusClient } from '@docyrus/signin'
250
251function RegisterDevtoolsClient() {
252 // Register the auth-managed client once it exists so requests are instrumented.
253 useRegisterDocyrusClient(useDocyrusClient())
254 return null
255}
256
257export function App() {
258 return (
259 <QueryClientProvider client={queryClient}>
260 {/* enabled gates ALL instrumentation — keep devtools out of production */}
261 <DocyrusDevtools enabled={import.meta.env.DEV} queryClient={queryClient} openApiSpecPath="/openapi-spec.json">
262 <DocyrusAuthProvider apiUrl={/* … */} clientId={/* … */}>
263 <RegisterDevtoolsClient />
264 <YourRoutes />
265 </DocyrusAuthProvider>
266 </DocyrusDevtools>
267 </QueryClientProvider>
268 )
269}
270```
271
272- Gate it with `enabled={import.meta.env.DEV}` (or ship it dormant behind `activationShortcut` for on-demand use in production). When `enabled` is `false`, it only renders children — no listeners, no UI.
273- Pass the existing `queryClient` so TanStack Query issues surface in the `Issues` tab.
274- Call `useRegisterDocyrusClient(useDocyrusClient())` after mount so the auth-managed client is instrumented as soon as it exists.
275- Point `openApiSpecPath` at the served spec to enable the request explorer.
276
277See `references/devtools-readme.md` for the full prop list, host bridge, iframe-message tap, DOM element picker, and the CDP/agent in-page API.
278
279## Critical App/Data Rules
280
2811. **Always send `columns`** in `.list()` and `.get()` calls. Without it, only `id` is returned.
2822. **Collections are React hooks** — call `useBaseProjectCollection()`, `useUsersCollection()`, and similar hooks inside React components.
2833. **Data source endpoints are dynamic** — they only exist if the data source is defined in the tenant OpenAPI spec.
2844. **Use `id` for `count` calculations**. Use actual field slugs for `sum`, `avg`, `min`, and `max`.
2855. **Child query keys must appear in `columns`**.
2866. **Formula keys must appear in `columns`**.
2877. **Read the signed-in user from `useDocyrusAuth().user`** — `@docyrus/signin` already fetches it from `/v1/users/me` on sign-in (roles, permissions, `aclRules`, identity). Never add your own `/v1/users/me` call; use `refreshUser()` after a role change, and `useUsersCollection().getMyInfo()` only for profile fields not on the auth user.
2888. **Initialize `TenantPreferences` once per app runtime** and create shared `dateUtils` / `numberUtils` instances from `@docyrus/app-utils`.
2899. **Formatting functions from `@docyrus/app-utils` are regionalized** — do not hardcode locale, date format, decimal separator, thousand separator, or decimal precision when tenant preferences should drive them.
29010. **Use `createAppConfigClient(client, appId)`** for the app's single persisted config document; `upsert` is the default write path.
29111. **Use `createUserAppConfigClient(client, appId)`** for the current user's persisted config document scoped to an app (e.g. theme, layout preferences, sidebar state); `upsert` is the default write path.
29212. **Use `createDataViewClient(client, appId)`** for saved grid-view CRUD.
29313. **Use `DataViews` with `DataGridViewSelect`** to show, create, edit, reorder, hide, unhide, soft-delete, and hard-delete saved data grid views.
29414. **`DataGridViewSelect` needs a TanStack table instance** and should receive `fields` when you want the built-in filter builder/editor experience.
29515. **Data view creation requires `name` and `tenant_data_source_id`**.
29616. **Use `dataViews.update(viewId, { archived: true })` for soft-delete** and `dataViews.remove(viewId)` only for irreversible hard-delete.
29717. **Regenerate collections after schema changes** by rebuilding the tenant OpenAPI spec, downloading the latest `openapi.json`, and re-running the collection generator.
29818. **ACL endpoints are usually raw-client integrations** — use `useDocyrusClient()` or `RestApiClient` for roles, user-role assignments, role queries, record sharing, and ownership transfer.
29919. **Prefer role `uid` values** for ACL role writes, user-role `roleIds`, and role-query `roleIds`.
30020. **Treat `PUT /v1/users/acl/users/:userId/roles` as full replacement** and `POST /v1/users/acl/users/:userId/roles` as additive.
30121. **Send role-query `query` as raw JSON** and omit `tenantAppId` when `dataSourceId` is present; backend derives it.
30222. **After deleting a role, invalidate dependent app queries** for role lists, user-role lists, role-query lists, and any UI that renders primary-role labels.
30323. **Create one shared `InventoryClient` after sign-in and `load()` it** — pass that single instance to every app-utils client so they share the warmed cache; call `inventory.refresh()` on tenant switch.
30424. **Mount `@docyrus/devtools` in dev builds** gated by `enabled={import.meta.env.DEV}`, pass the app's `queryClient`, and register the auth client with `useRegisterDocyrusClient(useDocyrusClient())`.
305
306## Critical UI/UX Rules
307
3081. **Always check preferred components first** before creating anything custom.
3092. **Use `AwesomeCard` for dashboards** unless the user explicitly wants a different card style.
3103. **Use animate-ui `Sidebar` for app layouts** unless another layout is requested.
3114. **Prefer Recharts for charts** in general feature UI. **Exception — dashboards/analytics/reporting:** use the **docyrus-dashboard-design** skill, which mandates Bklit UI charts, `AwesomeCard` panels, and `AwesomeStats` KPI cards.
3125. **Use icons in this order**: hugeicons, then fontawesome light, then lucide.
3136. **Use `AwesomeDialog` for item create forms**.
314 - Small/simple forms: `container="sheet"` with `side="right"`
315 - Long/complex forms: `container="modal"` or `container="drawer"`
3167. **Choose detail containers based on item complexity**.
317 - Large items: dedicated page
318 - Small items: `AwesomeDialog` right sheet
3198. **All forms must use TanStack Form + the Docyrus form system**. Do not build feature forms with plain HTML forms or React Hook Form directly.
3209. **Use `EditableRecordDetail` for inline editing** in item detail views.
32110. **Always enable `trackChanges`** for editable detail and grid experiences.
32211. **Use `DataGridViewSelect` for saved grid views** and back it with `DataViews` from `@docyrus/app-utils`.
32312. **Prefer `DataGridViewEditor` only when you need a standalone grid-view editor** outside the selector component.
324
325## Default UI Choices
326
327| Use Case | Default Component | Library |
328|----------|-------------------|---------|
329| Item create form | `AwesomeDialog` | docyrus |
330| Quick record create | `CreateRecordDialog` | docyrus |
331| Item detail (small) | `AwesomeDialog` sheet right | docyrus |
332| Item detail (large) | Dedicated page | — |
333| Inline editing | `EditableRecordDetail` | docyrus |
334| Dashboard card | `AwesomeCard` | docyrus |
335| Stat dashboards | `AwesomeStats` | docyrus |
336| App navigation | `Sidebar` | animate-ui |
337| Data table | `DataTable` | diceui |
338| Editable grid | `Data Grid` | docyrus |
339| Grid saved views | `DataGridViewSelect` + `DataViews` | docyrus + `@docyrus/app-utils` |
340| Forms | Docyrus form fields + TanStack Form | docyrus |
341| Charts (general) | shadcn chart + Recharts | shadcn |
342| Dashboards / analytics / KPIs | Bklit charts + `AwesomeCard` + `AwesomeStats` (see **docyrus-dashboard-design**) | bklit + docyrus |
343| File upload | File Upload | diceui |
344| Gantt/project scheduling | `Gantt` | docyrus |
345| Resource scheduling | `ResourceSchedulerPanel` | docyrus |
346| Team chat | `TeamChatChannel` | docyrus |
347| AI interface | `DocyrusAgent` | docyrus |
348| Pricing / quoting | `PricingEnginePanel` | docyrus |
349| Analytics / pivot | `PivotGrid` | docyrus |
350
351## Quick UI Patterns
352
353### Item create form
354
355```tsx
356<AwesomeDialog open={open} onOpenChange={setOpen} container="sheet" side="right" size="default">
357 <AwesomeDialogHeader title="Create Task" icon="far-plus" />
358 <AwesomeDialogBody>
359 <form.Field name="title">{(field) => <TextFormField field={field} label="Title" />}</form.Field>
360 <form.Field name="status">{(field) => <SelectFormField field={field} label="Status" />}</form.Field>
361 </AwesomeDialogBody>
362 <AwesomeDialogFooter>
363 <Button variant="outline" onClick={() => setOpen(false)}>Cancel</Button>
364 <Button onClick={handleSubmit}>Create</Button>
365 </AwesomeDialogFooter>
366</AwesomeDialog>
367```
368
369### Item detail with inline editing
370
371```tsx
372<AwesomeDialog open={open} onOpenChange={setOpen} container="sheet" side="right" size="lg" fullscreenable>
373 <AwesomeDialogHeader
374 title="Task Detail"
375 description="Review and edit task fields inline"
376 headerButtons={<Button variant="outline" size="sm" onClick={switchToFullForm}>Edit All</Button>}
377 />
378 <AwesomeDialogBody>
379 <EditableRecordDetail fields={fields} record={record} onSave={handleSave} trackChanges>
380 <EditableRecordDetailField slug="title" />
381 <EditableRecordDetailField slug="status" />
382 <EditableRecordDetailField slug="assignee" />
383 <EditableRecordDetailField slug="due_date" />
384 </EditableRecordDetail>
385 </AwesomeDialogBody>
386</AwesomeDialog>
387```
388
389## TanStack Query Pattern
390
391```typescript
392function useProjects(params?: ICollectionListParams) {
393 const { list } = useBaseProjectCollection()
394 return useQuery({
395 queryKey: ['projects', 'list', params],
396 queryFn: () => list({ columns: PROJECT_COLUMNS, ...params }),
397 })
398}
399
400function useCreateProject() {
401 const { create } = useBaseProjectCollection()
402 const qc = useQueryClient()
403 return useMutation({
404 mutationFn: (data: Record<string, unknown>) => create(data),
405 onSuccess: () => {
406 void qc.invalidateQueries({ queryKey: ['projects'] })
407 },
408 })
409}
410```
411
412## Collection CRUD Methods
413
414```typescript
415const { list, get, create, update, delete: deleteOne, deleteMany } = useBaseProjectCollection()
416
417list(params?: ICollectionListParams)
418get(id, { columns })
419create(data)
420update(id, data)
421deleteOne(id)
422deleteMany({ recordIds })
423```
424
425API endpoint pattern: `/v1/apps/{appSlug}/data-sources/{slug}/items`
426
427## Query Capabilities Summary
428
429The `.list()` method supports:
430
431- `columns`
432- `filters`
433- `filterKeyword`
434- `orderBy`
435- `limit` and `offset`
436- `fullCount`
437- `calculations`
438- `formulas`
439- `childQueries`
440- `pivot`
441- `expand`
442
443## Component Installation Pattern
444
445```bash
446pnpm dlx shadcn@latest add button
447pnpm dlx shadcn@latest add @diceui/data-table
448pnpm dlx shadcn@latest add @animate-ui/sidebar
449pnpm dlx @docyrus/cli add @docyrus/ui-awesome-card
450pnpm dlx shadcn@latest add @reui/file-upload-default
451```
452
453## References
454
455For deep dives, read:
456
457- `references/README.md` — merged reference map for app development and UI design
458- `references/api-client-and-auth.md`
459- `references/collections-and-patterns.md`
460- `references/signin-readme.md` — full `@docyrus/signin` package README (auth provider, hooks, iframe/host bridge, SSR, roles & permissions). Published on npm as `@docyrus/signin`; source at `docyrus-devkit/packages/signin`
461- `references/host-communication-integration.md` — embedded-app ↔ host shell `postMessage` integration, **excluding** Guidy: host→app navigation (`useDocyrusHostNavigation`) & notifications (`useDocyrusHostNotification`), app→host route sync (`syncRouteToHost` / `useDocyrusHostRouteSync` / `notifyRouteChange`) and navigation requests (`requestHostNavigation`), origin validation, Vue equivalents
462- `references/guidy-integration.md` — make an embedded app Guidy-compatible (host AI assistant driving the app's UI): `enableGuidyBridge`, targetable controls (stable ids + accessible labels), and declared routes (`guidyRoutes` / `useDocyrusGuidyRoutes`); routes also need `useDocyrusHostNavigation` from the host-communication reference
463- `references/app-utils-readme.md` — full `@docyrus/app-utils` package README (tenant preferences, date/number formatting, app/user config, data views/forms, data-source metadata, and the Inventory Cache). Published on npm as `@docyrus/app-utils`; source at `docyrus-devkit/packages/app-utils`
464- `references/devtools-readme.md` — full `@docyrus/devtools` package README (in-app dev panel, request/console/message instrumentation, OpenAPI explorer, element picker, CDP/agent API). Published on npm as `@docyrus/devtools`; source at `docyrus-devkit/packages/devtools`
465- the **docyrus-app-settings** skill — designing and using app-scoped (`AppConfig`) and per-user (`UserAppConfig`) settings documents with `createAppConfigClient` / `createUserAppConfigClient`: scope choice, wholesale-replace and empty-document gotchas, and the REST/CLI contract
466- the **docyrus-acl-design** skill — ACL roles, permissions, and role-queries (`docyrus acl`); plus the ACL REST endpoints in **docyrus-api-dev**'s SKILL.md
467- `../docyrus-api-dev/references/data-source-query-guide.md`
468- `../docyrus-api-dev/references/formula-design-guide-llm.md`
469- `../docyrus-api-dev/references/query-guide.md`
470- `references/preferred-components-catalog.md`
471- `references/component-selection-guide.md`
472- `references/icon-usage-guide.md`