All files / frontend/src/components/SukohForm FormProvider.tsx

63.5% Statements 87/137
61.11% Branches 44/72
46.15% Functions 12/26
62.5% Lines 80/128

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                      32x   31x         31x 31x 59x 56x 56x   28x                         19x   18x         18x 19x   19x 18x 18x 18x   18x 11x 7x 2x 5x 5x   18x     18x 18x   18x                     10x   9x         9x 10x   10x 11x 11x 10x 2x 8x 8x   10x     8x 8x   8x             32x 32x               12x 32x 32x 32x   32x 8x   8x         8x     32x                                                                               4x 4x 4x 4x     4x 4x 4x 4x 4x 4x 4x   4x 4x       4x                                                       4x                   4x         4x                               4x 4x       4x 4x 4x   4x     4x                                       4x                                       4x 4x                                                                       4x                        
import { useState, useCallback, useRef, useMemo, ReactNode } from 'react';
import { FormContext, FormContextValue, FieldConfig, FileReference, FormMeta } from './FormContext';
import { FieldRenderer } from './FieldRenderer';
import type { Field } from '@quiqr/types';
import Box from '@mui/material/Box';
 
/**
 * Get a value from a nested object using dot notation with array support.
 * Supports paths like: "foo.bar", "foo[0].bar", "foo.0.bar"
 */
function getAtPath<T = unknown>(obj: unknown, path: string): T | undefined {
  if (!path || path === '') return obj as T;
 
  const segments = path
    .replace(/\[(\d+)\]/g, '.$1') // Convert [0] to .0
    .split('.')
    .filter(Boolean);
 
  let current: unknown = obj;
  for (const segment of segments) {
    if (current === null || current === undefined) return undefined;
    Iif (typeof current !== 'object') return undefined;
    current = (current as Record<string, unknown>)[segment];
  }
  return current as T;
}
 
/**
 * Set a value in a nested object using dot notation with array support.
 * Creates intermediate objects/arrays as needed.
 * Returns a new object (immutable).
 */
function setAtPath<T extends Record<string, unknown>>(
  obj: T,
  path: string,
  value: unknown
): T {
  if (!path || path === '') return value as T;
 
  const segments = path
    .replace(/\[(\d+)\]/g, '.$1')
    .split('.')
    .filter(Boolean);
 
  const result = Array.isArray(obj) ? [...obj] : { ...obj };
  let current: Record<string, unknown> = result as Record<string, unknown>;
 
  for (let i = 0; i < segments.length - 1; i++) {
    const segment = segments[i];
    const nextSegment = segments[i + 1];
    const isNextArrayIndex = /^\d+$/.test(nextSegment);
 
    if (current[segment] === undefined || current[segment] === null) {
      current[segment] = isNextArrayIndex ? [] : {};
    } else if (Array.isArray(current[segment])) {
      current[segment] = [...(current[segment] as unknown[])];
    E} else if (typeof current[segment] === 'object') {
      current[segment] = { ...(current[segment] as Record<string, unknown>) };
    }
    current = current[segment] as Record<string, unknown>;
  }
 
  const lastSegment = segments[segments.length - 1];
  current[lastSegment] = value;
 
  return result as T;
}
 
/**
 * Delete a value from a nested object.
 * Returns a new object (immutable).
 */
function deleteAtPath<T extends Record<string, unknown>>(
  obj: T,
  path: string
): T {
  if (!path || path === '') return {} as T;
 
  const segments = path
    .replace(/\[(\d+)\]/g, '.$1')
    .split('.')
    .filter(Boolean);
 
  const result = Array.isArray(obj) ? [...obj] : { ...obj };
  let current: Record<string, unknown> = result as Record<string, unknown>;
 
  for (let i = 0; i < segments.length - 1; i++) {
    const segment = segments[i];
    if (current[segment] === undefined) return obj; // Path doesn't exist
    if (Array.isArray(current[segment])) {
      current[segment] = [...(current[segment] as unknown[])];
    E} else if (typeof current[segment] === 'object') {
      current[segment] = { ...(current[segment] as Record<string, unknown>) };
    }
    current = current[segment] as Record<string, unknown>;
  }
 
  const lastSegment = segments[segments.length - 1];
  delete current[lastSegment];
 
  return result as T;
}
 
/**
 * Generate compositeKey for a field based on its position in the tree.
 */
function generateCompositeKey(field: Field, parentPath: string): string {
  const basePath = parentPath || 'root';
  return `${basePath}.${field.key}`;
}
 
function processFields(
  fields: Field[],
  parentPath: string,
  configMap: Map<string, FieldConfig>
): FieldConfig[] {
  return fields.map((field) => {
    const compositeKey = generateCompositeKey(field, parentPath);
    const config: FieldConfig = { ...field, compositeKey };
    configMap.set(compositeKey, config);
 
    if ('fields' in field && Array.isArray(field.fields)) {
      const nestedFields = field.fields as Field[];
      // For section/nest with groupdata: false, children use same parent path
      const childPath =
        (field.type === 'section' || field.type === 'nest') &&
        (field as { groupdata?: boolean }).groupdata === false
          ? parentPath
          : compositeKey;
      processFields(nestedFields, childPath, configMap);
    }
 
    return config;
  });
}
 
function getStatePath(
  _field: FieldConfig,
  parentPath: string,
  fieldKey: string
): string {
  if (!parentPath || parentPath === 'root') {
    return fieldKey;
  }
  const cleanParent = parentPath.replace(/^root\./, '');
  return `${cleanParent}.${fieldKey}`;
}
 
interface DebouncedUpdate {
  timeoutId: ReturnType<typeof setTimeout> | null;
  pendingValue: unknown;
}
 
