import { useQuery, useWidgetProps } from './utils'; import { useEffect, useState, type KeyboardEvent } from 'react'; export type Section = { name: string; id: number; has_subsections: 0 | 1; } type SectionRowProps = { section: { name: string; id: number; full_path?: string }; depth?: number; hasSubsections?: boolean; }; function getEndpoint(sectionId: number) { return `/admin/autocomplete/sections/${sectionId}`; } export function SectionRow({ section, hasSubsections, depth = 0 }: SectionRowProps) { const [showChildren, setShowChildren] = useState(false); const [shouldFetchChildren, setShouldFetchChildren] = useState(false); const { data } = useQuery(shouldFetchChildren ? getEndpoint(section.id): undefined); const { onAddSection, onAddWithSubsections, onSelect, hide, shouldHideAfterSelect } = useWidgetProps(); useEffect(() => { if (!shouldFetchChildren) { setShouldFetchChildren(showChildren); } }, [showChildren]); function handleKeyboardNav(ev: KeyboardEvent) { switch (ev.key) { case 'ArrowLeft': setShowChildren(false); break; case 'ArrowRight': setShowChildren(true); break; case 'Enter': if (ev.ctrlKey) { if (onAddWithSubsections) { onAddWithSubsections(section.id); } break; } if (onAddSection) { onAddSection(section.id); } if (onSelect) { onSelect(section.id); } break; } } return ( <>
0 ? ' subsection' : ''}`} style={{ paddingLeft: `${depth * 28}px` }} onKeyUp={handleKeyboardNav} >
{ if (onSelect) { ev.stopPropagation(); if (shouldHideAfterSelect) { hide(); } onSelect(section.id); } }} >
{!!hasSubsections && (
{ ev.stopPropagation(); setShowChildren(prev => !prev); }} className={`bi bi-dash-circle opener ${showChildren ? 'minus' : 'plus'}`} />
)}
{section.name} {!!section.full_path && ( {section.full_path} )}
{!!onAddSection && ( )} {!!onAddWithSubsections && ( )}
{showChildren && data?.map((child, i) => ( ))} ); }