import { Check, Shapes } from 'lucide-react'; import React, { createElement, useEffect, useRef, useState } from 'react'; import type { Category, TranslationFn } from '../../types'; import { getCategoryIcon } from '../shared/categoryIcons'; import { Tooltip } from '../shared/Tooltip'; interface CategoryTileMenuProps { categories: Category[]; value: number | null; onChange: (id: number | null) => void; /** The tile's side in pixels: 46 in a dialog's head band, 40 beside the sheet's name field. */ size?: number; t: TranslationFn; } /** * The place's category as the tile in front of its name: its icon in its colour, * and a tap opens the list to pick another. It replaces the row of category chips * the forms had, so the category reads as part of the place and the form loses a row. */ export default function CategoryTileMenu({ categories, value, onChange, size = 46, t, }: CategoryTileMenuProps): React.ReactElement { const [open, setOpen] = useState(false); const ref = useRef(null); useEffect(() => { if (!open) return; const onDoc = (e: MouseEvent) => { if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false); }; const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') { e.stopPropagation(); setOpen(false); } }; document.addEventListener('mousedown', onDoc); document.addEventListener('keydown', onKey, true); return () => { document.removeEventListener('mousedown', onDoc); document.removeEventListener('keydown', onKey, true); }; }, [open]); const current = value != null ? (categories.find((c) => c.id === value) ?? null) : null; const Icon = current ? getCategoryIcon(current.icon ?? undefined) : Shapes; const tone = current?.color || null; const label = `${t('collections.category')}: ${current?.name ?? t('collections.noCategory')}`; return (
{open && (
{[null, ...categories].map((cat) => { const on = (cat?.id ?? null) === value; const OptIcon = cat ? getCategoryIcon(cat.icon ?? undefined) : Shapes; return ( ); })}
)}
); }