All files / layers / L2W coordinator.ts

90.34% Statements 262/290
80.24% Branches 130/162
87.5% Functions 49/56
95.3% Lines 203/213

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          628x 628x 628x 628x             218x 218x 218x 168x 168x     628x 228x 10x 10x           628x 628x 628x 628x 628x 628x 628x 628x 628x 628x 628x 628x 628x 628x 628x 628x       628x   56x 56x 56x 175x 96x 175x 58x   175x 56x 175x 56x 56x 58x 58x 628x 628x 58x   628x 628x 223x 108x 628x 223x 1x 1x 175x 1x 175x 58x   175x 175x     628x 223x 5x 5x 175x 5x 5x 175x 175x 175x 175x   175x 175x 628x 223x 217x 217x 217x 217x 175x   628x 222x 222x 222x 222x 2x 1x 1x 175x   4x 4x 4x 4x 634x 7x       4x     175x   628x 628x 1x 1x 175x 1x 175x 61x 1x 1x 175x 61x 5x 5x 5x 5x 5x       175x 61x 26x 26x 26x 26x 26x 26x       628x 628x 29x 29x 628x 29x       175x 67x 628x 628x 628x 628x 222x 1x 1x   1x 1x   1x 1x               628x 1x 106x   628x 1x 175x 10x 10x 10x 10x 628x   10x 628x 942x 255x     7x 3x 1x 1x 1x 1x                 942x   175x   175x 2x     175x   954x 12x         175x 175x 175x   175x 67x 8x 628x 5x   5x     5x   8x 628x         175x 7x 7x 68x   175x 11x 11x 11x 11x 11x     175x 2x     175x 175x 85x                                   175x 175x                             175x 62x               175x     59x        
import { useState, useEffect, useRef, useCallback, useMemo } from 'react'
import type {
  RouteContext,
  EntityHooks,
  BehaviorContract,
  CoordinatorSnapshot,
  CrudContext,
  FailureIntent,
  FieldPolicy,
  QueryParams,
  OfflineState,
  DeleteState,
  EntitySelectSource,
  EntitySelectOptionData,
} from '../interfaces'
import { useFormBridge } from './formBridge'
import type { FormBridgeControl } from './formBridge'
import { useEntityList } from '../L1/entityResolver'
import type { EntityPath } from '../L1/contracts'
 
export interface CoordinatorConfig<
  TEntity extends { id: string },
  TForm,
  TCreate,
  TIUpdate,
  TListQuery extends QueryParams = QueryParams,
> {
  hooks: EntityHooks<TEntity, TCreate, TUpdate, TListQuery>
  behavior: BehaviorContract<TEntity, TForm, TCreate, TUpdate>
  owner: string
  entitySelectSources?: Record<string, EntitySelectSource>
}
 
export interface UseCoordinatorResult<TForm> {
  snapshot: CoordinatorSnapshot<TForm>
  updateField: (field: string, value: unknown) => void
  setFormModel: (model: TForm) => void
  cancel: () => void
  offlineState: OfflineState
}
 
export function createCoordinator<
  TEntity extends { id: string },
  TForm = TEntity,
  TCreate = Partial<TEntity>,
  TUpdate = Partial<TEntity>,
  TListQuery extends QueryParams = QueryParams,
