{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "pages-record-list",
  "title": "Record list page",
  "description": "The records of the register's record entity: cards for a holder, a table for staff, with search, a create action and cursor paging.",
  "dependencies": [
    "@registrystack/app-runtime@~0.43.0-next.0",
    "lucide-react@1.43.0"
  ],
  "registryDependencies": [
    "@registrystack/pages-record",
    "@registrystack/pages-content",
    "@registrystack/pages-register-routes",
    "@registrystack/pages-landing-starts",
    "@registrystack/pages-find-record",
    "@registrystack/record-list",
    "@registrystack/record-filters",
    "@registrystack/record-table",
    "@registrystack/shell-page-heading",
    "@registrystack/shell-loading",
    "@registrystack/shell-error-panel",
    "@registrystack/shell-empty-state",
    "@registrystack/shell-live-announcer",
    "@registrystack/ui-button",
    "@registrystack/lib-format",
    "@registrystack/shell-routing",
    "@registrystack/pages-record-route-query",
    "@registrystack/lib-content"
  ],
  "files": [
    {
      "path": "pages/record-list-page.tsx",
      "content": "import { useEffect, useState } from \"react\";\nimport { Plus } from \"lucide-react\";\nimport type { EntityModel, RecordView } from \"@registrystack/app-runtime\";\nimport { useAuthority, useModel, useRecords } from \"@registrystack/app-runtime/react\";\nimport { Button } from \"@/components/ui/button\";\nimport { PageHeading } from \"@/blocks/shell/page-heading\";\nimport { Loading } from \"@/blocks/shell/loading\";\nimport { ErrorPanel } from \"@/blocks/shell/error-panel\";\nimport { EmptyState } from \"@/blocks/shell/empty-state\";\nimport { navigate, splitRoute, useRoute } from \"@/blocks/shell/routing\";\nimport { LiveAnnouncer, useAnnouncement } from \"@/blocks/shell/live-announcer\";\nimport { RecordCards, RecordPager } from \"@/blocks/record/record-list\";\nimport { RecordFilterBar, RecordSearchForm } from \"@/blocks/record/record-filters\";\nimport { RecordTable } from \"@/blocks/record/record-table\";\nimport { useLocale } from \"@/blocks/lib/content\";\nimport {\n  createWords,\n  listTitle,\n  usePagesContent,\n} from \"@/blocks/pages/pages-content\";\nimport {\n  listQueryOf,\n  listRoute,\n  type ListQuery,\n} from \"@/blocks/pages/record-route-query\";\nimport { FindRecordPage } from \"@/blocks/pages/find-record-page\";\nimport { LandingStarts } from \"@/blocks/pages/landing-starts\";\nimport { useRegisterRoutes } from \"@/blocks/pages/register-routes\";\nimport {\n  entityRoutes,\n  fieldOf,\n  recordTitle,\n  RecordEntityGate,\n  UnavailableWrite,\n  type RegisterEntities,\n} from \"@/blocks/pages/record\";\n\n/**\n * The records of one record entity, the register's own when `entity` is left\n * out: cards for a holder, a table for staff. Columns, filters, search,\n * create and the governed actions whose result lands in these records come\n * from the session model and the list the host serves; nothing here names an\n * entity, a field or an action. Filters and the search live in the route's\n * query, so a link to a narrowed list is a plain link.\n */\nexport function RecordListPage({ entity }: { entity?: string }) {\n  const route = useRoute();\n  return (\n    <RecordEntityGate entity={entity}>\n      {(entities, model) =>\n        !model.operations.list &&\n        (model.operations.get || model.operations.lookup) ? (\n          // Another record type's find page starts empty.\n          <FindRecord key={model.id} entities={entities} entity={model} />\n        ) : (\n          // A new query starts the list from its first page.\n          <RecordList key={route} entities={entities} entity={model} />\n        )\n      }\n    </RecordEntityGate>\n  );\n}\n\n/** A session that may read an entity's records but not list them finds one. */\nfunction FindRecord({\n  entities,\n  entity,\n}: {\n  entities: RegisterEntities;\n  entity: EntityModel;\n}) {\n  const routes = entityRoutes(useRegisterRoutes(), entities, entity.id);\n  if (!routes) return <UnavailableWrite />;\n  return <FindRecordPage entity={entity} recordRoute={routes.record} />;\n}\n\nfunction RecordList({\n  entities,\n  entity,\n}: {\n  entities: RegisterEntities;\n  entity: EntityModel;\n}) {\n  const pages = usePagesContent(),\n    locale = useLocale(),\n    routes = entityRoutes(useRegisterRoutes(), entities, entity.id),\n    session = useAuthority();\n  const landing = useModel().data?.home;\n  const holder = session.holder;\n  const ownEntity = entity.id === entities.record.id;\n  // The full route, query included, so a start opened here returns to the\n  // list as narrowed.\n  const here = useRoute();\n  const { query: asked } = splitRoute(here);\n  const applied = listQueryOf(asked);\n  const [cursors, setCursors] = useState<(string | undefined)[]>([undefined]);\n  const cursor = cursors.at(-1);\n  const searchFields = entity.list.search;\n  // Without a multi-field search, one text box matches the first filter\n  // field that is not already a select.\n  const filterField = entity.list.filters.find(\n    (filter) => !fieldOf(entity, filter.field)?.options?.length,\n  )?.field;\n  const searchable = Boolean(searchFields?.length || filterField);\n  const filters = { ...applied.filters };\n  if (!searchFields?.length && filterField && applied.search)\n    filters[filterField] = applied.search;\n  const query = useRecords(\n    entity.id,\n    cursor\n      ? { cursor }\n      : {\n          ...(Object.keys(filters).length ? { filters } : {}),\n          ...(searchFields?.length && applied.search\n            ? { search: applied.search }\n            : {}),\n        },\n  );\n  const [announcement, announce] = useAnnouncement();\n  // A cursor the host no longer holds (a restarted session lost the cursor\n  // store) is recovered from, not reported: go back to the first page of the\n  // same list, keeping the filters and search.\n  const recovering = cursor !== undefined && query.cursorExpired;\n  useEffect(() => {\n    if (!recovering) return;\n    setCursors([undefined]);\n    announce(pages.listRecoveredAnnouncement);\n  }, [recovering]);\n  const narrowed = Object.keys(filters).length > 0 || Boolean(applied.search);\n  const show = (next: Partial<ListQuery>) => {\n    if (routes) navigate(listRoute(routes.records, next));\n  };\n  const create = query.data?.actions?.find(\n    (action) => action.name === \"create\" && action.entity === entity.id,\n  );\n  // A governed action is offered only where the app names a form for it.\n  const governed = (query.data?.actions ?? []).flatMap((action) =>\n    action.name === \"invoke\" &&\n    action.entity === entity.id &&\n    action.actionId &&\n    routes?.recordAction\n      ? [\n          {\n            id: action.actionId,\n            label: action.label ?? action.actionId,\n            href: `#${routes.recordAction(action.actionId)}`,\n          },\n        ]\n      : [],\n  );\n  const columns = entity.list.columns\n    .map((id) => fieldOf(entity, id))\n    .filter((field) => field !== undefined);\n  const linkColumn =\n    columns.find((field) => field.id === entity.title) ?? columns[0];\n  const title = listTitle(\n    pages,\n    holder ? \"ownRecordListTitle\" : \"recordListTitle\",\n    entity.pluralLabel,\n  );\n  if (!routes) return <UnavailableWrite />;\n  const recordHref = (record: RecordView) => `#${routes.record(record.id)}`;\n  return (\n    <>\n      <LiveAnnouncer message={announcement} />\n      <PageHeading\n        title={title}\n        description={holder ? pages.ownListDescription : pages.listDescription}\n        action={\n          (create || governed.length > 0) && (\n            <div className=\"actions\">\n              {create && (\n                <Button render={<a href={`#${routes.createRecord}`} />}>\n                  <Plus />\n                  {createWords(\n                    pages,\n                    ownEntity ? \"createRecord\" : \"addRecord\",\n                    create.label,\n                    entity.label,\n                    locale,\n                  )}\n                </Button>\n              )}\n              {governed.map((action) => (\n                <Button\n                  key={action.id}\n                  variant=\"outline\"\n                  render={<a href={action.href} />}\n                >\n                  {action.label}\n                </Button>\n              ))}\n            </div>\n          )\n        }\n      />\n      {landing?.entity === entity.id && landing.starts?.length ? (\n        <LandingStarts\n          entities={entities}\n          ids={landing.starts}\n          from={here}\n          shown={[\n            ...(create && routes ? [`#${routes.createRecord}`] : []),\n            ...governed.map((action) => action.href),\n          ]}\n        />\n      ) : null}\n      <RecordFilterBar\n        entity={entity}\n        allLabel={pages.filterAll}\n        applied={applied.filters}\n        onChange={(field, value) => {\n          const next = { ...applied.filters };\n          if (value === undefined) delete next[field];\n          else next[field] = value;\n          show({ filters: next, search: applied.search });\n        }}\n      />\n      {searchable && (\n        <RecordSearchForm\n          label={pages.searchLabel}\n          hint={searchFields?.length ? pages.searchWordsHint : pages.searchHint}\n          applied={applied.search}\n          onSearch={(value) =>\n            show({ filters: applied.filters, search: value })\n          }\n          onClear={() => show({ filters: applied.filters })}\n        />\n      )}\n      {query.isPending || recovering ? (\n        <Loading />\n      ) : query.error ? (\n        <ErrorPanel error={query.error} retry={() => void query.refetch()} />\n      ) : (\n        query.data && (\n          <>\n            {query.data.items.length === 0 ? (\n              <EmptyState title={holder ? pages.noOwnRecords : pages.noRecords}>\n                {narrowed\n                  ? pages.noSearchResults\n                  : holder\n                    ? pages.noOwnRecordsBody\n                    : pages.noStaffRecordsBody}\n              </EmptyState>\n            ) : holder ? (\n              <RecordCards\n                entity={entity}\n                records={query.data.items}\n                fields={columns\n                  .filter((field) => field.id !== entity.title)\n                  .map((field) => field.id)}\n                titleOf={(record) =>\n                  recordTitle(entity, record, locale) ?? entity.label\n                }\n                recordHref={recordHref}\n              />\n            ) : (\n              <RecordTable\n                caption={title}\n                columns={columns}\n                linkColumn={linkColumn}\n                records={query.data.items}\n                recordHref={recordHref}\n                viewLabel={(record) => recordTitle(entity, record, locale) ?? record.id}\n              />\n            )}\n            <RecordPager\n              nextCursor={query.data.nextCursor}\n              pageCount={cursors.length}\n              onPrevious={() => setCursors(cursors.slice(0, -1))}\n              onNext={(next) => setCursors([...cursors, next])}\n            />\n          </>\n        )\n      )}\n    </>\n  );\n}\n",
      "type": "registry:block",
      "target": "@components/pages/record-list-page.tsx"
    }
  ],
  "type": "registry:block"
}