All files / layers / L2R / surfaces CrudSurface.tsx

65.45% Statements 108/165
58.78% Branches 97/165
72.72% Functions 24/33
71.83% Lines 102/142

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414                    125x   125x   16x 16x                                               125x   88x 88x                   125x   502x     6x                 125x   198x 104x 29x 29x   104x 39x     39x 39x 39x 66x 66x 66x   39x                                           65x 42x     42x     42x         65x     3008x 3008x 3008x 3008x 3008x                                 3008x 3008x 428x                       132x       2x                   290x                                               606x         606x     6x                                                                       290x         290x       24x               382x   10x                 880x       8x                       3008x                                                     2718x                                                           2464x 2464x 2464x 2464x 2464x 2464x 732x       2464x 824x 13x 13x                 2464x 2464x 2464x 2464x 2464x 2464x 50x 50x 50x 100x         2464x 23x 23x 23x 148x 148x 148x 148x 148x   23x 23x             2464x                                        
import { useCallback, useEffect, useState, type ReactNode } from 'react'
import { useBlocker } from 'react-router-dom'
import type {
  CrudSurfaceProps,
  CoordinatorSnapshot,
  CrudVisualOverrides,
  FieldPolicy,
  CrudFieldType,
  CrudFieldConfig,
  CrudFieldValidation,
  EntitySelectOptionData,
  FieldLint,
} from '../../interfaces'
import { CrudModal } from '@/shared/components/CrudModal'
iImport { DiscardDialog } from '@/shared/components/DiscardDialog'
import { EntitySelect } from '@/shared/components/EntitySelect'
import { EntitySelectList } from '@/shared/components/EntitySelectList'
import { KeyValueEditor } from '@/shared/components/KeyValueEditor'
import { YamlEditor } from '@/shared/components/YamlEditor'
import { dump } from 'js-yaml'
import { Button } from '@/components/ui/button'
 
export interface CrudSurfaceExtendedProps<TForm> extends CrudSurfaceProps<TForm> {
}
 
function ErrorFragment({ failure, overrides }: { failure: CoordinatorSnapshot<unknown>['failure']; overrides?: CrudVisualOverrides }): ReactNode {
  if (overrides?.fragments?.error) return overrides.fragments.error
  return (
    <div data-testid="crud-error" className="py-8 text-center text-sm text-destructive">
      <p>{failure ? String(failure.cause) : 'Unknown error'}</p>
      {failure && (
        <Button variant="outline" size="sm" data-testid="retry-button" onClick={failure.retry}>
          Retry
        </Button>
      )}
    </div>
  )
}
 
function LoadingFragment({ overrides }: { overrides?: CrudVisualOverrides }): ReactNode {
  if (overrides?.fragments?.loading) return overrides.fragments.loading
 I return <div data-testid="crud-loading" className="flex flex-col gap-3 py-8">Loading...</div>
}
 
function EntitySelectField({
  data,
  value,
  onChange,
  disabled,
}: {
  data: EntitySelectOptionData
  value: unknown
  onChange?: (val: unknown) => void
  disabled: boolean
}) {
  return (
    <EntitySelect
      options={data.options}
      value={value as string | undefined}
      onChange={(v) => onChange?.(v)}
      disabled={disabled}
      isLoading={data.isLoading}
    />
  )
}
 
