import { FieldType, type FieldInfo, type FieldInfo as MetadataFieldInfo, type SelectOption, } from '@shumai/dtos' import { ulid } from 'ulid' import { client } from '@/ui/api/client' import { useFieldStore } from '@/ui/stores/fields' import { DragDropProvider, KeyboardSensor, PointerSensor, type DragEndEvent } from '@dnd-kit/react' import { useSortable } from '@dnd-kit/react/sortable' import { useMutation, useQueryClient } from '@tanstack/react-query' import { InferRequestType, InferResponseType } from 'hono/client' import { Button } from '@/ui/components/ui/button' import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, } from '@/ui/components/ui/dropdown-menu' import { Popover, PopoverContent, PopoverTrigger } from '@/ui/components/ui/popover' import { Input } from '@/ui/components/ui/input' import { Label } from '@/ui/components/ui/label' import { Switch } from '@/ui/components/ui/switch' import { arrayMove } from '@/ui/lib/dnd-utils' import { PointerActivationConstraints } from '@dnd-kit/dom' export const PREDEFINED_COLORS = ['red', 'orange', 'yellow', 'green', 'blue', 'purple', 'gray'] export const COLOR_MAP: Record = { red: { bg: 'rgba(239, 68, 68, 0.15)', text: '#ef4444', hex: '#ef4444' }, orange: { bg: 'rgba(249, 115, 22, 0.15)', text: '#f97316', hex: '#f97316' }, yellow: { bg: 'rgba(234, 179, 8, 0.15)', text: '#ca8a04', hex: '#eab308' }, green: { bg: 'rgba(34, 197, 94, 0.15)', text: '#16a34a', hex: '#22c55e' }, blue: { bg: 'rgba(59, 130, 246, 0.15)', text: '#2563eb', hex: '#3b82f6' }, purple: { bg: 'rgba(168, 85, 247, 0.15)', text: '#9333ea', hex: '#a855f7' }, gray: { bg: 'rgba(128, 128, 128, 0.15)', text: '#4b5563', hex: '#808080' }, system: { bg: 'rgba(128, 128, 128, 0.1)', text: '#6b7280', hex: '#808080' }, } export function getOptionStyle(color?: string) { if (!color) { return { backgroundColor: 'rgba(128, 128, 128, 0.1)', color: '#6b7280', } } const normalized = color.toLowerCase() const mapped = COLOR_MAP[normalized] if (mapped) { return { backgroundColor: mapped.bg, color: mapped.text, } } // Support hex colors (e.g. for existing custom fields) if (color.startsWith('#')) { return { backgroundColor: `${color}33`, color: color, } } // Fallback return { backgroundColor: 'rgba(128, 128, 128, 0.1)', color: color, } } import { AlignLeft, Calendar, ChevronDown, GripVertical, Hash, List, Plus, Search, Settings, Sparkles, Star, Tags, ToggleLeft, Type, X, } from 'lucide-react' import { useMemo, useState, useEffect } from 'react' export const FIELD_TYPE_ICONS: Record> = { [FieldType.text]: Type, [FieldType.longText]: AlignLeft, [FieldType.select]: List, [FieldType.selectMulti]: Tags, [FieldType.rating]: Star, [FieldType.number]: Hash, [FieldType.toggle]: ToggleLeft, [FieldType.date]: Calendar, } type SortableFieldItemProps = { field: FieldInfo index: number onVisibilityChange: (fieldId: string, visible: boolean) => void } function SortableFieldItem({ field, index, onVisibilityChange }: SortableFieldItemProps) { const { ref, handleRef } = useSortable({ id: field.id!, index, }) const Icon = field.config?.type ? FIELD_TYPE_ICONS[field.config.type as FieldType] : null return (
{Icon && } {field.aiAutofill && } {field.config?.name}
onVisibilityChange(field.id!, checked)} />
) } type FieldsManagerProps = { projectId: string onManageFields?: () => void onSave?: () => void } export function FieldsManager({ projectId, onManageFields, onSave }: FieldsManagerProps) { const { fields, updateFields } = useFieldStore() const [searchQuery, setSearchQuery] = useState('') const [view, setView] = useState<'list' | 'create'>('list') const [newFieldName, setNewFieldName] = useState('') const [newFieldType, setNewFieldType] = useState('') const [newAiAutofill, setNewAiAutofill] = useState(false) const [newDescription, setNewDescription] = useState('') const [newOptions, setNewOptions] = useState([]) const queryClient = useQueryClient() useEffect(() => { queryClient.invalidateQueries({ queryKey: ['fields', projectId] }) }, [projectId, queryClient]) const $patchOrder = client.api.projects[':projectId'].fields.order.$patch const { mutate: updateFieldsOrder } = useMutation< InferResponseType, Error, InferRequestType >({ mutationFn: async (request) => { const res = await $patchOrder(request) if (!res.ok) throw new Error('Failed to update fields order') return null as unknown as InferResponseType }, }) const $post = client.api.projects[':projectId'].fields.$post const { mutate: createField } = useMutation< InferResponseType, Error, InferRequestType >({ mutationFn: async (request) => { const res = await $post(request) if (!res.ok) throw new Error('Failed to create field') return (await res.json()) as MetadataFieldInfo }, onSuccess: (data) => { const newField: MetadataFieldInfo = { ...(data as MetadataFieldInfo), visible: true, } const newFieldsList = [...fields, newField] updateFields(newFieldsList) setNewFieldName('') setNewOptions([]) updateFieldsOrder({ param: { projectId: projectId }, json: newFieldsList.map((f) => ({ fieldId: f.id!, visible: f.visible || false, })), }) onSave?.() }, }) const filteredFields = useMemo( () => fields.filter((field) => field.config?.name?.toLowerCase().includes(searchQuery.toLowerCase()), ), [fields, searchQuery], ) const handleDragEnd = (event: DragEndEvent) => { const { source, target } = event.operation if (source && target && source.id !== target.id) { const oldIndex = fields.findIndex((f) => f.id === source.id) const newIndex = fields.findIndex((f) => f.id === target.id) const newFields = arrayMove(fields, oldIndex, newIndex) updateFields(newFields) updateFieldsOrder({ param: { projectId: projectId }, json: newFields.map((f: MetadataFieldInfo) => ({ fieldId: f.id!, visible: f.visible || false, })), }) } } const handleVisibilityChange = (fieldId: string, visible: boolean) => { const newFields = fields.map((f) => (f.id === fieldId ? { ...f, visible } : f)) updateFields(newFields) updateFieldsOrder({ param: { projectId: projectId }, json: newFields.map((f) => ({ fieldId: f.id!, visible: f.visible || false, })), }) } const handleCreateField = () => { if (!newFieldName || !newFieldType) return const typeConfig = newFieldType === FieldType.select ? { select: { options: newOptions } } : newFieldType === FieldType.selectMulti ? { selectMulti: { options: newOptions } } : {} createField({ param: { projectId: projectId }, json: { config: { name: newFieldName, type: newFieldType, ...typeConfig, }, label: newFieldName, aiAutofill: newAiAutofill, description: newDescription, }, }) } const visibleCount = fields.filter((f) => f.visible).length if (view === 'create') { return (
setNewFieldName(e.target.value)} autoFocus />
{Object.values(FieldType).map((type) => ( { setNewFieldType(type) setNewOptions([]) }} className="capitalize" > {type.replace(/_/g, ' ')} ))}
setNewDescription(e.target.value)} />
{(newFieldType === FieldType.select || newFieldType === FieldType.selectMulti) && (
{newOptions.map((opt, idx) => (
{ const updated = [...newOptions] updated[idx] = { ...opt, displayName: e.target.value } setNewOptions(updated) }} placeholder="Option name" className="h-8 flex-1" />
))}
)}
) } return (

Fields{' '} ({visibleCount} visible)

setSearchQuery(e.target.value)} className="pl-8" />
{filteredFields.map((field, index) => ( ))}
{onManageFields && (
)}
) }