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): multi select (#198)
Seamuse1d719f6634d
diff --git a/js/app/packages/app/component/EntityActionsMenuItems.tsx b/js/app/packages/app/component/EntityActionsMenuItems.tsxnew file mode 100644index 0000000000..d3b9920eb0--- /dev/null+++ b/js/app/packages/app/component/EntityActionsMenuItems.tsx@@ -0,0 +1,98 @@+import { globalSplitManager } from '@app/signal/splitLayout';+import { MenuItem } from '@core/component/Menu';+import { fileTypeToBlockName } from '@core/constant/allBlocks';+import { intersection } from '@core/util/list';+import type { EntityData } from '@macro-entity';+import { type Setter, Show } from 'solid-js';+import { useSplitPanelOrThrow } from './split-layout/layoutUtils';+import type { EntityActionType } from './UnifiedEntityActions';++interface EntityActionsMenuItemsProps {+ entity: EntityData;+ 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;++ const entities = () => {+ const { selectedEntities } = viewsDataStore[selectedView()];+ if (selectedEntities.length > 0) {+ if (selectedEntities.some((e) => e.id === props.entity.id)) {+ return selectedEntities;+ }+ }+ return [props.entity];+ };++ const setSelection: Setter<EntityData[]> = (entities) => {+ return unifiedListContext.setViewDataStore(+ selectedView(),+ 'selectedEntities',+ entities+ );+ };++ const MenuItemInner = (props: {+ action: EntityActionType;+ label: string;+ }) => {+ return (+ <Show when={actionRegistry.has(props.action)}>+ <MenuItem+ text={props.label}+ disabled={actionRegistry.isActionDisabled(props.action, entities())}+ onClick={async () => {+ const { success, failedEntities } = await actionRegistry.execute(+ props.action,+ entities()+ );+ console.log({ success, failedEntities });+ if (success) {+ setSelection([]);+ } else if (failedEntities) {+ setSelection((prev) =>+ intersection(prev, failedEntities, (a, b) => a.id === b.id)+ );+ }+ }}+ />+ </Show>+ );+ };++ return (+ <>+ <MenuItemInner action="mark_as_done" label="Mark Done" />+ <MenuItemInner action="delete" label="Delete" />+ <MenuItem+ text="Open in new split"+ disabled={entities().length > 1}+ onClick={() => {+ const splitManager = globalSplitManager();+ if (!splitManager) {+ console.error('No split manager available');+ return;+ }+ if (props.entity.type === 'document') {+ const { fileType, id } = props.entity;+ splitManager.createNewSplit({+ type: fileTypeToBlockName(fileType),+ id,+ });+ } else {+ const { id, type } = props.entity;+ splitManager.createNewSplit({+ type,+ id,+ });+ }+ }}+ />+ </>+ );+};diff --git a/js/app/packages/app/component/EntitySelectionToolbarModal.tsx b/js/app/packages/app/component/EntitySelectionToolbarModal.tsxnew file mode 100644index 0000000000..b6606650f9--- /dev/null+++ b/js/app/packages/app/component/EntitySelectionToolbarModal.tsx@@ -0,0 +1,50 @@+import { Hotkey } from '@core/component/Hotkey';+import { ScopedPortal } from '@core/component/ScopedPortal';+import type { EntityData } from '@macro-entity';+import CloseIcon from '@phosphor-icons/core/regular/x.svg?component-solid';++interface EntitySelectionToolbarModalProps {+ selectedEntities: EntityData[];+ onClose: VoidFunction;+ onAction: VoidFunction;+}++export const EntitySelectionToolbarModal = (+ props: EntitySelectionToolbarModalProps+) => {+ 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="flex items-center">+ <button+ type="button"+ class="size-6 aspect-square p-1 flex items-center justify-center hover:bg-hover"+ onClick={props.onClose}+ >+ <CloseIcon class="shrink-0 size-full" />+ </button>+ <span class="text-ink font-regular w-full whitespace-nowrap">+ {props.selectedEntities.length} selected+ </span>+ </div>+ <button+ 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" />+ <span>Actions</span>+ </button>+ <button+ onClick={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" />+ <span>Clear</span>+ </button>+ </div>+ </div>+ </ScopedPortal>+ );+};diff --git a/js/app/packages/app/component/Layout.tsx b/js/app/packages/app/component/Layout.tsxindex c47b6db29f..5d3cbeaf0e 100644--- a/js/app/packages/app/component/Layout.tsx+++ b/js/app/packages/app/component/Layout.tsx@@ -14,6 +14,7 @@ import { attachGlobalDOMScope } from 'core/hotkey/hotkeys';import { createEffect, onCleanup, onMount, Show, Suspense } from 'solid-js';import { updateCookie } from '../util/updateCookie';import Banner from './banner/Banner';+import { GlobalBulkEditEntityModal } from './bulk-edit-entity/BulkEditEntityModal';import { KommandMenu } from './command/Konsole';import { Dock } from './dock/Dock';import GlobalShortcuts from './GlobalHotkeys';@@ -112,6 +113,7 @@ export function Layout(props: RouteSectionProps) {<KommandMenu /></Suspense><QuickCreateMenu />+ <GlobalBulkEditEntityModal /></Show><Showwhen={diff --git a/js/app/packages/app/component/Root.tsx b/js/app/packages/app/component/Root.tsxindex 6867bc2c3f..fe46c3d30c 100644--- a/js/app/packages/app/component/Root.tsx+++ b/js/app/packages/app/component/Root.tsx@@ -56,6 +56,7 @@ import { useSoundHover } from '../util/soundHover';import { updateCookie } from '../util/updateCookie';import { Login } from './auth/Login';import { LOGIN_COOKIE_AGE, setCookie } from './auth/Shared';+import { GlobalAppStateProvider } from './GlobalAppState';import { Layout } from './Layout';import MacroJump from './MacroJump';diff --git a/js/app/packages/app/component/SoupContext.tsx b/js/app/packages/app/component/SoupContext.tsxindex 97730d69fe..d12c8291a1 100644--- a/js/app/packages/app/component/SoupContext.tsx+++ b/js/app/packages/app/component/SoupContext.tsx@@ -7,12 +7,14 @@ import {type View,type ViewId,} from '@core/types/view';+import { filterMap } from '@core/util/list';import { isErr } from '@core/util/maybeResult';import { getScrollParent } from '@core/util/scrollParent';import type { EntityData } from '@macro-entity';import { useTutorialCompleted } from '@service-gql/client';import { storageServiceClient } from '@service-storage/client';import { createLazyMemo } from '@solid-primitives/memo';+import { useQuery } from '@tanstack/solid-query';import { registerHotkey, useHotkeyDOMScope } from 'core/hotkey/hotkeys';import {@@ -32,9 +34,27 @@ import {type Store,} from 'solid-js/store';import type { VirtualizerHandle } from 'virtua/solid';+import { useUserId } from '../../macro-entity/src/queries/auth';import { playSound } from '../util/sound';+import { openBulkEditModal } from './bulk-edit-entity/BulkEditEntityModal';+import {+ resetCommandCategoryIndex,+ searchCategories,+ setCommandCategoryIndex,+ setKonsoleContextInformation,+} from './command/KonsoleItem';+import {+ konsoleOpen,+ resetKonsoleMode,+ setKonsoleMode,+ toggleKonsoleVisibility,+} from './command/state';import { useGlobalNotificationSource } from './GlobalAppState';import type { SplitHandle } from './split-layout/layoutManager';+import {+ createEntityActionRegistry,+ type EntityActionRegistry,+} from './UnifiedEntityActions';import {VIEWCONFIG_BASE,VIEWCONFIG_DEFAULTS,@@ -56,6 +76,7 @@ export type UnifiedListContext = {emailViewSignal: Signal<'inbox' | 'sent' | 'drafts' | 'all'>;showHelpDrawer: Accessor<Set<string>>;setShowHelpDrawer: Setter<Set<string>>;+ actionRegistry: EntityActionRegistry;};const DEFAULT_VIEW_ID: View = 'all';@@ -103,6 +124,7 @@ export function createSoupContext(): UnifiedListContext {emailViewSignal,showHelpDrawer,setShowHelpDrawer,+ actionRegistry: createEntityActionRegistry(),};}@@ -152,11 +174,23 @@ function createViewData(selectedEntity: undefined,scrollOffset: undefined,initialConfig: undefined,+ selectedEntities: [],hasUserInteractedEntity: false,searchText: viewProps?.searchText,};}+type NavigationInput = {+ axis: 'start' | 'end'; // movement direction+ mode: 'step' | 'jump'; // how far: one step or to the end+ highlight?: boolean;+};++type NavigationResult = {+ success: boolean;+ entity: EntityData | undefined;+};+export function createNavigationEntityListShortcut({splitName,splitHandle,@@ -177,20 +211,60 @@ export function createNavigationEntityListShortcut({setSelectedView,// selectedEntitySignal: [selectedEntity, setSelectedEntity],entitiesSignal: [entities],+ actionRegistry,} = unifiedListContext;const viewData = createMemo(() => viewsData[selectedView()]);const viewIds = createMemo<ViewId[]>(() => Object.keys(viewsData));const selectedEntity = () => viewData().selectedEntity;+ const userId = useUserId();const notificationSource = useGlobalNotificationSource();- const defaultHotkeyE = () =>- VIEWCONFIG_DEFAULTS[selectedView() as View]?.hotkeyOptions?.e;- const markEntityAsDone = (entity: EntityData) =>- defaultHotkeyE()?.(entity, {- notificationSource,- soupContext: unifiedListContext,- });++ // const markEntityAsDone = (entity: EntityData) =>+ // defaultHotkeyE()?.(entity, {+ // notificationSource,+ // soupContext: unifiedListContext,+ // });+ //+ 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,+ });+ }+ }+ return { success: true };+ });++ actionRegistry.register(+ 'delete',+ async (entities) => {+ try {+ openBulkEditModal({+ view: 'delete',+ entities: entities,+ onFinish: () => {+ setViewDataStore(selectedView(), 'selectedEntities', []);+ },+ });+ } catch (err) {+ console.error('Failed to open bulk delete modal', err);+ }+ return { success: true };+ },+ {+ disabled: (entity) => {+ if (entity.type === 'channel' || entity.type === 'email') return true;+ if (entity.ownerId !== userId()) return true;+ return false;+ },+ }+ );const openEntity = (entity: EntityData) => {const { type, id } = entity;@@ -236,6 +310,73 @@ export function createNavigationEntityListShortcut({};});+ const getEntitiesForAction = createLazyMemo<{+ entities: Array<{ entity: EntityData; index: number }>;+ beforeEntity: EntityData | null;+ afterEntity: EntityData | null;+ }>(() => {+ const entityList = entities();+ if (!entityList)+ return { entities: [], beforeEntity: null, afterEntity: null };++ const idToIndexMap = new Map(entityList.map(({ id }, i) => [id, i]));+ let selectedEntityIndices: Array<{ entity: EntityData; index: number }> =+ [];++ if (viewData().selectedEntities.length > 0) {+ selectedEntityIndices = filterMap(+ viewData().selectedEntities,+ (entity) => {+ const index = idToIndexMap.get(entity.id);+ if (index === undefined) {+ return undefined;+ }+ return {+ index,+ entity,+ };+ }+ );+ } else {+ const entity = getHighlightedEntity();+ if (entity) selectedEntityIndices = [entity];+ }++ if (selectedEntityIndices.length === 0) {+ return { entities: [], beforeEntity: null, afterEntity: null };+ }++ selectedEntityIndices.sort((a, b) => a.index - b.index);++ const firstIndex = selectedEntityIndices[0].index;+ const lastIndex =+ selectedEntityIndices[selectedEntityIndices.length - 1].index;++ let before = null;+ if (firstIndex === 0) {+ // If first item is at index 0, use the item after the selection as beforeId+ const afterSelectionIndex = lastIndex + 1;+ if (afterSelectionIndex < entityList.length) {+ before = entityList[afterSelectionIndex];+ }+ } else {+ before = entityList[firstIndex - 1];+ }++ // Calculate afterId+ let after = null;+ const afterSelectionIndex = lastIndex + 1;+ if (afterSelectionIndex < entityList.length) {+ after = entityList[afterSelectionIndex];+ }++ return {+ entities: selectedEntityIndices,+ beforeEntity: before,+ afterEntity: after,+ };+ });+const isEntityLastItem = createLazyMemo(() => {const entityList = entities();if (!entityList) return false;@@ -246,14 +387,42 @@ export function createNavigationEntityListShortcut({return highlightedEntity.index >= entityList.length - 1;});+ const calculateEntityIndex = (+ startIndex: number,+ { axis, mode }: NavigationInput+ ) => {+ let index = startIndex;++ const maxLength = (entities()?.length || 1) - 1;+ if (mode === 'jump') {+ if (axis === 'start') {+ // setIndex(0);+ index = 0;+ } else {+ // setIndex(maxLength);+ index = maxLength;+ }+ } else {+ if (axis === 'start') {+ // setIndex(Math.max(index() - 1, 0));+ index = Math.max(index - 1, 0);+ } else {+ // setIndex(Math.min(index() + 1, maxLength));+ index = Math.min(index + 1, maxLength);+ }+ }++ return index;+ };+const navigateThroughList = async ({axis,mode,- }: {- axis: 'start' | 'end'; // movement direction- mode: 'step' | 'jump'; // how far: one step or to the end- }) => {- let index = getHighlightedEntity()?.index ?? -1;+ }: NavigationInput): Promise<NavigationResult> => {+ let index = calculateEntityIndex(getHighlightedEntity()?.index ?? -1, {+ axis,+ mode,+ });setJumpedToEnd(false);setViewDataStore(selectedView(), 'hasUserInteractedEntity', true);@@ -262,25 +431,6 @@ export function createNavigationEntityListShortcut({const scrollParent = getScrollParent(entityEl);const getAdjecentEl = async () => {- const maxLength = (entities()?.length || 1) - 1;- if (mode === 'jump') {- if (axis === 'start') {- // setIndex(0);- index = 0;- } else {- // setIndex(maxLength);- index = maxLength;- }- } else {- if (axis === 'start') {- // setIndex(Math.max(index() - 1, 0));- index = Math.max(index - 1, 0);- } else {- // setIndex(Math.min(index() + 1, maxLength));- index = Math.min(index + 1, maxLength);- }- }-virtualizerHandle()?.scrollToIndex(index, {// align: mode === 'jump' && axis === 'end' ? 'end' : undefined,// align: align(),@@ -308,10 +458,7 @@ export function createNavigationEntityListShortcut({const selectedEntity = entities()?.at(index);if (selectedEntity) {- if (- splitHandle.content().type !== 'component' &&- splitHandle.content().type !== 'project'- ) {+ if (splitHandle.content().type !== 'component') {const { type, id } = selectedEntity;if (type === 'document') {const { fileType } = selectedEntity;@@ -341,10 +488,13 @@ export function createNavigationEntityListShortcut({});}- return newSelectedEntityEl;+ return {+ element: newSelectedEntityEl,+ entity: selectedEntity,+ };};- const adjacentEl = await getAdjecentEl();+ const { element: adjacentEl, entity } = await getAdjecentEl();// Logic fails to focus entity element due to EntityList shuffling items after fetching new page// *ReSelectEntity effect logic covers this failure@@ -352,9 +502,15 @@ export function createNavigationEntityListShortcut({if (adjacentEl instanceof HTMLElement) {adjacentEl.focus();setTimeout(() => adjacentEl.focus());- return true;+ return {+ success: true,+ entity,+ };}- return false;+ return {+ success: false,+ entity,+ };};const scrollToEntityFromId = async () => {@@ -390,6 +546,70 @@ export function createNavigationEntityListShortcut({listScrollEl?.addEventListener('scroll', onListScroll);};+ const isEntitySelected = (entityID: string) => {+ return (+ viewData()?.selectedEntities.find((e) => e.id === entityID) !== undefined+ );+ };++ const toggleEntity = (entity: EntityData) => {+ setViewDataStore(selectedView(), 'selectedEntities', (s) => {+ if (isEntitySelected(entity.id)) {+ return s.filter((e) => e.id !== entity.id);+ }+ return s.concat(entity);+ });+ };++ const navigateAndSelectEntity = async (input: NavigationInput) => {+ const { success, entity } = await navigateThroughList(input);++ if (!success || !entity) return;++ toggleEntity(entity);+ };++ const handleNavigationSelection = (input: NavigationInput) => {+ const highlightedEntity = getHighlightedEntity();+ const currentIndex = highlightedEntity?.index ?? -1;+ const nextIndex = calculateEntityIndex(currentIndex, input);++ const nextEntity = entities()?.at(nextIndex);+ if (!nextEntity) return true;++ if (!highlightedEntity) {+ navigateAndSelectEntity(input);+ return true;+ }++ // If selectedEntities is empty, select current item first without moving+ const selectedEntities = viewData()?.selectedEntities || [];+ if (selectedEntities.length === 0) {+ toggleEntity(highlightedEntity.entity);+ return true;+ }++ if (+ !isEntitySelected(highlightedEntity.entity.id) &&+ !isEntitySelected(nextEntity.id)+ ) {+ toggleEntity(highlightedEntity.entity);+ navigateAndSelectEntity(input);++ return true;+ }++ if (isEntitySelected(nextEntity.id)) {+ toggleEntity(highlightedEntity.entity);+ navigateThroughList(input);+ return true;+ }++ navigateAndSelectEntity(input);++ return true;+ };+let virtuaMount = true;createEffect(on(virtualizerHandle, (virtuaRef) => {@@ -448,6 +668,41 @@ export function createNavigationEntityListShortcut({}));+ registerHotkey({+ scopeId: splitHotkeyScope,+ description: 'Root Modify selection',+ hotkey: 'cmd+k',+ condition: () => !konsoleOpen(),+ keyDownHandler: (e) => {+ e?.preventDefault();+ const selectedEntities = viewData().selectedEntities;++ const hasSelection = selectedEntities.length > 0;++ if (hasSelection) {+ setKonsoleMode('SELECTION_MODIFICATION');+ const selectionIndex = searchCategories.getCateoryIndex('Selection');++ if (selectionIndex === undefined) return false;++ setCommandCategoryIndex(selectionIndex);++ searchCategories.showCategory('Selection');++ setKonsoleContextInformation({+ selectedEntities: selectedEntities.slice(),+ });++ toggleKonsoleVisibility();+ return true;+ }+ searchCategories.hideCategory('Selection');+ resetCommandCategoryIndex();+ resetKonsoleMode();+ return false;+ },+ });+registerHotkey({hotkey: ['j', 'arrowdown'],scopeId: splitHotkeyScope,@@ -460,6 +715,17 @@ export function createNavigationEntityListShortcut({},hide: true,});+ registerHotkey({+ hotkey: ['shift+arrowdown', 'shift+j'],+ scopeId: splitHotkeyScope,+ description: 'Select down',+ hotkeyToken: TOKENS.entity.step.end,+ keyDownHandler: () => {+ const navigationInput: NavigationInput = { axis: 'end', mode: 'step' };+ return handleNavigationSelection(navigationInput);+ },+ hide: true,+ });registerHotkey({hotkey: ['k', 'arrowup'],scopeId: splitHotkeyScope,@@ -472,6 +738,18 @@ export function createNavigationEntityListShortcut({},hide: true,});++ registerHotkey({+ hotkey: ['shift+arrowup', 'shift+k'],+ scopeId: splitHotkeyScope,+ hotkeyToken: TOKENS.entity.step.start,+ description: 'Select up',+ keyDownHandler: () => {+ const navigationInput: NavigationInput = { axis: 'start', mode: 'step' };+ return handleNavigationSelection(navigationInput);+ },+ hide: true,+ });registerHotkey({hotkey: ['home'],scopeId: splitHotkeyScope,@@ -590,9 +868,10 @@ export function createNavigationEntityListShortcut({scopeId: entityHotkeyScope,description: 'Mark done',keyDownHandler: () => {- const entity = getHighlightedEntity()?.entity;-- if (!entity) return false;+ const entitiesForAction = getEntitiesForAction();+ if (entitiesForAction.entities.length === 0) {+ return false;+ }if (isEntityLastItem()) {navigateThroughList({ axis: 'start', mode: 'step' });@@ -600,12 +879,73 @@ export function createNavigationEntityListShortcut({navigateThroughList({ axis: 'end', mode: 'step' });}- markEntityAsDone(entity);+ actionRegistry.execute(+ 'mark_as_done',+ entitiesForAction.entities.map(({ entity }) => entity)+ );+ setViewDataStore(selectedView(), 'selectedEntities', []);+ return true;+ },+ displayPriority: 10,+ tags: ['selection-modification'],+ });+ registerHotkey({+ hotkey: ['x'],+ scopeId: entityHotkeyScope,+ description: 'Toggle select item',+ keyDownHandler: () => {+ const entity = getHighlightedEntity();+ if (!entity) return false;+ toggleEntity(entity.entity);return true;},displayPriority: 10,});+ registerHotkey({+ hotkey: ['escape'],+ scopeId: splitHotkeyScope,+ description: 'Clear multi selection',+ condition: () => viewData().selectedEntities.length > 0,+ keyDownHandler: () => {+ const length = viewData().selectedEntities.length;+ setViewDataStore(selectedView(), 'selectedEntities', []);+ return length > 1;+ },+ });+ registerHotkey({+ hotkey: ['delete', 'backspace'],+ scopeId: splitHotkeyScope,+ description: () =>+ viewData().selectedEntities.length > 1 ? 'Delete items' : 'Delete item',+ keyDownHandler: () => {+ const entitiesForAction = getEntitiesForAction();+ if (entitiesForAction.entities.length === 0) {+ return false;+ }+ actionRegistry+ .execute(+ 'delete',+ entitiesForAction.entities.map(({ entity }) => entity)+ )+ .then(({ success }) => {+ if (success && entitiesForAction.afterEntity) {+ setViewDataStore(+ selectedView(),+ 'highlightedId',+ entitiesForAction.afterEntity.id+ );+ setViewDataStore(+ selectedView(),+ 'selectedEntity',+ entitiesForAction.afterEntity+ );+ }+ });+ return true;+ },+ tags: ['selection-modification'],+ });createEffect(() => {const ref = entityListRef();diff --git a/js/app/packages/app/component/UnifiedEntityActions.tsx b/js/app/packages/app/component/UnifiedEntityActions.tsxnew file mode 100644index 0000000000..7cb8468851--- /dev/null+++ b/js/app/packages/app/component/UnifiedEntityActions.tsx@@ -0,0 +1,122 @@+import type { EntityData } from '@macro-entity';++export type EntityActionType =+ | 'mark_as_done'+ | 'delete'+ | 'rename'+ | 'move_to_project'+ | 'copy';++export type EntityActionResult = {+ success: boolean;+ failedEntities?: EntityData[];+ message?: string;+};++export type EntityActionHandler = (+ entities: EntityData[]+) => Promise<EntityActionResult>;++export type EntityActionConfig = {+ label?: string;+ icon?: string;+ disabled?: (entity: EntityData) => boolean;+};++export type EntityActionRegistry = {+ register: (+ type: EntityActionType,+ handler: EntityActionHandler,+ config?: EntityActionConfig+ ) => void;+ getHandler: (type: EntityActionType) => EntityActionHandler | undefined;+ getConfig: (type: EntityActionType) => EntityActionConfig | undefined;+ execute: (+ type: EntityActionType,+ entities: EntityData | EntityData[]+ ) => Promise<EntityActionResult>;+ isActionDisabled: (+ type: EntityActionType,+ entities: EntityData | EntityData[]+ ) => boolean;+ getAvailableActions: () => EntityActionType[];+ 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>();++ const register = (+ type: EntityActionType,+ handler: EntityActionHandler,+ config?: EntityActionConfig+ ): void => {+ actions.set(type, handler);+ if (config) {+ configs.set(type, config);+ }+ };++ const getHandler = (+ type: EntityActionType+ ): EntityActionHandler | undefined => {+ return actions.get(type);+ };++ const getConfig = (+ type: EntityActionType+ ): EntityActionConfig | undefined => {+ return configs.get(type);+ };++ const execute = async (+ type: EntityActionType,+ entities: EntityData | EntityData[]+ ): Promise<EntityActionResult> => {+ const handler = actions.get(type);+ if (!handler) {+ return { success: false, message: `Unknown action: ${type}` };+ }++ const result = await handler(+ Array.isArray(entities) ? entities : [entities]+ );++ if (typeof result === 'boolean') {+ return { success: result };+ } else if (result && typeof result === 'object') {+ return result;+ }+ return { success: true };+ };++ const isActionDisabled = (+ type: EntityActionType,+ entities: EntityData | EntityData[]+ ): boolean => {+ const config = configs.get(type);+ if (!config) return false;+ if (Array.isArray(entities)) {+ return entities.some((e) => config.disabled?.(e));+ }+ return config.disabled?.(entities) ?? false;+ };++ const getAvailableActions = (): EntityActionType[] => {+ return Array.from(actions.keys());+ };++ return {+ register,+ getHandler,+ getConfig,+ execute,+ isActionDisabled,+ getAvailableActions,+ has: (action) => actions.has(action),+ };+}diff --git a/js/app/packages/app/component/UnifiedListView.tsx b/js/app/packages/app/component/UnifiedListView.tsxindex c269c45ac6..d999f63fff 100644--- a/js/app/packages/app/component/UnifiedListView.tsx+++ b/js/app/packages/app/component/UnifiedListView.tsx@@ -6,18 +6,13 @@ import {emailRefetchInterval,useEmailLinksStatus,} from '@app/signal/emailAuth';-import { globalSplitManager } from '@app/signal/splitLayout';import { Button } from '@core/component/FormControls/Button';import DropdownMenu from '@core/component/FormControls/DropdownMenu';import { SegmentedControl } from '@core/component/FormControls/SegmentControls';import { ToggleButton } from '@core/component/FormControls/ToggleButton';import { ToggleSwitch } from '@core/component/FormControls/ToggleSwitch';import { IconButton } from '@core/component/IconButton';-import {- ContextMenuContent,- MenuItem,- MenuSeparator,-} from '@core/component/Menu';+import { ContextMenuContent, MenuSeparator } from '@core/component/Menu';import { RecipientSelector } from '@core/component/RecipientSelector';import {blockAcceptsFileExtension,@@ -37,7 +32,6 @@ import { ContextMenu } from '@kobalte/core/context-menu';import { supportedExtensions } from '@lexical-core/utils';import {createChannelsQuery,- createDeleteDssItemMutation,createDssInfiniteQuery,createEmailsInfiniteQuery,createFilterComposer,@@ -104,9 +98,21 @@ import {} from 'solid-js';import { createStore, type SetStoreFunction, unwrap } from 'solid-js/store';import { EntityWithEverything } from '../../macro-entity/src/components/EntityWithEverything';-import { createCopyDssEntityMutation } from '../../macro-entity/src/queries/dss';import type { FetchPaginatedEmailsParams } from '../../macro-entity/src/queries/email';+import {+ resetCommandCategoryIndex,+ searchCategories,+ setCommandCategoryIndex,+ setKonsoleContextInformation,+} from './command/KonsoleItem';+import {+ resetKonsoleMode,+ setKonsoleMode,+ toggleKonsoleVisibility,+} from './command/state';+import { EntityActionsMenuItems } from './EntityActionsMenuItems';import { EntityModal } from './EntityModal/EntityModal';+import { EntitySelectionToolbarModal } from './EntitySelectionToolbarModal';import { useUpsertSavedViewMutation } from './Soup';import {SplitToolbarLeft,@@ -174,21 +180,6 @@ export function UnifiedListView(props: UnifiedListViewProps) {prevSelectedEntity: undefined,});- const openEntityModal = (view: 'rename' | 'moveToProject') => {- // terrible will fix- // context menu upon closing steals focus from mounted menu- setTimeout(() => {- setTimeout(() => {- setContextAndModalState((prev) => ({- ...prev,- modalOpen: true,- modalView: view,- selectedEntity: prev.prevSelectedEntity,- }));- }, 100);- });- };-const [localEntityListRef, setLocalEntityListRef] = createSignal<HTMLDivElement | undefined>();@@ -860,16 +851,17 @@ export function UnifiedListView(props: UnifiedListViewProps) {handle?.activate();};- const { mutate: deleteDssItem } = createDeleteDssItemMutation();- const { mutate: copyDssItem } = createCopyDssEntityMutation();-const StyledTriggerLabel = (props: ParentProps) => {return <span class="text-[0.625rem]">{props.children}</span>;};const highlightedSelector = createSelector(() => view()?.highlightedId);- const selectedSelector = createSelector(() => selectedEntity()?.id);+ const focusedSelector = createSelector(() => selectedEntity()?.id);+ const selectedSelector = createSelector(+ () => view()?.selectedEntities,+ (a: string, b: EntityData[]) => b.find((e) => e.id === a) !== undefined+ );const saveViewMutation = useUpsertSavedViewMutation();@@ -1162,6 +1154,7 @@ export function UnifiedListView(props: UnifiedListViewProps) {</SplitToolbarRight></Show><ContextMenu+ forceMount={contextAndModalState.contextMenuOpen}onOpenChange={(open) => {setContextAndModalState((prev) => {if (open) {@@ -1179,7 +1172,7 @@ export function UnifiedListView(props: UnifiedListViewProps) {});}}>- <ContextMenu.Trigger class="size-full">+ <ContextMenu.Trigger class="size-full unified-list-root"><UnifiedListComponententityListRef={setLocalEntityListRef}virtualizerHandle={setVirtualizerHandle}@@ -1283,8 +1276,21 @@ export function UnifiedListView(props: UnifiedListViewProps) {showDoneButton={displayDoneButton()}highlighted={highlightedSelector?.(innerProps.entity.id)}selected={- isPanelActive() && selectedSelector(innerProps.entity.id)+ isPanelActive() && focusedSelector(innerProps.entity.id)}+ checked={selectedSelector(innerProps.entity.id)}+ onChecked={(next) => {+ unifiedListContext.setViewDataStore(+ selectedView(),+ 'selectedEntities',+ (p) => {+ if (!next) {+ return p.filter((e) => e.id !== innerProps.entity.id);+ }+ return p.concat(innerProps.entity);+ }+ );+ }}/>);}}@@ -1322,91 +1328,61 @@ export function UnifiedListView(props: UnifiedListViewProps) {/><MenuSeparator /></Show>- <Show when={markEntityAsDone}>- {(fnAccessor) => {- const entityDisabled = (- entity: WithNotification<EntityData>- ) => {- return entity.type === 'email'- ? entity.done- : entity.notifications?.().every(({ done }) => done);- };- return (- <MenuItem- text="Mark as Done"- onClick={() => fnAccessor()(selectedEntity())}- disabled={entityDisabled(selectedEntity())}- />- );- }}- </Show>- <MenuItem- text="Delete"- onClick={() => deleteDssItem(selectedEntity())}- disabled={- selectedEntity().type !== 'document' &&- selectedEntity().type !== 'project' &&- selectedEntity().type !== 'chat'- }- />- <MenuItem- text="Rename"- onClick={() => openEntityModal('rename')}- disabled={- selectedEntity().type !== 'document' &&- selectedEntity().type !== 'chat'- }- />- <MenuItem- text="Move to Project"- onClick={() => {- openEntityModal('moveToProject');- }}- disabled={- selectedEntity().type !== 'document' &&- selectedEntity().type !== 'project' &&- selectedEntity().type !== 'chat'- }- />- <MenuItem- text="Copy"- onClick={() => {- copyDssItem({ entity: selectedEntity() });- }}- disabled={- selectedEntity().type !== 'document' &&- selectedEntity().type !== 'chat'- }- />- <MenuItem- text="Open in new split"- onClick={() => {- const splitManager = globalSplitManager();- if (!splitManager) {- console.error('No split manager available');- return;- }- const entity = selectedEntity();- if (entity.type === 'document') {- const { fileType, id } = entity;- splitManager.createNewSplit({- type: fileTypeToBlockName(fileType),- id,- });- } else {- const { id, type } = entity;- splitManager.createNewSplit({- type,- id,- });- }- }}+ <EntityActionsMenuItems+ entity={selectedEntity()}+ onSelectAction={() => {}}/></ContextMenuContent>)}</Show></ContextMenu.Portal></ContextMenu.Trigger>+ <Show when={view()?.selectedEntities.length}>+ <EntitySelectionToolbarModal+ selectedEntities={view()?.selectedEntities ?? []}+ onClose={() =>+ unifiedListContext.setViewDataStore(+ selectedView(),+ 'selectedEntities',+ []+ )+ }+ onAction={() => {+ const selectedEntities =+ viewsData[selectedView()].selectedEntities;+ const hasSelection = selectedEntities.length > 0;+ if (hasSelection) {+ setKonsoleMode('SELECTION_MODIFICATION');+ const selectionIndex =+ searchCategories.getCateoryIndex('Selection');++ if (selectionIndex === undefined) return false;++ setCommandCategoryIndex(selectionIndex);++ searchCategories.showCategory('Selection');++ setKonsoleContextInformation({+ selectedEntities: selectedEntities.slice(),+ clearSelection: () => {+ unifiedListContext.setViewDataStore(+ selectedView(),+ 'selectedEntities',+ []+ );+ },+ });++ toggleKonsoleVisibility();+ return true;+ }+ searchCategories.hideCategory('Selection');+ resetCommandCategoryIndex();+ resetKonsoleMode();+ return false;+ }}+ />+ </Show>{' '}</ContextMenu></>);@@ -1543,7 +1519,7 @@ function SearchBar(props: {keyDownHandler: () => {setTimeout(() => {const searchInput = document.getElementById(- `search-input-${selectedView()}`+ `search-input-${splitContext.handle.id}-${selectedView()}`) as HTMLInputElement;searchInput?.focus();}, 0);@@ -1569,7 +1545,7 @@ function SearchBar(props: {</Show><inputref={inputRef}- id={`search-input-${selectedView()}`}+ id={`search-input-${splitContext.handle.id}-${selectedView()}`}placeholder={`Search in ${viewName()}`}value={searchText()}onInput={(e) => {diff --git a/js/app/packages/app/component/ViewConfig.tsx b/js/app/packages/app/component/ViewConfig.tsxindex 74c0386cc0..26b008e0fb 100644--- a/js/app/packages/app/component/ViewConfig.tsx+++ b/js/app/packages/app/component/ViewConfig.tsx@@ -32,6 +32,7 @@ export type ViewData = {initialConfig: string | undefined;hasUserInteractedEntity: boolean;searchText: string | undefined;+ selectedEntities: EntityData[];} & ViewConfigBase;/** maps view id to view data */diff --git a/js/app/packages/app/component/bulk-edit-entity/BulkDeleteView.tsx b/js/app/packages/app/component/bulk-edit-entity/BulkDeleteView.tsxnew file mode 100644index 0000000000..cca1a5319c--- /dev/null+++ b/js/app/packages/app/component/bulk-edit-entity/BulkDeleteView.tsx@@ -0,0 +1,53 @@+import type { EntityData } from '@macro-entity';+import { createBulkDeleteDssItemsMutation } from '../../../macro-entity/src/queries/dss';+import { konsoleContextInformation } from '../command/KonsoleItem';+import {+ BulkEditEntityModalActionFooter,+ BulkEditEntityModalTitle,+} from './BulkEditEntityModal';++export const BulkDeleteView = (props: {+ entities: EntityData[];+ onFinish: () => void;+ onCancel: () => void;+}) => {+ const bulkDelete = createBulkDeleteDssItemsMutation();++ const handleDelete = async () => {+ try {+ await bulkDelete.mutateAsync(props.entities);++ const context = konsoleContextInformation();+ const clearSelection = context.clearSelection as (() => void) | undefined;+ clearSelection?.();+ props.onFinish();+ } catch (error) {+ console.error('Failed to delete entities:', error);+ }+ };++ const handleCancel = () => {+ props.onCancel();+ };++ return (+ <div class="w-full">+ <BulkEditEntityModalTitle title="Delete Items" />++ <div class="mb-4">+ <p class="text-ink-muted text-sm">+ {props.entities.length === 1+ ? `You are about to delete "${props.entities[0].name}".`+ : `You are about to delete ${props.entities.length} items.`}+ </p>+ <p class="text-ink-muted text-sm mt-2">This action cannot be undone.</p>+ </div>++ <BulkEditEntityModalActionFooter+ onCancel={handleCancel}+ onConfirm={handleDelete}+ confirmText="Delete"+ />+ </div>+ );+};diff --git a/js/app/packages/app/component/bulk-edit-entity/BulkEditEntityModal.tsx b/js/app/packages/app/component/bulk-edit-entity/BulkEditEntityModal.tsxnew file mode 100644index 0000000000..6b5c4da1c0--- /dev/null+++ b/js/app/packages/app/component/bulk-edit-entity/BulkEditEntityModal.tsx@@ -0,0 +1,162 @@+import { createControlledOpenSignal } from '@core/util/createControlledOpenSignal';+import { Dialog } from '@kobalte/core/dialog';+import type { EntityData } from '@macro-entity';+import {+ type Accessor,+ createSignal,+ type ParentComponent,+ type Setter,+ Show,+} from 'solid-js';+import { BulkDeleteView } from './BulkDeleteView';+import { BulkRenameEntitiesView } from './BulkRenameEntitiesView';++export const BulkEditEntityModalTitle = (props: { title: string }) => {+ return <h2 class="text-lg mb-3">{props.title}</h2>;+};++export const BulkEditEntityModalActionFooter = (props: {+ onCancel: () => void;+ onConfirm: () => void;+ confirmText: string;+ 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}>+ 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'+ }`}+ onClick={props.onConfirm}+ disabled={props.isDisabled}+ >+ {props.confirmText}+ </button>+ </div>+ );+};++const BulkEditEntityModalContent = (props: {+ isOpen: Accessor<boolean>;+ setIsOpen: Setter<boolean>;+ view: 'rename' | 'moveToProject' | 'delete' | null;+ entities: EntityData[];+ onFinish?: () => void;+}) => {+ const handleFinish = () => {+ props.setIsOpen(false);+ props.onFinish?.();+ };+ const handleCancel = () => {+ props.setIsOpen(false);+ };++ return (+ <Dialog open={props.isOpen()} onOpenChange={props.setIsOpen} 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="w-full my-1">+ <Show when={props.view === 'rename'}>+ <BulkRenameEntitiesView+ entities={props.entities}+ onFinish={handleFinish}+ onCancel={handleCancel}+ />+ </Show>+ <Show when={props.view === 'moveToProject'}>+ {/* <MoveToProjectView */}+ {/* entity={props.entity!} */}+ {/* onFinish={handleFinish} */}+ {/* onCancel={handleCancel} */}+ {/* /> */}+ <div />+ </Show>+ <Show when={props.view === 'delete'}>+ <BulkDeleteView+ entities={props.entities}+ onFinish={handleFinish}+ onCancel={handleCancel}+ />+ </Show>+ </div>+ </div>+ </Dialog.Content>+ </div>+ </Dialog.Portal>+ </Dialog>+ );+};++export type BulkEditEntityModalProps = {+ isOpen: Accessor<boolean>;+ setIsOpen: Setter<boolean>;+ view: 'rename' | 'moveToProject' | 'delete';+ entities: Accessor<EntityData[]>;+};++export const BulkEditEntityModal: ParentComponent<BulkEditEntityModalProps> = (+ props+) => {+ return (+ <Show when={props.isOpen()}>+ <BulkEditEntityModalContent+ isOpen={props.isOpen}+ setIsOpen={props.setIsOpen}+ view={props.view}+ entities={props.entities()}+ />+ </Show>+ );+};++// Global modal state+const [globalModalProps, setGlobalModalProps] = createSignal<{+ view: 'rename' | 'moveToProject' | 'delete';+ entities: EntityData[];+ onFinish?: () => void;+} | null>(null);+const [modalOpen, setModalOpen] = createControlledOpenSignal();++// Global modal open function+export const openBulkEditModal = (props: {+ view: 'rename' | 'moveToProject' | 'delete';+ entities: EntityData[];+ onFinish?: () => void;+}) => {+ setModalOpen(true);+ setGlobalModalProps(props);+};++export const GlobalBulkEditEntityModal = () => {+ const modalProps = () => globalModalProps();++ const handleFinish = () => {+ const props = globalModalProps();+ setGlobalModalProps(null);+ if (props?.onFinish) {+ props.onFinish();+ }+ };++ return (+ <Show when={modalProps()}>+ {(props) => (+ <BulkEditEntityModalContent+ isOpen={modalOpen}+ setIsOpen={setModalOpen}+ view={props().view}+ entities={props().entities}+ onFinish={handleFinish}+ />+ )}+ </Show>+ );+};diff --git a/js/app/packages/app/component/bulk-edit-entity/BulkRenameEntitiesView.tsx b/js/app/packages/app/component/bulk-edit-entity/BulkRenameEntitiesView.tsxnew file mode 100644index 0000000000..6a126d7fe9--- /dev/null+++ b/js/app/packages/app/component/bulk-edit-entity/BulkRenameEntitiesView.tsx@@ -0,0 +1,81 @@+import type { EntityData } from '@macro-entity';+import { createSignal, onMount } from 'solid-js';+import { createBulkRenameDssEntityMutation } from '../../../macro-entity/src/queries/dss';+import {+ BulkEditEntityModalActionFooter,+ BulkEditEntityModalTitle,+} from './BulkEditEntityModal';++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()));++ if (noDupes.size > 1) return '';++ return Array.from(noDupes)[0] ?? '';+ };++ const [editValue, setEditValue] = createSignal(commonInitName());++ const handleKeyDown = (e: KeyboardEvent) => {+ if (e.key === 'Enter') {+ e.preventDefault();+ finishEditing();+ } else if (e.key === 'Escape') {+ e.preventDefault();+ props.onCancel();+ }+ };++ const finishEditing = async () => {+ const newValue = editValue().trim();++ if (newValue) {+ // Todo - Bulk rename+ await renameMutation.mutateAsync({+ entities: props.entities,+ newName: newValue,+ });+ }++ props.onFinish();+ };++ return (+ <div class="w-full">+ <BulkEditEntityModalTitle title="Rename" />+ <div class="w-full focus-within:bracket-offset-2">+ <input+ ref={(el) => {+ inputRef = el;+ onMount(() => {+ // it needs to focus on next task, no idea why+ setTimeout(() => {+ inputRef?.focus();+ inputRef?.select();+ });+ });+ }}+ 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..."+ />+ </div>++ <BulkEditEntityModalActionFooter+ onCancel={props.onCancel}+ onConfirm={finishEditing}+ confirmText="Rename"+ />+ </div>+ );+};diff --git a/js/app/packages/app/component/bulk-edit-entity/MoveToProjectView.tsx b/js/app/packages/app/component/bulk-edit-entity/MoveToProjectView.tsxnew file mode 100644index 0000000000..ad46316139--- /dev/null+++ b/js/app/packages/app/component/bulk-edit-entity/MoveToProjectView.tsx@@ -0,0 +1,555 @@+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/app/component/command/Konsole.tsx b/js/app/packages/app/component/command/Konsole.tsxindex 1835547e16..da98e4a061 100644--- a/js/app/packages/app/component/command/Konsole.tsx+++ b/js/app/packages/app/component/command/Konsole.tsx@@ -79,7 +79,7 @@ export function KommandMenu() {const CommandWindow = (props: { children?: JSXElement }) => {return (<div- class="z-50 fixed inset-0 flex flex-row justify-center items-center bg-modal-overlay"+ class="z-50 fixed inset-0 flex flex-row justify-center items-center bg-modal-overlay pattern-edge-muted pattern-diagonal-4"ref={setCommandKRef}>{props.children}diff --git a/js/app/packages/app/component/command/KonsoleFilter.tsx b/js/app/packages/app/component/command/KonsoleFilter.tsxindex 5ae5149146..1adf5527d9 100644--- a/js/app/packages/app/component/command/KonsoleFilter.tsx+++ b/js/app/packages/app/component/command/KonsoleFilter.tsx@@ -9,10 +9,10 @@ import {} from 'solid-js';import {commandCategoryIndex,- SEARCH_CATEGORY,+ searchCategories,setCommandCategoryIndex,} from './KonsoleItem';-import { currentKonsoleMode, konsoleOpen } from './state';+import { konsoleOpen } from './state';export function KonsoleFilter() {const [containerRef, setContainerRef] = createSignal<HTMLDivElement>();@@ -27,9 +27,15 @@ export function KonsoleFilter() {setCommandCategoryIndex((prev) => {let nextCategoryIndex = -1;if (e.shiftKey) {- nextCategoryIndex = findNextCategoryIndex(prev, true);+ nextCategoryIndex = searchCategories.findNextCategoryIndex(+ prev,+ true+ );} else {- nextCategoryIndex = findNextCategoryIndex(prev, false);+ nextCategoryIndex = searchCategories.findNextCategoryIndex(+ prev,+ false+ );}return Math.max(nextCategoryIndex, 0);});@@ -42,46 +48,6 @@ export function KonsoleFilter() {});});- function isCategoryActive(category: number): boolean {- if (SEARCH_CATEGORY[category] === 'Emails') {- // only use emails for the search bar- if (currentKonsoleMode() !== 'FULL_TEXT_SEARCH') return false;-- // TODO only show emails if they are enabled- // NOTE: this also seems to trigger a "computations created outside a 'createRoot' will never be disposed error- //const emailActive = useEmailActive();- const emailEnabled = () => {- // TODO: this causes a loop- //if (emailActive()?.link_exists) return true;- return true;- };- return emailEnabled();- }- return true;- }-- function findNextCategoryIndex(category: number, backwards: boolean): number {- let candidateCategory = -1;- for (let i = 1; i < SEARCH_CATEGORY.length; i++) {- if (backwards) {- candidateCategory = category - i;- } else {- candidateCategory = category + i;- }-- // Perform wrap-around- if (candidateCategory >= SEARCH_CATEGORY.length) {- candidateCategory = 0;- } else if (candidateCategory < 0) {- candidateCategory = SEARCH_CATEGORY.length + candidateCategory;- }-- if (isCategoryActive(candidateCategory)) break;- candidateCategory = -1;- }- return candidateCategory;- }-// Scroll selected category into view when selection changescreateEffect(() => {const container = containerRef();@@ -121,9 +87,9 @@ export function KonsoleFilter() {ref={setContainerRef}class="flex pb-4 overflow-x-auto scrollbar-hidden bg-transparent">- <For each={SEARCH_CATEGORY}>+ <For each={searchCategories.listVisible()}>{(item, index) => (- <Show when={isCategoryActive(index())}>+ <Show when={searchCategories.isCategoryActive(index())}><TextButtonref={(el) => {if (el) buttonRefs[index()] = el;@@ -131,7 +97,7 @@ export function KonsoleFilter() {theme={index() === commandCategoryIndex() ? 'accentFill' : 'clear'}- text={item}+ text={item.name}onMouseDown={() => setCommandCategoryIndex(index())}class="flex-shrink-0 h-auto *:h-7 *:px-2"/>diff --git a/js/app/packages/app/component/command/KonsoleItem.tsx b/js/app/packages/app/component/command/KonsoleItem.tsxindex d3fb6574f2..5497f00e8a 100644--- a/js/app/packages/app/component/command/KonsoleItem.tsx+++ b/js/app/packages/app/component/command/KonsoleItem.tsx@@ -41,11 +41,13 @@ import {type Setter,Switch,} from 'solid-js';+import { createStore } from 'solid-js/store';import { useGlobalBlockOrchestrator } from '../GlobalAppState';import { useSplitLayout } from '../split-layout/layout';import { EmailCommandItem } from './EmailKonsoleItem';import {cleanQuery,+ currentKonsoleMode,resetKonsoleMode,resetQuery,setKonsoleOpen,@@ -71,6 +73,10 @@ export function createChannelLookup(channelsContext: ChannelsContext) {});}+// Context information for actions and stuff+export const [konsoleContextInformation, setKonsoleContextInformation] =+ createSignal<Record<string, unknown>>({});+// TODO: better naming?export function hydrateChannel(item: CommandItemCard,@@ -88,17 +94,107 @@ export function hydrateChannel(return item;}-export const SEARCH_CATEGORY = [- 'Everything',- 'Channels',- 'DMs',- 'Notes',- 'Documents',- 'Chats',- 'Folders',- 'Emails',- ...(ENABLE_GMAIL_BASED_CONTACTS ? ['Contacts', 'Companies'] : []),-];+const DEFAULT_CATEGORIES = [+ { name: 'Selection', visible: false },+ { name: 'Everything', visible: true },+ { name: 'Channels', visible: true },+ { name: 'DMs', visible: true },+ { name: 'Notes', visible: true },+ { name: 'Documents', visible: true },+ { name: 'Chats', visible: true },+ { name: 'Folders', visible: true },+ { name: 'Emails', visible: true },+ { name: 'Contacts', visible: ENABLE_GMAIL_BASED_CONTACTS },+ { name: 'Companies', visible: ENABLE_GMAIL_BASED_CONTACTS },+] as const;++type DefaultCategoryNames = (typeof DEFAULT_CATEGORIES)[number]['name'];++type KonsoleCategory = {+ name: string;+ visible: boolean;+};++const [categories, setCategories] = createStore<KonsoleCategory[]>(+ DEFAULT_CATEGORIES.slice()+);++export const searchCategories = {+ getCateoryIndex(name: DefaultCategoryNames | (string & {})) {+ const index = categories.findIndex((c) => c.name === name);++ if (index === -1) return;++ return index;+ },+ hideCategory(name: DefaultCategoryNames | (string & {})) {+ setCategories((p) => p.name === name, 'visible', false);+ },+ showCategory(name: DefaultCategoryNames | (string & {})) {+ setCategories((p) => p.name === name, 'visible', true);+ },+ toggleCategory(name: DefaultCategoryNames | (string & {})) {+ setCategories(+ (p) => p.name === name,+ 'visible',+ (p) => !p+ );+ },+ isCategoryActive(index: number) {+ if (categories[index].name === 'Emails') {+ // only use emails for the search bar+ if (currentKonsoleMode() !== 'FULL_TEXT_SEARCH') return false;++ // TODO only show emails if they are enabled+ // NOTE: this also seems to trigger a "computations created outside a 'createRoot' will never be disposed error+ //const emailActive = useEmailActive();+ const emailEnabled = () => {+ // TODO: this causes a loop+ //if (emailActive()?.link_exists) return true;+ return true;+ };+ return emailEnabled();+ }+ return true;+ },+ findNextCategoryIndex(category: number, backwards: boolean): number {+ let candidateCategory = -1;+ const length = categories.length;+ for (let i = 1; i < length; i++) {+ if (backwards) {+ candidateCategory = category - i;+ } else {+ candidateCategory = category + i;+ }++ // Perform wrap-around+ if (candidateCategory >= length) {+ candidateCategory = 0;+ } else if (candidateCategory < 0) {+ candidateCategory = length + candidateCategory;+ }++ if (this.isCategoryActive(candidateCategory)) break;+ candidateCategory = -1;+ }+ return candidateCategory;+ },+ listVisible() {+ return [...categories.filter((c) => c.visible)];+ },+ listAll() {+ return [...categories];+ },+};++export const resetCommandCategoryIndex = () => {+ const everything = DEFAULT_CATEGORIES[1].name;+ const indexOfEverything = searchCategories+ .listVisible()+ .findIndex((c) => c.name === everything);++ setCommandCategoryIndex(indexOfEverything === -1 ? 0 : indexOfEverything);+};export type SearchSnippet = {content: string;@@ -164,6 +260,7 @@ export type CommandPreview = {hotkeys: ValidHotkey[];handler: (e: KeyboardEvent) => boolean;activateCommandScopeId?: string;+ tags?: string[];};export type ChannelPreview = {@@ -264,7 +361,6 @@ export function useCommandItemAction(args: {const blockName = getCommandItemBlockName(item);const id = item.data.id;const split = action === 'new-split' ? insertSplit : replaceSplit;- console.log('GO TO LOCATION', id);if (blockName) {split({ type: blockName, id });@@ -290,7 +386,6 @@ export function useCommandItemAction(args: {limitToCurrentScope: true,});- console.log(commandScopeCommands);resetQuery();setCommandScopeCommands(commandScopeCommands);break;@@ -345,15 +440,30 @@ function getCommandItemName(item: CommandItemCard): string {}export function filterItemByCategory(item: CommandItemCard) {+ const categories = searchCategories.listVisible();+ const category = categories[commandCategoryIndex()].name;+// This should appear at the bottom of every category, if there are more items that need to be loadedif (item.type === 'loadmore') {return true;}++ if (category === 'Selection') {+ if (+ currentKonsoleMode() === 'SELECTION_MODIFICATION' &&+ item.type === 'command'+ ) {+ return item.data.tags?.includes('selection-modification');+ }+ return false;+ }+// Action items should always appear in the "Everything" categoryif (item.type === 'command') {- return SEARCH_CATEGORY[commandCategoryIndex()] === 'Everything';+ return category === 'Everything';}- switch (SEARCH_CATEGORY[commandCategoryIndex()]) {++ switch (category) {case 'Channels':return (item.type === 'channel' &&diff --git a/js/app/packages/app/component/command/state.ts b/js/app/packages/app/component/command/state.tsindex d9fe37b0a2..cd7dff418d 100644--- a/js/app/packages/app/component/command/state.ts+++ b/js/app/packages/app/component/command/state.ts@@ -40,6 +40,7 @@ export const COMMAND_MODES = [// { id: "REGEX_SEARCH", sigil: "/", label: "Regex Search" },// { id: "RUN_COMMAND", sigil: ">", label: "Run" },// { id: "TEMP_CHAT", sigil: " ", label: "Temporary Chat" },+ { id: 'SELECTION_MODIFICATION', sigil: '', label: 'Modify selection' },];export const DEFAULT_MODE = {id: 'ENTITY_SEARCH',diff --git a/js/app/packages/app/component/command/useCommandItems.ts b/js/app/packages/app/component/command/useCommandItems.tsindex 2ff22da0a4..50b427cfae 100644--- a/js/app/packages/app/component/command/useCommandItems.ts+++ b/js/app/packages/app/component/command/useCommandItems.ts@@ -51,6 +51,7 @@ export function useCommandItems() {hotkeys: command.hotkeys ?? [],handler: command.keyDownHandler ?? (() => false),activateCommandScopeId: command.activateCommandScopeId,+ tags: command.tags ?? [],},updatedAt: 0,};diff --git a/js/app/packages/app/component/command/useCommandItems.ts.rej b/js/app/packages/app/component/command/useCommandItems.ts.rejnew file mode 100644index 0000000000..f85f58e238--- /dev/null+++ b/js/app/packages/app/component/command/useCommandItems.ts.rej@@ -0,0 +1,11 @@+diff a/js/app/packages/app/component/command/useCommandItems.ts b/js/app/packages/app/component/command/useCommandItems.ts (rejected hunks)+@@ -31,6 +32,9 @@ export function useCommandItems() {+ const channelsContext = useChannelsContext();+ const channels = () => channelsContext.channels();+ const contactItems = useEmailContacts();++++ const entityActionItems = useEntityActionItems();+++ const activeScope = activeScopeStack().at(-1) ?? 'global';+ const activeCommands = getActiveCommandsFromScope(activeScope, {+ sortByScopeLevel: false,diff --git a/js/app/packages/app/component/settings/AiMemory/component/CreateMemory.tsx b/js/app/packages/app/component/settings/AiMemory/component/CreateMemory.tsxindex 73b32375ca..e6e1da264b 100644--- a/js/app/packages/app/component/settings/AiMemory/component/CreateMemory.tsx+++ b/js/app/packages/app/component/settings/AiMemory/component/CreateMemory.tsx@@ -1,6 +1,6 @@import { TextButton } from '@core/component/TextButton';import clickOutside from '@core/directive/clickOutside';-import CheckIcon from '@icon/regular/check.svg';+import CheckIcon from '@icon/bold/check-bold.svg';import XIcon from '@icon/regular/x.svg';import { createSignal, onCleanup, onMount } from 'solid-js';import { creatingMemory, useCreateUserMemory } from '../signal';@@ -69,7 +69,7 @@ export function CreateMemory() {contentEditable="plaintext-only"/><div- class={` ${visible() ? 'opacity-50' : 'opacity-0'}+ class={` ${visible() ? 'opacity-50' : 'opacity-0'}absolute left-2transition-opacity duration-300 ease-in-out select-none ${value() ? 'hidden' : ''}`}diff --git a/js/app/packages/app/component/split-layout/SplitLayout.tsx b/js/app/packages/app/component/split-layout/SplitLayout.tsxindex d49c06ad79..dcf717d9fa 100644--- a/js/app/packages/app/component/split-layout/SplitLayout.tsx+++ b/js/app/packages/app/component/split-layout/SplitLayout.tsx@@ -416,6 +416,7 @@ function SplitPanel(props: SplitPanelProps) {});const unifiedListContext = createSoupContext();+createNavigationEntityListShortcut({splitName,splitHandle: props.handle,diff --git a/js/app/packages/app/component/split-layout/components/SplitFileMenu.tsx b/js/app/packages/app/component/split-layout/components/SplitFileMenu.tsxindex 5a8f05cfb9..3bdebf02e6 100644--- a/js/app/packages/app/component/split-layout/components/SplitFileMenu.tsx+++ b/js/app/packages/app/component/split-layout/components/SplitFileMenu.tsx@@ -96,6 +96,7 @@ export function SplitFileMenu(props: {};case 'delete':+ if (!isOwner()) return null;return {label: 'Delete',action: async () => {@@ -156,6 +157,7 @@ export function SplitFileMenu(props: {};case 'moveToProject':+ if (!isOwner()) return null;return {label: 'Move to Folder',action: () => {diff --git a/js/app/packages/app/index.css b/js/app/packages/app/index.cssindex 57e1b13f9b..8f226d5dd5 100644--- a/js/app/packages/app/index.css+++ b/js/app/packages/app/index.css@@ -694,6 +694,11 @@ html[data-modality="keyboard"] [contenteditable="true"]:focus-visible::after {--pattern-color: color-mix(in srgb, var(--color-overlay), var(--color-ink) 2%);}+@utility bg-modal-overlay-konsole {+ background-color: var(--color-overlay);+ background-image: linear-gradient(rgba(from var(--color-accent) r g b / 0.1) 0%, transparent 25%);+}+@utility portal-scope {--documentation: "Set this element as a bounding scope for the ScopedPortal component";}diff --git a/js/app/packages/core/component/FileList/itemOperations.ts b/js/app/packages/core/component/FileList/itemOperations.tsindex 4e36df8631..207331e566 100644--- a/js/app/packages/core/component/FileList/itemOperations.ts+++ b/js/app/packages/core/component/FileList/itemOperations.ts@@ -64,8 +64,9 @@ export async function renameItem(args: {itemType: ItemType;id: string;newName: string;+ skipRefetch?: boolean;}): Promise<boolean> {- const { itemType, id, newName } = args;+ const { itemType, id, newName, skipRefetch = false } = args;let result;@@ -100,7 +101,9 @@ export async function renameItem(args: {return false;}- refetchResources();+ if (!skipRefetch) {+ refetchResources();+ }return true;}@@ -186,6 +189,43 @@ 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.tsindex 8465d4714f..bb7a4c59e3 100644--- a/js/app/packages/core/component/FileList/useItemOperations.ts+++ b/js/app/packages/core/component/FileList/useItemOperations.ts@@ -14,6 +14,7 @@ import {bulkDelete as bulkDeleteOp,bulkMoveToFolder as bulkMoveToFolderOp,bulkPermanentlyDelete as bulkPermanentlyDeleteOp,+ bulkRename as bulkRenameOp,bulkRevertDelete as bulkRevertDeleteOp,bulkTogglePin as bulkTogglePinOp,copyItem as copyItemOp,@@ -238,6 +239,25 @@ 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) =>+ `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'}...`,@@ -265,6 +285,7 @@ export const useItemOperations = createSingletonRoot(() => {bulkDelete,bulkCopy,bulkMoveToFolder,+ bulkRename,getItemAccessLevel,revertDelete,permanentlyDelete,diff --git a/js/app/packages/core/hotkey/hotkeys.ts b/js/app/packages/core/hotkey/hotkeys.tsindex 6657f2d298..7b78f9fe2e 100644--- a/js/app/packages/core/hotkey/hotkeys.ts+++ b/js/app/packages/core/hotkey/hotkeys.ts@@ -80,6 +80,8 @@ import {* hotkey display UI. 1 is the lowest priority, 10 is the highest.* @param args.hide - If true, hotkey command can be hidden from the UI. It* will still run, but may not be displayed.+ * @param args.icon - Optional icon to display in the command palette.+ * @param args.tags - Optional tags for categorizing in the command palette.* @returns An object with a dispose function to clean up the hotkey* registration. If `activateCommandScope` is true, it also includes the* `commandScopeId`.@@ -117,6 +119,7 @@ export function registerHotkey(displayPriority,hide,icon,+ tags,} = args;``;@@ -189,6 +192,7 @@ export function registerHotkey(displayPriority: displayPriority ?? 0,hide,icon,+ tags,};// Check for existing hotkeys in the scopediff --git a/js/app/packages/core/hotkey/types.ts b/js/app/packages/core/hotkey/types.tsindex 2acee1ffe4..c924f5fe08 100644--- a/js/app/packages/core/hotkey/types.ts+++ b/js/app/packages/core/hotkey/types.ts@@ -24,6 +24,8 @@ export interface HotkeyCommand {hide?: boolean;// Optional icon to display in the command palette.icon?: Component<JSX.SvgSVGAttributes<SVGSVGElement>>;+ // Optional tags for categorizing in the command palette.+ tags?: string[];}export interface HotkeyRegistrationOptions {@@ -99,6 +101,10 @@ export interface HotkeyRegistrationOptions {* Optional icon to display in the command palette.*/icon?: Component<JSX.SvgSVGAttributes<SVGSVGElement>>;+ /**+ * Optional tags for categorizing in the command palette.+ */+ tags?: string[];}export type RegisterHotkeyReturn = {diff --git a/js/app/packages/core/util/list.ts b/js/app/packages/core/util/list.tsindex c4851423af..7268afd3a1 100644--- a/js/app/packages/core/util/list.ts+++ b/js/app/packages/core/util/list.ts@@ -28,3 +28,11 @@ export async function filterMapAsync<T, U>(return results;}++export function intersection<T>(+ a: T[],+ b: T[],+ equal: (a: T, b: T) => boolean+): T[] {+ return a.filter((item) => b.some((other) => equal(item, other)));+}diff --git a/js/app/packages/macro-entity/src/components/EntityWithEverything.tsx b/js/app/packages/macro-entity/src/components/EntityWithEverything.tsxindex 68ffbf1ef8..d71b1b83b9 100644--- a/js/app/packages/macro-entity/src/components/EntityWithEverything.tsx+++ b/js/app/packages/macro-entity/src/components/EntityWithEverything.tsx@@ -20,7 +20,6 @@ import {Suspense,} from 'solid-js';import { Dynamic } from 'solid-js/web';-import { ITEM_WRAPPER } from '../constants/classStrings';import { createProfilePictureQuery } from '../queries/auth';import {createProjectQuery,@@ -34,14 +33,16 @@ import type { EntityClickHandler } from './Entity';function UnreadIndicator(props: { active?: boolean }) {return (- <div class="flex min-w-5 items-center justify-center">+ <div class="flex size-4 items-center justify-center"><svgxmlns="http://www.w3.org/2000/svg"classList={{- 'flex size-[10px] fill-accent': true,+ 'fill-accent': true,'opacity-0': !props.active,}}viewBox="0 0 8 8"+ width="75%"+ height="75%"fill="none"><path d="M3.39622 8C3.29136 8 3.23894 7.94953 3.23894 7.84858L3.33068 5.13565L0.932129 6.58675C0.836012 6.63722 0.76174 6.6204 0.709312 6.53628L0.0801831 5.56467C0.0190178 5.47213 0.0364936 5.40063 0.132611 5.35016L2.58359 4.07571L0.09329 2.88959C-0.00282696 2.83912 -0.0246717 2.77182 0.0277557 2.6877L0.59135 1.58991C0.643778 1.49737 0.71805 1.47634 0.814167 1.52681L3.31758 2.95268L3.21272 0.151421C3.21272 0.0504735 3.26515 0 3.37 0H4.57583C4.68069 0 4.73312 0.0504735 4.73312 0.151421L4.64137 2.94006L7.14478 1.40063C7.2409 1.34175 7.3108 1.35857 7.35449 1.4511L7.97051 2.46057C8.02294 2.5531 8.00546 2.6204 7.91808 2.66246L5.40157 4L7.82633 5.18612C7.91371 5.23659 7.93556 5.30389 7.89187 5.38801L7.36759 6.4858C7.32391 6.58675 7.25837 6.60778 7.17099 6.54889L4.6938 5.13565L4.78554 7.84858C4.79428 7.94953 4.74185 8 4.62826 8H3.39622Z" />@@ -53,7 +54,7 @@ function UnreadIndicator(props: { active?: boolean }) {function ImportantBadge(props: { active?: boolean }) {return (<Show when={props.active}>- <div class="font-mono user-select-none uppercase flex items-center text-accent bg-accent/10 p-0.5 px-2 text-[0.625rem] rounded-full border border-accent/10">+ <div class="font-mono font-medium user-select-none uppercase flex items-center text-accent bg-accent/10 p-0.5 px-2 text-[0.625rem] rounded-full border border-accent/10"><span class="@max-xl/split:hidden">Important</span><span class="hidden @max-xl/split:block font-bold">!</span></div>@@ -84,12 +85,15 @@ interface EntityProps<T extends WithNotification<EntityData>>highlighted?: boolean;selected?: boolean;ref?: Ref<HTMLDivElement>;+ onChecked?: (checked: boolean) => void;+ checked?: boolean;}export function EntityWithEverything(props: EntityProps<WithNotification<EntityData | WithSearch<EntityData>>>) {const [showActionList, setShowActionList] = createSignal(false);+ const [entityHovered, setEntityHovered] = createSignal(false);const [actionButtonRef, setActionButtonRef] =createSignal<HTMLButtonElement | null>(null);const [showRestOfNotifications, setShowRestOfNotifications] =@@ -132,10 +136,10 @@ export function EntityWithEverything(const hasNotifications = () =>!!props.entity.notifications && props.entity.notifications().length > 0;- const threadGap = 10;+ const threadGap = 6;const ThreadBorder = () => (<div- class="absolute left-[9.5px] border-[0.5px] border-edge -top-1/2 "+ class="absolute left-[calc(0.5rem+1px)] w-[1px] border-l border-edge-muted -top-0.75"style={{ height: `${threadGap}px` }}/>);@@ -204,7 +208,7 @@ export function EntityWithEverything(};return (- <div class="flex gap-2 items-center text-sm min-w-0 w-full truncate overflow-hidden">+ <div class="flex gap-1 items-center text-sm min-w-0 w-full truncate overflow-hidden">{/* sometimes senderName and senderEmail are the same */}<div class="flex w-[20cqw] gap-2 font-semibold shrink-0">{/* Sender Name */}@@ -270,7 +274,7 @@ export function EntityWithEverything(return (<div class="flex gap-2 items-center min-w-0 w-fit max-w-full overflow-hidden">- <span class="flex gap-2 truncate font-medium text-sm shrink-0 items-center">+ <span class="flex gap-1 truncate font-medium text-sm shrink-0 items-center"><spanclass="font-semibold truncate"classList={{@@ -295,33 +299,36 @@ export function EntityWithEverything(!isDirectMessage()}>- <ImportantBadge active={props.importantIndicatorActive} />- <span class="inline-block">- <span class="text-ink">{userName()}</span>- </span>+ <div class="flex items-center gap-1">+ <ImportantBadge active={props.importantIndicatorActive} />+ <span class="inline-block">+ <span class="text-ink">{userName()}</span>+ </span>+ </div></Show>- </span>- <Show- when={!props.showUnrollNotifications && notificationMessageContent()}- >- {(messageContent) => (- <div class="text-sm truncate line-clamp-1 leading-none shrink text-ink-extra-muted py-1">- <StaticMarkdown- markdown={messageContent()}- theme={unifiedListMarkdownTheme}- singleLine={false}- />- </div>- )}- </Show>+ <Show+ when={+ !props.showUnrollNotifications && notificationMessageContent()+ }+ >+ {(messageContent) => (+ <div class="text-sm truncate line-clamp-1 leading-none shrink text-ink-extra-muted py-1">+ <StaticMarkdown+ markdown={messageContent()}+ theme={unifiedListMarkdownTheme}+ singleLine={false}+ />+ </div>+ )}+ </Show>+ </span></div>);};const draggable = createDraggable(props.entity.id, props.entity);false && draggable;-const droppable = createDroppable(props.entity.id, props.entity);false && droppable;@@ -339,22 +346,26 @@ export function EntityWithEverything(<divuse:draggableuse:droppable- class={`relative group py-[5px] px-2 ${ITEM_WRAPPER_CLASS()}`}+ data-checked={props.checked}+ class="everything-entity relative group/entity"classList={{- 'bg-hover': props.highlighted,- bracket: props.selected,- 'bg-hover ring-1 ring-inset ring-edge-muted': props.selected,+ 'bg-hover/30': props.highlighted && !props.checked,+ 'bg-accent/5': props.checked,+ 'bracket outline outline-accent/20 outline-offset-[-1px]':+ props.selected,}}onMouseOver={(e) => {if (!didCursorMove(e)) {return;}-setShowActionList(true);-props.onMouseOver?.();}}+ onMouseEnter={() => {+ setEntityHovered(true);+ }}onMouseLeave={() => {+ setEntityHovered(false);setShowActionList(false);}}onFocusIn={() => {@@ -374,12 +385,7 @@ export function EntityWithEverything(<divdata-entitydata-entity-id={props.entity.id}- // class="@md:flex grid w-full min-w-0 flex-1 grid-cols-2 @md:flex-row @md:items-center @md:gap-4"- class="min-h-[40px] grid w-full min-w-0 flex-1 gap-2 grid-rows-1 @md:items-center suppress-css-bracket"- classList={{- 'grid-cols-[auto_1fr_auto]': props.showLeftColumnIndicator,- 'grid-cols-[1fr_auto]': !props.showLeftColumnIndicator,- }}+ class="w-full min-w-0 grid flex-1 items-center suppress-css-bracket grid-cols-[2rem_1fr_auto] pr-2"{...navHandlers()}// Action List is also rendered based on focus, but when focused via Shift+Tab, parent is focused due to Action List dom not present. Here we check if current browser task has captured Shift+Tab focus on Action ListonFocusIn={(e) => {@@ -403,13 +409,36 @@ export function EntityWithEverything(tabIndex={0}ref={props.ref}>+ <button+ type="button"+ class="col-1 size-full relative group/button flex items-center justify-center"+ onClick={(e) => {+ e.stopPropagation();+ props.onChecked?.(!props.checked);+ }}+ >+ <div+ class="size-4 p-0.5 flex items-center justify-center rounded-xs group-hover/button:border-accent group-hover/button:border"+ classList={{+ 'ring ring-edge-muted': props.selected || entityHovered(),+ 'bg-panel': !props.checked && (props.selected || entityHovered()),+ 'bg-accent border border-accent': props.checked,+ }}+ >+ <Show when={props.checked}>+ <CheckIcon class="w-full h-full text-panel" />+ </Show>+ </div>+ <Show when={props.showLeftColumnIndicator && !props.checked}>+ <div class="absolute inset-0 flex items-center justify-center -z-1">+ <UnreadIndicator active={props.unreadIndicatorActive} />+ </div>+ </Show>+ </button>{/* Left Column Indicator(s) */}- <Show when={props.showLeftColumnIndicator}>- <UnreadIndicator active={props.unreadIndicatorActive} />- </Show>{/* Icon and name - top left on mobile, first item on desktop */}<div- class="min-h-[40px] min-w-[50px] flex flex-row items-center gap-2"+ class="min-h-10 min-w-[50px] flex flex-row items-center gap-2 col-2"classList={{grow: props.contentPlacement === 'bottom-row','opacity-70': props.fadeIfRead && !props.unreadIndicatorActive,@@ -425,10 +454,8 @@ export function EntityWithEverything(</div>{/* Date and user - top right on mobile, end on desktop */}<div- class="relative row-1 ml-2 @md:ml-4 self-center min-w-0"+ class="relative row-1 ml-2 @md:ml-4 self-center min-w-0 col-3"classList={{- 'col-3': props.showLeftColumnIndicator,- 'col-2': !props.showLeftColumnIndicator,'opacity-50': props.fadeIfRead && !props.unreadIndicatorActive,}}>@@ -466,13 +493,7 @@ export function EntityWithEverything(</div>{/* Content Highlights from Search */}<Show when={contentHighlights().length > 0}>- <div- class="relative row-2 grid gap-2"- classList={{- 'col-[2/-1]': props.showLeftColumnIndicator,- 'col-[1/-1]': !props.showLeftColumnIndicator,- }}- >+ <div class="relative row-2 grid gap-2 col-2 col-end-4 pb-2"><For each={contentHighlights()}>{(highlight) => (<div class="text-sm text-ink-muted truncate">@@ -487,17 +508,14 @@ export function EntityWithEverything(</div></Show>{/* Notifications */}- <Show when={props.showUnrollNotifications && hasNotifications()}>- <div- class="relative row-2 col-[2/-1] grid"- classList={{- 'col-[2/-1]': props.showLeftColumnIndicator,- 'col-[1/-1]': !props.showLeftColumnIndicator,- }}- style={{- gap: `${threadGap}px`,- }}- >+ <Show+ when={+ props.showUnrollNotifications &&+ hasNotifications() &&+ contentHighlights().length === 0+ }+ >+ <div class="relative col-2 col-end-4 200 pb-2 gap-2"><For each={notDoneNotifications()}>{(notification) => {const [userName] = useDisplayName(notification.senderId);@@ -560,7 +578,7 @@ export function EntityWithEverything(return (<div- class="relative flex gap-1 items-center min-w-0 h-5"+ class="relative flex gap-1 items-center min-w-0 h-7"classList={{'hover:bg-hover/20 hover:opacity-70':!!props.onClickNotification,@@ -600,7 +618,7 @@ export function EntityWithEverything(<MessageContent /></div></div>- <div class="shrink-0 font-mono text-sm uppercase text-ink-extra-muted ml-2 @md:ml-4">+ <div class="shrink-0 font-mono text-xs uppercase text-ink-extra-muted ml-2">{formattedDate()}</div></div>@@ -763,22 +781,6 @@ const createFormattedDate = (timestamp: number) =>});});-const ITEM_WRAPPER_CLASS = () => {- let input = ITEM_WRAPPER;- const excludeclasses = [- 'focus-bracket-within',- 'suppress-css-brackets',- 'focus-within:bg-hover',- 'hover:bg-hover',- ];- excludeclasses.forEach((pattern) => {- input = input.replace(new RegExp(pattern, 'g'), '');- });-- // Optional: clean up extra spaces- input = input.replace(/\s+/g, ' ').trim();-};-let lastMouseX: number | null = null;let lastMouseY: number | null = null;let initialMouseMove: boolean = false;diff --git a/js/app/packages/macro-entity/src/queries/dss.ts b/js/app/packages/macro-entity/src/queries/dss.tsindex 894d621d5d..3c0380cec7 100644--- a/js/app/packages/macro-entity/src/queries/dss.ts+++ b/js/app/packages/macro-entity/src/queries/dss.ts@@ -263,6 +263,54 @@ export function createDeleteDssItemMutation() {}));}+export function createBulkDeleteDssItemsMutation() {+ const isUnsupportedEntity = (entity: EntityData) => {+ const type = entity.type;+ return type !== 'chat' && type !== 'document';+ };+ return useMutation(() => ({+ mutationFn: async (entities: EntityData[]) => {+ if (entities.some(isUnsupportedEntity)) {+ throw new Error(`Unsupported entity types`);+ }++ return await Promise.all(+ entities.map((e) => {+ return deleteItem({ id: e.id, itemType: e.type });+ })+ );+ },+ onMutate: async (entities: EntityData[]) => {+ const deletedIDs = entities.map((e) => e.id);+ await queryClient.cancelQueries({+ queryKey: queryKeys.dss({ infinite: true }),+ });++ queryClient.setQueriesData(+ { queryKey: queryKeys.dss({ infinite: true }) },+ (prev: { pages: { items: EntityData[] }[] }) => {+ const pages = prev.pages.map((page) => ({+ ...page,+ items: page.items.filter((item) => !deletedIDs.includes(item.id)),+ }));+ return {+ ...prev,+ pages,+ };+ }+ );+ },+ onSettled: (data, error, entities) => {+ if (error)+ console.error(`Failed to delete dss items`, entities, data, error);++ queryClient.invalidateQueries({+ queryKey: queryKeys.dss({ infinite: true }),+ });+ },+ }));+}+export function createRenameDssEntityMutation() {const itemOperations = useItemOperations();return useMutation(() => ({@@ -319,6 +367,78 @@ export function createRenameDssEntityMutation() {}));}+export function createBulkRenameDssEntityMutation() {+ // const itemOperations = useItemOperations();++ const isUnsupportedEntity = (entity: EntityData) => {+ const type = entity.type;+ return type === 'channel' || type === 'email';+ };++ return useMutation(() => ({+ mutationFn: async ({+ entities,+ newName,+ }: {+ entities: EntityData[];+ newName: 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 };+ },+ onMutate: async ({+ entities,+ newName,+ }: {+ entities: EntityData[];+ newName: string;+ }) => {+ await queryClient.cancelQueries({+ queryKey: queryKeys.dss({ infinite: true }),+ });+ queryClient.setQueriesData(+ { queryKey: queryKeys.dss({ infinite: true }) },+ (prev: { pages: { items: EntityData[] }[] }) => {+ 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 };+ }),+ }));+ return {+ ...prev,+ pages,+ };+ }+ );+ },+ onSettled: (data, error, { entities }) => {+ if (error)+ console.error(`Failed to rename dss items`, entities, data, error);++ queryClient.invalidateQueries({+ queryKey: queryKeys.dss({ infinite: true }),+ });+ },+ }));+}+export function createMoveToProjectDssEntityMutation() {const itemOperations = useItemOperations();return useMutation(() => ({diff --git a/js/app/packages/macro-entity/src/types/entity.ts b/js/app/packages/macro-entity/src/types/entity.tsindex a5e4f86603..a807723340 100644--- a/js/app/packages/macro-entity/src/types/entity.ts+++ b/js/app/packages/macro-entity/src/types/entity.ts@@ -1,3 +1,4 @@+import { isEntityType } from '@core/types/utils';import type { JSX } from 'solid-js';export type EntityBase = {@@ -66,6 +67,18 @@ export type EntityData =| EmailEntity| ProjectEntity;+export const isEntityData = (item: unknown): item is EntityData => {+ if (typeof item !== 'object') return false;++ if (!item) return false;++ if (!('type' in item)) return false;++ if (typeof item.type !== 'string') return false;++ return isEntityType(item.type);+};+export type EntityType = EntityData['type'];export type EntityOf<K extends EntityType> = Extract<EntityData, { type: K }>;