Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
chore: mostly deprecate macro entity package (#1485)
gbirman0c77a86aad59
diff --git a/js/app/packages/app/component/EntityModal/EntityModal.tsx b/js/app/packages/app/component/EntityModal/EntityModal.tsxindex c0738da092..fa4ae363ef 100644--- a/js/app/packages/app/component/EntityModal/EntityModal.tsx+++ b/js/app/packages/app/component/EntityModal/EntityModal.tsx@@ -13,7 +13,7 @@ import {Show,} from 'solid-js';import { Portal } from 'solid-js/web';-import type { EntityData } from '../../../macro-entity/src/types/entity';+import type { EntityData } from '@entity';import { MoveToProjectView } from './MoveToProjectView';import { RenameView } from './RenameView';diff --git a/js/app/packages/app/component/EntityModal/MoveToProjectView.tsx b/js/app/packages/app/component/EntityModal/MoveToProjectView.tsxindex a6b6254dbd..c7209f0f45 100644--- a/js/app/packages/app/component/EntityModal/MoveToProjectView.tsx+++ b/js/app/packages/app/component/EntityModal/MoveToProjectView.tsx@@ -22,8 +22,8 @@ import {import { createStore, reconcile } from 'solid-js/store';import { Dynamic } from 'solid-js/web';import { VList } from 'virtua/solid';-import { createMoveToProjectDssEntityMutation } from '../../../macro-entity/src/queries/dss';-import type { EntityData } from '../../../macro-entity/src/types/entity';+import { createMoveToProjectDssEntityMutation } from '@macro-entity';+import type { EntityData } from '@entity';import { EntityModalActionFooter, EntityModalTitle } from './EntityModal';export const MoveToProjectView = (props: {diff --git a/js/app/packages/app/component/EntityModal/RenameView.tsx b/js/app/packages/app/component/EntityModal/RenameView.tsxindex b65f1ad1f2..0a422664bf 100644--- a/js/app/packages/app/component/EntityModal/RenameView.tsx+++ b/js/app/packages/app/component/EntityModal/RenameView.tsx@@ -1,6 +1,6 @@import { createSignal, onMount } from 'solid-js';-import { createRenameDssEntityMutation } from '../../../macro-entity/src/queries/rename';-import type { EntityData } from '../../../macro-entity/src/types/entity';+import { createRenameDssEntityMutation } from '@macro-entity';+import type { EntityData } from '@entity';import { EntityModalActionFooter, EntityModalTitle } from './EntityModal';export const RenameView = (props: {diff --git a/js/app/packages/app/component/EntitySelectionToolbarModal.tsx b/js/app/packages/app/component/EntitySelectionToolbarModal.tsxindex ab6cfd0567..bcdbc30c7b 100644--- a/js/app/packages/app/component/EntitySelectionToolbarModal.tsx+++ b/js/app/packages/app/component/EntitySelectionToolbarModal.tsx@@ -1,6 +1,6 @@import { Hotkey } from '@core/component/Hotkey';import { ScopedPortal } from '@core/component/ScopedPortal';-import type { EntityData } from '@macro-entity';+import type { EntityData } from '@entity';import CloseIcon from '@phosphor-icons/core/regular/x.svg?component-solid';interface EntitySelectionToolbarModalProps {diff --git a/js/app/packages/app/component/ItemDragAndDrop.tsx b/js/app/packages/app/component/ItemDragAndDrop.tsxindex 8217531360..a011d3f445 100644--- a/js/app/packages/app/component/ItemDragAndDrop.tsx+++ b/js/app/packages/app/component/ItemDragAndDrop.tsx@@ -7,7 +7,7 @@ import {useDragDropContext,} from '@thisbeyond/solid-dnd';import { EntityIcon, getEntityIconType } from 'core/component/EntityIcon';-import type { EntityDragData } from '@macro-entity';+import type { EntityDragData } from '@entity';import {createContext,createMemo,diff --git a/js/app/packages/app/component/PreviewPanel.tsx b/js/app/packages/app/component/PreviewPanel.tsxindex fc9f137104..f287626a95 100644--- a/js/app/packages/app/component/PreviewPanel.tsx+++ b/js/app/packages/app/component/PreviewPanel.tsx@@ -2,7 +2,7 @@ import type { BlockAliasContext } from '@core/block';import { fileTypeToResolvedBlockName } from '@core/constant/allBlocks';import type { BlockOrchestrator } from '@core/orchestrator';import type { NonNullableFields } from '@core/util/withRequired';-import { type EntityData, isTaskEntity } from '@macro-entity';+import { type EntityData, isTaskEntity } from '@entity';import {type Component,createRenderEffect,diff --git a/js/app/packages/app/component/PropertyFilter/FilterValueEntity.tsx b/js/app/packages/app/component/PropertyFilter/FilterValueEntity.tsxindex ba9129cc77..e1b33b7056 100644--- a/js/app/packages/app/component/PropertyFilter/FilterValueEntity.tsx+++ b/js/app/packages/app/component/PropertyFilter/FilterValueEntity.tsx@@ -14,11 +14,9 @@ import { usePropertyEntityDisplay } from '@core/component/Properties/hooks/usePrimport { useAugmentUserWithDmActivity, useContacts } from '@core/user';import { useEmail } from '@core/context/user';import { createFreshSearch } from '@core/util/freshSort';-import {- createEmailsInfiniteQuery,- createUnifiedSearchInfiniteQuery,- type EmailEntity,-} from '@macro-entity';+import { createEmailsInfiniteQuery } from '@macro-entity';+import type { EmailEntity } from '@entity';+import { useSearchSoupQuery } from '@queries/soup/search';import XIcon from '@phosphor-icons/core/assets/regular/x.svg';import type { EntityType } from '@service-properties/generated/schemas/entityType';import { useHistoryQuery } from '@queries/history/history';@@ -103,19 +101,19 @@ export const FilterValueEntity: Component<FilterValueEntityProps> = (props) => {const emails = () => emailsQuery.data ?? [];// Server-side email search- const emailSearchQuery = createUnifiedSearchInfiniteQuery(+ const emailSearchQuery = useSearchSoupQuery(() => ({- params: { page: 0, page_size: 20 },- request: {+ params: { page_size: 20 },+ body: {query: searchTerm(),match_type: 'partial' as const,include: ['emails' as const],search_on: 'name' as const,},}),- {- disabled: () => !needsEmailSearch(),- }+ () => ({+ enabled: needsEmailSearch(),+ }));// Server search results mapped to our formatdiff --git a/js/app/packages/app/component/bulk-edit-entity/BulkDeleteView.tsx b/js/app/packages/app/component/bulk-edit-entity/BulkDeleteView.tsxindex 022f0825b2..f14f193a46 100644--- a/js/app/packages/app/component/bulk-edit-entity/BulkDeleteView.tsx+++ b/js/app/packages/app/component/bulk-edit-entity/BulkDeleteView.tsx@@ -1,5 +1,5 @@-import type { EntityData } from '@macro-entity';-import { createBulkDeleteDssItemsMutation } from '../../../macro-entity/src/queries/dss';+import type { EntityData } from '@entity';+import { createBulkDeleteDssItemsMutation } from '@macro-entity';import { konsoleContextInformation } from '../command/KonsoleItem';import {BulkEditEntityModalActionFooter,diff --git a/js/app/packages/app/component/bulk-edit-entity/BulkEditEntityModal.tsx b/js/app/packages/app/component/bulk-edit-entity/BulkEditEntityModal.tsxindex 0b2ccce84b..2d39578d6d 100644--- a/js/app/packages/app/component/bulk-edit-entity/BulkEditEntityModal.tsx+++ b/js/app/packages/app/component/bulk-edit-entity/BulkEditEntityModal.tsx@@ -1,6 +1,6 @@import { createControlledOpenSignal } from '@core/util/createControlledOpenSignal';import { Dialog } from '@kobalte/core/dialog';-import type { EntityData } from '@macro-entity';+import type { EntityData } from '@entity';import {type Accessor,createSignal,diff --git a/js/app/packages/app/component/bulk-edit-entity/BulkMoveToProjectView.tsx b/js/app/packages/app/component/bulk-edit-entity/BulkMoveToProjectView.tsxindex f3e064afbc..70e44c10b9 100644--- a/js/app/packages/app/component/bulk-edit-entity/BulkMoveToProjectView.tsx+++ b/js/app/packages/app/component/bulk-edit-entity/BulkMoveToProjectView.tsx@@ -4,8 +4,8 @@ import { useProjectsQuery } from '@queries/storage/projects';import type { Project } from '@service-storage/generated/schemas';import { registerHotkey, useHotkeyDOMScope } from 'core/hotkey/hotkeys';import { createMemo, createSignal, For, onMount, Show } from 'solid-js';-import { createBulkMoveToProjectDssEntityMutation } from '../../../macro-entity/src/queries/dss';-import type { EntityData } from '../../../macro-entity/src/types/entity';+import { createBulkMoveToProjectDssEntityMutation } from '@macro-entity';+import type { EntityData } from '@entity';import {BulkEditEntityModalActionFooter,BulkEditEntityModalTitle,diff --git a/js/app/packages/app/component/bulk-edit-entity/BulkRenameEntitiesView.tsx b/js/app/packages/app/component/bulk-edit-entity/BulkRenameEntitiesView.tsxindex 94005acbb4..ee2c0ce6ff 100644--- a/js/app/packages/app/component/bulk-edit-entity/BulkRenameEntitiesView.tsx+++ b/js/app/packages/app/component/bulk-edit-entity/BulkRenameEntitiesView.tsx@@ -1,7 +1,7 @@import { SegmentedControl } from '@core/component/FormControls/SegmentControls';import { createMemo, createSignal, onMount, Show } from 'solid-js';-import { createBulkRenameDssEntityMutation } from '../../../macro-entity/src/queries/rename';-import type { EntityData } from '../../../macro-entity/src/types/entity';+import { createBulkRenameDssEntityMutation } from '@macro-entity';+import type { EntityData } from '@entity';import {BulkEditEntityModalActionFooter,BulkEditEntityModalTitle,diff --git a/js/app/packages/app/component/next-soup/actions/make-copy-action.ts b/js/app/packages/app/component/next-soup/actions/make-copy-action.tsindex 08b9025719..88a6b1f9a9 100644--- a/js/app/packages/app/component/next-soup/actions/make-copy-action.ts+++ b/js/app/packages/app/component/next-soup/actions/make-copy-action.ts@@ -1,7 +1,7 @@import { toast } from '@core/component/Toast/Toast';import type { EntityData } from '@entity';import type { SoupState } from '../create-soup-state';-import { createBulkCopyDssEntityMutation } from '../../../../macro-entity/src/queries/dss';+import { createBulkCopyDssEntityMutation } from '@macro-entity';export const makeCopyAction = () => {const bulkCopyMutation = createBulkCopyDssEntityMutation();diff --git a/js/app/packages/app/component/next-soup/soup-view/soup-view.tsx b/js/app/packages/app/component/next-soup/soup-view/soup-view.tsxindex 73cb4a558c..ef20aeb710 100644--- a/js/app/packages/app/component/next-soup/soup-view/soup-view.tsx+++ b/js/app/packages/app/component/next-soup/soup-view/soup-view.tsx@@ -40,7 +40,8 @@ import {type SearchLocation,type ProjectEntity,} from '@entity';-import { queryKeys, useQueryClient } from '@macro-entity';+import { queryKeys } from '@macro-entity';+import { useQueryClient } from '@queries/client';import { createEffectOnEntityTypeNotification } from '@notifications';import { debounce } from '@solid-primitives/scheduled';import { cn } from '@ui/utils/classname';diff --git a/js/app/packages/app/component/property-edit-modal/PropertyEditorModal.tsx b/js/app/packages/app/component/property-edit-modal/PropertyEditorModal.tsxindex 2e0d55acf1..84b2bdb6a9 100644--- a/js/app/packages/app/component/property-edit-modal/PropertyEditorModal.tsx+++ b/js/app/packages/app/component/property-edit-modal/PropertyEditorModal.tsx@@ -30,8 +30,6 @@ import { beveledCorners } from '../../../block-theme/signals/themeSignals';import { useAllProperties } from './hooks/useAllProperties';import { usePropertySelection } from '@core/component/Properties/hooks';import { cn } from '@ui/utils/classname';-import type { EntityData } from '@macro-entity';-import { InlineEntity } from '../../../macro-entity/src/components/InlineEntity';import { useIsKeyPressActive } from '@core/util/useIsKeyPressActive';import type {Property,@@ -65,6 +63,7 @@ import type { PropertyApiValues } from '@core/component/Properties/types';import { toast } from '@core/component/Toast/Toast';import { useSavePropertyForMultiEntitites } from './hooks/useSaveProperties';import { useEntityPropertiesQuery } from '@queries/properties/entity';+import { InlineEntity, type EntityData } from '@entity';/* Styled wrapper for list items in each menu. */function ListItem(props: {diff --git a/js/app/packages/app/component/property-edit-modal/hooks/useEntitiesForProperty.ts b/js/app/packages/app/component/property-edit-modal/hooks/useEntitiesForProperty.tsindex 7c1186524c..6f25080c18 100644--- a/js/app/packages/app/component/property-edit-modal/hooks/useEntitiesForProperty.ts+++ b/js/app/packages/app/component/property-edit-modal/hooks/useEntitiesForProperty.ts@@ -11,11 +11,9 @@ import {import { useAugmentUserWithDmActivity, useContacts } from '@core/user';import { createFreshSearch } from '@core/util/freshSort';import { useEmail } from '@core/context/user';-import {- createEmailsInfiniteQuery,- createUnifiedSearchInfiniteQuery,- type EmailEntity,-} from '@macro-entity';+import { createEmailsInfiniteQuery } from '@macro-entity';+import type { EmailEntity } from '@entity';+import { useSearchSoupQuery } from '@queries/soup/search';import type { EntityType } from '@service-properties/generated/schemas/entityType';import { useHistoryQuery } from '@queries/history/history';import { debounce } from '@solid-primitives/scheduled';@@ -62,19 +60,19 @@ export function useEntitiesForProperty(const emails = () => emailsQuery.data ?? [];// Server-side email search- const emailSearchQuery = createUnifiedSearchInfiniteQuery(+ const emailSearchQuery = useSearchSoupQuery(() => ({- params: { page: 0, page_size: 20 },- request: {+ params: { page_size: 20 },+ body: {query: searchTerm(),match_type: 'partial' as const,include: ['emails' as const],search_on: 'name' as const,},}),- {- disabled: () => !needsEmailSearch() || !searchTerm(),- }+ () => ({+ enabled: needsEmailSearch() && !!searchTerm(),+ }));// Server search results mapped to our formatdiff --git a/js/app/packages/app/component/property-edit-modal/hooks/usePropertyEditorHotkeys.ts b/js/app/packages/app/component/property-edit-modal/hooks/usePropertyEditorHotkeys.tsindex 6b920749f7..ab5e6cc050 100644--- a/js/app/packages/app/component/property-edit-modal/hooks/usePropertyEditorHotkeys.ts+++ b/js/app/packages/app/component/property-edit-modal/hooks/usePropertyEditorHotkeys.ts@@ -4,7 +4,7 @@ import type {Property,PropertyDefinitionDomain,} from '@core/component/Properties/types';-import { isTaskEntity, type EntityData } from '@macro-entity';+import { isTaskEntity, type EntityData } from '@entity';import { TOKENS } from '@core/hotkey/tokens';import { HotkeyTags } from '@core/hotkey/constants';import { useAllProperties } from './useAllProperties';diff --git a/js/app/packages/app/component/property-edit-modal/hooks/useSaveProperties.ts b/js/app/packages/app/component/property-edit-modal/hooks/useSaveProperties.tsindex 1391b26de4..207bd6d54d 100644--- a/js/app/packages/app/component/property-edit-modal/hooks/useSaveProperties.ts+++ b/js/app/packages/app/component/property-edit-modal/hooks/useSaveProperties.ts@@ -7,7 +7,7 @@ import {isInstantiatedProperty,macroEntityToPropertyEntityType,} from '@core/component/Properties/utils';-import type { EntityData } from '@macro-entity';+import type { EntityData } from '@entity';import { useBulkSaveEntityPropertiesMutation } from '@queries/properties/entity';export function useSavePropertyForMultiEntitites() {diff --git a/js/app/packages/app/component/property-edit-modal/state/propertyEditor.ts b/js/app/packages/app/component/property-edit-modal/state/propertyEditor.tsindex e265083ee3..b90a43c337 100644--- a/js/app/packages/app/component/property-edit-modal/state/propertyEditor.ts+++ b/js/app/packages/app/component/property-edit-modal/state/propertyEditor.ts@@ -1,4 +1,4 @@-import type { EntityData } from '@macro-entity';+import type { EntityData } from '@entity';import type {Property,PropertyDefinitionDomain,diff --git a/js/app/packages/app/component/rightbar/Rightbar.tsx b/js/app/packages/app/component/rightbar/Rightbar.tsxindex 1e30472449..b63bfae9a5 100644--- a/js/app/packages/app/component/rightbar/Rightbar.tsx+++ b/js/app/packages/app/component/rightbar/Rightbar.tsx@@ -82,7 +82,7 @@ import { SplitlikeContainer } from '../split-layout/components/SplitContainer';import { Button } from '@ui/components/Button';import { Hotkey } from '@core/component/Hotkey';import { AccessLevel } from '@service-cognition/generated/schemas/accessLevel';-import { useWaitChatRename } from '../../../macro-entity/src/queries/rename';+import { useWaitChatRename } from '@macro-entity';type ChatData = {messages: ChatMessageWithAttachments[];diff --git a/js/app/packages/app/component/split-layout/components/SplitModalContext.tsx b/js/app/packages/app/component/split-layout/components/SplitModalContext.tsxindex d2882157f1..0e77011e0c 100644--- a/js/app/packages/app/component/split-layout/components/SplitModalContext.tsx+++ b/js/app/packages/app/component/split-layout/components/SplitModalContext.tsx@@ -1,5 +1,5 @@import { EntityModal } from '@app/component/EntityModal/EntityModal';-import type { EntityData } from '@macro-entity';+import type { EntityData } from '@entity';import type { ItemType } from '@service-storage/client';import {createContext,diff --git a/js/app/packages/block-canvas/component/CanvasController.tsx b/js/app/packages/block-canvas/component/CanvasController.tsxindex bea8def10c..930acd350d 100644--- a/js/app/packages/block-canvas/component/CanvasController.tsx+++ b/js/app/packages/block-canvas/component/CanvasController.tsx@@ -7,7 +7,7 @@ import { useRenderMermaid } from '@block-canvas/util/mermaid';import { withAnalytics } from '@coparse/analytics';import { type BlockName, useBlockId, useIsNestedBlock } from '@core/block';import { FileDropOverlay } from '@core/component/FileDropOverlay';-import type { EntityDragEvent } from '@macro-entity';+import type { EntityDragEvent } from '@entity';import { BasicHotkey } from '@core/component/Hotkey';import { OldMenu, OldMenuItem } from '@core/component/OldMenu';import {diff --git a/js/app/packages/block-channel/component/Channel.tsx b/js/app/packages/block-channel/component/Channel.tsxindex 5e4a7f7ef1..e59fb7323f 100644--- a/js/app/packages/block-channel/component/Channel.tsx+++ b/js/app/packages/block-channel/component/Channel.tsx@@ -4,7 +4,7 @@ import { URL_PARAMS } from '@block-channel/constants';import { handleFileUpload } from '@block-channel/utils/inputAttachments';import { withAnalytics } from '@coparse/analytics';import { TrackingEvents } from '@coparse/analytics/src/types/TrackingEvents';-import type { EntityDragEvent } from '@macro-entity';+import type { EntityDragEvent } from '@entity';import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';import { fileTypeToBlockName } from '@core/constant/allBlocks';import { useChannelActivity } from '@core/context/channels';diff --git a/js/app/packages/block-chat/component/TopBar.tsx b/js/app/packages/block-chat/component/TopBar.tsxindex a639390009..3964aea75d 100644--- a/js/app/packages/block-chat/component/TopBar.tsx+++ b/js/app/packages/block-chat/component/TopBar.tsx@@ -21,7 +21,7 @@ import { useBlockDocumentName } from '@core/util/currentBlockDocumentName';import Notepad from '@icon/regular/notepad.svg';import { useOpenInstructionsMd } from 'core/component/AI/util/instructions';import { onCleanup, onMount } from 'solid-js';-import { useWaitChatRename } from '../../macro-entity/src/queries/rename';+import { useWaitChatRename } from '@macro-entity';export function TopBar() {const blockId = useBlockId();diff --git a/js/app/packages/block-md/component/MarkdownEditor.tsx b/js/app/packages/block-md/component/MarkdownEditor.tsxindex 2f3bb434f9..fcf7a49da6 100644--- a/js/app/packages/block-md/component/MarkdownEditor.tsx+++ b/js/app/packages/block-md/component/MarkdownEditor.tsx@@ -11,7 +11,7 @@ import {} from '@core/block';import { IS_MAC } from '@core/constant/isMac';import { ENABLE_MARKDOWN_AI_GENERATE } from '@core/constant/featureFlags';-import type { EntityDragEvent } from '@macro-entity';+import type { EntityDragEvent } from '@entity';import { DecoratorRenderer } from '@core/component/LexicalMarkdown/component/core/DecoratorRenderer';import { FocusClickTarget } from '@core/component/LexicalMarkdown/component/core/FocusClickTarget';import {diff --git a/js/app/packages/block-md/signal/save.ts b/js/app/packages/block-md/signal/save.tsindex f3ab17a180..02ff9c7f69 100644--- a/js/app/packages/block-md/signal/save.ts+++ b/js/app/packages/block-md/signal/save.ts@@ -12,7 +12,7 @@ import { refetchHistory } from '@queries/history/history';import { createCallback } from '@solid-primitives/rootless';import { createMemo } from 'solid-js';import { mdStore } from './markdownBlockData';-import { createRenameDssEntityMutation } from '../../macro-entity/src/queries/rename';+import { createRenameDssEntityMutation } from '@macro-entity';export const useBlockSave = () => {const pendingComment = createMemo(() => activeCommentThreadSignal() === -1);diff --git a/js/app/packages/core/component/AI/hook/useEntityDropAttachment.ts b/js/app/packages/core/component/AI/hook/useEntityDropAttachment.tsindex 69ebe4c28c..fd9c7a6789 100644--- a/js/app/packages/core/component/AI/hook/useEntityDropAttachment.ts+++ b/js/app/packages/core/component/AI/hook/useEntityDropAttachment.ts@@ -4,7 +4,7 @@ import type { Attachment, Attachments } from '@core/component/AI/types';import { asFileType } from '@core/component/AI/util';import { toast } from '@core/component/Toast/Toast';import { fileTypeToBlockName } from '@core/constant/allBlocks';-import type { EntityDragData, EntityDragEvent } from '@macro-entity';+import type { EntityDragData, EntityDragEvent } from '@entity';import { createDroppable, useDragDropContext } from '@thisbeyond/solid-dnd';import type { AttachmentType } from '@service-cognition/generated/schemas';import { type Accessor, createMemo } from 'solid-js';diff --git a/js/app/packages/core/component/AI/signal/tabAttachments.ts b/js/app/packages/core/component/AI/signal/tabAttachments.tsindex 64b15d6832..d328edd098 100644--- a/js/app/packages/core/component/AI/signal/tabAttachments.ts+++ b/js/app/packages/core/component/AI/signal/tabAttachments.ts@@ -3,7 +3,7 @@ import type { Attachment } from '@core/component/AI/types';import { useChannelsContext } from '@core/context/channels';import type { ChannelWithParticipants } from '@core/user';import { isOk } from '@core/util/maybeResult';-import { type EmailEntity, useEmails } from '@macro-entity';+import type { EmailEntity } from '@entity';import type {AttachmentType,ChannelType,@@ -99,7 +99,8 @@ export function useTabAttachments(): Accessor<ChatAttachmentWithName[]> {const historyQuery = useHistoryQuery();const channelsContext = useChannelsContext();const channels = channelsContext.channels;- const emails = useEmails();+ // TODO: hook into email query because useEmails was deprecated+ const emails: Accessor<EmailEntity[]> = () => [];// Get valid active tabs using createMemoconst tabs = createMemo(() => {diff --git a/js/app/packages/core/component/EntityIcon.tsx b/js/app/packages/core/component/EntityIcon.tsxindex d8c977b453..9b6ca6a80b 100644--- a/js/app/packages/core/component/EntityIcon.tsx+++ b/js/app/packages/core/component/EntityIcon.tsx@@ -53,7 +53,7 @@ import type {ChannelEntity,DocumentEntity,EmailEntity,-} from '@macro-entity';+} from '@entity';import type { PreviewItem } from '@queries/preview';import type { Component, JSX } from 'solid-js';import { Dynamic } from 'solid-js/web';diff --git a/js/app/packages/core/component/ItemPreview.tsx b/js/app/packages/core/component/ItemPreview.tsxindex 938b9da746..62c312254b 100644--- a/js/app/packages/core/component/ItemPreview.tsx+++ b/js/app/packages/core/component/ItemPreview.tsx@@ -13,7 +13,7 @@ import { useSplitNavigationHandler } from '@core/util/useSplitNavigationHandler'import EyeSlash from '@icon/duotone/eye-slash-duotone.svg';import TrashSimple from '@icon/duotone/trash-simple-duotone.svg';import LoadingSpinner from '@icon/regular/spinner.svg';-import type { NamedSubType } from '@macro-entity';+import type { NamedSubType } from '@entity';import type { ItemType } from '@service-storage/client';import type { FileType } from '@service-storage/generated/schemas/fileType';import {diff --git a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu.tsx b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu.tsxindex a94f79bffe..df50826b74 100644--- a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu.tsx+++ b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu.tsx@@ -28,14 +28,11 @@ 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 type { EntityData, WithSearch } from '@macro-entity';-import {- createUnifiedSearchInfiniteQuery,- type EmailEntity,- useEmails,-} from '@macro-entity';import { useHistoryQuery } from '@queries/history/history';-import type { SearchArgs } from '@service-search/client';+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';@@ -80,6 +77,7 @@ import {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;@@ -473,7 +471,8 @@ function MentionsMenuInner(props: {props.emails?.().map(entityMapper('email')).filter(allItemFilter) ?? []);} else {- const emailsFromSource = useEmails();+ // TODO: hook into email query because useEmails was deprecated+ const emailsFromSource: Accessor<EmailEntity[]> = () => [];emails = createMemo(() =>emailsFromSource().map(entityMapper('email')).filter(allItemFilter) ??@@ -509,13 +508,13 @@ function MentionsMenuInner(props: {});}- const args = createMemo((): SearchArgs => {+ const args = createMemo((): SearchSoupQueryArgs => {return {params: {cursor: null,page_size: 10,},- request: {+ body: {match_type: 'partial',search_on: 'name',include: ['emails'],@@ -524,8 +523,7 @@ function MentionsMenuInner(props: {};});- const emailUnifiedSearchInfiniteQuery =- createUnifiedSearchInfiniteQuery(args);+ const emailUnifiedSearchInfiniteQuery = useSearchSoupQuery(args);const foundEmails = createMemo((): Entity<'email'>[] => {if (emailUnifiedSearchInfiniteQuery.status === 'success') {diff --git a/js/app/packages/core/component/LexicalMarkdown/utils/mentionsUtils.ts b/js/app/packages/core/component/LexicalMarkdown/utils/mentionsUtils.tsindex aa7d5d4a54..1fd1cb6c8b 100644--- a/js/app/packages/core/component/LexicalMarkdown/utils/mentionsUtils.ts+++ b/js/app/packages/core/component/LexicalMarkdown/utils/mentionsUtils.ts@@ -3,11 +3,11 @@ import { fileTypeToBlockName } from '@core/constant/allBlocks';import { trackMention } from '@core/signal/mention';import type { ChannelWithParticipants, IUser } from '@core/user';import type { ParsedDate } from '@core/util/dateParser';-import type { EmailEntity } from '@macro-entity';+import type { EmailEntity } from '@entity';import { waitBulkUploadStatus } from '@service-connection/bulkUpload';import type { DocumentMentionMetadata } from '@service-notification/client';import type { BasicDocument } from '@service-storage/generated/schemas/basicDocument';-import type { Item } from '@service-storage/generated/schemas/item';+import type { HistoryItem as Item } from '@queries/history/history';import type { Project } from '@service-storage/generated/schemas/project';import type { UploadSuccess } from '@service-storage/util/upload';import type { LexicalEditor } from 'lexical';diff --git a/js/app/packages/core/component/LexicalMarkdown/utils/snapshotMention.ts b/js/app/packages/core/component/LexicalMarkdown/utils/snapshotMention.tsindex 38dc096eaf..fa9ee4d015 100644--- a/js/app/packages/core/component/LexicalMarkdown/utils/snapshotMention.ts+++ b/js/app/packages/core/component/LexicalMarkdown/utils/snapshotMention.ts@@ -7,7 +7,7 @@ import { fetchDocumentAsMarkdown } from '@queries/sync/markdownText';import { propertiesServiceClient } from '@service-properties/client';import { EntityType } from '@service-properties/generated/schemas/entityType';import { storageServiceClient } from '@service-storage/client';-import type { Item } from '@service-storage/generated/schemas/item';+import type { HistoryItem as Item } from '@queries/history/history';import { INSERT_SNAPSHOT_NODE_COMMAND } from '../plugins/mentions';import {entityMapper,diff --git a/js/app/packages/core/component/Properties/component/modal/shared/PropertyEntitySelector.tsx b/js/app/packages/core/component/Properties/component/modal/shared/PropertyEntitySelector.tsxindex 16d5dd57b2..e6dd0ff620 100644--- a/js/app/packages/core/component/Properties/component/modal/shared/PropertyEntitySelector.tsx+++ b/js/app/packages/core/component/Properties/component/modal/shared/PropertyEntitySelector.tsx@@ -13,11 +13,9 @@ import {} from '@core/user';import { createFreshSearch } from '@core/util/freshSort';import SearchIcon from '@icon/regular/magnifying-glass.svg';-import {- createEmailsInfiniteQuery,- createUnifiedSearchInfiniteQuery,- type EmailEntity,-} from '@macro-entity';+import { createEmailsInfiniteQuery } from '@macro-entity';+import type { EmailEntity } from '@entity';+import { useSearchSoupQuery } from '@queries/soup/search';import { useEmail, useUserId } from '@core/context/user';import type { EntityType } from '@service-properties/generated/schemas/entityType';import { useHistoryQuery } from '@queries/history/history';@@ -186,19 +184,19 @@ export function PropertyEntitySelector(props: EntityInputProps) {const emails = () => emailsQuery.data ?? [];// Server-side email search (query internally disables when < 3 chars)- const emailSearchQuery = createUnifiedSearchInfiniteQuery(+ const emailSearchQuery = useSearchSoupQuery(() => ({- params: { page: 0, page_size: 20 },- request: {+ params: { page_size: 20 },+ body: {query: searchTerm(),match_type: 'partial' as const,include: ['emails' as const],search_on: 'name' as const,},}),- {- disabled: () => !needsEmailSearch(),- }+ () => ({+ enabled: needsEmailSearch(),+ }));// Server search results mapped to our formatdiff --git a/js/app/packages/core/component/Properties/component/modal/shared/entityUtils.ts b/js/app/packages/core/component/Properties/component/modal/shared/entityUtils.tsindex f804d0c1bd..30716981f8 100644--- a/js/app/packages/core/component/Properties/component/modal/shared/entityUtils.ts+++ b/js/app/packages/core/component/Properties/component/modal/shared/entityUtils.ts@@ -1,5 +1,5 @@import type { ChannelWithParticipants, IUser } from '@core/user';-import type { EmailEntity } from '@macro-entity';+import type { EmailEntity } from '@entity';import type { EntityType } from '@service-properties/generated/schemas/entityType';import type { Accessor } from 'solid-js';import type { FreshSortConfig, TimestampedItem } from '@core/util/freshSort';diff --git a/js/app/packages/core/component/Properties/hooks/useTaskProperties.ts b/js/app/packages/core/component/Properties/hooks/useTaskProperties.tsindex 0a4551d52a..b6f8007748 100644--- a/js/app/packages/core/component/Properties/hooks/useTaskProperties.ts+++ b/js/app/packages/core/component/Properties/hooks/useTaskProperties.ts@@ -1,4 +1,4 @@-import type { SubType } from '@macro-entity';+import type { SubType } from '@entity';import { useBulkEntityPropertiesQuery } from '@queries/properties/bulk';import { createMemo } from 'solid-js';import { SYSTEM_PROPERTY_IDS } from '../constants';diff --git a/js/app/packages/core/component/Properties/utils/entityConversion.ts b/js/app/packages/core/component/Properties/utils/entityConversion.tsindex 5217214eec..5cd7d9d4f8 100644--- a/js/app/packages/core/component/Properties/utils/entityConversion.ts+++ b/js/app/packages/core/component/Properties/utils/entityConversion.ts@@ -1,4 +1,4 @@-import { type EntityData, isTaskEntity } from '@macro-entity';+import { type EntityData, isTaskEntity } from '@entity';import type { EntityReference } from '@service-properties/generated/schemas/entityReference';import { EntityType } from '@service-properties/generated/schemas/entityType';import type { ItemType } from '@service-storage/client';diff --git a/js/app/packages/core/component/Properties/utils/suggestedProperties.ts b/js/app/packages/core/component/Properties/utils/suggestedProperties.tsindex 5050142f88..c5876456f8 100644--- a/js/app/packages/core/component/Properties/utils/suggestedProperties.ts+++ b/js/app/packages/core/component/Properties/utils/suggestedProperties.ts@@ -1,4 +1,4 @@-import type { ExpandedEntityType } from '@macro-entity';+import type { ExpandedEntityType } from '@entity';import type { PropertyDefinitionDomain } from '../types';/**diff --git a/js/app/packages/core/constant/allBlocks.ts b/js/app/packages/core/constant/allBlocks.tsindex eebfddb3be..4e11519ff7 100644--- a/js/app/packages/core/constant/allBlocks.ts+++ b/js/app/packages/core/constant/allBlocks.ts@@ -6,7 +6,7 @@ import {type FileTypeString,type MimeType,} from '@core/block';-import type { SubType } from '@macro-entity';+import type { SubType } from '@entity';import type { ItemType } from '@service-storage/client';import type { BasicDocumentSubTypeProperty } from '@service-storage/generated/schemas';import type { BasicDocumentFileType } from '@service-storage/generated/schemas/basicDocumentFileType';diff --git a/js/app/packages/core/internal/trackBlockOpened.ts b/js/app/packages/core/internal/trackBlockOpened.tsindex 5fb14f18f1..dc2d0c1b5c 100644--- a/js/app/packages/core/internal/trackBlockOpened.ts+++ b/js/app/packages/core/internal/trackBlockOpened.ts@@ -1,8 +1,8 @@import type { BlockName } from '../block';import { useUpsertToHistoryMutation } from '@queries/history/history';-import { optimisticUpdateDssItemViewedAt } from '@macro-entity';import {hasSoupEntity,+ optimisticUpdateSoupItemViewedAt,refetchSoupEntity,type SoupEntityTag,} from '@queries/soup/cache';@@ -30,7 +30,7 @@ export function track({const inSoup = hasSoupEntity(itemId);if (inSoup) {- optimisticUpdateDssItemViewedAt(itemId);+ optimisticUpdateSoupItemViewedAt(itemId);} else if (itemType) {refetchSoupEntity(itemId, itemType as SoupEntityTag);}diff --git a/js/app/packages/entity/src/core/Layout.tsx b/js/app/packages/entity/src/core/Layout.tsxindex e3e0c10a5f..930b4881ff 100644--- a/js/app/packages/entity/src/core/Layout.tsx+++ b/js/app/packages/entity/src/core/Layout.tsx@@ -5,7 +5,7 @@ export function Layout(props: JSX.HTMLAttributes<HTMLDivElement>) {const [local, rest] = splitProps(props, ['class', 'children']);return (- <div class={cn('entity-layout', local.class)} {...rest}>+ <div class={cn(local.class)} {...rest}>{local.children}</div>);diff --git a/js/app/packages/macro-entity/src/components/Entity.tsx b/js/app/packages/macro-entity/src/components/Entity.tsxdeleted file mode 100644index bdba4f808c..0000000000--- a/js/app/packages/macro-entity/src/components/Entity.tsx+++ /dev/null@@ -1,162 +0,0 @@-import { getEntityIconConfig } from 'core/component/EntityIcon';-import { StaticMarkdown } from 'core/component/LexicalMarkdown/component/core/StaticMarkdown';-import { unifiedListMarkdownTheme } from 'core/component/LexicalMarkdown/theme';-import type { Component, JSX, ParentProps, Ref } from 'solid-js';-import { children, createMemo, Show, Suspense } from 'solid-js';-import { Dynamic } from 'solid-js/web';-import { formatDocumentName } from '@service-storage/util/filename';-import { createProfilePictureQuery } from '../queries/auth';-import type { EntityData } from '../types/entity';-import type { EntityClickHandler } from './EntityWithEverything';--interface EntityProps<T extends EntityData> extends ParentProps {- entity: T;- timestamp?: number;- icon?: Component<JSX.SvgSVGAttributes<SVGSVGElement>>;- iconClass?: string;- onClick?: EntityClickHandler<T>;- ref?: Ref<HTMLDivElement>;-}--export function Entity<T extends EntityData = EntityData>(- props: EntityProps<T>-) {- const iconConfig = createMemo(() => getEntityIconConfig(props.entity));-- const content = children(() => {- if (props.children) return props.children;-- switch (props.entity.type) {- case 'channel':- return (- <Show when={props.entity.latestMessage}>- {(latestMessage) => (- <StaticMarkdown- markdown={latestMessage().content}- theme={unifiedListMarkdownTheme}- singleLine={true}- />- )}- </Show>- );- case 'email':- return (- <p>- <span class="font-semibold mr-2 text-ink">- {props.entity.senderName}- </span>- <span class="text-ink-muted">{props.entity.snippet}</span>- </p>- );- default:- return props.children;- }- });-- const formattedDate = createMemo(() => {- const timestamp = props.timestamp ?? props.entity.updatedAt;- if (!timestamp) return;- const date = new Date(timestamp);- const currentDate = new Date();-- if (date.getDate() === currentDate.getDate())- return date.toLocaleTimeString('en-US', {- hour: '2-digit',- minute: '2-digit',- });-- if (date.getFullYear() === currentDate.getFullYear())- return date.toLocaleDateString('en-US', {- month: 'short',- day: 'numeric',- });-- return date.toLocaleDateString('en-US', {- month: 'numeric',- day: 'numeric',- year: '2-digit',- });- });-- const displayName = createMemo(() => {- if (props.entity.type === 'document') {- return formatDocumentName(props.entity.name, props.entity.fileType, {- fullyQualifiedBlockName: true,- });- }- return props.entity.name;- });-- return (- <div- data-entity- data-entity-id={props.entity.id}- class="@md:flex grid w-full min-w-0 flex-1 grid-cols-2 @md:flex-row @md:items-center @md:gap-4"- ref={props.ref}- onClick={props.onClick ? [props.onClick, props.entity] : undefined}- role="button"- tabIndex={0}- >- {/* Icon and name - top left on mobile, first item on desktop */}- <div class="order-1 flex flex-row items-center gap-2">- <div class="flex @md:size-6 size-4 shrink-0 items-center justify-center">- <Dynamic- component={props.icon ?? iconConfig().icon}- class={`flex size-full ${props.iconClass ?? iconConfig().foreground}`}- />- </div>- <span class="@md:w-52 truncate font-medium text-sm">- {displayName()}- </span>- </div>-- {/* Content - full width bottom row on mobile, middle on desktop */}- <div class="@md:order-2 order-3 col-span-2 flex min-h-10 w-full min-w-0 flex-1 items-center font-medium text-sm">- <div class="line-clamp-1 w-full">{content()}</div>- </div>-- {/* Date and user - top right on mobile, end on desktop */}- <div class="@md:order-3 order-2 @md:ml-5 flex flex-row items-center justify-end gap-2.5">- <Show when={formattedDate()}>- {(date) => (- <span class="whitespace-nowrap font-medium text-sm">{date()}</span>- )}- </Show>- <div class="@md:flex hidden size-8 items-center justify-center">- <UserIcon id={props.entity.ownerId} />- </div>- </div>- </div>- );-}--// SCUFFED THEME: how do we want to handle these colors?-function UserIcon(props: { id: string; name?: string }) {- const fallbackName = () => props.name || props.id.replace('macro|', '');- const Fallback = () => (- <span class="flex size-8 items-center justify-center rounded-full bg-[oklch(0.551_0.027_264.364)]">- <span class="font-medium text-sm text-white">- {fallbackName().charAt(0).toUpperCase()}- </span>- </span>- );-- if (!props.id.startsWith('macro|')) return <Fallback />;-- const profilePicQuery = createProfilePictureQuery(props.id);- const Loading = () => (- <div class="flex size-8 animate-pulse rounded-full bg-[oklch(0.446_0.03_256.802)]" />- );- return (- <Suspense fallback={<Loading />}>- <Show when={profilePicQuery.data?.url} fallback={<Fallback />}>- {(url) => (- <img- src={url()}- class="inline-block size-8 rounded-full bg-[oklch(0.551_0.027_264.364)]"- />- )}- </Show>- </Suspense>- );-}diff --git a/js/app/packages/macro-entity/src/components/EntityPropertyValues.tsx b/js/app/packages/macro-entity/src/components/EntityPropertyValues.tsxdeleted file mode 100644index 121e7ff80e..0000000000--- a/js/app/packages/macro-entity/src/components/EntityPropertyValues.tsx+++ /dev/null@@ -1,173 +0,0 @@-import { PropertyValue } from '@core/component/Properties/component/propertyValue/PropertyValue';-import {- PropertiesProvider,- type PropertySaveHandler,-} from '@core/component/Properties/context/PropertiesContext';-import { Modals } from '@core/component/Properties/component/modal';-import type {- Property,- PropertyApiValues,-} from '@core/component/Properties/types';-import { SYSTEM_PROPERTY_IDS } from '@core/component/Properties/constants';-import type { EntityType } from '@service-properties/generated/schemas/entityType';-import { For, Show, createMemo } from 'solid-js';-import { useSaveEntityPropertyMutation } from '@queries/properties/entity';--const PROPERTY_SORT_ORDER = [- SYSTEM_PROPERTY_IDS.STATUS,- SYSTEM_PROPERTY_IDS.PRIORITY,- SYSTEM_PROPERTY_IDS.ASSIGNEES,-] as const;--function sortProperties(properties: Property[]): Property[] {- return [...properties].sort((a, b) => {- const aIndex = PROPERTY_SORT_ORDER.indexOf(- a.propertyDefinitionId as (typeof PROPERTY_SORT_ORDER)[number]- );- const bIndex = PROPERTY_SORT_ORDER.indexOf(- b.propertyDefinitionId as (typeof PROPERTY_SORT_ORDER)[number]- );-- if (aIndex !== -1 && bIndex !== -1) {- return aIndex - bIndex;- }- if (aIndex !== -1) {- return -1;- }- if (bIndex !== -1) {- return 1;- }- return 0;- });-}--export type EntityPropertyValuesProps = {- properties: Property[];- entityId: string;- entityType: EntityType;- excludeKeyProperties?: boolean;- maxDisplay?: number;- onRefresh?: () => void;-};--const MAX_DEFAULT_DISPLAY = 4;--export const EntityPropertyValues = (props: EntityPropertyValuesProps) => {- const displayProperties = createMemo(() => {- const sorted = sortProperties(props.properties);- return sorted.slice(0, props.maxDisplay ?? MAX_DEFAULT_DISPLAY);- });-- const saveMutation = useSaveEntityPropertyMutation();-- const saveHandler: PropertySaveHandler = {- saveProperty: (property: Property, value: PropertyApiValues) =>- saveMutation.mutateAsync({- entityId: props.entityId,- entityType: props.entityType,- property,- apiValues: value,- }),- saveDate: (property: Property, date: Date) =>- saveMutation.mutateAsync({- entityId: props.entityId,- entityType: props.entityType,- property,- apiValues: {- valueType: 'DATE',- value: date.toISOString(),- },- }),- };-- return (- <Show when={props.properties.length > 0}>- <PropertiesProvider- entityType={props.entityType}- canEdit={true}- properties={displayProperties}- onRefresh={() => {}}- onPropertyAdded={() => {}}- onPropertyDeleted={() => {}}- saveHandler={saveHandler}- >- <div class="flex items-center gap-1 justify-start overflow-hidden">- <For each={displayProperties()}>- {(property) => (- <div class="relative">- <PropertyValue property={property} condensed />- </div>- )}- </For>- </div>- <Modals />- </PropertiesProvider>- </Show>- );-};--export const KeyPropertiesGrid = (props: EntityPropertyValuesProps) => {- const keyProperties = createMemo(() => {- const filtered = props.properties.filter((prop) =>- PROPERTY_SORT_ORDER.includes(- prop.propertyDefinitionId as (typeof PROPERTY_SORT_ORDER)[number]- )- );-- return filtered.sort((a, b) => {- const aIndex = PROPERTY_SORT_ORDER.indexOf(- a.propertyDefinitionId as (typeof PROPERTY_SORT_ORDER)[number]- );- const bIndex = PROPERTY_SORT_ORDER.indexOf(- b.propertyDefinitionId as (typeof PROPERTY_SORT_ORDER)[number]- );- return aIndex - bIndex;- });- });-- const saveMutation = useSaveEntityPropertyMutation();- const saveHandler: PropertySaveHandler = {- saveProperty: (property: Property, value: PropertyApiValues) =>- saveMutation.mutateAsync({- entityId: props.entityId,- entityType: props.entityType,- property,- apiValues: value,- }),- saveDate: (property: Property, date: Date) =>- saveMutation.mutateAsync({- entityId: props.entityId,- entityType: props.entityType,- property,- apiValues: {- valueType: 'DATE',- value: date.toISOString(),- },- }),- };-- return (- <Show when={keyProperties().length > 0}>- <PropertiesProvider- entityType={props.entityType}- canEdit={true}- properties={keyProperties}- onRefresh={() => {}}- onPropertyAdded={() => {}}- onPropertyDeleted={() => {}}- saveHandler={saveHandler}- >- <div class="grid grid-cols-[auto_auto_2.4rem] gap-1 items-center">- <For each={keyProperties()}>- {(property) => (- <div class="relative">- <PropertyValue property={property} condensed />- </div>- )}- </For>- </div>- <Modals />- </PropertiesProvider>- </Show>- );-};diff --git a/js/app/packages/macro-entity/src/components/EntityWithEverything.tsx b/js/app/packages/macro-entity/src/components/EntityWithEverything.tsxdeleted file mode 100644index c27c8054f1..0000000000--- a/js/app/packages/macro-entity/src/components/EntityWithEverything.tsx+++ /dev/null@@ -1,1727 +0,0 @@-import { EntityIcon } from '@core/component/EntityIcon';-import type { Property } from '@core/component/Properties/types';-import { LabelAndHotKey, Tooltip } from '@core/component/Tooltip';-import '@core/directive/dnd';-import { useDragOperation } from '@app/component/ItemDragAndDrop';-import { useEmail, useUserId } from '@core/context/user';-import { TOKENS } from '@core/hotkey/tokens';-import { isTouchDevice } from '@core/mobile/isTouchDevice';-import { matches } from '@core/util/match';-import ArrowBendUpLeftIcon from '@icon/regular/arrow-bend-up-left.svg';-import AtIcon from '@icon/regular/at.svg';-import ChatIcon from '@icon/regular/chat.svg';-import CheckIcon from '@icon/regular/check.svg';-import {- getAllNotificationsFromGroup,- getMostRecentNotification,- type NotificationStack,- stackNotifications,- type UnifiedNotification,-} from '@notifications';-import { formatDocumentName } from '@service-storage/util/filename';-import { syncServiceClient } from '@service-sync/client';-import { ChannelTypeEnum } from '@service-comms/client';-import { mergeRefs } from '@solid-primitives/refs';-import { createDraggable } from '@thisbeyond/solid-dnd';-import { getEntityIconConfig } from 'core/component/EntityIcon';-import { StaticMarkdown } from 'core/component/LexicalMarkdown/component/core/StaticMarkdown';-import { unifiedListMarkdownTheme } from 'core/component/LexicalMarkdown/theme';-import { UserIcon } from 'core/component/UserIcon';-import {- emailToMacroId,- tryMacroId,- useDisplayName,- useDisplayNameParts,-} from 'core/user';-import type { JSX, ParentProps, Ref } from 'solid-js';-import {- createDeferred,- createMemo,- createSignal,- createUniqueId,- For,- Match,- onCleanup,- onMount,- Show,- Suspense,- Switch,-} from 'solid-js';-import { Dynamic } from 'solid-js/web';-import {- createProjectQuery,- isProjectContainedEntity,- type ProjectContainedEntity,-} from '../queries/project';-import { isSearchEntity } from '../queries/search';-import type { EntityDragData } from '../types/drag';-import {- type EntityData,- isTaskEntity,- type ProjectEntity,-} from '../types/entity';-import type {- Notification,- WithNotification,- WithStackedNotifications,-} from '../types/notification';-import type {- ChannelContentHitData,- ContentHitData,- EmailContentHitData,- SearchLocation,- WithSearch,-} from '../types/search';-import { KeyPropertiesGrid } from './EntityPropertyValues';--export type EntityClickEvent = Parameters<- JSX.EventHandler<HTMLDivElement, MouseEvent>->[0];-type EntityPointerDownEvent = Parameters<- JSX.EventHandler<HTMLDivElement, PointerEvent>->[0];-type EntityClickProps<T extends EntityData, E> = {- type: 'entity' | 'entity-project-path';- entity: T;- projectEntity?: T;- event: E;- location?: SearchLocation;-};-export type EntityClickHandler<T extends EntityData> = (- args: EntityClickProps<T, EntityClickEvent>-) => void;-export type EntityPointerDownHandler<T extends EntityData> = (- args: EntityClickProps<T, EntityPointerDownEvent>-) => void;--export const ENTITY_HEIGHT = 40;--function UnreadIndicator(props: { active?: boolean }) {- return (- <div class="flex size-4 items-center justify-center">- <div- classList={{- 'bg-accent rounded-full size-2': true,- 'opacity-0': !props.active,- }}- />- </div>- );-}--function SharedBadge(props: { ownerId: string }) {- return (- <div class="font-mono font-medium user-select-none uppercase flex items-center text-ink-extra-muted p-0.5 gap-1 text-[0.625rem] rounded-full border border-edge-muted pr-2">- <UserIcon id={props.ownerId} size="xs" />- shared- </div>- );-}--function GenericContentHit(props: { data: ContentHitData }) {- return (- <div class="text-ink-muted truncate flex items-center">- <StaticMarkdown- markdown={props.data.content}- theme={unifiedListMarkdownTheme}- singleLine={true}- />- </div>- );-}--function ChannelMessageContentHit(props: { data: ChannelContentHitData }) {- const [userName] = useDisplayName(tryMacroId(props.data.senderId));-- return (- <div class="flex gap-2 items-center min-w-0">- <div class="flex size-5 shrink-0 items-center justify-center">- <UserIcon id={props.data.senderId} size="xs" />- </div>- <div class="flex gap-2 w-full min-w-0 overflow-hidden items-baseline">- <div class="shrink-0 truncate min-w-0 font-medium">{userName()}</div>- <div class="shrink-0 font-mono text-xs touch:mobile-width:text-sm uppercase text-ink-extra-muted">- {createFormattedDate(props.data.sentAt)}- </div>- <div class="text-ink-muted truncate flex items-center flex-1 min-w-0">- <StaticMarkdown- markdown={props.data.content}- theme={unifiedListMarkdownTheme}- singleLine={true}- />- </div>- </div>- </div>- );-}--function EmailMessageContentHit(props: {- allData: EmailContentHitData[];- data: EmailContentHitData;-}) {- const isSingleMatch = createMemo(() => {- return props.allData.length === 1;- });- const isSingleSender = createMemo(() => {- const senders = props.allData.map((d) => d.sender);- if (senders.length === 1) return true;- if (new Set(senders).size === 1) return true;- return false;- });- const isSingleSentAt = createMemo(() => {- const sentAts = props.allData.map((d) => d.sentAt);- if (sentAts.length === 1) return true;- if (new Set(sentAts).size === 1) return true;- const formattedDates = sentAts.map(createFormattedDate);- if (new Set(formattedDates).size === 1) return true;- return false;- });-- return (- <div class="flex gap-2 items-center min-w-0">- <div class="flex size-5 shrink-0 items-center justify-center">- <UserIcon id={props.data.senderId} size="xs" />- </div>- <div class="flex gap-2 w-full min-w-0 overflow-hidden items-baseline">- <Show when={!isSingleMatch() && !isSingleSender()}>- <div class="shrink-0 truncate min-w-0 font-medium">- {props.data.sender}- </div>- </Show>- <Show when={!isSingleMatch() && !isSingleSentAt()}>- <div class="shrink-0 font-mono text-xs touch:mobile-width:text-sm uppercase text-ink-extra-muted">- {createFormattedDate(props.data.sentAt)}- </div>- </Show>- <div class="text-ink-muted truncate flex items-center flex-1 min-w-0">- <StaticMarkdown- markdown={props.data.content}- theme={unifiedListMarkdownTheme}- singleLine={true}- />- </div>- </div>- </div>- );-}--function ThreadBorder() {- return (- <div- class="absolute left-[calc(0.5rem+1px)] w-[1px] border-l border-edge-muted -top-0.75"- style={{ height: '6px' }}- />- );-}--function CollapsibleListRow(- props: ParentProps<{- onClick?: (e: EntityClickEvent) => void;- classList?: Record<string, boolean>;- enableHover?: boolean;- showThreadBorder?: boolean;- blockNavigation?: boolean;- }>-) {- return (- <div- class="relative flex gap-1 items-center min-w-0 h-8 transition-all"- classList={{- 'hover:bg-hover/50 hover:opacity-85':- props.enableHover ?? !!props.onClick,- ...props.classList,- }}- onClick={(e) => {- if (props.onClick) {- if (props.blockNavigation) {- e.stopPropagation();- }- props.onClick(e);- }- }}- data-blocks-navigation={props.blockNavigation}- >- <Show when={props.showThreadBorder}>- <ThreadBorder />- </Show>- {props.children}- </div>- );-}--function CollapsibleList<T>(props: {- items: T[];- visibleCount?: number;- children: (item: T, index?: number, count?: number) => any;- threadBorder?: boolean;-}) {- const [showAll, setShowAll] = createSignal(false);- const visibleCount = () => props.visibleCount ?? 3;-- const visibleItems = () => {- if (props.items.length <= visibleCount() || showAll()) {- return props.items;- }- return props.items.slice(0, visibleCount());- };-- const count = () => props.items.length;- const hasMore = () => props.items.length > visibleCount();-- return (- <>- <For each={visibleItems()}>- {(child, index) => props.children(child, index(), count())}- </For>- <Show when={hasMore()}>- <div class="h-5">- <Show when={props.threadBorder}>- <ThreadBorder />- </Show>- <button- class="block w-fit px-2 py-0.5 text-xxs border border-edge uppercase font-mono hover:font-medium"- onClick={(e) => {- e.stopPropagation();- setShowAll((prev) => !prev);- }}- data-blocks-navigation- >- <Show when={!showAll()} fallback={<>Collapse</>}>- + {props.items.length - visibleCount()} More- </Show>- </button>- </div>- </Show>- </>- );-}--function NotificationRow(props: {- notification: Notification;- onClick?: NotificationClickHandler;- entity: EntityData;- icon?: (props: { class?: string }) => JSX.Element;-}) {- const [userName] = useDisplayName(- tryMacroId(props.notification.senderId ?? '')- );-- const ActionContent = () => {- if (- props.notification.notificationEventType === 'document_mention' ||- props.notification.notificationEventType === 'channel_message_document'- ) {- return 'shared';- }- if (props.notification.notificationEventType === 'task_assigned') {- return 'assigned to you';- }- if (props.notification.notificationEventType === 'channel_mention') {- return 'mentioned you';- }-- const tag = (props.notification as UnifiedNotification).notificationMetadata- .tag;- if (- tag !== 'channel_mention' &&- tag !== 'channel_message_send' &&- tag !== 'channel_message_reply'- )- return '';-- return 'message';- };-- const MessageContent = () => {- if (- props.notification.notificationEventType === 'document_mention' ||- props.notification.notificationEventType === 'channel_message_document'- ) {- return '';- }-- const n = props.notification as UnifiedNotification;- const tag = n.notificationMetadata.tag;- if (- tag !== 'channel_mention' &&- tag !== 'channel_message_send' &&- tag !== 'channel_message_reply'- ) {- return '';- }-- const content = n.notificationMetadata.content.messageContent;- return (- <Show- when={content?.trim()}- fallback={<span class="italic text-ink-disabled">Attached items</span>}- >- {(content) => (- <StaticMarkdown- markdown={content()}- theme={unifiedListMarkdownTheme}- singleLine={true}- />- )}- </Show>- );- };-- return (- <CollapsibleListRow- showThreadBorder- onClick={- props.onClick- ? (e) => {- props.onClick?.({- type: 'entity',- entity: {- ...props.entity,- notification: props.notification,- },- event: e,- });- }- : undefined- }- >- <div class="flex size-5 shrink-0 items-center justify-center mr-1">- <Show- when={props.icon}- fallback={<UserIcon id={props.notification.senderId!} size="xs" />}- >- <Dynamic component={props.icon} class="size-4 text-ink-muted" />- </Show>- </div>- <div class="flex gap-1 w-full min-w-0 overflow-hidden items-baseline">- <div class="w-[20cqw] shrink-0 truncate min-w-0">- {userName()}{' '}- <span class="opacity-70 uppercase font-mono text-[0.625rem] ml-2">- {ActionContent()}- </span>- </div>- <MessageContent />- </div>- <div class="shrink-0 font-mono text-xs touch:mobile-width:text-sm uppercase text-ink-extra-muted ml-2">- {createFormattedDate(props.notification.createdAt)}- </div>- </CollapsibleListRow>- );-}--/**- * Shared row component for stacked notifications (new messages and replies)- */-function StackedNotificationRow(props: {- notifications: UnifiedNotification[];- title: JSX.Element;- icon: (props: { class?: string }) => JSX.Element;- onClick?: (e: EntityClickEvent) => void;-}) {- const mostRecent = () => props.notifications[0];-- // Get up to 3 unique sender IDs for avatar display- const senderIds = createMemo(() => {- const ids = new Set<string>();- for (const n of props.notifications) {- if (n.senderId) {- ids.add(n.senderId);- if (ids.size >= 3) break;- }- }- return Array.from(ids);- });-- // Get the sender of the most recent message- const mostRecentSenderId = () => mostRecent()?.senderId ?? '';- const [mostRecentSenderName] = useDisplayName(- tryMacroId(mostRecentSenderId())- );-- const messageContent = createMemo(() => {- const notification = mostRecent();- if (!notification) return '';- const tag = notification.notificationMetadata.tag;- if (- tag !== 'channel_mention' &&- tag !== 'channel_message_send' &&- tag !== 'channel_message_reply'- ) {- return '';- }- const content = notification.notificationMetadata.content.messageContent;- return content?.trim() ?? '';- });-- return (- <CollapsibleListRow showThreadBorder onClick={props.onClick}>- <div class="flex size-5 shrink-0 items-center justify-center mr-1">- <props.icon class="size-4 text-ink-muted" />- </div>- <div class="flex gap-1 w-full overflow-hidden items-baseline">- {/* Count + Stacked avatars */}- <div class="min-w-[20cqw] shrink-0 flex items-center gap-1">- <span>{props.title}</span>- <div class="flex shrink-0 items-center">- <For each={senderIds()}>- {(id, index) => (- <div- class="flex size-5 items-center justify-center"- classList={{ '-ml-2': index() > 0 }}- >- <UserIcon id={id} size="xs" />- </div>- )}- </For>- </div>- </div>- {/* Sender avatar + name + message content */}- <Show when={mostRecentSenderId()}>- <div class="flex items-center gap-1 flex-1 min-w-0">- <span class="shrink-0 font-medium">{mostRecentSenderName()}</span>- <Show when={messageContent()}>- {(content) => (- <div class="text-ink-muted truncate flex items-center flex-1 min-w-0">- <StaticMarkdown- markdown={content()}- theme={unifiedListMarkdownTheme}- singleLine={true}- />- </div>- )}- </Show>- </div>- </Show>- </div>- <div class="shrink-0 font-mono text-xs touch:mobile-width:text-sm uppercase text-ink-extra-muted ml-2">- {createFormattedDate(mostRecent().createdAt)}- </div>- </CollapsibleListRow>- );-}--/**- * Row component for stacked new messages- */-function StackedNewMessagesRow(props: {- group: NotificationStack & { type: 'channel_message_send' };- onClick?: StackedNotificationClickHandler;- entity: EntityData;-}) {- const count = () => props.group.notifications.length;-- return (- <StackedNotificationRow- notifications={props.group.notifications}- title={<>{count()} New Messages</>}- icon={ChatIcon}- onClick={- props.onClick- ? (e) =>- props.onClick?.({- group: props.group,- entity: props.entity,- event: e,- })- : undefined- }- />- );-}--/**- * Row component for stacked replies to a thread- */-function StackedRepliesRow(props: {- group: NotificationStack & { type: 'channel_message_reply' };- onClick?: StackedNotificationClickHandler;- entity: EntityData;-}) {- const count = () => props.group.notifications.length;-- // Derive from notifications[0] (mostRecent)- const threadParentSenderId = () => {- const notification = props.group.notifications[0];- if (!notification) return '';- const meta = notification.notificationMetadata;- if (meta.tag !== 'channel_message_reply') return '';- return meta.content.threadParentSenderId ?? '';- };-- const { firstName } = useDisplayNameParts(tryMacroId(threadParentSenderId()));-- const title = () => (- <>- {count()} {count() === 1 ? 'Reply' : 'Replies'}- <Show when={firstName()}>{(name) => <> to {name}</>}</Show>- </>- );-- return (- <StackedNotificationRow- notifications={props.group.notifications}- title={title()}- icon={ArrowBendUpLeftIcon}- onClick={- props.onClick- ? (e) =>- props.onClick?.({- group: props.group,- entity: props.entity,- event: e,- })- : undefined- }- />- );-}--type StackedNotificationClickHandler<T extends EntityData = EntityData> =- (args: {- group: NotificationStack;- entity: T;- event: EntityClickEvent;- }) => void;--/**- * Renderer component that switches between different stacked notification types- */-function StackedNotificationRenderer(props: {- group: NotificationStack;- onClick?: NotificationClickHandler;- onClickStacked?: StackedNotificationClickHandler;- entity: EntityData;-}) {- return (- <Switch>- <Match when={props.group.type === 'channel_message_send' && props.group}>- {(group) => (- <StackedNewMessagesRow- group={- group() as NotificationStack & { type: 'channel_message_send' }- }- onClick={props.onClickStacked}- entity={props.entity}- />- )}- </Match>- <Match when={props.group.type === 'channel_message_reply' && props.group}>- {(group) => (- <StackedRepliesRow- group={- group() as NotificationStack & { type: 'channel_message_reply' }- }- onClick={props.onClickStacked}- entity={props.entity}- />- )}- </Match>- <Match when={props.group.type === 'channel_mention' && props.group}>- {(group) => (- <NotificationRow- notification={group().notifications[0]}- onClick={props.onClick}- entity={props.entity}- icon={AtIcon}- />- )}- </Match>- <Match- when={- props.group.type !== 'channel_message_send' &&- props.group.type !== 'channel_message_reply' &&- props.group.type !== 'channel_mention' &&- props.group- }- >- {(group) => (- <NotificationRow- notification={group().notifications[0]}- onClick={props.onClick}- entity={props.entity}- />- )}- </Match>- </Switch>- );-}--function ContentHitRow(props: {- allData: ContentHitData[];- data: ContentHitData;- onClick: (e: EntityClickEvent, location?: SearchLocation) => void;- index?: number;- count?: number;-}) {- const match = (): [number, number] | undefined => {- if (props.index !== undefined && props.count !== undefined)- return [props.index, props.count];- };-- return (- <CollapsibleListRow- blockNavigation- onClick={(e) => props.onClick(e, props.data.location)}- showThreadBorder={props.data.type === 'channel'}- >- <Switch>- <Match when={props.data.type === 'channel' && props.data}>- {(data) => <ChannelMessageContentHit data={data()} />}- </Match>- <Match when={props.data.type === 'email' && props.data}>- {(data) => (- <EmailMessageContentHit- allData={props.allData as EmailContentHitData[]}- data={data()}- />- )}- </Match>- <Match when={true}>- <div class="flex gap-2 items-center min-w-0 w-full">- <div class="flex size-5 shrink-0 items-center justify-center">- <div class="h-4/5 border-l border-b w-2 border-edge-muted -translate-y-2 translate-x-[calc(0.25em-1px)]"></div>- </div>- <Show when={match()}>- {(match) => {- return (- <span class="font-mono text-xs touch:mobile-width:text-sm text-ink-disabled/50">- {match()[0] + 1}/{match()[1]}- </span>- );- }}- </Show>- <GenericContentHit data={props.data} />- </div>- </Match>- </Switch>- </CollapsibleListRow>- );-}--// function ImportantBadge(props: { active?: boolean }) {-// return (-// <Show when={props.active}>-// <div class="font-mono font-medium user-select-none uppercase flex items-center text-accent bg-accent/10 p-0.5 px-2 text-[0.625rem] rounded-full border border-accent/10">-// <span class="@max-xl/split:hidden">Important</span>-// <span class="hidden @max-xl/split:block font-bold">!</span>-// </div>-// </Show>-// );-// }-//--type NotificationClickHandler<T extends EntityData = EntityData> =- EntityClickHandler<- WithStackedNotifications<T & { notification: Notification }>- >;--interface EntityProps<T extends WithNotification<EntityData>>- extends ParentProps {- entity: T;- focused?: boolean;- timestamp?: number;- onClick?: EntityClickHandler<T>;- onDblClick?: EntityClickHandler<T>;- onPointerDown?: EntityClickHandler<T>;- onClickRowAction?: (entity: T, type: 'done') => void;- onClickNotification?: NotificationClickHandler<T>;- onMouseOver?: () => void;- onMouseLeave?: () => void;- onFocusIn?: () => void;- onContextMenu?: () => void;- properties?: Property[];- contentPlacement?: 'middle' | 'bottom-row';- unreadIndicatorActive?: boolean;- fadeIfRead?: boolean;- importantIndicatorActive?: boolean;- showLeftColumnIndicator?: boolean;- showUnrollNotifications?: boolean;- showDoneButton?: boolean;- highlighted?: boolean;- selected: { active: boolean; muted?: boolean };- ref?: Ref<HTMLDivElement>;- onChecked?: (checked: boolean, shiftKey?: boolean) => void;- checked?: boolean;- searchActive?: boolean;- splitId?: string;-}--const [hoveredComponentId, setHoveredComponentId] = createSignal<Symbol>(- Symbol()-);--export function EntityWithEverything(- props: EntityProps<WithNotification<EntityData | WithSearch<EntityData>>>-) {- const id = Symbol();- const [actionButtonRef, setActionButtonRef] =- createSignal<HTMLButtonElement | null>(null);- const [entityDivRef, setEntityDivRef] = createSignal<HTMLDivElement | null>(- null- );-- const { keydownDataDuringTask } = trackKeydownDuringTask();- const userEmail = useEmail();-- const getIcon = createMemo(() => getEntityIconConfig(props.entity));-- /**- * TODO (seamus + teo) : These notifications are being attached to the wrong- * entity - ie the channel and not the document being shared. this means- * we have notification rows that point to a channel but do not have a- * message_id to link to. These notifications result in 2 notifications- * on a channel when an item is shared. One for the message, and this- * weird busted one. Needs to be fixed in the service, then I will delete- * this logic.- */- const validNotifications = () => {- return (- props.entity.notifications?.().filter((notification) => {- return (- notification.notificationEventType !== 'channel_message_document'- );- }) ?? []- );- };-- const hasNotifications = () => validNotifications().length > 0;-- const notDoneNotifications = () => {- return validNotifications().filter(({ done }) => !done);- };-- const stackedNotificationsGroups = createMemo(() =>- stackNotifications(notDoneNotifications())- );-- const isSearch = createMemo(- () => !!props.searchActive && isSearchEntity(props.entity)- );-- const searchHighlightName = () =>- isSearchEntity(props.entity) && props.entity.search.nameHighlight;-- const displayName = createMemo(() => {- if (props.entity.type === 'document') {- return formatDocumentName(props.entity.name, props.entity.fileType, {- fullyQualifiedBlockName: true,- });- }- return props.entity.name;- });-- const contentHitData = () => {- if (!isSearchEntity(props.entity)) return [];- return props.entity.search.contentHitData ?? [];- };-- onMount(() => {- if (props.entity.type === 'document' && props.entity.fileType === 'md') {- syncServiceClient.safeWakeup(props.entity.id);- onCleanup(() => {- syncServiceClient.cancelWakeup(props.entity.id);- });- }- });-- const EntityTitle = createMemo(() => {- if (props.entity.type === 'email') {- const isLikelyEmail = (value?: string) =>- typeof value === 'string' && value.includes('@');-- const combinedParticipantNames = createMemo(() => {- if (props.entity.type !== 'email') return [];- const me = userEmail();- if (- props.entity.participants?.length === 1 &&- props.entity.participants?.[0].email === me- ) {- return ['me'];- }- const namesSet = new Set<string>();-- props.entity.participants?.forEach((participant) => {- if (!participant.email) return;- if (me && participant.email === me) return;- const macroDisplayName = useDisplayName(- emailToMacroId(participant.email)- )[0]?.();- const participantFullName = participant.name ?? '';- if (macroDisplayName && !isLikelyEmail(macroDisplayName)) {- namesSet.add(macroDisplayName);- } else if (- participantFullName &&- !isLikelyEmail(participantFullName)- ) {- namesSet.add(participantFullName);- } else {- const emailName = participant.email.split('@')[0];- namesSet.add(emailName);- }- });- return Array.from(namesSet);- });-- const displayedNames = () => {- const names = combinedParticipantNames();- if (!names || names.length === 0) return undefined;- if (names.length === 1) return names[0];- // For multiple participants, use first names only- const firstNames = names.map((name) => name.split(' ')[0]);- if (firstNames.length <= 3) return firstNames.join(', ');- return `${firstNames[0]} .. ${firstNames[firstNames.length - 2]}, ${firstNames[firstNames.length - 1]}`;- };-- return (- <div class="flex gap-1 items-center min-w-0 w-full truncate overflow-hidden @max-md/uList:flex-col @max-md/uList:items-start @max-md/uList:gap-1 @max-md/uList:truncate-none">- {/* sometimes senderName and senderEmail are the same */}- <div- class="flex gap-2 items-center font-semibold shrink-0 @max-md/uList:w-full @max-md/uList:truncate"- classList={{- 'w-[20cqw]': !isSearch(),- }}- >- {/* Icon inline with sender in narrow mode */}- <div class="hidden @max-md/uList:flex size-[1em] shrink-0 items-center justify-center relative group/icon-checkbox">- {/* Checkbox for narrow mode - shown on hover or when checked */}- <button- type="button"- class="absolute inset-0 flex items-center justify-center opacity-0 group-hover/icon-checkbox:opacity-100 transition-opacity"- classList={{- 'opacity-100': props.checked,- }}- onClick={(e) => {- e.stopPropagation();- props.onChecked?.(!props.checked, e.shiftKey);- }}- data-blocks-navigation- >- <div- class="size-[0.875em] flex items-center justify-center rounded-xs border border-edge-muted pointer-events-none"- classList={{- 'bg-accent border-accent': props.checked,- }}- >- <Show when={props.checked}>- <CheckIcon class="w-full h-full text-panel" />- </Show>- </div>- </button>- {/* Icon - hidden on hover in narrow mode when not checked */}- <div- class="flex items-center justify-center group-hover/icon-checkbox:opacity-0 transition-opacity"- classList={{- 'opacity-0': props.checked,- }}- >- <Dynamic- component={getIcon().icon}- class={`flex size-full ${getIcon().foreground}`}- />- </div>- </div>- {/* Sender Name */}- <div class="truncate flex items-center gap-1 @max-md/uList:min-w-0">- <Show- when={props.entity.type === 'email' && props.entity.isDraft}- >- <div class="font-mono font-medium user-select-none uppercase flex items-center text-accent-30 p-0.5 gap-1 text-[0.625rem] rounded-full border border-edge-muted px-2">- DRAFT- </div>- </Show>- <span>- {displayedNames() ??- props.entity.senderName ??- props.entity.senderEmail?.split('@')[0]}- </span>- </div>- {/* Sender Email Address */}- {/* <Show- when={- props.entity.senderEmail- }- >- <div class="text-accent-ink truncate">{`<${- props.entity.senderEmail- }>`}</div>- </Show> */}- </div>- {/* Subject */}- {/*<ImportantBadge active={props.importantIndicatorActive} />*/}- <div class="flex items-center w-full gap-2 flex-1 min-w-0 @max-md/uList:flex-col @max-md/uList:items-start @max-md/uList:w-full @max-md/uList:gap-1">- <div class="flex items-center gap-2 flex-1 min-w-0 @max-md/uList:w-full @max-md/uList:justify-between @max-md/uList:min-w-0">- <div- class="shrink-0 truncate @max-md/uList:min-w-0 @max-md/uList:flex-1"- classList={{- 'font-regular text-ink-disabled': isSearch(),- 'font-medium': !isSearch(),- }}- >- <Show when={isSearch()}>- <span class="@max-md/uList:hidden"> – </span>- </Show>- <Show- when={isSearch() && searchHighlightName()}- fallback={displayName()}- >- {(name) => (- <StaticMarkdown- markdown={name()}- theme={unifiedListMarkdownTheme}- singleLine={true}- />- )}- </Show>- </div>- {/* Body snippet - inline in wide mode */}- <div class="truncate shrink grow opacity-60 @max-md/uList:hidden">- {props.entity.snippet}- </div>- {/* Timestamp inline with subject in narrow mode */}- <Show when={props.timestamp ?? props.entity.updatedAt}>- {(date) => (- <span class="hidden @max-md/uList:inline shrink-0 whitespace-nowrap text-xs touch:mobile-width:text-sm font-mono uppercase text-ink-extra-muted">- {createFormattedDate(date())}- </span>- )}- </Show>- </div>- {/* Body snippet - below subject in narrow mode */}- <div class="hidden @max-md/uList:block truncate w-full text-xs touch:mobile-width:text-sm opacity-60">- {props.entity.snippet}- </div>- </div>- </div>- );- }-- const channelEntity = createMemo(() =>- props.entity.type === 'channel' ? props.entity : null- );-- const latestMessage = createMemo(() => channelEntity()?.latestMessage);-- const userNameFromSender = createMemo(() => {- const senderId = channelEntity()?.latestMessage?.senderId;- if (!senderId) return;- const [userName] = useDisplayName(tryMacroId(senderId));- return userName();- });-- const showLatestMessageInfo = () => {- return (- !props.showUnrollNotifications &&- props.entity.type === 'channel' &&- !isSearchEntity(props.entity)- );- };-- return (- <div class="flex gap-2 items-center min-w-0 w-fit max-w-full overflow-hidden @max-md/uList:flex-col @max-md/uList:items-start @max-md/uList:w-full @max-md/uList:gap-1">- <span class="flex gap-1 truncate font-medium shrink-0 items-center @max-md/uList:w-full @max-md/uList:flex-col @max-md/uList:items-start @max-md/uList:gap-1">- <div class="flex items-center gap-2 w-full @max-md/uList:justify-between @max-md/uList:min-w-0">- {/* Icon inline with title in narrow mode */}- <div class="hidden @max-md/uList:flex size-[1em] shrink-0 items-center justify-center relative group/icon-checkbox-nonemail">- {/* Checkbox for narrow mode - shown on hover or when checked */}- <button- type="button"- class="absolute inset-0 flex items-center justify-center opacity-0 group-hover/icon-checkbox-nonemail:opacity-100 transition-opacity"- classList={{- 'opacity-100': props.checked,- }}- onClick={(e) => {- e.stopPropagation();- props.onChecked?.(!props.checked, e.shiftKey);- }}- data-blocks-navigation- >- <div- class="size-[0.875em] flex items-center justify-center rounded-xs border border-edge-muted pointer-events-none"- classList={{- 'bg-accent border-accent': props.checked,- }}- >- <Show when={props.checked}>- <CheckIcon class="w-full h-full text-panel" />- </Show>- </div>- </button>- {/* Icon - hidden on hover in narrow mode when not checked */}- <div- class="flex items-center justify-center group-hover/icon-checkbox-nonemail:opacity-0 transition-opacity"- classList={{- 'opacity-0': props.checked,- }}- >- <Show- when={- props.entity.type === 'channel' &&- props.entity.channelType === ChannelTypeEnum.DirectMessage- }- fallback={- <Dynamic- component={getIcon().icon}- class={`flex size-full ${getIcon().foreground}`}- />- }- >- <DirectMessageIcon entity={props.entity} />- </Show>- </div>- </div>- <span- class="font-semibold truncate @max-md/uList:min-w-0 @max-md/uList:flex-1"- classList={{- 'w-[20cqw]': !props.showUnrollNotifications,- }}- >- <Show- when={isSearch() && searchHighlightName()}- fallback={displayName()}- >- {(name) => (- <StaticMarkdown- markdown={name()}- theme={unifiedListMarkdownTheme}- singleLine={true}- />- )}- </Show>- </span>- {/* Timestamp inline with title in narrow mode */}- <Show when={props.timestamp ?? props.entity.updatedAt}>- {(date) => (- <span class="hidden @max-md/uList:inline shrink-0 whitespace-nowrap text-xs touch:mobile-width:text-sm font-mono uppercase text-ink-extra-muted">- {createFormattedDate(date())}- </span>- )}- </Show>- </div>-- <Show when={showLatestMessageInfo()}>- <div class="flex items-center gap-1 @max-md/uList:w-full @max-md/uList:flex-col @max-md/uList:items-start @max-md/uList:gap-1">- {/*<ImportantBadge active={props.importantIndicatorActive} />*/}- <span class="font-medium shrink-0 truncate @max-md/uList:w-full">- {userNameFromSender()}- </span>- <Show when={latestMessage()}>- {(lastMessage) => (- <div class="truncate shrink grow opacity-60 flex items-center @max-md/uList:w-full @max-md/uList:text-xs @max-md/uList:touch:mobile-width:text-sm">- {/* TODO (seamus): Channels endpoint does not return any information about attachments. If we have an empty message, assume it's attachments.*/}- <Show- when={lastMessage().content.trim()}- fallback={- <span class="italic text-ink-disabled">- Attached items- </span>- }- >- {(content) => (- <StaticMarkdown- markdown={content()}- theme={unifiedListMarkdownTheme}- singleLine={true}- />- )}- </Show>- </div>- )}- </Show>- </div>- </Show>- </span>- </div>- );- });-- const { isAltKey } = useDragOperation();- const operation = createMemo(() => {- switch (props.entity.type) {- case 'document':- return isAltKey() ? 'copy' : 'move';- case 'chat':- return isAltKey() ? 'copy' : 'move';- default:- return 'move';- }- });- const draggableId = `${props.entity.id}-${props.splitId ?? createUniqueId()}`;- const dragData: EntityDragData = {- dragType: 'entity',- splitId: props.splitId,- ...props.entity,- operation,- };- const draggable = createDraggable(draggableId, dragData);- false && draggable;-- // The main click handler for the entity row should navigate to an entity- // without forcing focus back to the source split until after navigation.- // Certain buttons in the entity need to NOT Navigate AND return focus to- // the split. Those buttons should have a 'data-blocks-navigation'- function blocksNavigation(e: PointerEvent | MouseEvent): boolean {- const { target } = e;- if (target instanceof Element) {- const closest = target.closest('[data-blocks-navigation]');- if (closest && entityDivRef()?.contains(closest)) return true;- }- return false;- }-- const userId = useUserId();- const sharedData = () => {- if (props.entity.type === 'channel') {- return false;- }-- if (props.entity.ownerId === userId()) {- return false;- }- return {- ownerDisplayName: useDisplayName(tryMacroId(props.entity.ownerId))[0],- ownerId: props.entity.ownerId,- };- };-- /**- * Properties for this entity- * TODO - @danielkweon: Once endpoint includes properties, remove temp data and use: props.displayProperties ?? []- */- const properties = (): Property[] => {- // Use real properties if provided, otherwise use temp data for testing- return props.properties ?? [];- };-- return (- <div- use:draggable- data-checked={props.checked}- class="everything-entity w-full relative group/entity hover:bg-hover/30 text-sm touch:mobile-width:text-base"- style={{- 'min-height': `${ENTITY_HEIGHT}px`,- }}- classList={{- 'outline outline-accent/20 outline-offset-[-1px]':- !isTouchDevice() && props.selected.active && !props.checked,- '!bg-accent/5 outline outline-accent/20 outline-offset-[-1px]':- props.checked,- 'bracket outline outline-accent/20 outline-offset-[-1px]':- !isTouchDevice() && props.selected.active,- 'after:opacity-20 !outline-accent/10':- !isTouchDevice() && props.selected.active && props.selected.muted,- 'active:bracket active:outline active:outline-accent/20 active:outline-offset-[-1px]':- isTouchDevice() && !props.checked,- }}- onMouseMove={() => {- if (isTouchDevice()) return;-- setHoveredComponentId(id);- props.onMouseOver?.();- }}- onContextMenu={() => {- props.onContextMenu?.();- }}- >- <div- data-entity- data-entity-id={props.entity.id}- class="w-full min-w-0 grid flex-1 items-center suppress-css-bracket grid-cols-[2rem_1fr_auto] @max-md/uList:flex @max-md/uList:flex-col pr-2 @max-md/uList:px-2 @max-md/uList:py-2"- onClick={(e) => {- if (blocksNavigation(e)) return;- props.onClick?.({ type: 'entity', entity: props.entity, event: e });- }}- onDblClick={(e) => {- if (blocksNavigation(e)) return;- props.onDblClick?.({- type: 'entity',- entity: props.entity,- event: e,- });- }}- onMouseDown={(e) => {- if (blocksNavigation(e)) return;- e.preventDefault();- }}- onPointerDown={(e) => {- if (blocksNavigation(e)) return;- props.onPointerDown?.({- type: 'entity',- entity: props.entity,- event: e,- });- }}- // Action List is also rendered based on focus, but when focused via Shift+Tab, parent is focused due to Action List dom not present. Here we check if current browser task has captured Shift+Tab focus on Action List- onFocusIn={(e) => {- if (- !(- keydownDataDuringTask().pressedShiftTab &&- !e.currentTarget.contains(keydownDataDuringTask().target)- )- ) {- return;- }-- actionButtonRef()?.focus();- }}- role="button"- tabIndex={0}- ref={mergeRefs(setEntityDivRef, props.ref)}- >- <button- type="button"- class="col-1 size-full relative group/button flex items-center justify-center bracket-never @max-md/uList:hidden touch:hidden"- onMouseDown={(e) => {- e.stopPropagation();- }}- onClick={(e) => {- e.stopPropagation();- props.onChecked?.(!props.checked, e.shiftKey);- }}- data-blocks-navigation- >- <div- class="size-4 p-0.5 flex items-center justify-center rounded-xs group-hover/button:border-accent group-hover/button:border pointer-events-none"- classList={{- 'ring ring-edge-muted': props.highlighted,- 'bg-panel': !props.checked && props.highlighted,- 'bg-accent border border-accent': props.checked,- }}- >- <Show when={props.checked}>- <CheckIcon class="w-full h-full text-panel" />- </Show>- </div>- <Show- when={- props.showLeftColumnIndicator &&- !props.checked &&- !props.highlighted- }- >- <div class="absolute inset-0 flex items-center justify-center group-hover/button:opacity-0 @max-md/uList:hidden">- <UnreadIndicator active={props.unreadIndicatorActive} />- </div>- </Show>- </button>- {/* Left Column Indicator(s) */}- {/* Icon and name - top left on mobile, first item on desktop */}- <div- class="min-h-10 min-w-[50px] flex flex-row items-center gap-2 col-2 @max-md/uList:col-auto @max-md/uList:w-full @max-md/uList:min-h-0 @max-md/uList:items-start"- classList={{- grow: props.contentPlacement === 'bottom-row',- }}- >- {/* When the left checkbox column is hidden in narrow split containers, we still want- unread indicators to be visible. */}- <Show when={props.showLeftColumnIndicator && !props.checked}>- <div- class="flex size-4 items-center justify-center @min-md/split:hidden"- classList={{- invisible: props.highlighted,- }}- >- <UnreadIndicator active={props.unreadIndicatorActive} />- </div>- </Show>- {/* Icon/Checkbox container - in narrow mode, shows icon by default, checkbox on hover */}- {/* For emails, icon is inline with sender, so hide this container in narrow mode */}- <div class="flex size-5 shrink-0 items-center justify-center relative group/icon-checkbox @max-md/uList:hidden">- {/* Checkbox for narrow mode - shown on hover or when checked, hidden at larger widths */}- <button- type="button"- class="hidden @max-md/uList:flex @min-md/uList:hidden absolute inset-0 items-center justify-center opacity-0 group-hover/icon-checkbox:opacity-100 transition-opacity"- classList={{- 'opacity-100': props.checked,- }}- onClick={(e) => {- e.stopPropagation();- props.onChecked?.(!props.checked, e.shiftKey);- }}- data-blocks-navigation- >- <div- class="size-4 p-0.5 flex items-center justify-center rounded-xs border border-edge-muted pointer-events-none"- classList={{- 'bg-accent border-accent': props.checked,- }}- >- <Show when={props.checked}>- <CheckIcon class="w-full h-full text-panel" />- </Show>- </div>- </button>- {/* Icon - hidden on hover in narrow mode when not checked */}- <div- class="flex items-center justify-center @max-md/uList:group-hover/icon-checkbox:opacity-0 @max-md/uList:transition-opacity"- classList={{- '@max-md/uList:opacity-0': props.checked,- }}- >- <Show- when={- props.entity.type === 'channel' &&- props.entity.channelType === ChannelTypeEnum.DirectMessage- }- fallback={- <Dynamic- component={getIcon().icon}- class={`flex size-full ${getIcon().foreground}`}- />- }- >- <DirectMessageIcon entity={props.entity} />- </Show>- </div>- </div>- <EntityTitle />- </div>- {/* Date and user - top right on mobile, end on desktop */}- <div class="row-1 ml-2 @md:ml-4 self-center min-w-0 col-3 @max-md/uList:col-auto @max-md/uList:row-auto @max-md/uList:ml-0 @max-md/uList:mt-1 @max-md/uList:self-start @max-md/uList:w-full">- <div class="flex flex-row items-center justify-end gap-2 min-w-0 @max-md/uList:justify-start @max-md/uList:flex-wrap">- <Show when={sharedData()}>- {(shared) => (- <Tooltip- tooltip={`${shared().ownerDisplayName()} shared with you`}- >- <SharedBadge ownerId={shared().ownerId} />- </Tooltip>- )}- </Show>- <Show when={matches(props.entity, isProjectContainedEntity)}>- {(entity) => (- <EntityProject- entity={entity()}- onClick={props.onClick}- onPointerdown={props.onPointerDown}- />- )}- </Show>- <Show when={isTaskEntity(props.entity) && properties().length > 0}>- <KeyPropertiesGrid- properties={properties()}- entityId={props.entity.id}- entityType="TASK"- />- </Show>- <Show when={props.timestamp ?? props.entity.updatedAt}>- {(date) => (- <span class="w-[8ch] text-right shrink-0 whitespace-nowrap text-xs touch:mobile-width:text-sm font-mono uppercase text-ink-extra-muted @max-md/uList:hidden">- {createFormattedDate(date())}- </span>- )}- </Show>- <Show- when={- (props.selected.active || hoveredComponentId() === id) &&- props.onClickRowAction- }- >- <div class="absolute top-1 right-1 items-center flex @max-sm/uList:hidden">- <Tooltip- tooltip={- <LabelAndHotKey- label="Mark as done"- hotkeyToken={TOKENS.entity.action.markDone}- />- }- >- <button- class="bg-panel flex items-center justify-center size-8 border border-edge-muted hover:bg-accent hover:text-panel"- onClick={(e) => {- e.stopPropagation();- props.onClickRowAction?.(props.entity, 'done');- }}- ref={setActionButtonRef}- data-blocks-navigation- >- <CheckIcon class="w-4 h-4 pointer-events-none" />- </button>- </Tooltip>- </div>- </Show>- </div>- </div>- {/* Content Hits from Search */}- <Show when={isSearch() && contentHitData().length > 0}>- <div class="relative row-2 col-2 col-end-4 pb-2 @max-md/split:row-auto @max-md/split:col-auto @max-md/split:w-full @max-md/split:mt-1">- <CollapsibleList- items={contentHitData()}- threadBorder- visibleCount={1}- >- {(data, index, count) => (- <ContentHitRow- allData={contentHitData()}- data={data}- onClick={(e, location) => {- props.onClick?.({- type: 'entity',- entity: props.entity,- event: e,- location,- });- }}- index={index}- count={count}- />- )}- </CollapsibleList>- </div>- </Show>- {/* Notifications (stacked by type) */}- <Show- when={- props.showUnrollNotifications &&- hasNotifications() &&- contentHitData().length === 0- }- >- <div class="relative col-2 col-end-4 pb-2 @max-md/uList:col-auto @max-md/uList:w-full @max-md/uList:mt-1">- <CollapsibleList items={stackedNotificationsGroups()} threadBorder>- {(group) => (- <StackedNotificationRenderer- group={group}- onClick={props.onClickNotification}- onClickStacked={(args) => {- // Navigate to the most recent notification in the stack- const mostRecent = getMostRecentNotification(args.group);- props.onClickNotification?.({- type: 'entity',- entity: {- ...args.entity,- notification: mostRecent,- // Attach all notifications in the group for bulk operations- stackedNotifications: getAllNotificationsFromGroup(- args.group- ),- },- event: args.event,- });- }}- entity={props.entity}- />- )}- </CollapsibleList>- </div>- </Show>- </div>- </div>- );-}--function DirectMessageIcon(props: { entity: EntityData }) {- const userId = useUserId();- const participantId = () =>- props.entity.type === 'channel'- ? (props.entity.participantIds ?? [])- .filter((id) => id !== userId())- .at(0)- : undefined;-- const Fallback = () => <EntityIcon targetType="direct_message" />;-- return (- <div class="bg-panel size-5 rounded-full p-[2px]">- <Show when={participantId()} fallback={<Fallback />}>- {(id) => <UserIcon id={id()} isDeleted={false} size="xs" />}- </Show>- </div>- );-}--function EntityProjectPathDisplay(props: { name: string; path: string[] }) {- const [displayPath, setDisplayPath] = createSignal<string | undefined>(- props.name- );- const [truncated, setTruncated] = createSignal(false);-- const fullPath = createMemo(() => props.path.join(' / '));-- const getDisplayPath = (): { name: string; truncated: boolean } => {- const fullPathString = fullPath();- const maxLength = 30;-- if (fullPathString.length <= maxLength) {- return { name: fullPathString, truncated: false };- }-- if (props.path.length === 1) {- return {- name: props.path[0].slice(0, maxLength - 3) + '...',- truncated: true,- };- }-- if (props.path.length === 2) {- const first = props.path[0];- const last = props.path[props.path.length - 1];- const combined = `${first} / ... / ${last}`;- if (combined.length <= maxLength) {- return { name: combined, truncated: true };- }- return {- name: `${first.slice(0, 10)}... / ${last.slice(0, 10)}...`,- truncated: true,- };- }-- const first = props.path[0];- const last = props.path[props.path.length - 1];- return { name: `${first} / ... / ${last}`, truncated: true };- };-- createDeferred(() => {- const { name, truncated } = getDisplayPath();- setDisplayPath(name);- setTruncated(truncated);- });-- return (- <Tooltip tooltip={fullPath()} hide={!truncated()}>- <div class="truncate">{displayPath()}</div>- </Tooltip>- );-}--function EntityProject(props: {- entity: ProjectContainedEntity;- onClick?: EntityClickHandler<ProjectEntity>;- onPointerdown?: EntityPointerDownHandler<ProjectEntity>;-}) {- const projectQuery = createProjectQuery(props.entity.projectId);- const openProjectEntity: (args: {- event: Parameters<JSX.EventHandler<HTMLDivElement, MouseEvent>>[number];- eventHandler?: EntityClickHandler<ProjectEntity>;- }) => void = ({ event, eventHandler }) => {- if (!projectQuery.isSuccess) return;-- const data = projectQuery.data;- const projectEntity: ProjectEntity = {- type: 'project',- id: data.id,- name: data.name,- ownerId: data.owner,- updatedAt: data.updatedAt,- };- eventHandler?.({- type: 'entity-project-path',- entity: props.entity as unknown as ProjectEntity,- projectEntity,- event,- });- };-- return (- <div- data-blocks-navigation={projectQuery.isSuccess ? 'true' : undefined}- onClick={(e) =>- openProjectEntity({ event: e, eventHandler: props.onClick })- }- onPointerDown={(e) =>- openProjectEntity({ event: e, eventHandler: props.onPointerdown })- }- class="flex gap-1 items-center text-xs touch:mobile-width:text-sm text-ink-extra-muted min-w-0"- classList={{- 'hover:text-accent': projectQuery.isSuccess,- }}- >- <svg- class="shrink-0"- xmlns="http://www.w3.org/2000/svg"- width="16"- height="16"- viewBox="0 0 18 18"- fill="none"- >- <path- d="M15.1875 5.0625H9.18773L7.23727 3.6C7.04225 3.45449 6.80558 3.3756 6.56227 3.375H2.8125C2.51413 3.375 2.22798 3.49353 2.017 3.7045C1.80603 3.91548 1.6875 4.20163 1.6875 4.5V14.0625C1.6875 14.3609 1.80603 14.647 2.017 14.858C2.22798 15.069 2.51413 15.1875 2.8125 15.1875H15.2501C15.5317 15.1871 15.8018 15.0751 16.0009 14.8759C16.2001 14.6768 16.3121 14.4067 16.3125 14.1251V6.1875C16.3125 5.88913 16.194 5.60298 15.983 5.392C15.772 5.18103 15.4859 5.0625 15.1875 5.0625ZM15.1875 14.0625H2.8125V4.5H6.56227L8.6625 6.075C8.75987 6.14803 8.87829 6.1875 9 6.1875H15.1875V14.0625Z"- fill="currentColor"- />- </svg>- <Suspense- fallback={<div class="h-3 w-10 bg-ink-placeholder animate-pulse" />}- >- <Show when={projectQuery.data}>- {(data) => (- <EntityProjectPathDisplay name={data().name} path={data().path} />- )}- </Show>- </Suspense>- </div>- );-}--const trackKeydownDuringTask = () => {- // data captured during shift tab keydown event, data is only kept for that browser task then emptied- const [keydownDataDuringTask, setKeydownDataDuringTask] = createSignal<{- pressedShiftTab: boolean;- pressedAnyKey: boolean;- target: HTMLElement | null;- }>({- pressedShiftTab: false,- pressedAnyKey: false,- target: null,- });- const hasShiftTabbedEvent = (e: KeyboardEvent) => {- if (!(e.key === 'Tab' && e.shiftKey)) return;- setKeydownDataDuringTask({- pressedAnyKey: !!e.key,- pressedShiftTab: true,- target: e.target as HTMLElement,- });-- setTimeout(() => {- setKeydownDataDuringTask({- pressedShiftTab: false,- target: null,- pressedAnyKey: false,- });- });- };-- onMount(() => {- document.addEventListener('keydown', hasShiftTabbedEvent);-- onCleanup(() => {- document.removeEventListener('keydown', hasShiftTabbedEvent);- });- });-- return { keydownDataDuringTask };-};--const startOfDay = (d: Date) =>- new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();--const createFormattedDate = (timestamp: number) => {- const ts = timestamp < 1e12 ? timestamp * 1000 : timestamp;-- const date = new Date(ts);- const now = new Date();-- const dateDay = startOfDay(date);- const todayDay = startOfDay(now);-- // Today → show time- if (dateDay === todayDay) {- return date.toLocaleTimeString('en-US', {- hour: '2-digit',- minute: '2-digit',- });- }-- // Same year → show Month Day- if (date.getFullYear() === now.getFullYear()) {- return date.toLocaleDateString('en-US', {- month: 'short',- day: 'numeric',- });- }-- // Older → show numeric date- return date.toLocaleDateString('en-US', {- month: 'numeric',- day: 'numeric',- year: '2-digit',- });-};diff --git a/js/app/packages/macro-entity/src/components/EntityWrapper.tsx b/js/app/packages/macro-entity/src/components/EntityWrapper.tsxdeleted file mode 100644index 529ff2489b..0000000000--- a/js/app/packages/macro-entity/src/components/EntityWrapper.tsx+++ /dev/null@@ -1,23 +0,0 @@-import { type JSX, type ParentProps, splitProps } from 'solid-js';--interface EntityWrapperProps extends JSX.HTMLAttributes<HTMLDivElement> {- selected?: boolean;-}--export function EntityWrapper(props: ParentProps<EntityWrapperProps>) {- const [localProps, divProps] = splitProps(props, [- 'selected',- 'class',- 'classList',- ]);-- return (- <div- class="flex min-h-19 w-full flex-row items-center gap-1 px-1 transition-all hover:bg-hover transition-none sm:min-h-13.5 sm:gap-2.5 sm:px-5 suppress-css-brackets"- classList={{ 'bracket bg-hover': localProps.selected }}- {...divProps}- >- {divProps.children}- </div>- );-}diff --git a/js/app/packages/macro-entity/src/components/Filter.tsx b/js/app/packages/macro-entity/src/components/Filter.tsxdeleted file mode 100644index 79de77f275..0000000000--- a/js/app/packages/macro-entity/src/components/Filter.tsx+++ /dev/null@@ -1,263 +0,0 @@-import { DeprecatedTextButton } from '@core/component/DeprecatedTextButton';-import { DropdownMenu } from '@kobalte/core/dropdown-menu';-import FunnelIcon from '@phosphor-icons/core/assets/regular/funnel-simple.svg';-import FunnelClearIcon from '@phosphor-icons/core/assets/regular/funnel-simple-x.svg';-import {- DropdownMenuContent,- MenuItem,- MenuSeparator,-} from 'core/component/Menu';-import {- createMemo,- createSignal,- type ParentProps,- Show,- splitProps,-} from 'solid-js';-import { createStore } from 'solid-js/store';-import {- DEFAULT_FILTERS as defaultFilters,- FilterContext,- type FilterState,- useFilterContext,-} from '../contexts/filter';-import { useUserId } from '../queries/auth';-import type { EntityData } from '../types/entity';-import type { Filters } from '../types/filter';-import type { WithNotification } from '../types/notification';-import { containsAllSameValues } from '../utils/arrayCompare';-import { FileTypeFilter } from './filters/FileType';-import { OwnerTypeFilter } from './filters/OwnerType';-import { UnreadSwitch } from './Unread';--export function Filter(props: ParentProps<FilterContext>) {- const [localProps, filterContext] = splitProps(props, ['children']);-- return (- <FilterContext.Provider value={filterContext}>- <div class="flex flex-row items-center gap-2 px-2.5 py-1">- {localProps.children}- </div>- </FilterContext.Provider>- );-}--type CreateFilterContext = {- [key in keyof Filters]?: FilterState[key] | Filters[key];-};-export function createFilter<- T extends WithNotification<EntityData> = WithNotification<EntityData>,->(context: CreateFilterContext = {}) {- const filterContext = Object.entries(context).reduce<FilterContext>(- (acc, [key, value]) => {- if (Array.isArray(value) && typeof value[0] === 'function') {- // @ts-expect-error- acc[key] = value;- // @ts-expect-error- acc.defaultFilters[key] = value[0]();- } else {- // @ts-expect-error- acc[key] = createSignal(value);- // @ts-expect-error- acc.defaultFilters[key] = value;- }-- return acc;- },- { defaultFilters }- );- const [filterState, setFilterState] = createStore<FilterContext>({- ...filterContext,- });-- const resetFilter = () => setFilterState({ ...filterContext });-- const fileTypeFilter = createMemo(- () => {- const filter = filterState.fileTypeFilter?.[0]();- if (!filter) return [];-- return filter;- },- [],- { equals: containsAllSameValues }- );-- const userId = useUserId();-- const filterFn = createMemo(- () => {- const unreadFilter = filterState.unreadFilter?.[0]();- const ownerType = filterState.ownerTypeFilter?.[0]();- const fileFilterArray = fileTypeFilter();- return (entity: T) => {- if (unreadFilter)- return !!entity.notifications && entity.notifications().length > 0;-- if (ownerType && ownerType !== 'all') {- return (ownerType === 'me') === (entity.ownerId === userId());- }- if (fileFilterArray.length > 0) {- if (- entity.type === 'document' &&- entity.fileType &&- !fileFilterArray.includes(entity.fileType.toLowerCase())- )- return false;- }-- return true;- };- },- undefined,- { equals: false }- );-- const FilterComponent = (props: ParentProps) => {- return (- <Filter {...filterState}>- <Show when={filterState.unreadFilter}>- {(unreadFilter) => (- <UnreadSwitch- checked={unreadFilter()[0]()}- onChange={unreadFilter()[1]}- />- )}- </Show>- <Show when={filterState.fileTypeFilter}>- <FileTypeFilter />- </Show>- <Show when={filterState.ownerTypeFilter}>- <OwnerTypeFilter />- </Show>- {props.children}- <FilterOptions onReset={resetFilter}>- <Show when={filterContext.unreadFilter}>- {(contextFilter) => (- <MenuItem- text="Unread Filter"- selectorType="checkbox"- checked={!!filterState.unreadFilter}- onClick={() => {- const unreadFilter = filterState.unreadFilter;- if (unreadFilter) {- unreadFilter[1](false);- setFilterState('unreadFilter', undefined);- } else {- contextFilter()[1](true);- setFilterState('unreadFilter', contextFilter());- }- }}- closeOnSelect- />- )}- </Show>- <Show when={filterContext.fileTypeFilter}>- {(contextFilter) => (- <MenuItem- text="FileType Filter"- selectorType="checkbox"- checked={!!filterState.fileTypeFilter}- onClick={() => {- const fileTypeFilter = filterState.fileTypeFilter;- if (fileTypeFilter) {- setFilterState('fileTypeFilter', undefined);- } else {- setFilterState('fileTypeFilter', contextFilter());- }- }}- closeOnSelect- />- )}- </Show>- <Show when={filterContext.ownerTypeFilter}>- {(contextFilter) => (- <MenuItem- text="OwnerType Filter"- selectorType="checkbox"- checked={!!filterState.ownerTypeFilter}- onClick={() => {- const ownerTypeFilter = filterState.ownerTypeFilter;- if (ownerTypeFilter) {- setFilterState('ownerTypeFilter', undefined);- } else {- setFilterState('ownerTypeFilter', contextFilter());- }- }}- closeOnSelect- />- )}- </Show>- </FilterOptions>- </Filter>- );- };-- return {- FilterComponent,- filterState,- filterFn,- resetFilter,- };-}--interface FilterOptionsProps extends ParentProps {- onReset?: () => void;-}-export function FilterOptions(props: FilterOptionsProps) {- const filterContext = useFilterContext();- const filterKeys = createMemo<Array<keyof FilterState>>(- () =>- Object.keys(filterContext).filter(- (key) => key !== 'defaultFilters'- ) as Array<keyof FilterState>,- [],- { equals: containsAllSameValues }- );- const hasFilters = createMemo(() =>- filterKeys().some((key) => {- const currentFilterValue = filterContext[key]?.[0]();- const defaultValue = filterContext.defaultFilters[key];- if (Array.isArray(currentFilterValue) && Array.isArray(defaultValue)) {- return !containsAllSameValues(currentFilterValue, defaultValue);- }-- return currentFilterValue !== defaultValue;- })- );-- const [isOpen, setIsOpen] = createSignal(false);- return (- <DropdownMenu open={isOpen()} onOpenChange={setIsOpen}>- <DropdownMenu.Trigger- class="flex items-center justify-end gap-2 px-1 align-middle"- as="div"- >- <DeprecatedTextButton- theme="clear"- icon={FunnelIcon}- class={`${hasFilters() ? 'text-accent-ink!' : ''} ${isOpen() ? 'bg-active!' : ''}`}- tabIndex={-1}- text="Filter"- />- </DropdownMenu.Trigger>- <DropdownMenuContent>- <MenuItem- text="Reset To Default"- icon={FunnelClearIcon}- disabled={!hasFilters()}- onClick={() => {- props.onReset?.();- filterKeys().forEach((key) =>- // @ts-expect-error- filterContext[key]?.[1](filterContext.defaultFilters[key])- );- }}- closeOnSelect- />- <MenuSeparator />- {props.children}- </DropdownMenuContent>- </DropdownMenu>- );-}diff --git a/js/app/packages/macro-entity/src/components/InlineEntity.tsx b/js/app/packages/macro-entity/src/components/InlineEntity.tsxdeleted file mode 100644index 398a85342d..0000000000--- a/js/app/packages/macro-entity/src/components/InlineEntity.tsx+++ /dev/null@@ -1,19 +0,0 @@-import { createMemo } from 'solid-js';-import type { EntityData } from '../types/entity';-import { getEntityIconConfig } from '@core/component/EntityIcon';-import { cn } from '@ui/utils/classname';-import { Dynamic } from 'solid-js/web';--export function InlineEntity(props: { entity: EntityData }) {- const iconConfig = createMemo(() => getEntityIconConfig(props.entity));-- return (- <div class="flex items-center gap-2 min-w-0">- <Dynamic- component={iconConfig().icon}- class={cn('flex shrink-0 size-[1em]', iconConfig().foreground)}- />- <span class="truncate">{props.entity.name}</span>- </div>- );-}diff --git a/js/app/packages/macro-entity/src/components/ProjectDrop.tsx b/js/app/packages/macro-entity/src/components/ProjectDrop.tsxdeleted file mode 100644index 2b1301aed2..0000000000--- a/js/app/packages/macro-entity/src/components/ProjectDrop.tsx+++ /dev/null@@ -1,164 +0,0 @@-import type { EntityDragData, EntityDragEvent } from '../types/drag';-import {- createCopyDssEntityMutation,- createMoveToProjectDssEntityMutation,-} from '../queries/dss';-import { createDroppable, useDragDropContext } from '@thisbeyond/solid-dnd';-import { createMemo, Show } from 'solid-js';-import { FileDropOverlay } from '@core/component/FileDropOverlay';--export type ProjectDropData = {- dropType: 'project';- id: string;-};--export const ProjectDropOverlay = (props: {- projectId: string;- name?: string;- splitId?: string;-}) => {- const [state, { onDragEnd }] = useDragDropContext() ?? [- undefined,- {- onDragEnd: () => {},- },- ];-- const moveMutation = createMoveToProjectDssEntityMutation();- const copyMutation = createCopyDssEntityMutation();-- onDragEnd((event: EntityDragEvent) => {- const droppable = event.droppable;- if (- !droppable ||- droppable.id !== props.projectId ||- droppable.data?.dropType !== 'project'- )- return;-- const dropData = droppable.data as ProjectDropData;- const targetProjectId = dropData.id;-- const draggable = event.draggable;- if (!draggable?.data) return;-- const entityData = draggable.data;-- // ignore drag and drop within same split- if (entityData.splitId === props.splitId) return;-- switch (entityData.operation()) {- case 'copy':- if (entityData.type !== 'document' && entityData.type !== 'chat') {- console.error('copy only supported for document and chat');- return;- }- copyMutation.mutate(- {- entity: entityData,- },- {- onSuccess: (id: string) => {- // TODO: add project id as an argument to backend copy endpoint- // so we don't need multiple calls to copy and move- moveMutation.mutate({- entity: {- ...entityData,- id,- },- project: {- id: targetProjectId,- },- });- },- }- );- break;- case 'move':- if (- entityData.type !== 'document' &&- entityData.type !== 'chat' &&- entityData.type !== 'project'- ) {- console.error('move only supported for document, chat, and project');- return;- }- moveMutation.mutate({- entity: entityData,- project: {- id: targetProjectId,- },- });- break;- }- });-- const entityDragData = createMemo(() => {- const draggable = state?.active.draggable;- if (!draggable) return;- const dragData = draggable.data;- if (!dragData || dragData.dragType !== 'entity') return;- return dragData as EntityDragData;- });-- const showProjectOverlay = createMemo(() => {- const dragData = entityDragData();- if (!dragData) return false;-- const entityType = dragData.type;- if (- entityType !== 'document' &&- entityType !== 'chat' &&- entityType !== 'project'- ) {- return false;- }-- // Don't show overlay if dragging within the same split- if (props.splitId && dragData.splitId === props.splitId) return false;-- const activeDroppable = state?.active.droppable;-- if (!activeDroppable || activeDroppable.data.dropType !== 'project')- return false;-- // Show overlay if dropping on this project or an entity within it- if (activeDroppable.id === props.projectId) return true;-- return false;- });-- const dropActionText = createMemo(() => {- switch (entityDragData()?.operation?.()) {- case 'copy':- return 'Copy to this folder';- case 'move':- return 'Move to this folder';- }- });-- return (- <>- <Show when={props.projectId} keyed>- {(projectId) => {- const data: ProjectDropData = {- dropType: 'project',- id: projectId,- };- const droppable = createDroppable(props.projectId, data);- false && droppable;-- return (- <div- use:droppable- class="absolute inset-0 pointer-events-none z-10"- />- );- }}- </Show>- <Show when={showProjectOverlay()}>- <FileDropOverlay>{dropActionText()}</FileDropOverlay>- </Show>- </>- );-};diff --git a/js/app/packages/macro-entity/src/components/Provider.tsx b/js/app/packages/macro-entity/src/components/Provider.tsxindex fc4248f2de..32a41defa1 100644--- a/js/app/packages/macro-entity/src/components/Provider.tsx+++ b/js/app/packages/macro-entity/src/components/Provider.tsx@@ -3,7 +3,7 @@ import { SolidQueryDevtools } from '@tanstack/solid-query-devtools';import { LOCAL_ONLY } from '@core/constant/featureFlags';import { Show, type ParentProps } from 'solid-js';import { fetchApiToken } from '../queries/auth';-import { queryClient } from '../queries/client';+import { queryClient } from '@queries/client';import { queryKeys } from '../queries/key';import { RemoveInstructionsMdFromHistorySideEffect } from '@queries/history/history';diff --git a/js/app/packages/macro-entity/src/components/Sort.tsx b/js/app/packages/macro-entity/src/components/Sort.tsxdeleted file mode 100644index 9d3c89da5f..0000000000--- a/js/app/packages/macro-entity/src/components/Sort.tsx+++ /dev/null@@ -1,521 +0,0 @@-import { ENABLE_PROPERTY_SORT } from '@core/constant/featureFlags';-import ClockIcon from '@phosphor-icons/core/assets/regular/clock.svg';-import MagnifyingGlassIcon from '@phosphor-icons/core/assets/regular/magnifying-glass.svg';-import SortAscendingIcon from '@phosphor-icons/core/assets/regular/sort-ascending.svg';-import SortDescendingIcon from '@phosphor-icons/core/assets/regular/sort-descending.svg';-import XIcon from '@phosphor-icons/core/assets/regular/x.svg';-import { propertiesServiceClient } from '@service-properties/client';-import { SegmentedControl } from 'core/component/FormControls/SegmentControls';-import { ToggleButton } from 'core/component/FormControls/ToggleButton';-import type { PropertyDefinitionDomain } from 'core/component/Properties/types';-import {- PropertyDataTypeIcon,- toPropertyDefinitionDomain,-} from 'core/component/Properties/utils';-import { isErr } from 'core/util/maybeResult';-import {- type Accessor,- type Component,- createEffect,- createMemo,- createSignal,- For,- type JSX,- on,- onCleanup,- onMount,- Show,- type Signal,-} from 'solid-js';-import type { EntityComparator, EntityData } from '../types/entity';-import type { WithNotification } from '../types/notification';--export function Sort() {- return <SegmentedControl list={['Notified', 'Updated', 'Viewed']} />;-}--type PropertySortSearchProps = {- onSelectProperty?: (property: PropertyDefinitionDomain) => void;-};--function PropertySortSearch(props: PropertySortSearchProps) {- const [availableProperties, setAvailableProperties] = createSignal<- PropertyDefinitionDomain[]- >([]);- const [searchQuery, setSearchQuery] = createSignal('');- const [isDropdownOpen, setIsDropdownOpen] = createSignal(false);-- let searchInputRef!: HTMLInputElement;- let dropdownRef!: HTMLDivElement;- let containerRef!: HTMLDivElement;-- const fetchAvailableProperties = async () => {- try {- const result = await propertiesServiceClient.listProperties({- scope: 'all',- include_options: false,- });-- if (isErr(result)) {- return;- }-- const [, data] = result;- const properties = Array.isArray(data) ? data : [];- const normalizedProperties = properties.map((item) => {- const definition = 'definition' in item ? item.definition : item;- return toPropertyDefinitionDomain(definition);- });- setAvailableProperties(normalizedProperties);- } catch (_apiError) {- // Silently fail- }- };-- // Filter to only sortable properties- const sortableProperties = createMemo(() => {- return availableProperties().filter((property) => {- if (- ['BOOLEAN', 'ENTITY', 'LINK', 'STRING'].includes(property.valueType) ||- property.isMultiSelect- )- return false;- return true;- });- });-- const filteredProperties = createMemo(() => {- const query = searchQuery().toLowerCase().trim();- const properties = sortableProperties();-- if (!query) return properties;-- return properties.filter((property) => {- const name = property.displayName.toLowerCase();- return name.includes(query);- });- });-- const handleSelectProperty = (property: PropertyDefinitionDomain) => {- props.onSelectProperty?.(property);- setSearchQuery('');- setIsDropdownOpen(false);- };-- onMount(() => {- fetchAvailableProperties();- });-- // Close dropdown when clicking outside- createEffect(() => {- if (!isDropdownOpen()) return;-- const handleClickOutside = (event: MouseEvent) => {- const target = event.target;- if (!(target instanceof Node)) return;-- const isInsideContainer = containerRef?.contains(target);- const isInsideDropdown = dropdownRef?.contains(target);-- if (!isInsideContainer && !isInsideDropdown) {- setIsDropdownOpen(false);- }- };-- document.addEventListener('mousedown', handleClickOutside);- onCleanup(() => {- document.removeEventListener('mousedown', handleClickOutside);- });- });-- return (- <div ref={containerRef} class="relative w-full">- <MagnifyingGlassIcon class="absolute left-2 top-1/2 -translate-y-1/2 size-3.5 text-ink-muted pointer-events-none" />- <input- ref={searchInputRef}- type="text"- value={searchQuery()}- onInput={(e) => {- setSearchQuery(e.currentTarget.value);- setIsDropdownOpen(true);- }}- onFocus={() => setIsDropdownOpen(true)}- placeholder="Search Properties..."- class="w-full pl-7 pr-2 py-1 font-mono text-xs text-ink placeholder-ink-muted bg-transparent border border-edge focus:ring-2 focus:ring-accent/50 focus:border-accent"- />- <Show when={isDropdownOpen()}>- <div- ref={dropdownRef}- class="absolute left-0 right-0 top-full mt-1 z-[100] border border-edge bg-menu shadow-lg max-h-48 overflow-y-auto font-mono"- >- <Show- when={filteredProperties().length > 0}- fallback={- <div class="px-3 py-2 text-xs text-ink-muted text-center">- No sortable properties found- </div>- }- >- <For each={filteredProperties()}>- {(property) => (- <button- type="button"- onMouseDown={(e) => {- e.preventDefault();- e.stopPropagation();- handleSelectProperty(property);- }}- class="w-full px-2 py-1.5 text-xs text-ink hover:bg-hover flex items-center gap-2 text-left"- >- <PropertyDataTypeIcon property={property} />- <span class="truncate flex-1">{property.displayName}</span>- </button>- )}- </For>- </Show>- </div>- </Show>- </div>- );-}--type DefaultSortType = 'important' | 'updatedAt' | 'viewedAt' | 'frecency';--export type SortOption<- T extends EntityData,- S extends string = DefaultSortType,-> = {- value: S;- label: string;- sortFn: EntityComparator<T>;-};--export function notifiedSortFn<T extends WithNotification<EntityData>>(- a: T,- b: T-) {- const aNotification = a.notifications?.()[0];- const bNotification = b.notifications?.()[0];-- if (aNotification && bNotification) {- return bNotification.createdAt - aNotification.createdAt;- } else if (aNotification) {- return -1;- } else if (bNotification) {- return 1;- }-- return sortByUpdatedAt(a, b);-}--export function sortByCreatedAt<T extends EntityData>(a: T, b: T): number {- return (b.createdAt ?? 0) - (a.createdAt ?? 0);-}--export function sortByUpdatedAt<T extends EntityData>(a: T, b: T) {- return (b.updatedAt ?? 0) - (a.updatedAt ?? 0);-}--export function sortByViewedAt<T extends EntityData>(a: T, b: T) {- return (b.viewedAt ?? 0) - (a.viewedAt ?? 0);-}--export function sortByFrecencyScore<T extends EntityData>(a: T, b: T): number {- return (b.frecencyScore ?? 0) - (a.frecencyScore ?? 0);-}--export const defaultSortOptions: SortOption<WithNotification<EntityData>>[] = [- { value: 'important', label: 'Important', sortFn: notifiedSortFn },- { value: 'updatedAt', label: 'Updated', sortFn: sortByUpdatedAt },- { value: 'viewedAt', label: 'Viewed', sortFn: sortByViewedAt },-];--type InferSortFn<Options extends SortOption<any, string>[]> =- Options[number] extends SortOption<infer U, string>- ? EntityComparator<U>- : never;--type SortComponent = (props: {- size?: 'SM' | 'Base';- onSelectSystemSort?: () => void;-}) => JSX.Element;--export function createSort(): {- sortFn: Accessor<EntityComparator<WithNotification<EntityData>>>;- SortComponent: SortComponent;-};-export function createSort<Options extends SortOption<EntityData>[]>(context: {- sortOptions: Options;- defaultSortOption: Options[number]['value'];-}): {- sortFn: Accessor<InferSortFn<Options>>;- SortComponent: SortComponent;-};-export function createSort<T extends EntityData, S extends string>(context: {- sortOptions: SortOption<T, S>[];- defaultSortOption: S;-}): {- sortFn: Accessor<InferSortFn<SortOption<T, S>[]>>;- SortComponent: SortComponent;-};-export function createSort<T extends EntityData, S extends string>(context: {- sortOptions: SortOption<T, S>[];- defaultSortOption?: S;- sortTypeSignal: Signal<S>;- propertyIdSignal?: Signal<string | null>;- sortOrderSignal?: Signal<'ascending' | 'descending'>;- disabled?: Accessor<boolean>;-}): {- sortFn: Accessor<InferSortFn<SortOption<T, S>[]>>;- SortComponent: SortComponent;-};-export function createSort<- Options extends SortOption<any, string>[],->(context?: {- sortOptions: Options;- defaultSortOption?: Options[number]['value'];- sortTypeSignal?: Signal<Options[number]['value']>;- propertyIdSignal?: Signal<string | null>;- sortOrderSignal?: Signal<'ascending' | 'descending'>;- disabled?: Accessor<boolean>;-}): {- sortFn: Accessor<InferSortFn<Options>>;- SortComponent: SortComponent;-} {- const { sortOptions, defaultSortOption, disabled } = {- sortOptions: defaultSortOptions,- defaultSortOption: 'important',- ...context,- };- const [sortType, setSortType] =- context?.sortTypeSignal ??- createSignal<Options[number]['value']>(defaultSortOption);-- // Use external signals if provided, otherwise local state- const [localSortOrder, setLocalSortOrder] = createSignal<- 'ascending' | 'descending'- >('descending');- const [sortOrder, setSortOrder] = context?.sortOrderSignal ?? [- localSortOrder,- setLocalSortOrder,- ];-- const [localPropertyId, setLocalPropertyId] = createSignal<string | null>(- null- );- const [propertyId, setPropertyId] = context?.propertyIdSignal ?? [- localPropertyId,- setLocalPropertyId,- ];-- const sortFn = createMemo<InferSortFn<Options>>(() => {- // If property sort is active, return no-op (backend handles sorting)- if (propertyId()) {- return ((_, __) => 0) as InferSortFn<Options>;- }-- const sortBy = sortType();- const sortFn = sortOptions.find(- (option) => option.value === sortBy- )?.sortFn;- if (!sortFn) {- console.error(`Sort function for ${sortBy} not found`);- return ((_, __) => 0) as InferSortFn<Options>;- }-- return sortFn as InferSortFn<Options>;- });-- // Track the full property object for display (fetched when needed)- const [selectedProperty, setSelectedProperty] =- createSignal<PropertyDefinitionDomain | null>(null);-- // Fetch property details when propertyId changes- createEffect(- on(propertyId, (id) => {- if (id) {- // Fetch property details- propertiesServiceClient- .listProperties({ scope: 'all', include_options: false })- .then((result) => {- if (isErr(result)) return;- const [, data] = result;- const properties = Array.isArray(data) ? data : [];- const normalizedProperties = properties.map((item) => {- const definition = 'definition' in item ? item.definition : item;- return toPropertyDefinitionDomain(definition);- });- const property = normalizedProperties.find((p) => p.id === id);- if (property) {- setSelectedProperty(property);- }- });- } else {- setSelectedProperty(null);- }- })- );-- const isSortedByProperty = createMemo(() => {- return propertyId() !== null;- });-- const handleSelectProperty = (property: PropertyDefinitionDomain) => {- setPropertyId(property.id);- setSelectedProperty(property);- };-- const handleClearProperty = () => {- setPropertyId(null);- setSelectedProperty(null);- setSortOrder('descending');- setSortType(defaultSortOption);- };-- const handleSelectSystemSort = (value: string) => {- setPropertyId(null);- setSelectedProperty(null);- setSortOrder('descending');- setSortType(value);- };-- type SystemSortPillsProps = {- sortType: Accessor<string>;- onSelect: (value: string) => void;- disabled?: Accessor<boolean>;- isSortedByProperty: Accessor<boolean>;- };-- const SystemSortPills: Component<SystemSortPillsProps> = (props) => {- const pillClass =- 'inline-flex w-fit min-h-[24px] items-center gap-1.5 px-2 py-1 text-xs font-mono border cursor-pointer';-- const isSelected = (value: string) =>- !props.isSortedByProperty() && props.sortType() === value;-- return (- <div class="flex flex-wrap gap-1">- <button- type="button"- onClick={() => props.onSelect('viewed_at')}- disabled={props.disabled?.()}- class={pillClass}- classList={{- 'bg-ink text-panel border-ink': isSelected('viewed_at'),- 'bg-transparent text-ink border-edge hover:bg-hover':- !isSelected('viewed_at'),- }}- >- <ClockIcon class="size-3.5" />- Viewed- </button>- <button- type="button"- onClick={() => props.onSelect('updated_at')}- disabled={props.disabled?.()}- class={pillClass}- classList={{- 'bg-ink text-panel border-ink': isSelected('updated_at'),- 'bg-transparent text-ink border-edge hover:bg-hover':- !isSelected('updated_at'),- }}- >- <ClockIcon class="size-3.5" />- Updated- </button>- <button- type="button"- onClick={() => props.onSelect('created_at')}- disabled={props.disabled?.()}- class={pillClass}- classList={{- 'bg-ink text-panel border-ink': isSelected('created_at'),- 'bg-transparent text-ink border-edge hover:bg-hover':- !isSelected('created_at'),- }}- >- <ClockIcon class="size-3.5" />- Created- </button>- </div>- );- };-- const SortComponent: SortComponent = (props) => (- <div class="flex flex-col gap-2">- <span class="text-xs font-medium">Sort</span>- <SystemSortPills- sortType={sortType}- onSelect={(value) => {- handleSelectSystemSort(value);- props.onSelectSystemSort?.();- }}- disabled={disabled}- isSortedByProperty={isSortedByProperty}- />- <Show when={ENABLE_PROPERTY_SORT}>- <Show- when={isSortedByProperty()}- fallback={- <div class="w-full">- <PropertySortSearch onSelectProperty={handleSelectProperty} />- </div>- }- >- <div class="flex items-center gap-2">- <div class="flex max-w-[200px]">- <Show- when={selectedProperty()}- fallback={- <div class="flex items-center gap-1.5 px-2 py-1 text-xs font-mono border border-failure bg-failure/10 text-failure min-w-0 overflow-hidden">- <span class="truncate">Property not found</span>- </div>- }- >- <div class="flex items-center gap-1.5 px-2 py-1 text-xs font-mono border bg-ink text-panel border-ink min-w-0 overflow-hidden">- <PropertyDataTypeIcon- property={selectedProperty()!}- class="text-panel size-3.5 shrink-0"- />- <span class="truncate">- {selectedProperty()?.displayName}- </span>- </div>- </Show>- <button- type="button"- onClick={handleClearProperty}- class="px-1 bg-edge-muted hover:opacity-70 transition-opacity shrink-0 border border-ink"- >- <XIcon class="size-3.5" />- </button>- </div>- <Show when={selectedProperty()}>- <div class="flex shrink-0">- <ToggleButton- size="SM"- pressed={sortOrder() === 'descending'}- onChange={() => setSortOrder('descending')}- >- <SortDescendingIcon class="size-4" />- </ToggleButton>- <ToggleButton- size="SM"- pressed={sortOrder() === 'ascending'}- onChange={() => setSortOrder('ascending')}- >- <SortAscendingIcon class="size-4" />- </ToggleButton>- </div>- </Show>- </div>- </Show>- </Show>- </div>- );-- return {- SortComponent,- sortFn,- };-}diff --git a/js/app/packages/macro-entity/src/components/Unread.tsx b/js/app/packages/macro-entity/src/components/Unread.tsxdeleted file mode 100644index b7079b91c2..0000000000--- a/js/app/packages/macro-entity/src/components/Unread.tsx+++ /dev/null@@ -1,66 +0,0 @@-import FilledCircle from '@phosphor-icons/core/assets/fill/circle-fill.svg';-import Circle from '@phosphor-icons/core/assets/regular/circle.svg';-import { ToggleSwitch } from 'core/component/FormControls/ToggleSwitch';-import { type JSX, Show } from 'solid-js';--export function UnreadIndicator(props: { active?: boolean }) {- return (- <div class="flex min-w-5 items-center justify-center">- <FilledCircle- classList={{- 'flex size-3 text-accent': true,- invisible: !props.active,- }}- />- </div>- );-}--export function UnreadCheckbox(props: {- checked?: boolean;- onChange?: JSX.ChangeEventHandlerUnion<HTMLInputElement, Event>;-}) {- return (- <div- class="hover-transition-bg relative flex h-8 flex-row items-center gap-1 px-2.5 py-1 hover:bg-hover has-checked:bg-accent/20 sm:gap-2.5"- tabindex={1}- >- <div class="flex min-w-5 items-center justify-center">- <Show- when={props.checked}- fallback={<Circle class="flex size-3 text-accent" />}- >- <FilledCircle class="flex size-3 text-accent" />- </Show>- </div>- <label class="has-checked:text-accent">- <input- class="group absolute inset-0 appearance-none"- type="checkbox"- checked={props.checked}- onChange={props.onChange}- />- Unread- </label>- </div>- );-}--export function UnreadSwitch(props: {- checked?: boolean;- onChange?: (isChecked: boolean) => void;-}) {- return (- <div class="flex h-8 flex-row items-center gap-1 px-2.5 py-1 sm:gap-2.5">- <div class="flex min-w-5 items-center justify-center">- <Show- when={props.checked}- fallback={<Circle class="flex size-3 text-accent" />}- >- <FilledCircle class="flex size-3 text-accent" />- </Show>- </div>- <ToggleSwitch {...props} label="Unread" />- </div>- );-}diff --git a/js/app/packages/macro-entity/src/components/filters/FileType.tsx b/js/app/packages/macro-entity/src/components/filters/FileType.tsxdeleted file mode 100644index cf0b1db349..0000000000--- a/js/app/packages/macro-entity/src/components/filters/FileType.tsx+++ /dev/null@@ -1,81 +0,0 @@-import { DeprecatedTextButton } from '@core/component/DeprecatedTextButton';-import { DropdownMenu } from '@kobalte/core/dropdown-menu';-import FileIcon from '@phosphor-icons/core/assets/regular/file-magnifying-glass.svg';-import FunnelClearIcon from '@phosphor-icons/core/assets/regular/funnel-simple-x.svg';-import {- DropdownMenuContent,- MenuItem,- MenuSeparator,-} from 'core/component/Menu';-import { createMemo, createSelector, createSignal, For } from 'solid-js';-import { useFilterContext } from '../../contexts/filter';-import { containsAllSameValues } from '../../utils/arrayCompare';--const FILE_TYPE_FILTERS = ['MD', 'PDF', 'Canvas'];--export function FileTypeFilter() {- const filterContext = useFilterContext();- const fileTypeFilter = filterContext.fileTypeFilter;-- const hasFilters = createMemo(() => {- const filter = fileTypeFilter?.[0]();- if (!filter) return false;-- return !containsAllSameValues(- filter,- filterContext.defaultFilters.fileTypeFilter- );- });-- const fileTypeSelector = createSelector(- fileTypeFilter?.[0] ?? (() => []),- (fileType: string, filter) => filter.includes(fileType.toLowerCase())- );-- const toggleFileTypeFilter = (fileType: string) => {- fileTypeFilter?.[1](- fileTypeSelector(fileType)- ? fileTypeFilter?.[0]().filter((f) => f !== fileType.toLowerCase())- : [...fileTypeFilter[0](), fileType.toLowerCase()]- );- };-- const [isOpen, setIsOpen] = createSignal(false);-- return (- <DropdownMenu open={isOpen()} onOpenChange={setIsOpen}>- <DropdownMenu.Trigger- class="flex items-center justify-end gap-2 px-1 align-middle"- as="div"- >- <DeprecatedTextButton- theme="clear"- icon={FileIcon}- class={`${hasFilters() ? 'text-accent-ink!' : ''} ${isOpen() ? 'bg-active!' : ''}`}- tabIndex={-1}- text="FileType"- />- </DropdownMenu.Trigger>- <DropdownMenuContent>- <MenuItem- text="Clear"- icon={FunnelClearIcon}- disabled={!hasFilters()}- onClick={() => fileTypeFilter?.[1]([])}- closeOnSelect- />- <MenuSeparator />- <For each={FILE_TYPE_FILTERS}>- {(fileType) => (- <MenuItem- text={fileType}- selectorType="checkbox"- checked={fileTypeSelector(fileType)}- onClick={() => toggleFileTypeFilter(fileType)}- />- )}- </For>- </DropdownMenuContent>- </DropdownMenu>- );-}diff --git a/js/app/packages/macro-entity/src/components/filters/OwnerType.tsx b/js/app/packages/macro-entity/src/components/filters/OwnerType.tsxdeleted file mode 100644index ff826b748f..0000000000--- a/js/app/packages/macro-entity/src/components/filters/OwnerType.tsx+++ /dev/null@@ -1,78 +0,0 @@-import { DeprecatedTextButton } from '@core/component/DeprecatedTextButton';-import { DropdownMenu } from '@kobalte/core/dropdown-menu';-import FunnelClearIcon from '@phosphor-icons/core/assets/regular/funnel-simple-x.svg';-import UserSwitchIcon from '@phosphor-icons/core/assets/regular/user-switch.svg';-import {- DropdownMenuContent,- MenuItem,- MenuSeparator,-} from 'core/component/Menu';-import { createMemo, createSignal } from 'solid-js';-import { useFilterContext } from '../../contexts/filter';--export function OwnerTypeFilter() {- const filterContext = useFilterContext();- const ownerTypeFilter = filterContext.ownerTypeFilter;-- const hasFilters = createMemo(() => {- const filter = ownerTypeFilter?.[0]();- if (!filter) return false;-- return filter !== filterContext.defaultFilters.ownerTypeFilter;- });-- const [isOpen, setIsOpen] = createSignal(false);-- return (- <DropdownMenu open={isOpen()} onOpenChange={setIsOpen}>- <DropdownMenu.Trigger- class="flex items-center justify-end gap-2 px-1 align-middle"- as="div"- >- <DeprecatedTextButton- theme="clear"- icon={UserSwitchIcon}- class={`${hasFilters() ? 'text-accent-ink!' : ''} ${isOpen() ? 'bg-active!' : ''}`}- tabIndex={-1}- text="OwnerType"- />- </DropdownMenu.Trigger>- <DropdownMenuContent>- <MenuItem- text="Reset"- icon={FunnelClearIcon}- disabled={!hasFilters()}- onClick={() => ownerTypeFilter?.[1]('all')}- closeOnSelect- />- <MenuSeparator />- <DropdownMenu.RadioGroup- value={ownerTypeFilter?.[0]() ?? 'all'}- onChange={(value) => ownerTypeFilter?.[1](value)}- >- <MenuItem- text="All"- selectorType="radio"- value="all"- groupValue={ownerTypeFilter?.[0]() ?? 'all'}- closeOnSelect- />- <MenuItem- text="Me"- selectorType="radio"- value="me"- groupValue={ownerTypeFilter?.[0]() ?? 'all'}- closeOnSelect- />- <MenuItem- text="Others"- selectorType="radio"- value="other"- groupValue={ownerTypeFilter?.[0]() ?? 'all'}- closeOnSelect- />- </DropdownMenu.RadioGroup>- </DropdownMenuContent>- </DropdownMenu>- );-}diff --git a/js/app/packages/macro-entity/src/constants/classStrings.tsx b/js/app/packages/macro-entity/src/constants/classStrings.tsxdeleted file mode 100644index 2d160fcce5..0000000000--- a/js/app/packages/macro-entity/src/constants/classStrings.tsx+++ /dev/null@@ -1,5 +0,0 @@-export const LIST_WRAPPER =- 'flex size-full flex-col gap-0 overflow-y-auto overflow-x-clip';--export const ITEM_WRAPPER =- 'flex min-h-19 w-full flex-row items-center gap-1 px-1 transition-all hover:bg-hover transition-none sm:min-h-13.5 sm:gap-2.5 sm:px-5 focus-bracket-within suppress-css-brackets focus-within:bg-hover';diff --git a/js/app/packages/macro-entity/src/contexts/filter.ts b/js/app/packages/macro-entity/src/contexts/filter.tsdeleted file mode 100644index d24aa30f25..0000000000--- a/js/app/packages/macro-entity/src/contexts/filter.ts+++ /dev/null@@ -1,30 +0,0 @@-import { createContext, type Signal, useContext } from 'solid-js';-import type { Filters } from '../types/filter';--export type FilterState = {- [key in keyof Filters]?: Signal<Filters[key]>;-};--export interface FilterContext extends FilterState {- defaultFilters: Filters;-}--export const DEFAULT_FILTERS = {- unreadFilter: false,- sortBy: 'updated',- fileTypeFilter: [],- ownerTypeFilter: 'all',-} as const satisfies Filters;--export const FilterContext = createContext<FilterContext>({- defaultFilters: DEFAULT_FILTERS,-});--export function useFilterContext() {- const context = useContext(FilterContext);- if (!context) {- throw new Error('cannot find filter context');- }-- return context;-}diff --git a/js/app/packages/macro-entity/src/index.css b/js/app/packages/macro-entity/src/index.cssdeleted file mode 100644index aae7806481..0000000000--- a/js/app/packages/macro-entity/src/index.css+++ /dev/null@@ -1,25 +0,0 @@-.entity-layout {- display: grid;- grid-template-rows: 1fr 2fr;- grid-template-areas:- "header-left header-right"- "content content";-}--@media (width >= 40rem) {- .entity-layout {- grid-template-areas: "header-left content header-right";- }-}--.entity-layout .header-left {- grid-area: header-left;-}--.entity-layout .header-right {- grid-area: header-right;-}--.entity-layout .content {- grid-area: content;-}\ No newline at end of filediff --git a/js/app/packages/macro-entity/src/index.tsx b/js/app/packages/macro-entity/src/index.tsxindex 155655c74a..860ba8ee1d 100644--- a/js/app/packages/macro-entity/src/index.tsx+++ b/js/app/packages/macro-entity/src/index.tsx@@ -1,27 +1,14 @@-export { Entity } from './components/Entity';-export { EntityWrapper } from './components/EntityWrapper';-export { createFilter } from './components/Filter';export { Provider } from './components/Provider';-export * from './components/Sort';-export { UnreadIndicator } from './components/Unread';-export { useQueryClient } from './queries/client';export {- createChatsInfiniteQuery,- createDeleteDssItemMutation,- createDssInfiniteQuery,createMoveToProjectDssEntityMutation,- createCopyDssEntityMutation,- optimisticUpdateDssItemViewedAt,+ createBulkDeleteDssItemsMutation,+ createBulkCopyDssEntityMutation,+ createBulkMoveToProjectDssEntityMutation,} from './queries/dss';export { createEmailsInfiniteQuery } from './queries/email';-export type { EntityInfiniteQuery, EntityQuery } from './queries/entity';export { queryKeys } from './queries/key';-export { enhanceWithNotifications } from './queries/notification';-export * from './queries/search';-export { createEmailSource, type EmailSource, useEmails } from './source/email';-export type * from './types/drag';-export * from './types/entity';-export * from './types/notification';-export * from './types/search';-export * from './utils/filter';-export { composeFilters, createFilterComposer } from './utils/filter';+export {+ createRenameDssEntityMutation,+ createBulkRenameDssEntityMutation,+ useWaitChatRename,+} from './queries/rename';diff --git a/js/app/packages/macro-entity/src/queries/auth.ts b/js/app/packages/macro-entity/src/queries/auth.tsindex b1516a51d3..18d7f65c38 100644--- a/js/app/packages/macro-entity/src/queries/auth.ts+++ b/js/app/packages/macro-entity/src/queries/auth.ts@@ -1,5 +1,4 @@import type { MacroApiTokenResponse } from '@service-auth/generated/schemas/macroApiTokenResponse';-import type { ProfilePictures } from '@service-auth/generated/schemas/profilePictures';import {queryOptions,type SolidQueryOptions,@@ -8,13 +7,11 @@ import {import { SERVER_HOSTS } from 'core/constant/servers';import { fetchWithToken } from 'core/util/fetchWithToken';import { isOk } from 'core/util/maybeResult';-import { platformFetch } from 'core/util/platformFetch';-import { createMemo } from 'solid-js';import { queryKeys } from './key';const authHost = SERVER_HOSTS['auth-service'];-export class FetchDocumentsError extends Error {+class FetchDocumentsError extends Error {constructor(message: string,public readonly response: Response,@@ -91,75 +88,3 @@ export function createApiTokenQueryOptions(): ApiTokenQueryOptions {export function createApiTokenQuery() {return useQuery(() => createApiTokenQueryOptions());}--export function useUserId() {- const authQuery = createApiTokenQuery();- return createMemo<string | undefined>(() => {- if (!authQuery.isSuccess) return;-- const token = authQuery.data;- if (!token) return;-- const parts = token.split('.');- if (parts.length !== 3) return;- try {- const payload = parts[1];- if (!payload) return;-- const parsedPayload = JSON.parse(- atob(payload.replace(/-/g, '+').replace(/_/g, '/'))- );-- return parsedPayload.macro_user_id;- } catch {- return;- }- });-}--const fetchProfilePictures = async (- user_id_list: Array<string>,- apiToken?: string-) => {- const credentials: RequestInit = apiToken- ? {- headers: {- Authorization: `Bearer ${apiToken}`,- 'Content-Type': 'application/json',- },- }- : {- headers: {- 'Content-Type': 'application/json',- },- credentials: 'include',- };- const response = await platformFetch(`${authHost}/user/profile_pictures`, {- method: 'POST',- body: JSON.stringify({ user_id_list }),- ...credentials,- });-- await handleFetchResponse(response, 'Failed to fetch profile picture');-- const { pictures }: ProfilePictures = await response.json();- if (pictures.length === 0)- throw new Error(`No profile picture found for ${user_id_list}`);-- return pictures;-};--export function createProfilePictureQuery(id: string) {- const authQuery = createApiTokenQuery();- return useQuery(() => ({- queryKey: queryKeys.auth.profilePicture({ id }),- queryFn: () =>- withApiTokenRetry(authQuery, (apiToken) =>- fetchProfilePictures([id], apiToken)- ),- select: (pictures) => pictures.at(0),- enabled: authQuery.isSuccess,- retry: 1,- retryOnMount: false,- }));-}diff --git a/js/app/packages/macro-entity/src/queries/client.ts b/js/app/packages/macro-entity/src/queries/client.tsdeleted file mode 100644index b8dea596b5..0000000000--- a/js/app/packages/macro-entity/src/queries/client.ts+++ /dev/null@@ -1,7 +0,0 @@-import { queryClient as _queryClient } from '@queries/client';--export const queryClient = _queryClient;--export function useQueryClient() {- return queryClient;-}diff --git a/js/app/packages/macro-entity/src/queries/dss.ts b/js/app/packages/macro-entity/src/queries/dss.tsindex 4996bc8e78..b35ba61e90 100644--- a/js/app/packages/macro-entity/src/queries/dss.ts+++ b/js/app/packages/macro-entity/src/queries/dss.ts@@ -3,42 +3,10 @@ import {deleteItem,moveToFolder,} from '@core/component/FileList/itemOperations';-import { itemToSafeName } from '@core/constant/allBlocks';import { toast } from '@core/component/Toast/Toast';-import type {- PostItemsSoupParams,- PostSoupRequest,- SoupApiSort,- SoupDocument,-} from '@service-storage/generated/schemas';-import type { GetItemsSoupParams } from '@service-storage/generated/schemas/getItemsSoupParams';-import type { SoupPage } from '@service-storage/generated/schemas/soupPage';-import { useInstructionsMdIdQuery } from '@queries/storage/instructions-md';-import {- hashKey,- type InfiniteData,- type UseQueryResult,- useInfiniteQuery,- useMutation,-} from '@tanstack/solid-query';-import { SERVER_HOSTS } from 'core/constant/servers';-import { platformFetch } from 'core/util/platformFetch';-import type { Accessor } from 'solid-js';-import type {- ChannelEntity,- ChatEntity,- DocumentEntity,- EmailEntity,- EntityData,- ProjectEntity,-} from '../types/entity';-import {- createApiTokenQuery,- handleFetchResponse,- withApiTokenRetry,-} from './auth';-import { queryClient } from './client';-import { type DssQueryKey, dssQueryKeyHashFn, queryKeys } from './key';+import { useMutation } from '@tanstack/solid-query';+import type { EntityData } from '@entity';+import { queryClient } from '@queries/client';import { soupKeys } from '@queries/soup/keys';import {removeSoupEntities,@@ -46,364 +14,8 @@ import {getSoupEntityById,optimisticUpdateSoupEntity,invalidateSoupEntity,- refetchSoupEntity,} from '@queries/soup/cache';-const resolveDocumentEntityName = (- entity: DocumentEntity | SoupDocument-): string => {- return itemToSafeName({- type: 'document',- name: entity.name,- fileType: entity.fileType,- subType:- entity.subType === null || entity.subType === undefined- ? null- : {- type: entity.subType.type,- is_completed: entity.subType.is_completed,- },- });-};--const fetchPaginatedDocumentsGet = async ({- apiToken,- ...params-}: GetItemsSoupParams & {- apiToken?: string;-}) => {- if (!apiToken) throw new Error('No API token provided');- const Authorization = `Bearer ${apiToken}`;-- const url = new URL(`${SERVER_HOSTS['document-storage-service']}/items/soup`);- Object.entries(params).forEach(([key, value]) => {- if (value) url.searchParams.set(key, value.toString());- });-- const response = await platformFetch(url, { headers: { Authorization } });- await handleFetchResponse(response, 'Failed to fetch documents');-- const result: SoupPage = await response.json();- return result;-};--const fetchPaginatedDocumentsPost = async ({- apiToken,- params,- requestBody,- signal,-}: {- apiToken?: string;- requestBody?: PostSoupRequest;- params?: PostItemsSoupParams;- signal?: AbortSignal;-}) => {- if (!apiToken) throw new Error('No API token provided');- const Authorization = `Bearer ${apiToken}`;-- const url = new URL(`${SERVER_HOSTS['document-storage-service']}/items/soup`);- if (params) {- Object.entries(params).forEach(([key, value]) => {- if (value) url.searchParams.set(key, value.toString());- });- }-- const response = await platformFetch(url, {- headers: { Authorization, 'Content-Type': 'application/json' },- method: 'POST',- body: requestBody ? JSON.stringify(requestBody) : undefined,- signal,- });-- await handleFetchResponse(response, 'Failed to fetch documents');-- const result: SoupPage = await response.json();- return result;-};--export function createDssInfiniteQuery(- initialParams?: Accessor<PostItemsSoupParams>,- getRequestBody?: Accessor<PostSoupRequest>,- options?: {- disabled?: Accessor<boolean>;- }-) {- const params = () => {- const argParams = initialParams?.();- let limit = 100;- let sort_method;- let emailView;-- if (getRequestBody) {- const body = getRequestBody();- if (body?.limit) {- limit = body.limit;- }- if (body?.sort_method) {- sort_method = body.sort_method;- }- if (body?.emailView) {- emailView = body.emailView;- }- }-- return {- ...argParams,- limit,- sort_method,- emailView,- };- };-- const authQuery = createApiTokenQuery();- const instructionsIdQuery = useInstructionsMdIdQuery();-- return useInfiniteQuery(() => {- const requestBody = getRequestBody?.();- // Include all filters in query key so query refetches when any filter changes- const documentFilters = requestBody?.document_filters;- const projectFilters = requestBody?.project_filters;- const chatFilters = requestBody?.chat_filters;- const emailFilters = requestBody?.email_filters;- const channelFilters = requestBody?.channel_filters;-- const queryKey = queryKeys.dss({- infinite: true,- ...params(),- documentFilters: documentFilters- ? JSON.stringify(documentFilters)- : undefined,- projectFilters: projectFilters- ? JSON.stringify(projectFilters)- : undefined,- chatFilters: chatFilters ? JSON.stringify(chatFilters) : undefined,- emailFilters: emailFilters ? JSON.stringify(emailFilters) : undefined,- channelFilters: channelFilters- ? JSON.stringify(channelFilters)- : undefined,- });-- return {- queryKey,- queryKeyHashFn: hashKey,- queryFn: ({ pageParam, signal }) =>- withApiTokenRetry(authQuery, (apiToken) =>- fetchPaginatedDocumentsPost({- apiToken,- requestBody,- params: { cursor: pageParam.cursor },- signal,- })- ),- initialPageParam: params(),- getNextPageParam: ({ next_cursor: cursor }) =>- cursor ? { ...params(), cursor } : undefined,- select: (data) => selectData(data, { instructionsIdQuery }),- enabled: authQuery.isSuccess && !options?.disabled?.(),- };- });-}--const selectData: (- data: InfiniteData<- SoupPage,- {- limit: number;- expand?: boolean;- sort_method?: SoupApiSort;- cursor?: string;- }- >,- options: {- instructionsIdQuery: UseQueryResult<string | null | undefined, Error>;- }-) => (- | DocumentEntity- | ChatEntity- | ProjectEntity- | EmailEntity- | ChannelEntity-)[] = (data, options) => {- return data.pages.flatMap(({ items }) =>- items- .filter(- (item) =>- item.tag !== 'document' ||- !options.instructionsIdQuery.isSuccess ||- item.data.id !== options.instructionsIdQuery.data- )- .map(- (- item- ):- | DocumentEntity- | ChatEntity- | ProjectEntity- | EmailEntity- | ChannelEntity => {- if (item.tag === 'chat') {- return {- ...item.data,- type: item.tag,- name: item.data.name || 'New Chat',- frecencyScore: item.frecency_score,- viewedAt: item.data.viewedAt ?? undefined,- projectId: item.data.projectId ?? undefined,- };- }-- if (item.tag === 'project') {- return {- createdAt: item.data.createdAt,- updatedAt: item.data.updatedAt,- id: item.data.id,- ownerId: item.data.ownerId,- frecencyScore: item.frecency_score,- viewedAt: item.data.viewedAt ?? undefined,- projectId: item.data.parentId ?? undefined,- type: item.tag,- name: item.data.name || 'New Project',- };- }-- if (item.tag === 'emailThread') {- const participants = item.data.participants?.map((p) => ({- email: p.emailAddress ?? '',- name: p.name ?? '',- }));-- return {- ...item.data,- senderEmail: item.data.senderEmail ?? undefined,- senderName: item.data.senderName ?? undefined,- snippet: item.data.snippet ?? undefined,- done: !item.data.inboxVisible,- type: 'email',- name: item.data.name || 'Email Thread',- frecencyScore: item.frecency_score,- viewedAt: item.data.viewedAt ?? undefined,- participants,- };- }-- if (item.tag === 'channel') {- const out: ChannelEntity = {- type: 'channel',- id: item.data.channel.id,- name: item.data.channel.name || 'Unknown Channel',- channelType: item.data.channel.channel_type,- ownerId: item.data.channel.owner_id,- frecencyScore: item.frecency_score ?? 0,- updatedAt: Date.parse(item.data.channel.updated_at),- createdAt: Date.parse(item.data.channel.created_at),- participantIds: item.data.participants.map((p) => p.user_id),- viewedAt: item.data.viewed_at- ? Date.parse(item.data.viewed_at)- : item.data.interacted_at- ? Date.parse(item.data.interacted_at)- : undefined,- latestMessage: item.data.latest_non_thread_message- ? {- content: item.data.latest_non_thread_message.content,- senderId: item.data.latest_non_thread_message.sender_id,- createdAt: Date.parse(- item.data.latest_non_thread_message.created_at- ),- }- : undefined,- };- return out;- }-- return {- ...item.data,- type: item.tag,- frecencyScore: item.frecency_score,- viewedAt: item.data.viewedAt ?? undefined,- fileType: item.data.fileType ?? undefined,- projectId: item.data.projectId ?? undefined,- subType:- item.data.subType === null || item.data.subType === undefined- ? undefined- : {- type: item.data.subType.type as 'task',- is_completed: item.data.subType.is_completed,- },- name: resolveDocumentEntityName(item.data),- };- }- )- );-};--export function createChatsInfiniteQuery(- args?: GetItemsSoupParams | Accessor<GetItemsSoupParams>-) {- const params = () => {- const argParams = typeof args === 'function' ? args() : args;- const limit =- argParams?.limit && argParams.limit > 0 && argParams.limit <= 500- ? argParams.limit- : 500;- return {- ...argParams,- limit,- };- };-- const authQuery = createApiTokenQuery();- return useInfiniteQuery(() => ({- queryKey: queryKeys.chat({ infinite: true, ...params() }),- queryHash: dssQueryKeyHashFn(- queryKeys.chat({ infinite: true, ...params() }) as DssQueryKey- ),- queryFn: ({ pageParam }) =>- withApiTokenRetry(authQuery, (apiToken) =>- fetchPaginatedDocumentsGet({ apiToken, ...pageParam })- ),- initialPageParam: params(),- getNextPageParam: ({ next_cursor: cursor }) =>- cursor ? { ...params(), cursor } : undefined,- select: (data) =>- data.pages.flatMap(({ items }) =>- items- .filter((item) => item.tag === 'chat')- .filter((item) => !item.data.isPersistent)- .map(- (item): ChatEntity => ({- ...item.data,- type: item.tag,- frecencyScore: item.frecency_score,- viewedAt: item.data.viewedAt ?? undefined,- projectId: item.data.projectId ?? undefined,- })- )- ),- enabled: authQuery.isSuccess,- }));-}--export function createDeleteDssItemMutation() {- return useMutation(() => ({- mutationFn: async ({ id, type }: EntityData) => {- const success = await deleteItem({ id, itemType: type });- return { success };- },- onMutate: async ({ id }: EntityData) => {- return removeSoupEntities(new Set([id]));- },- onSettled: (data, error, entity, context) => {- if (data?.success === false || error) {- context?.rollback();- console.error(`Failed to delete dss item ${entity}`, data, error);- toast.failure('Failed to delete item');- }-- invalidateSoupEntity(entity.id);- },- }));-}-export function createBulkDeleteDssItemsMutation() {const isUnsupportedEntity = (entity: EntityData) => {const type = entity.type;@@ -502,45 +114,6 @@ export function createMoveToProjectDssEntityMutation() {}));}-export function createCopyDssEntityMutation() {- return useMutation(() => ({- mutationFn: async ({- entity: { id, type, name },- }: {- entity: EntityData & { type: 'document' | 'chat' };- }) => {- const newId = await copyItem({- itemType: type,- id,- name,- });-- if (!newId) {- throw new Error(`Failed to copy ${type} with id ${id}`);- }-- return newId;- },- onMutate: async () => {- queryClient.cancelQueries({- queryKey: soupKeys.items._def,- });- // For copy operations, we don't need optimistic updates since we're creating a new item- // The new item will be added when the mutation completes and queries are invalidated- },- onSettled: (data, error, { entity: { id, type } }) => {- if (error) {- console.error(`Failed to copy dss item ${id}`, data, error);- toast.failure('Failed to copy item');- }- if (data) {- refetchSoupEntity(data, type as 'document' | 'chat');- }- queryClient.invalidateQueries({ queryKey: ['entity'] });- },- }));-}-export function createBulkCopyDssEntityMutation() {// Only support chat + document, same as single-copy versionconst isUnsupportedEntity = (entity: EntityData) => {@@ -670,28 +243,3 @@ export function createBulkMoveToProjectDssEntityMutation() {},}));}--/**- * Optimistically update the viewedAt timestamp for a DSS item.- * Updates the item across all DSS queries if it exists.- */-export function optimisticUpdateDssItemViewedAt(itemId: string) {- const current = getSoupEntityById(itemId);- if (!current) return;-- const now = new Date();-- if (current.tag === 'channel') {- optimisticUpdateSoupEntity({- tag: 'channel',- data: { channel: { id: itemId }, viewed_at: now.toISOString() },- frecency_score: current.frecency_score,- });- } else {- optimisticUpdateSoupEntity({- tag: current.tag,- data: { id: itemId, viewedAt: now.getTime() },- frecency_score: current.frecency_score,- });- }-}diff --git a/js/app/packages/macro-entity/src/queries/email.ts b/js/app/packages/macro-entity/src/queries/email.tsindex d31312cdc3..574b791622 100644--- a/js/app/packages/macro-entity/src/queries/email.ts+++ b/js/app/packages/macro-entity/src/queries/email.ts@@ -5,7 +5,7 @@ import { useInfiniteQuery } from '@tanstack/solid-query';import { SERVER_HOSTS } from 'core/constant/servers';import { platformFetch } from 'core/util/platformFetch';import { type Accessor, createMemo } from 'solid-js';-import type { EmailEntity } from '../types/entity';+import type { EmailEntity } from '@entity';import {createApiTokenQuery,handleFetchResponse,@@ -13,7 +13,7 @@ import {} from './auth';import { queryKeys } from './key';-export type FetchPaginatedEmailsParams = PreviewsInboxCursorParams & {+type FetchPaginatedEmailsParams = PreviewsInboxCursorParams & {// path parameterview: PreviewViewStandardLabel;};diff --git a/js/app/packages/macro-entity/src/queries/entity.ts b/js/app/packages/macro-entity/src/queries/entity.tsdeleted file mode 100644index 5082210e24..0000000000--- a/js/app/packages/macro-entity/src/queries/entity.ts+++ /dev/null@@ -1,30 +0,0 @@-import type {- UseInfiniteQueryResult,- UseQueryResult,-} from '@tanstack/solid-query';-import type { EntityData } from '../types/entity';--export type EntityQueryOperations = {- filter: boolean;- search: boolean;-};--export type EntityQueryWithOperations<- T extends EntityData,- Q extends EntityQuery | EntityInfiniteQuery<T> =- | EntityQuery- | EntityInfiniteQuery<T>,-> = {- query: Q;- operations?: Partial<EntityQueryOperations>;-};--export type EntityQuery = UseQueryResult<EntityData[]>;--export type EntityInfiniteQuery<T extends EntityData = EntityData> =- UseInfiniteQueryResult<T[]>;--export type EntityList<T extends EntityData = EntityData> = {- data: T[];- operations?: EntityQueryOperations;-};diff --git a/js/app/packages/macro-entity/src/queries/key.ts b/js/app/packages/macro-entity/src/queries/key.tsindex 846749f876..fe041ac8cc 100644--- a/js/app/packages/macro-entity/src/queries/key.ts+++ b/js/app/packages/macro-entity/src/queries/key.ts@@ -1,6 +1,5 @@import type { PreviewViewStandardLabel } from '@service-email/generated/schemas';import type { SearchArgs } from '@service-search/client';-import { hashKey } from '@tanstack/solid-query';const BASE_AUTH = ['auth'];@@ -59,21 +58,3 @@ export const queryKeys = {],search: (args: SearchKeyOptions) => [...BASE_ENTITY.search, { ...args }],};--export type DssQueryKey = [- (typeof BASE_ENTITY.dss)[0],- (typeof BASE_ENTITY.dss)[1],- { type: 'chat' | 'document' } & InfiniteKeyOptions,- ...string[],-];-export function dssQueryKeyHashFn(queryKey: DssQueryKey): string {- try {- const [, , { type: _, ...options }, ...additional] = queryKey;- const hashedKey = hashKey([options, ...additional]);-- return `dss-entity|${hashedKey}`;- } catch (error) {- console.error('Error hashing DSS query key', error);- return hashKey(queryKey);- }-}diff --git a/js/app/packages/macro-entity/src/queries/notification.ts b/js/app/packages/macro-entity/src/queries/notification.tsdeleted file mode 100644index 249a554323..0000000000--- a/js/app/packages/macro-entity/src/queries/notification.ts+++ /dev/null@@ -1,41 +0,0 @@-import { useEntityNotificationsQuery } from '@queries/notification/user-notifications';-import { createEffect } from 'solid-js';-import { unwrap } from 'solid-js/store';-import type { EntityData } from '../types/entity';-import type { WithNotification } from '../types/notification';--/**- * Enhances an entity with its notifications as an accessor.- */-export function enhanceWithNotifications<T extends EntityData>(- entity: T-): WithNotification<T> {- const eventItemId = entity.id;- const limit = 100;-- const notificationsQuery = useEntityNotificationsQuery({- eventItemId: () => eventItemId,- limit,- });-- createEffect(() => {- if (notificationsQuery.isSuccess) {- if (notificationsQuery.hasNextPage && !notificationsQuery.isFetching) {- notificationsQuery.fetchNextPage();- }- }- });-- return Object.assign(unwrap(entity), {- get notifications() {- return () =>- notificationsQuery.isSuccess- ? notificationsQuery.data- .filter(({ viewedAt }) => !viewedAt)- .toSorted((a, b) => {- return b.createdAt - a.createdAt;- })- : [];- },- });-}diff --git a/js/app/packages/macro-entity/src/queries/project.ts b/js/app/packages/macro-entity/src/queries/project.tsdeleted file mode 100644index ea96dd0cc5..0000000000--- a/js/app/packages/macro-entity/src/queries/project.ts+++ /dev/null@@ -1,95 +0,0 @@-import { SERVER_HOSTS } from '@core/constant/servers';-import type { WithRequired } from '@core/util/withRequired';-import type {- GetBatchProjectPreviewResponse,- ProjectPreviewData,-} from '@service-storage/generated/schemas';-import { useQuery } from '@tanstack/solid-query';-import {- type ChatEntity,- type DocumentEntity,- type EntityData,- getEntityProjectId,- type ProjectEntity,-} from '../types/entity';-import {- createApiTokenQuery,- handleFetchResponse,- withApiTokenRetry,-} from './auth';-import { queryKeys } from './key';--export type ProjectContainedEntity = WithRequired<- Extract<EntityData, DocumentEntity | ChatEntity | ProjectEntity>,- 'projectId'->;--export const isProjectContainedEntity = (- entity: EntityData-): entity is ProjectContainedEntity => {- return getEntityProjectId(entity) !== false;-};--const fetchProjectData = async (- projectId: string,- apiToken?: string-): Promise<ProjectPreviewData> => {- if (!apiToken) throw new Error('No API token provided');-- const dssHost = SERVER_HOSTS['document-storage-service'];- const url = `${dssHost}/projects/preview`;-- const response = await fetch(url, {- method: 'POST',- headers: {- Authorization: `Bearer ${apiToken}`,- 'Content-Type': 'application/json',- },- body: JSON.stringify({- projectIds: [projectId],- }),- });-- await handleFetchResponse(response, 'Failed to fetch project');-- const json = (await response.json()) as GetBatchProjectPreviewResponse;-- const projectPreview = json.previews.find(- (preview) => preview.id === projectId- );-- if (!projectPreview) {- throw new Error(`Project ${projectId} not found in preview response`);- }-- if (projectPreview.access === 'no_access') {- throw new Error(`No access to folder ${projectId}`);- }-- if (projectPreview.access === 'does_not_exist') {- throw new Error(`Project ${projectId} does not exist`);- }-- return projectPreview;-};--export function createProjectQuery(projectId: string) {- const authQuery = createApiTokenQuery();-- const projectQuery = useQuery(() => {- return {- queryKey: queryKeys.project({- projectId,- }),- queryFn: () =>- withApiTokenRetry(authQuery, (apiToken) =>- fetchProjectData(projectId, apiToken)- ),- enabled: authQuery.isSuccess && !!projectId,- gcTime: 1000 * 60 * 10, // 10 minutes- staleTime: 1000 * 60 * 5, // 5 minutes- };- });-- return projectQuery;-}diff --git a/js/app/packages/macro-entity/src/queries/rename.ts b/js/app/packages/macro-entity/src/queries/rename.tsindex 0b6f3137d7..2f2dd15699 100644--- a/js/app/packages/macro-entity/src/queries/rename.ts+++ b/js/app/packages/macro-entity/src/queries/rename.ts@@ -7,7 +7,7 @@ import {import { type MutationCallbacks, withCallbacks } from '@queries/utils';import type { ItemType } from '@service-storage/client';import { ChannelTypeEnum } from '@service-comms/client';-import type { EntityData } from '../types/entity';+import type { EntityData } from '@entity';import { useMutation } from '@tanstack/solid-query';import { toast } from '@core/component/Toast/Toast';import { setPreviewName } from '@queries/preview';diff --git a/js/app/packages/macro-entity/src/queries/search.ts b/js/app/packages/macro-entity/src/queries/search.tsdeleted file mode 100644index df5a5fe52d..0000000000--- a/js/app/packages/macro-entity/src/queries/search.ts+++ /dev/null@@ -1,420 +0,0 @@-import { useChannelsContext } from '@core/context/channels';-import { blockNameToDefaultFile } from '@core/constant/allBlocks';-import { ENABLE_SEARCH_SERVICE } from '@core/constant/featureFlags';-import { emailToId } from '@core/user';-import { isErr } from '@core/util/maybeResult';-import {- extractSearchSnippet,- extractSearchTerms,- mergeAdjacentMacroEmTags,- truncateSearchMatch,-} from '@core/util/searchHighlight';-import type { ChannelType } from '@service-comms/generated/models';-import { type SearchArgs, searchClient } from '@service-search/client';-import type {- ChannelSearchResult,- ChatMessageSearchResult,- DocumentSearchResult,- EmailSearchResult,- ProjectSearchResult,- UnifiedSearchResponseItem,-} from '@service-search/generated/models';-import { useHistoryQuery } from '@queries/history/history';-import { useInfiniteQuery } from '@tanstack/solid-query';-import { type Accessor, createMemo } from 'solid-js';-import type { EntityData } from '../types/entity';-import type { ContentHitData, SearchData, WithSearch } from '../types/search';-import type { EntityInfiniteQuery } from './entity';-import { queryKeys } from './key';--const SEARCH_MATCH_LENGTH = 60;--type InnerSearchResult =- | DocumentSearchResult- | EmailSearchResult- | ChatMessageSearchResult- | ChannelSearchResult- | ProjectSearchResult;--type TypedInnerSearchResult =- | { results: InnerSearchResult[]; type?: undefined }- | { results: DocumentSearchResult[]; type: 'pdf'; searchQuery: string }- | { results: DocumentSearchResult[]; type: 'md' }- | { results: ChannelSearchResult[]; type: 'channel' }- | { results: EmailSearchResult[]; type: 'email' };--export const isSearchEntity = <T extends EntityData>(- entity: T-): entity is WithSearch<T> => 'search' in entity;--const getSearchData = (data: TypedInnerSearchResult): SearchData => {- let contentHitData: ContentHitData[] = [];-- switch (data.type) {- case 'channel': {- contentHitData = data.results.flatMap((r) => {- const isContentHit = !!r.message_id;- if (!isContentHit) return [];-- const contents = r.highlight.content ?? [];- return contents.map((content) => ({- type: 'channel' as const,- id: r.message_id!,- content: truncateSearchMatch(- mergeAdjacentMacroEmTags(content),- SEARCH_MATCH_LENGTH- ),- senderId: r.sender_id!,- sentAt: r.created_at!,- location: {- type: 'channel' as const,- threadId: r.thread_id ?? undefined,- messageId: r.message_id!,- },- }));- });- break;- }- case 'pdf': {- contentHitData = data.results.flatMap((r) => {- const contents = r.highlight.content ?? [];- return contents.map((content) => {- const mergedContent = mergeAdjacentMacroEmTags(content);- return {- type: 'pdf' as const,- content: truncateSearchMatch(- mergeAdjacentMacroEmTags(content),- SEARCH_MATCH_LENGTH- ),- location: {- type: 'pdf' as const,- searchPage: Number(r.node_id),- searchSnippet: extractSearchSnippet(mergedContent),- searchRawQuery: data.searchQuery,- highlightTerms: extractSearchTerms(mergedContent),- },- };- });- });- break;- }- case 'md': {- contentHitData = data.results.flatMap((r) => {- const isContentHit = !!r.node_id;- if (!isContentHit) return [];-- const contents = r.highlight.content ?? [];- return contents.map((content) => ({- type: 'md' as const,- content: truncateSearchMatch(- mergeAdjacentMacroEmTags(content),- SEARCH_MATCH_LENGTH- ),- location: { type: 'md' as const, nodeId: r.node_id! },- }));- });- break;- }- case 'email': {- contentHitData = data.results.flatMap((r) => {- const contents = r.highlight.content ?? [];- return contents.map((content) => ({- type: 'email' as const,- content: truncateSearchMatch(- mergeAdjacentMacroEmTags(content),- SEARCH_MATCH_LENGTH- ),- sender: r.pretty_sender!,- senderId: emailToId(r.sender),- sentAt: r.sent_at!,- location: {- type: 'email' as const,- messageId: r.message_id!,- },- }));- });- break;- }- default: {- contentHitData = data.results.flatMap((r) => {- const contents = r.highlight.content ?? [];- return contents.map((content) => ({- content: truncateSearchMatch(- mergeAdjacentMacroEmTags(content),- SEARCH_MATCH_LENGTH- ),- location: undefined,- }));- });- }- }-- const nameHighlight = data.results.at(0)?.highlight.name ?? null;-- return {- nameHighlight: nameHighlight- ? mergeAdjacentMacroEmTags(nameHighlight)- : null,- contentHitData: contentHitData.length > 0 ? contentHitData : null,- source: 'service' as const,- };-};--const useMapSearchResponseItem = () => {- const channelsContext = useChannelsContext();- const channels = channelsContext.channels;-- const historyQuery = useHistoryQuery();-- return (- result: UnifiedSearchResponseItem,- searchQuery: string- ): WithSearch<EntityData> | undefined => {- switch (result.type) {- case 'document': {- if (!result.metadata || result.metadata.deleted_at) return;- const searchFileType =- result.file_type === 'docx' ? 'pdf' : result.file_type;- let search: SearchData;- if (searchFileType === 'md') {- search = getSearchData({- results: result.document_search_results,- type: 'md',- });- } else if (searchFileType === 'pdf') {- search = getSearchData({- results: result.document_search_results,- type: 'pdf',- searchQuery,- });- } else {- search = getSearchData({- results: result.document_search_results,- });- }- return {- type: 'document',- subType: result.sub_type === 'task' ? { type: 'task' } : null,- id: result.document_id,- name: result.name || blockNameToDefaultFile(result.file_type),- ownerId: result.owner_id,- createdAt: result.metadata?.created_at,- updatedAt: result.metadata?.updated_at,- fileType: result.file_type || undefined,- projectId: result.metadata?.project_id ?? undefined,- search,- };- }- case 'email': {- const messageHits = result.email_message_search_results.filter(- (m) => m.message_id- );- // NOTE: guaranteed to be empty or singleton array- const threadHits = result.email_message_search_results.filter(- (m) => !m.message_id- );-- const singleMessage = messageHits.length === 1;-- const search = getSearchData({- results: result.email_message_search_results,- type: 'email',- });-- const name = result.name ?? blockNameToDefaultFile('email');-- // TODO: display sender for each message in the content hit list- const combinedSenders =- [...new Set(messageHits.map((m) => m.pretty_sender))].join(', ') ||- threadHits.at(0)?.pretty_sender;-- // TODO: we probably want to get the actual latest message info on the full thread- const messagesSentAt = messageHits- .map((m) => m.sent_at)- .filter((m) => m != null);- const latestMessageSentAt =- messagesSentAt.length > 0 ? Math.max(...messagesSentAt) : null;-- return {- type: 'email',- id: result.thread_id,- name,- ownerId: result.owner_id,- createdAt: latestMessageSentAt ?? result.created_at,- updatedAt: latestMessageSentAt ?? result.updated_at,- viewedAt: result.viewed_at ?? undefined,- isRead: singleMessage- ? !messageHits[0].labels.includes('UNREAD')- : false,- isImportant: singleMessage- ? messageHits[0].labels.includes('IMPORTANT')- : false,- isDraft: singleMessage- ? messageHits[0].labels.includes('DRAFT')- : false,- done: singleMessage- ? !messageHits[0].labels.includes('INBOX')- : false,- senderName: combinedSenders,- search,- };- }- case 'chat': {- if (!result.metadata || result.metadata.deleted_at) return;- const search = getSearchData({- results: result.chat_search_results,- });- let name = result.name;- if (!name || name === blockNameToDefaultFile('chat')) {- const chat = (historyQuery.data ?? []).find(- (item) => item.id === result.chat_id- );- if (chat) {- name = chat.name;- }- }- return {- type: 'chat',- id: result.chat_id,- name,- ownerId: result.user_id,- createdAt: result.metadata?.created_at,- updatedAt: result.metadata?.updated_at,- projectId: result.metadata?.project_id ?? undefined,- search,- };- }- case 'channel': {- const channelWithLatest = channels().find(- (c) => c.id === result.channel_id- );-- const search = getSearchData({- type: 'channel',- results: result.channel_message_search_results,- });-- return {- type: 'channel',- id: result.channel_id,- name: channelWithLatest?.name ?? blockNameToDefaultFile('channel'),- ownerId: result.owner_id ?? '',- createdAt: result.metadata?.created_at,- updatedAt: result.metadata?.updated_at,- channelType: result.channel_type as ChannelType,- interactedAt: result.metadata?.interacted_at ?? undefined,- participantIds: channelWithLatest?.participants?.map(- (p) => p.user_id- ),- search,- };- }-- case 'project': {- if (!result.metadata || result.metadata.deleted_at) return;- const search = getSearchData({- results: result.project_search_results,- });-- return {- type: 'project',- id: result.id,- name: result.name,- ownerId: result.owner_id,- createdAt: result.created_at,- updatedAt: result.updated_at,- projectId: result.metadata?.parent_project_id ?? undefined,- search,- };- }- }- };-};--const fetchSearchResults = async (args: SearchArgs, signal?: AbortSignal) => {- const res = await searchClient.search(args, { signal });- if (isErr(res)) throw res[0];- const [, data] = res;- return data;-};--export function createUnifiedSearchInfiniteQuery(- args: Accessor<SearchArgs>,- options?: {- disabled?: Accessor<boolean>;- }-): EntityInfiniteQuery<WithSearch<EntityData>> {- const params = createMemo(() => args());- const pageSize = createMemo(() => params().params.page_size);- const request = createMemo(() => params().request);- const terms = createMemo(() => {- const query = request().query;- const hasQuery = query && query.length > 0;- const terms = request().terms;- const hasTerms = terms && terms.length > 0;- if (hasTerms && hasQuery) {- console.error('Cannot have both query and terms');- return [];- }- if (hasTerms) {- return terms;- }- if (hasQuery) {- return [query];- }- return [];- });- const validSearchTerms = createMemo(() => {- return terms().length > 0 && terms().every((term) => term.length >= 3);- });- const validSearchFilters = createMemo(() => {- const senders = params().request.filters?.email?.senders;- if (senders && senders.length > 0) return true;- return false;- });- const enabled = createMemo(- () =>- ENABLE_SEARCH_SERVICE &&- !options?.disabled?.() &&- (validSearchTerms() || validSearchFilters())- );-- const mapSearchResponseItem = useMapSearchResponseItem();-- const query = useInfiniteQuery(() => ({- queryKey: queryKeys.search({- infinite: true,- ...params(),- }),- queryFn: (ctx) =>- fetchSearchResults(- {- params: ctx.pageParam,- request: request(),- },- ctx.signal- ),- initialPageParam: {- cursor: null as string | null,- page_size: pageSize(),- },- getNextPageParam: (lastPage) => {- if (!lastPage.next_cursor) return;- return {- cursor: lastPage.next_cursor as string | null,- page_size: pageSize(),- };- },- select: (data) => {- const searchQuery = terms()[0];- return data.pages.flatMap((page) =>- page.results- .map((result) => mapSearchResponseItem(result, searchQuery))- .filter((entity): entity is WithSearch<EntityData> => !!entity)- );- },- enabled: enabled(),- }));-- return query;-}diff --git a/js/app/packages/macro-entity/src/source/email.ts b/js/app/packages/macro-entity/src/source/email.tsdeleted file mode 100644index 7cfa94ad93..0000000000--- a/js/app/packages/macro-entity/src/source/email.ts+++ /dev/null@@ -1,164 +0,0 @@-import { isErr } from '@core/util/maybeResult';-import { emailClient } from '@service-email/client';-import { trackStore } from '@solid-primitives/deep';-import type { UseInfiniteQueryResult } from '@tanstack/solid-query';-import {- type Accessor,- batch,- createDeferred,- createEffect,- createMemo,-} from 'solid-js';-import { createStore, reconcile, type Store } from 'solid-js/store';-import type { FetchPaginatedEmailsParams } from '../queries/email';-import { createEmailsInfiniteQuery } from '../queries/email';-import type { EmailEntity } from '../types/entity';--type EmailStore = Record<string, EmailEntity>;-type EmailBySortedView = Record<string, string[]>; // viewKey -> array of email IDs-type EmailQueryParams = Partial<FetchPaginatedEmailsParams>;--export type EmailSource = {- readonly _store: Store<EmailStore>;- readonly _query: UseInfiniteQueryResult<EmailEntity[], Error>;- readonly emails: Accessor<EmailEntity[]>;- readonly isLoading: Accessor<boolean>;-- setQueryParams: (params: EmailQueryParams) => void;- getByParams: (params: EmailQueryParams) => EmailEntity[];-- /** Archive or unarchive an email */- archiveEmail: (id: string, archive: boolean) => Promise<void>;-- /** Mark an email as read */- markAsRead: (id: string) => Promise<void>;-- /** Refetch emails */- refetch: () => Promise<void>;-};--const singletonEmailStore = createStore<EmailStore>({});--export function useEmails() {- const [store] = singletonEmailStore;- return createMemo(() => Object.values(store));-}--function getViewKey(params?: EmailQueryParams): string {- const view = params?.view ?? 'inbox';- const sort = params?.sort_method ?? 'viewed_updated';- return `${view}-${sort}`;-}--export function createEmailSource(- maybeQuery?: UseInfiniteQueryResult<EmailEntity[], Error>,- initialQueryParams: FetchPaginatedEmailsParams = { view: 'inbox' },- options?: {- disabled?: Accessor<boolean>;- }-): EmailSource {- const [store, setStore] = singletonEmailStore;- const [sortedView, setSortedView] = createStore<EmailBySortedView>({});- const [queryParams, setQueryParams] =- createStore<FetchPaginatedEmailsParams>(initialQueryParams);-- const query =- maybeQuery ??- createEmailsInfiniteQuery(() => ({ ...queryParams }), {- disabled: options?.disabled,- });-- const emails = createMemo(() => Object.values(store));-- const getByParams = (params: EmailQueryParams) => {- const viewKey = getViewKey(params);- const emailIds = trackStore(sortedView[viewKey]) ?? [];-- // Map IDs to actual email entities from the store- return emailIds.map((id) => store[id]).filter((email) => !!email);- };-- const isLoading = () => query.isLoading;-- /** Reconcile new emails into the store and update view */- const reconcileEmails = (emails: EmailEntity[], viewKey: string) =>- batch(() => {- const emailsById: EmailStore = {};- const emailIds: string[] = [];-- for (const email of emails) {- emailsById[email.id] = email;- emailIds.push(email.id);- }-- setStore(emailsById);- setSortedView(viewKey, reconcile(emailIds, { key: 'id' }));- });-- // TODO: if something needs emails it needs to be using search query- const canBackgroundFetch = createDeferred(- () => false && query.isSuccess && query.hasNextPage && !query.isFetching- );- createEffect(() => {- // don't background fetch for all view, there are too many emails to fetch- if (queryParams.view === 'all') return;-- if (canBackgroundFetch()) query.fetchNextPage();- });-- createEffect(() => {- if (query.isSuccess) reconcileEmails(query.data, getViewKey(queryParams));- });-- const archiveEmail = async (id: string, value: boolean) => {- // Optimistically update- const previousValue = store[id]?.done;- setStore(id, 'done', value);-- try {- // Server mutation- const maybeResult = await emailClient.flagArchived({ id, value });- if (isErr(maybeResult)) throw maybeResult[0];- } catch (_) {- // Rollback on error- setStore(id, 'done', previousValue);- } finally {- // Revalidate- refetch();- }- };-- const markAsRead = async (id: string) => {- // Optimistically update- const previousValue = store[id]?.isRead;- setStore(id, 'isRead', true);-- try {- // Server mutation- const maybeResult = await emailClient.markThreadAsSeen({ thread_id: id });- if (isErr(maybeResult)) throw maybeResult[0];- } catch (_) {- // Rollback on error- setStore(id, 'isRead', previousValue);- } finally {- // Revalidate- refetch();- }- };-- const refetch = async () => {- await query.refetch();- };-- return {- _store: store,- _query: query,- emails,- isLoading,- setQueryParams,- getByParams,- archiveEmail,- markAsRead,- refetch,- };-}diff --git a/js/app/packages/macro-entity/src/types/drag.ts b/js/app/packages/macro-entity/src/types/drag.tsdeleted file mode 100644index 765ae16d4d..0000000000--- a/js/app/packages/macro-entity/src/types/drag.ts+++ /dev/null@@ -1,17 +0,0 @@-import type { DragEvent } from '@thisbeyond/solid-dnd';-import type { EntityData } from './entity';-import type { Accessor } from 'solid-js';--export type EntityDragOperation = 'move' | 'copy';--export type EntityDragData = EntityData & {- dragType: 'entity';- operation: Accessor<EntityDragOperation>;- splitId?: string;-};--export type EntityDragEvent = DragEvent & {- draggable: {- data: EntityDragData;- };-};diff --git a/js/app/packages/macro-entity/src/types/entity.ts b/js/app/packages/macro-entity/src/types/entity.tsdeleted file mode 100644index 4cb98721da..0000000000--- a/js/app/packages/macro-entity/src/types/entity.ts+++ /dev/null@@ -1,157 +0,0 @@-import { isEntityType } from '@core/types/utils';-import type { ApiLabel } from '@service-email/generated/schemas';-import type {- SoupLabel,- SoupProperty,-} from '@service-storage/generated/schemas';-import type { JSX } from 'solid-js';--export type EntityBase = {- id: string;- name: string;- ownerId: string;- frecencyScore?: number;- createdAt?: number;- updatedAt?: number;- viewedAt?: number;-};--export type ChannelEntity = EntityBase & {- type: 'channel';- channelType: 'direct_message' | 'private' | 'organization' | 'public';- interactedAt?: number;- participantIds?: string[];- latestMessage?: {- content: string;- senderId: string;- createdAt: number;- };-};--export type ChatEntity = EntityBase & {- type: 'chat';- projectId?: string;-};--/** Named sub types - currently only 'task' */-export type NamedSubType = 'task';--/** SubType for documents - currently only tasks */-export type SubType = {- type: NamedSubType;- is_completed?: boolean;-} | null;--export type BaseDocumentEntity = EntityBase & {- type: 'document';- fileType?: string;- projectId?: string;- subType?: SubType;-};--export type TaskEntity = EntityBase & {- type: 'document';- fileType: 'md';- subType: { type: 'task'; is_completed?: boolean };- projectId?: string;-};--export type MarkdownEntity = EntityBase & {- type: 'document';- fileType: 'md';- subType?: null;- projectId?: string;-};--export type DocumentEntity = BaseDocumentEntity | MarkdownEntity;--export const getEntityProjectId = (e: EntityData): string | false => {- return 'projectId' in e ? (e.projectId ?? false) : false;-};--// We spread ApiThreadPreviewCursor into the email entity, should we explcitly include all those fields here, or only add them as needed?-export type EmailEntity = EntityBase & {- type: 'email';- isRead: boolean;- isDraft: boolean;- snippet?: string;- isImportant: boolean;- done: boolean;- participants?: Array<{ email: string; name: string }>;- senderEmail?: string;- senderName?: string;- labels?: SoupLabel[] | ApiLabel[];-};--export type ProjectEntity = EntityBase & {- type: 'project';- projectId?: string;-};--// Create new entity types above this comment-// Then add it to the EntityData union below--export type EntityData =- | ChannelEntity- | ChatEntity- | DocumentEntity- | TaskEntity- | EmailEntity- | ProjectEntity;--export const isEntityData = (item: unknown): item is EntityData => {- if (typeof item !== 'object') return false;-- if (!item) return false;-- if (!('type' in item)) return false;-- if (typeof item.type !== 'string') return false;-- return isEntityType(item.type);-};--export const isTaskEntity = (entity: EntityData): entity is TaskEntity => {- return (- entity.type === 'document' &&- entity.fileType === 'md' &&- entity.subType?.type === 'task'- );-};--export const isPureDocumentEntity = (- entity: EntityData-): entity is DocumentEntity => {- return entity.type === 'document' && entity.subType?.type !== 'task';-};--export type EntityType = EntityData['type'];--export type ExpandedEntityType = EntityType | 'task';--export type EntityWithProperties<T extends EntityData> = T & {- properties?: SoupProperty[];-};--export type TaskEntityWithProperties = EntityWithProperties<TaskEntity>;--export type EntityOf<K extends EntityType> = Extract<EntityData, { type: K }>;--export type EntityMapper<T extends EntityData> = (entity: EntityData) => T;--export type EntityEnhancer<T extends EntityData> = (- entity: EntityData,- index?: number,- array?: EntityData[]-) => T;--export type EntityFilter<T extends EntityData> = (entity: T) => boolean;--export type EntitiesFilter<T extends EntityData> = (entities: T[]) => T[];--export type EntityComparator<T extends EntityData> = (a: T, b: T) => number;--export type EntityRenderer<T extends EntityData> = (props: {- entity: T;- index: number;-}) => JSX.Element;diff --git a/js/app/packages/macro-entity/src/types/filter.ts b/js/app/packages/macro-entity/src/types/filter.tsdeleted file mode 100644index 8375110461..0000000000--- a/js/app/packages/macro-entity/src/types/filter.ts+++ /dev/null@@ -1,10 +0,0 @@-export type SortType = 'unread' | 'updated' | 'created' | 'viewed';--export type OwnerType = 'all' | 'me' | 'other';--export type Filters = {- unreadFilter: boolean;- sortBy: SortType;- fileTypeFilter: string[];- ownerTypeFilter: OwnerType;-};diff --git a/js/app/packages/macro-entity/src/types/notification.ts b/js/app/packages/macro-entity/src/types/notification.tsdeleted file mode 100644index 0b859c6e53..0000000000--- a/js/app/packages/macro-entity/src/types/notification.ts+++ /dev/null@@ -1,18 +0,0 @@-// Temporarily use the generated types for now-import type { ApiUserNotification } from '@service-notification/generated/schemas/apiUserNotification';-import type { Accessor } from 'solid-js';--export type Notification = Omit<ApiUserNotification, 'ownerId'>;--export type WithNotification<T> = T & {- notifications?: Accessor<Notification[]>;-};--/**- * Extended notification type that includes stacked notifications for bulk operations.- * When clicking a stacked notification row, this array contains all notifications in the stack- * so they can be bulk-marked as done.- */-export type WithStackedNotifications<T> = T & {- stackedNotifications?: Notification[];-};diff --git a/js/app/packages/macro-entity/src/types/search.ts b/js/app/packages/macro-entity/src/types/search.tsdeleted file mode 100644index 1494f28559..0000000000--- a/js/app/packages/macro-entity/src/types/search.ts+++ /dev/null@@ -1,88 +0,0 @@-import type { EntityData } from './entity';--type MarkdownHighlightLocation = {- type: 'md';- nodeId: string;-};--type PdfHighlightLocation = {- type: 'pdf';- searchPage: number;- highlightTerms: string[];- searchSnippet: string;- searchRawQuery: string;-};--type ChannelMessageHighlightLocation = {- type: 'channel';- threadId?: string;- messageId: string;-};--type EmailMessageHighlightLocation = {- type: 'email';- messageId: string;-};--export type SearchLocation =- | MarkdownHighlightLocation- | PdfHighlightLocation- | ChannelMessageHighlightLocation- | EmailMessageHighlightLocation;--export type ChannelContentHitData = {- type: 'channel';- id: string;- content: string;- senderId: string;- sentAt: number;- location: ChannelMessageHighlightLocation;-};--type MdContentHitData = {- type: 'md';- content: string;- location: MarkdownHighlightLocation;-};--type PdfContentHitData = {- type: 'pdf';- content: string;- location: PdfHighlightLocation;-};--type GenericContentHitData = {- type?: undefined;- content: string;- location?: never;-};--export type EmailContentHitData = {- type: 'email';- content: string;- sender: string;- senderId: string;- sentAt: number;- location: EmailMessageHighlightLocation;-};--export type DocumentContentHitData =- | MdContentHitData- | PdfContentHitData- | GenericContentHitData;--export type ContentHitData =- | DocumentContentHitData- | ChannelContentHitData- | EmailContentHitData- | GenericContentHitData;--export type SearchData = {- nameHighlight: string | null;- contentHitData: ContentHitData[] | null;- source: 'local' | 'service';-};--export type WithSearch<T extends EntityData> = T & {- search: SearchData;-};diff --git a/js/app/packages/macro-entity/src/utils/arrayCompare.ts b/js/app/packages/macro-entity/src/utils/arrayCompare.tsdeleted file mode 100644index 90f77964c2..0000000000--- a/js/app/packages/macro-entity/src/utils/arrayCompare.ts+++ /dev/null@@ -1,12 +0,0 @@-export function containsAllSameValues(a: unknown[], b: unknown[]) {- if (a.length !== b.length) return false;- return (- a.every((value) => b.includes(value)) &&- b.every((value) => a.includes(value))- );-}--export function containsAllSameOrderedValues(a: unknown[], b: unknown[]) {- if (a.length !== b.length) return false;- return a.every((value, index) => value === b[index]);-}diff --git a/js/app/packages/macro-entity/src/utils/filter.ts b/js/app/packages/macro-entity/src/utils/filter.tsdeleted file mode 100644index 2c0bbec692..0000000000--- a/js/app/packages/macro-entity/src/utils/filter.ts+++ /dev/null@@ -1,52 +0,0 @@-import { createMemo, createSignal } from 'solid-js';-import {- type EntityData,- type EntityFilter,- getEntityProjectId,- isTaskEntity,-} from '../types/entity';-import type { WithNotification } from '../types/notification';--export function composeFilters<T extends EntityData>(- ...filters: EntityFilter<T>[]-): EntityFilter<T> {- return (entity: T) => filters.every((filter) => filter(entity));-}--export function createFilterComposer<T extends EntityData = EntityData>(- initialFilters: EntityFilter<T>[] = []-) {- const [filters, setFilters] = createSignal<EntityFilter<T>[]>(initialFilters);-- const filterFn = createMemo(() => composeFilters(...filters()));-- return {- setFilters,- filterFn,- };-}--export function createProjectFilterFn(projectId: string) {- return (entity: EntityData) => {- return getEntityProjectId(entity) === projectId;- };-}--export function unreadFilterFn(entity: WithNotification<EntityData>) {- if (entity.type === 'email') return !entity.isRead;- return entity.notifications?.()?.some(({ viewedAt }) => !viewedAt) ?? false;-}--export function importantFilterFn(entity: WithNotification<EntityData>) {- if (entity.type === 'email') return entity.isImportant;- return !!entity.notifications && entity.notifications().length > 0;-}--export function notDoneFilterFn(entity: WithNotification<EntityData>) {- if (entity.type === 'email') return !entity.done;- // Tasks are handled by signalFilter based on assignee/status, not notifications- if (isTaskEntity(entity)) return true;- return (- !!entity.notifications && entity.notifications().some(({ done }) => !done)- );-}diff --git a/js/app/packages/queries/preview/types.ts b/js/app/packages/queries/preview/types.tsindex f3bee6f81d..ceb9147a65 100644--- a/js/app/packages/queries/preview/types.ts+++ b/js/app/packages/queries/preview/types.ts@@ -1,4 +1,4 @@-import type { SubType } from '@macro-entity';+import type { SubType } from '@entity';import type { ChannelType } from '@service-cognition/generated/schemas/channelType';import type { Message } from '@service-comms/generated/models';import type { ItemType } from '@service-storage/client';diff --git a/js/app/packages/queries/soup/items.ts b/js/app/packages/queries/soup/items.tsindex 7bb5704900..350a88ab60 100644--- a/js/app/packages/queries/soup/items.ts+++ b/js/app/packages/queries/soup/items.ts@@ -1,5 +1,5 @@import { throwOnErr } from '@core/util/maybeResult';-import type { EntityData } from '@macro-entity';+import type { EntityData } from '@entity';import { soupKeys } from '@queries/soup/keys';import { mapSoupPageToEntityList } from '@queries/soup/transform-utils';import { useInstructionsMdIdQuery } from '@queries/storage/instructions-md';diff --git a/js/app/packages/queries/soup/normalized-cache/index.ts b/js/app/packages/queries/soup/normalized-cache/index.tsindex 8857f09203..ad6eb8f663 100644--- a/js/app/packages/queries/soup/normalized-cache/index.ts+++ b/js/app/packages/queries/soup/normalized-cache/index.ts@@ -16,4 +16,5 @@ export {removeSoupEntities,removeSearchEntities,refetchSoupEntity,+ optimisticUpdateSoupItemViewedAt,} from './operations';diff --git a/js/app/packages/queries/soup/normalized-cache/operations.ts b/js/app/packages/queries/soup/normalized-cache/operations.tsindex 517a275592..41a95e6d5d 100644--- a/js/app/packages/queries/soup/normalized-cache/operations.ts+++ b/js/app/packages/queries/soup/normalized-cache/operations.ts@@ -266,6 +266,31 @@ export function buildSingleEntityFilter();}+/**+ * Optimistically update the viewedAt timestamp for a soup item.+ * Updates the item across all soup queries if it exists.+ */+export function optimisticUpdateSoupItemViewedAt(itemId: string) {+ const current = getSoupEntityById(itemId);+ if (!current) return;++ const now = new Date();++ if (current.tag === 'channel') {+ optimisticUpdateSoupEntity({+ tag: 'channel',+ data: { channel: { id: itemId }, viewed_at: now.toISOString() },+ frecency_score: current.frecency_score,+ });+ } else {+ optimisticUpdateSoupEntity({+ tag: current.tag,+ data: { id: itemId, viewedAt: now.getTime() },+ frecency_score: current.frecency_score,+ });+ }+}+/** @private */function getSearchResultId(result: UnifiedSearchResponseItem): string {return match(result)diff --git a/js/app/packages/queries/soup/search.ts b/js/app/packages/queries/soup/search.tsindex 9f532080b4..e8b3da2f42 100644--- a/js/app/packages/queries/soup/search.ts+++ b/js/app/packages/queries/soup/search.ts@@ -1,6 +1,6 @@import { ENABLE_SEARCH_SERVICE } from '@core/constant/featureFlags';import { throwOnErr } from '@core/util/maybeResult';-import type { WithSearch, EntityData } from '@macro-entity';+import type { WithSearch, EntityData } from '@entity';import { soupKeys } from '@queries/soup/keys';import { useSearchResponseItemMapper } from '@queries/soup/transform-utils';import { searchClient } from '@service-search/client';diff --git a/js/app/packages/queries/soup/transform-utils.ts b/js/app/packages/queries/soup/transform-utils.tsindex 53dc10c90d..1426872ca8 100644--- a/js/app/packages/queries/soup/transform-utils.ts+++ b/js/app/packages/queries/soup/transform-utils.ts@@ -20,7 +20,7 @@ import type {ProjectEntity,EmailEntity,ChannelEntity,-} from '@macro-entity';+} from '@entity';import { useHistoryQuery } from '@queries/history/history';import type { ChannelType } from '@service-comms/generated/models';import type {