Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat: renaming refactor, make optimistic, fixes and improvements (#1311)

gbirmanfaba3138a0d9
diff --git a/js/app/packages/app/component/EntityModal/RenameView.tsx b/js/app/packages/app/component/EntityModal/RenameView.tsx
index 75a68e2a55..49ce24567e 100644
--- a/js/app/packages/app/component/EntityModal/RenameView.tsx
+++ b/js/app/packages/app/component/EntityModal/RenameView.tsx
@@ -2,15 +2,8 @@ import { useUpsertSavedViewMutation } from '@app/component/Soup';
import { useSplitPanelOrThrow } from '@app/component/split-layout/layoutUtils';
import type { ViewConfigBase } from '@app/component/ViewConfig';
import { unwrapSignals } from '@core/util/unwrapSignals';
-import {
- optimisticUpdateChannelName,
- rollbackUpdateChannelName,
- type UpdateChannelNameContext,
-} from '@queries/channel/channel';
-import { channelKeys } from '@queries/channel/keys';
-import { queryClient } from '@queries/client';
import { createMemo, createSignal, onMount } from 'solid-js';
-import { createRenameDssEntityMutation } from '../../../macro-entity/src/queries/dss';
+import { createRenameDssEntityMutation } from '../../../macro-entity/src/queries/rename';
import type { EntityData } from '../../../macro-entity/src/types/entity';
import { EntityModalActionFooter, EntityModalTitle } from './EntityModal';
@@ -20,38 +13,7 @@ export const RenameView = (props: {
onFinish: () => void;
onCancel: () => void;
}) => {
- const renameMutation = createRenameDssEntityMutation({
- onMutate(variables) {
- if (variables.entity.type !== 'channel') return;
-
- const context = optimisticUpdateChannelName({
- channelId: variables.entity.id,
- name: variables.newName,
- });
- return { context, channelId: variables.entity.id };
- },
- onError(
- _,
- _variables,
- onMutateResult: {
- context: UpdateChannelNameContext | undefined;
- channelId: string;
- }
- ) {
- if (onMutateResult?.context) {
- rollbackUpdateChannelName(
- onMutateResult.channelId,
- onMutateResult.context
- );
- }
- },
- onSettled(_, __, variables) {
- // TODO: fix the backend so that the /channels/{id} endpoint returns the updated name
- queryClient.prefetchQuery({
- queryKey: channelKeys.withID(variables.entity.id).queryKey,
- });
- },
- });
+ const renameMutation = createRenameDssEntityMutation();
let inputRef: HTMLInputElement | undefined;
const saveViewMutation = useUpsertSavedViewMutation();
const {
diff --git a/js/app/packages/app/component/bulk-edit-entity/BulkRenameEntitiesView.tsx b/js/app/packages/app/component/bulk-edit-entity/BulkRenameEntitiesView.tsx
index b39a6fc1ff..94005acbb4 100644
--- a/js/app/packages/app/component/bulk-edit-entity/BulkRenameEntitiesView.tsx
+++ b/js/app/packages/app/component/bulk-edit-entity/BulkRenameEntitiesView.tsx
@@ -1,6 +1,6 @@
import { SegmentedControl } from '@core/component/FormControls/SegmentControls';
import { createMemo, createSignal, onMount, Show } from 'solid-js';
-import { createBulkRenameDssEntityMutation } from '../../../macro-entity/src/queries/dss';
+import { createBulkRenameDssEntityMutation } from '../../../macro-entity/src/queries/rename';
import type { EntityData } from '../../../macro-entity/src/types/entity';
import {
BulkEditEntityModalActionFooter,
@@ -88,10 +88,9 @@ export const BulkRenameEntitiesView = (props: {
default:
}
- await renameMutation.mutateAsync({
- entities: props.entities,
- name: renameFn,
- });
+ await renameMutation.mutateAsync(
+ props.entities.map((e) => ({ entity: e, newName: renameFn(e.name) }))
+ );
props.onFinish();
};
diff --git a/js/app/packages/app/component/split-layout/components/SplitModalContext.tsx b/js/app/packages/app/component/split-layout/components/SplitModalContext.tsx
index a8488ac566..d2882157f1 100644
--- a/js/app/packages/app/component/split-layout/components/SplitModalContext.tsx
+++ b/js/app/packages/app/component/split-layout/components/SplitModalContext.tsx
@@ -50,16 +50,7 @@ export function useRenameSplit() {
// Helper to convert ItemType to EntityData type
const itemTypeToEntityType = (itemType: ItemType): EntityData['type'] => {
- switch (itemType) {
- case 'document':
- return 'document';
- case 'chat':
- return 'chat';
- case 'project':
- return 'project';
- default:
- return 'document'; // fallback
- }
+ return itemType;
};
export function SplitModalProvider(props: ParentProps) {
@@ -73,6 +64,8 @@ export function SplitModalProvider(props: ParentProps) {
setIsOpen(true);
};
+ // TODO: we should ideally not be type casting here because
+ // downstream components might not be aware that some entity data fields are missing
const createEntityData = (): EntityData | undefined => {
const params = modalParams();
if (!params) return undefined;
diff --git a/js/app/packages/block-channel/component/Top.tsx b/js/app/packages/block-channel/component/Top.tsx
index 6988e4054d..17d8ff428f 100644
--- a/js/app/packages/block-channel/component/Top.tsx
+++ b/js/app/packages/block-channel/component/Top.tsx
@@ -97,7 +97,9 @@ export function Top(props: TopProps) {
label={channelName() ?? 'New Channel'}
id={props.channelId}
itemType="channel"
- lockRename={!isAdminOrOwner()}
+ lockRename={
+ props.channelType === 'direct_message' || !isAdminOrOwner()
+ }
/>
</div>
</div>
diff --git a/js/app/packages/core/component/FileList/itemOperations.ts b/js/app/packages/core/component/FileList/itemOperations.ts
index 28c9ec8570..2c4a705ee6 100644
--- a/js/app/packages/core/component/FileList/itemOperations.ts
+++ b/js/app/packages/core/component/FileList/itemOperations.ts
@@ -60,13 +60,13 @@ export async function getItemAccessLevel({
}
}
+/** @internal use rename mutation wrappers instead of this */
export async function renameItem(args: {
itemType: ItemType;
id: string;
newName: string;
- skipRefetch?: boolean;
}): Promise<boolean> {
- const { itemType, id, newName, skipRefetch = false } = args;
+ const { itemType, id, newName } = args;
let result;
@@ -108,9 +108,6 @@ export async function renameItem(args: {
return false;
}
- if (!skipRefetch) {
- refetchResources({ id });
- }
return true;
}
@@ -195,43 +192,6 @@ export async function bulkDelete(
};
}
-export async function bulkRename(
- selectedItems: { item: Item; newName: string }[],
- chunkSize: number = DEFAULT_CHUNK_SIZE
-): Promise<{ success: boolean; failedItems: Item[] }> {
- const failedItems: Item[] = [];
-
- for (let i = 0; i < selectedItems.length; i += chunkSize) {
- const chunk = selectedItems.slice(i, i + chunkSize);
-
- const results = await Promise.allSettled(
- chunk.map(({ item, newName }) =>
- renameItem({
- itemType: item.type,
- id: item.id,
- newName,
- skipRefetch: true,
- })
- )
- );
-
- results.forEach((result, index) => {
- if (
- result.status === 'rejected' ||
- (result.status === 'fulfilled' && !result.value)
- ) {
- failedItems.push(chunk[index].item);
- }
- });
- }
-
- refetchResources();
- return {
- success: failedItems.length === 0,
- failedItems,
- };
-}
-
export async function moveToFolder(args: {
itemType: ItemType;
id: string;
diff --git a/js/app/packages/core/component/FileList/useItemOperations.ts b/js/app/packages/core/component/FileList/useItemOperations.ts
index b3025b486d..97dd63255c 100644
--- a/js/app/packages/core/component/FileList/useItemOperations.ts
+++ b/js/app/packages/core/component/FileList/useItemOperations.ts
@@ -16,14 +16,12 @@ import {
bulkDelete as bulkDeleteOp,
bulkMoveToFolder as bulkMoveToFolderOp,
bulkPermanentlyDelete as bulkPermanentlyDeleteOp,
- bulkRename as bulkRenameOp,
bulkRevertDelete as bulkRevertDeleteOp,
copyItem as copyItemOp,
deleteItem as deleteItemOp,
getItemAccessLevel as getItemAccessLevelOp,
moveToFolder as moveToFolderOp,
permanentlyDelete as permanentlyDeleteOp,
- renameItem as renameItemOp,
revertDelete as revertDeleteOp,
} from './itemOperations';
@@ -32,25 +30,6 @@ export const useItemOperations = createSingletonRoot(() => {
(args: { itemType: ItemType; id: string }) => getItemAccessLevelOp(args)
);
- const renameItem = createCallback(
- async (args: {
- itemType: ItemType;
- id: string;
- itemName: string;
- newName: string;
- }) => {
- const success = await renameItemOp({
- itemType: args.itemType,
- id: args.id,
- newName: args.newName,
- });
- if (!success) {
- toast.failure('Unable to rename item');
- }
- return success;
- }
- );
-
const deleteItem = createCallback(
async (args: { itemType: ItemType; id: string; itemName: string }) => {
const success = await deleteItemOp(args);
@@ -208,26 +187,6 @@ export const useItemOperations = createSingletonRoot(() => {
return result;
});
- const bulkRename = createCallback(
- async (items: { item: Item; newName: string }[]) => {
- const result = await toast.promise(bulkRenameOp(items), {
- loading: `Renaming ${items.length} ${items.length === 1 ? 'item' : 'items'}...`,
- success: ({ failedItems }) => {
- if (failedItems.length > 0) {
- return `Failed to rename ${failedItems.length} ${failedItems.length === 1 ? 'item' : 'items'}`;
- }
- return `Successfully renamed ${items.length} ${items.length === 1 ? 'item' : 'items'}`;
- },
- error: (error) => {
- return `Failed to rename items: ${error.message || 'Unknown error'}`;
- },
- toastTypeDeterminer: (result) =>
- result.failedItems.length > 0 ? ToastType.FAILURE : ToastType.SUCCESS,
- });
- return result;
- }
- );
-
const bulkRevertDelete = createCallback(async (items: Item[]) => {
const result = await toast.promise(bulkRevertDeleteOp(items), {
loading: `Restoring ${items.length} ${items.length === 1 ? 'item' : 'items'}...`,
@@ -246,14 +205,12 @@ export const useItemOperations = createSingletonRoot(() => {
});
return {
- renameItem,
deleteItem,
moveToFolder,
copyItem,
bulkDelete,
bulkCopy,
bulkMoveToFolder,
- bulkRename,
getItemAccessLevel,
revertDelete,
permanentlyDelete,
diff --git a/js/app/packages/macro-entity/src/queries/dss.ts b/js/app/packages/macro-entity/src/queries/dss.ts
index 86ca4dbc47..3226cb0c35 100644
--- a/js/app/packages/macro-entity/src/queries/dss.ts
+++ b/js/app/packages/macro-entity/src/queries/dss.ts
@@ -2,13 +2,10 @@ import {
copyItem,
deleteItem,
moveToFolder,
- renameItem,
} from '@core/component/FileList/itemOperations';
import { itemToSafeName } from '@core/constant/allBlocks';
import { toast } from '@core/component/Toast/Toast';
-import { type MutationCallbacks, withCallbacks } from '@queries/utils';
import type { UnifiedSearchResponseItem } from '@service-search/generated/models';
-import type { ItemType } from '@service-storage/client';
import type {
PostItemsSoupParams,
PostSoupRequest,
@@ -540,170 +537,6 @@ export function createBulkDeleteDssItemsMutation() {
}));
}
-type RenameDssEntityMutationVariables = {
- entity: EntityData & { name: string };
- newName: string;
-};
-
-type RenameDssEntityMutationData = {
- success: boolean;
-};
-
-const isEntityRenameSupported = (entity: EntityData) => {
- const type = entity.type;
- if (entity.type === 'channel') {
- return entity.channelType !== 'direct_message';
- }
- return type !== 'email';
-};
-
-/**
- * Mutation to rename a DSS entity.
- */
-export function createRenameDssEntityMutation(
- callbacks?: MutationCallbacks<
- RenameDssEntityMutationData,
- Error,
- RenameDssEntityMutationVariables
- >
-) {
- return useMutation(() => ({
- mutationFn: async (params: RenameDssEntityMutationVariables) => {
- if (!isEntityRenameSupported(params.entity)) {
- throw new Error('Unsupported entity type provided');
- }
-
- const success = await renameItem({
- id: params.entity.id,
- itemType: params.entity.type,
- newName: params.newName,
- });
-
- return { success };
- },
- ...withCallbacks<
- RenameDssEntityMutationData,
- Error,
- RenameDssEntityMutationVariables
- >(
- {
- onMutate: async ({ entity: { id }, newName }) => {
- queryClient.cancelQueries({
- queryKey: queryKeys.dss({ infinite: true }),
- });
- function updateEntityNameInQueryData(
- prev: { pages: { items: EntityData[] }[] } | undefined,
- id: string,
- newName: string
- ) {
- if (!prev) return prev;
- const pages = prev.pages.map((page) => ({
- ...page,
- items: page.items.map((item) =>
- item.id === id ? { ...item, name: newName } : item
- ),
- }));
- return {
- ...prev,
- pages,
- };
- }
-
- queryClient.setQueriesData(
- { queryKey: queryKeys.dss({ infinite: true }) },
- (prev: { pages: { items: EntityData[] }[] } | undefined) =>
- updateEntityNameInQueryData(prev, id, newName)
- );
- },
- onSettled: (data, error, { entity: { id } }) => {
- if (data?.success === false || error) {
- console.error(`Failed to rename dss item ${id}`, data, error);
- toast.failure('Failed to rename item');
- }
-
- queryClient.invalidateQueries({
- queryKey: queryKeys.all.dss,
- });
- },
- },
- callbacks
- ),
- }));
-}
-
-export function createBulkRenameDssEntityMutation() {
- return useMutation(() => ({
- mutationFn: async ({
- entities,
- name,
- }: {
- entities: (EntityData & { name: string })[];
- name: (oldName: string) => string | string;
- }) => {
- if (!entities.every(isEntityRenameSupported)) {
- throw new Error(`Unsupported entity type provided`);
- }
- return await Promise.all(
- entities.map((e) => {
- return renameItem({
- itemType: e.type as ItemType,
- id: e.id,
- newName: typeof name === 'function' ? name(e.name) : name,
- });
- })
- );
- },
-
- onMutate: async ({
- entities,
- name,
- }: {
- entities: (EntityData & { name: string })[];
- name: (oldName: string) => string | string;
- }) => {
- const ids = new Set(entities.map((e) => e.id));
-
- queryClient.cancelQueries({
- queryKey: queryKeys.dss({ infinite: true }),
- });
-
- function update(prev: { pages: { items: EntityData[] }[] } | undefined) {
- if (!prev) return prev;
- return {
- ...prev,
- pages: prev.pages.map((page) => ({
- ...page,
- items: page.items.map((item) =>
- ids.has(item.id)
- ? {
- ...item,
- name: typeof name === 'function' ? name(item.name) : name,
- }
- : item
- ),
- })),
- };
- }
-
- queryClient.setQueriesData(
- { queryKey: queryKeys.dss({ infinite: true }) },
- (prev) => update(prev as any)
- );
- },
-
- onSettled: (data, error, { entities }) => {
- if (error) {
- console.error(`Failed bulk rename`, entities, data, error);
- toast.failure('Failed to rename items');
- }
-
- queryClient.invalidateQueries({
- queryKey: queryKeys.all.dss,
- });
- },
- }));
-}
-
function createMoveOptimisticUpdate(entityIds: string[], projectId: string) {
return (
prev: { pages: { items: EntityData[] }[] } | undefined
diff --git a/js/app/packages/macro-entity/src/queries/rename.ts b/js/app/packages/macro-entity/src/queries/rename.ts
new file mode 100644
index 0000000000..effc671e6b
--- /dev/null
+++ b/js/app/packages/macro-entity/src/queries/rename.ts
@@ -0,0 +1,341 @@
+import { renameItem } from '@core/component/FileList/itemOperations';
+import {
+ optimisticUpdateChannelName,
+ rollbackUpdateChannelName,
+ type UpdateChannelNameContext,
+} from '@queries/channel/channel';
+import { type MutationCallbacks, withCallbacks } from '@queries/utils';
+import type { ItemType } from '@service-storage/client';
+import type { EntityData } from '../types/entity';
+import { queryClient } from './client';
+import { queryKeys } from './key';
+import { type InfiniteData, useMutation } from '@tanstack/solid-query';
+import { toast } from '@core/component/Toast/Toast';
+import type { SoupPage } from '@service-storage/generated/schemas';
+import { setPreviewData } from '@queries/preview';
+import { setHistoryItemData } from '@queries/history/history';
+
+type EntityWithName = EntityData & { name: string };
+
+type EntityRenameOperation = {
+ entity: EntityWithName;
+ newName: string;
+};
+
+type EntityRenameOperationResult = {
+ success: boolean;
+};
+
+// Maps channel ID to its update context, which lets us rollback the updated at timestamp as well as name
+type ChannelRenameContexts = Map<string, UpdateChannelNameContext | undefined>;
+
+type RenameRollbackContext = {
+ channels: ChannelRenameContexts;
+};
+
+type EntityRenameData = {
+ id: string;
+ itemType: ItemType;
+ oldName: string;
+ newName: string;
+};
+
+type EntityIdToNameMap = Map<string, string>;
+
+type RenameDssEntityMutationVariables = EntityRenameOperation;
+
+type BulkRenameDssEntityMutationVariables = RenameDssEntityMutationVariables[];
+
+type RenameDssEntityMutationData = EntityRenameOperationResult;
+
+type BulkRenameDssEntityMutationData = RenameDssEntityMutationData[];
+
+type RenameOnMutateResult = {
+ contexts: RenameRollbackContext;
+ updates: EntityRenameData[];
+};
+
+const getEntityRenameData = (
+ operation: EntityRenameOperation
+): EntityRenameData => {
+ const { entity, newName } = operation;
+ return {
+ id: entity.id,
+ itemType: entity.type,
+ oldName: entity.name,
+ newName,
+ };
+};
+
+const performEntityRename = async (operation: EntityRenameOperation) => {
+ const data = getEntityRenameData(operation);
+ const success = await renameItem(data);
+ return { success };
+};
+
+const validateEntityRename = (entity: EntityData): void => {
+ switch (entity.type) {
+ case 'channel':
+ // NOTE: channel type is undefined if provided from the split modal due to casting in createEntityData
+ if (entity.channelType === 'direct_message') {
+ throw new Error('Direct messages do not support renaming');
+ }
+ break;
+ case 'document':
+ case 'chat':
+ case 'project':
+ return;
+ default:
+ throw new Error(`Unsupported entity type: ${entity.type}`);
+ }
+};
+
+// TODO: move item to front of list with updatedAt timestamp
+function updateEntityNamesInDssQueryData(
+ prev: InfiniteData<SoupPage, unknown> | undefined,
+ updates: EntityIdToNameMap
+): InfiniteData<SoupPage, unknown> | undefined {
+ if (!prev) return prev;
+ const pages = prev.pages.map((page) => ({
+ ...page,
+ items: page.items.map((item) => {
+ // NOTE: reactivity does not seem to be a problem here so no spread is needed?
+ switch (item.tag) {
+ case 'channel': {
+ const itemId = item.data.channel.id;
+ const newName = updates.get(itemId);
+ if (!newName) return item;
+ item.data.channel.name = newName;
+ break;
+ }
+ case 'document':
+ case 'chat':
+ case 'project': {
+ const itemId = item.data.id;
+ const newName = updates.get(itemId);
+ if (!newName) return item;
+ item.data.name = newName;
+ break;
+ }
+ default:
+ break;
+ }
+ return item;
+ }),
+ }));
+ return {
+ ...prev,
+ pages,
+ };
+}
+
+const renameDssSetData = (entities: EntityRenameData[]) => {
+ const updates: EntityIdToNameMap = new Map(
+ entities.map((e) => [e.id, e.newName])
+ );
+
+ queryClient.cancelQueries({
+ queryKey: queryKeys.all.dss,
+ });
+ queryClient.setQueriesData({ queryKey: queryKeys.all.dss }, (prev) =>
+ updateEntityNamesInDssQueryData(
+ prev as InfiniteData<SoupPage, unknown> | undefined,
+ updates
+ )
+ );
+};
+
+const renameChannelSetData = (
+ entities: EntityRenameData[]
+): ChannelRenameContexts => {
+ const contexts: ChannelRenameContexts = new Map();
+
+ entities.forEach(({ id, itemType, newName }) => {
+ if (itemType === 'channel') {
+ const context = optimisticUpdateChannelName({
+ channelId: id,
+ name: newName,
+ });
+ if (context) {
+ contexts.set(id, context);
+ }
+ }
+ });
+
+ return contexts;
+};
+
+const renamePreviewSetData = (entities: EntityRenameData[]) => {
+ entities.forEach(({ id, newName }) => {
+ setPreviewData(id, (prev) => ({
+ ...prev,
+ name: newName,
+ }));
+ });
+};
+
+const renameHistorySetData = (entities: EntityRenameData[]) => {
+ entities.forEach(({ id, newName }) => {
+ setHistoryItemData(id, (prev) => ({
+ ...prev,
+ name: newName,
+ }));
+ });
+};
+
+function performOptimisticRenameUpdates(
+ entities: EntityRenameData[]
+): RenameRollbackContext {
+ renamePreviewSetData(entities);
+ renameHistorySetData(entities);
+ renameDssSetData(entities);
+ const channelContexts = renameChannelSetData(entities);
+
+ return {
+ channels: channelContexts,
+ };
+}
+
+function rollbackOptimisticRenameUpdates({
+ contexts,
+ updates,
+}: RenameOnMutateResult): void {
+ updates.forEach(({ id, oldName, itemType }) => {
+ const reverseUpdate = { id, itemType, newName: oldName, oldName };
+ renameDssSetData([reverseUpdate]);
+ renameHistorySetData([reverseUpdate]);
+ renamePreviewSetData([reverseUpdate]);
+
+ if (itemType === 'channel') {
+ const context = contexts.channels.get(id);
+ if (context) {
+ rollbackUpdateChannelName(id, context);
+ } else {
+ console.error(`No rollback context provided for channel item ${id}`);
+ }
+ }
+ });
+}
+
+const bulkRenameMutationFn = async (
+ params: BulkRenameDssEntityMutationVariables
+): Promise<BulkRenameDssEntityMutationData> => {
+ const entities = params.map((p) => p.entity);
+ entities.forEach(validateEntityRename);
+
+ // TODO: add bulk rename on backend or consider batching in chunks
+ // with timeouts to avoid too many requests
+ return await Promise.all(params.map(performEntityRename));
+};
+
+const bulkRenameOnMutate = (
+ params: BulkRenameDssEntityMutationVariables
+): RenameOnMutateResult => {
+ const updates = params.map(getEntityRenameData);
+ const contexts = performOptimisticRenameUpdates(updates);
+ return { contexts, updates };
+};
+
+const bulkRenameOnSettled = (
+ data: BulkRenameDssEntityMutationData | undefined,
+ error: Error | null,
+ params: BulkRenameDssEntityMutationVariables,
+ onMutateResult: RenameOnMutateResult | undefined
+): void => {
+ const hasFailed = !!error || data?.some((d) => !d.success);
+ if (!hasFailed) return;
+
+ console.error(`Failed rename`, params, data, error);
+ toast.failure('Failed to rename');
+
+ if (!onMutateResult) {
+ // TODO: refetch everything since we don't have rollback data
+ return;
+ }
+
+ // rollback everything if we can't identify specific failures
+ if (!data) {
+ rollbackOptimisticRenameUpdates(onMutateResult);
+ return;
+ }
+
+ // Rollback only the failed items by matching indices
+ const failedUpdates: EntityRenameData[] = [];
+ const failedChannelContexts: ChannelRenameContexts = new Map();
+
+ data.forEach((result, index) => {
+ if (!result.success) {
+ const update = onMutateResult.updates[index];
+ if (update) {
+ failedUpdates.push(update);
+ // Preserve channel context for failed channels
+ if (update.itemType === 'channel') {
+ const context = onMutateResult.contexts.channels.get(update.id);
+ if (context !== undefined) {
+ failedChannelContexts.set(update.id, context);
+ }
+ }
+ }
+ }
+ });
+
+ // Rollback only the failed items
+ if (failedUpdates.length > 0) {
+ rollbackOptimisticRenameUpdates({
+ contexts: { channels: failedChannelContexts },
+ updates: failedUpdates,
+ });
+ }
+};
+
+/** supports channel/document/chat/project rename */
+export function createRenameDssEntityMutation(
+ callbacks?: MutationCallbacks<
+ RenameDssEntityMutationData,
+ Error,
+ RenameDssEntityMutationVariables,
+ RenameOnMutateResult
+ >
+) {
+ return useMutation<
+ RenameDssEntityMutationData,
+ Error,
+ RenameDssEntityMutationVariables,
+ RenameOnMutateResult
+ >(() => ({
+ mutationFn: async (params) => (await bulkRenameMutationFn([params]))[0],
+ ...withCallbacks<
+ RenameDssEntityMutationData,
+ Error,
+ RenameDssEntityMutationVariables,
+ RenameOnMutateResult
+ >(
+ {
+ onMutate: async (params) => bulkRenameOnMutate([params]),
+ onSettled: (data, error, params, onMutateResult) => {
+ bulkRenameOnSettled(
+ data ? [data] : undefined,
+ error,
+ [params],
+ onMutateResult
+ );
+ },
+ },
+ callbacks
+ ),
+ }));
+}
+
+/** supports channel/document/chat/project bulk rename */
+export function createBulkRenameDssEntityMutation() {
+ return useMutation<
+ BulkRenameDssEntityMutationData,
+ Error,
+ BulkRenameDssEntityMutationVariables,
+ RenameOnMutateResult
+ >(() => ({
+ mutationFn: bulkRenameMutationFn,
+ onMutate: bulkRenameOnMutate,
+ onSettled: bulkRenameOnSettled,
+ }));
+}
diff --git a/js/app/packages/queries/channel/channel.ts b/js/app/packages/queries/channel/channel.ts
index d1dfd0324f..7e5ad0823c 100644
--- a/js/app/packages/queries/channel/channel.ts
+++ b/js/app/packages/queries/channel/channel.ts
@@ -79,65 +79,84 @@ export type UpdateChannelNameContext = {
previousUpdatedAt: string;
};
-/**
- * Optimistically update the channel name.
- * Returns minimal context: only the previous name and timestamp.
- */
-export function optimisticUpdateChannelName(
- vars: WithChannelId<{ name: string }>
-): UpdateChannelNameContext | undefined {
- const queryKey = channelKeys.withID(vars.channelId).queryKey;
- queryClient.cancelQueries({ queryKey });
-
- let context: UpdateChannelNameContext | undefined;
+/** Helper to update channel name in both single channel and list queries. */
+function updateChannelNameInQueries(
+ channelId: string,
+ name: string | null | undefined,
+ updatedAt: string
+): void {
+ const queryKey = channelKeys.withID(channelId).queryKey;
+ const listQueryKey = channelKeys.listChannels.queryKey;
queryClient.setQueriesData(
{ queryKey },
(prev: GetChannelResponse | undefined) => {
if (!prev) return prev;
- context = {
- previousName: prev.channel.name,
- previousUpdatedAt: prev.channel.updated_at,
- };
-
return {
...prev,
channel: {
...prev.channel,
- name: vars.name,
- updated_at: new Date().toISOString(),
+ name,
+ updated_at: updatedAt,
},
};
}
);
- return context;
+ queryClient.setQueriesData(
+ { queryKey: listQueryKey },
+ (prev: ApiChannelWithLatest[] | undefined) => {
+ if (!prev) return prev;
+
+ return prev.map((channel) =>
+ channel.id === channelId
+ ? { ...channel, name, updated_at: updatedAt }
+ : channel
+ );
+ }
+ );
}
/**
- * Rollback an optimistic channel name update.
+ * Optimistically update the channel name.
+ * Returns context needed to rollback the update.
*/
+export function optimisticUpdateChannelName(
+ vars: WithChannelId<{ name: string }>
+): UpdateChannelNameContext | undefined {
+ const queryKey = channelKeys.withID(vars.channelId).queryKey;
+ const listQueryKey = channelKeys.listChannels.queryKey;
+
+ queryClient.cancelQueries({ queryKey });
+ queryClient.cancelQueries({ queryKey: listQueryKey });
+
+ let context: UpdateChannelNameContext | undefined;
+
+ // Capture previous state for rollback
+ const prev = queryClient.getQueryData<GetChannelResponse>(queryKey);
+ if (prev) {
+ context = {
+ previousName: prev.channel.name,
+ previousUpdatedAt: prev.channel.updated_at,
+ };
+ }
+
+ const now = new Date().toISOString();
+ updateChannelNameInQueries(vars.channelId, vars.name, now);
+
+ return context;
+}
+
+/** Rollback an optimistic channel name update. */
export function rollbackUpdateChannelName(
channelId: string,
context: UpdateChannelNameContext
): void {
- const queryKey = channelKeys.withID(channelId).queryKey;
-
- queryClient.setQueriesData(
- { queryKey },
- (prev: GetChannelResponse | undefined) => {
- if (!prev) return prev;
-
- return {
- ...prev,
- channel: {
- ...prev.channel,
- name: context.previousName,
- updated_at: context.previousUpdatedAt,
- },
- };
- }
+ updateChannelNameInQueries(
+ channelId,
+ context.previousName,
+ context.previousUpdatedAt
);
}
diff --git a/js/app/packages/queries/history/history.ts b/js/app/packages/queries/history/history.ts
index 664c601a6c..8f25757ee7 100644
--- a/js/app/packages/queries/history/history.ts
+++ b/js/app/packages/queries/history/history.ts
@@ -9,7 +9,7 @@ import {
useQuery,
type QueryClient,
} from '@tanstack/solid-query';
-import type { Accessor } from 'solid-js';
+import type { Accessor, Setter } from 'solid-js';
import { queryClient } from '../client';
import { historyKeys } from './keys';
import {
@@ -30,6 +30,28 @@ export {
const HISTORY_STALE_TIME = 5 * 60 * 1000;
const HISTORY_GC_TIME = 10 * 60 * 1000;
+export function setHistoryItemData(
+ itemId: string,
+ updater: Setter<HistoryItem>
+) {
+ return queryClient.setQueryData<HistoryQueryResponse>(
+ historyKeys.list.queryKey,
+ (prev) => {
+ if (!prev) return prev;
+ const items = prev.data.map((item) => {
+ if (item.id === itemId) {
+ return updater(item);
+ }
+ return item;
+ });
+ return {
+ ...prev,
+ data: items,
+ };
+ }
+ );
+}
+
function historyQueryOptions() {
return {
queryKey: historyKeys.list.queryKey,
diff --git a/js/app/packages/service-clients/service-storage/util/refetchResources.ts b/js/app/packages/service-clients/service-storage/util/refetchResources.ts
index 92faaeddc9..1f7048cd8d 100644
--- a/js/app/packages/service-clients/service-storage/util/refetchResources.ts
+++ b/js/app/packages/service-clients/service-storage/util/refetchResources.ts
@@ -4,27 +4,15 @@ import { invalidateProjects } from '@queries/storage/projects';
import { invalidateUserQuota } from '@queries/auth';
import { refetchHistory } from '@queries/history/history';
import { invalidatePreview } from '@queries/preview';
-import { invalidateChannelWithID } from '@queries/channel/channel';
-import { invalidateListChannels } from '@queries/channel/channels';
-type RefetchResourcesOptions = {
- id?: string;
-};
-
-export function refetchResources(options?: RefetchResourcesOptions) {
+export function refetchResources() {
// TODO: fetch documents
// refetchDocuments();
invalidateUserQuota();
refetchHistory();
refetchProjectResources();
invalidateDeletedItems();
- // TODO: consolidate where we rename items
- // and optimistically set the data using setPreviewData
- invalidatePreview(options?.id);
- if (options?.id) {
- invalidateChannelWithID(options.id);
- invalidateListChannels();
- }
+ invalidatePreview();
}
export async function refetchProjectResources(_force = false) {