function validateField(value: unknown, validation?: CrudFieldValidation): string | null {
  if (!validation) return null
 
  if (validation.required) {
    const str = typeof value === 'string' ? value.trim() : String(value ?? '').trim()
  I  if (!str) return 'This field is required'
  }
 
  Iif (Array.isArray(value) && validation.array) {
    if (validation.array.maxItems != null && value.length > validation.array.maxItems) {
      return `Maximum ${validation.array.maxItems} entries`
  E  }
    if (validation.array.unique === true) {
      const seen = new Set<string>()
    I  for (const item of value) {
    I    if (typeof item !== 'string' || item === '') continue
        if (seen.has(item)) return `Duplicate entry: ${item}`
        seen.add(item)
      }
      return null
    }
    const uniqueFields = validation.array.unique ?? []
    const seen: Record<string, Set<string>> = {}
    for (const item of value) {
      if (typeof item !== 'object' || item === null) return 'Invalid entry'
      const record = item as Record<string, unknown>
      for (const field of uniqueFields) {
        seen[field] ??= new Set<string>()
        const fieldValue = record[field]
        if (typeof fieldValue === 'string' && fieldValue !== '') {
          if (seen[field].has(fieldValue)) return `Duplicate ${field}: ${fieldValue}`
          seen[field].add(fieldValue)
        }
      }
      for (const [field, itemValidation] of Object.entries(validation.array.items ?? {})) {
        const itemError = validateField(record[field], itemValidation)
        if (itemError) return `${field}: ${itemError}`
      }
    }
    return null
  }
I
  if (typeof value === 'string') {
    if (validation.minLength && value.length < validation.minLength) {
  I    return `Minimum ${validation.minLength} characters`
    }
    if (validation.maxLength && value.length > validation.maxLength) {
  I    return `Maximum ${validation.maxLength} characters`
    }
    if (validation.pattern && value.trim() !== '') {
      const regex = new RegExp(validation.pattern)
      if (!regex.test(value)) return validation.patternMessage ?? 'Invalid format'
    }
  }
 
  return null
}
I
function renderField(
  field: string,
  value: unknown,
  policy: FieldPolicy[string] | undefined,
  updateField: ((field: string, value: unknown) => void) | undefined,
  fieldType: CrudFieldType | undefined,
  entitySelectDataField: EntitySelectOptionData | undefined,
  pending: boolean,
  fieldConfig?: CrudFieldConfig,
  error?: string | null,
  fieldLint?: FieldLint,
) {
  const isVisible = policy?.visible !== false
  const isEditable = policy?.editable !== false && !pending
  if (!isVisible) return null
 
  const labelText = fieldConfig?.title ?? field
  const label = (
    <label htmlFor={`field-${field}`} className="text-sm font-medium mb-1 block">
      {labelText}
      {fieldConfig?.tooltip && (
        <span className="ml-1 cursor-help" title={fieldConfig.tooltip}>&#x24D8;</span>
      )}
    </label>
  )
 
  const input = (() => {
    switch (fieldType) {
      case 'textarea':
        return (
          <textarea
            id={`field-${field}`}
            value={String(value ?? '')}
            onChange={(e) => updateField?.(field, e.target.value)}
            disabled={!isEditable}
            data-testid={`crud-input-${field}`}
            className="flex min-h-[5rem] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:opacity-50"
          />
        )
      case 'password':
        return (
          <input
            id={`field-${field}`}
            type="password"
            value={String(value ?? '')}
            onChange={(e) => updateField?.(field, e.target.value)}
            disabled={!isEditable}
            placeholder="••••••••"
            data-testid={`crud-input-${field}`}
            className="flex h-9 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:opacity-50"
          />
        )
      case 'checkbox':
        return (
          <label className="flex items-center gap-2">
            <input
              type="checkbox"
              checked={!!value}
              onChange={(e) => updateField?.(field, e.target.checked)}
              disabled={!isEditable}
              data-testid={`crud-input-${field}`}
              className="size-4 cursor-pointer"
            />
            {' '}{fieldConfig?.title ?? field}
          </label>
        )
      case 'entity-select':
        if (!entitySelectDataField) return <p>Missing entitySelectData</p>
        return (
          <EntitySelectField
    I        data={entitySelectDataField}
            value={value}
            onChange={(v) => updateField?.(field, v)}
            disabled={!isEditable}
          />
        )
      case 'kv-editor':
        if (isEditable) {
          return (
            <KeyValueEditor
              value={(value as Record<string, string>) ?? {}}
              onChange={(v) => updateField?.(field, v)}
              readOnly={!isEditable}
            />
          )
        }
        return (
          <div className="mt-2">
            <KeyValueEditor
              value={(value as Record<string, string>) ?? {}}
              onChange={() => {}}
              readOnly
            />
          </div>
        )
      case 'entity-select-list':
        if (!entitySelectDataField) return <p>Missing entitySelectData</p>
        return (
          <EntitySelectList
            value={value}
            options={entitySelectDataField.options}
            isLoading={entitySelectDataField.isLoading}
            onChange={(v) => updateField?.(field, v)}
            readOnly={!isEditable}
            data-testid={`crud-input-${field}`}
          />
        )
      case 'yaml':
        return (
          <YamlEditor
            value={value == null ? '' : typeof value === 'object' ? dump(value) : String(value)}
            onChange={(v) => updateField?.(field, v)}
            readOnly={!isEditable}
            lint={fieldLint}
    I        data-testid={`crud-input-${field}`}
          />
        )
      default:
        return (
          <input
            id={`field-${field}`}
            type="text"
            value={String(value ?? '')}
            onChange={(e) => updateField?.(field, e.target.value)}
            disabled={!isEditable}
            readOnly={!isEditable}
            data-testid={`crud-input-${field}`}
            className="flex h-9 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:opacity-50"
          />
        )
    }
  })()
 
  if (fieldType === 'checkbox') return (
    <div key={field} data-testid={`crud-field-${field}`}>
      {input}
      {fieldConfig?.description && <p className="mt-1 text-xs text-muted-foreground">{fieldConfig.description}</p>}
      {error && <p className="mt-1 text-xs text-destructive" data-testid={`crud-error-${field}`}>{error}</p>}
    </div>
  )
  return (
    <div key={field} data-testid={`crud-field-${field}`}>
      {label}
      {input}
      {fieldConfig?.description && <p className="mt-1 text-xs text-muted-foreground">{fieldConfig.description}</p>}
      {error && <p className="mt-1 text-xs text-destructive" data-testid={`crud-error-${field}`}>{error}</p>}
    </div>
  )
}
 