>(
  config: CoordinatorConfig<TEntity, TForm, TCreate, TUpdate, TListQuery>,
): {
  useCoordinator: (
    routeContext: RouteContext,
  ) => UseCoordinatorResult<TForm>
} {
  function useCoordinator(routeContext: RouteContext): UseCoordinatorResult<TForm> {
    const crud = routeContext.crud

    const [isOnline, setIsOnline] = useState(() =>
      typeof navigator !== 'undefined' ? navigator.onLine : true,
    )
    const [lastSynced, setLastSynced] = useState<Date | null>(null)
 
    useEffect(() => {
      function handleOnline() { setIsOnline(true) }
      function handleOffline() { setIsOnline(false) }
      window.addEventListener('online', handleOnline)
      window.addEventListener('offline', handleOffline)
      return () => {
        window.removeEventListener('online', handleOnline)
        window.removeEventListener('offline', handleOffline)
      }
    }, [])
 
    const activeCrud: CrudContext | null = useMemo(() => {
      if (!crud) return null
      if (crud.owner !== config.owner) return null
      return { mode: crud.mode, owner: crud.owner, prefix: crud.prefix }
    }, [crud])
 
    const mode = activeCrud?.mode ?? null
 
    const [formModel, setFormModel] = useState<TForm>(() =>
      config.behavior.defaults(),
    )
    const formModelRef = useRef(formModel)
    formModelRef.current = formModel
 
    const {
      bridge,
      setDirty,
      setPending,
      markDirty,
      reset: resetBridge,
    }: FormBridgeControl = useFormBridge()
 
    const mutation = config.hooks.useMutation()
    const prevPendingRef = useRef(mutation.isPending)
    const submitRef = useRef<() => void>(() => {})
    const submitIntentRef = useRef(false)
 
    const [failure, setFailure] = useState<FailureIntent | null>(null)
    const [closeIntent, setCloseIntent] = useState<{
      type: 'success' | 'cancel'
    } | null>(null)
 
    const detailId =
      routeContext.page === 'detail' ? routeContext.id : ''
 
    const detail = config.hooks.useEntityDetail(
      activeCrud?.mode === 'edit' ? detailId : '',
    )
 
    const sources = config.entitySelectSources ?? {}
    const sourceEntries = Object.entries(sources)
    const nextEntitySelectData: Record<string, EntitySelectOptionData> = {}
    // The following loop always iterates the same number of times for a given
    // coordinator instance (entitySelectSources is a stable config). The
    // hooks-in-loop warning is a false positive for determinant iterations.
    Ifor (const [field, source] of sourceEntries) {
      // eslint-disable-next-line react-hooks/rules-of-hooks
      const listResult = useEntityList(source.entityPath as EntityPath, {})
      const idField = source.idField ?? 'id'
      const nameField = source.nameField ?? 'name'
      const descField = source.descriptionField
      const options = (listResult.data ?? []).map((item: Record<string, unknown>) => ({
        value: String(item[idField] ?? ''),
        label: String(item[nameField] ?? ''),
        ...(descField ? { description: String(item[descField] ?? '') } : {}),
      }))
      nextEntitySelectData[field] = { options, isLoading: listResult.isLoading, error: listResult.error }
    }
 
    const entitySelectDataRef = useRef<Record<string, EntitySelectOptionData>>(
      nextEntitySelectData,
    )
    Iif (JSON.stringify(entitySelectDataRef.current) !== JSON.stringify(nextEntitySelectData)) {
      entitySelectDataRef.current = nextEntitySelectData
    }
    const entitySelectData = entitySelectDataRef.current
 
    useEffect(() => {
      setCloseIntent(null)
    }, [mode])
 
    useEffect(() => {
      if (mode === 'edit' && detail.data) {
        conEst populated = config.behavior.populate(detail.data)
        setFormModel(populated)
        formModelRef.current = populated
        setDirty(false)
        setFailure(null)
      }
    }, [mode, detail.data, setDirty])

    useEffect(() => {
      if (mode === 'add') {
        const defaults = config.behavior.defaults()
        setFormModel(defaults)
        formModelRef.current = defaults
        setDirty(false)
        setFailure(null)
        resetBridge()
      }
    }, [mode, setDirty, resetBridge])
 
    useEffect(() => {
      if (!mode) {
        setFormModel(config.behavior.defaults())
        formModelRef.current = config.behavior.defaults()
        setFailure(null)
        resetBridge()
      }
    }, [mode, resetBridge])
 
    useEffect(() => {
      const wasPending = prevPendingRef.current
      const isNowPending = mutation.isPending
      prevPendingRef.current = isNowPending
 
      if (wasPending && !isNowPending) {
        if (!submitIntentRef.current) return
        submitIntentRef.current = false
    I    setPending(false)

        if (mutation.isError) {
          setFailure({
            cause: mutation.error,
    E        retry: submitRef.current,
          })
        } else E{
          setLastSynced(new Date())
          setCloseIntent({ type: 'success' })
        }
      }
    }, [mutation.isPending, mutation.isError, mutation.error, setPending])
 
    const fieldPolicy: FieldPolicy = useMemo(
      () =>
        activeCrud ? config.behavior.fieldPolicy(activeCrud.mode) : {},
      [activeCrud],
    )
I
    const submit = useCallback(() => {
      const currentForm = formModelRef.current
      submitIntentRef.current = true
      setPending(true)
      setFailure(null)
      setCloseIntent(null)

      try {
        if (mode === 'add') {
          const payload = config.behavior.toCreate(currentForm)
          const context = routeContext.page === 'detail' && routeContext.id
            ? { projectId: routeContext.id }
            : undefined
          mutation.create(payload, context)
        } else if (mode === 'edit') {
          const payload = config.behavior.toUpdate(currentForm)
          const id = routeContext.page === 'detail' ? routeContext.id : ''
          Iif (!id) return
          mutation.update(id, payload)
        }
      } catch (error: unknown) {
        setFailure({
          cause: error,
          retry: submitRef.current,
        })
        setPending(false)
      }
    }, [mode, routeContext, setPending, mutation])
 
    submitRef.current = submit
 
    const cancel = useCallback(() => {
      setCloseIntent({ type: 'cancel' })
    }, [])
 
    const updateField = useCallback(
      (field: string, value: unknown) => {
        setFormModel((prev) => ({ ...prev, [field]: value }))
        markDirty()
      },
      [markDirty],
    )
 
    const [showDeleteConfirm, setShowDeleteConfirm] = useState(false)
    const [deleteError, setDeleteError] = useState<unknown>(null)
    const deleteIntentRef = useRef(false)
 
    useEffect(() => {
      if (deleteIntentRef.current && !mutation.isPending) {
        deleteIntentRef.current = false
        if (mutation.isError) {
          const err = mutation.error as any
          const message =
            err?.response?.data?.error ??
            err?.message ??
            String(err ?? 'Delete failed')
          setDeleteError(message)
        }
        if (!mutation.isError) {
          setDeleteError(null)
        }
      }
    }, [mutation.isPending, mutation.isError, mutation.error])
 
    const requestDelete = useCallback(() => {
      setDeleteError(null)
      setShowDeleteConfirm(true)
    }, [])
 
    const confirmDelete = useCallback(() => {
      Iif (routeContext.page !== 'detail') return
      setShowDeleteConfirm(false)
      setDeleteError(null)
      deleteIntentRef.current = true
      mutation.remove(routeContext.id)
    }, [routeContext, mutation])
 
    const cancelDelete = useCallback(() => {
      setShowDeleteConfirm(false)
    }, [])
 
    const deleteState: DeleteState | null = useMemo(() => {
      if (routeContext.page !== 'detail') return null
      return {
        showConfirm: showDeleteConfirm,
        isPending: mutation.isPending && deleteIntentRef.current,
        error: deleteError,
        requestDelete,
        confirmDelete,
        cancelDelete,
      }
    }, [
      routeContext.page,
      showDeleteConfirm,
      mutation.isPending,
      deleteError,
      requestDelete,
      confirmDelete,
      cancelDelete,
    ])
 
    const snapshot: CoordinatorSnapshot<TForm> = useMemo(
      () => ({
        activeCrud,
        formModel,
        fieldPolicy,
        bridge,
        submit,
        failure,
        closeIntent,
        lastMutationData: mutation.lastMutationData,
        deleteState,
        entitySelectData,
      }),
      [activeCrud, formModel, fieldPolicy, bridge, submit, failure, closeIntent, mutation.lastMutationData, deleteState, entitySelectData],
    )
 
    const offlineState: OfflineState = useMemo(
      () => ({
        isOnline,
        pendingCount: mutation.isPending ? 1 : 0,
        lastSynced,
      }),
      [isOnline, mutation.isPending, lastSynced],
    )
 
    return { snapshot, updateField, setFormModel, cancel, offlineState }
  }
 
  return { useCoordinator }
}
 
export type { CoordinatorSnapshot, CrudContext, FailureIntent }