Skip to content

feat(ui): expose refresh method to list drawer context #13173

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Jul 24, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 42 additions & 21 deletions packages/ui/src/elements/ListDrawer/DrawerContent.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
'use client'
import type { ListQuery } from 'payload'
import type { CollectionSlug, ListQuery } from 'payload'

import { useModal } from '@faceless-ui/modal'
import { hoistQueryParamsToAnd } from 'payload/shared'
import React, { useCallback, useEffect, useState } from 'react'

import type { ListDrawerContextProps, ListDrawerContextType } from '../ListDrawer/Provider.js'
import type { ListDrawerProps } from './types.js'

import { useDocumentDrawer } from '../../elements/DocumentDrawer/index.js'
Expand All @@ -25,7 +26,7 @@ export const ListDrawerContent: React.FC<ListDrawerProps> = ({
onBulkSelect,
onSelect,
overrideEntityVisibility = true,
selectedCollection: selectedCollectionFromProps,
selectedCollection: collectionSlugFromProps,
}) => {
const { closeModal, isModalOpen } = useModal()

Expand All @@ -45,7 +46,7 @@ export const ListDrawerContent: React.FC<ListDrawerProps> = ({
})

const [selectedOption, setSelectedOption] = useState<Option<string>>(() => {
const initialSelection = selectedCollectionFromProps || enabledCollections[0]?.slug
const initialSelection = collectionSlugFromProps || enabledCollections[0]?.slug
const found = getEntityConfig({ collectionSlug: initialSelection })

return found
Expand All @@ -61,20 +62,25 @@ export const ListDrawerContent: React.FC<ListDrawerProps> = ({
collectionSlug: selectedOption.value,
})

const updateSelectedOption = useEffectEvent((selectedCollectionFromProps: string) => {
if (selectedCollectionFromProps && selectedCollectionFromProps !== selectedOption?.value) {
const updateSelectedOption = useEffectEvent((collectionSlug: CollectionSlug) => {
if (collectionSlug && collectionSlug !== selectedOption?.value) {
setSelectedOption({
label: getEntityConfig({ collectionSlug: selectedCollectionFromProps })?.labels,
value: selectedCollectionFromProps,
label: getEntityConfig({ collectionSlug })?.labels,
value: collectionSlug,
})
}
})

useEffect(() => {
updateSelectedOption(selectedCollectionFromProps)
}, [selectedCollectionFromProps])

const renderList = useCallback(
updateSelectedOption(collectionSlugFromProps)
}, [collectionSlugFromProps])

/**
* This performs a full server round trip to get the list view for the selected collection.
* On the server, the data is freshly queried for the list view and all components are fully rendered.
* This work includes building column state, rendering custom components, etc.
*/
const refresh = useCallback(
async ({ slug, query }: { query?: ListQuery; slug: string }) => {
try {
const newQuery: ListQuery = { ...(query || {}), where: { ...(query?.where || {}) } }
Expand Down Expand Up @@ -129,9 +135,9 @@ export const ListDrawerContent: React.FC<ListDrawerProps> = ({

useEffect(() => {
if (!ListView) {
void renderList({ slug: selectedOption?.value })
void refresh({ slug: selectedOption?.value })
}
}, [renderList, ListView, selectedOption.value])
}, [refresh, ListView, selectedOption.value])

const onCreateNew = useCallback(
({ doc }) => {
Expand All @@ -149,19 +155,33 @@ export const ListDrawerContent: React.FC<ListDrawerProps> = ({
[closeModal, documentDrawerSlug, drawerSlug, onSelect, selectedOption.value],
)

const onQueryChange = useCallback(
(query: ListQuery) => {
void renderList({ slug: selectedOption?.value, query })
const onQueryChange: ListDrawerContextProps['onQueryChange'] = useCallback(
(query) => {
void refresh({ slug: selectedOption?.value, query })
},
[renderList, selectedOption.value],
[refresh, selectedOption.value],
)

const setMySelectedOption = useCallback(
(incomingSelection: Option<string>) => {
const setMySelectedOption: ListDrawerContextProps['setSelectedOption'] = useCallback(
(incomingSelection) => {
setSelectedOption(incomingSelection)
void renderList({ slug: incomingSelection?.value })
void refresh({ slug: incomingSelection?.value })
},
[refresh],
)

const refreshSelf: ListDrawerContextType['refresh'] = useCallback(
async (incomingCollectionSlug) => {
if (incomingCollectionSlug) {
setSelectedOption({
label: getEntityConfig({ collectionSlug: incomingCollectionSlug })?.labels,
value: incomingCollectionSlug,
})
}

await refresh({ slug: selectedOption.value || incomingCollectionSlug })
},
[renderList],
[getEntityConfig, refresh, selectedOption.value],
)

if (isLoading) {
Expand All @@ -178,6 +198,7 @@ export const ListDrawerContent: React.FC<ListDrawerProps> = ({
onBulkSelect={onBulkSelect}
onQueryChange={onQueryChange}
onSelect={onSelect}
refresh={refreshSelf}
selectedOption={selectedOption}
setSelectedOption={setMySelectedOption}
>
Expand Down
12 changes: 9 additions & 3 deletions packages/ui/src/elements/ListDrawer/Provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,19 +24,25 @@ export type ListDrawerContextProps = {
*/
docID: string
}) => void
readonly selectedOption?: Option<string>
readonly setSelectedOption?: (option: Option<string>) => void
readonly selectedOption?: Option<CollectionSlug>
readonly setSelectedOption?: (option: Option<CollectionSlug>) => void
}

export type ListDrawerContextType = {
isInDrawer: boolean
readonly isInDrawer: boolean
/**
* When called, will either refresh the list view with its currently selected collection.
* If an collection slug is provided, will use that instead of the currently selected one.
*/
readonly refresh: (collectionSlug?: CollectionSlug) => Promise<void>
} & ListDrawerContextProps

export const ListDrawerContext = createContext({} as ListDrawerContextType)

export const ListDrawerContextProvider: React.FC<
{
children: React.ReactNode
refresh: ListDrawerContextType['refresh']
} & ListDrawerContextProps
> = ({ children, ...rest }) => {
return (
Expand Down
19 changes: 19 additions & 0 deletions packages/ui/src/elements/ListDrawer/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,25 @@ export const ListDrawer: React.FC<ListDrawerProps> = (props) => {
)
}

/**
* Returns an array containing the ListDrawer component, the ListDrawerToggler component, and an object with state and methods for controlling the drawer.
* @example
* import { useListDrawer } from '@payloadcms/ui'
*
* // inside a React component
* const [ListDrawer, ListDrawerToggler, { closeDrawer, openDrawer }] = useListDrawer({
* collectionSlugs: ['users'],
* selectedCollection: 'users',
* })
*
* // inside the return statement
* return (
* <>
* <ListDrawer />
* <ListDrawerToggler onClick={openDrawer}>Open List Drawer</ListDrawerToggler>
* </>
* )
*/
export const useListDrawer: UseListDrawer = ({
collectionSlugs: collectionSlugsFromProps,
filterOptions,
Expand Down
60 changes: 60 additions & 0 deletions test/admin/collections/CustomListDrawer/Component.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
'use client'
import { toast, useListDrawer, useListDrawerContext, useTranslation } from '@payloadcms/ui'
import React, { useCallback } from 'react'

export const CustomListDrawer = () => {
const [isCreating, setIsCreating] = React.useState(false)

// this is the _outer_ drawer context (if any), not the one for the list drawer below
const { refresh } = useListDrawerContext()
const { t } = useTranslation()

const [ListDrawer, ListDrawerToggler] = useListDrawer({
collectionSlugs: ['custom-list-drawer'],
})

const createDoc = useCallback(async () => {
if (isCreating) {
return
}

setIsCreating(true)

try {
await fetch('/api/custom-list-drawer', {
body: JSON.stringify({}),
credentials: 'include',
headers: {
'Content-Type': 'application/json',
},
method: 'POST',
})

setIsCreating(false)

toast.success(
t('general:successfullyCreated', {
label: 'Custom List Drawer',
}),
)

// In the root document view, there is no outer drawer context, so this will be `undefined`
if (typeof refresh === 'function') {
await refresh()
}
} catch (_err) {
console.error('Error creating document:', _err) // eslint-disable-line no-console
setIsCreating(false)
}
}, [isCreating, refresh, t])

return (
<div>
<button id="create-custom-list-drawer-doc" onClick={createDoc} type="button">
{isCreating ? 'Creating...' : 'Create Document'}
</button>
<ListDrawer />
<ListDrawerToggler id="open-custom-list-drawer">Open list drawer</ListDrawerToggler>
</div>
)
}
16 changes: 16 additions & 0 deletions test/admin/collections/CustomListDrawer/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import type { CollectionConfig } from 'payload'

export const CustomListDrawer: CollectionConfig = {
slug: 'custom-list-drawer',
fields: [
{
name: 'customListDrawer',
type: 'ui',
admin: {
components: {
Field: '/collections/CustomListDrawer/Component.js#CustomListDrawer',
},
},
},
],
}
2 changes: 2 additions & 0 deletions test/admin/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { buildConfigWithDefaults } from '../buildConfigWithDefaults.js'
import { Array } from './collections/Array.js'
import { BaseListFilter } from './collections/BaseListFilter.js'
import { CustomFields } from './collections/CustomFields/index.js'
import { CustomListDrawer } from './collections/CustomListDrawer/index.js'
import { CustomViews1 } from './collections/CustomViews1.js'
import { CustomViews2 } from './collections/CustomViews2.js'
import { DisableBulkEdit } from './collections/DisableBulkEdit.js'
Expand Down Expand Up @@ -185,6 +186,7 @@ export default buildConfigWithDefaults({
Placeholder,
UseAsTitleGroupField,
DisableBulkEdit,
CustomListDrawer,
],
globals: [
GlobalHidden,
Expand Down
36 changes: 36 additions & 0 deletions test/admin/e2e/list-view/e2e.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1676,6 +1676,42 @@ describe('List View', () => {

await expect(page.locator('.list-selection')).toContainText('2 selected')
})

test('should refresh custom list drawer using the refresh method from context', async () => {
const url = new AdminUrlUtil(serverURL, 'custom-list-drawer')

await payload.delete({
collection: 'custom-list-drawer',
where: { id: { exists: true } },
})

const { id } = await payload.create({
collection: 'custom-list-drawer',
data: {},
})

await page.goto(url.list)

await expect(page.locator('.table > table > tbody > tr')).toHaveCount(1)

await page.goto(url.edit(id))

await page.locator('#open-custom-list-drawer').click()
const drawer = page.locator('[id^=list-drawer_1_]')
await expect(drawer).toBeVisible()

await expect(drawer.locator('.table > table > tbody > tr')).toHaveCount(1)

await drawer.locator('.list-header__create-new-button.doc-drawer__toggler').click()
const createNewDrawer = page.locator('[id^=doc-drawer_custom-list-drawer_1_]')
await createNewDrawer.locator('#create-custom-list-drawer-doc').click()

await expect(page.locator('.payload-toast-container')).toContainText('successfully')

await createNewDrawer.locator('.doc-drawer__header-close').click()

await expect(drawer.locator('.table > table > tbody > tr')).toHaveCount(2)
})
})

async function createPost(overrides?: Partial<Post>): Promise<Post> {
Expand Down
23 changes: 23 additions & 0 deletions test/admin/payload-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ export interface Config {
placeholder: Placeholder;
'use-as-title-group-field': UseAsTitleGroupField;
'disable-bulk-edit': DisableBulkEdit;
'custom-list-drawer': CustomListDrawer;
'payload-locked-documents': PayloadLockedDocument;
'payload-preferences': PayloadPreference;
'payload-migrations': PayloadMigration;
Expand Down Expand Up @@ -125,6 +126,7 @@ export interface Config {
placeholder: PlaceholderSelect<false> | PlaceholderSelect<true>;
'use-as-title-group-field': UseAsTitleGroupFieldSelect<false> | UseAsTitleGroupFieldSelect<true>;
'disable-bulk-edit': DisableBulkEditSelect<false> | DisableBulkEditSelect<true>;
'custom-list-drawer': CustomListDrawerSelect<false> | CustomListDrawerSelect<true>;
'payload-locked-documents': PayloadLockedDocumentsSelect<false> | PayloadLockedDocumentsSelect<true>;
'payload-preferences': PayloadPreferencesSelect<false> | PayloadPreferencesSelect<true>;
'payload-migrations': PayloadMigrationsSelect<false> | PayloadMigrationsSelect<true>;
Expand Down Expand Up @@ -565,6 +567,15 @@ export interface DisableBulkEdit {
updatedAt: string;
createdAt: string;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "custom-list-drawer".
*/
export interface CustomListDrawer {
id: string;
updatedAt: string;
createdAt: string;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "payload-locked-documents".
Expand Down Expand Up @@ -675,6 +686,10 @@ export interface PayloadLockedDocument {
| ({
relationTo: 'disable-bulk-edit';
value: string | DisableBulkEdit;
} | null)
| ({
relationTo: 'custom-list-drawer';
value: string | CustomListDrawer;
} | null);
globalSlug?: string | null;
user: {
Expand Down Expand Up @@ -1074,6 +1089,14 @@ export interface DisableBulkEditSelect<T extends boolean = true> {
updatedAt?: T;
createdAt?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "custom-list-drawer_select".
*/
export interface CustomListDrawerSelect<T extends boolean = true> {
updatedAt?: T;
createdAt?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "payload-locked-documents_select".
Expand Down
Loading
Loading