export function CrudSurface<TForm>({
  coordinatorSnapshot,
  onClose,
  onSuccess,
  overrides,
  updateField,
  cancel,
  fieldTypes,
  fieldLints,
  fieldConfigs,
  entitySelectData,
}: CrudSurfaceExtendedProps<TForm> & {
  updateField?: (field: string, value: unknown) => void
  cancel?: () => void
  fieldTypes?: Record<string, CrudFieldType>
  fieldLints?: Record<string, FieldLint>
  fieldConfigs?: Record<string, CrudFieldConfig>
  entitySelectData?: Record<string, EntitySelectOptionData>
}) {
  const { closeIntent, failure, bridge, submit, activeCrud, formModel, fieldPolicy } = coordinatorSnapshot

  const [showBlockerDiscard, setShowBlockerDiscard] = useState(false)
  const [errors, setErrors] = useState<Record<string, string | null>>({})
 
  const blocker = useBlocker(
    ({ currentLocation, nextLocation }) =>
      !!activeCrud && bridge.dirty && !closeIntent && currentLocation.pathname !== nextLocation.pathname
  )
 
  useEffect(() => {
    if (blocker.state === 'blocked') {
      setShowBlockerDiscard(true)
    }
  }, [blocker.state])
 
  useEffect(() => {
    if (!closeIntent) return
    if (closeIntent.type === 'success') {
      onSuccess()
    } else if (closeIntent.type === 'cancel') {
      onClose()
    }
  }, [closeIntent, onSuccess, onClose])
 
  const open = activeCrud !== null
 
  const orderedFields = overrides?.fieldOrder ?? Object.keys(fieldPolicy)
 
  const titleLabel = overrides?.labels?.title ?? (activeCrud?.mode === 'add' ? 'Create' : 'Edit')
  const saveLabel = overrides?.labels?.save ?? 'Save'
  const cancelLabel = overrides?.labels?.cancel ?? 'Cancel'
 
  const handleFieldChange = useCallback((field: string, value: unknown) => {
    updateField?.(field, value)
    const config = fieldConfigs?.[field]
    const error = validateField(value, config?.validation)
    setErrors(prev => ({ ...prev, [field]: error }))
  }, [updateField, fieldConfigs])
 
  const handleSave = useCallback(() => {
    const newErrors: Record<string, string | null> = {}
    let hasError = false
    for (const field of orderedFields) {
      const value = (formModel as Record<string, unknown>)[field]
      const config = fieldConfigs?.[field]
      const error = validateField(value, config?.validation)
      newErrors[field] = error
      if (error) hasError = true
    }
    setErrors(newErrors)
    if (!hasError) submit()
  I}, [orderedFields, formModel, fieldConfigs, submit])

  return (
    <>
      <CrudModal
        open={open}
        title={titleLabel}
        isDirty={bridge.dirty}
        iEsPending={bridge.pending}
        saveLabel={saveLabel}
        cancelLabel={cancelLabel}
        onClose={() => cancel?.()}
        onSave={handleSave}
      >
 
        {failure && <ErrorFragment failure={failure} overrides={overrides} />}
 
        {bridge.pending && !failure && <LoadingFragment overrides={overrides} />}
 
        <form
          data-testid="crud-form"
          onSubmit={(e) => {
            e.preventDefault()
            handleSave()
          }}
        >
          <fieldset disabled={bridge.pending} style={{ border: 'none', padding: 0, margin: 0 }}>
            {orderedFields.map((field) =>
              renderField(
                field,
                (formModel as Record<string, unknown>)[field],
                fieldPolicy[field],
                handleFieldChange,
                fieldTypes?.[field],
                entitySelectData?.[field],
                bridge.pending,
                fieldConfigs?.[field],
                errors[field],
   I             fieldLints?.[field],
              ),
            )}
  E        </fieldset>
        </form>
      </CrudModal>
 
      {showBlockerDiscard && (
        <DiscardDialog
          open={showBlockerDiscard}
          onDiscard={() => {
            setShowBlockerDiscard(false)
            if (blocker.state === 'blocked') blocker.proceed()
          }}
          onKeepEditing={() => {
            setShowBlockerDiscard(false)
            if (blocker.state === 'blocked') blocker.reset()
          }}
        />
      )}
    </>
  )
}
 
export {
  type CrudSurfaceProps,
  type CoordinatorSnapshot,
  type CrudVisualOverrides,
  type FieldPolicy,
}