All files / layers / L2W coordinator.ts

90.54% Statements 268/296
80.12% Branches 133/166
90.74% Functions 49/54
95.92% Lines 212/221

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              648x 648x 648x 648x 648x 218x   648x 228x 10x 10x           648x 648x 223x 6x 6x       648x 648x 648x 648x 648x 648x 648x 648x 648x 648x 648x 648x 648x 648x 648x 648x       648x   56x 56x 56x 56x 96x 185x   185x   185x 185x   185x 648x   648x 648x 117x 89x 648x 648x 223x 185x 648x 223x 172x 87x 172x 10x 1x           185x 648x 223x 63x 5x 185x 185x 5x 5x         185x   648x 223x 217x 217x 217x 217x 185x 185x 648x 222x 222x 222x 222x 2x 185x 1x 1x   185x 185x 185x   1x 1x 185x   14x 14x 14x 14x 14x   654x 648x 1x 14x 1x 1x 185x 1x 1x 185x 1x 1x 185x   185x 66x     185x 66x 5x 5x 5x 5x 5x       185x 66x 29x 648x 648x 29x 29x 648x       185x 66x 31x 648x 648x 648x 648x 222x 1x 185x 72x 72x 72x   72x 4x 1x 1x   1x 1x     648x 1x 1x   648x 1x 1x 1x 185x 1x 114x 648x     648x 972x 282x 10x 10x 10x   10x 10x 7x 7x     7x 3x 1x 1x 1x 1x 972x                   185x   185x 2x     185x   660x 12x       648x 185x 185x 185x   185x 72x 8x 8x 648x   5x     5x   8x 68x         185x 7x 7x     185x 11x 11x 11x 11x 11x     185x 2x     185x 185x 85x                                   185x 185x                             185x 67x               185x     64x        
import { useState, useEffect, useRef, useCallback, useMemo } from 'react'
import { useQueryClient } from '@tanstack/react-query'
import type {
  RouteContext,
  EntityHooks,
  BehaviorContract,
  CoordinatorSnapshot,
  CrudContext,
  FailureIntent,
  FieldPolicy,
  QueryParams,
  OfflineState,
  DeleteState,
  EntitySelectSource,
  EntitySelectOptionData,
} from '../interfaces'
impIort { useFormBridge } from './formBridge'
import type { FormBridgeControl } from './formBridge'
import { useEntityList } from '../L1/entityResolver'
import type { EntityPath } from '../L1/contracts'
import { getOnlineDetector } from '@/lib/onlineDetector'
 
export interface CoordinatorConfig<
  TEntity extends { id: string },
  TForm,
  TCreate,
  TUpdate,
  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 detector = getOnlineDetector()
 
    const [isOnline, setIsOnline] = useState(() => detector.isOnline())
    const [lastSynced, setLastSynced] = useState<Date | null>(null)
 
    useEffect(() => {
      return detector.subscribe(() => setIsOnline(detector.isOnline()))
    }, [detector])
 
  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 queryClient = useQueryClient()
 
  useEffect(() => {
    if (!activeCrud) return
    const sources = config.entitySelectSources ?? {}
    for (const [, source] of Object.entries(sources)) {
      queryClient.refetchQueries(
        { queryKey: [source.entityPath] },
        { cancelRefetch: false },
      )
    }
  }, [activeCrud, queryClient])
 
  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 : '',
    I)

    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.
    for (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 eEntitySelectData = entitySelectDataRef.current

    useEffect(() => {
      setCloseIntent(null)
    }, [mode])
 
    useEffect(() => {
      if (mode === 'edit' && detail.data) {
        const 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])
 
    IuseEffect(() => {
      const wasPending = prevPendingRef.current
      const isNowPending = mutation.isPending
      prevPendingRef.current = isNowPending
 
    E  if (wasPending && !isNowPending) {
        if (!submitIntentRef.current) return
        submitIntentRef.current = false
        setPending(false)
 
        if (mutation.isError) {
          setFailure({
            cause: mutation.error,
            retry: submitRef.current,
          })
        } else E{
          setLastSynced(new Date())
          setCloseIntent({ type: 'success' })
        }
   I   }
    }, [mutation.isPending, mutation.isError, mutation.error, setPending])
 
    const fieldPolicy: FieldPolicy = useMemo(
      () =>
        activeCrud ? config.behavior.fieldPolicy(activeCrud.mode) : {},
      [activeCrud],
    )
 
    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 }