All files / src/components/Recipe/Create/hooks useRecipeForm.tsx

78.68% Statements 48/61
50% Branches 11/22
72.72% Functions 8/11
78.57% Lines 44/56

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                                                    1x         10x 10x   10x         10x                                                 10x             10x                                   10x 10x   10x         10x   10x 10x 10x           10x 10x 10x   10x 10x   10x 5x 5x 1x   1x 1x 1x             10x 1x       1x               10x 1x 1x 1x 1x 1x             10x 1x 1x               1x     10x 1x 1x         1x     10x                        
import { useMutation } from '@apollo/client/react';
import { useDebouncedValue, useLocalStorage } from '@mantine/hooks';
import { notifications } from '@mantine/notifications';
import { IconCheck, IconDeviceFloppy } from '@tabler/icons-react';
import { useRouter } from 'next/navigation';
import { useTranslations } from 'next-intl';
import { useCallback, useEffect, useMemo, useRef } from 'react';
import { v4 as uuidv4 } from 'uuid';
import { CREATE_RECIPE } from '@/lib/graphql/mutations';
import { recipeFormValidationSchema } from '@/lib/validation/validation';
import { zodResolver } from '@/lib/validation/zodResolver';
import { useRecipeFormHook } from '../FormContext';
import type {
  DraftState,
  FormIngredient,
  FormPreparationStep,
  RecipeFormValues,
  UseRecipeFormProps,
} from '../types';
import {
  computeCompletion,
  DRAFT_STORAGE_KEY,
  EMPTY_FORM_VALUES,
  transformValuesToInput,
} from '../utils';
 
export const useRecipeForm = ({
  metadataLoaded,
  onSectionChange,
  labels,
}: UseRecipeFormProps) => {
  const router = useRouter();
  const translate = useTranslations();
 
  const [draft, setDraft] = useLocalStorage<DraftState | null>({
    key: DRAFT_STORAGE_KEY,
    defaultValue: null,
  });
 
  const [createRecipe, { loading: publishLoading }] = useMutation(
    CREATE_RECIPE,
    {
      onCompleted: () => {
        setDraft(null);
        notifications.show({
          title: translate('notifications.recipeCreatedTitle'),
          message: translate('notifications.recipeCreatedMessage'),
          color: 'teal',
          icon: <IconCheck size={18} />,
        });
        router.push('/me/my-recipes');
      },
      onError: (error) => {
        notifications.show({
          title: translate('notifications.recipeCreateFailedTitle'),
          message:
            error.message ||
            translate('notifications.recipeCreateFailedMessage'),
          color: 'red',
        });
      },
    },
  );
 
  const form = useRecipeFormHook({
    mode: 'controlled',
    initialValues: draft?.values ?? EMPTY_FORM_VALUES,
    validate: zodResolver(recipeFormValidationSchema),
    validateInputOnBlur: true,
  });
 
  const handlePublish = async (values: RecipeFormValues) => {
    if (!values.difficultyLevel || !values.category) {
      notifications.show({
        title: translate('notifications.missingFieldsTitle'),
        message: translate('notifications.missingFieldsMessage'),
        color: 'orange',
      });
      onSectionChange('basics');
      return;
    }
 
    const input = transformValuesToInput(values, labels);
 
    await createRecipe({
      variables: { recipeCreateInput: input },
    });
  };
 
  const formRef = useRef(form);
  formRef.current = form;
 
  const completion = useMemo(
    () => computeCompletion(form.values),
    [form.values],
  );
 
  const [debouncedValues] = useDebouncedValue(form.values, 800);
 
  useEffect(() => {
    Iif (!metadataLoaded) return;
    setDraft({
      updatedAt: Date.now(),
      values: debouncedValues,
    });
  }, [debouncedValues, metadataLoaded, setDraft]);
 
  const lastSavedLabel = useMemo(() => {
    const unsaved = translate('sidebar.unsaved') || 'Unsaved';
    const justSaved = translate('sidebar.justSaved') || 'Just saved';
    const savedRecently =
      translate('sidebar.savedRecently') || 'Saved recently';
    const savedAgoTemplate = 'Saved {minutes}m ago';
 
    if (!draft?.updatedAt) return unsaved;
    const delta = Date.now() - draft.updatedAt;
    if (delta < 3_000) return justSaved;
    Iif (delta < 60_000) return savedRecently;
 
    const minutes = Math.floor(delta / 60_000);
    try {
      return translate('sidebar.savedAgo', { minutes });
    } catch (e) {
      console.error(e);
      return savedAgoTemplate.replace('{minutes}', minutes.toString());
    }
  }, [draft?.updatedAt, translate]);
 
  const saveDraftNow = useCallback(() => {
    setDraft({
      updatedAt: Date.now(),
      values: formRef.current.getValues(),
    });
    notifications.show({
      message: translate('notifications.draftSavedMessage'),
      color: 'blue',
      icon: <IconDeviceFloppy size={16} />,
      withBorder: true,
    });
  }, [setDraft, translate]);
 
  const resetDraft = useCallback(() => {
    setDraft(null);
    formRef.current.reset();
    formRef.current.setValues(EMPTY_FORM_VALUES);
    onSectionChange('basics');
    notifications.show({
      title: translate('notifications.draftClearedTitle'),
      message: translate('notifications.draftClearedMessage'),
      color: 'gray',
    });
  }, [setDraft, onSectionChange, translate]);
 
  const addIngredient = useCallback(() => {
    const f = formRef.current;
    const newIngredient: FormIngredient = {
      localId: uuidv4(),
      name: '',
      quantity: '',
      unit: '',
      isOptional: false,
      note: '',
    };
    f.insertListItem('ingredients', newIngredient);
  }, []);
 
  const addStep = useCallback(() => {
    const f = formRef.current;
    const newStep: FormPreparationStep = {
      localId: uuidv4(),
      description: '',
      order: f.getValues().preparationSteps.length + 1,
    };
    f.insertListItem('preparationSteps', newStep);
  }, []);
 
  return {
    form,
    handlePublish,
    publishLoading,
    completion,
    lastSavedLabel,
    saveDraftNow,
    resetDraft,
    addIngredient,
    addStep,
  };
};