Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(soup): entity actions working in soup (copy, rename, move) (#312)
Seamus7617c8e762bf
diff --git a/js/app/packages/app/component/EntityActionsMenuItems.tsx b/js/app/packages/app/component/EntityActionsMenuItems.tsxindex d3b9920eb0..a2d5a8c753 100644--- a/js/app/packages/app/component/EntityActionsMenuItems.tsx+++ b/js/app/packages/app/component/EntityActionsMenuItems.tsx@@ -12,9 +12,6 @@ interface EntityActionsMenuItemsProps {onSelectAction: (action: EntityActionType) => void;}-// TODO (seamus): this does not handle restoring the previous soup selection-// very gracefully.-export const EntityActionsMenuItems = (props: EntityActionsMenuItemsProps) => {const { unifiedListContext } = useSplitPanelOrThrow();const { actionRegistry, viewsDataStore, selectedView } = unifiedListContext;@@ -29,6 +26,17 @@ export const EntityActionsMenuItems = (props: EntityActionsMenuItemsProps) => {return [props.entity];};+ const canOpenEntityInSplit = () => {+ const splits = globalSplitManager()?.splits;+ if (!splits) return false;+ for (const split of splits()) {+ if (split.content.id === props.entity.id) {+ return false;+ }+ }+ return true;+ };+const setSelection: Setter<EntityData[]> = (entities) => {return unifiedListContext.setViewDataStore(selectedView(),@@ -36,6 +44,9 @@ export const EntityActionsMenuItems = (props: EntityActionsMenuItemsProps) => {entities);};+ const Divider = () => (+ <div class="border-b border-edge-muted w-full my-1"></div>+ );const MenuItemInner = (props: {action: EntityActionType;@@ -45,13 +56,12 @@ export const EntityActionsMenuItems = (props: EntityActionsMenuItemsProps) => {<Show when={actionRegistry.has(props.action)}><MenuItemtext={props.label}- disabled={actionRegistry.isActionDisabled(props.action, entities())}+ disabled={!actionRegistry.isActionEnabled(props.action, entities())}onClick={async () => {const { success, failedEntities } = await actionRegistry.execute(props.action,entities());- console.log({ success, failedEntities });if (success) {setSelection([]);} else if (failedEntities) {@@ -68,10 +78,9 @@ export const EntityActionsMenuItems = (props: EntityActionsMenuItemsProps) => {return (<><MenuItemInner action="mark_as_done" label="Mark Done" />- <MenuItemInner action="delete" label="Delete" /><MenuItemtext="Open in new split"- disabled={entities().length > 1}+ disabled={entities().length > 1 || !canOpenEntityInSplit()}onClick={() => {const splitManager = globalSplitManager();if (!splitManager) {@@ -93,6 +102,14 @@ export const EntityActionsMenuItems = (props: EntityActionsMenuItemsProps) => {}}}/>+ <Divider />+ <MenuItemInner action="rename" label="Rename" />+ <MenuItemInner action="move_to_project" label="Move to Project" />+ <MenuItemInner action="copy" label="Copy" />+ <Divider />+ <div class="text-failure-ink w-full">+ <MenuItemInner action="delete" label="Delete" />+ </div></>);};diff --git a/js/app/packages/app/component/EntitySelectionToolbarModal.tsx b/js/app/packages/app/component/EntitySelectionToolbarModal.tsxindex b6606650f9..cfaf96efd6 100644--- a/js/app/packages/app/component/EntitySelectionToolbarModal.tsx+++ b/js/app/packages/app/component/EntitySelectionToolbarModal.tsx@@ -15,8 +15,8 @@ export const EntitySelectionToolbarModal = (return (<ScopedPortal scope="split"><div class="absolute left-1/2 bottom-4 -translate-x-1/2">- <div class="absolute size-full pattern-edge pattern-diagonal-4 left-1 top-1 -z-1" />- <div class="text-sm font-bold flex flex-row items-center gap-2 p-2 bg-menu border border-edge">+ {/*<div class="absolute size-full pattern-edge-muted pattern-diagonal-4 left-1 top-1 -z-1" />*/}+ <div class="text-sm font-bold flex flex-row items-center gap-2 p-2 bg-menu border border-edge-muted"><div class="flex items-center"><buttontype="button"@@ -33,14 +33,18 @@ export const EntitySelectionToolbarModal = (onClick={props.onAction}class="p-1 px-2 flex gap-1 border-edge-muted border items-center h-full w-full hover:bg-hover hover-transition-bg">- <Hotkey shortcut="cmd+k" />+ <div class="flex border border-edge-muted text-[0.625rem] rounded-xs items-center px-1.5 py-0.25 font-normal">+ <Hotkey shortcut="cmd+k" class="space-x-1" />+ </div><span>Actions</span></button><buttononClick={props.onClose}class="p-1 px-2 flex gap-1 border-edge-muted border items-center h-full w-full hover:bg-hover hover-transition-bg">- <Hotkey shortcut="ESC" />+ <div class="flex border border-edge-muted text-[0.625rem] rounded-xs items-center px-1.5 py-0.25 font-normal">+ <Hotkey shortcut="ESC" />+ </div><span>Clear</span></button></div>diff --git a/js/app/packages/app/component/SoupContext.tsx b/js/app/packages/app/component/SoupContext.tsxindex 42ee6c8c00..d5a0876cdc 100644--- a/js/app/packages/app/component/SoupContext.tsx+++ b/js/app/packages/app/component/SoupContext.tsx@@ -14,6 +14,7 @@ import { isErr } from '@core/util/maybeResult';import { getScrollParent } from '@core/util/scrollParent';import { waitForFrames } from '@core/util/sleep';import type { EntityData } from '@macro-entity';+import { entityHasUnreadNotifications } from '@notifications';import { useTutorialCompleted } from '@service-gql/client';import { storageServiceClient } from '@service-storage/client';import { createLazyMemo } from '@solid-primitives/memo';@@ -41,6 +42,7 @@ import {} from 'solid-js/store';import type { VirtualizerHandle } from 'virtua/solid';import { useUserId } from '../../macro-entity/src/queries/auth';+import { createBulkCopyDssEntityMutation } from '../../macro-entity/src/queries/dss';import { playSound } from '../util/sound';import { openBulkEditModal } from './bulk-edit-entity/BulkEditEntityModal';import {@@ -224,79 +226,150 @@ export function createNavigationEntityListShortcut({const viewData = createMemo(() => viewsData[selectedView()]);const viewIds = createMemo<ViewId[]>(() => Object.keys(viewsData));+ const [attachEntityHotkeys, entityHotkeyScope] = useHotkeyDOMScope('entity');const selectedEntity = () => viewData().selectedEntity;- const userId = useUserId();const notificationSource = useGlobalNotificationSource();+ const userId = useUserId();const isViewingList = createMemo(() => {return splitHandle.content().id === 'unified-list';});- createEffect(() => console.log('IS VIEWING LIST', isViewingList()));-- actionRegistry.register('mark_as_done', async (entities) => {- const handler =- VIEWCONFIG_DEFAULTS[selectedView() as View]?.hotkeyOptions?.e;- if (handler) {- for (const entity of entities) {- handler(entity, {- soupContext: unifiedListContext,- notificationSource,++ /**+ * From the current selection, get the entity to try to select after a modal+ * edit operation.+ */+ const getNextEntity = (+ entitiesForAction: EntityData[]+ ): EntityData | null => {+ const entityList = entities();+ if (!entityList) return null;+ const idToIndexMap = new Map(entityList.map(({ id }, i) => [id, i]));+ let maxIndex = 0;+ for (const entity of entitiesForAction) {+ const ndx = idToIndexMap.get(entity.id);+ if (ndx && ndx > maxIndex) {+ maxIndex = ndx;+ }+ }+ return maxIndex < entityList.length - 1 ? entityList[maxIndex + 1] : null;+ };++ /**+ * Return to list after entity modal edit action.+ */+ const afterEntityAction = (+ entity: EntityData | null | undefined,+ clearSelection?: boolean+ ) => {+ if (clearSelection) {+ setViewDataStore(selectedView(), 'selectedEntities', []);+ }+ if (entity) {+ setViewDataStore(selectedView(), 'selectedEntity', entity);+ setViewDataStore(selectedView(), 'highlightedId', entity.id);+ const nextIndex = entities()?.findIndex(({ id }) => id === entity.id);+ if (nextIndex !== undefined && nextIndex > -1) {+ virtualizerHandle()?.scrollToIndex(nextIndex, {+ align: 'nearest',+ });+ waitForFrames(2).then(() => {+ const elem = getEntityElAtIndex(nextIndex);+ if (elem instanceof HTMLElement) {+ elem.focus();+ return;+ // TODO: cooked state (no focus returned - have not yet seen tho)+ }});+ } else {+ const firstIndex = virtualizerHandle()?.findStartIndex();+ if (!firstIndex) return;+ const elem = getEntityElAtIndex(firstIndex);+ if (elem instanceof HTMLElement) elem.focus();+ // TODO: cooked state (no focus returned - have not yet seen tho)}}- return { success: true };- });+ };+ // ---------------------------------------------------------------------------+ // MARK AS DONE+ // ---------------------------------------------------------------------------actionRegistry.register(- 'delete',- async (entitiesToDelete) => {- const entityList = entities();- if (!entityList) return { success: false };-- const idToIndexMap = new Map(entityList.map(({ id }, i) => [id, i]));- let maxIndex = 0;- for (const entity of entitiesToDelete) {- const ndx = idToIndexMap.get(entity.id);- if (ndx && ndx > maxIndex) {- maxIndex = ndx;+ 'mark_as_done',+ async (entities) => {+ const handler =+ VIEWCONFIG_DEFAULTS[selectedView() as View]?.hotkeyOptions?.e;+ if (handler) {+ if (isEntityLastItem()) {+ navigateThroughList({ axis: 'start', mode: 'step' });+ } else {+ navigateThroughList({ axis: 'end', mode: 'step' });}++ for (const entity of entities) {+ handler(entity, {+ soupContext: unifiedListContext,+ notificationSource,+ });+ }++ setViewDataStore(selectedView(), 'selectedEntities', []);+ }++ return { success: true };+ },+ {+ testEnabled: (entity) => {+ if (entity.type === 'email') return true;+ if (entityHasUnreadNotifications(notificationSource, entity))+ return true;+ return false;+ },+ }+ );++ registerHotkey({+ hotkey: ['e'],+ scopeId: entityHotkeyScope,+ description: 'Mark done',+ condition: () =>+ isViewingList() &&+ actionRegistry.isActionEnabled('mark_as_done', plainSelectedEntities()),+ keyDownHandler: () => {+ const entitiesForAction = getEntitiesForAction();+ if (entitiesForAction.entities.length === 0) {+ return false;}- const next =- maxIndex < entityList.length - 1 ? entityList[maxIndex + 1] : null;+ actionRegistry.execute(+ 'mark_as_done',+ entitiesForAction.entities.map(({ entity }) => entity)+ );++ return true;+ },+ displayPriority: 10,+ tags: [HotkeyTags.SelectionModification],+ });++ // ---------------------------------------------------------------------------+ // DELETE+ // ---------------------------------------------------------------------------+ actionRegistry.register(+ 'delete',+ async (entitiesToDelete) => {+ const prev = selectedEntity();+ const next = getNextEntity(entitiesToDelete);try {openBulkEditModal({view: 'delete',entities: entitiesToDelete,onFinish: () => {- setViewDataStore(selectedView(), 'selectedEntities', []);- if (next !== null) {- setViewDataStore(selectedView(), 'selectedEntity', next);- setViewDataStore(selectedView(), 'highlightedId', next.id);- const nextIndex = entities()?.findIndex(- ({ id }) => id === next.id- );- if (nextIndex !== undefined && nextIndex > -1) {- virtualizerHandle()?.scrollToIndex(nextIndex, {- align: 'nearest',- });- waitForFrames(2).then(() => {- const elem = getEntityElAtIndex(nextIndex);- if (elem instanceof HTMLElement) {- elem.focus();- return;- // cooked state (no focus returned)- }- });- } else {- const firstIndex = virtualizerHandle()?.findStartIndex();- if (!firstIndex) return;- const elem = getEntityElAtIndex(firstIndex);- if (elem instanceof HTMLElement) elem.focus();- // cooked state (no focus returned)- }- }+ afterEntityAction(next, true);+ },+ onCancel: () => {+ afterEntityAction(prev);},});} catch (err) {@@ -305,14 +378,208 @@ export function createNavigationEntityListShortcut({return { success: true };},{- disabled: (entity) => {- if (entity.type === 'channel' || entity.type === 'email') return true;- if (entity.ownerId !== userId()) return true;+ testEnabled: (entity) => {+ // can't delete these bad boys yet.+ if (entity.type === 'channel' || entity.type === 'email') return false;+ // only delete what you own.+ return entity.ownerId === userId();+ },+ // TODO (seamus): fix the handler from the modal so that we can delete+ // some of the items. Then switch this to some.+ enabledMode: 'every',+ }+ );++ registerHotkey({+ hotkey: ['delete', 'backspace'],+ scopeId: splitHotkeyScope,+ description: () =>+ viewData().selectedEntities.length > 1 ? 'Delete items' : 'Delete item',+ condition: () =>+ isViewingList() &&+ actionRegistry.isActionEnabled('delete', plainSelectedEntities()),+ keyDownHandler: () => {+ const entitiesForAction = getEntitiesForAction();+ if (entitiesForAction.entities.length === 0) {return false;+ }+ actionRegistry.execute(+ 'delete',+ entitiesForAction.entities.map(({ entity }) => entity)+ );+ return true;+ },+ tags: [HotkeyTags.SelectionModification],+ displayPriority: 10,+ });++ createEffect(() => {+ const ref = entityListRef();+ if (!ref) return;++ attachEntityHotkeys(ref);+ });++ // ---------------------------------------------------------------------------+ // RENAME+ // ---------------------------------------------------------------------------+ actionRegistry.register(+ 'rename',+ async (entitiesToRename) => {+ const prev = selectedEntity();+ const next = getNextEntity(entitiesToRename);+ try {+ openBulkEditModal({+ view: 'rename',+ entities: entitiesToRename,+ onFinish: () => {+ afterEntityAction(next);+ },+ onCancel: () => {+ afterEntityAction(prev);+ },+ });+ } catch (err) {+ console.error('Failed to open bulk rename modal', err);+ }+ return { success: true };+ },+ {+ testEnabled: (entity) => {+ // can't rename these bad boys yet.+ if (entity.type === 'channel' || entity.type === 'email') return false;+ // only rename what you own.+ return entity.ownerId === userId();},});+ registerHotkey({+ scopeId: splitHotkeyScope,+ description: () =>+ viewData().selectedEntities.length > 1 ? 'Rename items' : 'Rename item',+ condition: () =>+ isViewingList() &&+ actionRegistry.isActionEnabled('rename', plainSelectedEntities()),+ keyDownHandler: () => {+ const entitiesForAction = getEntitiesForAction();+ if (entitiesForAction.entities.length === 0) {+ return false;+ }+ actionRegistry.execute(+ 'rename',+ entitiesForAction.entities.map(({ entity }) => entity)+ );+ return true;+ },+ tags: [HotkeyTags.SelectionModification],+ displayPriority: 10,+ });++ // ---------------------------------------------------------------------------+ // COPY+ // ---------------------------------------------------------------------------+ const bulkCopyMutation = createBulkCopyDssEntityMutation();+ actionRegistry.register(+ 'copy',+ async (entitiesToCopy) => {+ try {+ await bulkCopyMutation.mutateAsync({+ entities: entitiesToCopy,+ name: (name) => name,+ });+ } catch (_) {}+ return { success: true };+ },+ {+ testEnabled: (entity) => {+ if (entity.type === 'channel' || entity.type === 'email') return false;+ return true;+ },+ }+ );++ registerHotkey({+ scopeId: splitHotkeyScope,+ description: () =>+ viewData().selectedEntities.length > 1 ? 'Copy items' : 'Copy item',+ condition: () =>+ isViewingList() &&+ actionRegistry.isActionEnabled('copy', plainSelectedEntities()),+ keyDownHandler: () => {+ const entitiesForAction = getEntitiesForAction();+ if (entitiesForAction.entities.length === 0) {+ return false;+ }+ actionRegistry.execute(+ 'copy',+ entitiesForAction.entities.map(({ entity }) => entity)+ );+ return true;+ },+ tags: [HotkeyTags.SelectionModification],+ displayPriority: 10,+ });++ // ---------------------------------------------------------------------------+ // MOVE TO PROJECT+ // ---------------------------------------------------------------------------+ actionRegistry.register(+ 'move_to_project',+ async (entitiesToMove) => {+ const prev = selectedEntity();+ const next = getNextEntity(entitiesToMove);+ try {+ openBulkEditModal({+ view: 'moveToProject',+ entities: entitiesToMove,+ onFinish: () => {+ afterEntityAction(next, true);+ },+ onCancel: () => {+ afterEntityAction(prev);+ },+ });+ } catch (err) {+ console.error('Failed to open bulk move modal', err);+ }+ return { success: true };+ },+ {+ testEnabled: (entity) => {+ if (entity.type === 'channel' || entity.type === 'email') return false;+ return true;+ },+ }+ );++ registerHotkey({+ scopeId: splitHotkeyScope,+ description: () =>+ viewData().selectedEntities.length > 1+ ? 'Move items to project'+ : 'Move item to project',+ condition: () =>+ isViewingList() &&+ actionRegistry.isActionEnabled(+ 'move_to_project',+ plainSelectedEntities()+ ),+ keyDownHandler: () => {+ const entitiesForAction = getEntitiesForAction();+ if (entitiesForAction.entities.length === 0) {+ return false;+ }+ actionRegistry.execute(+ 'move_to_project',+ entitiesForAction.entities.map(({ entity }) => entity)+ );+ return true;+ },+ tags: [HotkeyTags.SelectionModification],+ displayPriority: 10,+ });+const openEntity = (entity: EntityData) => {const { type, id } = entity;if (type === 'document') {@@ -901,7 +1168,6 @@ export function createNavigationEntityListShortcut({hide: true,});- const [attachEntityHotkeys, entityHotkeyScope] = useHotkeyDOMScope('entity');registerHotkey({hotkey: ['enter'],scopeId: entityHotkeyScope,@@ -969,39 +1235,9 @@ export function createNavigationEntityListShortcut({},displayPriority: 4,});- registerHotkey({- hotkey: ['e'],- scopeId: entityHotkeyScope,- description: 'Mark done',- condition: () =>- isViewingList() &&- !actionRegistry.isActionDisabled('mark_as_done', plainSelectedEntities()),- keyDownHandler: () => {- const entitiesForAction = getEntitiesForAction();- if (entitiesForAction.entities.length === 0) {- return false;- }-- if (isEntityLastItem()) {- navigateThroughList({ axis: 'start', mode: 'step' });- } else {- navigateThroughList({ axis: 'end', mode: 'step' });- }-- actionRegistry.execute(- 'mark_as_done',- entitiesForAction.entities.map(({ entity }) => entity)- );-- setViewDataStore(selectedView(), 'selectedEntities', []);- return true;- },- displayPriority: 10,- tags: [HotkeyTags.SelectionModification],- });registerHotkey({hotkey: ['x'],- scopeId: entityHotkeyScope,+ scopeId: splitHotkeyScope,description: 'Toggle select item',condition: isViewingList,keyDownHandler: () => {@@ -1023,35 +1259,6 @@ export function createNavigationEntityListShortcut({return length > 1;},});- registerHotkey({- hotkey: ['delete', 'backspace'],- scopeId: splitHotkeyScope,- description: () =>- viewData().selectedEntities.length > 1 ? 'Delete items' : 'Delete item',- condition: () =>- isViewingList() &&- !actionRegistry.isActionDisabled('delete', plainSelectedEntities()),- keyDownHandler: () => {- const entitiesForAction = getEntitiesForAction();- if (entitiesForAction.entities.length === 0) {- return false;- }- actionRegistry.execute(- 'delete',- entitiesForAction.entities.map(({ entity }) => entity)- );- return true;- },- tags: [HotkeyTags.SelectionModification],- displayPriority: 10,- });-- createEffect(() => {- const ref = entityListRef();- if (!ref) return;-- attachEntityHotkeys(ref);- });}const useAllViews = ({diff --git a/js/app/packages/app/component/UnifiedEntityActions.tsx b/js/app/packages/app/component/UnifiedEntityActions.tsxindex 7cb8468851..a6dc3a06ca 100644--- a/js/app/packages/app/component/UnifiedEntityActions.tsx+++ b/js/app/packages/app/component/UnifiedEntityActions.tsx@@ -1,4 +1,5 @@-import type { EntityData } from '@macro-entity';+import { type EntityData, isEntityData } from '@macro-entity';+import type { Component } from 'solid-js';export type EntityActionType =| 'mark_as_done'@@ -18,9 +19,22 @@ export type EntityActionHandler = () => Promise<EntityActionResult>;export type EntityActionConfig = {+ /** Optional label for the action */label?: string;- icon?: string;- disabled?: (entity: EntityData) => boolean;+ /** Optional icon component */+ icon?: Component;+ /**+ * Optional test to run over an entity to see if the action can be performed+ * on that entity.+ */+ testEnabled?: (entity: EntityData) => boolean;+ /**+ * Enabled mode for bulk version of action. If 'every' then all entities must pass+ * for the action to register as enabled. If 'some' then the action can be+ * enabled if a single entity passes the test. Only meaningful if testEnabled+ * is also provided. Default is 'every'+ */+ enabledMode?: 'some' | 'every';};export type EntityActionRegistry = {@@ -35,7 +49,7 @@ export type EntityActionRegistry = {type: EntityActionType,entities: EntityData | EntityData[]) => Promise<EntityActionResult>;- isActionDisabled: (+ isActionEnabled: (type: EntityActionType,entities: EntityData | EntityData[]) => boolean;@@ -43,9 +57,6 @@ export type EntityActionRegistry = {has: (action: EntityActionType) => boolean;};-/**- * Creates a registry for entity actions that supports both individual and bulk operations- */export function createEntityActionRegistry(): EntityActionRegistry {const actions = new Map<EntityActionType, EntityActionHandler>();const configs = new Map<EntityActionType, EntityActionConfig>();@@ -94,16 +105,22 @@ export function createEntityActionRegistry(): EntityActionRegistry {return { success: true };};- const isActionDisabled = (+ const isActionEnabled = (type: EntityActionType,entities: EntityData | EntityData[]): boolean => {- const config = configs.get(type);- if (!config) return false;+ const { testEnabled, enabledMode } = configs.get(type) ?? {};+ if (!testEnabled) return true;if (Array.isArray(entities)) {- return entities.some((e) => config.disabled?.(e));+ if (enabledMode === 'some') {+ return entities.some(testEnabled);+ } else {+ return entities.every(testEnabled);+ }+ } else if (isEntityData(entities)) {+ return testEnabled(entities);}- return config.disabled?.(entities) ?? false;+ return false;};const getAvailableActions = (): EntityActionType[] => {@@ -115,7 +132,7 @@ export function createEntityActionRegistry(): EntityActionRegistry {getHandler,getConfig,execute,- isActionDisabled,+ isActionEnabled: isActionEnabled,getAvailableActions,has: (action) => actions.has(action),};diff --git a/js/app/packages/app/component/UnifiedListView.tsx b/js/app/packages/app/component/UnifiedListView.tsxindex 579c6af61b..aa8190125e 100644--- a/js/app/packages/app/component/UnifiedListView.tsx+++ b/js/app/packages/app/component/UnifiedListView.tsx@@ -1009,12 +1009,24 @@ export function UnifiedListView(props: UnifiedListViewProps) {});let lastClickedEntityId = -1;++ // reset last clicked on view change.createEffect(on(view, () => {lastClickedEntityId = -1;}));+ // reset last clicked on reset multi-selection.+ createEffect(() => {+ if (+ unifiedListContext.viewsDataStore[selectedView()].selectedEntities+ .length === 0+ ) {+ lastClickedEntityId = -1;+ }+ });+return (<><Show when={!props.hideToolbar}>diff --git a/js/app/packages/app/component/bulk-edit-entity/BulkDeleteView.tsx b/js/app/packages/app/component/bulk-edit-entity/BulkDeleteView.tsxindex cca1a5319c..022f0825b2 100644--- a/js/app/packages/app/component/bulk-edit-entity/BulkDeleteView.tsx+++ b/js/app/packages/app/component/bulk-edit-entity/BulkDeleteView.tsx@@ -16,7 +16,6 @@ export const BulkDeleteView = (props: {const handleDelete = async () => {try {await bulkDelete.mutateAsync(props.entities);-const context = konsoleContextInformation();const clearSelection = context.clearSelection as (() => void) | undefined;clearSelection?.();diff --git a/js/app/packages/app/component/bulk-edit-entity/BulkEditEntityModal.tsx b/js/app/packages/app/component/bulk-edit-entity/BulkEditEntityModal.tsxindex e2cb15c45d..0b2ccce84b 100644--- a/js/app/packages/app/component/bulk-edit-entity/BulkEditEntityModal.tsx+++ b/js/app/packages/app/component/bulk-edit-entity/BulkEditEntityModal.tsx@@ -9,10 +9,11 @@ import {Show,} from 'solid-js';import { BulkDeleteView } from './BulkDeleteView';+import { BulkMoveToProjectView } from './BulkMoveToProjectView';import { BulkRenameEntitiesView } from './BulkRenameEntitiesView';export const BulkEditEntityModalTitle = (props: { title: string }) => {- return <h2 class="text-xl mb-3">{props.title}</h2>;+ return <h2 class="text-xl mb-4">{props.title}</h2>;};export const BulkEditEntityModalActionFooter = (props: {@@ -22,16 +23,19 @@ export const BulkEditEntityModalActionFooter = (props: {isDisabled?: boolean;}) => {return (- <div class="flex justify-end mt-2 tex-sm pt-2">- <button class="py-1 px-3 font-mono text-sm" onClick={props.onCancel}>+ <div class="flex w-full justify-end items-stretch tex-sm gap-1">+ <button+ class="py-1 px-3 text-sm border-edge-muted border bg-panel"+ onClick={props.onCancel}+ >Cancel</button><button- class={`uppercase py-1 px-3 font-mono text-sm ${- props.isDisabled- ? 'bg-edge/20 text-ink-placeholder cursor-not-allowed'- : 'bg-accent text-menu'- }`}+ class="uppercase py-1 px-3 text-sm font-semibold border"+ classList={{+ 'text-accent bg-accent/10 border-accent/20': !props.isDisabled,+ 'text-ink-disabled bg-egde/10 border-edge-muted': props.isDisabled,+ }}onClick={props.onConfirm}disabled={props.isDisabled}>@@ -47,6 +51,7 @@ const BulkEditEntityModalContent = (props: {view: 'rename' | 'moveToProject' | 'delete' | null;entities: EntityData[];onFinish?: () => void;+ onCancel?: () => void;}) => {const handleFinish = () => {props.setIsOpen(false);@@ -54,15 +59,25 @@ const BulkEditEntityModalContent = (props: {};const handleCancel = () => {props.setIsOpen(false);+ props.onCancel?.();};return (- <Dialog open={props.isOpen()} onOpenChange={props.setIsOpen} modal={true}>+ <Dialog+ open={props.isOpen()}+ onOpenChange={(open) => {+ if (!open) {+ handleCancel();+ }+ props.setIsOpen(open);+ }}+ modal={true}+ ><Dialog.Portal><Dialog.Overlay class="fixed inset-0 z-modal bg-modal-overlay" />- <div class="fixed inset-0 z-modal w-screen h-screen flex items-center justify-center">- <Dialog.Content class="flex items-center justify-center">- <div class="pointer-events-auto max-w-xl bg-menu border border-edge w-lg h-fit p-2">+ <div class="fixed inset-0 z-modal">+ <Dialog.Content>+ <div class="pointer-events-auto max-w-xl bg-menu border border-edge-muted w-lg h-fit p-2 mt-[25vh] mx-auto"><div class="w-full my-1"><Show when={props.view === 'rename'}><BulkRenameEntitiesView@@ -72,12 +87,11 @@ const BulkEditEntityModalContent = (props: {/></Show><Show when={props.view === 'moveToProject'}>- {/* <MoveToProjectView */}- {/* entity={props.entity!} */}- {/* onFinish={handleFinish} */}- {/* onCancel={handleCancel} */}- {/* /> */}- <div />+ <BulkMoveToProjectView+ entities={props.entities}+ onFinish={handleFinish}+ onCancel={handleCancel}+ /></Show><Show when={props.view === 'delete'}><BulkDeleteView@@ -117,19 +131,19 @@ export const BulkEditEntityModal: ParentComponent<BulkEditEntityModalProps> = ();};-// Global modal stateconst [globalModalProps, setGlobalModalProps] = createSignal<{view: 'rename' | 'moveToProject' | 'delete';entities: EntityData[];onFinish?: () => void;+ onCancel?: () => void;} | null>(null);const [modalOpen, setModalOpen] = createControlledOpenSignal();-// Global modal open functionexport const openBulkEditModal = (props: {view: 'rename' | 'moveToProject' | 'delete';entities: EntityData[];onFinish?: () => void;+ onCancel?: () => void;}) => {setModalOpen(true);setGlobalModalProps(props);@@ -146,6 +160,14 @@ export const GlobalBulkEditEntityModal = () => {}};+ const handleCancel = () => {+ const props = globalModalProps();+ setGlobalModalProps(null);+ if (props?.onCancel) {+ props.onCancel();+ }+ };+return (<Show when={modalProps()}>{(props) => (@@ -155,6 +177,7 @@ export const GlobalBulkEditEntityModal = () => {view={props().view}entities={props().entities}onFinish={handleFinish}+ onCancel={handleCancel}/>)}</Show>diff --git a/js/app/packages/app/component/bulk-edit-entity/BulkMoveToProjectView.tsx b/js/app/packages/app/component/bulk-edit-entity/BulkMoveToProjectView.tsxnew file mode 100644index 0000000000..fe26d6b2fc--- /dev/null+++ b/js/app/packages/app/component/bulk-edit-entity/BulkMoveToProjectView.tsx@@ -0,0 +1,442 @@+import { EntityIcon } from '@core/component/EntityIcon';+import type { Project } from '@service-storage/generated/schemas';+import { useProjects } from '@service-storage/projects';+import { registerHotkey, useHotkeyDOMScope } from 'core/hotkey/hotkeys';+import { createMemo, createSignal, For, onMount, Show } from 'solid-js';+import { createBulkMoveToProjectDssEntityMutation } from '../../../macro-entity/src/queries/dss';+import type { EntityData } from '../../../macro-entity/src/types/entity';+import { scrollToKeepGap } from '../SoupContext';+import {+ BulkEditEntityModalActionFooter,+ BulkEditEntityModalTitle,+} from './BulkEditEntityModal';++type ProjectWithDepth = Project & { depth?: number; path?: string };++export const BulkMoveToProjectView = (props: {+ entities: EntityData[];+ onFinish: () => void;+ onCancel: () => void;+}) => {+ let listRef!: HTMLDivElement;+ const bulkMoveToProjectMutation = createBulkMoveToProjectDssEntityMutation();+ const projects = useProjects();+ const [searchQuery, setSearchQuery] = createSignal('');+ const [selectedProject, setSelectedProject] =+ createSignal<ProjectWithDepth | null>(null);+ const [expandedProjects, setExpandedProjects] = createSignal<{+ [key: string]: boolean;+ }>({});+ const [focusedIndex, setFocusedIndex] = createSignal(-1);+ const [attachHotkeys, moveToProjectHotkeyScopeId] = useHotkeyDOMScope(+ 'bulk-move-to-project',+ true+ );+ let rootScopeId!: HTMLDivElement;++ onMount(() => {+ attachHotkeys(rootScopeId);+ registerHotkey({+ hotkey: ['arrowdown'],+ scopeId: moveToProjectHotkeyScopeId,+ description: 'Down',+ keyDownHandler: () => {+ const items = flattenedProjects().items;+ if (items.length === 0) return false;++ const currentIndex = focusedIndex();+ const nextIndex =+ currentIndex === -1+ ? 0+ : Math.min(currentIndex + 1, items.length - 1);+ setFocusedIndex(nextIndex);++ // Update selection+ const nextProject = items[nextIndex];+ if (nextProject) {+ setSelectedProject(nextProject);+ scrollToKeepGap({+ container: listRef,+ target: listRef.querySelector('.focused') as HTMLElement,+ align: 'bottom',+ });+ }+ return true;+ },+ runWithInputFocused: true,+ });+ registerHotkey({+ hotkey: ['arrowup'],+ scopeId: moveToProjectHotkeyScopeId,+ description: 'Up',+ keyDownHandler: () => {+ const items = flattenedProjects().items;+ if (items.length === 0) return false;++ const currentIndex = focusedIndex();+ const prevIndex =+ currentIndex === -1+ ? items.length - 1+ : Math.max(currentIndex - 1, 0);+ setFocusedIndex(prevIndex);++ // Update selection+ const prevProject = items[prevIndex];+ if (prevProject) {+ setSelectedProject(prevProject);+ scrollToKeepGap({+ container: listRef,+ target: listRef.querySelector('.focused') as HTMLElement,+ align: 'top',+ });+ }+ return true;+ },+ runWithInputFocused: true,+ });+ registerHotkey({+ hotkey: ['arrowright'],+ scopeId: moveToProjectHotkeyScopeId,+ description: 'Expand',+ keyDownHandler: () => {+ const items = flattenedProjects().items;+ const currentIndex = focusedIndex();+ if (currentIndex === -1) return false;+ const currentProject = items[currentIndex];++ if (currentProject && !searchQuery()) {+ const tree = projectTree();+ const hasChildren =+ tree.itemMap[currentProject.id]?.children &&+ tree.itemMap[currentProject.id].children!.length > 0;+ const isExpanded = expandedProjects()[currentProject.id];++ if (hasChildren && !isExpanded) {+ // Expand current project+ setExpandedProjects((prev) => ({+ ...prev,+ [currentProject.id]: true,+ }));+ return true;+ } else if (hasChildren && isExpanded) {+ // Move to first child+ const children = tree.itemMap[currentProject.id].children!;+ const firstChild = children[0];+ const firstChildIndex = items.findIndex(+ (item: Project) => item.id === firstChild.id+ );+ if (firstChildIndex !== -1) {+ setFocusedIndex(firstChildIndex);+ setSelectedProject(firstChild);+ scrollToKeepGap({+ container: listRef,+ target: listRef.querySelector('.focused') as HTMLElement,+ align: 'bottom',+ });+ }+ return true;+ }+ }+ return false;+ },+ runWithInputFocused: true,+ });+ registerHotkey({+ hotkey: ['arrowleft'],+ scopeId: moveToProjectHotkeyScopeId,+ description: 'Collapse',+ keyDownHandler: () => {+ const items = flattenedProjects().items;+ const currentIndex = focusedIndex();+ if (currentIndex === -1) return false;+ const currentProject = items[currentIndex];++ if (currentProject && !searchQuery()) {+ const isExpanded = expandedProjects()[currentProject.id];++ if (isExpanded) {+ // Collapse current project+ setExpandedProjects((prev) => ({+ ...prev,+ [currentProject.id]: false,+ }));+ return true;+ } else {+ // Move to parent+ const parentId = currentProject.parentId;+ if (parentId) {+ const parentIndex = items.findIndex(+ (item: Project) => item.id === parentId+ );+ if (parentIndex !== -1) {+ setFocusedIndex(parentIndex);+ setSelectedProject(items[parentIndex]);+ scrollToKeepGap({+ container: listRef,+ target: listRef.querySelector('.focused') as HTMLElement,+ align: 'top',+ });+ }+ }+ return true;+ }+ }+ return false;+ },+ runWithInputFocused: true,+ });+ });++ const projectTree = createMemo(() => {+ const allProjects = projects();+ const itemMap: Record<string, Project & { children?: Project[] }> = {};+ const rootItems: Project[] = [];+ // Build project tree structure++ // First pass: create item map and identify root items+ for (const project of allProjects) {+ itemMap[project.id] = { ...project, children: [] };+ if (!project.parentId) {+ rootItems.push(project);+ } else {+ // This will be processed in second pass+ const parentId = project.parentId;+ if (!itemMap[parentId]) {+ itemMap[parentId] = { ...project, children: [] };+ }+ }+ }++ // Second pass: build parent-child relationships+ for (const project of allProjects) {+ if (project.parentId && itemMap[project.parentId]) {+ itemMap[project.parentId].children!.push(project);+ }+ }++ return { itemMap, rootItems };+ });++ const getProjectPath = (projectId: string): string => {+ const tree = projectTree();+ const path: string[] = [];+ let currentId: string | undefined = projectId;+ while (currentId) {+ const project: Project & { children?: Project[] } =+ tree.itemMap[currentId];+ if (project) {+ path.unshift(project.name);+ currentId = project.parentId || undefined;+ } else {+ break;+ }+ }+ return path.join(' / ');+ };++ const [flattenedProjects, setFlattenedProjects] = createSignal<{+ items: ProjectWithDepth[];+ }>({ items: [] });++ const updateFlattenedProjects = () => {+ const query = searchQuery().toLowerCase();++ if (query) {+ // Search mode: filter projects that match the query+ const searchResults = projects()+ .filter((project: Project) =>+ project.name.toLowerCase().includes(query)+ )+ .map(+ (item: Project): ProjectWithDepth => ({+ ...item,+ depth: 0,+ path: getProjectPath(item.id),+ })+ );+ setFlattenedProjects({ items: searchResults });+ } else {+ // Tree mode: flatten the hierarchy respecting expanded state+ const result: ProjectWithDepth[] = [];+ const expanded = expandedProjects();+ const tree = projectTree();++ const processItems = (+ items: Project[],+ depth: number = 0,+ path: string = ''+ ) => {+ for (const item of items.sort((a, b) => a.name.localeCompare(b.name))) {+ const currentPath = path ? `${path} / ${item.name}` : item.name;+ result.push({ ...item, depth, path: currentPath });++ if (expanded[item.id] && tree.itemMap[item.id]?.children) {+ const childrenAsTreeItems = tree.itemMap[item.id].children!;+ processItems(childrenAsTreeItems, depth + 1, currentPath);+ }+ }+ };++ processItems(tree.rootItems);+ setFlattenedProjects({ items: result });+ }++ // Reset focus when items change+ const items = flattenedProjects().items;+ if (items.length > 0 && focusedIndex() === -1) {+ setFocusedIndex(0);+ setSelectedProject(items[0]);+ } else if (focusedIndex() >= items.length) {+ const newIndex = Math.max(0, items.length - 1);+ setFocusedIndex(newIndex);+ setSelectedProject(items[newIndex] || null);+ }+ };++ // Update flattened projects when dependencies change+ createMemo(() => {+ updateFlattenedProjects();+ });++ const items = () => flattenedProjects().items;++ const currentSelected = () => selectedProject();++ const currentIndex = () => {+ const selected = currentSelected();+ return selected ? items().findIndex((item) => item.id === selected.id) : -1;+ };++ // Keep focused index in sync with current selection+ createMemo(() => {+ const index = currentIndex();+ if (index !== -1 && index !== focusedIndex()) {+ setFocusedIndex(index);+ }+ });++ const currentFocus = () => {+ const index = focusedIndex();+ return index >= 0 && index < items().length ? items()[index] : null;+ };++ // Auto-select focused item+ createMemo(() => {+ const focused = currentFocus();+ if (focused && focused.id !== currentSelected()?.id) {+ setSelectedProject(focused);+ }+ });++ const toggleExpanded = (projectId: string) => {+ setExpandedProjects((prev) => ({+ ...prev,+ [projectId]: !prev[projectId],+ }));+ };++ const finishEditing = async () => {+ const selected = selectedProject();+ if (selected) {+ try {+ const projectId = selected.id;+ const projectName = selected.name;++ await bulkMoveToProjectMutation.mutateAsync({+ entities: props.entities.map((entity) => ({+ ...entity,+ name: entity.name || entity.id,+ })),+ project: { id: projectId, name: projectName },+ });++ props.onFinish();+ } catch (error) {+ console.error('Failed to move entities to project:', error);+ }+ }+ };++ const entityCount = () => props.entities.length;+ const entityText = () => (entityCount() === 1 ? 'item' : 'items');++ return (+ <div ref={rootScopeId}>+ <BulkEditEntityModalTitle+ title={`Move ${entityCount()} ${entityText()} to project`}+ />+ <div class="mb-4">+ <input+ type="text"+ placeholder="Search projects..."+ value={searchQuery()}+ onInput={(e) => setSearchQuery(e.target.value)}+ class="w-full px-3 py-2 border border-edge bg-menu text-ink focus:outline-none focus:border-accent"+ />+ </div>+ <div class="h-64 overflow-auto border border-edge" ref={listRef}>+ <For each={items()}>+ {(project, index) => {+ const isSelected = () => currentSelected()?.id === project.id;+ const isFocused = () => focusedIndex() === index();+ const isExpanded = () => expandedProjects()[project.id];+ const hasChildren = () => {+ const tree = projectTree();+ return (+ tree.itemMap[project.id]?.children &&+ tree.itemMap[project.id].children!.length > 0+ );+ };++ return (+ <div+ class={`flex items-center px-2 py-1 cursor-pointer hover:bg-accent/10 ${+ isFocused() ? 'focused bg-accent/20' : ''+ } ${isSelected() ? 'bg-accent/10' : ''}`}+ style={{+ 'padding-left': `${(project.depth || 0) * 16 + 8}px`,+ }}+ onClick={() => {+ setSelectedProject(project);+ setFocusedIndex(index());+ scrollToKeepGap({+ container: listRef,+ target: listRef.querySelector('.focused') as HTMLElement,+ align: 'top',+ });+ }}+ >+ <div+ class={`mr-2 w-4 h-4 flex items-center justify-center text-xs ${+ hasChildren() ? 'cursor-pointer' : 'opacity-20'+ }`}+ onClick={(e) => {+ e.stopPropagation();+ if (hasChildren()) {+ toggleExpanded(project.id);+ }+ }}+ >+ {hasChildren() ? (isExpanded() ? '▼' : '▶') : ''}+ </div>+ <div class="mr-2">{<EntityIcon targetType="project" />}</div>+ <div class="flex-1 text-sm truncate">{project.name}</div>+ <Show when={searchQuery()}>+ <div class="text-xs text-ink-placeholder ml-2 truncate max-w-48">+ {getProjectPath(project.id)}+ </div>+ </Show>+ </div>+ );+ }}+ </For>+ </div>+ <BulkEditEntityModalActionFooter+ onCancel={props.onCancel}+ onConfirm={finishEditing}+ confirmText="Move"+ isDisabled={!selectedProject()}+ />+ </div>+ );+};diff --git a/js/app/packages/app/component/bulk-edit-entity/BulkRenameEntitiesView.tsx b/js/app/packages/app/component/bulk-edit-entity/BulkRenameEntitiesView.tsxindex 6a126d7fe9..b39a6fc1ff 100644--- a/js/app/packages/app/component/bulk-edit-entity/BulkRenameEntitiesView.tsx+++ b/js/app/packages/app/component/bulk-edit-entity/BulkRenameEntitiesView.tsx@@ -1,28 +1,41 @@-import type { EntityData } from '@macro-entity';-import { createSignal, onMount } from 'solid-js';+import { SegmentedControl } from '@core/component/FormControls/SegmentControls';+import { createMemo, createSignal, onMount, Show } from 'solid-js';import { createBulkRenameDssEntityMutation } from '../../../macro-entity/src/queries/dss';+import type { EntityData } from '../../../macro-entity/src/types/entity';import {BulkEditEntityModalActionFooter,BulkEditEntityModalTitle,} from './BulkEditEntityModal';+type RenameMode = 'total' | 'prepend' | 'append' | 'replace';+export const BulkRenameEntitiesView = (props: {entities: EntityData[];onFinish: () => void;onCancel: () => void;}) => {const renameMutation = createBulkRenameDssEntityMutation();+let inputRef: HTMLInputElement | undefined;- const commonInitName = () => {- const noDupes = new Set(props.entities.map((e) => e.name.trim()));+ const primaryEntity = () => props.entities[0];+ const multi = () => props.entities.length > 1;- if (noDupes.size > 1) return '';+ const [editValue, setEditValue] = createSignal(primaryEntity()?.name ?? '');+ const [replaceFind, setReplaceFind] = createSignal('');+ const [replaceWith, setReplaceWith] = createSignal('');- return Array.from(noDupes)[0] ?? '';- };+ // Mode defaults+ const [mode, setMode] = createSignal<RenameMode>(+ multi() ? 'append' : 'total'+ );- const [editValue, setEditValue] = createSignal(commonInitName());+ const modeOptions = [+ { value: 'prepend', label: 'Prepend' },+ { value: 'append', label: 'Append' },+ { value: 'replace', label: 'Replace' },+ { value: 'total', label: 'Total' },+ ];const handleKeyDown = (e: KeyboardEvent) => {if (e.key === 'Enter') {@@ -34,29 +47,76 @@ export const BulkRenameEntitiesView = (props: {}};+ const previewName = createMemo(() => {+ const base = primaryEntity()?.name ?? '';+ const v = editValue().trim();++ switch (mode()) {+ case 'total':+ return v;++ case 'prepend':+ return v + base;++ case 'append':+ return base + v;++ case 'replace':+ if (!replaceFind()) return base;+ return base.replaceAll(replaceFind(), replaceWith());++ default:+ return base;+ }+ });+const finishEditing = async () => {- const newValue = editValue().trim();-- if (newValue) {- // Todo - Bulk rename- await renameMutation.mutateAsync({- entities: props.entities,- newName: newValue,- });+ const newValue = editValue();++ let renameFn: (old?: string) => string = () => newValue;+ switch (mode()) {+ case 'prepend':+ renameFn = (old: string) => newValue + old;+ break;+ case 'append':+ renameFn = (old: string) => old + newValue;+ break;+ case 'replace':+ renameFn = (old: string) =>+ old.replaceAll(replaceFind(), replaceWith());+ break;+ default:}+ await renameMutation.mutateAsync({+ entities: props.entities,+ name: renameFn,+ });+props.onFinish();};return (<div class="w-full"><BulkEditEntityModalTitle title="Rename" />- <div class="w-full focus-within:bracket-offset-2">++ <Show when={multi()}>+ <div class="mb-3">+ <SegmentedControl+ label="Mode"+ value={mode()}+ list={modeOptions}+ onChange={(value) => setMode(value as RenameMode)}+ size="SM"+ />+ </div>+ </Show>++ <div class="w-full focus-within:bracket-offset-2 mb-3"><inputref={(el) => {inputRef = el;onMount(() => {- // it needs to focus on next task, no idea whysetTimeout(() => {inputRef?.focus();inputRef?.select();@@ -66,11 +126,41 @@ export const BulkRenameEntitiesView = (props: {value={editValue()}onInput={(e) => setEditValue(e.currentTarget.value)}onKeyDown={handleKeyDown}- class="w-full p-2 text-sm border-1 border-edge/20 bg-menu text-ink placeholder:text-ink-placeholder focus:outline-none selection:bg-ink selection:text-panel"- placeholder="Enter title..."+ class="w-full p-2 text-sm border-1 border-edge/20 bg-menu text-ink+ placeholder:text-ink-placeholder focus:outline-none+ selection:bg-ink selection:text-panel"+ placeholder="Enter new text..."/></div>+ {/* Extra inputs for replace mode */}+ <Show when={multi() && mode() === 'replace'}>+ <div class="flex flex-col gap-2 mb-4">+ <input+ class="p-1 text-sm border border-edge/20 bg-menu"+ placeholder="Find…"+ value={replaceFind()}+ onInput={(e) => setReplaceFind(e.currentTarget.value)}+ />+ <input+ class="p-1 text-sm border border-edge/20 bg-menu"+ placeholder="Replace with…"+ value={replaceWith()}+ onInput={(e) => setReplaceWith(e.currentTarget.value)}+ />+ </div>+ </Show>++ {/* Preview */}+ <Show when={multi() && mode() !== 'total'}>+ <div class="text-xs opacity-70 mb-3">+ Preview (first item):+ <div class="mt-1 p-2 bg-surface border border-edge/10 rounded">+ {previewName()}+ </div>+ </div>+ </Show>+<BulkEditEntityModalActionFooteronCancel={props.onCancel}onConfirm={finishEditing}diff --git a/js/app/packages/app/component/bulk-edit-entity/MoveToProjectView.tsx b/js/app/packages/app/component/bulk-edit-entity/MoveToProjectView.tsxdeleted file mode 100644index ad46316139..0000000000--- a/js/app/packages/app/component/bulk-edit-entity/MoveToProjectView.tsx+++ /dev/null@@ -1,555 +0,0 @@-import { scrollToKeepGap } from '@app/component/SoupContext';-import { BozzyBracket } from '@core/component/BozzyBracket';-import {- CustomEntityIcon,- EntityIcon,- getIconConfig,-} from '@core/component/EntityIcon';-import { ExplorerSpacer } from '@core/component/FileList/ExplorerSpacer';-import { registerHotkey, useHotkeyDOMScope } from '@core/hotkey/hotkeys';-import Fragment from '@core/util/Fragment';-import CaretRight from '@icon/regular/caret-right.svg';-import type { EntityData } from '@macro-entity';-import ArrowRight from '@phosphor-icons/core/regular/arrow-right.svg?component-solid';-import type { Project } from '@service-storage/generated/schemas';-import { useProjects } from '@service-storage/projects';-import {- createEffect,- createMemo,- createSignal,- onMount,- Show,-} from 'solid-js';-import { createStore, reconcile } from 'solid-js/store';-import { Dynamic } from 'solid-js/web';-import { VList } from 'virtua/solid';-import { createMoveToProjectDssEntityMutation } from '../../../macro-entity/src/queries/dss';-import {- EntityModalActionFooter,- EntityModalTitle,-} from '../EntityModal/EntityModal';--export const MoveToProjectView = (props: {- entity: EntityData;- onFinish: () => void;- onCancel: () => void;-}) => {- let listRef!: HTMLDivElement;- const moveToProjectMutation = createMoveToProjectDssEntityMutation();- const projects = useProjects();- const [searchQuery, setSearchQuery] = createSignal('');- const [selectedProject, setSelectedProject] = createSignal<Project | null>(- null- );- const [expandedProjects, setExpandedProjects] = createSignal<{- [key: string]: boolean;- }>({});- const [focusedIndex, setFocusedIndex] = createSignal(-1);- const [attachHotkeys, moveToProjectHotkeyScopeId] = useHotkeyDOMScope(- 'move-to-project',- true- );- let rootScopeId!: HTMLDivElement;-- onMount(() => {- attachHotkeys(rootScopeId);- registerHotkey({- hotkey: ['arrowdown'],- scopeId: moveToProjectHotkeyScopeId,- description: 'Down',- keyDownHandler: () => {- const items = flattenedProjects.items;- if (items.length === 0) return false;-- const currentIndex = focusedIndex();- const nextIndex =- currentIndex === -1- ? 0- : Math.min(currentIndex + 1, items.length - 1);- setFocusedIndex(nextIndex);-- // Update selection- const nextProject = items[nextIndex];- if (nextProject) {- setSelectedProject(nextProject);- scrollToKeepGap({- container: listRef,- target: listRef.querySelector('.focused') as HTMLElement,- align: 'bottom',- });- }- return true;- },- runWithInputFocused: true,- });- registerHotkey({- hotkey: ['arrowup'],- scopeId: moveToProjectHotkeyScopeId,- description: 'Up',- keyDownHandler: () => {- const items = flattenedProjects.items;- if (items.length === 0) return false;-- const currentIndex = focusedIndex();- const prevIndex =- currentIndex === -1- ? items.length - 1- : Math.max(currentIndex - 1, 0);- setFocusedIndex(prevIndex);-- // Update selection- const prevProject = items[prevIndex];- if (prevProject) {- setSelectedProject(prevProject);- scrollToKeepGap({- container: listRef,- target: listRef.querySelector('.focused') as HTMLElement,- align: 'top',- });- }- return true;- },- runWithInputFocused: true,- });- registerHotkey({- hotkey: ['arrowright'],- scopeId: moveToProjectHotkeyScopeId,- description: 'Expand',- keyDownHandler: () => {- const items = flattenedProjects.items;- const currentIndex = focusedIndex();- if (currentIndex === -1) return false;- const currentProject = items[currentIndex];-- if (currentProject && !searchQuery()) {- // Check if project has children and is not expanded- const tree = projectTree();- const hasChildren =- tree.itemMap[currentProject.id]?.children.length > 0;- const isExpanded = expandedProjects()[currentProject.id];-- if (hasChildren && !isExpanded) {- toggleExpanded(currentProject.id);- return true;- } else if (hasChildren && isExpanded) {- // If already expanded, try to jump to first child- const children = tree.itemMap[currentProject.id]?.children || [];- if (children.length > 0) {- const firstChild = children[0];- const firstChildIndex = items.findIndex(- (item) => item.id === firstChild.id- );- if (firstChildIndex !== -1) {- setFocusedIndex(firstChildIndex);- setSelectedProject(items[firstChildIndex]);- scrollToKeepGap({- container: listRef,- target: listRef.querySelector('.focused') as HTMLElement,- align: 'top',- });- return true;- }- }- }- }- return false;- },- runWithInputFocused: true,- });- registerHotkey({- hotkey: ['arrowleft'],- scopeId: moveToProjectHotkeyScopeId,- description: 'Collapse',- keyDownHandler: () => {- const items = flattenedProjects.items;- const currentIndex = focusedIndex();- if (currentIndex === -1) return false;- const currentProject = items[currentIndex];-- if (currentProject && !searchQuery()) {- // Check if project is expanded- const isExpanded = expandedProjects()[currentProject.id];-- if (isExpanded) {- toggleExpanded(currentProject.id);- return true;- } else {- // If already collapsed, try to jump to parent directory- const parentId = currentProject.parentId;- if (parentId) {- const parentIndex = items.findIndex(- (item) => item.id === parentId- );- if (parentIndex !== -1) {- setFocusedIndex(parentIndex);- setSelectedProject(items[parentIndex]);- scrollToKeepGap({- container: listRef,- target: listRef.querySelector('.focused') as HTMLElement,- align: 'top',- });- return true;- }- }- }- }- return false;- },- runWithInputFocused: true,- });- });-- // Build project tree structure- const projectTree = createMemo(() => {- const allProjects = projects();- const itemMap: { [key: string]: { item: any; children: any[] } } = {};- const rootItems: { item: any; children: any[] }[] = [];- const processedItems = new Set<string>();-- // First pass: Create a map of all items- allProjects.forEach((item) => {- itemMap[item.id] = { item, children: [] };- });-- // Second pass: Connect children to parents- allProjects.forEach((item) => {- const parentId = item.parentId;- if (parentId && itemMap[parentId]) {- itemMap[parentId].children.push(item);- processedItems.add(item.id);- }- });-- // Third pass: Add only root items (those without parents)- allProjects.forEach((item) => {- if (!processedItems.has(item.id)) {- rootItems.push(itemMap[item.id]);- }- });-- return { rootItems, itemMap };- });-- // Helper function to build project path- const getProjectPath = (project: Project): string => {- const tree = projectTree();- const path: string[] = [];- let currentId = project.parentId;-- while (currentId && tree.itemMap[currentId]) {- const parent = tree.itemMap[currentId].item;- path.unshift(parent.name);- currentId = parent.parentId;- }-- return path.length > 0 ? `/${path.join('/')}` : '';- };-- // Flatten tree for display (only show expanded items)- const [flattenedProjects, setFlattenedProjects] = createStore<{- items: (Project & { depth: number; path?: string })[];- }>({- items: [],- });-- // Update flattened projects when dependencies change- const updateFlattenedProjects = () => {- const query = searchQuery().toLowerCase();-- if (query) {- // If searching, show flat list with paths- const searchResults = projects()- .filter((project) => project.name.toLowerCase().includes(query))- .map((project) => ({- ...project,- depth: 0,- path: getProjectPath(project),- }));- setFlattenedProjects('items', reconcile(searchResults));- } else {- // If not searching, show tree structure- const result: (Project & { depth: number; path?: string })[] = [];- const expanded = expandedProjects();- const tree = projectTree();-- const processItems = (- items: { item: any; children: any[] }[],- depth = 0- ) => {- for (const item of items) {- result.push({- ...item.item,- depth,- path: getProjectPath(item.item),- });- // Only show children if the parent is expanded- if (expanded[item.item.id] && item.children.length > 0) {- // Convert children to the expected format- const childrenAsTreeItems = item.children.map((child) => ({- item: child,- children: tree.itemMap[child.id]?.children || [],- }));- processItems(childrenAsTreeItems, depth + 1);- }- }- };-- processItems(tree.rootItems);- setFlattenedProjects('items', reconcile(result));- }- };-- // Update when search query changes- createEffect(() => {- searchQuery();- updateFlattenedProjects();- });-- // Update when expanded projects change- createEffect(() => {- expandedProjects();- updateFlattenedProjects();- });-- // Update when projects change- createEffect(() => {- projects();- updateFlattenedProjects();- });-- // Reset focused index when list changes (but preserve focus on current project if possible)- createEffect(() => {- const items = flattenedProjects.items;- if (items.length > 0) {- const currentSelected = selectedProject();- if (currentSelected) {- // Try to find the currently selected project in the new list- const currentIndex = items.findIndex(- (item) => item.id === currentSelected.id- );- if (currentIndex !== -1) {- setFocusedIndex(currentIndex);- return; // Don't change selection, just update focus- }- }-- // Don't automatically set focus or selection - wait for user interaction- // Only set focus if there's already a focused item to maintain- const currentFocus = focusedIndex();- if (currentFocus >= 0 && currentFocus < items.length) {- // Keep existing focus if it's still valid- return;- }- }- });-- const toggleExpanded = (projectId: string) => {- setExpandedProjects((prev) => ({- ...prev,- [projectId]: !prev[projectId],- }));- };-- const finishEditing = async () => {- const projectId = selectedProject()?.id;- if (projectId && props.entity) {- // Only allow moving supported entity types- if (- props.entity.type === 'document' ||- props.entity.type === 'chat' ||- props.entity.type === 'project'- ) {- // Find the project name for the toast message- const projectName = selectedProject()?.name || 'Unknown Project';-- await moveToProjectMutation.mutateAsync({- entity: props.entity,- project: { id: projectId, name: projectName },- });- }- }- props.onFinish();- };-- const getIcon = createMemo(() => {- switch (props.entity.type) {- case 'channel':- switch (props.entity.channelType) {- case 'direct_message':- return getIconConfig('directMessage');- case 'organization':- return getIconConfig('company');- default:- return getIconConfig('channel');- }- case 'document':- return getIconConfig(props.entity.fileType || 'default');- case 'chat':- return getIconConfig('chat');- case 'project':- return getIconConfig('project');- case 'email':- return getIconConfig(props.entity.isRead ? 'emailRead' : 'email');- }- });-- return (- <div class="" ref={rootScopeId} tabindex={-1}>- <EntityModalTitle title="Move to Project" />- <div class="flex pb-2">- <div class="flex justify-between items-center gap-2">- <div class="flex items-center gap-1">- <div class="size-5 flex items-center justify-center">- <Dynamic- component={getIcon().icon}- class={`flex size-full ${getIcon().foreground}`}- />- </div>-- {/* Project name */}- <span class="shrink-0 text-ink text-sm sm:text-sm font-medium focus:font-bold font-sans grow overflow-hidden truncate">- {props.entity.name}- </span>- </div>- <CustomEntityIcon icon={ArrowRight} size="sm" />- <div class="flex gap-1 items-center">- {/* Project icon */}- <div- class="size-6 flex items-center justify-center"- classList={{- 'opacity-20': !selectedProject(),- }}- >- <EntityIcon targetType="project" size="sm" />- </div>-- <Show when={selectedProject()}>- {/* Project name */}- <span class="shrink-0 text-ink text-sm sm:text-sm font-medium focus:font-bold font-sans grow overflow-hidden truncate">- {selectedProject()?.name}- </span>- <Show when={searchQuery()}>- <span class="text-ink-extra-muted/80 text-xs truncate">- {getProjectPath(selectedProject()!)}- </span>- </Show>- </Show>- </div>- </div>- </div>-- <div class="w-full h-fit suppress-css-brackets mb-3">- <input- type="text"- placeholder="Search projects..."- value={searchQuery()}- onInput={(e) => setSearchQuery(e.currentTarget.value)}- class="w-full p-2 text-sm border-1 border-edge/20 bg-menu text-ink placeholder:text-ink-placeholder focus:outline-none selection:bg-ink selection:text-panel"- />- </div>- <div class="w-full max-h-64 h-[300px] overflow-hidden">- <Fragment ref={listRef}>- <VList data={flattenedProjects.items} class="[&>div]:overflow-clip">- {(project, index) => {- // Safety check- if (!project || !project.id) {- console.warn('Skipping invalid project:', project);- return null;- }-- const isSelected = () => selectedProject()?.id === project.id;- const isFocused = () =>- focusedIndex() !== -1 && index() === focusedIndex();- const isExpanded = () => expandedProjects()[project.id] || false;- const hasChildren = () => {- const tree = projectTree();- return tree.itemMap[project.id]?.children.length > 0;- };-- return (- <div- class="group flex flex-col px-2"- style="margin: 2px 0"- onClick={() => {- setFocusedIndex(index());- setSelectedProject(project);- scrollToKeepGap({- container: listRef,- target: listRef.querySelector('.focused') as HTMLElement,- align: 'top',- });- }}- classList={{- 'bg-accent/10': isFocused() && !isSelected(),- focused: isFocused(),- }}- >- <BozzyBracket- active={isSelected() || isFocused()}- class="flex h-5"- >- <div- class="w-full"- style={{- 'padding-top': '6px',- 'padding-bottom': '6px',- }}- >- <div- class="w-full flex gap-1.5 items-center ml-auto text-ink-extra-muted h-5"- style={{- height: '20px',- }}- >- {/* Indentation spacers */}- <ExplorerSpacer depth={project.depth} size="sm" />-- {/* Expand/collapse caret */}- <div- class="flex items-center justify-center w-4 h-4 cursor-pointer hover:bg-edge/10 rounded"- onClick={(e) => {- e.stopPropagation();- toggleExpanded(project.id);- }}- classList={{- 'opacity-20': !!searchQuery() || !hasChildren(),- }}- >- <CaretRight- class={`w-3 h-3 transition-transform duration-150 ${isExpanded() && !searchQuery() ? 'rotate-90' : ''}`}- />- </div>-- {/* Project icon */}- <div class="size-6 flex items-center justify-center">- <EntityIcon targetType="project" size="sm" />- </div>-- {/* Project name */}- <span class="shrink-0 text-ink text-sm sm:text-sm font-medium focus:font-bold font-sans overflow-hidden truncate">- {project.name}- </span>- <Show when={searchQuery()}>- <span class="text-ink-extra-muted/80 text-xs truncate">- {project.path || ''}- </span>- </Show>- </div>- </div>- </BozzyBracket>- </div>- );- }}- </VList>- </Fragment>- </div>-- <EntityModalActionFooter- onCancel={props.onCancel}- onConfirm={finishEditing}- confirmText="Move"- isDisabled={!selectedProject()?.id}- />- </div>- );-};diff --git a/js/app/packages/core/component/FileList/useItemOperations.ts b/js/app/packages/core/component/FileList/useItemOperations.tsindex bb7a4c59e3..d56aed7413 100644--- a/js/app/packages/core/component/FileList/useItemOperations.ts+++ b/js/app/packages/core/component/FileList/useItemOperations.ts@@ -249,8 +249,9 @@ export const useItemOperations = createSingletonRoot(() => {}return `Successfully renamed ${items.length} ${items.length === 1 ? 'item' : 'items'}`;},- error: (error) =>- `Failed to rename items: ${error.message || 'Unknown error'}`,+ error: (error) => {+ return `Failed to rename items: ${error.message || 'Unknown error'}`;+ },toastTypeDeterminer: (result) =>result.failedItems.length > 0 ? ToastType.FAILURE : ToastType.SUCCESS,});diff --git a/js/app/packages/core/component/Menu.tsx b/js/app/packages/core/component/Menu.tsxindex 4aa9b5768c..22ff57744d 100644--- a/js/app/packages/core/component/Menu.tsx+++ b/js/app/packages/core/component/Menu.tsx@@ -176,7 +176,7 @@ export function MenuItem(props: MenuItemProps) {return (// Note: Kobalte's ContextMenu.Item is identical to DropdownMenu.Item. Either can be used inside of the other.<MenuItemWrapper- class={`${MENU_ITEM_CLASS} ${props.disabled ? 'opacity-50 cursor-not-allowed text-ink' : 'hover:bg-hover hover-transition-bg text-ink'} ${props.class ?? ''}`}+ class={`${MENU_ITEM_CLASS} ${props.disabled ? 'opacity-50 cursor-not-allowed' : 'hover:bg-hover hover-transition-bg'} ${props.class ?? ''}`}onClick={props.onClick}disabled={props.disabled}closeOnSelect={props.closeOnSelect}diff --git a/js/app/packages/macro-entity/src/components/EntityWithEverything.tsx b/js/app/packages/macro-entity/src/components/EntityWithEverything.tsxindex 2caae01138..b906d60963 100644--- a/js/app/packages/macro-entity/src/components/EntityWithEverything.tsx+++ b/js/app/packages/macro-entity/src/components/EntityWithEverything.tsx@@ -406,7 +406,7 @@ export function EntityWithEverything(><buttontype="button"- class="col-1 size-full relative group/button flex items-center justify-center"+ class="col-1 size-full relative group/button flex items-center justify-center bracket-never"onClick={(e) => {props.onChecked?.(!props.checked, e.shiftKey);}}diff --git a/js/app/packages/macro-entity/src/queries/dss.ts b/js/app/packages/macro-entity/src/queries/dss.tsindex 6122bfdf6b..ea2583c9a4 100644--- a/js/app/packages/macro-entity/src/queries/dss.ts+++ b/js/app/packages/macro-entity/src/queries/dss.ts@@ -1,5 +1,9 @@-import { deleteItem } from '@core/component/FileList/itemOperations';-import { useItemOperations } from '@core/component/FileList/useItemOperations';+import {+ copyItem,+ deleteItem,+ moveToFolder,+ renameItem,+} from '@core/component/FileList/itemOperations';import type { ItemType } from '@service-storage/client';import type {PostItemsSoupParams,@@ -506,19 +510,17 @@ export function createBulkDeleteDssItemsMutation() {}export function createRenameDssEntityMutation() {- const itemOperations = useItemOperations();return useMutation(() => ({mutationFn: async ({- entity: { id, type, name },+ entity: { id, type },newName,}: {entity: EntityData & { name: string };newName: string;}) => {- const success = await itemOperations.renameItem({+ const success = await renameItem({itemType: type as ItemType,id,- itemName: name,newName,});@@ -591,8 +593,6 @@ export function createRenameDssEntityMutation() {}export function createBulkRenameDssEntityMutation() {- // const itemOperations = useItemOperations();-const isUnsupportedEntity = (entity: EntityData) => {const type = entity.type;return type === 'channel' || type === 'email';@@ -601,34 +601,34 @@ export function createBulkRenameDssEntityMutation() {return useMutation(() => ({mutationFn: async ({entities,- newName,+ name,}: {- entities: EntityData[];- newName: string;+ entities: (EntityData & { name: string })[];+ name: (oldName: string) => string | string;}) => {if (entities.some(isUnsupportedEntity)) {throw new Error(`Unsupported entity type provided`);}-- // const success = await itemOperations.bulkRename(- // entities.map((entity) => ({}))- // );- //- const success = false;-- if (!success) {- throw new Error(`TODO (SEAMUS): bulk rename! – ${newName}`);- }-- return { success: true };+ 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,- newName,+ name,}: {- entities: EntityData[];- newName: string;+ entities: (EntityData & { name: string })[];+ name: (oldName: string) => string | string;}) => {+ const ids = new Set(entities.map((e) => e.id));+await Promise.all([queryClient.cancelQueries({queryKey: queryKeys.dss({ infinite: true }),@@ -637,66 +637,65 @@ export function createBulkRenameDssEntityMutation() {queryKey: queryKeys.dssPost({ infinite: true }),}),]);- function updateBulkEntityNamesInQueryData(- prev: { pages: { items: EntityData[] }[] } | undefined- ): { pages: { items: EntityData[] }[] } | undefined {- if (!prev) return prev;- const pages = prev.pages.map((page) => ({- ...page,- items: page.items.map((item) => {- const found = entities.find((e) => e.id === item.id);- if (!found) return item;- return { ...item, name: newName };- }),- }));+ function update(prev: { pages: { items: EntityData[] }[] } | undefined) {+ if (!prev) return prev;return {...prev,- pages,+ 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) =>- updateBulkEntityNamesInQueryData(- prev as { pages: { items: EntityData[] }[] } | undefined- )+ (prev) => update(prev as any));+queryClient.setQueriesData({ queryKey: queryKeys.dssPost({ infinite: true }) },- (prev) =>- updateBulkEntityNamesInQueryData(- prev as { pages: { items: EntityData[] }[] } | undefined- )+ (prev) => update(prev as any));},+onSettled: (data, error, { entities }) => {- if (error)- console.error(`Failed to rename dss items`, entities, data, error);+ if (error) {+ console.error(`Failed bulk rename`, entities, data, error);+ }queryClient.invalidateQueries({queryKey: queryKeys.dss({ infinite: true }),});++ queryClient.invalidateQueries({+ queryKey: queryKeys.dssPost({ infinite: true }),+ });},}));}export function createMoveToProjectDssEntityMutation() {- const itemOperations = useItemOperations();return useMutation(() => ({mutationFn: async ({- entity: { id, type, name },- project: { id: projectId, name: projectName },+ entity: { id, type },+ project: { id: projectId },}: {entity: EntityData & { name: string };project: { id: string; name: string };}) => {- const success = await itemOperations.moveToFolder({+ const success = await moveToFolder({itemType: type as 'document' | 'chat' | 'project',id: id,- itemName: name,folderId: projectId,- folderName: projectName,});return { success };@@ -758,7 +757,6 @@ export function createMoveToProjectDssEntityMutation() {}export function createCopyDssEntityMutation() {- const itemOperations = useItemOperations();return useMutation(() => ({mutationFn: async ({entity: { id, type, name },@@ -770,7 +768,7 @@ export function createCopyDssEntityMutation() {`Unsupported entity type: ${type} for id ${id}. Projects cannot be copied.`);- const success = await itemOperations.copyItem({+ const success = await copyItem({itemType: type as 'document' | 'chat',id,name,@@ -803,3 +801,169 @@ export function createCopyDssEntityMutation() {},}));}++export function createBulkCopyDssEntityMutation() {+ // Only support chat + document, same as single-copy version+ const isUnsupportedEntity = (entity: EntityData) => {+ const type = entity.type;+ return type !== 'chat' && type !== 'document';+ };++ return useMutation(() => ({+ mutationFn: async ({+ entities,+ name,+ }: {+ entities: (EntityData & { name: string })[];+ name: string | ((oldName: string) => string);+ }) => {+ if (entities.some(isUnsupportedEntity)) {+ throw new Error(`Unsupported entity type provided`);+ }++ const results = await Promise.all(+ entities.map((e) =>+ copyItem({+ itemType: e.type as 'document' | 'chat',+ id: e.id,+ name: typeof name === 'function' ? name(e.name) : name,+ })+ )+ );++ if (results.some((r) => !r)) {+ throw new Error(`One or more DSS items failed to copy`);+ }++ return { success: true };+ },++ onMutate: async () => {+ // For copy, no optimistic update — new IDs unknown until server+ await Promise.all([+ queryClient.cancelQueries({+ queryKey: queryKeys.dss({ infinite: true }),+ }),+ queryClient.cancelQueries({+ queryKey: queryKeys.dssPost({ infinite: true }),+ }),+ ]);+ },++ onSettled: (data, error, { entities }) => {+ if (error) {+ console.error(`Failed bulk copy`, entities, data, error);+ }++ // Trigger refetch so new items appear+ queryClient.invalidateQueries({+ queryKey: queryKeys.dss({ infinite: true }),+ });++ queryClient.invalidateQueries({+ queryKey: queryKeys.dssPost({ infinite: true }),+ });+ },+ }));+}++export function createBulkMoveToProjectDssEntityMutation() {+ const isUnsupportedEntity = (entity: EntityData) => {+ const type = entity.type;+ return type !== 'chat' && type !== 'document' && type !== 'project';+ };++ return useMutation(() => ({+ mutationFn: async ({+ entities,+ project,+ }: {+ entities: (EntityData & { name: string })[];+ project: { id: string; name: string };+ }) => {+ if (entities.some(isUnsupportedEntity)) {+ throw new Error(`Unsupported entity type provided`);+ }++ const results = await Promise.all(+ entities.map((entity) =>+ moveToFolder({+ itemType: entity.type as 'document' | 'chat' | 'project',+ id: entity.id,+ folderId: project.id,+ })+ )+ );++ if (results.some((r) => !r)) {+ throw new Error(`One or more DSS items failed to move`);+ }++ return { success: true };+ },++ onMutate: async ({+ entities,+ project,+ }: {+ entities: (EntityData & { name: string })[];+ project: { id: string; name: string };+ }) => {+ await Promise.all([+ queryClient.cancelQueries({+ queryKey: queryKeys.dss({ infinite: true }),+ }),+ queryClient.cancelQueries({+ queryKey: queryKeys.dssPost({ infinite: true }),+ }),+ ]);++ function updateEntityProjectIdInQueryData(+ prev: { pages: { items: EntityData[] }[] } | undefined+ ): { pages: { items: EntityData[] }[] } | undefined {+ if (!prev) return prev;+ const entityIds = entities.map((e) => e.id);+ const pages = prev.pages.map((page) => ({+ ...page,+ items: page.items.map((item) =>+ entityIds.includes(item.id)+ ? { ...item, projectId: project.id }+ : item+ ),+ }));+ return {+ ...prev,+ pages,+ };+ }++ queryClient.setQueriesData(+ { queryKey: queryKeys.dss({ infinite: true }) },+ (prev) =>+ updateEntityProjectIdInQueryData(+ prev as { pages: { items: EntityData[] }[] } | undefined+ )+ );+ queryClient.setQueriesData(+ { queryKey: queryKeys.dssPost({ infinite: true }) },+ (prev) =>+ updateEntityProjectIdInQueryData(+ prev as { pages: { items: EntityData[] }[] } | undefined+ )+ );+ },++ onSettled: (data, error, { entities }) => {+ if (data?.success === false || error)+ console.error(`Failed to bulk move dss items`, entities, data, error);++ queryClient.invalidateQueries({+ queryKey: queryKeys.dss({ infinite: true }),+ });++ queryClient.invalidateQueries({+ queryKey: queryKeys.dssPost({ infinite: true }),+ });+ },+ }));+}