All files / layers / L2R / surfaces CrudSurface.tsx

71.85% Statements 217/302
70.75% Branches 225/318
78.68% Functions 48/61
78.5% Lines 168/214

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 415 416 417 418 419 420                    69x   69x   4x 4x                       5x 4x                     69x   34x 34x                   69x   368x   49x 4x                 69x   108x 51x 18x 18x 2x 51x 20x 12x 4x 20x 20x 20x 33x 33x 33x 8x 20x   4x     4x 4x                               31x 23x   8x 23x     23x 4x 4x 6x 1x 29x     1976x 1976x 1976x 1976x 1976x                         383x 383x 383x   1976x 1976x 383x               383x 382x   33x 204x                   33x       148x                 22x         1x                 59x 456x         456x     4x 1x 1x                                   18x 18x         2x           24x     2x 148x         148x   192x   14x     1x         164x   4x     383x             670x       7x                       1976x                             125x   125x 125x   125x   2x     125x 83x 1828x       125x 102x 16x 10x 6x 6x       125x   125x   125x 125x 125x   125x 6x 6x 6x 1834x     125x 5x 1390x 1390x 1390x 1390x 1390x 1390x 420x   5x 5x 1390x 466x 125x 6x               2x 1390x 1390x 1390x 1390x 1390x 1390x 29x 29x 29x 58x         1390x 10x 383x 10x 79x 79x 79x 79x 79x   10x 10x             1390x           1x 1x     1x 1x                            
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,
  ConfigSchemaHelpNode,
} from '../../interfaces'
iImport { CrudModal } from '@/shared/components/CrudModal'
import { 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 {
 I if (overrides?.fragments?.loading) return overrides.fragments.loading
  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) {
  I  const str = typeof value === 'string' ? value.trim() : String(value ?? '').trim()
    Iif (!str) return 'This field is required'
  }
I
  if (Array.isArray(value) && validation.array) {
    Iif (validation.array.maxItems != null && value.length > validation.array.maxItems) {
  E    return `Maximum ${validation.array.maxItems} entries`
    }
    Eif (validation.array.unique === true) {
    I  const seen = new Set<string>()
    I  for (const item of value) {
        Iif (typeof item !== 'string' || item === '') continue
        Iif (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') {
  I  Iif (validation.minLength && value.length < validation.minLength) {
      return `Minimum ${validation.minLength} characters`
    }
    Iif (validation.maxLength && value.length > validation.maxLength) {
      return `Maximum ${validation.maxLength} characters`
    }
    if (validation.pattern && value.trim() !== '') {
      const regex = new RegExp(validation.pattern)
      Eif (!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,
  fieldHelpNodes?: ConfigSchemaHelpNode[],
) {
  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>
    I    return (
          <EntitySelectField
            data={entitySelectDataField}
            value={value}
            onChange={(v) => updateField?.(field, v)}
            disabled={!isEditable}
          />
        )
      case 'kv-editor':
        Eif (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':
        Iif (!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)}
    I        readOnly={!isEditable}
            lint={fieldLint}
            help={fieldHelpNodes}
            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,
  fieldHelp,
  fieldConfigs,
  entitySelectData,
}: CrudSurfaceExtendedProps<TForm> & {
  updateField?: (field: string, value: unknown) => void
  cancel?: () => void
  fieldTypes?: Record<string, CrudFieldType>
  fieldLints?: Record<string, FieldLint>
  fieldHelp?: Record<string, ConfigSchemaHelpNode[]>
  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 Eif (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
  I    if (error) hasError = true
    }
    setErrors(newErrors)
    if (!hasError) submit()
  }, [orderedFields, formModel, fieldConfigs, submit])
 
  return (
    <>
      <CrEudModal
        open={open}
        title={titleLabel}
        isDirty={bridge.dirty}
        isPending={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],
                fieldLints?.[field],
                fieldHelp?.[field],
              ),
            )}
          </fieldset>
        </form>
      </CrudModal>
 
      {showBlockerDiscard && (
        <DiscardDialog
          open={showBlockerDiscard}
          onDiscard={() => {
            setShowBlockerDiscard(false)
            Eif (blocker.state === 'blocked') blocker.proceed()
          }}
          onKeepEditing={() => {
            setShowBlockerDiscard(false)
            Eif (blocker.state === 'blocked') blocker.reset()
          }}
        />
      )}
    </>
  )
}
 
export {
  type CrudSurfaceProps,
  type CoordinatorSnapshot,
  type CrudVisualOverrides,
  type FieldPolicy,
}