All files / libs/reporting/custom-reports/views/details/src/lib useCustomReportEditingState.ts

0% Statements 0/60
0% Branches 0/1
0% Functions 0/1
0% Lines 0/60

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                                                                                                                         
import { useCallback, useEffect, useState } from 'react';

import { useBoolState } from '@amalia/ext/react/hooks';
import { canModifyCustomReports } from '@amalia/kernel/auth/shared';
import { useAbilityContext } from '@amalia/kernel/auth/state';
import { type CustomReport } from '@amalia/reporting/custom-reports/shared';
import { useCustomReport } from '@amalia/reporting/custom-reports/state';

export const useCustomReportEditingState = (reportId: string) => {
  const ability = useAbilityContext();

  // To fetch the report from the API.
  const {
    data: customReportFromApi,
    error: customReportError,
    isLoading: isCustomReportLoading,
  } = useCustomReport(reportId);

  // Proxy state for the editor configuration.
  const [customReportEditingState, setCustomReportEditingState] = useState<CustomReport | null>(null);

  const { isDirty, setDirtyTrue, setDirty } = useBoolState(false, 'dirty');

  // Populate the proxy state on load or when the cache is invalidated.
  useEffect(() => {
    if (customReportFromApi) {
      setCustomReportEditingState(customReportFromApi);
    }
  }, [customReportFromApi, setCustomReportEditingState]);

  // Proxy callback to set the isDirty.
  const setCustomReport = useCallback(
    (report: CustomReport) => {
      setCustomReportEditingState(report);
      if (!isDirty) {
        setDirtyTrue();
      }
    },
    [isDirty, setDirtyTrue, setCustomReportEditingState],
  );

  const canEdit = !customReportFromApi?.isPreset && !customReportFromApi?.archived && canModifyCustomReports(ability);

  const { isDrawerOpenRaw, toggleDrawerOpenRaw } = useBoolState(true, 'drawerOpenRaw');
  const isDrawerOpen = canEdit && isDrawerOpenRaw;

  return {
    customReport: customReportEditingState,
    setCustomReport,
    customReportError,
    isCustomReportLoading,

    isDirty,
    setDirty,

    canEdit,
    toggleDrawerOpen: toggleDrawerOpenRaw,
    isDrawerOpen,
  };
};