'use client' import type { Column, SanitizedCollectionConfig, StaticLabel } from 'payload' import { getTranslation } from '@payloadcms/translations' import { fieldIsHiddenOrDisabled, fieldIsID, isFieldDisabled } from 'payload/shared' import React, { useCallback, useId, useLayoutEffect, useMemo, useRef, useState } from 'react' import { AlignJustifiedIcon } from '../../icons/AlignJustified/index.js' import { SearchIcon } from '../../icons/Search/index.js' import { XIcon } from '../../icons/X/index.js' import { useEditDepth } from '../../providers/EditDepth/index.js' import { useTranslation } from '../../providers/Translation/index.js' import { matchesSearchQuery } from '../../utilities/matchesSearchQuery.js' import { Button } from '../Button/index.js' import { DraggableSortable } from '../DraggableSortable/index.js' import { useDraggableSortable } from '../DraggableSortable/useDraggableSortable/index.js' import { Switch } from '../Switch/index.js' import './Popup.css' const baseClass = 'column-selector' /** * Parses a nested field label and returns segments for rendering. * - For deeply nested paths (more than 3 segments), truncates to [First, "...", Last] */ function parseNestedLabel(label: string): string[] { if (!label.includes(' > ')) { return [label] } const segments = label.split(' > ') if (segments.length <= 3) { return segments } // For deep nesting, show: First / ... / Last return [segments[0], '...', segments[segments.length - 1]] } type NestedLabelProps = { readonly label: string } const NestedLabel: React.FC = ({ label }) => { const segments = parseNestedLabel(label) if (segments.length === 1) { return <>{segments[0]} } return ( <> {segments.map((segment, index) => ( {index > 0 && /} {segment} ))} ) } export type ColumnSelectionPopupProps = { readonly collectionSlug: SanitizedCollectionConfig['slug'] readonly columns: Column[] /** Called with the next column state whenever a column is toggled or reordered. */ readonly onChange: (columns: Column[]) => void readonly onClose?: () => void } type ColumnItemProps = { readonly active: boolean readonly id: string readonly labelText: string readonly onToggle: () => void } const ColumnItem: React.FC = ({ id, active, labelText, onToggle }) => { const { t } = useTranslation() const { attributes, isDragging, isOver, isSorting, listeners, setActivatorNodeRef, setNodeRef, transform, } = useDraggableSortable({ id, }) return (
) } export const ColumnSelectionPopup: React.FC = ({ collectionSlug, columns, onChange, onClose, }) => { const { i18n, t } = useTranslation() const toggleColumn = useCallback( (column: string) => { onChange( columns.map((col) => (col.accessor === column ? { ...col, active: !col.active } : col)), ) }, [columns, onChange], ) const moveColumn = useCallback( ({ fromIndex, toIndex }: { fromIndex: number; toIndex: number }) => { const next = [...columns] const [moved] = next.splice(fromIndex, 1) next.splice(toIndex, 0, moved) onChange(next) }, [columns, onChange], ) const uuid = useId() const editDepth = useEditDepth() const [searchQuery, setSearchQuery] = useState('') const containerRef = useRef(null) const [lockedWidth, setLockedWidth] = useState(null) // Lock the width when search starts to prevent layout shift useLayoutEffect(() => { if (!containerRef.current) { return } if (searchQuery && lockedWidth === null) { // Capture width when search starts setLockedWidth(containerRef.current.offsetWidth) } else if (!searchQuery && lockedWidth !== null) { // Release width lock when search is cleared setLockedWidth(null) } }, [searchQuery, lockedWidth]) const filteredColumns = useMemo( () => columns?.filter( (col) => !(fieldIsHiddenOrDisabled(col.field) && !fieldIsID(col.field)) && !isFieldDisabled(col.field, 'column'), ), [columns], ) const columnItems = useMemo(() => { if (!filteredColumns) { return { all: [], hidden: [], shown: [] } } const items = filteredColumns.map((col, i) => { const { accessor, active, field } = col const label = 'labelWithPrefix' in field && field.labelWithPrefix !== undefined ? field.labelWithPrefix : 'label' in field && field.label !== undefined && field.label !== false ? field.label : 'name' in field && field.name !== undefined ? field.name : accessor const labelText = typeof label === 'string' ? label : getTranslation(label as StaticLabel, i18n) return { id: `${collectionSlug}-${accessor}-${i}${editDepth ? `-${editDepth}-` : ''}${uuid}`, accessor, active, index: i, label, labelText, } }) // Filter by search query const filtered = searchQuery ? items.filter((item) => matchesSearchQuery({ label: item.labelText, query: searchQuery })) : items return { all: items, hidden: filtered.filter((item) => !item.active), shown: filtered.filter((item) => item.active), } }, [collectionSlug, editDepth, filteredColumns, i18n, searchQuery, uuid]) const handleDragEnd = useCallback( ({ moveFromIndex, moveToIndex }: { moveFromIndex: number; moveToIndex: number }) => { if (moveFromIndex === moveToIndex) { return } // All shown items first, then all hidden items const allItems = [...columnItems.shown, ...columnItems.hidden] const shownCount = columnItems.shown.length const fromItem = allItems[moveFromIndex] const toItem = allItems[moveToIndex] if (!fromItem || !toItem) { return } // Determine if crossing sections const fromIsShown = moveFromIndex < shownCount const toIsShown = moveToIndex < shownCount if (fromIsShown !== toIsShown) { // Cross-section move: just toggle the column's active state (show/hide) void toggleColumn(fromItem.accessor) // Don't reorder when crossing sections - the toggle handles the change return } // Same-section move: perform the reorder void moveColumn({ fromIndex: fromItem.index, toIndex: toItem.index, }) }, [columnItems.shown, columnItems.hidden, moveColumn, toggleColumn], ) if (!filteredColumns) { return null } // Combined IDs: shown items first, then hidden items const allIds = [...columnItems.shown, ...columnItems.hidden].map((item) => item.id) const containerStyle = lockedWidth ? ({ '--column-selector-locked-width': `${lockedWidth}px` } as React.CSSProperties) : undefined return (

{t('general:editColumns')}

{onClose && (
{t('general:searchAutomatically')}
setSearchQuery(e.target.value)} placeholder={t('general:searchColumns')} type="text" value={searchQuery} />
{columnItems.shown.length === 0 && columnItems.hidden.length === 0 && searchQuery && (
{t('general:noMatchesFound')}
)} {columnItems.shown.length > 0 && (

{t('general:shownInTable')}

{columnItems.shown.map((item) => ( { void toggleColumn(item.accessor) }} /> ))}
)} {columnItems.hidden.length > 0 && (

{t('general:notShownInTable')}

{columnItems.hidden.map((item) => ( { void toggleColumn(item.accessor) }} /> ))}
)}
) }