{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "collection-query",
  "title": "Collection Query",
  "description": "A Pages block that queries the starter Posts collection by category or manual selection and renders grid, list, or featured cards.",
  "registryDependencies": [
    "badge",
    "card"
  ],
  "files": [
    {
      "path": "payload-components/source/blocks/shared/PostCard.tsx",
      "content": "import Link from 'next/link'\nimport React from 'react'\n\nimport type { Post } from '@/payload-types'\n\nimport { Media } from '@/components/Media'\nimport { Badge } from '@/components/ui/badge'\nimport {\n  Card,\n  CardContent,\n  CardDescription,\n  CardHeader,\n  CardTitle,\n} from '@/components/ui/card'\nimport { cn } from '@/utilities/ui'\n\nexport type PostCardData = Pick<Post, 'categories' | 'meta' | 'publishedAt' | 'slug' | 'title'>\n\nexport function PostCard({\n  className,\n  post,\n  variant = 'grid',\n}: {\n  className?: string\n  post: PostCardData\n  variant?: 'featured' | 'grid' | 'list'\n}) {\n  const image = post.meta?.image\n  const description = post.meta?.description?.replace(/\\s+/g, ' ').trim()\n  const href = `/posts/${post.slug}`\n  const publishedAt = post.publishedAt ? new Date(post.publishedAt) : undefined\n  const categories = (post.categories ?? []).flatMap((category) =>\n    typeof category === 'object' && category?.title ? [category.title] : [],\n  )\n\n  return (\n    <Card\n      className={cn(\n        'group gap-0 overflow-hidden border-border/70 bg-card py-0 shadow-none transition-colors hover:border-foreground/25',\n        variant === 'list' && 'sm:grid sm:grid-cols-[14rem_minmax(0,1fr)]',\n        className,\n      )}\n    >\n      <div className={cn('overflow-hidden bg-muted', variant === 'featured' && 'lg:aspect-[2/1]')}>\n        {image && typeof image === 'object' ? (\n          <Media\n            imgClassName=\"aspect-[16/10] h-full w-full object-cover transition-transform duration-500 motion-reduce:transform-none group-hover:scale-[1.02]\"\n            resource={image}\n            size={variant === 'list' ? '14rem' : '(min-width: 1024px) 33vw, 100vw'}\n          />\n        ) : (\n          <div className=\"aspect-[16/10] bg-muted\" />\n        )}\n      </div>\n\n      <div className=\"flex min-w-0 flex-col\">\n        <CardHeader className=\"flex flex-col gap-3 p-5\">\n          <div className=\"flex flex-wrap items-center gap-2\">\n            {categories.slice(0, 2).map((category, index) => (\n              <Badge key={`${category}-${index}`} variant=\"outline\" className=\"font-normal\">\n                {category}\n              </Badge>\n            ))}\n            {publishedAt && !Number.isNaN(publishedAt.valueOf()) ? (\n              <time\n                className=\"text-xs text-muted-foreground\"\n                dateTime={publishedAt.toISOString()}\n              >\n                {new Intl.DateTimeFormat('en', {\n                  day: 'numeric',\n                  month: 'short',\n                  year: 'numeric',\n                  timeZone: 'UTC',\n                }).format(publishedAt)}\n              </time>\n            ) : null}\n          </div>\n          <CardTitle className=\"text-balance text-xl font-medium leading-snug tracking-title\">\n            <Link\n              className=\"rounded-sm outline-none transition-colors group-hover:text-brand focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2\"\n              href={href}\n            >\n              {post.title}\n            </Link>\n          </CardTitle>\n        </CardHeader>\n\n        {description ? (\n          <CardContent className=\"px-5 pb-5 pt-0\">\n            <CardDescription className=\"line-clamp-3 text-sm leading-6\">\n              {description}\n            </CardDescription>\n          </CardContent>\n        ) : null}\n      </div>\n    </Card>\n  )\n}\n",
      "type": "registry:file",
      "target": "~/src/blocks/shared/PostCard.tsx"
    },
    {
      "path": "payload-components/source/blocks/CollectionQuery/config.ts",
      "content": "import type { Block } from 'payload'\n\nexport const CollectionQuery: Block = {\n  slug: 'collectionQuery',\n  // Existing apps must migrate stored data before adopting this identifier:\n  // https://www.payload-components.xyz/docs/registry#installed-source-and-migrations\n  dbName: 'pc_col_que',\n  interfaceName: 'CollectionQueryBlock',\n  admin: {\n    group: 'Collection query',\n  },\n  fields: [\n    {\n      name: 'populateBy',\n      type: 'select',\n      defaultValue: 'collection',\n      options: [\n        { label: 'Latest posts', value: 'collection' },\n        { label: 'Manual selection', value: 'selection' },\n      ],\n      required: true,\n    },\n    {\n      name: 'categories',\n      type: 'relationship',\n      admin: {\n        condition: (_, siblingData) => siblingData.populateBy === 'collection',\n      },\n      hasMany: true,\n      relationTo: 'categories',\n    },\n    {\n      name: 'limit',\n      type: 'number',\n      admin: {\n        condition: (_, siblingData) => siblingData.populateBy === 'collection',\n        step: 1,\n      },\n      defaultValue: 6,\n      max: 24,\n      min: 1,\n      required: true,\n    },\n    {\n      name: 'sort',\n      type: 'select',\n      admin: {\n        condition: (_, siblingData) => siblingData.populateBy === 'collection',\n      },\n      defaultValue: '-publishedAt',\n      options: [\n        { label: 'Newest first', value: '-publishedAt' },\n        { label: 'Oldest first', value: 'publishedAt' },\n        { label: 'Title A–Z', value: 'title' },\n        { label: 'Title Z–A', value: '-title' },\n      ],\n      required: true,\n    },\n    {\n      name: 'selectedDocs',\n      type: 'relationship',\n      admin: {\n        condition: (_, siblingData) => siblingData.populateBy === 'selection',\n      },\n      hasMany: true,\n      relationTo: 'posts',\n    },\n    {\n      name: 'enablePagination',\n      type: 'checkbox',\n      defaultValue: false,\n      admin: { condition: (_, siblingData) => siblingData.populateBy === 'collection' },\n    },\n    {\n      name: 'enableFilters',\n      type: 'checkbox',\n      defaultValue: false,\n      admin: {\n        condition: (_, siblingData) => siblingData.populateBy === 'collection',\n        description:\n          'Show category links. Selecting categories above limits the available choices.',\n      },\n    },\n    {\n      name: 'queryKey',\n      type: 'text',\n      custom: { payloadComponents: { localization: 'global' } },\n      defaultValue: 'posts',\n      admin: {\n        description:\n          'Fallback URL namespace when rendering outside a saved Page block. Use a unique key per instance.',\n      },\n    },\n    {\n      name: 'emptyMessage',\n      type: 'text',\n      custom: { payloadComponents: { localization: 'localized' } },\n      defaultValue: 'No posts found. Try another category or check back soon.',\n    },\n    {\n      name: 'layout',\n      type: 'select',\n      defaultValue: 'grid',\n      options: [\n        { label: 'Grid', value: 'grid' },\n        { label: 'List', value: 'list' },\n        { label: 'Featured', value: 'featured' },\n      ],\n      required: true,\n    },\n  ],\n  labels: {\n    plural: 'Collection Query Blocks',\n    singular: 'Collection Query',\n  },\n}\n",
      "type": "registry:file",
      "target": "~/src/blocks/CollectionQuery/config.ts"
    },
    {
      "path": "payload-components/source/blocks/CollectionQuery/Component.tsx",
      "content": "import React from 'react'\nimport type { TypedLocale } from 'payload'\n\nimport type { CollectionQueryBlock as CollectionQueryBlockData } from '@/payload-types'\nimport { cn } from '@/utilities/ui'\n\nimport { CollectionBrowser } from './Browser'\nimport { queryCategories, queryPosts, type CollectionOptions } from './query'\nimport {\n  readCollectionRequest,\n  type CollectionRequest,\n  type CollectionSearchParams,\n} from './navigation'\n\ntype Props = CollectionQueryBlockData & {\n  id?: string\n  className?: string\n  disableInnerContainer?: boolean\n  locale?: TypedLocale\n  searchParams?: CollectionSearchParams\n}\n\nexport const CollectionQueryBlock: React.FC<Props> = async ({\n  className,\n  disableInnerContainer,\n  id,\n  layout = 'grid',\n  emptyMessage = 'No posts found. Try another category or check back soon.',\n  locale,\n  searchParams,\n  ...data\n}) => {\n  const options: CollectionOptions = {\n    categories: data.categories?.map((category) =>\n      typeof category === 'object' ? category.id : category,\n    ),\n    enableFilters: data.enableFilters,\n    enablePagination: data.enablePagination,\n    limit: data.limit,\n    populateBy: data.populateBy,\n    selectedDocs: data.selectedDocs?.map((post) => (typeof post === 'object' ? post.id : post)),\n    sort: data.sort,\n    locale,\n  }\n  const key = `collection-${id || data.queryKey || 'posts'}`\n  const params = new URLSearchParams()\n  for (const [name, value] of Object.entries(searchParams ?? {})) {\n    for (const entry of Array.isArray(value) ? value : value === undefined ? [] : [value]) {\n      params.append(name, entry)\n    }\n  }\n  const request = readCollectionRequest(params, key)\n  const [initial, categories] = await Promise.all([\n    queryPosts(options, request),\n    queryCategories(options),\n  ])\n\n  async function load(request: CollectionRequest) {\n    'use server'\n    return queryPosts(options, request)\n  }\n\n  return (\n    <section className={cn('container', className)} id={id ? `block-${id}` : undefined}>\n      <div className=\"contents\">\n        <CollectionBrowser\n          categories={categories}\n          disableInnerContainer={disableInnerContainer}\n          emptyMessage={emptyMessage || 'No posts found.'}\n          initial={initial}\n          initialSearch={params.toString()}\n          layout={layout || 'grid'}\n          load={load}\n          pagination={data.populateBy !== 'selection' && Boolean(data.enablePagination)}\n          queryKey={key}\n        />\n      </div>\n    </section>\n  )\n}\n",
      "type": "registry:file",
      "target": "~/src/blocks/CollectionQuery/Component.tsx"
    },
    {
      "path": "payload-components/source/blocks/CollectionQuery/Browser.tsx",
      "content": "'use client'\n\nimport React, { startTransition, useEffect, useRef, useState } from 'react'\n\nimport { PostCard } from '@/blocks/shared/PostCard'\nimport { cn } from '@/utilities/ui'\n\nimport { collectionHref, readCollectionRequest, type CollectionRequest } from './navigation'\nimport type { CollectionResult } from './query'\n\ntype Props = {\n  categories: { id: string; title: string }[]\n  disableInnerContainer?: boolean\n  emptyMessage: string\n  initial: CollectionResult\n  initialSearch: string\n  layout: 'featured' | 'grid' | 'list'\n  load: (request: CollectionRequest) => Promise<CollectionResult>\n  pagination: boolean\n  queryKey: string\n}\n\nconst navigationEvent = 'payload-collection-navigation'\nconst linkClass =\n  'rounded-md border border-border px-3 py-2 text-sm transition-colors hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring'\n\nexport function CollectionBrowser({\n  categories,\n  disableInnerContainer,\n  emptyMessage,\n  initial,\n  initialSearch,\n  layout,\n  load,\n  pagination,\n  queryKey,\n}: Props) {\n  const [result, setResult] = useState(initial)\n  const [previousInitial, setPreviousInitial] = useState(initial)\n  const [search, setSearch] = useState(initialSearch)\n  const [pending, setPending] = useState(false)\n  const [error, setError] = useState(false)\n  const retry = useRef<() => void>(() => {})\n\n  // A new server render (including live preview) supersedes the old result.\n  if (initial !== previousInitial) {\n    setPreviousInitial(initial)\n    setResult(initial)\n    setPending(false)\n    setError(false)\n  }\n\n  useEffect(() => {\n    let active = true\n    let sequence = 0\n    let previous = JSON.stringify({ category: initial.category, page: initial.page })\n    const sync = (force = false) => {\n      const currentSearch = window.location.search\n      setSearch(currentSearch)\n      const request = readCollectionRequest(new URLSearchParams(currentSearch), queryKey)\n      if (!pagination) request.page = 1\n      if (!categories.length) request.category = undefined\n      const signature = JSON.stringify(request)\n      if (!force && previous === signature) return\n      previous = signature\n      const ticket = ++sequence\n      setPending(true)\n      setError(false)\n      startTransition(async () => {\n        try {\n          const next = await load(request)\n          if (!active || ticket !== sequence) return\n          setResult(next)\n          // Replace stale page numbers without adding a history entry.\n          if (next.page !== request.page || next.category !== request.category) {\n            const href = collectionHref(window.location.search, queryKey, next)\n            window.history.replaceState(window.history.state, '', href)\n            previous = JSON.stringify({ category: next.category, page: next.page })\n            window.dispatchEvent(new Event(navigationEvent))\n          }\n        } catch {\n          if (active && ticket === sequence) setError(true)\n        } finally {\n          if (active && ticket === sequence) setPending(false)\n        }\n      })\n    }\n    const onNavigation = () => sync()\n    retry.current = () => sync(true)\n    sync()\n    window.addEventListener('popstate', onNavigation)\n    window.addEventListener(navigationEvent, onNavigation)\n    return () => {\n      active = false\n      window.removeEventListener('popstate', onNavigation)\n      window.removeEventListener(navigationEvent, onNavigation)\n    }\n  }, [categories, initial, load, pagination, queryKey])\n\n  const navigate = (event: React.MouseEvent<HTMLAnchorElement>) => {\n    if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey)\n      return\n    event.preventDefault()\n    window.history.pushState(window.history.state, '', event.currentTarget.href)\n    window.dispatchEvent(new Event(navigationEvent))\n  }\n\n  return (\n    <div\n      className={cn('space-y-6 scroll-mt-24', !disableInnerContainer && 'mx-auto max-w-6xl')}\n      id={queryKey}\n    >\n      {categories.length > 0 ? (\n        <nav aria-label=\"Filter posts by category\" className=\"flex flex-wrap gap-2\">\n          {[{ id: '', title: 'All posts' }, ...categories].map((category) => (\n            <a\n              aria-current={(result.category || '') === category.id ? 'true' : undefined}\n              className={cn(\n                linkClass,\n                (result.category || '') === category.id &&\n                  'border-foreground bg-foreground text-background hover:bg-foreground',\n              )}\n              href={collectionHref(search, queryKey, {\n                category: category.id || undefined,\n                page: 1,\n              })}\n              key={category.id}\n              onClick={navigate}\n            >\n              {category.title}\n            </a>\n          ))}\n        </nav>\n      ) : null}\n      <div aria-busy={pending}>\n        {result.docs.length > 0 ? (\n          <div\n            className={cn('gap-6', {\n              'flex flex-col': layout === 'list',\n              'grid md:grid-cols-2 lg:grid-cols-3': layout === 'grid',\n              'grid lg:grid-cols-2': layout === 'featured',\n            })}\n          >\n            {result.docs.map((post, index) => (\n              <PostCard\n                className={cn({ 'lg:col-span-2': layout === 'featured' && index === 0 })}\n                key={post.id}\n                post={post}\n                variant={\n                  layout === 'list'\n                    ? 'list'\n                    : layout === 'featured' && index === 0\n                      ? 'featured'\n                      : 'grid'\n                }\n              />\n            ))}\n          </div>\n        ) : (\n          <p className=\"rounded-xl border border-dashed border-border bg-muted/30 px-6 py-12 text-center text-sm text-muted-foreground\">\n            {emptyMessage}\n          </p>\n        )}\n      </div>\n      <div aria-atomic=\"true\" aria-live=\"polite\" className=\"text-sm text-muted-foreground\">\n        {pending\n          ? 'Loading posts…'\n          : error\n            ? 'Posts could not be loaded. Please try again.'\n            : `${result.totalDocs} ${result.totalDocs === 1 ? 'post' : 'posts'}`}\n      </div>\n      {error ? (\n        <button className={linkClass} onClick={() => retry.current()} type=\"button\">\n          Try again\n        </button>\n      ) : null}\n      {pagination && result.totalPages > 1 ? (\n        <nav\n          aria-label=\"Posts pagination\"\n          className=\"flex flex-wrap items-center justify-between gap-3\"\n        >\n          {result.page > 1 ? (\n            <a\n              className={linkClass}\n              href={collectionHref(search, queryKey, {\n                category: result.category,\n                page: result.page - 1,\n              })}\n              onClick={navigate}\n            >\n              Previous\n            </a>\n          ) : (\n            <span className=\"px-3 py-2 text-sm text-muted-foreground\">Previous</span>\n          )}\n          <span className=\"text-sm text-muted-foreground\">\n            Page {result.page} of {result.totalPages}\n          </span>\n          {result.page < result.totalPages ? (\n            <a\n              className={linkClass}\n              href={collectionHref(search, queryKey, {\n                category: result.category,\n                page: result.page + 1,\n              })}\n              onClick={navigate}\n            >\n              Next\n            </a>\n          ) : (\n            <span className=\"px-3 py-2 text-sm text-muted-foreground\">Next</span>\n          )}\n        </nav>\n      ) : null}\n    </div>\n  )\n}\n",
      "type": "registry:file",
      "target": "~/src/blocks/CollectionQuery/Browser.tsx"
    },
    {
      "path": "payload-components/source/blocks/CollectionQuery/query.ts",
      "content": "import configPromise from '@payload-config'\nimport { draftMode, headers } from 'next/headers'\nimport { getPayload, type TypedLocale, type Where } from 'payload'\n\nimport type { CollectionQueryBlock, Post } from '@/payload-types'\nimport type { PostCardData } from '@/blocks/shared/PostCard'\nimport type { CollectionRequest } from './navigation'\n\nexport type CollectionOptions = Pick<\n  CollectionQueryBlock,\n  | 'categories'\n  | 'enableFilters'\n  | 'enablePagination'\n  | 'limit'\n  | 'populateBy'\n  | 'selectedDocs'\n  | 'sort'\n> & { locale?: TypedLocale }\nexport type CollectionResult = {\n  category?: string\n  docs: Array<PostCardData & Pick<Post, 'id'>>\n  page: number\n  totalDocs: number\n  totalPages: number\n}\n\nconst sortOptions = new Set(['-publishedAt', 'publishedAt', 'title', '-title'])\nconst relationId = (value: { id: number | string } | number | string) =>\n  typeof value === 'object' ? value.id : value\n\nasync function queryContext() {\n  const payload = await getPayload({ config: configPromise })\n  const { user } = await payload.auth({ headers: await headers() })\n  const { isEnabled } = await draftMode()\n  // A preview cookie alone never grants access to drafts.\n  return { payload, user, draft: Boolean(isEnabled && user) }\n}\n\nexport async function queryCategories(options: CollectionOptions) {\n  if (!options.enableFilters || options.populateBy === 'selection') return []\n  const { payload, user } = await queryContext()\n  const ids = (options.categories ?? []).map(relationId)\n  const result = await payload.find({\n    collection: 'categories',\n    depth: 0,\n    limit: 100,\n    locale: options.locale,\n    overrideAccess: false,\n    user,\n    select: { title: true },\n    sort: ['title', 'id'],\n    where: ids.length ? { id: { in: ids } } : undefined,\n  })\n  return result.docs.map(({ id, title }) => ({ id: String(id), title }))\n}\n\nexport async function queryPosts(\n  options: CollectionOptions,\n  request: CollectionRequest = {},\n): Promise<CollectionResult> {\n  const { payload, user, draft } = await queryContext()\n  const selection = options.populateBy === 'selection'\n  const selectedIds = [...new Set((options.selectedDocs ?? []).map(relationId))]\n  const categoryIds = (options.categories ?? []).map(relationId)\n  const page =\n    !selection && options.enablePagination && Number.isSafeInteger(request?.page)\n      ? Math.min(Math.max(request.page ?? 1, 1), 10000)\n      : 1\n  // Treat server-function arguments as untrusted. A visitor can narrow the\n  // editor's selection, but cannot expand it or change its limit/sort/locale.\n  const category =\n    !selection &&\n    options.enableFilters &&\n    typeof request?.category === 'string' &&\n    request.category.length <= 128 &&\n    request.category.length > 0\n      ? request.category\n      : undefined\n  const clauses: Where[] = []\n  if (!draft) clauses.push({ _status: { equals: 'published' } })\n  if (selection) clauses.push({ id: { in: selectedIds } })\n  if (!selection && categoryIds.length) clauses.push({ categories: { in: categoryIds } })\n  if (category) clauses.push({ categories: { equals: category } })\n  if (selection && selectedIds.length === 0)\n    return { docs: [], page: 1, totalDocs: 0, totalPages: 1 }\n\n  const limit = selection\n    ? selectedIds.length\n    : Math.min(Math.max(Math.trunc(options.limit || 6), 1), 24)\n  const find = (requestedPage: number) =>\n    payload.find({\n      collection: 'posts',\n      depth: 1,\n      draft,\n      limit,\n      locale: options.locale,\n      overrideAccess: false,\n      user,\n      page: requestedPage,\n      pagination: !selection && Boolean(options.enablePagination),\n      select: { categories: true, meta: true, publishedAt: true, slug: true, title: true },\n      sort: [options.sort && sortOptions.has(options.sort) ? options.sort : '-publishedAt', 'id'],\n      where: { and: clauses },\n    })\n  let result = await find(page)\n  // Content removal or an old bookmarked URL can move the last page. Clamp and\n  // query once more so the visitor sees the last available page instead of a void.\n  if (!selection && options.enablePagination && page > Math.max(result.totalPages, 1)) {\n    result = await find(Math.max(result.totalPages, 1))\n  }\n  const docs = selection\n    ? selectedIds.flatMap((id) => result.docs.filter((post) => String(post.id) === String(id)))\n    : result.docs\n  return {\n    category,\n    docs: docs.map(({ id, categories, meta, publishedAt, slug, title }) => ({\n      id,\n      categories,\n      meta,\n      publishedAt,\n      slug,\n      title,\n    })),\n    page: result.page || 1,\n    totalDocs: result.totalDocs,\n    totalPages: Math.max(result.totalPages, 1),\n  }\n}\n",
      "type": "registry:file",
      "target": "~/src/blocks/CollectionQuery/query.ts"
    },
    {
      "path": "payload-components/source/blocks/CollectionQuery/navigation.ts",
      "content": "export type CollectionRequest = { category?: string; page?: number }\nexport type CollectionSearchParams = Record<string, string | string[] | undefined>\n\nexport function readCollectionRequest(search: URLSearchParams, key: string): CollectionRequest {\n  const value = search.get(`${key}-page`)\n  const page = value && /^\\d+$/.test(value) ? Number(value) : 1\n  return {\n    category: search.get(`${key}-category`) || undefined,\n    page: Number.isSafeInteger(page) && page > 0 ? Math.min(page, 10000) : 1,\n  }\n}\n\nexport function collectionHref(search: string, key: string, request: CollectionRequest) {\n  const params = new URLSearchParams(search)\n  params.delete(`${key}-page`)\n  params.delete(`${key}-category`)\n  if (request.page && request.page > 1) params.set(`${key}-page`, String(request.page))\n  if (request.category) params.set(`${key}-category`, request.category)\n  return `?${params.toString()}#${encodeURIComponent(key)}`\n}\n",
      "type": "registry:file",
      "target": "~/src/blocks/CollectionQuery/navigation.ts"
    }
  ],
  "meta": {
    "payloadComponent": {
      "installCommand": "payload-components add collection-query",
      "postInstall": [
        "generate:types",
        "generate:importmap"
      ],
      "requiresPayloadComponentWrapper": true,
      "supportedTargets": [
        "payload-website-starter"
      ]
    }
  },
  "docs": "Payload Components installs this as a Payload CMS block for the Payload website starter shape.\n\nRecommended install:\n\n```bash\npnpm payload-components add collection-query\n```\n\nDirect shadcn install URL:\n\n```bash\npnpm dlx shadcn@latest add https://www.payload-components.xyz/r/collection-query.json\n```\n\nDirect shadcn installs only copy the block source files and shadcn UI dependencies. Use `payload-components add collection-query` when you also want Payload layout registration, `RenderBlocks` wiring, `generate:types`, and `generate:importmap` handled for you.",
  "type": "registry:block"
}