File size: 1,917 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
import { useEffect, useRef } from 'react';
import type { DynamicSettingProps, TPreset } from 'librechat-data-provider';
import { defaultDebouncedDelay } from '~/common';

function useParameterEffects<T = unknown>({
  preset,
  settingKey,
  defaultValue,
  conversation,
  inputValue,
  setInputValue,
  preventDelayedUpdate = false,
}: Pick<DynamicSettingProps, 'settingKey' | 'defaultValue' | 'conversation'> & {
  preset: TPreset | null;
  inputValue: T;
  setInputValue: (inputValue: T) => void;
  preventDelayedUpdate?: boolean;
}) {
  const idRef = useRef<string | null>(null);
  const presetIdRef = useRef<string | null>(null);

  /** Updates the local state inputValue if global (conversation) is updated elsewhere */
  useEffect(() => {
    if (preventDelayedUpdate) {
      return;
    }

    const timeout = setTimeout(() => {
      if (conversation?.[settingKey] === inputValue) {
        return;
      }
      setInputValue(conversation?.[settingKey]);
    }, defaultDebouncedDelay * 1.25);

    return () => clearTimeout(timeout);
  }, [setInputValue, preventDelayedUpdate, conversation, inputValue, settingKey]);

  /** Resets the local state if conversationId changed */
  useEffect(() => {
    const conversationId = conversation?.conversationId ?? '';
    if (!conversationId) {
      return;
    }

    if (idRef.current === conversationId) {
      return;
    }

    idRef.current = conversationId;
    setInputValue(defaultValue as T);
  }, [setInputValue, conversation?.conversationId, defaultValue]);

  /** Resets the local state if presetId changed */
  useEffect(() => {
    const presetId = preset?.presetId ?? '';
    if (!presetId) {
      return;
    }

    if (presetIdRef.current === presetId) {
      return;
    }

    presetIdRef.current = presetId;
    setInputValue(defaultValue as T);
  }, [setInputValue, preset?.presetId, defaultValue]);
}

export default useParameterEffects;