All files / layers / L2R / surfaces CrudSurface.tsx

54.26% Statements 70/129
39.02% Branches 48/123
45.16% Functions 14/31
58.92% Lines 66/112

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                37x   37x                                                     37x   4x 4x                   37x                           37x   2x                                       64x 64x 64x 64x 64x                                 64x 64x 12x                       4x                                                                                                                                                                 48x                               64x                                                     64x                                                           480x 480x 480x 480x 480x 480x 172x       480x 180x 1x 1x                 480x 480x 480x 480x 480x 480x                 480x 1x 1x 1x 2x 2x 2x 2x 2x   1x 1x             480x                                                  
import { useCallback, useEffect, useState, type ReactNode } from 'react'
import { useBlocker } from 'react-router-dom'
import type {
  CrudSurfaceProps,
  CoordinatorSnapshot,
  CrudVisualOverrides,
  FieldPolicy,
  CrudFieldType,
  CrudFieldConfig,
  CrudFieldValidation,
  EntitySelectOptionData,
} from '../../interfaces'
import { CrudModal } from '@/shared/components/CrudModal'
import { DiscardDialog } from '@/shared/components/DiscardDialog'
import { OfflineIndicator } from '../offline/OfflineIndicator'
import { EntitySelect } from '@/shared/components/EntitySelect'
import { KeyValueEditor } from '@/shared/components/KeyValueEditor'
import type { OfflineState } from '../../interfaces'
import { Button } from '@/components/ui/button'
 
export interface CrudSurfaceExtendedProps<TForm> extends CrudSurfaceProps<TForm> {
  offlineState: OfflineState
}
 
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 {
 E if (!validation) return null

  if (validation.required) {
    const str = typeof value === 'string' ? value.trim() : String(value ?? '').trim()
    if (!str) return 'This field is required'
  }

  if (typeof value === 'string') {
    if (validation.minLength && value.length < validation.minLength) {
      return `Minimum ${validation.minLength} characters`
    }
    if (validation.maxLength && value.length > validation.maxLength) {
      return `Maximum ${validation.maxLength} characters`
    }
    if (validation.pattern) {
      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,
) {
  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
            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>
        )
      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,
 I onClose,
  onSuccess,
  overrides,
  offlineState,
  updateField,
  cancel,
  fieldTypes,
  fieldConfigs,
  entitySelectData,
}: CrudSurfaceExtendedProps<TForm> & {
  updateField?: (field: string, value: unknown) => void
  cancel?: () => void
  fieldTypes?: Record<string, CrudFieldType>
  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)
  I    newErrors[field] = error
      if (error) hasError = true
    }
    setErrors(newErrors)
    if (!hasError) submit()
  }, [orderedFields, formModel, fieldConfigs, submit])
 
  return (
    <>E
      <CrudModal
        open={open}
        title={titleLabel}
        isDirty={bridge.dirty}
        isPending={bridge.pending}
        saveLabel={saveLabel}
        cancelLabel={cancelLabel}
        onClose={() => cancel?.()}
        onSave={handleSave}
      >
        <OfflineIndicator state={offlineState} />
 
        {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],
   I             handleFieldChange,
                fieldTypes?.[field],
                entitySelectData?.[field],
  E              bridge.pending,
                fieldConfigs?.[field],
                errors[field],
              ),
            )}
          </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,
}