Skip to content

armgit / macro

Public Imported from GitHub
0

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

feat(core): create quick-access context for improving performance of repeated history transformation (#1560)

Seamusfdb7b96d1e32
diff --git a/js/app/packages/app/component/Root.tsx b/js/app/packages/app/component/Root.tsx
index b8defe661d..4c08a86e54 100644
--- a/js/app/packages/app/component/Root.tsx
+++ b/js/app/packages/app/component/Root.tsx
@@ -80,6 +80,7 @@ import { ReactiveFavicon } from './ReactiveFavicon';
import { SuspenseContextComp } from './SuspenseContext';
import { LAYOUT_ROUTE } from './split-layout/SplitLayoutRoute';
import Visor from './Visor';
+import { QuickAccessProvider } from '@core/context/quickAccess';
const { track, identify, TrackingEvents } = withAnalytics();
@@ -407,31 +408,33 @@ export function Root() {
<UserInfoSideEffects />
<ConfiguredGlobalAppStateProvider>
<ChannelsContextProvider>
- <SearchProvider>
- <TabAttachmentsInit />
- <ReactiveFavicon />
- <Title>{tabTitle()}</Title>
- <MacroJump />
- <Visor />
- <SuspenseContextComp fallback={<RootSuspenseFallback />}>
- <IsomorphicRouter
- transformUrl={transformShortIdInUrlPathname}
- root={Layout}
- rootPreload={rootPreload}
- base={ROUTER_BASE}
- >
- {{
- path: '/',
- component: TauriRouteListener,
- children: ROUTES,
- }}
- </IsomorphicRouter>
- </SuspenseContextComp>
- <ToastRegion />
- <Show when={ENABLE_WEBSOCKET_DEBUGGER}>
- <WebsocketDebugger />
- </Show>
- </SearchProvider>
+ <QuickAccessProvider>
+ <SearchProvider>
+ <TabAttachmentsInit />
+ <ReactiveFavicon />
+ <Title>{tabTitle()}</Title>
+ <MacroJump />
+ <Visor />
+ <SuspenseContextComp fallback={<RootSuspenseFallback />}>
+ <IsomorphicRouter
+ transformUrl={transformShortIdInUrlPathname}
+ root={Layout}
+ rootPreload={rootPreload}
+ base={ROUTER_BASE}
+ >
+ {{
+ path: '/',
+ component: TauriRouteListener,
+ children: ROUTES,
+ }}
+ </IsomorphicRouter>
+ </SuspenseContextComp>
+ <ToastRegion />
+ <Show when={ENABLE_WEBSOCKET_DEBUGGER}>
+ <WebsocketDebugger />
+ </Show>
+ </SearchProvider>
+ </QuickAccessProvider>
</ChannelsContextProvider>
</ConfiguredGlobalAppStateProvider>
</UserContextProvider>
diff --git a/js/app/packages/app/component/split-layout/componentRegistry.tsx b/js/app/packages/app/component/split-layout/componentRegistry.tsx
index dd974d506f..77e1d74682 100644
--- a/js/app/packages/app/component/split-layout/componentRegistry.tsx
+++ b/js/app/packages/app/component/split-layout/componentRegistry.tsx
@@ -146,6 +146,11 @@ if (LOCAL_ONLY) {
'entity-debug',
lazy(() => import('@entity/debug/DebugEntityView'))
);
+
+ registerComponent(
+ 'quick-access-list',
+ lazy(() => import('@core/context/quickAccess/debug/QuickAccessAll'))
+ );
}
if (DEV_MODE_ENV) {
diff --git a/js/app/packages/block-canvas/component/nodes/TextBox.tsx b/js/app/packages/block-canvas/component/nodes/TextBox.tsx
index d5b5b07550..e2fb298123 100644
--- a/js/app/packages/block-canvas/component/nodes/TextBox.tsx
+++ b/js/app/packages/block-canvas/component/nodes/TextBox.tsx
@@ -251,7 +251,6 @@ function TextBoxEditor(props: {
editor={editor}
menu={mentionsMenuOperations}
useBlockBoundary={true}
- emails={() => []}
/>
</ScopedPortal>
<DecoratorRenderer editor={editor} />
diff --git a/js/app/packages/block-channel/component/MarkdownArea.tsx b/js/app/packages/block-channel/component/MarkdownArea.tsx
index 9a25788c51..e23332d1a4 100644
--- a/js/app/packages/block-channel/component/MarkdownArea.tsx
+++ b/js/app/packages/block-channel/component/MarkdownArea.tsx
@@ -372,11 +372,9 @@ function MarkdownArea(props: MarkdownAreaProps & ConsumableMarkdownAreaProps) {
editor={editor}
menu={mentionsMenuOperations}
users={props.users}
- history={props.history}
block={'channel'}
useBlockBoundary={props.useBlockBoundary}
portalScope={props.portalScope}
- emails={() => []}
/>
</Show>
<FloatingLinkMenu />
diff --git a/js/app/packages/block-md/component/InstructionsEditor.tsx b/js/app/packages/block-md/component/InstructionsEditor.tsx
index 4e809292dc..2de662cb88 100644
--- a/js/app/packages/block-md/component/InstructionsEditor.tsx
+++ b/js/app/packages/block-md/component/InstructionsEditor.tsx
@@ -416,7 +416,6 @@ export function InstructionsEditor() {
menu={mentionsMenuOperations}
useBlockBoundary={true}
disableMentionTracking={true}
- emails={() => []}
/>
<Show when={DEBUG}>
diff --git a/js/app/packages/block-md/component/MarkdownEditor.tsx b/js/app/packages/block-md/component/MarkdownEditor.tsx
index 1cdf56ce61..1ee391d5aa 100644
--- a/js/app/packages/block-md/component/MarkdownEditor.tsx
+++ b/js/app/packages/block-md/component/MarkdownEditor.tsx
@@ -25,7 +25,7 @@ import { EmojiMenu } from '@core/component/LexicalMarkdown/component/menu/EmojiM
import { FloatingEquationMenu } from '@core/component/LexicalMarkdown/component/menu/FloatingEquationMenu';
import { FloatingLinkMenu } from '@core/component/LexicalMarkdown/component/menu/FloatingLinkMenu';
import { GenerateMenu } from '@core/component/LexicalMarkdown/component/menu/GenerateMenu';
-import { MentionsMenu } from '@core/component/LexicalMarkdown/component/menu/MentionsMenu';
+import { MentionsMenu } from '@core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu';
import TableActionMenu, {
anchorElemRefSignal,
menuButtonRefSignal,
@@ -975,7 +975,7 @@ export function MarkdownEditor(props: { autoFocusOnMount?: boolean } = {}) {
editor={editor}
menu={mentionsMenuOperations}
useBlockBoundary={true}
- emails={() => []}
+ showOpenTabs
/>
<ActionMenu editor={editor} menu={actionsMenuOperations} />
diff --git a/js/app/packages/core/component/AI/component/input/useChatMarkdownArea.tsx b/js/app/packages/core/component/AI/component/input/useChatMarkdownArea.tsx
index 4e852c52d3..e64c071cd9 100644
--- a/js/app/packages/core/component/AI/component/input/useChatMarkdownArea.tsx
+++ b/js/app/packages/core/component/AI/component/input/useChatMarkdownArea.tsx
@@ -430,12 +430,11 @@ function MarkdownArea(
editor={editor}
menu={mentionsMenuOperations}
users={() => []}
- // NOTE: we use default channel history
- history={props.history}
block={'chat'}
useBlockBoundary={true}
portalScope={props.portalScope}
useSnapshotForDocuments={ENABLE_SNAPSHOT_NODE}
+ showOpenTabs
/>
<FloatingMenuGroup>
<FloatingLinkMenu />
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/core/MarkdownTextarea.tsx b/js/app/packages/core/component/LexicalMarkdown/component/core/MarkdownTextarea.tsx
index 2afa14c19a..f2cc994619 100644
--- a/js/app/packages/core/component/LexicalMarkdown/component/core/MarkdownTextarea.tsx
+++ b/js/app/packages/core/component/LexicalMarkdown/component/core/MarkdownTextarea.tsx
@@ -357,7 +357,6 @@ export function MarkdownTextarea(props: MarkdownTextareaProps) {
onDocumentMention={props.onDocumentMention}
useBlockBoundary={props.useBlockBoundary}
portalScope={props.portalScope}
- emails={() => []}
/>
<EmojiMenu
editor={editor}
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/menu/ActionsMenu.tsx b/js/app/packages/core/component/LexicalMarkdown/component/menu/ActionsMenu.tsx
index ab627ee8bf..8e2b2f86ec 100644
--- a/js/app/packages/core/component/LexicalMarkdown/component/menu/ActionsMenu.tsx
+++ b/js/app/packages/core/component/LexicalMarkdown/component/menu/ActionsMenu.tsx
@@ -25,6 +25,7 @@ import {
import { ACTIONS, type Action } from '../../plugins/actions/actions';
import type { MenuOperations } from '../../shared/inlineMenu';
import { useIsKeyPressActive } from '@core/util/useIsKeyPressActive';
+import { useMenuKeyboardNavigation } from './useMenuKeyboardNavigation';
false && clickOutside;
false && floatWithSelection;
@@ -143,91 +144,58 @@ export function ActionMenu(props: {
}
});
- const handleKeyDown = (e: KeyboardEvent) => {
- if (!isOpen()) return;
+ const closeMenu = () => {
+ props.editor.dispatchCommand(CLOSE_ACTION_SEARCH_COMMAND, undefined);
+ setIsOpen(false);
+ };
+ const selectCurrentItem = () => {
const items = filteredItems();
const selectedItem = items[selectedIndex()];
-
- switch (e.key) {
- case ' ':
- switch (escapeSpaceState()) {
- case 'double':
- case 'start':
- props.editor.dispatchCommand(
- CLOSE_ACTION_SEARCH_COMMAND,
- undefined
- );
- setIsOpen(false);
- break;
- case 'single':
- setEscapeSpaceState('double');
- break;
- case null:
- setEscapeSpaceState('single');
- break;
- }
- break;
-
- case 'Escape':
- e.preventDefault();
- e.stopPropagation();
- props.editor.dispatchCommand(CLOSE_ACTION_SEARCH_COMMAND, undefined);
- setIsOpen(false);
- break;
-
- case 'ArrowDown':
- e.preventDefault();
- e.stopPropagation();
- setSelectedIndex((prev) => (prev + 1) % items.length);
- break;
-
- case 'ArrowUp':
- e.preventDefault();
- e.stopPropagation();
- setSelectedIndex((prev) => (prev - 1 + items.length) % items.length);
- break;
-
- case 'ArrowLeft':
- case 'ArrowRight':
- e.preventDefault();
- break;
-
- case 'Tab':
- e.preventDefault();
- e.stopPropagation();
- if (e.shiftKey) {
- setSelectedIndex((prev) => (prev - 1 + items.length) % items.length);
- } else {
- setSelectedIndex((prev) => (prev + 1) % items.length);
- }
- break;
-
- case 'Enter':
- e.preventDefault();
- e.stopPropagation();
- props.editor.dispatchCommand(REMOVE_ACTION_SEARCH_COMMAND, undefined);
- if (selectedItem) {
- selectedItem.action(props.editor);
- }
- setIsOpen(false);
- break;
-
- default:
- setEscapeSpaceState(null);
- break;
+ props.editor.dispatchCommand(REMOVE_ACTION_SEARCH_COMMAND, undefined);
+ if (selectedItem) {
+ selectedItem.action(props.editor);
}
+ setIsOpen(false);
};
- onMount(() => {
- document.addEventListener('keydown', handleKeyDown, { capture: true });
- onCleanup(() => {
- document.removeEventListener('keydown', handleKeyDown, { capture: true });
- });
+ useMenuKeyboardNavigation({
+ isActive: isOpen,
+ onUp: () => {
+ const items = filteredItems();
+ setSelectedIndex((prev) => (prev - 1 + items.length) % items.length);
+ },
+ onDown: () => {
+ const items = filteredItems();
+ setSelectedIndex((prev) => (prev + 1) % items.length);
+ },
+ onLeft: () => {},
+ onRight: () => {},
+ onSelect: selectCurrentItem,
+ onClose: closeMenu,
+ onSpace: () => {
+ switch (escapeSpaceState()) {
+ case 'double':
+ case 'start':
+ closeMenu();
+ return true;
+ case 'single':
+ setEscapeSpaceState('double');
+ return false;
+ case null:
+ setEscapeSpaceState('single');
+ return false;
+ }
+ return false;
+ },
+ onOtherKey: () => {
+ setEscapeSpaceState(null);
+ },
+ });
+ onMount(() => {
const focusOut = () => {
- props.editor.dispatchCommand(CLOSE_ACTION_SEARCH_COMMAND, undefined);
- setIsOpen(false);
+ closeMenu();
};
document.addEventListener('focusout', focusOut);
onCleanup(() => {
@@ -268,8 +236,7 @@ export function ActionMenu(props: {
});
const clickOutsideHandler = () => {
- props.editor.dispatchCommand(CLOSE_ACTION_SEARCH_COMMAND, undefined);
- setIsOpen(false);
+ closeMenu();
};
const floatWithElementProps = () =>
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/menu/EmojiMenu.tsx b/js/app/packages/core/component/LexicalMarkdown/component/menu/EmojiMenu.tsx
index f71b6cdeeb..9f5da20349 100644
--- a/js/app/packages/core/component/LexicalMarkdown/component/menu/EmojiMenu.tsx
+++ b/js/app/packages/core/component/LexicalMarkdown/component/menu/EmojiMenu.tsx
@@ -22,6 +22,7 @@ import {
} from '../../plugins';
import type { MenuOperations } from '../../shared/inlineMenu';
import { useIsKeyPressActive } from '@core/util/useIsKeyPressActive';
+import { useMenuKeyboardNavigation } from './useMenuKeyboardNavigation';
false && clickOutside;
false && floatWithSelection;
@@ -136,99 +137,49 @@ export function EmojiMenu(props: EmojiMenuProps) {
);
});
- const handleKeyDown = (e: KeyboardEvent) => {
- if (!props.menu.isOpen()) return;
- const items = emojiOptions();
- const selectedItem = items[selectedIndex()];
-
- switch (e.key) {
- case 'Escape':
- e.preventDefault();
- e.stopPropagation();
- props.menu.setIsOpen(false);
- props.editor.dispatchCommand(CLOSE_EMOJI_SEARCH_COMMAND, undefined);
- break;
-
- case 'ArrowDown': {
- e.preventDefault();
- e.stopPropagation();
- setSelectedIndex((prev) => (prev + 1) % items.length);
- const handle = virtualHandle();
- if (!handle) break;
-
- virtualHandle()?.scrollToIndex(selectedIndex() + 1, {
- align: 'nearest',
- });
- break;
- }
-
- case 'ArrowUp': {
- e.preventDefault();
- e.stopPropagation();
- setSelectedIndex((prev) => (prev - 1 + items.length) % items.length);
- const handle = virtualHandle();
- if (!handle) break;
-
- virtualHandle()?.scrollToIndex(selectedIndex() - 1, {
- align: 'nearest',
- });
- break;
- }
-
- case 'ArrowLeft':
- case 'ArrowRight':
- e.preventDefault();
- break;
-
- case 'Tab':
- e.preventDefault();
- e.stopPropagation();
- if (e.shiftKey) {
- const handle = virtualHandle();
- if (!handle) break;
- setSelectedIndex((prev) => (prev - 1 + items.length) % items.length);
- const startIndex = handle.findItemIndex(handle.scrollOffset);
- if (startIndex && startIndex === selectedIndex()) {
- virtualHandle()?.scrollToIndex(selectedIndex() - 1, {
- align: 'center',
- });
- }
- } else {
- setSelectedIndex((prev) => (prev + 1) % items.length);
- const handle = virtualHandle();
- if (!handle) break;
- const endIndex = handle.findItemIndex(
- handle.scrollOffset + handle.viewportSize
- );
- if (endIndex && endIndex === selectedIndex()) {
- virtualHandle()?.scrollToIndex(selectedIndex() + 1, {
- align: 'center',
- });
- }
- }
- break;
+ const closeMenu = () => {
+ props.editor.dispatchCommand(CLOSE_EMOJI_SEARCH_COMMAND, undefined);
+ props.menu.setIsOpen(false);
+ };
- case 'Enter':
- e.preventDefault();
- e.stopPropagation();
- if (selectedItem) {
- insertEmoji(selectedItem.emoji);
- } else {
- props.editor.dispatchCommand(CLOSE_EMOJI_SEARCH_COMMAND, undefined);
- }
- break;
- }
+ const scrollToIndex = (index: number) => {
+ virtualHandle()?.scrollToIndex(index, { align: 'nearest' });
};
- onMount(() => {
- document.addEventListener('keydown', handleKeyDown, { capture: true });
- onCleanup(() => {
- document.removeEventListener('keydown', handleKeyDown, { capture: true });
- });
+ useMenuKeyboardNavigation({
+ isActive: () => props.menu.isOpen(),
+ onUp: () => {
+ const items = emojiOptions();
+ const newIndex = (selectedIndex() - 1 + items.length) % items.length;
+ setSelectedIndex(newIndex);
+ scrollToIndex(newIndex);
+ },
+ onDown: () => {
+ const items = emojiOptions();
+ const newIndex = (selectedIndex() + 1) % items.length;
+ setSelectedIndex(newIndex);
+ scrollToIndex(newIndex);
+ },
+ onLeft: () => {
+ // block horizontal arrows
+ },
+ onRight: () => {
+ // block horizontal arrows
+ },
+ onSelect: () => {
+ const items = emojiOptions();
+ const selectedItem = items[selectedIndex()];
+ if (selectedItem) {
+ insertEmoji(selectedItem.emoji);
+ } else {
+ closeMenu();
+ }
+ },
+ onClose: closeMenu,
});
+
const focusOut = () => {
- props.editor.dispatchCommand(CLOSE_EMOJI_SEARCH_COMMAND, undefined);
- props.menu.setIsOpen(false);
+ closeMenu();
};
onMount(() => {
document.addEventListener('focusout', focusOut);
@@ -259,8 +210,7 @@ export function EmojiMenu(props: EmojiMenuProps) {
useBlockBoundary: props.useBlockBoundary,
}}
use:clickOutside={() => {
- props.editor.dispatchCommand(CLOSE_EMOJI_SEARCH_COMMAND, undefined);
- props.menu.setIsOpen(false);
+ closeMenu();
}}
ref={menuRef}
>
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu.tsx b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu.tsx
deleted file mode 100644
index 09e48e91c2..0000000000
--- a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu.tsx
+++ /dev/null
@@ -1,1306 +0,0 @@
-import {
- type BlockName,
- useMaybeBlockId,
- useMaybeBlockName,
-} from '@core/block';
-import { SUPPORTED_CHAT_ATTACHMENT_BLOCKS } from '@core/component/AI/constant/fileType';
-import { BozzyBracketInnerSibling } from '@core/component/BozzyBracket';
-import { EntityIcon } from '@core/component/EntityIcon';
-import { type PortalScope, ScopedPortal } from '@core/component/ScopedPortal';
-import { UserIcon } from '@core/component/UserIcon';
-import { ENABLE_CHAT_CHANNEL_ATTACHMENT } from '@core/constant/featureFlags';
-import { useChannelsContext } from '@core/context/channels';
-import { useEmail } from '@core/context/user';
-import clickOutside from '@core/directive/clickOutside';
-import {
- type ChannelWithParticipants,
- type IUser,
- useAugmentUserWithDmActivity,
- useContacts,
-} from '@core/user';
-import { getDateSuggestions } from '@core/util/dateParser';
-import {
- createFreshSearch,
- FreshSearchPresets,
- type TimestampedItem,
-} from '@core/util/freshSort';
-import { useIsKeyPressActive } from '@core/util/useIsKeyPressActive';
-import ClockIcon from '@icon/regular/clock.svg';
-import EmailIcon from '@icon/regular/envelope.svg';
-import UsersIcon from '@icon/regular/users.svg';
-import { useHistoryQuery } from '@queries/history/history';
-import {
- useSearchSoupQuery,
- type SearchSoupQueryArgs,
-} from '@queries/soup/search';
-import { debounce } from '@solid-primitives/scheduled';
-import { globalSplitManager } from 'app/signal/splitLayout';
-import type { LexicalEditor } from 'lexical';
-import type { List } from 'lodash';
-import {
- type Accessor,
- createEffect,
- createMemo,
- createSignal,
- For,
- type JSXElement,
- onCleanup,
- onMount,
- type ParentProps,
- Show,
- Suspense,
- untrack,
-} from 'solid-js';
-import { Dynamic } from 'solid-js/web';
-import { floatWithElement } from '../../directive/floatWithElement';
-import { floatWithSelection } from '../../directive/floatWithSelection';
-import {
- CLOSE_INLINE_SEARCH_COMMAND,
- REMOVE_INLINE_SEARCH_COMMAND,
-} from '../../plugins';
-import type { MenuOperations } from '../../shared/inlineMenu';
-import {
- type CombinedEntity,
- createGroupAlias,
- type Entity,
- type EntityMap,
- entityMapper,
- getCombinedEntityBlockName,
- getItemName,
- type HandlerDependencies,
- handleBasicMention,
- handleChannelMention,
- handleDateMention,
- handleEmailMention,
- handleGroupMention,
- handleUserMention,
- type UserMentionRecord,
-} from '../../utils/mentionsUtils';
-import type { HistoryItem as Item } from '@queries/history/history';
-import type { EntityData, WithSearch, EmailEntity } from '@entity';
-
-false && clickOutside;
-false && floatWithSelection;
-false && floatWithElement;
-
-/** The total number of max items in the menu. */
-const MAX_ITEMS = 8;
-
-/** Whether to filter sidebar non-persistent-chats */
-const ONLY_REAL_CHATS = false;
-
-const getUserSearchText = (item: IUser): string => {
- const { email, name } = item;
- // Note: we return the email twice to make users with a display name
- // able to rank above users without a display name.
- if (name === email) return `${email} | ${email}`;
- return `${name} | ${email}`;
-};
-
-const getItemSearchText = (item: CombinedEntity): string => {
- switch (item.kind) {
- case 'item':
- return item.data.name;
- case 'user':
- return getUserSearchText(item.data);
- case 'channel':
- return item.data.name ?? '';
- case 'date':
- return item.data.displayFormat;
- case 'email':
- return item.data.name ?? 'No Subject';
- case 'group':
- return item.data.groupAlias;
- }
-};
-
-const getItemTimestamp = (item: CombinedEntity): TimestampedItem => {
- switch (item.kind) {
- case 'item':
- return {
- updatedAt: item.data.updatedAt,
- };
- case 'channel':
- return {
- updatedAt: item.data.updated_at,
- };
- case 'email':
- return {
- updatedAt: item.data.updatedAt,
- viewedAt: item.data.viewedAt,
- };
- case 'user':
- return {
- lastInteraction: item.data.lastInteraction,
- };
- default:
- return {};
- }
-};
-
-/**
- * All incoming items will be run through this filter function. PLEASE use this function
- * to ignore certain items before they make it to search.
- * @param item
- * @returns
- */
-function allItemFilter(item: CombinedEntity): boolean {
- if (
- ONLY_REAL_CHATS &&
- item.kind === 'item' &&
- item.data.type === 'chat' &&
- item.data.isPersistent
- ) {
- return false;
- }
- if (item.kind === 'item' && item.data.deletedAt) {
- return false;
- }
- return true;
-}
-
-/**
- * Create the universal item handler.
- * @param dependencies
- * @param useSnapshotForDocuments Whether to use SnapshotNode for supported document types
- * @returns
- */
-function createItemHandler(dependencies: HandlerDependencies) {
- return async (item: CombinedEntity) => {
- if (!item) return;
- dependencies.editor.dispatchCommand(
- REMOVE_INLINE_SEARCH_COMMAND,
- undefined
- );
- switch (item.kind) {
- case 'user':
- return await handleUserMention(item.data, dependencies);
- case 'date':
- return await handleDateMention(item.data, dependencies);
- case 'item':
- return await handleBasicMention(item.data, dependencies);
- case 'channel':
- return await handleChannelMention(item.data, dependencies);
- case 'email':
- return await handleEmailMention(item.data, dependencies);
- case 'group':
- return await handleGroupMention(item.data, dependencies);
- }
- };
-}
-
-/**
- * Styled container for single category.
- */
-
-function ItemBin(
- props: ParentProps<{
- label: string;
- binType: MentionBins;
- isNextPage?: Accessor<boolean>;
- totalCount?: number;
- showingCount?: number;
- onViewAll?: (binType: MentionBins) => void;
- isSelected?: boolean;
- }>
-) {
- const showViewAllButton = () => {
- return (
- (props.binType &&
- props.totalCount &&
- props.showingCount &&
- props.totalCount > props.showingCount) ||
- props.isNextPage?.()
- );
- };
- const viewAllText = () => {
- if (
- props.totalCount &&
- props.showingCount &&
- props.totalCount > props.showingCount
- )
- return `View all (${props.totalCount})`;
- return `View all`;
- };
- return (
- <>
- <div
- class={`text-xs font-medium p-2 pt-0 flex justify-between items-center ${
- props.isSelected ? 'text-ink-muted' : 'text-ink-extra-muted'
- }`}
- >
- <span class="flex items-center gap-1">
- {props.label}
- <Show when={props.isSelected && showViewAllButton()}> →</Show>
- </span>
- <Show when={showViewAllButton()}>
- <button
- type="button"
- class="text-xs font-medium hover:text-ink hover:underline"
- onMouseDown={(e) => {
- e.preventDefault();
- e.stopPropagation();
- }}
- onClick={(e) => {
- e.preventDefault();
- e.stopPropagation();
- props.onViewAll?.(props.binType);
- }}
- >
- {viewAllText()}
- </button>
- </Show>
- </div>
- {props.children}
- </>
- );
-}
-
-/**
- * Calculate the correct number of items for each category.
- * The logic is each incoming bin with at least 1 item gets an outgoing bin of at least 1 item.
- * The remaining items up to MAX_ITEMS are allotted proportional to the size of the incoming bin.
- * @param bins An object with keys and incoming sizes.
- * @param targetLength An object the outgoing sizes for the same keys.
- * @returns
- */
-export function computeBins<T extends string>(
- bins: Record<T, number>,
- targetLength: number
-): Record<T, number> {
- const total = Object.values<number>(bins).reduce(
- (sum, count) => sum + count,
- 0
- );
-
- if (total === 0 || targetLength === 0) {
- return Object.fromEntries(
- Object.keys(bins).map((key) => [key, 0])
- ) as Record<T, number>;
- }
-
- const scaled = {} as Record<T, number>;
- const offsets = {} as Record<T, number>;
-
- const nonEmptyBins: Array<T> = Object.entries<number>(bins)
- .filter(([_, count]) => count > 0)
- .map(([key]) => key as T);
-
- let allocated = 0;
-
- for (const key in bins) {
- scaled[key] = 0;
- offsets[key] = 0;
- }
-
- for (const key of nonEmptyBins) {
- if (allocated < targetLength) {
- scaled[key] = 1;
- offsets[key] = allocated;
- allocated++;
- }
- }
-
- const remaining = targetLength - allocated;
- if (remaining > 0 && nonEmptyBins.length > 0) {
- const nonEmptyTotal = nonEmptyBins.reduce((sum, key) => sum + bins[key], 0);
- const remainders: { key: T; remainder: number }[] = [];
-
- for (const key of nonEmptyBins) {
- const proportion = bins[key] / nonEmptyTotal;
- const raw = proportion * remaining;
- const floor = Math.floor(raw);
- scaled[key] += floor;
- allocated += floor;
- remainders.push({ key, remainder: raw - floor });
- }
-
- const leftover = targetLength - allocated;
- remainders.sort((a, b) => b.remainder - a.remainder);
-
- for (let i = 0; i < leftover; i++) {
- const key = remainders[i % remainders.length].key;
- scaled[key]++;
- }
- }
-
- return scaled;
-}
-
-/** The current bins enum */
-export type MentionBins = 'items' | 'users' | 'dates' | 'emails';
-
-/** View all mode type */
-type ViewAllMode = MentionBins | null;
-
-/** Selected category type */
-type SelectedCategory = MentionBins | null;
-
-/**
- * Styled component for a single item.
- * @param props
- * @returns
- */
-export function MentionsMenuItem(props: {
- item: CombinedEntity;
- index: number;
- selected: boolean;
- itemAction: (item: CombinedEntity) => void;
- setIndex: (index: number) => void;
- setOpen: (open: boolean) => void;
-}) {
- let itemRef: HTMLDivElement | undefined;
-
- createEffect(() => {
- if (props.selected && itemRef) {
- itemRef.scrollIntoView({ block: 'nearest' });
- }
- });
-
- const name = () => getItemName(props.item);
-
- const icon = () => {
- switch (props.item.kind) {
- case 'user':
- return <UserIcon id={props.item.id} size="sm" isDeleted={false} />;
-
- case 'group':
- return <UsersIcon class="size-4 text-ink-muted" />;
-
- case 'date':
- return <ClockIcon class="size-4 text-ink-muted" />;
-
- case 'channel':
- return (
- <EntityIcon
- size="xs"
- targetType={props.item.data.channel_type || 'channel'}
- />
- );
-
- case 'item':
- return (
- <EntityIcon
- targetType={getCombinedEntityBlockName(props.item, true)}
- size="xs"
- />
- );
- case 'email':
- return <EmailIcon class="size-4 text-ink-muted" />;
- }
- };
-
- return (
- <div
- ref={itemRef}
- on:mouseup={(e) => {
- e.preventDefault();
- e.stopPropagation();
- }}
- on:mousedown={(e) => {
- e.preventDefault();
- e.stopPropagation();
- }}
- on:click={(e) => {
- props.itemAction(props.item);
- props.setOpen(false);
- e.stopPropagation();
- }}
- on:mousemove={() => props.setIndex(props.index)}
- class="group flex items-center p-1.5 mx-1.5"
- classList={{ 'bg-active bracket': props.selected }}
- >
- <div class="mr-2">{icon()}</div>
- <span
- class="text-ink text-xs sm:text-sm font-medium grow overflow-hidden text-nowrap"
- style={{ 'text-overflow': 'ellipsis' }}
- >
- {name()}
- </span>
- </div>
- );
-}
-
-export function MentionsMenu(props: Parameters<typeof MentionsMenuInner>[0]) {
- return (
- <Suspense>
- <Show when={props.menu.isOpen()}>
- <MentionsMenuInner {...props} />
- </Show>
- </Suspense>
- );
-}
-
-function MentionsMenuInner(props: {
- editor: LexicalEditor;
- menu: MenuOperations;
- /** pass in custom history list if necessary */
- history?: Accessor<Item[]>;
- /** pass in a custom users list if necessary */
- users?: Accessor<IUser[]>;
- /** pass in a custom channels list if necessary */
- channels?: Accessor<ChannelWithParticipants[]>;
- /** pass in a custom emails list if necessary */
- emails?: Accessor<EmailEntity[]>;
- /** whether the menu checks against block boundary in floating middleware. uses floating-ui default if false. */
- useBlockBoundary?: boolean;
- portalScope?: PortalScope;
- block?: BlockName;
- anchor?: HTMLElement | null;
- onUserMention?: (mention: UserMentionRecord) => void;
- onDocumentMention?: (item: Item | ChannelWithParticipants) => void;
- onEmailMention?: (item: EmailEntity) => void;
- disableMentionTracking?: boolean;
- /** Fetch text then past in a fold-node for plain-text mentions (useful for AI)*/
- useSnapshotForDocuments?: boolean;
-}) {
- const [searchTerm, setSearchTerm] = createSignal<string>(
- props.menu.searchTerm()
- );
- const historyQuery = useHistoryQuery();
- // TODO: support viewed at in history
- const history = createMemo(() => {
- if (props.history) {
- return props.history().map(entityMapper('item'));
- }
- return historyQuery.data?.map(entityMapper('item')) ?? [];
- });
-
- let emails: Accessor<Entity<'email'>[]>;
- if (props.emails) {
- emails = createMemo(
- () =>
- props.emails?.().map(entityMapper('email')).filter(allItemFilter) ?? []
- );
- } else {
- // TODO: hook into email query because useEmails was deprecated
- const emailsFromSource: Accessor<EmailEntity[]> = () => [];
- emails = createMemo(
- () =>
- emailsFromSource().map(entityMapper('email')).filter(allItemFilter) ??
- []
- );
- }
-
- const contacts = useContacts();
- const augmentUserWithDmActivity = useAugmentUserWithDmActivity();
-
- const users = createMemo((): Entity<'user'>[] => {
- const list = props.users?.() ?? contacts();
-
- return list
- .map((user) => entityMapper('user')(augmentUserWithDmActivity(user)))
- .filter(allItemFilter);
- });
-
- let channels: Accessor<Entity<'channel'>[]>;
- if (props.channels) {
- channels = createMemo(
- () =>
- props.channels?.().map(entityMapper('channel')).filter(allItemFilter) ??
- []
- );
- } else {
- const { channels: userChannels } = useChannelsContext();
- channels = createMemo(() => {
- if (!ENABLE_CHAT_CHANNEL_ATTACHMENT && props.block === 'chat') {
- return [];
- }
- return userChannels().map(entityMapper('channel')).filter(allItemFilter);
- });
- }
-
- const args = createMemo((): SearchSoupQueryArgs => {
- return {
- params: {
- cursor: null,
- page_size: 10,
- },
- body: {
- match_type: 'partial',
- search_on: 'name',
- include: ['emails'],
- query: searchTerm(),
- },
- };
- });
-
- const emailUnifiedSearchInfiniteQuery = useSearchSoupQuery(args);
-
- const foundEmails = createMemo((): Entity<'email'>[] => {
- if (emailUnifiedSearchInfiniteQuery.status === 'success') {
- function isEmail(
- e: WithSearch<EntityData>
- ): e is WithSearch<EmailEntity> {
- return e.type === 'email';
- }
-
- function entityDataToMentionEntity<T extends EmailEntity>(
- e: T
- ): Entity<'email'> {
- return {
- data: e,
- id: e.id,
- kind: 'email',
- };
- }
-
- return emailUnifiedSearchInfiniteQuery.data
- .filter(isEmail)
- .map(entityDataToMentionEntity);
- } else {
- return [];
- }
- });
-
- // Get open tabs from split manager
- const openTabs = createMemo(() => {
- const splitManager = globalSplitManager();
- if (!splitManager) return [];
-
- const splits = splitManager.splits();
- const historyItems = history();
- const channelList = channels();
- const emailList = emails();
-
- const tabItems: CombinedEntity<'item' | 'channel' | 'email'>[] = [];
-
- const seenKeys = new Set<string>();
-
- for (const split of splits) {
- if (
- split.content.type === 'component' ||
- (props.block === 'chat' &&
- !SUPPORTED_CHAT_ATTACHMENT_BLOCKS.includes(split.content.type))
- ) {
- continue;
- }
-
- const key = `${split.content.type}:${split.content.id}`;
- if (seenKeys.has(key)) continue;
- seenKeys.add(key);
-
- if (split.content.type === 'channel') {
- // Find the channel in our channels list
- const channel = channelList.find((ch) => ch.id === split.content.id);
- if (ENABLE_CHAT_CHANNEL_ATTACHMENT && channel) {
- tabItems.push(channel);
- }
- } else if (split.content.type === 'email') {
- const e = emailList.find((e) => e.id === split.content.id);
- if (e) tabItems.push(e);
- } else {
- // Find the document in history
- const historyItem = historyItems.find(
- (item) => item.id === split.content.id
- );
- if (historyItem) {
- tabItems.push(historyItem);
- }
- }
- }
-
- return tabItems.filter(allItemFilter);
- });
-
- const historyAndChannels = createMemo(() => {
- const historyItems = history().filter(allItemFilter);
- const channelItems = channels();
- const currentBlockId = useMaybeBlockId();
-
- // Create a map to deduplicate by ID
- const itemMap = new Map<string, CombinedEntity<'item' | 'channel'>>();
-
- // Add history items first (excluding current document)
- for (const item of historyItems) {
- if (!currentBlockId || item.id !== currentBlockId) {
- itemMap.set(item.id, item);
- }
- }
-
- // Add channel items (excluding current channel)
- for (const item of channelItems) {
- if (!currentBlockId || item.id !== currentBlockId) {
- itemMap.set(item.id, item);
- }
- }
-
- // Open tabs are already included in history/channels, so we don't need to add them separately
- // The prioritization happens in filteredItems instead
-
- return Array.from(itemMap.values());
- });
-
- const [menuOpen, setMenuOpen] = [props.menu.isOpen, props.menu.setIsOpen];
-
- const [selectedIndex, setSelectedIndex] = createSignal(0);
- const [viewAllMode, setViewAllMode] = createSignal<ViewAllMode>(null);
- const { isKeypressActive } = useIsKeyPressActive();
- const setSelectedIndexFromMouse = (index: number) => {
- if (isKeypressActive()) return;
- setSelectedIndex(index);
- };
-
- let menuRef!: HTMLDivElement;
-
- const [mountSelection, setMountSelection] = createSignal<Selection | null>();
-
- const debouncedSetSearchTerm = debounce(
- (term: string) => setSearchTerm(term.toLowerCase()),
- 60
- );
-
- createEffect(() => debouncedSetSearchTerm(props.menu.searchTerm()));
-
- const itemSearch = createFreshSearch<CombinedEntity<'item' | 'channel'>>(
- {},
- getItemSearchText,
- (item) => item.kind === 'channel',
- getItemTimestamp
- );
- const filteredItems = createMemo(() => {
- const allResults = itemSearch(historyAndChannels(), searchTerm()).map(
- (result) => {
- return result.item;
- }
- );
-
- // Separate open tabs from other items
- const openTabsSet = new Set(openTabs().map((item) => item.id));
- const tabResults: CombinedEntity<'item' | 'channel' | 'email'>[] = [];
- const otherResults: CombinedEntity<'item' | 'channel' | 'email'>[] = [];
-
- for (const item of allResults) {
- if (openTabsSet.has(item.id)) {
- tabResults.push(item);
- } else {
- otherResults.push(item);
- }
- }
-
- // Return open tabs first, then other items
- return [...tabResults, ...otherResults];
- });
-
- const currentUserEmail = useEmail();
- const currentUserDomain = createMemo(() => {
- const email = currentUserEmail();
- return email ? email.split('@')[1] : undefined;
- });
-
- const userSearch = createFreshSearch<Entity<'user'>>(
- FreshSearchPresets.baseUserSearch<Entity<'user'>>(
- currentUserDomain,
- (item) => item.data.email
- ),
- getItemSearchText,
- (_item) => false,
- getItemTimestamp
- );
-
- // Group aliases available in channel context
- const specialGroups = createMemo((): Entity<'group'>[] => {
- if (props.block !== 'channel') return [];
- if (!useMaybeBlockId()) return [];
-
- const term = searchTerm().toLowerCase();
-
- const availableGroups = [
- { alias: 'here', match: (t: string) => t === '' || 'here'.startsWith(t) },
- ];
-
- return availableGroups
- .filter((g) => g.match(term))
- .map((g) => createGroupAlias(g.alias));
- });
-
- const filteredUsers = createMemo(() => {
- const searchedUsers = userSearch(users(), searchTerm()).map((result) => {
- return result.item;
- });
- return [...specialGroups(), ...searchedUsers] as CombinedEntity<
- 'user' | 'group'
- >[];
- });
-
- const emailSearch = createFreshSearch<Entity<'email'>>(
- { timeWeight: 0, brevityWeight: 0.3 },
- getItemSearchText,
- (_item) => false,
- getItemTimestamp
- );
-
- const filteredEmails = createMemo(() => {
- const mail = emailSearch(emails(), searchTerm()).map(
- (result) => result.item
- );
-
- const otherMail = foundEmails();
-
- // dedup / preserve order
- function merge<T extends keyof EntityMap>(
- local: Entity<T>[],
- unifiedSearch: Entity<T>[]
- ): Entity<T>[] {
- const ids = new Set(local.map((e) => e.id));
- return [...local, ...unifiedSearch.filter((e) => !ids.has(e.id))];
- }
-
- return merge(mail, otherMail);
- });
-
- const dateSuggestions = createMemo(() => {
- const suggestions = getDateSuggestions(searchTerm());
- return suggestions
- .map((suggestion) => ({
- ...suggestion,
- id: `date-${suggestion.date.toISOString()}`,
- }))
- .map(entityMapper('date'));
- });
-
- // The raw bins store the counts for all matching items
- const rawBins = createMemo<Record<MentionBins, number>>(() => ({
- users: filteredUsers().length,
- items: filteredItems().length,
- dates: dateSuggestions().length,
- emails: filteredEmails().length,
- }));
-
- // The bins is the limited and rounded count for each bucket
- const bins = createMemo(() => computeBins(rawBins(), MAX_ITEMS));
-
- const combinedItems = createMemo<CombinedEntity[]>(() => {
- const currentViewAllMode = viewAllMode();
-
- if (currentViewAllMode) {
- // in view all mode, show all items for that category only
- switch (currentViewAllMode) {
- case 'users':
- return filteredUsers();
- case 'items':
- return filteredItems();
- case 'dates':
- return dateSuggestions();
- case 'emails':
- return filteredEmails();
- default:
- return [];
- }
- }
-
- // normal mode: show limited items from all categories
- return [
- ...filteredUsers().slice(0, bins().users),
- ...filteredItems().slice(0, bins().items),
- ...dateSuggestions().slice(0, bins().dates),
- ...filteredEmails().slice(0, bins().emails),
- ];
- });
-
- const [escapeSpaceState, setEscapeSpaceState] = createSignal<
- 'start' | 'single' | 'double' | null
- >('start');
- createEffect(() => {
- if (!menuOpen()) {
- setEscapeSpaceState('start');
- setViewAllMode(null);
- }
- });
-
- const selectedCategory = createMemo<SelectedCategory>(() => {
- if (viewAllMode()) return null; // no category selection in view all mode
-
- const index = selectedIndex();
- const { users, items, dates, emails } = bins();
-
- let currentIndex = 0;
-
- if (users > 0) {
- if (index < currentIndex + users) {
- return 'users';
- }
- currentIndex += users;
- }
-
- if (items > 0) {
- if (index < currentIndex + items) {
- return 'items';
- }
- currentIndex += items;
- }
-
- if (dates > 0) {
- if (index < currentIndex + dates) {
- return 'dates';
- }
- currentIndex += dates;
- }
-
- if (emails > 0) {
- if (index < currentIndex + emails) {
- return 'emails';
- }
- }
-
- return null;
- });
-
- const itemAction = createItemHandler({
- editor: props.editor,
- blockName: useMaybeBlockName(),
- blockId: useMaybeBlockId(),
- onUserMention: props.onUserMention,
- onDocumentMention: props.onDocumentMention,
- onEmailMention: props.onEmailMention,
- disableMentionTracking: props.disableMentionTracking,
- useSnapshotNode: props.useSnapshotForDocuments,
- });
-
- createEffect(() => {
- if (props.anchor) return;
- if (menuOpen()) {
- setMountSelection(document.getSelection());
- setSelectedIndex(0);
- } else {
- setMountSelection(null);
- }
- });
-
- const handleKeyDown = (e: KeyboardEvent) => {
- if (!menuOpen()) return;
-
- const items = combinedItems();
- const selectedItem = items[selectedIndex()];
-
- const handleArrowDown = () => {
- setSelectedIndex((p) => {
- if (p >= combinedItems.length) {
- if (
- viewAllMode() === 'emails' &&
- emailUnifiedSearchInfiniteQuery.isFetching
- ) {
- return items.length - 1;
- } else {
- return (p + 1) % items.length;
- }
- } else {
- return p + 1;
- }
- });
- };
-
- switch (e.key) {
- case ' ':
- switch (escapeSpaceState()) {
- case 'double':
- case 'start':
- props.editor.dispatchCommand(
- CLOSE_INLINE_SEARCH_COMMAND,
- undefined
- );
- setMenuOpen(false);
- break;
- case 'single':
- setEscapeSpaceState('double');
- break;
- case null:
- setEscapeSpaceState('single');
- break;
- }
- break;
-
- case 'Escape':
- e.preventDefault();
- e.stopPropagation();
- if (viewAllMode()) {
- handleBackToAll();
- } else {
- props.editor.dispatchCommand(CLOSE_INLINE_SEARCH_COMMAND, undefined);
- setMenuOpen(false);
- }
- break;
-
- case 'ArrowDown':
- e.preventDefault();
- e.stopPropagation();
- handleArrowDown();
- break;
-
- case 'ArrowUp':
- e.preventDefault();
- e.stopPropagation();
- setSelectedIndex((prev) =>
- prev - 1 < 0 ? items.length - 1 : prev - 1
- );
- break;
-
- case 'ArrowLeft':
- e.preventDefault();
- e.stopPropagation();
- if (viewAllMode()) {
- handleBackToAll();
- }
- break;
-
- case 'ArrowRight':
- e.preventDefault();
- e.stopPropagation();
- if (!viewAllMode()) {
- const currentCategory = selectedCategory();
- if (currentCategory) {
- const currentBins = bins();
- const currentRawBins = rawBins();
- const abbreviatedCount = currentBins[currentCategory];
- const fullCount = currentRawBins[currentCategory];
- if (
- abbreviatedCount < fullCount ||
- (emailUnifiedSearchInfiniteQuery.hasNextPage &&
- currentCategory === 'emails')
- ) {
- handleViewAll(currentCategory);
- }
- }
- }
- break;
-
- case 'Tab':
- e.preventDefault();
- e.stopPropagation();
- if (e.shiftKey) {
- setSelectedIndex((prev) => (prev - 1 + items.length) % items.length);
- } else {
- setSelectedIndex((prev) => (prev + 1) % items.length);
- }
- break;
-
- case 'Enter':
- e.preventDefault();
- e.stopPropagation();
- if (selectedItem) {
- itemAction(selectedItem);
- } else {
- props.editor.dispatchCommand(CLOSE_INLINE_SEARCH_COMMAND, undefined);
- }
- setSearchTerm('');
- setMenuOpen(false);
- break;
-
- default:
- setEscapeSpaceState(null);
- break;
- }
- };
-
- onMount(() => {
- document.addEventListener('keydown', handleKeyDown, { capture: true });
- onCleanup(() => {
- document.removeEventListener('keydown', handleKeyDown, { capture: true });
- });
- });
-
- const focusOut = () => {
- props.editor.dispatchCommand(CLOSE_INLINE_SEARCH_COMMAND, undefined);
- setMenuOpen(false);
- };
-
- onMount(() => {
- document.addEventListener('focusout', focusOut);
- onCleanup(() => {
- document.removeEventListener('focusout', focusOut);
- });
- });
-
- createEffect(() => {
- if (
- selectedIndex() >= combinedItems().length - 5 &&
- viewAllMode() === 'emails' &&
- emailUnifiedSearchInfiniteQuery.hasNextPage &&
- !emailUnifiedSearchInfiniteQuery.isFetching
- ) {
- emailUnifiedSearchInfiniteQuery.fetchNextPage();
- }
- if (selectedIndex() >= combinedItems().length) {
- setSelectedIndex(combinedItems().length - 1);
- }
- });
-
- const handleViewAll = (binType: MentionBins) => {
- setViewAllMode(binType);
- setSelectedIndex(0);
- };
-
- const handleBackToAll = () => {
- setViewAllMode(null);
- setSelectedIndex(0);
- };
-
- const hasOnlyOneCategory = createMemo(() => {
- const currentRawBins = rawBins();
- const categoriesWithMatches = Object.values(currentRawBins).filter(
- (count) => count > 0
- );
- return categoriesWithMatches.length === 1;
- });
-
- const inner = createMemo(() => {
- const currentViewAllMode = viewAllMode();
-
- // ---- SINGLE BUCKET MODE -------------------------------------------------
- if (currentViewAllMode) {
- const allItems = combinedItems();
- const totalLength = () => allItems.length;
-
- const renderViewAllOptions = createMemo(() => {
- const categoryLabel = {
- users: 'People',
- items: 'Documents & Channels',
- dates: 'Dates',
- emails: 'Emails',
- }[currentViewAllMode];
-
- return (
- <>
- <div class="px-2 pb-2">
- <div class="flex items-center justify-between">
- <span class="text-xs font-medium text-ink-muted">
- {categoryLabel}
- </span>
- <button
- type="button"
- class="text-xs font-medium text-ink-muted hover:text-ink hover:underline"
- onMouseDown={(e) => {
- e.preventDefault();
- e.stopPropagation();
- }}
- onClick={(e) => {
- e.preventDefault();
- e.stopPropagation();
- handleBackToAll();
- }}
- >
- ←{' '}
- {hasOnlyOneCategory()
- ? 'Back to summary'
- : 'Back to everything'}
- </button>
- </div>
- </div>
- <div class="max-h-64 overflow-y-auto scrollbar-hidden">
- <For each={allItems}>
- {(item, i) => (
- <MentionsMenuItem
- item={item}
- index={i()}
- selected={i() === selectedIndex()}
- itemAction={itemAction}
- setIndex={setSelectedIndexFromMouse}
- setOpen={setMenuOpen}
- />
- )}
- </For>
- </div>
- </>
- );
- });
-
- return (
- <Show
- when={totalLength() > 0}
- fallback={<div class="px-2 text-ink-extra-muted">No results</div>}
- >
- {renderViewAllOptions()}
- </Show>
- );
- }
-
- // ------ NORMAL MODE ------------------------------------------------------
- const users = filteredUsers().slice(0, bins().users);
- const docs = filteredItems().slice(0, bins().items);
- const dates = dateSuggestions().slice(0, bins().dates);
- const emailList = filteredEmails().slice(0, bins().emails);
- const totalLength = () =>
- users.length +
- docs.length +
- contacts.length +
- dates.length +
- emailList.length;
-
- const RenderOptions = () => {
- const options = [];
- if (users.length > 0) {
- options.push(
- <ItemBin
- label="People"
- binType="users"
- totalCount={filteredUsers().length}
- showingCount={users.length}
- onViewAll={handleViewAll}
- isSelected={selectedCategory() === 'users'}
- >
- <For each={users}>
- {(item, i) => (
- <MentionsMenuItem
- item={item}
- index={i()}
- selected={i() === selectedIndex()}
- itemAction={itemAction}
- setIndex={setSelectedIndexFromMouse}
- setOpen={setMenuOpen}
- />
- )}
- </For>
- </ItemBin>
- );
- }
-
- if (docs.length > 0) {
- options.push(
- <ItemBin
- label="Documents & Channels"
- binType="items"
- totalCount={filteredItems().length}
- showingCount={docs.length}
- onViewAll={handleViewAll}
- isSelected={selectedCategory() === 'items'}
- >
- <For each={docs}>
- {(item, i) => (
- <MentionsMenuItem
- item={item}
- index={users.length + i()}
- selected={users.length + i() === selectedIndex()}
- itemAction={itemAction}
- setIndex={setSelectedIndexFromMouse}
- setOpen={setMenuOpen}
- />
- )}
- </For>
- </ItemBin>
- );
- }
-
- if (dates.length > 0) {
- options.push(
- <ItemBin
- label="Dates"
- binType="dates"
- totalCount={dateSuggestions().length}
- showingCount={dates.length}
- onViewAll={handleViewAll}
- isSelected={selectedCategory() === 'dates'}
- >
- <For each={dates}>
- {(item, i) => (
- <MentionsMenuItem
- item={item}
- index={users.length + docs.length + i()}
- selected={
- users.length + docs.length + i() === selectedIndex()
- }
- itemAction={itemAction}
- setIndex={setSelectedIndexFromMouse}
- setOpen={setMenuOpen}
- />
- )}
- </For>
- </ItemBin>
- );
- }
-
- if (emailList.length > 0) {
- options.push(
- <ItemBin
- label="Emails"
- binType="emails"
- isNextPage={() => emailUnifiedSearchInfiniteQuery.hasNextPage}
- totalCount={filteredEmails().length}
- showingCount={emailList.length}
- onViewAll={handleViewAll}
- isSelected={selectedCategory() === 'emails'}
- >
- <For each={emailList}>
- {(item, i) => (
- <MentionsMenuItem
- item={item}
- index={i()}
- selected={
- users.length + docs.length + dates.length + i() ===
- selectedIndex()
- }
- itemAction={itemAction}
- setIndex={setSelectedIndexFromMouse}
- setOpen={setMenuOpen}
- />
- )}
- </For>
- </ItemBin>
- );
- }
-
- return options.map(
- (option: JSXElement, index: number, array: List<JSXElement>) => (
- <>
- {option}
- <Show when={index < array.length - 1}>
- <div class="w-full mt-4 border-b-1 border-edge mb-2" />
- </Show>
- </>
- )
- );
- };
-
- return (
- <Show
- when={totalLength() > 0}
- fallback={<div class="px-2 text-ink-extra-muted">No results</div>}
- >
- <div>
- <Dynamic component={RenderOptions} />
- </div>
- </Show>
- );
- });
-
- const clickOutsideHandler = (e: MouseEvent) => {
- e.stopPropagation();
- props.editor.dispatchCommand(CLOSE_INLINE_SEARCH_COMMAND, undefined);
- setMenuOpen(false);
- };
-
- const floatWithElementProps = () =>
- props.anchor
- ? {
- element: () => props.anchor,
- useBlockBoundary: props.useBlockBoundary,
- }
- : undefined;
-
- const floatWithSelectionProps = () =>
- !props.anchor
- ? {
- selection: untrack(mountSelection),
- reactiveOnContainer: props.editor.getRootElement(),
- useBlockBoundary: props.useBlockBoundary,
- }
- : undefined;
-
- return (
- <Show when={menuOpen()}>
- <ScopedPortal scope={props.portalScope}>
- <div
- class="w-96 cursor-default select-none z-modal-content"
- use:floatWithElement={floatWithElementProps()}
- use:floatWithSelection={floatWithSelectionProps()}
- use:clickOutside={clickOutsideHandler}
- ref={menuRef}
- >
- <div class="relative overflow-hidden ring-1 ring-edge bg-menu shadow-xl py-2">
- {inner()}
- </div>
- <BozzyBracketInnerSibling animOnOpen={true} />
- </div>
- </ScopedPortal>
- </Show>
- );
-}
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx
new file mode 100644
index 0000000000..3a8177ea0d
--- /dev/null
+++ b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx
@@ -0,0 +1,580 @@
+import type { BlockName } from '@core/block';
+import { useMaybeBlockId, useMaybeBlockName } from '@core/block';
+import { SUPPORTED_CHAT_ATTACHMENT_BLOCKS } from '@core/component/AI/constant/fileType';
+import { type PortalScope, ScopedPortal } from '@core/component/ScopedPortal';
+import { useQuickAccess, type EntityItem } from '@core/context/quickAccess';
+import clickOutside from '@core/directive/clickOutside';
+import type { ChannelWithParticipants, IUser } from '@core/user';
+import { useDateSearch } from '@core/util/dateSearch/useDateSearch';
+import { useIsKeyPressActive } from '@core/util/useIsKeyPressActive';
+import type { EmailEntity } from '@entity';
+import { globalSplitManager } from 'app/signal/splitLayout';
+import type { LexicalEditor } from 'lexical';
+import {
+ type Accessor,
+ createEffect,
+ createSignal,
+ For,
+ onCleanup,
+ onMount,
+ Show,
+ Suspense,
+ untrack,
+} from 'solid-js';
+import { createLazyMemo } from '@solid-primitives/memo';
+import { createVirtualizer } from '@tanstack/solid-virtual';
+import { floatWithElement } from '../../../directive/floatWithElement';
+import { floatWithSelection } from '../../../directive/floatWithSelection';
+import { CLOSE_INLINE_SEARCH_COMMAND } from '../../../plugins';
+import type { MenuOperations } from '../../../shared/inlineMenu';
+import type {
+ DateMentionItem,
+ UserMentionRecord,
+} from '../../../utils/mentionsUtils';
+import type { HistoryItem as Item } from '@queries/history/history';
+import { ClippedPanel } from '@core/component/ClippedPanel';
+import { debouncedDependent } from '@core/util/debounce';
+import type { BucketConfig } from './MentionsMenuController';
+import { useMentionsMenuController } from './MentionsMenuController';
+import type { MentionItem } from '../../../utils/mentionsUtils';
+import { ItemBin } from './components/ItemBin';
+import { MentionsMenuItem } from './components/MentionsMenuItem';
+import { createItemHandler } from './utils/mentionHandlers';
+import { useMenuKeyboardNavigation } from '../useMenuKeyboardNavigation';
+import { useUsersMention } from './hooks/useUsersMention';
+import { useEntityMention } from './hooks/useEntityMention';
+import { useEmailSearchMention } from './hooks/useEmailSearchMention';
+
+const MAX_ITEMS = 8;
+const VIRTUAL_ITEM_HEIGHT = 36;
+
+export type MentionsMenuProps = {
+ editor: LexicalEditor;
+ menu: MenuOperations;
+ /** pass in a custom users list if necessary */
+ users?: Accessor<IUser[]>;
+ /** whether the menu checks against block boundary in floating middleware. uses floating-ui default if false. */
+ useBlockBoundary?: boolean;
+ portalScope?: PortalScope;
+ block?: BlockName;
+ anchor?: HTMLElement | null;
+ onUserMention?: (mention: UserMentionRecord) => void;
+ onDocumentMention?: (item: Item | ChannelWithParticipants) => void;
+ onEmailMention?: (item: EmailEntity) => void;
+ disableMentionTracking?: boolean;
+ useSnapshotForDocuments?: boolean;
+ /** whether to show open tabs as a bucket in the menu */
+ showOpenTabs?: boolean;
+};
+
+export function MentionsMenu(props: MentionsMenuProps) {
+ return (
+ <Suspense>
+ <MentionsMenuInner {...props} />
+ </Suspense>
+ );
+}
+
+function MentionsMenuInner(props: MentionsMenuProps) {
+ const searchTerm = debouncedDependent(props.menu.searchTerm, 60);
+
+ const quickAccess = useQuickAccess();
+
+ const allItems = quickAccess.useList();
+
+ const { isKeypressActive } = useIsKeyPressActive();
+
+ const blockId = useMaybeBlockId();
+
+ const { usersAndGroups } = useUsersMention({
+ users: props.users,
+ searchTerm,
+ isChannelBlock: props.block === 'channel',
+ blockId: useMaybeBlockId(),
+ });
+
+ const { searchedEntities: docs } = useEntityMention({
+ buckets: ['note', 'task', 'document', 'project'],
+ searchTerm,
+ });
+
+ const { searchedEntities: channels } = useEntityMention({
+ buckets: ['channel'],
+ searchTerm,
+ });
+
+ const { emails, emailSearchQuery: emailUnifiedSearchInfiniteQuery } =
+ useEmailSearchMention({
+ searchTerm,
+ });
+
+ const dateOptions = useDateSearch({ query: searchTerm });
+ const dates = createLazyMemo((): DateMentionItem[] => {
+ return dateOptions().map(
+ (option): DateMentionItem => ({
+ kind: 'date',
+ id: `date-${option.id}`,
+ data: option,
+ })
+ );
+ });
+
+ const currentBlockId = useMaybeBlockId();
+
+ const openTabs = createLazyMemo(() => {
+ const splitManager = globalSplitManager();
+ if (!splitManager) return [];
+
+ const splits = splitManager.splits();
+ const allItems_ = allItems();
+
+ const tabItems: EntityItem[] = [];
+ const seenKeys = new Set<string>();
+
+ for (const split of splits) {
+ if (
+ split.content.type === 'component' ||
+ (props.block === 'chat' &&
+ !SUPPORTED_CHAT_ATTACHMENT_BLOCKS.includes(split.content.type))
+ ) {
+ continue;
+ }
+
+ if (split.content.id === currentBlockId) continue;
+
+ const key = `${split.content.type}:${split.content.id}`;
+ if (seenKeys.has(key)) continue;
+
+ seenKeys.add(key);
+
+ const item = allItems_.find((item) => item.id === split.content.id);
+ if (!item || item.kind !== 'entity') continue;
+ tabItems.push(item);
+ }
+
+ return tabItems;
+ });
+
+ const [menuOpen, setMenuOpen] = [props.menu.isOpen, props.menu.setIsOpen];
+
+ const setSelectedIndexFromMouse = (index: number) => {
+ if (isKeypressActive()) return;
+ controller.selectItem(index);
+ };
+
+ const [mountSelection, setMountSelection] = createSignal<Selection | null>();
+
+ const bucketConfigs = createLazyMemo((): BucketConfig[] => {
+ const buckets: BucketConfig[] = [
+ {
+ id: 'users',
+ label: 'People & Groups',
+ getData: () => usersAndGroups() ?? [],
+ getFullCount: () => usersAndGroups()?.length ?? 0,
+ },
+ {
+ id: 'documents',
+ label: 'Documents & Tasks',
+ getData: () => docs() ?? [],
+ getFullCount: () => docs()?.length ?? 0,
+ },
+ {
+ id: 'channels',
+ label: 'Channels',
+ getData: () => channels() ?? [],
+ getFullCount: () => channels()?.length ?? 0,
+ },
+ {
+ id: 'emails',
+ label: 'Emails',
+ getData: () => emails() ?? [],
+ getFullCount: () => emails()?.length ?? 0,
+ },
+ {
+ id: 'dates',
+ label: 'Dates',
+ getData: () => dates() ?? [],
+ getFullCount: () => dates()?.length ?? 0,
+ },
+ ];
+
+ if (props.showOpenTabs) {
+ buckets.unshift({
+ id: 'openTabs',
+ label: 'Open Tabs',
+ getData: () => openTabs() ?? [],
+ getFullCount: () => openTabs()?.length ?? 0,
+ });
+ }
+
+ return buckets.filter((bucket) => bucket.getFullCount() > 0);
+ });
+
+ const controller = useMentionsMenuController(bucketConfigs, {
+ ignoredIds: () => (blockId ? [blockId] : []),
+ maxItems: MAX_ITEMS,
+ });
+
+ const [escapeSpaceState, setEscapeSpaceState] = createSignal<
+ 'start' | 'single' | 'double' | null
+ >('start');
+
+ createEffect(() => {
+ if (!menuOpen()) {
+ setEscapeSpaceState('start');
+ controller.reset();
+ }
+ });
+
+ const itemAction = createItemHandler({
+ editor: props.editor,
+ blockName: useMaybeBlockName(),
+ blockId: useMaybeBlockId(),
+ onUserMention: props.onUserMention,
+ onDocumentMention: props.onDocumentMention,
+ onEmailMention: props.onEmailMention,
+ disableMentionTracking: props.disableMentionTracking,
+ useSnapshotNode: props.useSnapshotForDocuments,
+ });
+
+ createEffect(() => {
+ if (props.anchor) return;
+ if (menuOpen()) {
+ setMountSelection(document.getSelection());
+ controller.reset();
+ } else {
+ setMountSelection(null);
+ }
+ });
+
+ const closeMenu = () => {
+ props.editor.dispatchCommand(CLOSE_INLINE_SEARCH_COMMAND, undefined);
+ setMenuOpen(false);
+ };
+
+ useMenuKeyboardNavigation({
+ isActive: menuOpen,
+ onUp: () => {
+ controller.selectPrev();
+ },
+ onDown: () => {
+ controller.selectNext();
+ },
+ onLeft: () => {
+ if (controller.isViewAllMode()) {
+ controller.exitViewAll();
+ }
+ },
+ onRight: () => {
+ if (!controller.isViewAllMode()) {
+ const currentCategory = controller.selectedCategory();
+ if (currentCategory) {
+ if (
+ controller.canViewAllForCategory(currentCategory) ||
+ (emailUnifiedSearchInfiniteQuery.hasNextPage &&
+ currentCategory === 'emails')
+ ) {
+ controller.viewAll(currentCategory);
+ }
+ }
+ }
+ },
+ onSelect: () => {
+ const selectedItem = controller.selectedItem();
+ if (selectedItem) {
+ itemAction(selectedItem);
+ } else {
+ closeMenu();
+ }
+ props.menu.setSearchTerm('');
+ setMenuOpen(false);
+ },
+ onClose: () => {
+ if (controller.isViewAllMode()) {
+ controller.exitViewAll();
+ } else {
+ closeMenu();
+ }
+ },
+ onSpace: () => {
+ switch (escapeSpaceState()) {
+ case 'double':
+ case 'start':
+ closeMenu();
+ return true;
+ case 'single':
+ setEscapeSpaceState('double');
+ return false;
+ case null:
+ setEscapeSpaceState('single');
+ return false;
+ }
+ return false;
+ },
+ onOtherKey: () => {
+ setEscapeSpaceState(null);
+ },
+ });
+
+ const focusOut = () => {
+ closeMenu();
+ };
+
+ onMount(() => {
+ document.addEventListener('focusout', focusOut);
+ onCleanup(() => {
+ document.removeEventListener('focusout', focusOut);
+ });
+ });
+
+ createEffect(() => {
+ const items = controller.combinedItems();
+ if (!items) return;
+
+ if (
+ controller.selectedIndex() >= items.length - 5 &&
+ controller.viewAllMode() === 'emails' &&
+ emailUnifiedSearchInfiniteQuery.hasNextPage &&
+ !emailUnifiedSearchInfiniteQuery.isFetching
+ ) {
+ emailUnifiedSearchInfiniteQuery.fetchNextPage();
+ }
+ if (controller.selectedIndex() >= items.length) {
+ controller.selectItem(items.length - 1);
+ }
+ });
+
+ const handleViewAll = (binType: string) => {
+ controller.viewAll(binType);
+ };
+
+ const handleBackToAll = () => {
+ controller.exitViewAll();
+ };
+
+ const viewAllCategoryLabel = () => {
+ const mode = controller.viewAllMode();
+ if (!mode) return 'Items';
+ const bucket = bucketConfigs().find((b) => b.id === mode);
+ return bucket?.label || 'Items';
+ };
+
+ const visibleBuckets = () => {
+ const currentBins = controller.bins();
+ const seenIds = new Set<string>(blockId ? [blockId] : []);
+ let cumulativeIndex = 0;
+
+ return bucketConfigs()
+ .filter((config) => (currentBins[config.id] || 0) > 0)
+ .map((config) => {
+ const bucketLimit = currentBins[config.id] || 0;
+ const bucketItems: ReturnType<typeof config.getData> = [];
+
+ for (const item of config.getData()) {
+ if (bucketItems.length >= bucketLimit) break;
+ if (seenIds.has(item.id)) continue;
+ seenIds.add(item.id);
+ bucketItems.push(item);
+ }
+
+ const startIndex = cumulativeIndex;
+ cumulativeIndex += bucketItems.length;
+ return { config, bucketItems, startIndex };
+ });
+ };
+
+ const clickOutsideHandler = (e: MouseEvent) => {
+ e.stopPropagation();
+ props.editor.dispatchCommand(CLOSE_INLINE_SEARCH_COMMAND, undefined);
+ setMenuOpen(false);
+ };
+
+ const floatWithElementProps = () =>
+ props.anchor
+ ? {
+ element: () => props.anchor,
+ useBlockBoundary: props.useBlockBoundary,
+ }
+ : undefined;
+
+ const floatWithSelectionProps = () =>
+ !props.anchor
+ ? {
+ selection: untrack(mountSelection),
+ reactiveOnContainer: props.editor.getRootElement(),
+ useBlockBoundary: props.useBlockBoundary,
+ }
+ : undefined;
+
+ return (
+ <Show when={menuOpen()}>
+ <ScopedPortal scope={props.portalScope}>
+ <div
+ class="w-96 cursor-default select-none z-modal-content"
+ ref={(el) => {
+ floatWithElement(el, floatWithElementProps);
+ floatWithSelection(el, floatWithSelectionProps);
+ clickOutside(el, () => clickOutsideHandler);
+ }}
+ >
+ <ClippedPanel active tl class="py-2">
+ <Show
+ when={controller.combinedItems().length > 0}
+ fallback={<div class="px-2 text-ink-extra-muted">No results</div>}
+ >
+ <Show
+ when={controller.viewAllMode()}
+ fallback={
+ <div>
+ <For each={visibleBuckets()}>
+ {(bucket, idx) => (
+ <>
+ <Show when={idx() > 0}>
+ <div class="w-full mt-4 border-b-1 border-edge-muted mb-2" />
+ </Show>
+ <ItemBin
+ label={bucket.config.label}
+ binType={bucket.config.id}
+ totalCount={bucket.config.getFullCount()}
+ showingCount={bucket.bucketItems.length}
+ onViewAll={handleViewAll}
+ isSelected={
+ controller.selectedCategory() === bucket.config.id
+ }
+ >
+ <For each={bucket.bucketItems}>
+ {(item, i) => (
+ <MentionsMenuItem
+ item={item}
+ index={bucket.startIndex + i()}
+ selected={
+ bucket.startIndex + i() ===
+ controller.selectedIndex()
+ }
+ itemAction={itemAction}
+ setIndex={setSelectedIndexFromMouse}
+ setOpen={setMenuOpen}
+ />
+ )}
+ </For>
+ </ItemBin>
+ </>
+ )}
+ </For>
+ </div>
+ }
+ >
+ <div class="px-2 pb-2">
+ <div class="flex items-center justify-between">
+ <span class="text-xs font-medium text-ink-muted">
+ {viewAllCategoryLabel()}
+ </span>
+ <button
+ type="button"
+ class="text-xs font-medium text-ink-muted hover:text-ink hover:underline flex items-center gap-1"
+ onMouseDown={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ }}
+ onClick={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ handleBackToAll();
+ }}
+ >
+ <div class="p-0.5 px-1 -my-2 bg-panel text-ink border border-edge-muted rounded-xs text-xs">
+ ←
+ </div>
+ Back to everything
+ </button>
+ </div>
+ </div>
+ <VirtualizedItemList
+ items={controller.combinedItems()}
+ selectedIndex={controller.selectedIndex()}
+ itemAction={itemAction}
+ setIndex={setSelectedIndexFromMouse}
+ setOpen={setMenuOpen}
+ />
+ </Show>
+ </Show>
+ </ClippedPanel>
+ </div>
+ </ScopedPortal>
+ </Show>
+ );
+}
+
+function VirtualizedItemList(props: {
+ items: MentionItem[];
+ selectedIndex: number;
+ itemAction: (item: MentionItem) => void;
+ setIndex: (index: number) => void;
+ setOpen: (open: boolean) => void;
+}) {
+ let scrollContainerRef: HTMLDivElement | undefined;
+
+ const virtualizer = createVirtualizer({
+ get count() {
+ return props.items.length;
+ },
+ getScrollElement: () => scrollContainerRef ?? null,
+ estimateSize: () => VIRTUAL_ITEM_HEIGHT,
+ overscan: 5,
+ });
+
+ // Scroll selected item into view
+ createEffect(() => {
+ const index = props.selectedIndex;
+ if (index >= 0 && index < props.items.length) {
+ virtualizer.scrollToIndex(index, { align: 'auto' });
+ }
+ });
+
+ return (
+ <div
+ ref={scrollContainerRef}
+ class="max-h-64 overflow-y-auto scrollbar-hidden"
+ >
+ <div
+ style={{
+ height: `${virtualizer.getTotalSize()}px`,
+ width: '100%',
+ position: 'relative',
+ }}
+ >
+ <For each={virtualizer.getVirtualItems()}>
+ {(virtualRow) => {
+ const item = () => props.items[virtualRow.index];
+ return (
+ <Show when={item()}>
+ {(currentItem) => (
+ <div
+ style={{
+ position: 'absolute',
+ top: 0,
+ left: 0,
+ width: '100%',
+ height: `${virtualRow.size}px`,
+ transform: `translateY(${virtualRow.start}px)`,
+ }}
+ >
+ <MentionsMenuItem
+ item={currentItem()}
+ index={virtualRow.index}
+ selected={virtualRow.index === props.selectedIndex}
+ itemAction={props.itemAction}
+ setIndex={props.setIndex}
+ setOpen={props.setOpen}
+ disableScrollIntoView
+ />
+ </div>
+ )}
+ </Show>
+ );
+ }}
+ </For>
+ </div>
+ </div>
+ );
+}
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenuController.ts b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenuController.ts
new file mode 100644
index 0000000000..880f8b498b
--- /dev/null
+++ b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenuController.ts
@@ -0,0 +1,402 @@
+import type { Accessor, Signal } from 'solid-js';
+import { createSignal } from 'solid-js';
+import { createLazyMemo } from '@solid-primitives/memo';
+import type { MentionItem } from '../../../utils/mentionsUtils';
+
+export interface BucketConfig<T extends MentionItem = MentionItem> {
+ id: string;
+ label: string;
+ getData: () => T[];
+ getFullCount: () => number;
+}
+
+/**
+ * view mode
+ * - null: show all categories with limited items
+ * - string: show all items for the specified category
+ */
+export type ViewAllMode = string | null;
+
+/** the currently selected category id, or null if in view-all mode */
+export type SelectedCategory = string | null;
+
+/** result of bin computation - how many items to show per bucket */
+export type MentionBins = Record<string, number>;
+
+export class MentionsMenuController {
+ private buckets: Accessor<BucketConfig[]>;
+ private maxItems: number;
+ private ignoredIds: Accessor<string[]> = () => [];
+ private selectedIndexSignal: Signal<number>;
+ private viewAllModeSignal: Signal<ViewAllMode>;
+
+ constructor(
+ buckets: Accessor<BucketConfig[]>,
+ options: {
+ maxItems?: number;
+ ignoredIds?: Accessor<string[]>;
+ } = {}
+ ) {
+ this.buckets = buckets;
+ this.maxItems = options.maxItems ?? 8;
+ this.ignoredIds = options.ignoredIds ?? (() => []);
+
+ this.selectedIndexSignal = createSignal(0);
+ this.viewAllModeSignal = createSignal<ViewAllMode>(null);
+ }
+
+ get selectedIndex(): Accessor<number> {
+ return this.selectedIndexSignal[0];
+ }
+
+ get setSelectedIndex() {
+ return this.selectedIndexSignal[1];
+ }
+
+ get viewAllMode(): Accessor<ViewAllMode> {
+ return this.viewAllModeSignal[0];
+ }
+
+ get setViewAllMode() {
+ return this.viewAllModeSignal[1];
+ }
+
+ rawBins = createLazyMemo((): MentionBins => {
+ const buckets = this.buckets();
+ if (!buckets) return {};
+
+ const bins: MentionBins = {};
+ const seenIds = new Set<string>(this.ignoredIds());
+
+ // Count items per bucket, excluding items already seen in earlier buckets
+ buckets.forEach((config) => {
+ let count = 0;
+ for (const item of config.getData()) {
+ if (!seenIds.has(item.id)) {
+ seenIds.add(item.id);
+ count++;
+ }
+ }
+ bins[config.id] = count;
+ });
+
+ return bins;
+ });
+
+ bins = createLazyMemo((): MentionBins => {
+ return this.computeBins(this.rawBins(), this.maxItems);
+ });
+
+ combinedItems = createLazyMemo((): MentionItem[] => {
+ const buckets = this.buckets();
+ if (!buckets) return [];
+
+ const currentViewAllMode = this.viewAllMode();
+ const seenIds = new Set<string>(this.ignoredIds());
+
+ if (currentViewAllMode) {
+ const bucket = buckets.find((b) => b.id === currentViewAllMode);
+ if (!bucket) return [];
+
+ return bucket.getData().filter((item) => {
+ if (seenIds.has(item.id)) return false;
+ return true;
+ });
+ }
+
+ const result: MentionItem[] = [];
+ const currentBins = this.bins();
+
+ buckets.forEach((config) => {
+ const limit = currentBins[config.id] || 0;
+ if (limit === 0) return;
+
+ let added = 0;
+ for (const item of config.getData()) {
+ if (added >= limit) break;
+ if (seenIds.has(item.id)) continue;
+ seenIds.add(item.id);
+ result.push(item);
+ added++;
+ }
+ });
+
+ return result;
+ });
+
+ selectedCategory = createLazyMemo((): SelectedCategory => {
+ if (this.viewAllMode()) return null;
+
+ const buckets = this.buckets();
+ if (!buckets) return null;
+
+ const index = this.selectedIndex();
+ const currentBins = this.bins();
+ let currentIndex = 0;
+
+ for (const config of buckets) {
+ const count = currentBins[config.id] || 0;
+ if (count > 0) {
+ if (index < currentIndex + count) {
+ return config.id;
+ }
+ currentIndex += count;
+ }
+ }
+
+ return null;
+ });
+
+ selectedItem = createLazyMemo((): MentionItem | null => {
+ const items = this.combinedItems();
+ if (!items) return null;
+ const index = this.selectedIndex();
+ return items[index] ?? null;
+ });
+
+ totalItemCount = createLazyMemo((): number => {
+ const items = this.combinedItems();
+ return items?.length ?? 0;
+ });
+
+ selectNext(): void {
+ const items = this.combinedItems();
+ if (!items || items.length === 0) return;
+ const current = this.selectedIndex();
+ const next = current + 1;
+ this.setSelectedIndex(next >= items.length ? 0 : next);
+ }
+
+ selectPrev(): void {
+ const items = this.combinedItems();
+ if (!items || items.length === 0) return;
+ const current = this.selectedIndex();
+ const prev = current - 1;
+ this.setSelectedIndex(prev < 0 ? items.length - 1 : prev);
+ }
+
+ selectItem(index: number): void {
+ const items = this.combinedItems();
+ if (!items) return;
+ if (index >= 0 && index < items.length) {
+ this.setSelectedIndex(index);
+ }
+ }
+
+ selectNextCategory(): void {
+ if (this.viewAllMode()) {
+ this.selectNext();
+ return;
+ }
+
+ const currentCategory = this.selectedCategory();
+ const currentBins = this.bins();
+ const configs = this.buckets();
+ if (!configs) return;
+
+ if (!currentCategory) {
+ this.setSelectedIndex(0);
+ return;
+ }
+
+ const currentCategoryIndex = configs.findIndex(
+ (c) => c.id === currentCategory
+ );
+
+ if (currentCategoryIndex === -1) {
+ this.setSelectedIndex(0);
+ return;
+ }
+
+ let nextCategoryIndex = currentCategoryIndex + 1;
+ while (nextCategoryIndex < configs.length) {
+ const nextConfig = configs[nextCategoryIndex];
+ if (currentBins[nextConfig.id] > 0) {
+ let offset = 0;
+ for (let i = 0; i < nextCategoryIndex; i++) {
+ offset += currentBins[configs[i].id] || 0;
+ }
+ this.setSelectedIndex(offset);
+ return;
+ }
+ nextCategoryIndex++;
+ }
+
+ this.setSelectedIndex(0);
+ }
+
+ selectPrevCategory(): void {
+ if (this.viewAllMode()) {
+ this.selectPrev();
+ return;
+ }
+
+ const currentCategory = this.selectedCategory();
+ const currentBins = this.bins();
+ const configs = this.buckets();
+ if (!configs) return;
+
+ if (!currentCategory) {
+ this.setSelectedIndex(this.totalItemCount() - 1);
+ return;
+ }
+
+ const currentCategoryIndex = configs.findIndex(
+ (c) => c.id === currentCategory
+ );
+
+ if (currentCategoryIndex === -1) {
+ this.setSelectedIndex(0);
+ return;
+ }
+
+ let prevCategoryIndex = currentCategoryIndex - 1;
+ while (prevCategoryIndex >= 0) {
+ const prevConfig = configs[prevCategoryIndex];
+ if (currentBins[prevConfig.id] > 0) {
+ // Jump to first item of previous category
+ let offset = 0;
+ for (let i = 0; i < prevCategoryIndex; i++) {
+ offset += currentBins[configs[i].id] || 0;
+ }
+ this.setSelectedIndex(offset);
+ return;
+ }
+ prevCategoryIndex--;
+ }
+
+ let lastOffset = 0;
+ for (let i = 0; i < configs.length - 1; i++) {
+ lastOffset += currentBins[configs[i].id] || 0;
+ }
+ this.setSelectedIndex(lastOffset);
+ }
+
+ viewAll(bucketId: string): void {
+ this.setViewAllMode(bucketId);
+ this.setSelectedIndex(0);
+ }
+
+ exitViewAll(): void {
+ this.setViewAllMode(null);
+ this.setSelectedIndex(0);
+ }
+
+ toggleViewAllForCurrentCategory(): void {
+ const category = this.selectedCategory();
+ if (category) {
+ this.viewAll(category);
+ }
+ }
+
+ isViewAllMode(): boolean {
+ return this.viewAllMode() !== null;
+ }
+
+ hasOnlyOneCategory = createLazyMemo((): boolean => {
+ const configs = this.buckets();
+ if (!configs) return false;
+ const nonEmptyCount = configs.filter(
+ (config) => config.getFullCount() > 0
+ ).length;
+ return nonEmptyCount === 1;
+ });
+
+ reset(): void {
+ this.setSelectedIndex(0);
+ this.setViewAllMode(null);
+ }
+
+ getBucket(id: string): BucketConfig | undefined {
+ const buckets = this.buckets();
+ if (!buckets) return undefined;
+ return buckets.find((b) => b.id === id);
+ }
+
+ getAllBuckets(): BucketConfig[] {
+ return this.buckets() ?? [];
+ }
+
+ canViewAllForCategory(categoryId: string): boolean {
+ const currentBins = this.bins();
+ const rawBins = this.rawBins();
+ const abbreviatedCount = currentBins[categoryId] || 0;
+ const fullCount = rawBins[categoryId] || 0;
+ return fullCount > abbreviatedCount;
+ }
+
+ private computeBins(rawBins: MentionBins, maxItems: number): MentionBins {
+ const total = Object.values(rawBins).reduce((sum, count) => sum + count, 0);
+
+ // If total items fit in max, no scaling needed
+ if (total <= maxItems) {
+ return { ...rawBins };
+ }
+
+ // Allocate items proportionally, ensuring each non-empty bin gets at least 1
+ const scaled: MentionBins = {};
+
+ const nonEmptyBins = Object.entries(rawBins).filter(
+ ([_, count]) => count > 0
+ );
+
+ let allocated = 0;
+
+ // First pass: give each non-empty bin at least 1 item
+ for (const [key, count] of nonEmptyBins) {
+ if (count > 0) {
+ scaled[key] = 1;
+ allocated += 1;
+ }
+ }
+
+ // Second pass: distribute remaining slots proportionally
+ const remaining = maxItems - allocated;
+
+ if (remaining > 0) {
+ const nonEmptyTotal = nonEmptyBins.reduce((sum, [_, c]) => sum + c, 0);
+ const remainders: Array<{ key: string; remainder: number }> = [];
+ let totalFloorsAdded = 0;
+
+ for (const [key, count] of nonEmptyBins) {
+ const proportion = count / nonEmptyTotal;
+ const raw = proportion * remaining;
+ const floor = Math.floor(raw);
+ const remainder = raw - floor;
+
+ scaled[key] = (scaled[key] || 0) + floor;
+ totalFloorsAdded += floor;
+ remainders.push({ key, remainder });
+ }
+
+ // Distribute leftover items to bins with largest remainders
+ const leftover = remaining - totalFloorsAdded;
+ const sorted = remainders.sort((a, b) => b.remainder - a.remainder);
+
+ for (let i = 0; i < leftover && i < sorted.length; i++) {
+ const key = sorted[i].key;
+ scaled[key] = (scaled[key] || 0) + 1;
+ }
+ }
+
+ // Ensure we don't exceed actual bin counts
+ for (const [key, count] of Object.entries(scaled)) {
+ scaled[key] = Math.min(count, rawBins[key] || 0);
+ }
+
+ return scaled;
+ }
+}
+
+export function useMentionsMenuController(
+ buckets: Accessor<BucketConfig[]>,
+ options: {
+ maxItems?: number;
+ ignoredIds?: Accessor<string[]>;
+ } = {}
+): MentionsMenuController {
+ return new MentionsMenuController(buckets, {
+ maxItems: options.maxItems,
+ ignoredIds: options.ignoredIds,
+ });
+}
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/components/ItemBin.tsx b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/components/ItemBin.tsx
new file mode 100644
index 0000000000..8dc74086b4
--- /dev/null
+++ b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/components/ItemBin.tsx
@@ -0,0 +1,74 @@
+import type { Accessor, ParentProps } from 'solid-js';
+import { Show } from 'solid-js';
+import { cn } from '@ui/utils/classname';
+
+export function ItemBin(
+ props: ParentProps<{
+ label: string;
+ binType: string;
+ isNextPage?: Accessor<boolean>;
+ totalCount?: number;
+ showingCount?: number;
+ onViewAll?: (binType: string) => void;
+ isSelected?: boolean;
+ }>
+) {
+ const showViewAllButton = () => {
+ return (
+ (props.totalCount !== undefined &&
+ props.showingCount !== undefined &&
+ props.totalCount > props.showingCount) ||
+ props.isNextPage?.() === true
+ );
+ };
+
+ const viewAllText = () => {
+ if (
+ props.totalCount &&
+ props.showingCount &&
+ props.totalCount > props.showingCount
+ ) {
+ return `View all (${props.totalCount})`;
+ }
+ if (props.isNextPage?.()) {
+ return 'View all';
+ }
+ return 'View all';
+ };
+
+ return (
+ <>
+ <div
+ class={cn(
+ 'text-xs font-medium p-2 pt-0 flex justify-between items-center',
+ props.isSelected ? 'text-ink-muted' : 'text-ink-extra-muted'
+ )}
+ >
+ <span class="flex items-center gap-1.5">{props.label}</span>
+ <Show when={showViewAllButton()}>
+ <button
+ type="button"
+ class="text-xs font-medium hover:text-ink hover:underline flex items-center gap-1"
+ onMouseDown={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ }}
+ onClick={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ props.onViewAll?.(props.binType);
+ }}
+ >
+ <Show when={props.isSelected && showViewAllButton()}>
+ <div class="p-0.5 px-1 -my-2 bg-panel text-ink border border-edge-muted rounded-xs text-xs">
+ →
+ </div>
+ </Show>
+ {viewAllText()}
+ </button>
+ </Show>
+ </div>
+ {props.children}
+ </>
+ );
+}
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/components/MentionsMenuItem.tsx b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/components/MentionsMenuItem.tsx
new file mode 100644
index 0000000000..f4dad49670
--- /dev/null
+++ b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/components/MentionsMenuItem.tsx
@@ -0,0 +1,99 @@
+import { createEffect } from 'solid-js';
+import { EntityIcon } from '@core/component/EntityIcon';
+import { UserIcon } from '@core/component/UserIcon';
+import ClockIcon from '@icon/regular/clock.svg';
+import EmailIcon from '@icon/regular/envelope.svg';
+import UsersIcon from '@icon/regular/users.svg';
+import type { ChannelEntity } from '@entity';
+import type { MentionItem } from '../../../../utils/mentionsUtils';
+import {
+ getBlockNameFromEntity,
+ getMentionItemName,
+} from '../utils/entityUtils';
+
+export function MentionsMenuItem(props: {
+ item: MentionItem;
+ index: number;
+ selected: boolean;
+ itemAction: (item: MentionItem) => void;
+ setIndex: (index: number) => void;
+ setOpen: (open: boolean) => void;
+ /** When true, disables the internal scrollIntoView behavior (used when list is virtualized) */
+ disableScrollIntoView?: boolean;
+}) {
+ let itemRef: HTMLDivElement | undefined;
+
+ createEffect(() => {
+ if (props.selected && itemRef && !props.disableScrollIntoView) {
+ itemRef.scrollIntoView({ block: 'nearest' });
+ }
+ });
+
+ const name = () => getMentionItemName(props.item);
+
+ const icon = () => {
+ switch (props.item.kind) {
+ case 'user':
+ return <UserIcon id={props.item.id} size="xs" isDeleted={false} />;
+
+ case 'group':
+ return <UsersIcon class="size-4 text-ink-muted" />;
+
+ case 'date':
+ return <ClockIcon class="size-4 text-ink-muted" />;
+
+ case 'entity':
+ if (props.item.bucket === 'email') {
+ return <EmailIcon class="size-4 text-ink-muted" />;
+ }
+ if (props.item.bucket === 'channel' || props.item.bucket === 'dm') {
+ const entity = props.item.data as ChannelEntity;
+ return (
+ <EntityIcon
+ size="xs"
+ targetType={entity.channelType || 'channel'}
+ />
+ );
+ }
+ return (
+ <EntityIcon
+ targetType={getBlockNameFromEntity(props.item)}
+ size="xs"
+ />
+ );
+
+ case 'command':
+ return null;
+ }
+ };
+
+ return (
+ <div
+ ref={itemRef}
+ on:mouseup={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ }}
+ on:mousedown={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ }}
+ on:click={(e) => {
+ props.itemAction(props.item);
+ props.setOpen(false);
+ e.stopPropagation();
+ }}
+ on:mousemove={() => props.setIndex(props.index)}
+ class="group flex items-center p-1.5 mx-1.5"
+ classList={{ 'bg-active bracket': props.selected }}
+ >
+ <div class="mr-2">{icon()}</div>
+ <span
+ class="text-ink text-xs sm:text-sm font-medium grow overflow-hidden text-nowrap"
+ style={{ 'text-overflow': 'ellipsis' }}
+ >
+ {name()}
+ </span>
+ </div>
+ );
+}
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useEmailSearchMention.ts b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useEmailSearchMention.ts
new file mode 100644
index 0000000000..647be13abf
--- /dev/null
+++ b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useEmailSearchMention.ts
@@ -0,0 +1,82 @@
+import type { Accessor } from 'solid-js';
+import { createLazyMemo } from '@solid-primitives/memo';
+import type { EntityItem } from '@core/context/quickAccess';
+import { createFreshSearch } from '@core/util/freshSort';
+import {
+ type SearchSoupQueryArgs,
+ useSearchSoupQuery,
+} from '@queries/soup/search';
+
+export type UseEmailSearchMentionOptions = {
+ searchTerm: Accessor<string>;
+};
+
+export type UseEmailSearchMentionResult = {
+ emails: Accessor<EntityItem[]>;
+ emailSearchQuery: ReturnType<typeof useSearchSoupQuery>;
+};
+
+/**
+ * Hook for managing email mentions in the mentions menu with query-based search.
+ */
+export function useEmailSearchMention(
+ options: UseEmailSearchMentionOptions
+): UseEmailSearchMentionResult {
+ const { searchTerm } = options;
+
+ // Build search query args for remote email search
+ const args = createLazyMemo((): SearchSoupQueryArgs => {
+ return {
+ params: {
+ cursor: null,
+ page_size: 10,
+ },
+ body: {
+ match_type: 'partial',
+ search_on: 'name',
+ include: ['emails'],
+ query: searchTerm(),
+ },
+ };
+ });
+
+ const emailSearchQuery = useSearchSoupQuery(args);
+
+ const emailList = createLazyMemo((): EntityItem[] => {
+ if (emailSearchQuery.status !== 'success') return [];
+ return emailSearchQuery.data
+ .filter((e) => e.type === 'email')
+ .map(
+ (e): EntityItem => ({
+ kind: 'entity',
+ id: e.id,
+ bucket: 'email',
+ searchText: e.name ?? 'No Subject',
+ sortTimestamp: e.updatedAt ? new Date(e.updatedAt).getTime() : 0,
+ timestamps: {
+ updatedAt: e.updatedAt ?? null,
+ createdAt: e.createdAt ?? null,
+ },
+ data: e as unknown as EntityItem['data'],
+ })
+ );
+ });
+
+ const emailSearch = createFreshSearch<EntityItem>(
+ { timeWeight: 0, brevityWeight: 0.3 },
+ (item) => item.searchText,
+ (_item) => false,
+ (item) => item.timestamps
+ );
+
+ const emails = createLazyMemo((): EntityItem[] => {
+ const term = searchTerm();
+ if (!term) return emailList();
+ return emailSearch(emailList(), term).map(({ item }) => item);
+ });
+
+ return {
+ emails,
+ emailSearchQuery,
+ };
+}
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useEntityMention.ts b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useEntityMention.ts
new file mode 100644
index 0000000000..14668ed078
--- /dev/null
+++ b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useEntityMention.ts
@@ -0,0 +1,51 @@
+import type { Accessor } from 'solid-js';
+import { createLazyMemo } from '@solid-primitives/memo';
+import {
+ useQuickAccess,
+ type EntityItem,
+ type EntityBucket,
+} from '@core/context/quickAccess';
+import { createFreshSearch } from '@core/util/freshSort';
+
+export type UseEntityMentionOptions = {
+ searchTerm: Accessor<string>;
+ buckets: EntityBucket[];
+};
+
+export type UseEntityMentionResult = {
+ searchedEntities: Accessor<EntityItem[]>;
+ allEntities: Accessor<EntityItem[]>;
+};
+
+/**
+ * Generic hook for managing entity mentions in the mentions menu.
+ * Can be used for documents, channels, or any combination of entity buckets.
+ */
+export function useEntityMention(
+ options: UseEntityMentionOptions
+): UseEntityMentionResult {
+ const { searchTerm, buckets } = options;
+ const quickAccess = useQuickAccess();
+
+ const entitiesList = quickAccess.useList(
+ ...(buckets as [EntityBucket, ...EntityBucket[]])
+ );
+
+ const entitySearch = createFreshSearch<EntityItem>(
+ { useViewedAt: true },
+ (item) => item.searchText,
+ (item) => item.bucket === 'channel',
+ (item) => item.timestamps
+ );
+
+ const entities = createLazyMemo(() => {
+ const term = searchTerm();
+ if (!term) return entitiesList();
+ return entitySearch(entitiesList(), term).map(({ item }) => item);
+ });
+
+ return {
+ searchedEntities: entities,
+ allEntities: entitiesList,
+ };
+}
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useUsersMention.ts b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useUsersMention.ts
new file mode 100644
index 0000000000..0289b9f9d5
--- /dev/null
+++ b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useUsersMention.ts
@@ -0,0 +1,115 @@
+import type { Accessor } from 'solid-js';
+import { createLazyMemo } from '@solid-primitives/memo';
+import { useQuickAccess, type UserItem } from '@core/context/quickAccess';
+import type { IUser } from '@core/user';
+import { createFreshSearch, FreshSearchPresets } from '@core/util/freshSort';
+import { useEmail } from '@core/context/user';
+import type { GroupMentionItem } from '../../../../utils/mentionsUtils';
+
+export type UseUsersMentionOptions = {
+ /** Custom users list if necessary */
+ users?: Accessor<IUser[]>;
+ searchTerm: Accessor<string>;
+ isChannelBlock?: boolean;
+ blockId?: string;
+};
+
+export type UseUsersMentionResult = {
+ users: Accessor<UserItem[]>;
+ currentUserDomain: Accessor<string | undefined>;
+ groups: Accessor<GroupMentionItem[]>;
+ usersAndGroups: Accessor<(UserItem | GroupMentionItem)[]>;
+};
+
+/** Available group aliases and their match functions */
+const GROUPS = [
+ {
+ alias: 'here',
+ match: (term: string) => term === '' || 'here'.startsWith(term),
+ },
+] as const;
+
+/**
+ * Hook for managing user mentions in the mentions menu.
+ * Handles user list retrieval, search, filtering, and special groups.
+ */
+export function useUsersMention(
+ options: UseUsersMentionOptions
+): UseUsersMentionResult {
+ const { users: customUsers, searchTerm, isChannelBlock, blockId } = options;
+ const quickAccess = useQuickAccess();
+ const currentUserEmail = useEmail();
+
+ const currentUserDomain = () => {
+ const email = currentUserEmail();
+ return email ? email.split('@')[1] : undefined;
+ };
+
+ const usersList = createLazyMemo(() => {
+ if (customUsers) {
+ const users = customUsers;
+ return () =>
+ users().map(
+ (user) =>
+ ({
+ id: user.id,
+ data: user,
+ kind: 'user' as const,
+ bucket: 'person' as const,
+ sortTimestamp: 0,
+ timestamps: {},
+ searchText: user.name
+ ? user.name + ' | ' + user.email
+ : user.email + ' | ' + user.email,
+ }) as UserItem
+ );
+ }
+ return quickAccess.useList('person');
+ });
+
+ const userSearch = () =>
+ createFreshSearch<UserItem>(
+ FreshSearchPresets.baseUserSearch<UserItem>(
+ currentUserDomain,
+ (item) => item.data.email
+ ),
+ (item) => item.searchText,
+ (_) => false,
+ (item) => ({ lastInteraction: item.timestamps.lastInteraction })
+ );
+
+ const users = createLazyMemo(() => {
+ const term = searchTerm();
+ if (!term) return usersList()();
+ return userSearch()(usersList()(), term).map(({ item }) => item);
+ });
+
+ /**
+ * Special groups like @here that are only available in channel blocks.
+ * These are filtered based on the current search term.
+ */
+ const groups = (): GroupMentionItem[] => {
+ if (!isChannelBlock || !blockId) return [];
+
+ const term = searchTerm().toLowerCase();
+
+ return GROUPS.filter((g) => g.match(term)).map(
+ (g): GroupMentionItem => ({
+ kind: 'group',
+ id: g.alias,
+ data: { id: g.alias, groupAlias: g.alias },
+ })
+ );
+ };
+
+ const usersAndGroups = createLazyMemo((): (UserItem | GroupMentionItem)[] => {
+ return [...groups(), ...users()];
+ });
+
+ return {
+ users,
+ currentUserDomain,
+ groups,
+ usersAndGroups,
+ };
+}
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/index.ts b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/index.ts
new file mode 100644
index 0000000000..aaebe16e74
--- /dev/null
+++ b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/index.ts
@@ -0,0 +1 @@
+export { MentionsMenu } from './MentionsMenu';
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/entityUtils.ts b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/entityUtils.ts
new file mode 100644
index 0000000000..ec4aaa3bbc
--- /dev/null
+++ b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/entityUtils.ts
@@ -0,0 +1,49 @@
+import type { BlockAlias, BlockName } from '@core/block';
+import { fileTypeToBlockName } from '@core/constant/allBlocks';
+import type { EntityItem } from '@core/context/quickAccess';
+import type { MentionItem } from '../../../../utils/mentionsUtils';
+import { match } from 'ts-pattern';
+
+/**
+ * Get the block name from an entity item for use in mentions.
+ */
+export function getBlockNameFromEntity(
+ item: EntityItem
+): BlockName | BlockAlias {
+ return match(item.bucket)
+ .with('channel', () => 'channel' as const)
+ .with('dm', () => 'channel' as const)
+ .with('email', () => 'email' as const)
+ .with('chat', () => 'chat' as const)
+ .with('project', () => 'project' as const)
+ .with('task', () => 'task' as const)
+ .with('note', () => 'md' as const)
+ .otherwise(() => {
+ const entity = item.data;
+ if ('fileType' in entity && typeof entity.fileType === 'string') {
+ return fileTypeToBlockName(entity.fileType);
+ }
+ return 'unknown';
+ });
+}
+
+/**
+ * Get display name for a MentionItem.
+ */
+export function getMentionItemName(item: MentionItem): string {
+ switch (item.kind) {
+ case 'user': {
+ const { email, name } = item.data;
+ if (name === email) return email;
+ return `${name} | ${email}`;
+ }
+ case 'group':
+ return `@${item.data.groupAlias}`;
+ case 'date':
+ return item.data.displayText;
+ case 'entity':
+ return item.data.name ?? (item.bucket === 'email' ? 'No Subject' : '');
+ case 'command':
+ return item.searchText ?? '';
+ }
+}
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mentionHandlers.ts b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mentionHandlers.ts
new file mode 100644
index 0000000000..8677f1fa9e
--- /dev/null
+++ b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mentionHandlers.ts
@@ -0,0 +1,121 @@
+import type { EntityItem } from '@core/context/quickAccess';
+import type { ChannelEntity, EmailEntity } from '@entity';
+import { trackMention } from '@core/signal/mention';
+import {
+ INSERT_DATE_MENTION_COMMAND,
+ INSERT_DOCUMENT_MENTION_COMMAND,
+ INSERT_GROUP_MENTION_COMMAND,
+} from '../../../../plugins/mentions';
+import { REMOVE_INLINE_SEARCH_COMMAND } from '../../../../plugins';
+import type {
+ HandlerDependencies,
+ MentionItem,
+} from '../../../../utils/mentionsUtils';
+import { handleUserMention } from '../../../../utils/mentionsUtils';
+import type { DateOption } from '@core/util/dateSearch/useDateSearch';
+import { getBlockNameFromEntity } from './entityUtils';
+
+/**
+ * Handle entity mention (documents, channels, emails, etc.).
+ */
+export async function handleEntityMention(
+ item: EntityItem,
+ dependencies: HandlerDependencies
+): Promise<void> {
+ const {
+ editor,
+ blockName,
+ blockId,
+ onDocumentMention,
+ disableMentionTracking,
+ onEmailMention,
+ } = dependencies;
+
+ const entity = item.data;
+
+ let mentionId: string | undefined;
+ if (
+ blockId &&
+ blockName !== 'channel' &&
+ blockName !== 'chat' &&
+ !disableMentionTracking
+ ) {
+ const trackType =
+ item.bucket === 'channel' || item.bucket === 'dm'
+ ? 'channel'
+ : 'document';
+ mentionId = await trackMention(blockId, trackType, entity.id);
+ }
+
+ const blockNameForMention = getBlockNameFromEntity(item);
+ const itemName = entity.name ?? (item.bucket === 'email' ? 'No Subject' : '');
+
+ if (item.bucket === 'email') {
+ onEmailMention?.(entity as unknown as EmailEntity);
+ } else {
+ onDocumentMention?.(entity as unknown as any);
+ }
+
+ editor.dispatchCommand(INSERT_DOCUMENT_MENTION_COMMAND, {
+ documentId: entity.id,
+ documentName: itemName,
+ blockName: blockNameForMention,
+ mentionUuid: mentionId,
+ channelType:
+ item.bucket === 'channel' || item.bucket === 'dm'
+ ? (entity as ChannelEntity).channelType
+ : undefined,
+ });
+}
+
+/**
+ * Handle date mention from DateOption.
+ */
+export async function handleDateMentionFromOption(
+ dateOption: DateOption,
+ dependencies: HandlerDependencies
+): Promise<void> {
+ const { editor } = dependencies;
+ editor.dispatchCommand(INSERT_DATE_MENTION_COMMAND, {
+ date: dateOption.date.toISOString(),
+ displayFormat: dateOption.displayText,
+ });
+}
+
+/**
+ * Handle group mention (e.g., @here).
+ */
+export async function handleGroupMentionItem(
+ group: { id: string; groupAlias: string },
+ dependencies: HandlerDependencies
+): Promise<void> {
+ const { editor } = dependencies;
+ editor.dispatchCommand(INSERT_GROUP_MENTION_COMMAND, {
+ groupAlias: group.groupAlias,
+ });
+}
+
+/**
+ * Creates a handler for MentionItem selection.
+ */
+export function createItemHandler(dependencies: HandlerDependencies) {
+ return async (item: MentionItem): Promise<void> => {
+ if (!item) return;
+ dependencies.editor.dispatchCommand(
+ REMOVE_INLINE_SEARCH_COMMAND,
+ undefined
+ );
+ switch (item.kind) {
+ case 'user':
+ return await handleUserMention(item.data, dependencies);
+ case 'date':
+ return await handleDateMentionFromOption(item.data, dependencies);
+ case 'group':
+ return await handleGroupMentionItem(item.data, dependencies);
+ case 'entity':
+ return await handleEntityMention(item, dependencies);
+ case 'command':
+ return;
+ }
+ };
+}
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/menu/useMenuKeyboardNavigation.ts b/js/app/packages/core/component/LexicalMarkdown/component/menu/useMenuKeyboardNavigation.ts
new file mode 100644
index 0000000000..1e6210e97f
--- /dev/null
+++ b/js/app/packages/core/component/LexicalMarkdown/component/menu/useMenuKeyboardNavigation.ts
@@ -0,0 +1,189 @@
+import { onCleanup, onMount } from 'solid-js';
+
+export type MenuKeyboardHandlers = {
+ /** Called when the user navigates up (ArrowUp, Ctrl+K, Ctrl+P, Shift+Tab) */
+ onUp?: (e: KeyboardEvent) => void;
+
+ /** Called when the user navigates down (ArrowDown, Ctrl+J, Ctrl+N, Tab) */
+ onDown?: (e: KeyboardEvent) => void;
+
+ /** Called when the user navigates left (ArrowLeft) */
+ onLeft?: (e: KeyboardEvent) => void;
+
+ /** Called when the user navigates right (ArrowRight) */
+ onRight?: (e: KeyboardEvent) => void;
+
+ /** Called when the user confirms selection (Enter) */
+ onSelect?: (e: KeyboardEvent) => void;
+
+ /** Called when the user cancels/closes (Escape) */
+ onClose?: (e: KeyboardEvent) => void;
+
+ /**
+ * Called when the user presses Space.
+ * Return `true` to preventDefault/stopPropagation, `false` to let it through.
+ */
+ onSpace?: (e: KeyboardEvent) => boolean;
+
+ /** Called for any key that doesn't match a navigation handler. */
+ onOtherKey?: (e: KeyboardEvent) => void;
+
+ /**
+ * Guard function - if returns false, no handlers are called.
+ */
+ isActive?: () => boolean;
+
+ /**
+ * Whether to use capture phase for the event listener.
+ * @default true
+ */
+ capture?: boolean;
+
+ /**
+ * Whether to automatically call e.preventDefault() and e.stopPropagation()
+ * when a handler is matched.
+ * @default true
+ */
+ preventDefault?: boolean;
+};
+
+/**
+ * Creates a keyboard handler that maps various key combinations to
+ * directional navigation callbacks.
+ *
+ * Key mappings:
+ * - Up: ArrowUp, Ctrl+K, Ctrl+P, Shift+Tab
+ * - Down: ArrowDown, Ctrl+J, Ctrl+N, Tab (without Shift)
+ * - Left: ArrowLeft
+ * - Right: ArrowRight
+ * - Select: Enter
+ * - Close: Escape
+ * - Space: Space
+ *
+ * @example
+ * ```ts
+ * const { handleKeyDown } = createMenuKeyboardNavigation({
+ * isActive: () => menuOpen(),
+ * onUp: () => setSelectedIndex(i => Math.max(0, i - 1)),
+ * onDown: () => setSelectedIndex(i => Math.min(items.length - 1, i + 1)),
+ * onSelect: () => selectCurrentItem(),
+ * onClose: () => setMenuOpen(false),
+ * onSpace: () => handleEscapeSpace(),
+ * onOtherKey: () => resetEscapeSpaceState(),
+ * });
+ * ```
+ */
+export function createMenuKeyboardNavigation(handlers: MenuKeyboardHandlers): {
+ handleKeyDown: (e: KeyboardEvent) => void;
+} {
+ const {
+ onUp,
+ onDown,
+ onLeft,
+ onRight,
+ onSelect,
+ onClose,
+ onSpace,
+ onOtherKey,
+ isActive,
+ preventDefault = true,
+ } = handlers;
+
+ const handleKeyDown = (e: KeyboardEvent) => {
+ if (isActive && !isActive()) return;
+
+ let handler: ((e: KeyboardEvent) => void) | undefined;
+
+ switch (e.key) {
+ case 'ArrowUp':
+ handler = onUp;
+ break;
+
+ case 'ArrowDown':
+ handler = onDown;
+ break;
+
+ case 'ArrowLeft':
+ handler = onLeft;
+ break;
+
+ case 'ArrowRight':
+ handler = onRight;
+ break;
+
+ case 'Tab':
+ handler = e.shiftKey ? onUp : onDown;
+ break;
+
+ case 'j':
+ if (e.ctrlKey || e.metaKey) {
+ handler = onDown;
+ }
+ break;
+
+ case 'k':
+ if (e.ctrlKey || e.metaKey) {
+ handler = onUp;
+ }
+ break;
+
+ case 'n':
+ if (e.ctrlKey) {
+ handler = onDown;
+ }
+ break;
+
+ case 'p':
+ if (e.ctrlKey) {
+ handler = onUp;
+ }
+ break;
+
+ case 'Enter':
+ handler = onSelect;
+ break;
+
+ case 'Escape':
+ handler = onClose;
+ break;
+
+ case ' ':
+ if (onSpace) {
+ const shouldPrevent = onSpace(e);
+ if (shouldPrevent) {
+ e.preventDefault();
+ e.stopPropagation();
+ }
+ }
+ return;
+ }
+
+ if (handler) {
+ if (preventDefault) {
+ e.preventDefault();
+ e.stopPropagation();
+ }
+ handler(e);
+ } else {
+ onOtherKey?.(e);
+ }
+ };
+
+ return { handleKeyDown };
+}
+
+export function useMenuKeyboardNavigation(handlers: MenuKeyboardHandlers): {
+ handleKeyDown: (e: KeyboardEvent) => void;
+} {
+ const { handleKeyDown } = createMenuKeyboardNavigation(handlers);
+ const capture = handlers.capture ?? true;
+
+ onMount(() => {
+ document.addEventListener('keydown', handleKeyDown, { capture });
+ onCleanup(() => {
+ document.removeEventListener('keydown', handleKeyDown, { capture });
+ });
+ });
+
+ return { handleKeyDown };
+}
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/misc/MentionsTextarea.tsx b/js/app/packages/core/component/LexicalMarkdown/component/misc/MentionsTextarea.tsx
index eabfa34080..7c4e82f3e8 100644
--- a/js/app/packages/core/component/LexicalMarkdown/component/misc/MentionsTextarea.tsx
+++ b/js/app/packages/core/component/LexicalMarkdown/component/misc/MentionsTextarea.tsx
@@ -197,10 +197,7 @@ export function MentionsTextarea(props: MentionsTextareaProps) {
menu={mentionsMenuOperations}
anchor={props.anchor}
onUserMention={props.onContactMention}
- history={() => []}
- channels={() => []}
portalScope={props.portalScope}
- emails={() => []}
/>
</div>
</LexicalWrapperContext.Provider>
diff --git a/js/app/packages/core/component/LexicalMarkdown/utils/mentionsUtils.ts b/js/app/packages/core/component/LexicalMarkdown/utils/mentionsUtils.ts
index e88a950294..45fd79db2d 100644
--- a/js/app/packages/core/component/LexicalMarkdown/utils/mentionsUtils.ts
+++ b/js/app/packages/core/component/LexicalMarkdown/utils/mentionsUtils.ts
@@ -1,8 +1,10 @@
import type { BlockAlias, BlockName } from '@core/block';
import { fileTypeToBlockName } from '@core/constant/allBlocks';
+import type { QuickAccessItem } from '@core/context/quickAccess';
import { trackMention } from '@core/signal/mention';
import type { ChannelWithParticipants, IUser } from '@core/user';
import type { ParsedDate } from '@core/util/dateParser';
+import type { DateOption } from '@core/util/dateSearch/useDateSearch';
import type { EmailEntity } from '@entity';
import { waitBulkUploadStatus } from '@service-connection/bulkUpload';
import type { DocumentMentionMetadata } from '@service-notification/client';
@@ -351,3 +353,52 @@ export async function handleChannelMention(
channelType: channel.channel_type,
});
}
+
+// ============================================================================
+// MentionItem Types
+// ============================================================================
+// These types extend QuickAccessItem to support dates and groups in the
+// mentions menu, which aren't part of the standard quick access system.
+
+/**
+ * Date mention item using DateOption from useDateSearch.
+ */
+export type DateMentionItem = {
+ kind: 'date';
+ id: string;
+ data: DateOption;
+};
+
+/**
+ * Group mention item (e.g., @here).
+ */
+export type GroupMentionItem = {
+ kind: 'group';
+ id: string;
+ data: {
+ id: string;
+ groupAlias: string;
+ };
+};
+
+/**
+ * MentionItem = QuickAccessItem + Date + Group.
+ * Used in MentionsMenu to unify all mentionable item types.
+ */
+export type MentionItem = QuickAccessItem | DateMentionItem | GroupMentionItem;
+
+/**
+ * Type guard for DateMentionItem.
+ */
+export function isDateMentionItem(item: MentionItem): item is DateMentionItem {
+ return item.kind === 'date';
+}
+
+/**
+ * Type guard for GroupMentionItem.
+ */
+export function isGroupMentionItem(
+ item: MentionItem
+): item is GroupMentionItem {
+ return item.kind === 'group';
+}
diff --git a/js/app/packages/core/context/quickAccess/QuickAccessProvider.tsx b/js/app/packages/core/context/quickAccess/QuickAccessProvider.tsx
new file mode 100644
index 0000000000..2ed8e64e53
--- /dev/null
+++ b/js/app/packages/core/context/quickAccess/QuickAccessProvider.tsx
@@ -0,0 +1,532 @@
+import type { Accessor } from 'solid-js';
+import { createEffect, createSignal } from 'solid-js';
+import { createLazyMemo } from '@solid-primitives/memo';
+import { useChannelsContext } from '@core/context/channels';
+import {
+ type IUser,
+ useAugmentUserWithDmActivity,
+ useContacts,
+} from '@core/user';
+import type { ApiChannelWithLatest } from '@service-comms/generated/models';
+import type { ChannelEntity } from '@entity';
+import { useHistoryQuery, type HistoryItem } from '@queries/history/history';
+import { useInstructionsMdIdQuery } from '@queries/storage/instructions-md';
+import { queryReadyGate } from '@queries/gate';
+import type { DateValue } from '@core/util/date';
+import { toDate } from 'date-fns';
+import { createAssertedContextProvider } from '../createContext';
+import type {
+ Bucket,
+ BucketCombination,
+ EntityBucket,
+ QuickAccessItem,
+ QuickAccessContextValue,
+ QuickAccessEntity,
+} from './types';
+import { BUCKET_COMBINATIONS } from './types';
+
+/**
+ * index entry for sorted lists.
+ */
+type IndexEntry = {
+ id: string;
+ bucket: Bucket;
+ sortTimestamp: number;
+};
+
+/**
+ * full item and version hash.
+ */
+type CacheEntry = {
+ item: QuickAccessItem;
+ version: string;
+};
+
+function historyItemToEntity(item: HistoryItem): QuickAccessEntity {
+ const base = {
+ id: item.id,
+ name: item.name,
+ createdAt: item.createdAt,
+ updatedAt: item.updatedAt,
+ viewedAt: item.viewedAt,
+ };
+
+ switch (item.type) {
+ case 'chat':
+ return {
+ ...base,
+ type: 'chat',
+ } as QuickAccessEntity;
+
+ case 'project':
+ return {
+ ...base,
+ type: 'project',
+ } as QuickAccessEntity;
+
+ case 'document': {
+ if (item.subType?.type === 'task') {
+ return {
+ ...base,
+ type: 'document',
+ fileType: 'md',
+ subType: item.subType,
+ } as QuickAccessEntity;
+ }
+ return {
+ ...base,
+ type: 'document',
+ fileType: item.fileType ?? undefined,
+ subType: item.subType,
+ } as QuickAccessEntity;
+ }
+
+ default:
+ return {
+ ...base,
+ type: 'document',
+ } as QuickAccessEntity;
+ }
+}
+
+function channelToEntity(channel: ApiChannelWithLatest): ChannelEntity {
+ return {
+ type: 'channel',
+ id: channel.id,
+ name: channel.name ?? '',
+ ownerId: channel.owner_id ?? '',
+ channelType: channel.channel_type ?? 'public',
+ participantIds: channel.participants?.map((p) => p.user_id),
+ createdAt: channel.created_at,
+ updatedAt: channel.updated_at,
+ viewedAt: channel.viewed_at,
+ interactedAt: channel.interacted_at,
+ };
+}
+
+/**
+ * Determines the bucket for a history item.
+ */
+function getBucketForHistoryItem(item: HistoryItem): EntityBucket {
+ switch (item.type) {
+ case 'chat':
+ return 'chat';
+ case 'project':
+ return 'project';
+ case 'document': {
+ if (item.subType?.type === 'task') return 'task';
+ if (item.fileType === 'md') return 'note';
+ return 'document';
+ }
+ default:
+ return 'document';
+ }
+}
+
+function getUserSearchText(user: IUser): string {
+ const { email, name } = user;
+ if (name === email) return `${email} | ${email}`;
+ return `${name} | ${email}`;
+}
+
+function getEntitySearchText(entity: QuickAccessEntity): string {
+ return entity.name;
+}
+
+function toTimestamp(value: DateValue | null | undefined): number {
+ if (value == null) return 0;
+ return toDate(value).getTime();
+}
+
+/** dumb history item hash */
+function getHistoryItemVersion(item: HistoryItem): string {
+ return `${item.name}|${item.updatedAt}|${item.viewedAt}|${item.deletedAt}`;
+}
+
+/** dumb channel hash */
+function getChannelVersion(channel: ApiChannelWithLatest): string {
+ return `${channel.name}|${channel.updated_at}|${channel.viewed_at}`;
+}
+
+/** dumb use hash */
+function getUserVersion(user: IUser): string {
+ return `${user.name}|${user.email}|${user.lastInteraction}`;
+}
+
+/**
+ * Merge two *already* sorted index arrays into a single sorted array.
+ */
+function mergeSortedIndices(a: IndexEntry[], b: IndexEntry[]): IndexEntry[] {
+ const result: IndexEntry[] = [];
+ let i = 0;
+ let j = 0;
+
+ while (i < a.length && j < b.length) {
+ if (a[i].sortTimestamp >= b[j].sortTimestamp) {
+ result.push(a[i]);
+ i++;
+ } else {
+ result.push(b[j]);
+ j++;
+ }
+ }
+
+ while (i < a.length) {
+ result.push(a[i]);
+ i++;
+ }
+ while (j < b.length) {
+ result.push(b[j]);
+ j++;
+ }
+
+ return result;
+}
+
+/**
+ * Merge multiple *already* sorted index arrays into a single sorted array.
+ */
+function mergeMultipleSortedIndices(arrays: IndexEntry[][]): IndexEntry[] {
+ if (arrays.length === 0) return [];
+ if (arrays.length === 1) return arrays[0];
+ return arrays.reduce((acc, arr) => mergeSortedIndices(acc, arr));
+}
+
+export const [QuickAccessProvider, useQuickAccess] =
+ createAssertedContextProvider(
+ 'QuickAccessContext',
+ (): QuickAccessContextValue => {
+ // queries
+ const historyQuery = useHistoryQuery();
+ const { channels, isLoading: channelsLoading } = useChannelsContext();
+ const contacts = useContacts();
+ const augmentUserWithDmActivity = useAugmentUserWithDmActivity();
+ const instructionsIdQuery = useInstructionsMdIdQuery();
+
+ // globally hidden ids
+ const [hiddenIds, setHiddenIds] = createSignal<Set<string>>(new Set());
+
+ const hideId = (id: string) => {
+ setHiddenIds((prev) => {
+ const next = new Set(prev);
+ next.add(id);
+ return next;
+ });
+ };
+
+ // instructions.md effect
+ createEffect(() => {
+ const instructionsReady = queryReadyGate(instructionsIdQuery);
+ if (!instructionsReady) return;
+ const instructionsId = instructionsIdQuery.data;
+ if (!instructionsId) return;
+ hideId(instructionsId);
+ });
+
+ // stable cache for transformed items
+ const itemCache = new Map<string, CacheEntry>();
+
+ /**
+ * Process all data sources and update the cache incrementally.
+ * Returns the sorted index entries (lightweight id+timestamp arrays).
+ */
+ const processedData = createLazyMemo(() => {
+ const seenIds = new Set<string>();
+ const allEntries: IndexEntry[] = [];
+
+ const transformedItems: Array<{
+ id: string;
+ name: string;
+ type: string;
+ reason: string;
+ }> = [];
+
+ // Process history items
+ const historyData = historyQuery.data ?? [];
+ const hidden = hiddenIds();
+ for (const item of historyData) {
+ if (item.deletedAt) continue;
+ if (hidden.has(item.id)) continue;
+ seenIds.add(item.id);
+
+ const version = getHistoryItemVersion(item);
+ const cached = itemCache.get(item.id);
+
+ // Only transform if not cached or version changed
+ if (!cached || cached.version !== version) {
+ const reason = !cached
+ ? 'new'
+ : `changed (${cached.version} -> ${version})`;
+ transformedItems.push({
+ id: item.id,
+ name: item.name,
+ type: `history:${item.type}`,
+ reason,
+ });
+ const bucket = getBucketForHistoryItem(item);
+ const entity = historyItemToEntity(item);
+ const viewedAtMs = toTimestamp(item.viewedAt);
+ const updatedAtMs = toTimestamp(item.updatedAt);
+ const sortTimestamp = viewedAtMs || updatedAtMs;
+
+ const quickAccessItem: QuickAccessItem = {
+ kind: 'entity',
+ id: item.id,
+ bucket,
+ searchText: getEntitySearchText(entity),
+ sortTimestamp,
+ timestamps: {
+ viewedAt: item.viewedAt,
+ updatedAt: item.updatedAt,
+ createdAt: item.createdAt,
+ },
+ data: entity,
+ };
+
+ itemCache.set(item.id, { item: quickAccessItem, version });
+ allEntries.push({ id: item.id, bucket, sortTimestamp });
+ } else {
+ allEntries.push({
+ id: item.id,
+ bucket: cached.item.bucket,
+ sortTimestamp: cached.item.sortTimestamp,
+ });
+ }
+ }
+
+ // Process channels
+ const channelData = channels();
+ for (const channel of channelData) {
+ seenIds.add(channel.id);
+
+ const version = getChannelVersion(channel);
+ const cached = itemCache.get(channel.id);
+
+ if (!cached || cached.version !== version) {
+ const reason = !cached
+ ? 'new'
+ : `changed (${cached.version} -> ${version})`;
+ transformedItems.push({
+ id: channel.id,
+ name: channel.name ?? '',
+ type: `channel:${channel.channel_type}`,
+ reason,
+ });
+ const isDm = channel.channel_type === 'direct_message';
+ const bucket: Bucket = isDm ? 'dm' : 'channel';
+ const entity = channelToEntity(channel);
+ const sortTimestamp = toTimestamp(channel.updated_at);
+
+ const quickAccessItem: QuickAccessItem = {
+ kind: 'entity',
+ id: channel.id,
+ bucket,
+ searchText: channel.name ?? '',
+ sortTimestamp,
+ timestamps: {
+ viewedAt: channel.viewed_at,
+ updatedAt: channel.updated_at,
+ createdAt: channel.created_at,
+ },
+ data: entity,
+ };
+
+ itemCache.set(channel.id, { item: quickAccessItem, version });
+ allEntries.push({ id: channel.id, bucket, sortTimestamp });
+ } else {
+ allEntries.push({
+ id: channel.id,
+ bucket: cached.item.bucket,
+ sortTimestamp: cached.item.sortTimestamp,
+ });
+ }
+ }
+
+ // Process contacts (users)
+ const contactData = contacts();
+ for (const contact of contactData) {
+ const augmentedUser = augmentUserWithDmActivity(contact);
+ seenIds.add(augmentedUser.id);
+
+ const version = getUserVersion(augmentedUser);
+ const cached = itemCache.get(augmentedUser.id);
+
+ if (!cached || cached.version !== version) {
+ const reason = !cached
+ ? 'new'
+ : `changed (${cached.version} -> ${version})`;
+ transformedItems.push({
+ id: augmentedUser.id,
+ name: augmentedUser.name,
+ type: 'user',
+ reason,
+ });
+ const sortTimestamp = toTimestamp(augmentedUser.lastInteraction);
+
+ const quickAccessItem: QuickAccessItem = {
+ kind: 'user',
+ id: augmentedUser.id,
+ bucket: 'person',
+ searchText: getUserSearchText(augmentedUser),
+ sortTimestamp,
+ timestamps: {
+ lastInteraction: augmentedUser.lastInteraction,
+ },
+ data: augmentedUser,
+ };
+
+ itemCache.set(augmentedUser.id, { item: quickAccessItem, version });
+ allEntries.push({
+ id: augmentedUser.id,
+ bucket: 'person',
+ sortTimestamp,
+ });
+ } else {
+ allEntries.push({
+ id: augmentedUser.id,
+ bucket: cached.item.bucket,
+ sortTimestamp: cached.item.sortTimestamp,
+ });
+ }
+ }
+
+ // Clean up stale cache entries (items that no longer exist)
+ for (const id of itemCache.keys()) {
+ if (!seenIds.has(id)) {
+ itemCache.delete(id);
+ }
+ }
+
+ // Sort all entries by timestamp descending
+ allEntries.sort((a, b) => b.sortTimestamp - a.sortTimestamp);
+
+ // Deduplicate by id - keep the first occurrence (most recent timestamp)
+ const deduplicatedEntries: IndexEntry[] = [];
+ const dedupeSet = new Set<string>();
+ for (const entry of allEntries) {
+ if (!dedupeSet.has(entry.id)) {
+ dedupeSet.add(entry.id);
+ deduplicatedEntries.push(entry);
+ }
+ }
+
+ return deduplicatedEntries;
+ });
+
+ const getById = (id: string): QuickAccessItem | undefined => {
+ return itemCache.get(id)?.item;
+ };
+
+ const resolveEntries = (entries: IndexEntry[]): QuickAccessItem[] => {
+ const result: QuickAccessItem[] = [];
+ for (const entry of entries) {
+ const cached = itemCache.get(entry.id);
+ if (cached) {
+ result.push(cached.item);
+ }
+ }
+ return result;
+ };
+
+ // Pre-compute individual bucket index lists (each already sorted)
+ const bucketIndices = createLazyMemo<Map<Bucket, IndexEntry[]>>(() => {
+ const map = new Map<Bucket, IndexEntry[]>();
+ for (const entry of processedData()) {
+ const list = map.get(entry.bucket);
+ if (list) {
+ list.push(entry);
+ } else {
+ map.set(entry.bucket, [entry]);
+ }
+ }
+ return map;
+ });
+
+ const preBakedIndices = createLazyMemo<
+ Record<BucketCombination, IndexEntry[]>
+ >(() => {
+ const indices = bucketIndices();
+ return {
+ all: processedData(),
+ channels: mergeMultipleSortedIndices([
+ indices.get('dm') ?? [],
+ indices.get('channel') ?? [],
+ ]),
+ documents: mergeMultipleSortedIndices([
+ indices.get('document') ?? [],
+ indices.get('note') ?? [],
+ indices.get('task') ?? [],
+ indices.get('chat') ?? [],
+ indices.get('project') ?? [],
+ ]),
+ };
+ });
+
+ // helper to get a pre-baked index list if the bucket combination matches
+ const getPreBakedIndices = (
+ buckets: Bucket[]
+ ): IndexEntry[] | undefined => {
+ const baked = preBakedIndices();
+ const bucketSet = new Set(buckets);
+
+ for (const [name, combo] of Object.entries(BUCKET_COMBINATIONS)) {
+ if (
+ combo.length === buckets.length &&
+ combo.every((b) => bucketSet.has(b))
+ ) {
+ return baked[name as BucketCombination];
+ }
+ }
+ return undefined;
+ };
+
+ // API: useList
+ // Optimized for common cases:
+ // 1. No buckets = return pre-sorted all items list
+ // 2. Single bucket = return pre-computed bucket list
+ // 3. Pre-baked combination = return pre-merged list
+ // 4. Other combinations = merge-sort bucket lists
+ //
+ // Items are resolved lazily
+ const useList = <B extends Bucket>(...buckets: B[]): Accessor<any> => {
+ return createLazyMemo(() => {
+ let indices: IndexEntry[];
+
+ if (buckets.length === 0) {
+ indices = preBakedIndices().all;
+ } else if (buckets.length === 1) {
+ // Single bucket = return pre-computed bucket list
+ indices = bucketIndices().get(buckets[0]) ?? [];
+ } else {
+ // Check for pre-baked combination
+ const preBaked = getPreBakedIndices(buckets);
+ if (preBaked) {
+ indices = preBaked;
+ } else {
+ // Fallback: merge-sort the requested bucket index lists
+ const allIndices = bucketIndices();
+ const indicesToMerge = buckets
+ .map((b) => allIndices.get(b) ?? [])
+ .filter((arr) => arr.length > 0);
+ indices = mergeMultipleSortedIndices(indicesToMerge);
+ }
+ }
+
+ return resolveEntries(indices);
+ });
+ };
+
+ const isLoading = () => historyQuery.isLoading || channelsLoading();
+
+ const refresh = () => {
+ historyQuery.refetch();
+ };
+
+ return {
+ useList,
+ isLoading,
+ refresh,
+ getById,
+ };
+ }
+ );
diff --git a/js/app/packages/core/context/quickAccess/debug/QuickAccessAll.tsx b/js/app/packages/core/context/quickAccess/debug/QuickAccessAll.tsx
new file mode 100644
index 0000000000..bd107e9108
--- /dev/null
+++ b/js/app/packages/core/context/quickAccess/debug/QuickAccessAll.tsx
@@ -0,0 +1,50 @@
+import { SplitHeaderLeft } from '@app/component/split-layout/components/SplitHeader';
+import { StaticSplitLabel } from '@app/component/split-layout/components/SplitLabel';
+import { useQuickAccess } from '../QuickAccessProvider';
+import { For, Match, Switch } from 'solid-js';
+import { InlineEntity } from '@entity';
+
+export default function QuickAccessAll() {
+ const { useList } = useQuickAccess();
+
+ // @example const entities = useList('task', 'note', 'document', 'project');
+ const entities = useList();
+
+ return (
+ <>
+ <SplitHeaderLeft>
+ <StaticSplitLabel label="Quick Access - List"></StaticSplitLabel>
+ </SplitHeaderLeft>
+ <div class="size-full p-4 overflow-scroll scrollbar-hidden">
+ <For each={entities()}>
+ {(item, ndx) => (
+ <div class="flex items-center gap-2 py-2 truncate text-xs">
+ <span class="font-mono text-ink-extra-muted text-xs opacity-50">
+ {(ndx() + 1).toString().padStart(4, '0')}
+ </span>
+ <Switch>
+ <Match when={item.kind === 'entity' && item}>
+ {(item) => <InlineEntity entity={item().data as any} />}
+ </Match>
+ <Match when={item.kind === 'user' && item}>
+ {(item) => (
+ <span>
+ {item().data.name} ({item().data.email})
+ </span>
+ )}
+ </Match>
+ <Match when={item}>
+ {(item) => (
+ <span>
+ {item().bucket} - ({item().searchText})
+ </span>
+ )}
+ </Match>
+ </Switch>
+ </div>
+ )}
+ </For>
+ </div>
+ </>
+ );
+}
diff --git a/js/app/packages/core/context/quickAccess/index.ts b/js/app/packages/core/context/quickAccess/index.ts
new file mode 100644
index 0000000000..f3f4c72d92
--- /dev/null
+++ b/js/app/packages/core/context/quickAccess/index.ts
@@ -0,0 +1,25 @@
+export { QuickAccessProvider, useQuickAccess } from './QuickAccessProvider';
+export type {
+ Bucket,
+ EntityBucket,
+ QuickAccessItem,
+ EntityItem,
+ UserItem,
+ CommandItem,
+ SearchOptions,
+ SearchResult,
+ SearchWeights,
+ QuickAccessContextValue,
+ BucketEntityMap,
+ BucketItemMap,
+ ItemForBucket,
+ ItemsForBuckets,
+} from './types';
+export {
+ ALL_BUCKETS,
+ isEntityItem,
+ isUserItem,
+ isCommandItem,
+ isEntityOfType,
+ isFromBucket,
+} from './types';
diff --git a/js/app/packages/core/context/quickAccess/types.ts b/js/app/packages/core/context/quickAccess/types.ts
new file mode 100644
index 0000000000..3af9594579
--- /dev/null
+++ b/js/app/packages/core/context/quickAccess/types.ts
@@ -0,0 +1,217 @@
+import type { Accessor } from 'solid-js';
+import type {
+ EntityData,
+ ChannelEntity,
+ ChatEntity,
+ DocumentEntity,
+ TaskEntity,
+ EmailEntity,
+ ProjectEntity,
+} from '@entity';
+import type { HotkeyCommand } from '@core/hotkey/types';
+import type { IUser } from '@core/user/types';
+import type { DateValue } from '@core/util/date';
+
+export type QuickAccessEntity<T extends EntityData = EntityData> = Omit<
+ T,
+ 'ownerId'
+>;
+
+export type Bucket =
+ | 'channel'
+ | 'dm'
+ | 'person'
+ | 'document'
+ | 'task'
+ | 'note'
+ | 'chat'
+ | 'project'
+ | 'email'
+ | 'command';
+
+export type EntityBucket = Exclude<Bucket, 'person' | 'command'>;
+
+export const ALL_BUCKETS: Bucket[] = [
+ 'channel',
+ 'dm',
+ 'person',
+ 'document',
+ 'task',
+ 'note',
+ 'chat',
+ 'project',
+ 'email',
+ 'command',
+];
+
+export type BucketCombination = 'all' | 'channels' | 'documents';
+
+export const BUCKET_COMBINATIONS: Record<BucketCombination, Bucket[]> = {
+ all: ALL_BUCKETS,
+ channels: ['dm', 'channel'],
+ documents: ['document', 'note', 'task', 'chat', 'project'],
+};
+
+export type ItemTimestamps = {
+ viewedAt?: DateValue | null;
+ updatedAt?: DateValue | null;
+ createdAt?: DateValue | null;
+ lastInteraction?: DateValue | null;
+};
+
+type QuickAccessBase = {
+ id: string;
+ searchText: string;
+ sortTimestamp: number;
+ timestamps: ItemTimestamps;
+};
+
+export type EntityItem<T extends QuickAccessEntity = QuickAccessEntity> =
+ QuickAccessBase & {
+ kind: 'entity';
+ bucket: EntityBucket;
+ data: T;
+ };
+
+export type UserItem = QuickAccessBase & {
+ kind: 'user';
+ bucket: 'person';
+ data: IUser;
+};
+
+export type CommandItem = QuickAccessBase & {
+ kind: 'command';
+ bucket: 'command';
+ data: HotkeyCommand;
+};
+
+export type QuickAccessItem = EntityItem | UserItem | CommandItem;
+
+export function isEntityItem(item: QuickAccessItem): item is EntityItem {
+ return item.kind === 'entity';
+}
+
+export function isUserItem(item: QuickAccessItem): item is UserItem {
+ return item.kind === 'user';
+}
+
+export function isCommandItem(item: QuickAccessItem): item is CommandItem {
+ return item.kind === 'command';
+}
+
+export function isEntityOfType<T extends EntityData['type']>(
+ item: QuickAccessItem,
+ entityType: T
+): item is EntityItem<Extract<EntityData, { type: T }>> {
+ return item.kind === 'entity' && item.data.type === entityType;
+}
+
+export function isFromBucket<B extends Bucket>(
+ item: QuickAccessItem,
+ bucket: B
+): boolean {
+ return item.bucket === bucket;
+}
+
+export type BucketEntityMap = {
+ channel: ChannelEntity;
+ dm: ChannelEntity;
+ document: DocumentEntity;
+ task: TaskEntity;
+ note: DocumentEntity;
+ chat: ChatEntity;
+ project: ProjectEntity;
+ email: EmailEntity;
+ person: never; // UserItem, not EntityItem
+ command: never; // CommandItem, not EntityItem
+};
+
+/**
+ * Maps a bucket to its corresponding QuickAccessItem type
+ */
+export type BucketItemMap = {
+ channel: EntityItem<ChannelEntity>;
+ dm: EntityItem<ChannelEntity>;
+ document: EntityItem<DocumentEntity>;
+ task: EntityItem<TaskEntity>;
+ note: EntityItem<DocumentEntity>;
+ chat: EntityItem<ChatEntity>;
+ project: EntityItem<ProjectEntity>;
+ email: EntityItem<EmailEntity>;
+ person: UserItem;
+ command: CommandItem;
+};
+
+export type ItemForBucket<B extends Bucket> = BucketItemMap[B];
+
+export type ItemsForBuckets<Buckets extends Bucket[]> = Buckets extends [
+ infer First extends Bucket,
+ ...infer Rest extends Bucket[],
+]
+ ? ItemForBucket<First> | ItemsForBuckets<Rest>
+ : never;
+
+export type SearchWeights = {
+ fuzzy?: number;
+ time?: number;
+ brevity?: number;
+};
+
+export type SearchOptions = {
+ query: string;
+ limit?: number;
+ weights?: SearchWeights;
+ minScore?: number;
+};
+
+export type SearchResult<T extends QuickAccessItem = QuickAccessItem> = {
+ item: T;
+ score: number;
+ scoreDetails?: {
+ fuzzy: number;
+ time: number;
+ brevity: number;
+ };
+};
+
+export type QuickAccessContextValue = {
+ /**
+ * Get items from specific buckets, cached and reactive.
+ * Returns all items if no buckets specified.
+ *
+ * @example
+ * const channels = quickAccess.useList('channel', 'dm');
+ * const people = quickAccess.useList('person');
+ * const everything = quickAccess.useList();
+ */
+ useList: {
+ (): Accessor<QuickAccessItem[]>;
+ <B extends Bucket>(...buckets: [B]): Accessor<ItemForBucket<B>[]>;
+ <B extends Bucket[]>(...buckets: B): Accessor<ItemsForBuckets<B>[]>;
+ };
+
+ /**
+ * Whether any data sources are still loading.
+ */
+ isLoading: Accessor<boolean>;
+
+ /**
+ * Force refresh of all data sources.
+ */
+ refresh: () => void;
+
+ /**
+ * Get a single item by ID from the cache.
+ * Returns undefined if the item is not found.
+ *
+ * Use this for lazy lookup of full item data when you only have an ID.
+ * This is more efficient than searching through lists.
+ *
+ * @example
+ * const item = quickAccess.getById(someId);
+ * if (item) {
+ * console.log(item.data);
+ * }
+ */
+ getById: (id: string) => QuickAccessItem | undefined;
+};
diff --git a/js/app/packages/entity/src/composed/InlineEntity.tsx b/js/app/packages/entity/src/composed/InlineEntity.tsx
index 883080aa6d..e7d6e579d6 100644
--- a/js/app/packages/entity/src/composed/InlineEntity.tsx
+++ b/js/app/packages/entity/src/composed/InlineEntity.tsx
@@ -4,8 +4,8 @@ import { EntityTitle } from '../extractors/entity-title';
export function InlineEntity(props: { entity: EntityData }) {
return (
- <div class="flex items-center gap-1 min-w-0">
- <span class="w-[1.25em]">
+ <div class="flex items-center gap-1 min-w-0 truncate">
+ <span class="size-[1.25em] shrink-0">
<EntityIcon entity={props.entity} />
</span>
<EntityTitle entity={props.entity} />
diff --git a/js/app/packages/macro-entity/src/components/Provider.tsx b/js/app/packages/macro-entity/src/components/Provider.tsx
index 32a41defa1..8f2b4b48fd 100644
--- a/js/app/packages/macro-entity/src/components/Provider.tsx
+++ b/js/app/packages/macro-entity/src/components/Provider.tsx
@@ -5,7 +5,6 @@ import { Show, type ParentProps } from 'solid-js';
import { fetchApiToken } from '../queries/auth';
import { queryClient } from '@queries/client';
import { queryKeys } from '../queries/key';
-import { RemoveInstructionsMdFromHistorySideEffect } from '@queries/history/history';
export function Provider(props: ParentProps) {
queryClient.setQueryDefaults(queryKeys.all.auth, {
@@ -19,7 +18,6 @@ export function Provider(props: ParentProps) {
return (
<QueryClientProvider client={queryClient}>
- <RemoveInstructionsMdFromHistorySideEffect />
{props.children}
<Show when={LOCAL_ONLY}>
<SolidQueryDevtools initialIsOpen={false} />
diff --git a/js/app/packages/queries/history/history.ts b/js/app/packages/queries/history/history.ts
index 1ba923f0df..60c5db15a8 100644
--- a/js/app/packages/queries/history/history.ts
+++ b/js/app/packages/queries/history/history.ts
@@ -2,7 +2,6 @@ import { isOk, throwOnErr, catchToResult } from '@core/util/maybeResult';
import { type MutationCallbacks, withCallbacks } from '@queries/utils';
import { storageServiceClient } from '@service-storage/client';
import type { CloudStorageItemType } from '@service-storage/generated/schemas/cloudStorageItemType';
-import { useInstructionsMdIdQuery } from '@queries/storage/instructions-md';
import {
useMutation,
useQuery,
@@ -10,7 +9,7 @@ import {
type QueryClient,
type Updater,
} from '@tanstack/solid-query';
-import { createEffect, type Accessor, type Setter } from 'solid-js';
+import type { Accessor, Setter } from 'solid-js';
import { queryClient } from '../client';
import { historyKeys } from './keys';
import {
@@ -18,7 +17,6 @@ import {
transformHistoryResponse,
updateViewedAtAndMoveItemToFront,
} from './transforms';
-import { queryReadyGate } from '@queries/gate';
import type { HistoryItem } from './types';
// re-export history item type from this file
@@ -81,26 +79,6 @@ export function useHistoryQuery() {
return baseQuery;
}
-// TODO: this is a temporary side effect to remove the instructions item from history
-// load this at the app root level to prevent duplicate work
-// this will be removed from the backend
-export function RemoveInstructionsMdFromHistorySideEffect() {
- const instructionsIdQuery = useInstructionsMdIdQuery();
- const historyQuery = useHistoryQuery();
- createEffect(() => {
- const instructionsReady = queryReadyGate(instructionsIdQuery);
- if (!instructionsReady) return;
- const instructionsId = instructionsIdQuery.data;
- const history = historyQuery.data;
- if (!instructionsId || !history || !history.length) return;
- if (!history.some((item) => item.id === instructionsId)) return;
- return setHistoryData((prev) => {
- return prev.filter((item) => item.id !== instructionsId);
- });
- });
- return null;
-}
-
export async function prefetchHistory() {
void (await catchToResult(
async () => await queryClient.prefetchQuery(historyQueryOptions)