Skip to content

@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 (role data-table)
  • ResourceForm (role resource-form)
  • ResourceDetail (role detail-view)
  • ResourceSelect (role async-select)
  • ChangeHistory (role change-history)
  • ResourceImport (role resource-import)
  • ResourceGrid (role resource-grid, experimental)
  • ResourceBoard (role resource-board, experimental)
  • ResourceCalendar (role resource-calendar, experimental)
  • TreeView (role tree-view, experimental)
  • TreeSelect (role tree-select, experimental)
  • TreeBreadcrumb (role tree-breadcrumb, experimental)
  • FacetPanel (role facet-panel, experimental)

App shell and pages

  • Layout (role layout-shell)
  • GlobalSearch (role global-search, experimental)
  • Page (role page-shell)
  • EmptyState (role empty-state)
  • Modal (role modal)
  • ModalClose
  • ModalTitle
  • ModalDescription
  • Toaster (role toast)
  • Stat (role stat)
  • DataChart (role chart)
  • FileUpload (role file-upload)
  • KarniMark

The family screens (one layout, home, people, inbox and search for every part)

  • FamilyLayout (role family-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

  • AuthProvider
  • AuthGuard (role auth-guard)
  • LoginForm (role login-form)
  • SocialButton (role social-sign-in, experimental)
  • OtpLoginForm (role code-sign-in, experimental)
  • TermsGate (role terms-gate, experimental)
  • DemoNotice (role demo-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 (role dashboard-grid): a responsive grid of cards: one column on phones, two on md screens, columns (2, 3 or 4) on xl. Each card takes a span (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 (role chart-card): a DashboardCard around a DataChart (every DataChart prop passes through). The title names the chart for a screen reader too.
  • DataTable (role computed-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 (role comparison-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 (role accordion): 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 (role markdown): markdown shown as formatted HTML, sanitized: raw HTML shows as text unless allowHtml, and never a script, an event handler or a javascript: 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 pages karni build writes 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 as x-karni-related on its list operation, so nothing is guessed. A name is the relation's name, its resource, or resource.field when 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, and fieldGroups={[...]} or groupLayout replace the model's in one screen.
  • Column sets. ResourceTable gets a column set menu, one choice per set. The set named default shows first, else the first set, and the user's choice is remembered per user and table in the browser. columnSet and onColumnSetChange control it, and columnSets={false} shows every derived column. columns overrides 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 columns can 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).

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's customer role) or staff (any other role).
  • useAuth: { user, status, login(email, password), logout, refresh } from AuthProvider, 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 under minLength (2) sends nothing.
  • useImportActions: upload, preview (the dry run) and commit mutations 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; null while the inbox is off.
  • useKarniClient: The KarniClient behind every hook, with client.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's KARNI_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/, then otp/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 with granted. TreeView's access shows 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 with page_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 }. FacetPanel shows 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, update and remove for a resource. On success they invalidate the resource's queries.
  • useResourceSchemaIfKnown: Experimental. One resource's parsed schema when it is known, else undefined: never throws, and reads nothing outside a KarniProvider.
  • useResourceTree: Experimental. The nested nodes of a tree resource (GET /<resource>/tree/?root=&depth=): { results, truncated }, each node with has_children and children (null until 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 mounted Toaster.
  • useTreeMutations: Experimental. move({ id, parent, position }) (POST /<resource>/<id>/move/) and removeBranch(id) (DELETE ?branch=true) for a tree resource.
  • useUnsavedChangesGuard: { dirty, setDirty, isDirty, shouldBlock } for warning before leaving a dirty form. Give shouldBlock to your router's blocker and setDirty to ResourceForm's onDirtyChange.

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