@karni/ui¶
This page lists everything the package exports from its root (import { ... } from "@karni/ui").
It comes from the manifest built with the package (@karni/ui/manifest.json), which
coding agents read too. Props and usage are in the
package README.
The resource components render from the backend's OpenAPI schema, so a page
is a few lines that compose them (see the tutorial).
Resource components (schema-driven)¶
ResourceTable(roledata-table)ResourceForm(roleresource-form)ResourceDetail(roledetail-view)ResourceSelect(roleasync-select)ChangeHistory(rolechange-history)ResourceImport(roleresource-import)ResourceGrid(roleresource-grid, experimental)ResourceBoard(roleresource-board, experimental)ResourceCalendar(roleresource-calendar, experimental)TreeView(roletree-view, experimental)TreeSelect(roletree-select, experimental)TreeBreadcrumb(roletree-breadcrumb, experimental)FacetPanel(rolefacet-panel, experimental)
App shell and pages¶
Layout(rolelayout-shell)GlobalSearch(roleglobal-search, experimental)Page(rolepage-shell)EmptyState(roleempty-state)Modal(rolemodal)ModalCloseModalTitleModalDescriptionToaster(roletoast)Stat(rolestat)DataChart(rolechart)FileUpload(rolefile-upload)KarniMark
The family screens (one layout, home, people, inbox and search for every part)¶
FamilyLayout(rolefamily-layout, experimental)Storefront(experimental)BackOffice(experimental)FamilyHome(experimental)FamilyEmptyHome(experimental)PeoplePage(experimental)PersonPage(experimental)Timeline(experimental)InboxBell(experimental)InboxPage(experimental)EmailChoices(experimental)MyAddresses(experimental)SearchPage(experimental)AccountPage(experimental)SignInPage(experimental)SignUpForm(experimental)SettingsPage(experimental)
Auth¶
AuthProviderAuthGuard(roleauth-guard)LoginForm(rolelogin-form)SocialButton(rolesocial-sign-in, experimental)OtpLoginForm(rolecode-sign-in, experimental)TermsGate(roleterms-gate, experimental)DemoNotice(roledemo-notice, experimental)KarniProvider
Page blocks (experimental)¶
Experimental
The page blocks, useResourceCounts and ResourceDetail's related prop are
experimental: they may change in a minor
release, and each change is in the CHANGELOG.
Pages for large apps are dashboards, comparisons and reports, not only resource
tables. These components keep such a page within the 50-line cap
(karni/max-page-lines), and karni/no-raw-elements names them where a page
writes a raw <table> or <details>.
DashboardGrid(roledashboard-grid): a responsive grid of cards: one column on phones, two onmdscreens,columns(2, 3 or 4) onxl. Each card takes aspan(1 to 4, or"full"). Use it for the layout of a dashboard or a report.DashboardCard: one card of the grid: a region named by its title, with a description, actions, and the loading, empty and error states every data card needs. Put a DataTable, a ComparisonTable or anything else in it.ChartCard(rolechart-card): a DashboardCard around a DataChart (every DataChart prop passes through). The title names the chart for a screen reader too.DataTable(rolecomputed-table): rows the page computed (a summary, a breakdown, a report): sorting, a sticky header and first column, CSV and XLSX export of every row in the order shown, and only the rows in view rendered past 100, so 10,000 rows scroll smoothly. A resource's rows are a ResourceTable: it pages, filters and checks permissions through the API.ComparisonTable(rolecomparison-table): entities side by side: one column per entity, one row per metric, the best value of a metric marked (better: "higher"or"lower"). Use it to compare plans, regions or products.Accordion(roleaccordion): sections that open and close, after the WAI-ARIA accordion pattern (Down, Up, Home and End move between the headers). Use it where a page would write a raw<details>.MarkdownView(rolemarkdown): markdown shown as formatted HTML, sanitized: raw HTML shows as text unlessallowHtml, and never a script, an event handler or ajavascript:link. The parser and the sanitizer (marked, DOMPurify) load on first use.useResourceCounts(resources): the rows of each resource the user can read, as chart points (one list request each,page_size=1). The dashboard pageskarni buildwrites chart it.- ResourceDetail's
related={["deals", "people"]}: a tab per reverse relation, each a ResourceTable of the related rows filtered to the record. The backend publishes each model's reverse relations and the list parameter that filters by each one asx-karni-relatedon its list operation, so nothing is guessed. A name is the relation's name, its resource, orresource.fieldwhen two relations lead to one resource.
Their sizes are tokens: --karni-dashboard-gap (the space between cards),
--karni-data-table-max-height (the box DataTable and ComparisonTable scroll inside:
keep it a length, since DataTable needs a height to render only the rows in view) and
--karni-data-table-row-height. karni ui detect lists them.
An example page¶
EventHub's venue overview (examples/eventhub/frontend/src/pages/venue-overview.tsx, 47 lines)
computes its rows from one list request and lays them out with a DashboardGrid:
import { ChartCard, ComparisonTable, DashboardCard, DashboardGrid, DataTable } from "@karni/ui";
import { Page, useResourceList } from "@karni/ui";
type Venue = { id: string; name: string; city: string; capacity: number };
type City = { city: string; venues: number; seats: number };
const columns = [
{ key: "city", header: "City" },
{ key: "venues", header: "Venues" },
{ key: "seats", header: "Seats" },
];
const metrics = [
{ key: "city", label: "City" },
{ key: "capacity", label: "Seats", better: "higher" as const },
];
/** Seats by venue and by city: rows the page computes from one list request. */
export default function VenueOverviewPage() {
const venues = useResourceList<Venue>("venues", { pageSize: 100, ordering: "-capacity" });
const rows = venues.data?.results ?? [];
const top = rows.slice(0, 3);
const byCity = new Map<string, City>();
for (const { city, capacity } of rows) {
const seen = byCity.get(city) ?? { city, venues: 0, seats: 0 };
byCity.set(city, { city, venues: seen.venues + 1, seats: seen.seats + capacity });
}
const state = { loading: venues.isPending, error: venues.error, onRetry: venues.refetch };
return (
<Page title="Venues" description="Seats by venue and by city.">
<DashboardGrid>
<ChartCard
title="Seats per venue"
kind="bar"
span={2}
{...state}
data={rows.map((venue) => ({ label: venue.name, value: venue.capacity }))}
/>
<DashboardCard title="Largest venues" {...state} empty={rows.length === 0}>
<ComparisonTable caption="Largest venues" entities={top} metrics={metrics} />
</DashboardCard>
<DashboardCard title="Cities" span="full" {...state} empty={rows.length === 0}>
<DataTable caption="Cities" columns={columns} rows={[...byCity.values()]} />
</DashboardCard>
</DashboardGrid>
</Page>
);
}
Field groups and column sets (experimental)¶
Experimental
Karni.field_groups, field_group_layout and column_sets, their
x-karni-field-groups and x-karni-column-sets extensions, the fieldGroups and
groupLayout props of ResourceForm and ResourceDetail, ResourceTable's columnSets,
columnSet and onColumnSetChange, and the FieldGroupDef, FieldGroupLayout,
FieldGroupsDef, ColumnSetDef and ColumnSetsDef types are
experimental.
A model with a hundred columns and a dozen long markdown sections makes a generated form or detail page one endless list, and its table a hundred columns. Declare the layout on the model and every screen follows, with no page code:
from karni.fields import MarkdownField, MoneyField
class Product(BaseModel):
name = models.CharField(max_length=200)
summary = MarkdownField(blank=True)
price = MoneyField(currency="EUR")
cost = MoneyField(currency="EUR")
class Karni:
field_groups = {"Overview": ["name", "summary"], "Financials": ["price", "cost"]}
field_group_layout = "tabs" # or "sections", the default
column_sets = {
"default": ["name", "price"],
"financial": ["name", "price", "cost"],
}
- Field groups. ResourceForm shows each group as a fieldset with its legend,
ResourceDetail as a section with a heading, and the admin as a fieldset. The groups
keep the declaration's order, and the fields in no group come last, under Other. As
tabs, a tab with a failing field is marked, and moving focus to a field (the error
summary, a failed submit) opens its tab.
fieldGroups={false}shows one list, andfieldGroups={[...]}orgroupLayoutreplace the model's in one screen. - Column sets. ResourceTable gets a column set menu, one choice per set. The
set named
defaultshows first, else the first set, and the user's choice is remembered per user and table in the browser.columnSetandonColumnSetChangecontrol it, andcolumnSets={false}shows every derived column.columnsoverrides still apply to a set's columns. - MarkdownField. ResourceForm edits it with Write and Preview tabs (the preview is
MarkdownView), ResourceDetail shows it formatted and sanitized across the width, and
it is no default table column (a column set or
columnscan name it: it shows a one-line excerpt). See typed fields.
The backend publishes both on the model's list operation, limited to the fields the user's role may read, so a hidden field is never named:
"x-karni-field-groups": {"layout": "tabs", "groups": [
{"label": "Overview", "fields": ["name", "summary"]},
{"label": "Financials", "fields": ["price", "cost"]}
]},
"x-karni-column-sets": {"default": "default", "sets": [
{"name": "default", "label": "Default", "columns": ["name", "price"]},
{"name": "financial", "label": "Financial", "columns": ["name", "price", "cost"]}
]}
karni check refuses a malformed declaration (karni.E550, karni.E553), a group or
set that names a field the model does not have (karni.E551) and a field in two groups
(karni.E552), naming the model, the group or set, and the field. In karni.yaml an
entity's groups and column_sets write them (the app spec).
A 120-field test model with twelve markdown sections keeps these budgets: a list page of 25 rows under 200,000 bytes of JSON and a detail under 8,000 (the API suite), and ResourceForm under 1,000 ms and ResourceDetail under 600 ms to render in jsdom (the UI suite).
Names, links and rights on resource pages (experimental)¶
How a related row is named¶
A table cell or a detail value that points at another row shows that row's
name, never its id. The model says which field names its rows with
class Karni: label = "number" (an order shows as 1021, not as its
buyer's email). Without it, the first of name, title, label and
email is taken. A relation to the user model shows the person's name
(first and last name, else the email): ResourceTable and ResourceDetail
expand it on their own.
An app turns those names into links once at startup:
import { registerRecordLink, setRecordNavigate } from "@karni/ui";
registerRecordLink("orders", (row) => `/orders/${String(row.number)}`);
setRecordNavigate((to) => router.history.push(to));
getRowLabel on ResourceTable and fields on ResourceDetail still render
a value any other way.
Only the buttons a role may use¶
/me/ lists the permission keys the signed-in person holds
(permissions: ["shop.product:add", ...]), so ResourceTable and
ResourceDetail offer New, Edit, Delete and Import only to a role whose
grants allow them: a reader sees no button that ends in "You can't". The
pages karni build writes pass onCreate and onEdit, so they follow the
same rule. The server checks every write again.
A list whose resource takes imports (every Karni viewset) has an Import
button for those who may create rows: it opens ResourceImport above the table
(upload a CSV or XLSX file, check the preview with each row's problems,
commit), and the table reads its rows again afterwards. importable={false}
hides it.
bulkEdit={["price", "stock", "active"]} (experimental) adds a "Select rows,
then set … to …" line above the table and a bulk action that saves that value
on every selected row, each through the row's own update, so its rules and
history apply and a row the server refuses is marked with the reason. It
shows to roles that may update rows.
Primitives¶
Styled Radix parts and basics. Each one always merges className and forwards refs.
Button, Checkbox, Dashboard, DashboardTiles, DemoNoticeBody, DemoSignInPrompt, DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuPortal, DropdownMenuSeparator, DropdownMenuTrigger, EmailTemplateEditor, EmptyValue, ErrorState, Input, KarniPrimitivesProvider, Label, PendingButton, PermissionDenied, RecordLink, Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectRoot, SelectSeparator, SelectTrigger, SelectValue, Skeleton, Switch, Tabs, TabsContent, TabsList, TabsTrigger, Textarea, ThemeProvider, ThemeToggle
Hooks¶
useAggregate: Experimental. Grouped counts and sums of a resource (GET /<resource>/aggregate/):{ groupBy, metric, value, top, stack, series, filters, search }→{ categories, series }, which<DataChart aggregate>reads directly.useAudience: Experimental. Who is looking:loading,visitor,customer(only the family'scustomerrole) orstaff(any other role).useAuth:{ user, status, login(email, password), logout, refresh }fromAuthProvider, and (experimental){ terms, termsRequired, acceptTerms(client) }for terms acceptance.useBusiness: Experimental. The business's public details (GET /preferences/public/): name, address, phone, email, currency, logo.useChangeHistory: One row's field-level change history (GET /<resource>/<id>/history/, audited models).useDashboardTiles: See the package README.useDelayedFlag: See the package README.useDemo: See the package README.useGlobalSearch: Experimental.{ q, models, limit }→{ query, groups: [{ resource, label, hits: [{ resource, id, title, subtitle, score }] }] }: cross-model search (GET /search/), each model under its own list access. A query underminLength(2) sends nothing.useImportActions:upload,preview(the dry run) andcommitmutations of an import.useImportDescribe: The importable fields of a resource and the user's remembered column mapping.useImportJob: One import job's state. It polls while the backend previews or commits it.useInboxUnread: Experimental. The signed-in person's unread count (GET /inbox/unread/), read again every minute;nullwhile the inbox is off.useKarniClient: TheKarniClientbehind every hook, withclient.request(path, { method, body, query })for custom actions.useKarniPrimitives: See the package README.useMenu: Experimental. The entries of one named menu (GET /navigation/?menu=public) the signed-in person sees.useNavigation: Experimental. The menu the signed-in user gets (GET /navigation/, Django'sKARNI_NAVIGATION):{ items }, each{ label, icon, route, children }, cached per user.{ menu: "public" }reads a named menu.<Layout navSource="server">renders it.useOnlineStatus: See the package README.useOtpLogin: Experimental.{ step, send(email), verify(code), resend, back, status, error, cooldown, length }: sign in with a code sent by email (POST <authBasePath>/otp/send/, thenotp/verify/).usePageMeta: See the package README.usePermission:{ hasRole(...names), isAuthenticated }for gating UI on roles.usePersonFacts: Experimental. The person facts the installed parts contribute (GET /people/facts/):[{ name, label, kind, source }].useResourceAccessForest: Experimental. The requester's access forest of a tree resource (GET /<resource>/access/?permission=):{ results, all, truncated }, the granted nodes with their ancestors and every other root, each withgranted.TreeView'saccessshows it.useResourceAncestors: Experimental. The nodes above a tree node, root first (GET /<resource>/<id>/ancestors/).useResourceChildren: Experimental. One page of a tree node's children (GET /<resource>/<id>/children/).useResourceCounts: Experimental.{ data, loading, error, refetch }: the rows of each resource the user can read, as chart points (one list request each withpage_size=1).useResourceFacets: Experimental. Rows per node of one taxonomy under the list's filters (GET /<resource>/facets/?taxonomy=&rollup=):{ taxonomy, rollup, results }, each node{ id, label, parent, count }.FacetPanelshows it.useResourceItem: One row by id, optionally expanded.useResourceList: A page of a resource:{ page, pageSize, ordering, search, filters, expand }→ DRF's{ count, next, previous, results }.useResourceMutations:create,updateandremovefor a resource. On success they invalidate the resource's queries.useResourceSchemaIfKnown: Experimental. One resource's parsed schema when it is known, elseundefined: never throws, and reads nothing outside aKarniProvider.useResourceTree: Experimental. The nested nodes of a tree resource (GET /<resource>/tree/?root=&depth=):{ results, truncated }, each node withhas_childrenandchildren(nulluntil loaded).useSchema: The parsed OpenAPI schema of one resource (fields, operations, access).useSiteName: Experimental. The business's name from Settings, Details, else the page title the app started with.useSocialLogin: Experimental.{ signIn(idToken, { nonce, name }), status, error, reset }: sign in with a Google, Microsoft or Apple ID token the app got from the provider's SDK (POST <authBasePath>/social/<provider>/).useTheme: See the package README.useTimeline: Experimental. One timeline a page at a time (GET /timeline/?person=or?subject=, cursor paging,kinds).useToast: Show a toast through the mountedToaster.useTreeMutations: Experimental.move({ id, parent, position })(POST /<resource>/<id>/move/) andremoveBranch(id)(DELETE ?branch=true) for a tree resource.useUnsavedChangesGuard:{ dirty, setDirty, isDirty, shouldBlock }for warning before leaving a dirty form. GiveshouldBlockto your router's blocker andsetDirtyto ResourceForm'sonDirtyChange.
Component roles¶
Every top-level component claims one semantic role. karni make component refuses a
role that another component holds (compose it instead), and karni context lists the roles.
| Role | Component |
|---|---|
accordion |
Accordion |
async-select |
ResourceSelect |
auth-guard |
AuthGuard |
change-history |
ChangeHistory |
chart |
DataChart |
chart-card |
ChartCard |
code-sign-in |
OtpLoginForm |
comparison-table |
ComparisonTable |
computed-table |
DataTable |
dashboard |
Dashboard |
dashboard-grid |
DashboardGrid |
dashboard-tiles |
DashboardTiles |
data-table |
ResourceTable |
demo-notice |
DemoNotice |
detail-view |
ResourceDetail |
empty-state |
EmptyState |
error-state |
ErrorState |
facet-panel |
FacetPanel |
family-layout |
FamilyLayout |
file-upload |
FileUpload |
global-search |
GlobalSearch |
layout-shell |
Layout |
login-form |
LoginForm |
markdown |
MarkdownView |
modal |
Modal |
page-shell |
Page |
permission-denied |
PermissionDenied |
resource-board |
ResourceBoard |
resource-calendar |
ResourceCalendar |
resource-form |
ResourceForm |
resource-grid |
ResourceGrid |
resource-import |
ResourceImport |
social-sign-in |
SocialButton |
stat |
Stat |
terms-gate |
TermsGate |
theme-toggle |
ThemeToggle |
toast |
Toaster |
tree-breadcrumb |
TreeBreadcrumb |
tree-select |
TreeSelect |
tree-view |
TreeView |