initial commit

This commit is contained in:
yiling
2026-05-19 16:05:09 +08:00
commit 9cad96210c
370 changed files with 131609 additions and 0 deletions
+229
View File
@@ -0,0 +1,229 @@
import {
addMonths,
eachDayOfInterval,
endOfMonth,
format,
getDate,
getDay,
getHours,
getMinutes,
getMonth,
getYear,
isValid,
} from 'date-fns'
import { ChevronLeft, ChevronRight, Clock } from 'lucide-react'
import React, { useEffect, useRef, useState } from 'react'
import type { FieldProps } from './field-types'
const DateField: React.FC<FieldProps<string>> = ({ value, config, onSave, readOnly }) => {
const dateConfig = config?.date
const [isEditing, setIsEditing] = useState(false)
const containerRef = useRef<HTMLDivElement>(null)
// Parse value or default to today
// Replaced parseISO with new Date() to avoid import errors
const parsedDate = value ? new Date(value) : new Date()
const safeDate = isValid(parsedDate) ? parsedDate : new Date()
// Calendar State
const [viewDate, setViewDate] = useState(safeDate)
useEffect(() => {
if (isEditing && value) {
const d = new Date(value)
if (isValid(d)) setViewDate(d)
}
}, [isEditing, value])
// Click outside to close
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
if (isEditing) {
setIsEditing(false)
}
}
}
document.addEventListener('mousedown', handleClickOutside)
return () => document.removeEventListener('mousedown', handleClickOutside)
}, [isEditing])
const handleStartEdit = () => {
if (!readOnly) {
setIsEditing(true)
}
}
const getDisplayValue = (isoString: string) => {
if (!isoString) return ''
const date = new Date(isoString)
if (!isValid(date)) return 'Invalid Date'
let formatStr = 'PPP' // Default Friendly
if (dateConfig?.displayFormat === 'usa') formatStr = 'MM/dd/yyyy'
else if (dateConfig?.displayFormat === 'euro') formatStr = 'dd/MM/yyyy'
else if (dateConfig?.displayFormat === 'iso') formatStr = 'yyyy-MM-dd'
if (dateConfig?.includeTime) {
if (dateConfig?.timeFormat === 'twenty_four_hour') {
formatStr += ' HH:mm'
} else {
formatStr += ' p'
}
}
let display = format(date, formatStr)
if (dateConfig?.displayTimezone) {
display += ` (${Intl.DateTimeFormat().resolvedOptions().timeZone})`
}
return display
}
// Calendar Logic
// Replaced startOfMonth with native Date manipulation
const monthStart = new Date(viewDate.getFullYear(), viewDate.getMonth(), 1)
const monthEnd = endOfMonth(viewDate)
const daysInMonth = eachDayOfInterval({ start: monthStart, end: monthEnd })
const startDayOfWeek = getDay(monthStart) // 0 = Sunday
const handleDateClick = (day: Date) => {
// Preserve time from current value if exists
const newDate = new Date(day)
if (dateConfig?.includeTime) {
// Replaced setHours/setMinutes with native methods
newDate.setHours(getHours(safeDate))
newDate.setMinutes(getMinutes(safeDate))
}
const isoString = newDate.toISOString()
onSave(isoString)
if (!dateConfig?.includeTime) {
setIsEditing(false)
}
}
const handleTimeChange = (type: 'hour' | 'minute', val: number) => {
const newDate = value ? new Date(value) : new Date()
if (!isValid(newDate)) newDate.setTime(new Date().getTime())
if (type === 'hour') newDate.setHours(val)
if (type === 'minute') newDate.setMinutes(val)
const isoString = newDate.toISOString()
onSave(isoString)
}
const hours = Array.from({ length: 24 }, (_, i) => i)
const minutes = Array.from({ length: 12 }, (_, i) => i * 5) // 0, 5, 10...
if (isEditing) {
return (
<div className="relative w-full" ref={containerRef}>
<div className="w-full px-2 py-1 border border-blue-500 rounded bg-white text-sm shadow-sm min-h-[28px] flex items-center">
{value ? getDisplayValue(value) : <span className="text-gray-400">Select date...</span>}
</div>
<div className="absolute z-50 top-full left-0 mt-1 bg-white border border-gray-200 rounded-lg shadow-xl flex flex-col md:flex-row overflow-hidden min-w-[280px]">
{/* Date Picker */}
<div className="p-4 w-64">
<div className="flex justify-between items-center mb-4">
{/* Replaced subMonths with addMonths(-1) */}
<button
onClick={() => setViewDate(addMonths(viewDate, -1))}
className="p-1 hover:bg-gray-100 rounded"
>
<ChevronLeft className="w-4 h-4" />
</button>
<span className="font-semibold text-sm">{format(viewDate, 'MMMM yyyy')}</span>
<button
onClick={() => setViewDate(addMonths(viewDate, 1))}
className="p-1 hover:bg-gray-100 rounded"
>
<ChevronRight className="w-4 h-4" />
</button>
</div>
<div className="grid grid-cols-7 gap-1 text-center text-xs mb-2 text-gray-500">
{['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'].map((d) => (
<div key={d}>{d}</div>
))}
</div>
<div className="grid grid-cols-7 gap-1 text-center text-sm">
{Array.from({ length: startDayOfWeek }).map((_, i) => (
<div key={`empty-${i}`} />
))}
{daysInMonth.map((date) => {
const valDate = value ? new Date(value) : null
const isSelected =
valDate &&
isValid(valDate) &&
getDate(valDate) === getDate(date) &&
getMonth(valDate) === getMonth(date) &&
getYear(valDate) === getYear(date)
return (
<button
key={date.toString()}
onClick={() => handleDateClick(date)}
className={`w-8 h-8 rounded-full flex items-center justify-center hover:bg-blue-50 transition-colors ${
isSelected ? 'bg-blue-50 text-white hover:bg-blue-600' : 'text-gray-700'
}`}
>
{getDate(date)}
</button>
)
})}
</div>
</div>
{/* Time Picker */}
{dateConfig?.includeTime && (
<div className="border-l border-gray-200 bg-gray-50 w-32 flex flex-col">
<div className="p-2 border-b border-gray-200 text-xs font-semibold text-gray-500 flex items-center justify-center gap-1">
<Clock className="w-3 h-3" /> Time
</div>
<div className="flex flex-1 h-64">
<div className="flex-1 overflow-y-auto scrollbar-hide border-r border-gray-200">
{hours.map((h) => (
<div
key={h}
onClick={() => handleTimeChange('hour', h)}
className={`px-2 py-1 text-center text-sm cursor-pointer hover:bg-gray-200 ${getHours(safeDate) === h ? 'bg-blue-100 font-medium text-blue-700' : ''}`}
>
{h.toString().padStart(2, '0')}
</div>
))}
</div>
<div className="flex-1 overflow-y-auto scrollbar-hide">
{minutes.map((m) => (
<div
key={m}
onClick={() => handleTimeChange('minute', m)}
className={`px-2 py-1 text-center text-sm cursor-pointer hover:bg-gray-200 ${getMinutes(safeDate) === m ? 'bg-blue-100 font-medium text-blue-700' : ''}`}
>
{m.toString().padStart(2, '0')}
</div>
))}
</div>
</div>
</div>
)}
</div>
</div>
)
}
return (
<div
onClick={handleStartEdit}
className={`w-full min-h-[28px] px-2 py-1 text-sm text-gray-800 rounded border border-transparent transition-colors ${
!readOnly ? 'cursor-pointer hover:bg-gray-100 hover:border-gray-200' : ''
}`}
>
{value ? getDisplayValue(value) : <span className="text-gray-400 italic">Empty</span>}
</div>
)
}
export default DateField
+10
View File
@@ -0,0 +1,10 @@
import type { FieldInfo as MetadataFieldInfo } from '@/dtos/metadata'
export type FieldConfig = MetadataFieldInfo['config']
export interface FieldProps<T = unknown> {
value: T
config: FieldConfig
onSave: (value: T) => void
readOnly?: boolean
}
@@ -0,0 +1,99 @@
import React, { useEffect, useRef, useState } from 'react'
import type { FieldProps } from './field-types'
const LongTextField: React.FC<FieldProps<string>> = ({ value, onSave, readOnly }) => {
const [isEditing, setIsEditing] = useState(false)
const [localValue, setLocalValue] = useState(value || '')
const textareaRef = useRef<HTMLTextAreaElement>(null)
const containerRef = useRef<HTMLDivElement>(null)
const [expanded, setExpanded] = useState(false)
useEffect(() => {
setLocalValue(value || '')
}, [value])
useEffect(() => {
if (isEditing && textareaRef.current) {
textareaRef.current.focus()
setExpanded(false)
}
}, [isEditing])
// Handle click outside to close expanded state
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (
expanded &&
containerRef.current &&
!containerRef.current.contains(event.target as Node)
) {
setExpanded(false)
}
}
if (expanded) {
document.addEventListener('mousedown', handleClickOutside)
}
return () => {
document.removeEventListener('mousedown', handleClickOutside)
}
}, [expanded])
const handleBlur = () => {
setIsEditing(false)
onSave(localValue)
}
const handlePlaceholderClick = (e: React.MouseEvent) => {
e.stopPropagation()
setExpanded(true)
}
const handleOverlayClick = (e: React.MouseEvent) => {
e.stopPropagation()
if (!readOnly) {
setIsEditing(true)
}
}
if (isEditing) {
return (
<textarea
ref={textareaRef}
value={localValue}
onChange={(e) => setLocalValue(e.target.value)}
onBlur={handleBlur}
className="w-full min-h-[80px] p-2 border border-blue-500 rounded bg-white text-sm outline-none shadow-sm resize-none"
/>
)
}
return (
<div ref={containerRef} className="relative w-full text-sm">
{/* Placeholder */}
<div
onClick={handlePlaceholderClick}
className={`w-full text-gray-800 rounded border border-transparent transition-all px-2 py-1 line-clamp-2 max-h-[3rem] overflow-hidden ${
!readOnly ? 'cursor-pointer hover:bg-gray-100 hover:border-gray-200' : 'cursor-pointer'
}`}
title="Click to expand"
>
{value ? value : <span className="text-gray-400 italic">Empty</span>}
</div>
{/* Expanded Overlay */}
{expanded && (
<div
onClick={handleOverlayClick}
className={`absolute top-0 left-0 w-full min-h-full h-auto z-50 bg-white border border-blue-500 rounded shadow-lg px-2 py-1 whitespace-pre-wrap ${
!readOnly ? 'cursor-text' : ''
}`}
>
{value ? value : <span className="text-gray-400 italic">Empty</span>}
</div>
)}
</div>
)
}
export default LongTextField
+87
View File
@@ -0,0 +1,87 @@
import React, { useEffect, useRef, useState } from 'react'
import type { FieldProps } from './field-types'
const NumberField: React.FC<FieldProps<number | undefined>> = ({
value,
config,
onSave,
readOnly,
}) => {
const numberConfig = config?.number
const [isEditing, setIsEditing] = useState(false)
// Store as string to allow intermediate states like "1." or empty
const [localValue, setLocalValue] = useState('')
const inputRef = useRef<HTMLInputElement>(null)
useEffect(() => {
setLocalValue(value !== undefined && value !== null ? value.toString() : '')
}, [value])
useEffect(() => {
if (isEditing && inputRef.current) {
inputRef.current.focus()
}
}, [isEditing])
const handleStartEdit = () => {
if (!readOnly) {
setIsEditing(true)
}
}
const handleBlur = () => {
setIsEditing(false)
if (localValue === '') {
onSave(undefined) // Handle empty
} else {
const num = parseFloat(localValue)
onSave(isNaN(num) ? undefined : num)
}
}
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'Enter') {
e.stopPropagation()
inputRef.current?.blur()
}
}
const formatNumber = (val: number | undefined) => {
if (val === undefined || val === null || isNaN(val)) return ''
return val.toFixed(numberConfig?.scale)
}
if (isEditing) {
return (
<input
ref={inputRef}
type="number"
step={1 / Math.pow(10, numberConfig?.scale || 0)}
value={localValue}
onChange={(e) => setLocalValue(e.target.value)}
onBlur={handleBlur}
onKeyDown={handleKeyDown}
onDoubleClick={(e) => e.stopPropagation()}
className="w-full px-2 py-1 border border-blue-500 rounded bg-white text-sm outline-none shadow-sm text-left font-mono"
/>
)
}
return (
<div
onClick={handleStartEdit}
onDoubleClick={(e) => e.stopPropagation()}
className={`w-full min-h-[28px] px-2 py-1 text-sm text-gray-800 rounded border border-transparent transition-colors text-left font-mono ${
!readOnly ? 'cursor-pointer hover:bg-gray-100 hover:border-gray-200' : ''
}`}
>
{value !== undefined && value !== null ? (
formatNumber(value)
) : (
<span className="text-gray-400 italic font-sans text-left block">Empty</span>
)}
</div>
)
}
export default NumberField
+56
View File
@@ -0,0 +1,56 @@
import { Star } from 'lucide-react'
import React, { useState } from 'react'
import type { FieldProps } from './field-types'
const RatingField: React.FC<FieldProps<number>> = ({ value, config, onSave, readOnly }) => {
const ratingConfig = config?.rating
const max = Math.max(2, Math.min(6, ratingConfig?.maxValue || 5)) // Clamp 2-6
const [hoverValue, setHoverValue] = useState<number | null>(null)
const handleClick = (e: React.MouseEvent, rating: number) => {
e.stopPropagation()
if (readOnly) return
let newValue
if (value === rating) {
newValue = 0 // Toggle off
} else {
newValue = rating
}
onSave(newValue)
}
const stars = Array.from({ length: max }, (_, i) => i + 1)
return (
<div
className="flex items-center gap-1 h-[28px]"
onMouseLeave={() => !readOnly && setHoverValue(null)}
onDoubleClick={(e) => e.stopPropagation()}
>
{stars.map((star) => {
const isFilled = hoverValue !== null ? star <= hoverValue : star <= (value || 0)
return (
<button
key={star}
onClick={(e) => handleClick(e, star)}
onMouseEnter={() => !readOnly && setHoverValue(star)}
className={`focus:outline-none transition-transform ${
!readOnly ? 'cursor-pointer hover:scale-110' : 'cursor-default'
}`}
type="button"
disabled={readOnly}
>
<Star
className={`w-5 h-5 transition-colors ${
isFilled ? 'fill-yellow-400 text-yellow-400' : 'fill-gray-100 text-gray-300'
}`}
/>
</button>
)
})}
</div>
)
}
export default RatingField
+97
View File
@@ -0,0 +1,97 @@
import type { SelectOption } from '@/dtos/metadata'
import { ChevronDown, X } from 'lucide-react'
import React, { useEffect, useRef, useState } from 'react'
import type { FieldProps } from './field-types'
const SelectField: React.FC<FieldProps<string>> = ({ value, config, onSave, readOnly }) => {
const selectConfig = config?.select
const [isEditing, setIsEditing] = useState(false)
const containerRef = useRef<HTMLDivElement>(null)
const selectedOption = selectConfig?.options?.find((opt: SelectOption) => opt.id === value)
// Click outside handler
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
if (isEditing) {
setIsEditing(false)
}
}
}
document.addEventListener('mousedown', handleClickOutside)
return () => document.removeEventListener('mousedown', handleClickOutside)
}, [isEditing])
const handleStartEdit = () => {
if (!readOnly) {
setIsEditing(true)
}
}
const handleSelect = (optionId: string) => {
onSave(optionId)
setIsEditing(false)
}
const renderOptionBadge = (option: SelectOption | undefined) => {
if (!option) return <span className="text-gray-400 italic">Select an option</span>
return (
<span
className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium"
style={{
backgroundColor: `${option.color}33`,
color: option.color || undefined,
}} // 33 is approx 20% opacity hex
>
{option.displayName}
</span>
)
}
return (
<div className="relative w-full" ref={containerRef}>
<div
onClick={handleStartEdit}
className={`flex items-center justify-between w-full min-h-[28px] px-2 py-1 rounded border border-transparent transition-colors ${
!readOnly ? 'cursor-pointer hover:bg-gray-100 hover:border-gray-200 group' : ''
}`}
>
{renderOptionBadge(selectedOption)}
{!readOnly && (
<ChevronDown className="w-4 h-4 text-gray-400 opacity-0 group-hover:opacity-100" />
)}
</div>
{isEditing && (
<div className="absolute z-50 top-full left-0 mt-1 w-full min-w-[150px] bg-white border border-gray-200 rounded-lg shadow-lg py-1 max-h-60 overflow-auto">
<div
onClick={() => handleSelect('')}
className="px-3 py-2 text-sm text-gray-500 hover:bg-gray-50 cursor-pointer flex items-center gap-2"
>
<X className="w-3 h-3" /> Clear
</div>
{selectConfig?.options?.map((option: SelectOption) => (
<div
key={option.id}
onClick={() => handleSelect(option.id)}
className="px-3 py-2 hover:bg-gray-50 cursor-pointer flex items-center"
>
<span
className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium"
style={{
backgroundColor: `${option.color}33`,
color: option.color || undefined,
}}
>
{option.displayName}
</span>
</div>
))}
</div>
)}
</div>
)
}
export default SelectField
@@ -0,0 +1,221 @@
import { Check } from 'lucide-react'
import React, { useEffect, useLayoutEffect, useRef, useState } from 'react'
import type { FieldProps } from './field-types'
import type { SelectOption } from '@/dtos/metadata'
const SelectMultiField: React.FC<FieldProps<string[]>> = ({
value = [],
config,
onSave,
readOnly,
}) => {
const selectConfig = config?.selectMulti
const containerRef = useRef<HTMLDivElement>(null)
const dropdownRef = useRef<HTMLDivElement>(null)
const [isEditing, setIsEditing] = useState(false)
const [expanded, setExpanded] = useState(false)
const [visibleCount, setVisibleCount] = useState(value.length)
const selectedOptions =
selectConfig?.options?.filter((opt: SelectOption) => (value || []).includes(opt.id)) || []
// Dynamic calculation for how many items fit in one line
useLayoutEffect(() => {
if (isEditing || expanded) {
// When editing or expanded, we technically don't use visibleCount for rendering
// (we render all), but keeping state clean is good.
setVisibleCount(selectedOptions.length)
return
}
if (containerRef.current) {
const containerWidth = containerRef.current.offsetWidth
const canvas = document.createElement('canvas')
const context = canvas.getContext('2d')
if (context) {
context.font = '12px ui-sans-serif, system-ui, sans-serif'
let currentWidth = 0
let count = 0
const moreBadgeWidth = 28
// We use a small buffer to be safe
const maxAvailableWidth = containerWidth - moreBadgeWidth
for (let i = 0; i < selectedOptions.length; i++) {
const textWidth = context.measureText(selectedOptions[i].displayName).width
const badgeWidth = textWidth + 16 + 4 // 16px padding, 4px gap
if (currentWidth + badgeWidth > maxAvailableWidth && i < selectedOptions.length - 1) {
break
}
if (i === selectedOptions.length - 1) {
if (currentWidth + badgeWidth <= containerWidth) {
count++
}
break
}
currentWidth += badgeWidth
count++
}
setVisibleCount(count)
}
}
}, [selectedOptions, isEditing, expanded, value])
// Click outside to close dropdown or expanded view
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
// Check if click is outside both the main container and the dropdown
const isOutsideDropdown =
!dropdownRef.current || !dropdownRef.current.contains(event.target as Node)
const isOutsideContainer =
!containerRef.current || !containerRef.current.contains(event.target as Node)
if (isOutsideDropdown && isOutsideContainer) {
if (isEditing) {
setIsEditing(false)
}
if (expanded) {
setExpanded(false)
}
}
}
document.addEventListener('mousedown', handleClickOutside)
return () => document.removeEventListener('mousedown', handleClickOutside)
}, [isEditing, expanded])
const toggleOption = (optionId: string) => {
const currentVal = value || []
let newVal
if (currentVal.includes(optionId)) {
newVal = currentVal.filter((id) => id !== optionId)
} else {
newVal = [...currentVal, optionId]
}
onSave(newVal)
}
const handlePlaceholderClick = (e: React.MouseEvent) => {
e.stopPropagation()
if (isEditing) return
// "if there is hidden items, first click will expand"
const hiddenCount = selectedOptions.length - visibleCount
if (!expanded && hiddenCount > 0) {
setExpanded(true)
} else {
// "if there is no hidden items, will change to edit mode"
if (!readOnly) {
setIsEditing(true)
}
}
}
const handleOverlayClick = (e: React.MouseEvent) => {
e.stopPropagation()
// "second click (on expanded) will change to edit mode"
if (!readOnly) {
setIsEditing(true)
}
}
const hiddenCount = selectedOptions.length - visibleCount
return (
<div className="relative w-full">
{/* Placeholder Display Mode */}
<div
ref={containerRef}
onClick={handlePlaceholderClick}
className={`w-full px-1 py-1 flex flex-wrap gap-1 rounded border border-transparent transition-all box-border h-[32px] overflow-hidden ${
!readOnly || hiddenCount > 0
? 'cursor-pointer hover:bg-gray-100 hover:border-gray-200'
: ''
}`}
>
{selectedOptions.length === 0 && (
<span className="text-gray-400 text-sm italic px-1 pt-0.5">Empty</span>
)}
{/* Render visible items */}
{selectedOptions.slice(0, visibleCount).map((option: SelectOption) => (
<span
key={option.id}
className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium border border-transparent whitespace-nowrap h-[22px]"
style={{
backgroundColor: `${option.color}33`,
color: option.color || undefined,
}}
>
{option.displayName}
</span>
))}
{hiddenCount > 0 && (
<span className="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-gray-200 text-gray-600 h-[22px]">
+{hiddenCount}
</span>
)}
</div>
{/* Expanded Overlay Mode */}
{expanded && !isEditing && (
<div
onClick={handleOverlayClick}
className={`absolute top-0 left-0 w-full px-1 py-1 flex flex-wrap gap-1 bg-white rounded border border-blue-500 shadow-lg z-50 min-h-[32px] h-auto ${
!readOnly ? 'cursor-pointer' : ''
}`}
>
{selectedOptions.length === 0 && (
<span className="text-gray-400 text-sm italic px-1 pt-0.5">Empty</span>
)}
{selectedOptions.map((option: SelectOption) => (
<span
key={option.id}
className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium border border-transparent whitespace-nowrap h-[22px]"
style={{
backgroundColor: `${option.color}33`,
color: option.color || undefined,
}}
>
{option.displayName}
</span>
))}
</div>
)}
{/* Edit Mode Dropdown */}
{isEditing && (
<div
ref={dropdownRef}
className="absolute z-50 top-full left-0 mt-1 w-64 bg-white border border-gray-200 rounded-lg shadow-xl max-h-60 overflow-auto"
>
{selectConfig?.options?.map((option: SelectOption) => {
const isSelected = (value || []).includes(option.id)
return (
<div
key={option.id}
onClick={() => toggleOption(option.id)}
className="px-3 py-2 hover:bg-gray-50 cursor-pointer flex items-center justify-between"
>
<span
className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium"
style={{
backgroundColor: `${option.color}33`,
color: option.color || undefined,
}}
>
{option.displayName}
</span>
{isSelected && <Check className="w-4 h-4 text-blue-500" />}
</div>
)
})}
</div>
)}
</div>
)
}
export default SelectMultiField
+63
View File
@@ -0,0 +1,63 @@
import React, { useEffect, useRef, useState } from 'react'
import type { FieldProps } from './field-types'
const TextField: React.FC<FieldProps<string>> = ({ value, onSave, readOnly }) => {
const [isEditing, setIsEditing] = useState(false)
const [localValue, setLocalValue] = useState(value || '')
const inputRef = useRef<HTMLInputElement>(null)
// Sync with prop updates
useEffect(() => {
setLocalValue(value || '')
}, [value])
useEffect(() => {
if (isEditing && inputRef.current) {
inputRef.current.focus()
}
}, [isEditing])
const handleStartEdit = () => {
if (!readOnly) {
setIsEditing(true)
}
}
const handleBlur = () => {
setIsEditing(false)
onSave(localValue)
}
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'Enter') {
inputRef.current?.blur()
}
}
if (isEditing) {
return (
<input
ref={inputRef}
type="text"
value={localValue}
onChange={(e) => setLocalValue(e.target.value)}
onBlur={handleBlur}
onKeyDown={handleKeyDown}
className="w-full px-2 py-1 border border-blue-500 rounded bg-white text-sm outline-none shadow-sm"
/>
)
}
return (
<div
onClick={handleStartEdit}
className={`w-full min-h-[28px] px-2 py-1 text-sm text-gray-800 rounded truncate border border-transparent transition-colors ${
!readOnly ? 'cursor-pointer hover:bg-gray-100 hover:border-gray-200' : ''
}`}
>
{value || <span className="text-gray-400 italic">Empty</span>}
</div>
)
}
export default TextField
+42
View File
@@ -0,0 +1,42 @@
import type { FieldInfo as MetadataFieldInfo } from '@/dtos/metadata'
import React from 'react'
interface FieldProps {
value: boolean
config: MetadataFieldInfo['config']
onSave: (value: boolean) => void
readOnly?: boolean
}
const ToggleField: React.FC<FieldProps> = ({ value, onSave, readOnly }) => {
// Toggle is instant edit, doesn't really have a separate "Edit mode" UI structure other than interaction.
const handleToggle = (e: React.MouseEvent) => {
e.stopPropagation()
if (!readOnly) {
const newValue = !value
onSave(newValue)
}
}
return (
<div
onClick={handleToggle}
className={`flex items-center h-[28px] w-full ${!readOnly ? 'cursor-pointer' : ''}`}
>
<div
className={`relative inline-flex h-5 w-9 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 ${
value ? 'bg-green-500' : 'bg-gray-300'
} ${readOnly ? 'opacity-70' : ''}`}
>
<span
className={`inline-block h-3.5 w-3.5 transform rounded-full bg-white transition duration-200 ease-in-out ${
value ? 'translate-x-4.5' : 'translate-x-1'
}`}
style={{ transform: value ? 'translateX(18px)' : 'translateX(4px)' }}
/>
</div>
</div>
)
}
export default ToggleField