{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"resource-index","title":"Searchable resource index","type":"registry:block","description":"Filter products with status tabs, sort columns, search by title or SKU, trigger row quick actions, and paginate natively. Preview: https://counterblocks.site/blocks/resource-index Installs app/components/resource-index.tsx with @shopify/polaris-types@2.0.0 for TypeScript. Uses the host app's React and Shopify App Home Polaris 2.0 web components.","meta":{"previewUrl":"https://counterblocks.site/blocks/resource-index","version":"0.4.0"},"devDependencies":["@shopify/polaris-types@2.0.0"],"files":[{"path":"src/blocks/resource-index.tsx","type":"registry:file","target":"app/components/resource-index.tsx","content":"import { useEffect, useId, useRef, type ReactNode } from \"react\";\n\nexport type ResourceIndexSortDirection = \"asc\" | \"desc\";\n\nexport interface ResourceIndexSort {\n  columnId: string;\n  direction: ResourceIndexSortDirection;\n}\n\nexport interface ResourceIndexTab {\n  id: string;\n  label: string;\n  count?: number;\n}\n\nexport type ResourceIndexRowAction = {\n  id: string;\n  label: string;\n  icon?: HTMLElementTagNameMap[\"s-button\"][\"icon\"];\n  tone?: \"auto\" | \"critical\";\n  disabled?: boolean;\n} & (\n  | { href: string; onAction?: never }\n  | { onAction: () => void; href?: never }\n);\n\nexport interface ResourceIndexColumn<RecordType> {\n  id: string;\n  heading: string;\n  render: (record: RecordType) => ReactNode;\n  listSlot?: \"primary\" | \"secondary\" | \"inline\" | \"labeled\" | \"kicker\";\n  format?: \"base\" | \"currency\" | \"numeric\";\n  sortable?: boolean;\n  sortLabels?: { asc: string; desc: string };\n}\n\nexport interface ResourceIndexPagination {\n  hasPrevious?: boolean;\n  hasNext?: boolean;\n  onPrevious: () => void;\n  onNext: () => void;\n  label?: string;\n}\n\nexport interface ResourceIndexProps<RecordType> {\n  records: readonly RecordType[];\n  getRecordId: (record: RecordType) => string;\n  columns: readonly [\n    ResourceIndexColumn<RecordType>,\n    ...ResourceIndexColumn<RecordType>[],\n  ];\n  query: string;\n  onQueryChange: (query: string) => void;\n  heading?: string;\n  headerActions?: ReactNode;\n  tabs?: readonly ResourceIndexTab[];\n  activeTab?: string;\n  onTabChange?: (tabId: string) => void;\n  sort?: ResourceIndexSort;\n  onSortChange?: (sort: ResourceIndexSort) => void;\n  getRowClickDelegate?: (record: RecordType) => string | undefined;\n  getRowLabel?: (record: RecordType) => string;\n  rowActions?: (record: RecordType) => readonly ResourceIndexRowAction[];\n  emptyHeading?: string;\n  emptyContent?: ReactNode;\n  emptyAction?: { label: string; onAction: () => void };\n  emptyFilterRecovery?: { label: string; onClear: () => void };\n  toolbar?: ReactNode;\n  pagination?: ResourceIndexPagination;\n  footer?: ReactNode;\n  totalCount?: number;\n  sourceCount?: number;\n  searchLabel?: string;\n  loading?: boolean;\n}\n\nexport function ResourceIndex<RecordType>({\n  records,\n  getRecordId,\n  columns,\n  query,\n  onQueryChange,\n  heading,\n  headerActions,\n  tabs,\n  activeTab,\n  onTabChange,\n  sort,\n  onSortChange,\n  getRowClickDelegate,\n  getRowLabel,\n  rowActions,\n  emptyHeading,\n  emptyContent,\n  emptyAction,\n  emptyFilterRecovery,\n  toolbar,\n  pagination,\n  footer,\n  totalCount = records.length,\n  sourceCount,\n  searchLabel = \"Search records\",\n  loading = false,\n}: ResourceIndexProps<RecordType>) {\n  const idBase = useId().replace(/[^a-zA-Z0-9_-]/g, \"\");\n  const sortPopoverId = `resource-sort-${idBase}`;\n  const tableRef = useRef<HTMLElementTagNameMap[\"s-table\"]>(null);\n  const searchField = useRef<HTMLElementTagNameMap[\"s-search-field\"]>(null);\n  const onQueryChangeRef = useRef(onQueryChange);\n\n  useEffect(() => {\n    onQueryChangeRef.current = onQueryChange;\n  }, [onQueryChange]);\n\n  useEffect(() => {\n    const field = searchField.current;\n    if (!field) return;\n\n    let active = true;\n    const sync = () => {\n      if (active && field.value !== query) field.value = query;\n    };\n    if (customElements.get(\"s-search-field\")) sync();\n    else void customElements.whenDefined(\"s-search-field\").then(sync);\n\n    return () => {\n      active = false;\n    };\n  }, [query]);\n\n  useEffect(() => {\n    const field = searchField.current;\n    if (!field) return;\n\n    // React 18 does not wire custom-element events reliably through JSX props alone.\n    const handleInput = () => {\n      onQueryChangeRef.current(field.value);\n    };\n    field.addEventListener(\"input\", handleInput);\n    return () => field.removeEventListener(\"input\", handleInput);\n  }, []);\n\n  useEffect(() => {\n    const table = tableRef.current;\n    if (!table || !pagination) return;\n\n    const handlePrevious = () => pagination.onPrevious();\n    const handleNext = () => pagination.onNext();\n    table.addEventListener(\"previouspage\", handlePrevious);\n    table.addEventListener(\"nextpage\", handleNext);\n    return () => {\n      table.removeEventListener(\"previouspage\", handlePrevious);\n      table.removeEventListener(\"nextpage\", handleNext);\n    };\n  }, [pagination]);\n\n  const sortableColumns = columns.filter((column) => column.sortable);\n  const sortOptions = sortableColumns.flatMap((column) =>\n    ([\"asc\", \"desc\"] as const).map((direction) => ({\n      value: `${column.id}:${direction}`,\n      columnId: column.id,\n      direction,\n      label: direction === \"asc\"\n        ? column.sortLabels?.asc ?? `${column.heading} (A–Z)`\n        : column.sortLabels?.desc ?? `${column.heading} (Z–A)`,\n    })),\n  );\n  const activeSortValue = sort ? `${sort.columnId}:${sort.direction}` : \"\";\n  const canSort = sortOptions.length > 0 && Boolean(onSortChange);\n  const noMatches = sourceCount !== 0 && Boolean(emptyFilterRecovery || query.trim());\n\n  let message = `${totalCount} ${totalCount === 1 ? \"result\" : \"results\"}`;\n  if (loading) {\n    message = \"Loading records…\";\n  } else if (records.length === 0) {\n    message = noMatches && emptyFilterRecovery\n      ? \"No records match the current filters.\"\n      : noMatches\n        ? \"No matching records. Try another search.\"\n        : \"No records yet.\";\n  }\n\n  return (\n    <s-section heading={heading} padding=\"none\">\n      {headerActions}\n      <s-table\n        ref={tableRef}\n        loading={loading || undefined}\n        paginate={Boolean(pagination) || undefined}\n        hasPreviousPage={pagination?.hasPrevious || undefined}\n        hasNextPage={pagination?.hasNext || undefined}\n      >\n        <s-box slot=\"filters\" padding=\"base\">\n          <s-stack gap=\"small\">\n            {tabs && tabs.length > 0 && onTabChange && (\n              <div\n                style={{\n                  display: \"flex\",\n                  alignItems: \"center\",\n                  gap: \"0.25rem\",\n                  overflowX: \"auto\",\n                  scrollbarWidth: \"none\",\n                  whiteSpace: \"nowrap\",\n                }}\n              >\n                {tabs.map((tab) => (\n                  <div key={tab.id} style={{ flex: \"0 0 auto\" }}>\n                    <TabPressButton\n                      pressed={activeTab === tab.id}\n                      onSelect={() => onTabChange(tab.id)}\n                    >\n                      {tab.count !== undefined ? `${tab.label} (${tab.count.toLocaleString()})` : tab.label}\n                    </TabPressButton>\n                  </div>\n                ))}\n              </div>\n            )}\n            <s-grid\n              gridTemplateColumns={canSort ? \"minmax(0, 1fr) auto\" : \"minmax(0, 1fr)\"}\n              gap=\"small\"\n              alignItems=\"center\"\n            >\n              <s-search-field\n                ref={searchField}\n                labelAccessibilityVisibility=\"exclusive\"\n                placeholder={searchLabel}\n                label={searchLabel}\n                value={query}\n              />\n              {canSort && onSortChange && (\n                <s-box>\n                  <s-button\n                    variant=\"secondary\"\n                    icon=\"sort\"\n                    commandFor={sortPopoverId}\n                    command=\"--toggle\"\n                    accessibilityLabel=\"Sort records\"\n                  >\n                    Sort\n                  </s-button>\n                  <s-popover id={sortPopoverId}>\n                    <s-box padding=\"base\">\n                      <SortChoiceList\n                        options={sortOptions}\n                        activeValue={activeSortValue}\n                        onSelect={(nextValue) => {\n                          const chosen = sortOptions.find((option) => option.value === nextValue);\n                          if (!chosen) return;\n                          onSortChange({ columnId: chosen.columnId, direction: chosen.direction });\n                        }}\n                      />\n                    </s-box>\n                  </s-popover>\n                </s-box>\n              )}\n            </s-grid>\n            {toolbar}\n            <s-stack direction=\"inline\" justifyContent=\"space-between\" alignItems=\"center\" gap=\"small\">\n              <output>\n                <s-text color=\"subdued\">{message}</s-text>\n              </output>\n              {pagination?.label && <s-text color=\"subdued\">{pagination.label}</s-text>}\n            </s-stack>\n          </s-stack>\n        </s-box>\n        <s-table-header-row>\n          {columns.map((column, index) => {\n            const isSorted = sort?.columnId === column.id;\n            const nextDirection: ResourceIndexSortDirection =\n              isSorted && sort.direction === \"asc\" ? \"desc\" : \"asc\";\n            return (\n              <s-table-header\n                key={column.id}\n                listSlot={column.listSlot ?? (index === 0 ? \"primary\" : \"labeled\")}\n                format={column.format}\n              >\n                {column.sortable && onSortChange ? (\n                  <s-clickable\n                    inlineSize=\"100%\"\n                    accessibilityLabel={isSorted\n                      ? `${column.heading}, sorted ${sort.direction === \"asc\" ? \"ascending\" : \"descending\"}. Switch to ${nextDirection === \"asc\" ? \"ascending\" : \"descending\"}`\n                      : `Sort by ${column.heading}, ascending`}\n                    onClick={() => onSortChange({ columnId: column.id, direction: nextDirection })}\n                  >\n                    <s-stack\n                      direction=\"inline\"\n                      alignItems=\"center\"\n                      justifyContent={column.format === \"currency\" || column.format === \"numeric\" ? \"end\" : \"start\"}\n                      gap=\"small-200\"\n                    >\n                      <span>{column.heading}</span>\n                      {isSorted && (\n                        <s-icon type={sort.direction === \"asc\" ? \"arrow-up\" : \"arrow-down\"} size=\"small\" />\n                      )}\n                    </s-stack>\n                  </s-clickable>\n                ) : column.heading}\n              </s-table-header>\n            );\n          })}\n          {rowActions && (\n            <s-table-header listSlot=\"inline\">\n              <s-text accessibilityVisibility=\"exclusive\">Actions</s-text>\n            </s-table-header>\n          )}\n        </s-table-header-row>\n        <s-table-body>\n          {records.length > 0 ? (\n            records.map((record, index) => {\n              const recordId = getRecordId(record);\n              const actions = rowActions?.(record) ?? [];\n              const menuId = `row-actions-${idBase}-${index}`;\n              const rowLabel = getRowLabel?.(record) ?? `row ${index + 1}`;\n              return (\n                <s-table-row key={recordId} clickDelegate={getRowClickDelegate?.(record)}>\n                  {columns.map((column) => (\n                    <s-table-cell key={column.id}>{column.render(record)}</s-table-cell>\n                  ))}\n                  {rowActions && (\n                    <s-table-cell>\n                      {actions.length > 0 && (\n                        <>\n                          <s-button\n                            variant=\"tertiary\"\n                            icon=\"menu-horizontal\"\n                            accessibilityLabel={`Actions for ${rowLabel}`}\n                            commandFor={menuId}\n                            command=\"--toggle\"\n                          />\n                          <s-menu id={menuId} accessibilityLabel={`Actions for ${rowLabel}`}>\n                            {actions.map((action) => (\n                              \"href\" in action && action.href !== undefined ? (\n                                <s-button\n                                  key={action.id}\n                                  icon={action.icon}\n                                  tone={action.tone}\n                                  href={action.href}\n                                  disabled={action.disabled || undefined}\n                                >\n                                  {action.label}\n                                </s-button>\n                              ) : (\n                                <s-button\n                                  key={action.id}\n                                  icon={action.icon}\n                                  tone={action.tone}\n                                  disabled={action.disabled || undefined}\n                                  onClick={action.onAction}\n                                >\n                                  {action.label}\n                                </s-button>\n                              )\n                            ))}\n                          </s-menu>\n                        </>\n                      )}\n                    </s-table-cell>\n                  )}\n                </s-table-row>\n              );\n            })\n          ) : !loading ? (\n            <s-empty-state heading={noMatches ? \"No matching records\" : (emptyHeading ?? \"No records yet\")}>\n              <s-icon slot=\"graphic\" type={noMatches ? \"search\" : \"product\"} />\n              {noMatches ? (\n                <>\n                  <s-text slot=\"subheading\">\n                    {emptyFilterRecovery\n                      ? \"Try adjusting or clearing your filters.\"\n                      : \"Try another search term or clear your search.\"}\n                  </s-text>\n                  <s-button\n                    slot=\"primary-action\"\n                    variant=\"primary\"\n                    onClick={() => {\n                      if (emptyFilterRecovery) emptyFilterRecovery.onClear();\n                      else onQueryChange(\"\");\n                      searchField.current?.focus();\n                    }}\n                  >\n                    {emptyFilterRecovery?.label ?? \"Clear search\"}\n                  </s-button>\n                </>\n              ) : (\n                <>\n                  {typeof emptyContent === \"string\"\n                    ? <s-text slot=\"subheading\">{emptyContent}</s-text>\n                    : emptyContent}\n                  {emptyAction && (\n                    <s-button\n                      slot=\"primary-action\"\n                      variant=\"primary\"\n                      onClick={emptyAction.onAction}\n                    >\n                      {emptyAction.label}\n                    </s-button>\n                  )}\n                </>\n              )}\n            </s-empty-state>\n          ) : null}\n        </s-table-body>\n      </s-table>\n      {footer && <s-box padding=\"base\">{footer}</s-box>}\n    </s-section>\n  );\n}\n\nfunction TabPressButton({\n  pressed,\n  onSelect,\n  children,\n}: {\n  pressed: boolean;\n  onSelect: () => void;\n  children: ReactNode;\n}) {\n  const ref = useRef<HTMLElementTagNameMap[\"s-press-button\"]>(null);\n\n  useEffect(() => {\n    const button = ref.current;\n    if (!button) return;\n\n    let active = true;\n    const sync = () => {\n      if (active) button.pressed = pressed;\n    };\n    if (customElements.get(\"s-press-button\")) sync();\n    else void customElements.whenDefined(\"s-press-button\").then(sync);\n\n    const handleClick = () => {\n      button.pressed = pressed;\n      onSelect();\n    };\n    button.addEventListener(\"click\", handleClick);\n    return () => {\n      active = false;\n      button.removeEventListener(\"click\", handleClick);\n    };\n  }, [onSelect, pressed]);\n\n  return (\n    <s-press-button ref={ref} variant=\"tertiary\" pressed={pressed || undefined}>\n      {children}\n    </s-press-button>\n  );\n}\n\nfunction SortChoiceList({\n  options,\n  activeValue,\n  onSelect,\n}: {\n  options: readonly { value: string; label: string }[];\n  activeValue: string;\n  onSelect: (value: string) => void;\n}) {\n  const listRef = useRef<HTMLElementTagNameMap[\"s-choice-list\"]>(null);\n  const name = useId();\n  const onSelectRef = useRef(onSelect);\n\n  useEffect(() => {\n    onSelectRef.current = onSelect;\n  }, [onSelect]);\n\n  useEffect(() => {\n    const list = listRef.current;\n    if (!list) return;\n\n    let active = true;\n    const sync = () => {\n      if (active) list.values = activeValue ? [activeValue] : [];\n    };\n    if (customElements.get(\"s-choice-list\")) sync();\n    else void customElements.whenDefined(\"s-choice-list\").then(sync);\n\n    return () => {\n      active = false;\n    };\n  }, [activeValue]);\n\n  useEffect(() => {\n    const list = listRef.current;\n    if (!list) return;\n\n    const handleChange = () => {\n      const next = list.values[0];\n      if (next && next !== activeValue) {\n        onSelectRef.current(next);\n      }\n    };\n    list.addEventListener(\"change\", handleChange);\n    return () => list.removeEventListener(\"change\", handleChange);\n  }, [activeValue]);\n\n  return (\n    <s-choice-list\n      ref={listRef}\n      label=\"Sort by\"\n      name={name}\n      values={activeValue ? [activeValue] : []}\n    >\n      {options.map((option) => (\n        <s-choice\n          key={option.value}\n          value={option.value}\n          selected={option.value === activeValue || undefined}\n        >\n          {option.label}\n        </s-choice>\n      ))}\n    </s-choice-list>\n  );\n}\n"}],"docs":"Connect the block to your records with the example at https://counterblocks.site/blocks/resource-index"}