interface FormProviderProps {
  children: ReactNode;
  fields: Field[];
  initialValues: Record<string, unknown>;
  initialResources?: Record<string, FileReference[]>;
  meta: FormMeta;
  onSave: (document: Record<string, unknown>, resources: Record<string, FileReference[]>) => Promise<void>;
  onChange?: (document: Record<string, unknown>, isDirty: boolean, resources?: Record<string, FileReference[]>) => void;
}
 
export function FormProvider({
  children,
  fields,
  initialValues,
  initialResources = {},
  meta,
  onSave,
  onChange,
}: FormProviderProps) {
  const { fieldConfigs } = useMemo(() => {
    const configMap = new Map<string, FieldConfig>();
    const processed = processFields(fields, 'root', configMap);
    return { fieldConfigs: configMap, processedFields: processed };
  }, [fields]);
 
  const [document, setDocument] = useState<Record<string, unknown>>(initialValues);
  const [resources, setResourcesState] = useState<Record<string, FileReference[]>>(initialResources);
  const [isDirty, setIsDirty] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const cacheRef = useRef<Record<string, Record<string, unknown>>>({});
  const debounceRef = useRef<Record<string, DebouncedUpdate>>({});
  const originalValuesRef = useRef(initialValues);
 
  const getValueAtPath = useCallback(
    <T,>(path: string): T | undefined => getAtPath<T>(document, path),
    [document]
  );
 
  const setValueAtPath = useCallback(
    (path: string, value: unknown, debounce = 0) => {
      const applyUpdate = () => {
        setDocument((prev) => {
          const next = setAtPath(prev, path, value);
          const dirty = JSON.stringify(next) !== JSON.stringify(originalValuesRef.current);
          setIsDirty(dirty);
          onChange?.(next, dirty);
          return next;
        });
      };
 
      if (debounce > 0) {
        const existing = debounceRef.current[path];
        if (existing?.timeoutId) {
          clearTimeout(existing.timeoutId);
        }
        debounceRef.current[path] = {
          timeoutId: setTimeout(applyUpdate, debounce),
          pendingValue: value,
        };
      } else {
        applyUpdate();
      }
    },
    [onChange]
  );
 
  const clearValueAtPath = useCallback((path: string) => {
    setDocument((prev) => {
      const next = deleteAtPath(prev, path);
      const dirty = JSON.stringify(next) !== JSON.stringify(originalValuesRef.current);
      setIsDirty(dirty);
      onChange?.(next, dirty);
      return next;
    });
  }, [onChange]);
 
  const getResources = useCallback(
    (key: string): FileReference[] => resources[key] || [],
    [resources]
  );
 
  const setResourcesHandler = useCallback(
    (key: string, files: FileReference[], markDirty = true) => {
      setResourcesState((prev) => {
        const newResources = { ...prev, [key]: files };
        if (markDirty) {
          setIsDirty(true);
          // Notify parent that form has changed (for save button state)
          // Include resources so they can be tracked for saving
          onChange?.(document, true, newResources);
        }
        return newResources;
      });
    },
    [document, onChange]
  );
 
  const getFieldConfig = useCallback(
    (compositeKey: string): FieldConfig | undefined => fieldConfigs.get(compositeKey),
    [fieldConfigs]
  );
 
  const getCache = useCallback((compositeKey: string): Record<string, unknown> => {
    Eif (!cacheRef.current[compositeKey]) {
      cacheRef.current[compositeKey] = {};
    }
    return cacheRef.current[compositeKey];
  }, []);
 
  const renderFields = useCallback(
    (parentPath: string, fieldsToRender: Field[]): ReactNode => {
      // Process fields to get their compositeKeys
      const basePath = parentPath || 'root';
 
      return fieldsToRender.map((field) => {
        const compositeKey = `${basePath}.${field.key}`;
 
        // Ensure field config exists in the map (for dynamically rendered fields)
        if (!fieldConfigs.has(compositeKey)) {
          const config: FieldConfig = { ...field, compositeKey };
          fieldConfigs.set(compositeKey, config);
        }
 
        return <FieldRenderer key={compositeKey} compositeKey={compositeKey} />;
      });
    },
    [fieldConfigs]
  );
 
  const saveForm = useCallback(async () => {
    // Flush pending debounced updates before save
    Object.entries(debounceRef.current).forEach(([path, { timeoutId, pendingValue }]) => {
      if (timeoutId) {
        clearTimeout(timeoutId);
        setDocument((prev) => setAtPath(prev, path, pendingValue));
      }
    });
    debounceRef.current = {};
 
    setIsSubmitting(true);
    try {
      await onSave(document, resources);
      setIsDirty(false);
      originalValuesRef.current = document;
    } finally {
      setIsSubmitting(false);
    }
  }, [document, resources, onSave]);
 
  const contextValue: FormContextValue = useMemo(
    () => ({
      document,
      getValueAtPath,
      setValueAtPath,
      clearValueAtPath,
      resources,
      getResources,
      setResources: setResourcesHandler,
      fieldConfigs,
      getFieldConfig,
      isDirty,
      isSubmitting,
      meta,
      getCache,
      renderFields,
      saveForm,
    }),
    [
      document,
      getValueAtPath,
      setValueAtPath,
      clearValueAtPath,
      resources,
      getResources,
      setResourcesHandler,
      fieldConfigs,
      getFieldConfig,
      isDirty,
      isSubmitting,
      meta,
      getCache,
      renderFields,
      saveForm,
    ]
  );
 
  return (
    <FormContext.Provider value={contextValue}>
      <Box sx={{display: 'flex', flexDirection: 'column', gap: '1rem', padding: '3rem 2rem'}}>
        {children}
      </Box>
    </FormContext.Provider>
  );
}
 
export { getAtPath, setAtPath, deleteAtPath, getStatePath };
 
export default FormProvider;