mirror of
https://github.com/danny-avila/LibreChat.git
synced 2025-12-19 18:00:15 +01:00
🌎 i18n: React-i18next & i18next Integration (#5720)
* better i18n support an internationalization-framework. * removed unused package * auto sort for translation.json * fixed tests with the new locales function * added new CI actions from locize * to use locize a mention in the README.md * to use locize a mention in the README.md * updated README.md and added TRANSLATION.md to the repo * updated TRANSLATION.md badges * updated README.md to go to the TRANSLATION.md when clicking on the Translation Progress badge * updated TRANSLATION.md and added a new issue template. * updated TRANSLATION.md and added a new issue template. * updated issue template to add the iso code link. * updated the new GitHub actions for `locize` * updated label for new issue template --> i18n * fixed type issue * Fix eslint * Fix eslint with key-spacing spacing * fix: error type * fix: handle undefined values in SortFilterHeader component * fix: typing in Image component * fix: handle optional promptGroup in PromptCard component * fix: update localize function to accept string type and remove unnecessary JSX element * fix: update localize function to enforce TranslationKeys type for better type safety * fix: improve type safety and handle null values in Assistants component * fix: enhance null checks for fileId in FilesListView component * fix: localize 'Go back' button text in FilesListView component * fix: update aria-label for menu buttons and add translation for 'Close Menu' * docs: add Reasoning UI section for Chain-of-Thought AI models in README * fix: enhance type safety by adding type for message in MultiMessage component * fix: improve null checks and optional chaining in useAutoSave hook * fix: improve handling of optional properties in cleanupPreset function * fix: ensure isFetchingNextPage defaults to false and improve null checks for messages in Search component * fix: enhance type safety and null checks in useBuildMessageTree hook --------- Co-authored-by: Danny Avila <danny@librechat.ai>
This commit is contained in:
parent
2e8d969e35
commit
aae413cc71
153 changed files with 13448 additions and 38224 deletions
|
|
@ -2,7 +2,7 @@ import React, { useState } from 'react';
|
|||
import { TError } from 'librechat-data-provider';
|
||||
|
||||
type ProviderValue = {
|
||||
error: TError;
|
||||
error?: TError;
|
||||
setError: React.Dispatch<React.SetStateAction<boolean>>;
|
||||
};
|
||||
const ApiErrorBoundaryContext = React.createContext<ProviderValue | undefined>(undefined);
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ export default function useSelectAssistant(endpoint: AssistantsEndpoint) {
|
|||
|
||||
const onSelect = useCallback(
|
||||
(value: string) => {
|
||||
const assistant = assistantMap?.[endpoint]?.[value];
|
||||
const assistant = assistantMap[endpoint]?.[value];
|
||||
if (!assistant) {
|
||||
return;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -76,7 +76,6 @@ export default function useAppStartup({
|
|||
return;
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
|
||||
const userPlugins = user.plugins ?? [];
|
||||
|
||||
if (userPlugins.length === 0) {
|
||||
|
|
|
|||
|
|
@ -144,7 +144,7 @@ const usePresetIndexOptions: TUsePresetOptions = (_preset) => {
|
|||
}
|
||||
return tool;
|
||||
})
|
||||
?.filter((el) => !!el) || [];
|
||||
.filter((el) => !!el) || [];
|
||||
const isSelected = checkPluginSelection(newValue);
|
||||
const tool = availableTools[newValue];
|
||||
if (isSelected || remove) {
|
||||
|
|
|
|||
|
|
@ -138,7 +138,7 @@ const useSetIndexOptions: TUseSetOptions = (preset = false) => {
|
|||
}
|
||||
return tool;
|
||||
})
|
||||
?.filter((el) => !!el) || [];
|
||||
.filter((el) => !!el) || [];
|
||||
const isSelected = checkPluginSelection(newValue);
|
||||
const tool = availableTools[newValue];
|
||||
if (isSelected || remove) {
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ export const useDelayedUploadToast = () => {
|
|||
}
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
const message = localize('com_ui_upload_delay', fileName);
|
||||
const message = localize('com_ui_upload_delay', { 0: fileName });
|
||||
showToast({
|
||||
message,
|
||||
status: 'warning',
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ export default function useDeleteFilesFromTable(callback?: () => void) {
|
|||
const deletionMutation = useDeleteFilesMutation({
|
||||
onMutate: async (variables) => {
|
||||
const { files } = variables;
|
||||
if (!files?.length) {
|
||||
if (!files.length) {
|
||||
return new Map<string, BatchFile>();
|
||||
}
|
||||
|
||||
|
|
@ -26,7 +26,7 @@ export default function useDeleteFilesFromTable(callback?: () => void) {
|
|||
|
||||
queryClient.setQueryData([QueryKeys.files], (oldFiles: TFile[] | undefined) => {
|
||||
const { files } = variables;
|
||||
return files?.length
|
||||
return files.length
|
||||
? oldFiles?.filter((file) => !filesToDeleteMap.has(file.file_id))
|
||||
: oldFiles;
|
||||
});
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ export const useAutoSave = ({
|
|||
setFiles,
|
||||
}: {
|
||||
conversationId?: string | null;
|
||||
textAreaRef: React.RefObject<HTMLTextAreaElement>;
|
||||
textAreaRef?: React.RefObject<HTMLTextAreaElement>;
|
||||
files: Map<string, ExtendedFile>;
|
||||
setFiles: SetterOrUpdater<Map<string, ExtendedFile>>;
|
||||
}) => {
|
||||
|
|
@ -51,7 +51,7 @@ export const useAutoSave = ({
|
|||
const restoreFiles = useCallback(
|
||||
(id: string) => {
|
||||
const filesDraft = JSON.parse(
|
||||
localStorage.getItem(`${LocalStorageKeys.FILES_DRAFT}${id}`) || '[]',
|
||||
(localStorage.getItem(`${LocalStorageKeys.FILES_DRAFT}${id}`) ?? '') || '[]',
|
||||
) as string[];
|
||||
|
||||
if (filesDraft.length === 0) {
|
||||
|
|
@ -66,7 +66,10 @@ export const useAutoSave = ({
|
|||
const tempFileData = fileList?.find((f) => f.temp_file_id === fileId);
|
||||
const { fileToRecover, fileIdToRecover } = fileData
|
||||
? { fileToRecover: fileData, fileIdToRecover: fileId }
|
||||
: { fileToRecover: tempFileData, fileIdToRecover: tempFileData?.temp_file_id || fileId };
|
||||
: {
|
||||
fileToRecover: tempFileData,
|
||||
fileIdToRecover: (tempFileData?.temp_file_id ?? '') || fileId,
|
||||
};
|
||||
|
||||
if (fileToRecover) {
|
||||
setFiles((currentFiles) => {
|
||||
|
|
@ -87,7 +90,7 @@ export const useAutoSave = ({
|
|||
|
||||
const restoreText = useCallback(
|
||||
(id: string) => {
|
||||
const savedDraft = localStorage.getItem(`${LocalStorageKeys.TEXT_DRAFT}${id}`) || '';
|
||||
const savedDraft = (localStorage.getItem(`${LocalStorageKeys.TEXT_DRAFT}${id}`) ?? '') || '';
|
||||
setValue('text', decodeBase64(savedDraft));
|
||||
},
|
||||
[setValue],
|
||||
|
|
@ -115,12 +118,12 @@ export const useAutoSave = ({
|
|||
// This useEffect is responsible for setting up and cleaning up the auto-save functionality
|
||||
// for the text area input. It saves the text to localStorage with a debounce to prevent
|
||||
// excessive writes.
|
||||
if (!saveDrafts || !conversationId) {
|
||||
if (!saveDrafts || conversationId == null || conversationId === '') {
|
||||
return;
|
||||
}
|
||||
|
||||
const handleInput = debounce(() => {
|
||||
if (textAreaRef.current && textAreaRef.current.value) {
|
||||
if (textAreaRef?.current && textAreaRef.current.value) {
|
||||
localStorage.setItem(
|
||||
`${LocalStorageKeys.TEXT_DRAFT}${conversationId}`,
|
||||
encodeBase64(textAreaRef.current.value),
|
||||
|
|
@ -130,7 +133,7 @@ export const useAutoSave = ({
|
|||
}
|
||||
}, 1000);
|
||||
|
||||
const textArea = textAreaRef.current;
|
||||
const textArea = textAreaRef?.current;
|
||||
if (textArea) {
|
||||
textArea.addEventListener('input', handleInput);
|
||||
}
|
||||
|
|
@ -149,7 +152,7 @@ export const useAutoSave = ({
|
|||
// It handles both text and file drafts, ensuring that the user's input is preserved
|
||||
// across different conversations.
|
||||
|
||||
if (!saveDrafts || !conversationId) {
|
||||
if (!saveDrafts || conversationId == null || conversationId === '') {
|
||||
return;
|
||||
}
|
||||
if (conversationId === currentConversationId) {
|
||||
|
|
@ -160,7 +163,7 @@ export const useAutoSave = ({
|
|||
setFiles(new Map());
|
||||
|
||||
try {
|
||||
if (currentConversationId) {
|
||||
if (currentConversationId != null && currentConversationId) {
|
||||
saveText(currentConversationId);
|
||||
}
|
||||
|
||||
|
|
@ -187,7 +190,12 @@ export const useAutoSave = ({
|
|||
// It ensures that the file drafts are kept up-to-date and can be restored
|
||||
// when the conversation is revisited.
|
||||
|
||||
if (!saveDrafts || !conversationId || currentConversationId !== conversationId) {
|
||||
if (
|
||||
!saveDrafts ||
|
||||
conversationId == null ||
|
||||
conversationId === '' ||
|
||||
currentConversationId !== conversationId
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -202,7 +210,7 @@ export const useAutoSave = ({
|
|||
}, [files, conversationId, saveDrafts, currentConversationId, fileIds]);
|
||||
|
||||
const clearDraft = useCallback(() => {
|
||||
if (conversationId) {
|
||||
if (conversationId != null && conversationId) {
|
||||
localStorage.removeItem(`${LocalStorageKeys.TEXT_DRAFT}${conversationId}`);
|
||||
localStorage.removeItem(`${LocalStorageKeys.FILES_DRAFT}${conversationId}`);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -98,7 +98,7 @@ export default function useMentions({
|
|||
endpointsConfig,
|
||||
}),
|
||||
)
|
||||
?.filter(Boolean),
|
||||
.filter(Boolean),
|
||||
[EModelEndpoint.azureAssistants]: listMap[EModelEndpoint.azureAssistants]
|
||||
?.map(
|
||||
assistantMapFn({
|
||||
|
|
@ -107,7 +107,7 @@ export default function useMentions({
|
|||
endpointsConfig,
|
||||
}),
|
||||
)
|
||||
?.filter(Boolean),
|
||||
.filter(Boolean),
|
||||
}),
|
||||
[listMap, assistantMap, endpointsConfig],
|
||||
);
|
||||
|
|
|
|||
|
|
@ -67,7 +67,7 @@ function useTextToSpeechEdge({
|
|||
.catch((error) => {
|
||||
console.error('Error initializing TTS:', error);
|
||||
showToast({
|
||||
message: localize('com_nav_tts_init_error', (error as Error).message),
|
||||
message: localize('com_nav_tts_init_error', { 0: (error as Error).message }),
|
||||
status: 'error',
|
||||
});
|
||||
});
|
||||
|
|
@ -77,7 +77,7 @@ function useTextToSpeechEdge({
|
|||
.catch((error) => {
|
||||
console.error('Error initializing TTS:', error);
|
||||
showToast({
|
||||
message: localize('com_nav_tts_init_error', (error as Error).message),
|
||||
message: localize('com_nav_tts_init_error', { 0: (error as Error).message }),
|
||||
status: 'error',
|
||||
});
|
||||
});
|
||||
|
|
@ -168,7 +168,7 @@ function useTextToSpeechEdge({
|
|||
} catch (error) {
|
||||
console.error('Error generating speech:', error);
|
||||
showToast({
|
||||
message: localize('com_nav_audio_play_error', (error as Error).message),
|
||||
message: localize('com_nav_audio_play_error', { 0: (error as Error).message }),
|
||||
status: 'error',
|
||||
});
|
||||
setIsSpeaking(false);
|
||||
|
|
|
|||
|
|
@ -67,7 +67,7 @@ function useTextToSpeechExternal({
|
|||
return playPromise().catch(console.error);
|
||||
}
|
||||
console.error(error);
|
||||
showToast({ message: localize('com_nav_audio_play_error', error.message), status: 'error' });
|
||||
showToast({ message: localize('com_nav_audio_play_error', { 0: error.message }), status: 'error' });
|
||||
});
|
||||
|
||||
newAudio.onended = () => {
|
||||
|
|
@ -123,7 +123,7 @@ function useTextToSpeechExternal({
|
|||
},
|
||||
onError: (error: unknown) => {
|
||||
showToast({
|
||||
message: localize('com_nav_audio_process_error', (error as Error).message),
|
||||
message: localize('com_nav_audio_process_error', { 0: (error as Error).message }),
|
||||
status: 'error',
|
||||
});
|
||||
},
|
||||
|
|
|
|||
|
|
@ -96,14 +96,12 @@ export default function useTextarea({
|
|||
return localize('com_endpoint_message_not_appendable');
|
||||
}
|
||||
|
||||
const sender =
|
||||
isAssistant || isAgent
|
||||
? getEntityName({ name: entityName, isAgent, localize })
|
||||
: getSender(conversation as TEndpointOption);
|
||||
const sender = isAssistant || isAgent
|
||||
? getEntityName({ name: entityName, isAgent, localize })
|
||||
: getSender(conversation as TEndpointOption);
|
||||
|
||||
return `${localize(
|
||||
'com_endpoint_message_new',
|
||||
sender ? sender : localize('com_endpoint_ai'),
|
||||
'com_endpoint_message_new', { 0: sender ? sender : localize('com_endpoint_ai') },
|
||||
)}`;
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -20,19 +20,19 @@ export default function useBuildMessageTree() {
|
|||
recursive = false,
|
||||
}: {
|
||||
messageId: string | null | undefined;
|
||||
message: TMessage | null;
|
||||
messages: TMessage[] | null;
|
||||
message: Partial<TMessage> | null;
|
||||
messages: Array<Partial<TMessage> | undefined> | null;
|
||||
branches?: boolean;
|
||||
recursive?: boolean;
|
||||
}): Promise<TMessage | TMessage[]> => {
|
||||
let children: TMessage[] = [];
|
||||
if (messages?.length) {
|
||||
}): Promise<TMessage | Array<Partial<TMessage> | undefined>> => {
|
||||
let children: Array<Partial<TMessage> | undefined> = [];
|
||||
if (messages?.length != null && messages.length > 0) {
|
||||
if (branches) {
|
||||
for (const message of messages) {
|
||||
children.push(
|
||||
(await buildMessageTree({
|
||||
messageId: message?.messageId,
|
||||
message: message,
|
||||
message: message as TMessage,
|
||||
messages: message?.children || [],
|
||||
branches,
|
||||
recursive,
|
||||
|
|
@ -41,7 +41,7 @@ export default function useBuildMessageTree() {
|
|||
}
|
||||
} else {
|
||||
let message = messages[0];
|
||||
if (messages?.length > 1) {
|
||||
if (messages.length > 1) {
|
||||
const siblingIdx = await getSiblingIdx(messageId);
|
||||
message = messages[messages.length - siblingIdx - 1];
|
||||
}
|
||||
|
|
@ -49,7 +49,7 @@ export default function useBuildMessageTree() {
|
|||
children = [
|
||||
(await buildMessageTree({
|
||||
messageId: message?.messageId,
|
||||
message: message,
|
||||
message: message as TMessage,
|
||||
messages: message?.children || [],
|
||||
branches,
|
||||
recursive,
|
||||
|
|
@ -59,16 +59,16 @@ export default function useBuildMessageTree() {
|
|||
}
|
||||
|
||||
if (recursive && message) {
|
||||
return { ...message, children: children };
|
||||
return { ...(message as TMessage), children: children as TMessage[] };
|
||||
} else {
|
||||
let ret: TMessage[] = [];
|
||||
if (message) {
|
||||
const _message = { ...message };
|
||||
delete _message.children;
|
||||
ret = [_message];
|
||||
ret = [_message as TMessage];
|
||||
}
|
||||
for (const child of children) {
|
||||
ret = ret.concat(child);
|
||||
ret = ret.concat(child as TMessage);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -35,7 +35,7 @@ export default function usePromptGroupsNav() {
|
|||
}, [pageSize, name, category, setPageNumber]);
|
||||
|
||||
const promptGroups = useMemo(() => {
|
||||
return groupsQuery?.data?.pages?.[pageNumber - 1 + '']?.promptGroups || [];
|
||||
return groupsQuery.data?.pages[pageNumber - 1 + '']?.promptGroups || [];
|
||||
}, [groupsQuery.data, pageNumber]);
|
||||
|
||||
const nextPage = () => {
|
||||
|
|
|
|||
|
|
@ -35,7 +35,7 @@ export default function useContentHandler({ setMessages, getMessages }: TUseCont
|
|||
const messages =
|
||||
_messages
|
||||
?.filter((m) => m.messageId !== messageId)
|
||||
?.map((msg) => ({ ...msg, thread_id })) ?? [];
|
||||
.map((msg) => ({ ...msg, thread_id })) ?? [];
|
||||
const userMessage = messages[messages.length - 1] as TMessage | undefined;
|
||||
|
||||
const { initialResponse } = submission;
|
||||
|
|
|
|||
|
|
@ -217,7 +217,7 @@ export default function useEventHandlers({
|
|||
const parentId = requestMessage.parentMessageId;
|
||||
if (
|
||||
parentId !== Constants.NO_PARENT &&
|
||||
(title?.toLowerCase()?.includes('new chat') ?? false)
|
||||
(title?.toLowerCase().includes('new chat') ?? false)
|
||||
) {
|
||||
const convos = queryClient.getQueryData<ConversationData>([QueryKeys.allConversations]);
|
||||
const cachedConvo = getConversationById(convos, conversationId);
|
||||
|
|
@ -301,7 +301,7 @@ export default function useEventHandlers({
|
|||
const parentId = isRegenerate ? userMessage.overrideParentMessageId : parentMessageId;
|
||||
if (
|
||||
parentId !== Constants.NO_PARENT &&
|
||||
(title?.toLowerCase()?.includes('new chat') ?? false)
|
||||
(title?.toLowerCase().includes('new chat') ?? false)
|
||||
) {
|
||||
const convos = queryClient.getQueryData<ConversationData>([QueryKeys.allConversations]);
|
||||
const cachedConvo = getConversationById(convos, conversationId);
|
||||
|
|
|
|||
|
|
@ -22,6 +22,7 @@ export { default as useToast } from './useToast';
|
|||
export { default as useTimeout } from './useTimeout';
|
||||
export { default as useNewConvo } from './useNewConvo';
|
||||
export { default as useLocalize } from './useLocalize';
|
||||
export type { TranslationKeys } from './useLocalize';
|
||||
export { default as useMediaQuery } from './useMediaQuery';
|
||||
export { default as useScrollToRef } from './useScrollToRef';
|
||||
export { default as useLocalStorage } from './useLocalStorage';
|
||||
|
|
|
|||
|
|
@ -1,14 +1,25 @@
|
|||
import { useCallback } from 'react';
|
||||
import { useEffect, useCallback } from 'react';
|
||||
import { useRecoilValue } from 'recoil';
|
||||
import { localize } from '~/localization/Translation';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { TOptions } from 'i18next';
|
||||
import store from '~/store';
|
||||
import { resources } from '~/locales/i18n';
|
||||
|
||||
export type TranslationKeys = keyof typeof resources.en.translation;
|
||||
|
||||
export default function useLocalize() {
|
||||
const lang = useRecoilValue(store.lang);
|
||||
const { t, i18n } = useTranslation();
|
||||
|
||||
useEffect(() => {
|
||||
if (i18n.language !== lang) {
|
||||
i18n.changeLanguage(lang);
|
||||
}
|
||||
}, [lang, i18n]);
|
||||
|
||||
const memoizedLocalize = useCallback(
|
||||
(phraseKey: string, ...values: string[]) => localize(lang, phraseKey, ...(values ?? [])),
|
||||
[lang], // Only recreate the function when `lang` changes
|
||||
(phraseKey: TranslationKeys, options?: TOptions) => t(phraseKey, options),
|
||||
[t],
|
||||
);
|
||||
|
||||
return memoizedLocalize;
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue