File size: 2,507 Bytes
f0743f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { mergeFileConfig } from 'librechat-data-provider';
import { useCallback } from 'react';
import { useGetFileConfig } from '~/data-provider';
import {
  resizeImage,
  shouldResizeImage,
  supportsClientResize,
  type ResizeOptions,
  type ResizeResult,
} from '~/utils/imageResize';

/**
 * Hook for client-side image resizing functionality
 * Integrates with LibreChat's file configuration system
 */
export const useClientResize = () => {
  const { data: fileConfig = null } = useGetFileConfig({
    select: (data) => mergeFileConfig(data),
  });

  // Safe access to clientImageResize config with fallbacks
  // eslint-disable-next-line react-hooks/exhaustive-deps
  const config = (fileConfig as any)?.clientImageResize ?? {
    enabled: false,
    maxWidth: 1900,
    maxHeight: 1900,
    quality: 0.92,
  };
  const isEnabled = config?.enabled ?? false;

  /**
   * Resizes an image if client-side resizing is enabled and supported
   * @param file - The image file to resize
   * @param options - Optional resize options to override defaults
   * @returns Promise resolving to either the resized file result or original file
   */
  const resizeImageIfNeeded = useCallback(
    async (
      file: File,
      options?: Partial<ResizeOptions>,
    ): Promise<{ file: File; resized: boolean; result?: ResizeResult }> => {
      // Return original file if resizing is disabled
      if (!isEnabled) {
        return { file, resized: false };
      }

      // Return original file if browser doesn't support resizing
      if (!supportsClientResize()) {
        console.warn('Client-side image resizing not supported in this browser');
        return { file, resized: false };
      }

      // Return original file if it doesn't need resizing
      if (!shouldResizeImage(file)) {
        return { file, resized: false };
      }

      try {
        const resizeOptions: Partial<ResizeOptions> = {
          maxWidth: config?.maxWidth,
          maxHeight: config?.maxHeight,
          quality: config?.quality,
          ...options,
        };

        const result = await resizeImage(file, resizeOptions);
        return { file: result.file, resized: true, result };
      } catch (error) {
        console.warn('Client-side image resizing failed:', error);
        return { file, resized: false };
      }
    },
    [isEnabled, config],
  );

  return {
    isEnabled,
    isSupported: supportsClientResize(),
    config,
    resizeImageIfNeeded,
  };
};

export default useClientResize;