2025-01-23 18:19:04 -05:00
|
|
|
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
2025-03-05 12:04:26 -05:00
|
|
|
import { dataService, QueryKeys, Constants } from 'librechat-data-provider';
|
2025-01-23 18:19:04 -05:00
|
|
|
import type { UseMutationResult } from '@tanstack/react-query';
|
2025-03-05 12:04:26 -05:00
|
|
|
import type * as t from 'librechat-data-provider';
|
2025-01-23 18:19:04 -05:00
|
|
|
|
|
|
|
|
export const useEditArtifact = (
|
|
|
|
|
_options?: t.EditArtifactOptions,
|
|
|
|
|
): UseMutationResult<t.TEditArtifactResponse, Error, t.TEditArtifactRequest> => {
|
|
|
|
|
const queryClient = useQueryClient();
|
|
|
|
|
const { onSuccess, ...options } = _options ?? {};
|
|
|
|
|
return useMutation({
|
|
|
|
|
mutationFn: (variables: t.TEditArtifactRequest) => dataService.editArtifact(variables),
|
|
|
|
|
onSuccess: (data, vars, context) => {
|
2025-03-05 12:04:26 -05:00
|
|
|
let targetNotFound = true;
|
|
|
|
|
const setMessageData = (conversationId?: string | null) => {
|
|
|
|
|
if (!conversationId) {
|
|
|
|
|
return;
|
2025-01-23 18:19:04 -05:00
|
|
|
}
|
2025-03-05 12:04:26 -05:00
|
|
|
queryClient.setQueryData<t.TMessage[]>([QueryKeys.messages, conversationId], (prev) => {
|
|
|
|
|
if (!prev) {
|
|
|
|
|
return prev;
|
|
|
|
|
}
|
2025-01-23 18:19:04 -05:00
|
|
|
|
2025-03-05 12:04:26 -05:00
|
|
|
const newArray = [...prev];
|
|
|
|
|
let targetIndex: number | undefined;
|
2025-01-23 18:19:04 -05:00
|
|
|
|
2025-03-05 12:04:26 -05:00
|
|
|
for (let i = newArray.length - 1; i >= 0; i--) {
|
|
|
|
|
if (newArray[i].messageId === vars.messageId) {
|
|
|
|
|
targetIndex = i;
|
|
|
|
|
targetNotFound = false;
|
|
|
|
|
break;
|
|
|
|
|
}
|
2025-01-23 18:19:04 -05:00
|
|
|
}
|
|
|
|
|
|
2025-03-05 12:04:26 -05:00
|
|
|
if (targetIndex == null) {
|
|
|
|
|
return prev;
|
|
|
|
|
}
|
2025-01-23 18:19:04 -05:00
|
|
|
|
2025-03-05 12:04:26 -05:00
|
|
|
newArray[targetIndex] = {
|
|
|
|
|
...newArray[targetIndex],
|
|
|
|
|
content: data.content,
|
|
|
|
|
text: data.text,
|
|
|
|
|
};
|
2025-01-23 18:19:04 -05:00
|
|
|
|
2025-03-05 12:04:26 -05:00
|
|
|
return newArray;
|
|
|
|
|
});
|
|
|
|
|
};
|
|
|
|
|
setMessageData(data.conversationId);
|
|
|
|
|
if (targetNotFound) {
|
|
|
|
|
console.warn(
|
|
|
|
|
'Edited Artifact Message not found in cache, trying `new` as `conversationId`',
|
|
|
|
|
);
|
|
|
|
|
setMessageData(Constants.NEW_CONVO);
|
|
|
|
|
}
|
2025-01-23 18:19:04 -05:00
|
|
|
|
|
|
|
|
onSuccess?.(data, vars, context);
|
|
|
|
|
},
|
|
|
|
|
...options,
|
|
|
|
|
});
|
|
|
|
|
};
|