mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-01-02 08:38:51 +01:00
* chore: add i18n localization comment for AlwaysMakeProd component * feat: enhance accessibility by adding aria-label and aria-labelledby to Switch component * feat: add aria-labels for accessibility in Agent and Assistant avatar buttons * fix: add switch aria-labels for accessibility in various components * feat: add aria-labels and localization keys for accessibility in DataTable, DataTableColumnHeader, and OGDialogTemplate components * chore: refactor out nested ternary * feat: add aria-label to DataTable filter button for My Files modal * feat: add aria-labels for Buttons and localization strings * feat: add aria-labels to Checkboxes in Agent Builder * feat: enhance accessibility by adding aria-label and aria-labelledby to Checkbox component * feat: add aria-label to FileSearchCheckbox in Agent Builder * feat: add aria-label to Prompts text input area * feat: enhance accessibility by adding aria-label and aria-labelledby to TextAreaAutosize component * feat: remove improper role: "list" prop from List in Conversations.tsx to enhance accessibility and stop aria rules conflicting within react-virtualized component * feat: enhance accessibility by allowing tab navigation and adding ring highlights for conversation title editing accept/reject buttons * feat: add aria-label to Copy Link button in the conversation share modal * feat: add title to QR code svg in conversation share modal to describe the image content * feat: enhance accessibility by making Agent Avatar upload keyboard navigable and round out highlight border on focus * feat: enhance accessibility by adding aria attributes around alerting users with screen readers to invalid email address inputs in the Agent Builder * feat: add aria-labels to buttons in Advanced panel of Agent Builder * feat: enhance accessibility by making FileUpload and Clear All buttons in PresetItems keyboard navigable * feat: enchance accessiblity by indexing view and delete button aria-labels in shared links management modal to their specific chat titles * feat: add border highlighting on focus for AnimatedSearchInput * feat: add category description to aria-labels for prompts in ListCard * feat: add proper scoping to rows and columns in table headers * feat: add localized aria-labelling to EditTextPart's TextAreaAutosize component and base dynamic paramters panel components and their supporting translation keys * feat: add localized aria-labels and aria-labelledBy to Checkbox components without them * feat: add localized aria-labeledBy for endpoint settings Sliders * feat: add localized aria-labels for TextareaAutosize components * chore: remove unused i18n string * feat: add localized aria-label for BookmarkForm Checkbox * fix: add stopPropagation onKeyDown for Preview and Edit menu items in prompts that was causing the prompts to inadvertently be sent when triggered with keyboard navigation when Auto-send Prompts was toggled on * fix: switch TableCell to TableHead for title cells according to harvard issue #789 * fix: add more descriptive localization key for file filter button in DataTable * chore: remove self-explanatory code comment from RenameForm * fix: remove stray bg-yellow highlight that was left in during debugging * fix: add aria-label to model configurator panel back button * fix: undo incorrect hoist of tool name split for aria-label and span in MCPInput --------- Co-authored-by: Danny Avila <danny@librechat.ai>
230 lines
6.9 KiB
TypeScript
230 lines
6.9 KiB
TypeScript
import { useState, useEffect, useRef, useMemo } from 'react';
|
|
import * as Popover from '@radix-ui/react-popover';
|
|
import { useToastContext } from '@librechat/client';
|
|
import { useQueryClient } from '@tanstack/react-query';
|
|
import {
|
|
fileConfig as defaultFileConfig,
|
|
QueryKeys,
|
|
defaultOrderQuery,
|
|
mergeFileConfig,
|
|
} from 'librechat-data-provider';
|
|
import type {
|
|
Metadata,
|
|
Assistant,
|
|
AssistantsEndpoint,
|
|
AssistantCreateParams,
|
|
AssistantListResponse,
|
|
} from 'librechat-data-provider';
|
|
import type { UseMutationResult } from '@tanstack/react-query';
|
|
import { useUploadAssistantAvatarMutation, useGetFileConfig } from '~/data-provider';
|
|
import { AssistantAvatar, NoImage, AvatarMenu } from './Images';
|
|
import { useAssistantsMapContext } from '~/Providers';
|
|
// import { Spinner } from '@librechat/client';
|
|
import { useLocalize } from '~/hooks';
|
|
import { formatBytes } from '~/utils';
|
|
|
|
function Avatar({
|
|
endpoint,
|
|
version,
|
|
assistant_id,
|
|
metadata,
|
|
createMutation,
|
|
}: {
|
|
endpoint: AssistantsEndpoint;
|
|
version: number | string;
|
|
assistant_id: string | null;
|
|
metadata: null | Metadata;
|
|
createMutation: UseMutationResult<Assistant, Error, AssistantCreateParams>;
|
|
}) {
|
|
// console.log('Avatar', assistant_id, metadata, createMutation);
|
|
const queryClient = useQueryClient();
|
|
const assistantsMap = useAssistantsMapContext();
|
|
const [menuOpen, setMenuOpen] = useState(false);
|
|
const [progress, setProgress] = useState<number>(1);
|
|
const [input, setInput] = useState<File | null>(null);
|
|
const [previewUrl, setPreviewUrl] = useState<string | null>(null);
|
|
const lastSeenCreatedId = useRef<string | null>(null);
|
|
const { data: fileConfig = defaultFileConfig } = useGetFileConfig({
|
|
select: (data) => mergeFileConfig(data),
|
|
});
|
|
|
|
const localize = useLocalize();
|
|
const { showToast } = useToastContext();
|
|
|
|
const activeModel = useMemo(() => {
|
|
return assistantsMap?.[endpoint][assistant_id ?? '']?.model ?? '';
|
|
}, [assistantsMap, endpoint, assistant_id]);
|
|
|
|
const { mutate: uploadAvatar } = useUploadAssistantAvatarMutation({
|
|
onMutate: () => {
|
|
setProgress(0.4);
|
|
},
|
|
onSuccess: (data, vars) => {
|
|
if (vars.postCreation !== true) {
|
|
showToast({ message: localize('com_ui_upload_success') });
|
|
} else if (lastSeenCreatedId.current !== createMutation.data?.id) {
|
|
lastSeenCreatedId.current = createMutation.data?.id ?? '';
|
|
}
|
|
|
|
setInput(null);
|
|
setPreviewUrl(data.metadata?.avatar as string | null);
|
|
|
|
const res = queryClient.getQueryData<AssistantListResponse | undefined>([
|
|
QueryKeys.assistants,
|
|
endpoint,
|
|
defaultOrderQuery,
|
|
]);
|
|
|
|
if (!res?.data || !res) {
|
|
return;
|
|
}
|
|
|
|
const assistants = res.data.map((assistant) => {
|
|
if (assistant.id === assistant_id) {
|
|
return {
|
|
...assistant,
|
|
...data,
|
|
};
|
|
}
|
|
return assistant;
|
|
});
|
|
|
|
queryClient.setQueryData<AssistantListResponse>(
|
|
[QueryKeys.assistants, endpoint, defaultOrderQuery],
|
|
{
|
|
...res,
|
|
data: assistants,
|
|
},
|
|
);
|
|
|
|
setProgress(1);
|
|
},
|
|
onError: (error) => {
|
|
console.error('Error:', error);
|
|
setInput(null);
|
|
setPreviewUrl(null);
|
|
showToast({ message: localize('com_ui_upload_error'), status: 'error' });
|
|
setProgress(1);
|
|
},
|
|
});
|
|
|
|
useEffect(() => {
|
|
if (input) {
|
|
const reader = new FileReader();
|
|
reader.onloadend = () => {
|
|
setPreviewUrl(reader.result as string);
|
|
};
|
|
reader.readAsDataURL(input);
|
|
}
|
|
}, [input]);
|
|
|
|
useEffect(() => {
|
|
setPreviewUrl((metadata?.avatar as string | undefined) ?? null);
|
|
}, [metadata]);
|
|
|
|
useEffect(() => {
|
|
/** Experimental: Condition to prime avatar upload before Assistant Creation
|
|
* - If the createMutation state Id was last seen (current) and the createMutation is successful
|
|
* we can assume that the avatar upload has already been initiated and we can skip the upload
|
|
*
|
|
* The mutation state is not reset until the user deliberately selects a new assistant or an assistant is deleted
|
|
*
|
|
* This prevents the avatar from being uploaded multiple times before the user selects a new assistant
|
|
* while allowing the user to upload to prime the avatar and other values before the assistant is created.
|
|
*/
|
|
const sharedUploadCondition = !!(
|
|
createMutation.isSuccess &&
|
|
input &&
|
|
previewUrl &&
|
|
previewUrl.includes('base64')
|
|
);
|
|
if (sharedUploadCondition && lastSeenCreatedId.current === createMutation.data.id) {
|
|
return;
|
|
}
|
|
|
|
if (sharedUploadCondition && createMutation.data.id) {
|
|
console.log('[AssistantAvatar] Uploading Avatar after Assistant Creation');
|
|
|
|
const formData = new FormData();
|
|
formData.append('file', input, input.name);
|
|
formData.append('assistant_id', createMutation.data.id);
|
|
|
|
uploadAvatar({
|
|
assistant_id: createMutation.data.id,
|
|
model: activeModel,
|
|
postCreation: true,
|
|
formData,
|
|
endpoint,
|
|
version,
|
|
});
|
|
}
|
|
}, [
|
|
createMutation.data,
|
|
createMutation.isSuccess,
|
|
input,
|
|
previewUrl,
|
|
uploadAvatar,
|
|
activeModel,
|
|
endpoint,
|
|
version,
|
|
]);
|
|
|
|
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>): void => {
|
|
const file = event.target.files?.[0];
|
|
|
|
if (fileConfig.avatarSizeLimit && file && file.size <= fileConfig.avatarSizeLimit) {
|
|
if (!file) {
|
|
console.error('No file selected');
|
|
return;
|
|
}
|
|
|
|
setInput(file);
|
|
setMenuOpen(false);
|
|
|
|
if (!assistant_id) {
|
|
// wait for successful form submission before uploading avatar
|
|
console.log('[AssistantAvatar] No assistant_id, will wait until form submission + upload');
|
|
return;
|
|
}
|
|
|
|
const formData = new FormData();
|
|
formData.append('file', file, file.name);
|
|
formData.append('assistant_id', assistant_id);
|
|
|
|
uploadAvatar({
|
|
assistant_id,
|
|
model: activeModel,
|
|
formData,
|
|
endpoint,
|
|
version,
|
|
});
|
|
} else {
|
|
const megabytes = fileConfig.avatarSizeLimit ? formatBytes(fileConfig.avatarSizeLimit) : 2;
|
|
showToast({
|
|
message: localize('com_ui_upload_invalid_var', { 0: megabytes + '' }),
|
|
status: 'error',
|
|
});
|
|
}
|
|
|
|
setMenuOpen(false);
|
|
};
|
|
|
|
return (
|
|
<Popover.Root open={menuOpen} onOpenChange={setMenuOpen}>
|
|
<div className="flex w-full items-center justify-center gap-4">
|
|
<Popover.Trigger asChild>
|
|
<button
|
|
type="button"
|
|
className="h-20 w-20"
|
|
aria-label={localize('com_ui_upload_avatar_label')}
|
|
>
|
|
{previewUrl ? <AssistantAvatar url={previewUrl} progress={progress} /> : <NoImage />}
|
|
</button>
|
|
</Popover.Trigger>
|
|
</div>
|
|
{<AvatarMenu handleFileChange={handleFileChange} />}
|
|
</Popover.Root>
|
|
);
|
|
}
|
|
|
|
export default Avatar;
|