Skip to content

armgit / macro

Public Imported from GitHub
0

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

fix: preview rename non existent query (#1375)

gbirmana01b446c38bd
diff --git a/js/app/packages/app/component/rightbar/Rightbar.tsx b/js/app/packages/app/component/rightbar/Rightbar.tsx
index cdcca0447c..c12c54e0fd 100644
--- a/js/app/packages/app/component/rightbar/Rightbar.tsx
+++ b/js/app/packages/app/component/rightbar/Rightbar.tsx
@@ -54,7 +54,6 @@ import {
cognitionApiServiceClient,
cognitionWebsocketServiceClient,
} from '@service-cognition/client';
-import { createCognitionWebsocketEffect } from '@service-cognition/websocket';
import { refetchHistory, useHistoryQuery } from '@queries/history/history';
import { useOpenInstructionsMd } from 'core/component/AI/util/instructions';
import type { LexicalEditor } from 'lexical';
@@ -74,8 +73,8 @@ import {
import { SplitlikeContainer } from '../split-layout/components/SplitContainer';
import { Button } from '@ui/components/Button';
import { Hotkey } from '@core/component/Hotkey';
-import { setPreviewData } from '@queries/preview';
import { AccessLevel } from '@service-cognition/generated/schemas/accessLevel';
+import { useWaitChatRename } from '../../../macro-entity/src/queries/rename';
type ChatData = {
messages: ChatMessageWithAttachments[];
@@ -542,42 +541,6 @@ export const RightbarWrapper = (_props: { isBigChat?: boolean }) => {
saveChatState();
});
- // TODO: move this into a shared util: see dcs websocket extraction and connection websocket bulk upload
- const CHAT_RENAME_TIMEOUT_MS = 60000;
- const chatRenameMap = new Map<
- string,
- {
- callback: (name: string | undefined) => void;
- clearTimeout: () => void;
- }
- >();
- const waitChatRename = async (chatId: string) => {
- const dispose = createCognitionWebsocketEffect('chat_renamed', (data) => {
- if (data.chat_id !== chatId) return;
- const chatInfo = chatRenameMap.get(chatId);
- if (!chatInfo) return;
- chatInfo.callback(data.name);
- dispose();
- });
-
- return new Promise<string | undefined>((accept) => {
- // always run this after timeout
- setTimeout(() => {
- dispose();
- chatRenameMap.delete(chatId);
- }, CHAT_RENAME_TIMEOUT_MS);
-
- const errorTimeout = setTimeout(() => {
- accept(undefined);
- }, CHAT_RENAME_TIMEOUT_MS);
-
- chatRenameMap.set(chatId, {
- callback: accept,
- clearTimeout: () => clearTimeout(errorTimeout),
- });
- });
- };
-
const { showPaywall } = usePaywallState();
const onSend = async (request: Send | CreateAndSend) => {
@@ -596,19 +559,8 @@ export const RightbarWrapper = (_props: { isBigChat?: boolean }) => {
setChatId(newChatId);
setUserAccessLevel(AccessLevel.owner);
- // TODO: move this into a separate resource so we don't have to refetch history
- // refetch history immediately to have the new chat id
- // then rename again when the server provides a default name
refetchHistory();
- waitChatRename(newChatId).then((name) => {
- refetchHistory();
- if (name) {
- setPreviewData(newChatId, (prev) => ({
- ...prev,
- name,
- }));
- }
- });
+ useWaitChatRename(newChatId);
return await onSend(response);
} else if (request.type === 'send') {
setMessages((p) => {
diff --git a/js/app/packages/block-canvas/component/nodes/EntityMention.tsx b/js/app/packages/block-canvas/component/nodes/EntityMention.tsx
index 49bf44c7e6..4da47281a7 100644
--- a/js/app/packages/block-canvas/component/nodes/EntityMention.tsx
+++ b/js/app/packages/block-canvas/component/nodes/EntityMention.tsx
@@ -280,7 +280,6 @@ export function File(props: { node: EntityMentionNode; mode: RenderMode }) {
}
content={
<PopupPreview
- item={item}
mouseEnter={() => {}}
mouseLeave={() => {}}
documentInfo={{
diff --git a/js/app/packages/block-channel/component/AttachmentsModal.tsx b/js/app/packages/block-channel/component/AttachmentsModal.tsx
index 23f39f175f..660809718d 100644
--- a/js/app/packages/block-channel/component/AttachmentsModal.tsx
+++ b/js/app/packages/block-channel/component/AttachmentsModal.tsx
@@ -167,8 +167,8 @@ function AttachmentItem(props: AttachmentItemProps) {
<span class="text-ink-extra-muted">attached</span>
<InlineItemPreview
- itemId={props.attachment.entity_id}
- itemType={props.attachment.entity_type as ItemType}
+ id={props.attachment.entity_id}
+ type={props.attachment.entity_type as ItemType}
/>
</span>
</button>
diff --git a/js/app/packages/block-channel/component/Message/MessageAttachments.tsx b/js/app/packages/block-channel/component/Message/MessageAttachments.tsx
index 97f788b7aa..4ef0c27dfd 100644
--- a/js/app/packages/block-channel/component/Message/MessageAttachments.tsx
+++ b/js/app/packages/block-channel/component/Message/MessageAttachments.tsx
@@ -57,8 +57,8 @@ export function MessageAttachments(props: MessageAttachmentsProps) {
<For each={props.documentAttachments()}>
{(attachment) => (
<ItemPreview
- itemType={stringToItemType(attachment.entity_type)}
- itemId={attachment.entity_id}
+ type={stringToItemType(attachment.entity_type)}
+ id={attachment.entity_id}
/>
)}
</For>
diff --git a/js/app/packages/block-chat/component/TopBar.tsx b/js/app/packages/block-chat/component/TopBar.tsx
index 30b90df485..a639390009 100644
--- a/js/app/packages/block-chat/component/TopBar.tsx
+++ b/js/app/packages/block-chat/component/TopBar.tsx
@@ -19,11 +19,9 @@ import { ShareButton } from '@core/component/TopBar/ShareButton';
import { useGetPermissions } from '@core/signal/permissions';
import { useBlockDocumentName } from '@core/util/currentBlockDocumentName';
import Notepad from '@icon/regular/notepad.svg';
-import { createCognitionWebsocketEffect } from '@service-cognition/websocket';
-import { refetchHistory } from '@queries/history/history';
import { useOpenInstructionsMd } from 'core/component/AI/util/instructions';
import { onCleanup, onMount } from 'solid-js';
-import { setPreviewData } from '@queries/preview';
+import { useWaitChatRename } from '../../macro-entity/src/queries/rename';
export function TopBar() {
const blockId = useBlockId();
@@ -33,16 +31,7 @@ export function TopBar() {
onMount(() => {
if (!name() || name() === DEFAULT_CHAT_NAME) {
- const dispose = createCognitionWebsocketEffect('chat_renamed', (data) => {
- if (data.chat_id === blockId) {
- refetchHistory();
- setPreviewData(data.chat_id, (prev) => ({
- ...prev,
- name: data.name,
- }));
- dispose();
- }
- });
+ const dispose = useWaitChatRename(blockId, true);
onCleanup(() => {
dispose();
diff --git a/js/app/packages/core/component/AI/component/input/Attachment.tsx b/js/app/packages/core/component/AI/component/input/Attachment.tsx
index 7f420c9008..c118bba5ad 100644
--- a/js/app/packages/core/component/AI/component/input/Attachment.tsx
+++ b/js/app/packages/core/component/AI/component/input/Attachment.tsx
@@ -4,22 +4,16 @@ import {
isDssImage,
isImageAttachment,
} from '@core/component/AI/util/attachment';
-import { EntityIcon } from '@core/component/EntityIcon';
+import { EntityIcon, channelTypeIcon } from '@core/component/EntityIcon';
import { ImagePreview } from '@core/component/ImagePreview';
import { toast } from '@core/component/Toast/Toast';
import { fileTypeToBlockName } from '@core/constant/allBlocks';
import { openInNewSplitForMention } from '@core/util/openInNewSplit';
import { useSplitNavigationHandler } from '@core/util/useSplitNavigationHandler';
-import BuildingIcon from '@icon/duotone/building-office-duotone.svg';
-import GlobeIcon from '@icon/duotone/globe-duotone.svg';
-import ChannelIcon from '@icon/duotone/hash-duotone.svg';
-import User from '@icon/duotone/user-duotone.svg';
-import ThreeUsersIcon from '@icon/duotone/users-three-duotone.svg';
import XIcon from '@icon/regular/x.svg';
import Spinner from '@phosphor-icons/core/bold/spinner-gap-bold.svg?component-solid';
import Envelope from '@phosphor-icons/core/regular/envelope.svg';
import Close from '@phosphor-icons/core/regular/x.svg?component-solid';
-import type { ChannelType } from '@service-cognition/generated/schemas';
import type { Accessor } from 'solid-js';
import { createMemo, createSignal, For, Match, Show, Switch } from 'solid-js';
import { Dynamic } from 'solid-js/web';
@@ -221,18 +215,3 @@ function ChatAttachment(props: {
</Switch>
);
}
-
-function channelTypeIcon(channelType: ChannelType) {
- switch (channelType) {
- case 'direct_message':
- return User;
- case 'private':
- return ThreeUsersIcon;
- case 'organization':
- return BuildingIcon;
- case 'public':
- return GlobeIcon;
- default:
- return ChannelIcon;
- }
-}
diff --git a/js/app/packages/core/component/AI/component/message/UserMessage.tsx b/js/app/packages/core/component/AI/component/message/UserMessage.tsx
index 3f15e37a8b..acbaa081a0 100644
--- a/js/app/packages/core/component/AI/component/message/UserMessage.tsx
+++ b/js/app/packages/core/component/AI/component/message/UserMessage.tsx
@@ -99,9 +99,9 @@ export function UserMessage(props: {
<For each={itemPreviewAttachments()}>
{(attachment) => (
<ItemPreview
- itemId={attachment.attachmentId}
+ id={attachment.attachmentId}
// TODO: improve typing for item preview attachments
- itemType={
+ type={
attachment.attachmentType as
| 'channel'
| 'document'
diff --git a/js/app/packages/core/component/DocumentPreview.tsx b/js/app/packages/core/component/DocumentPreview.tsx
index 6cd14020ff..8f639e0a27 100644
--- a/js/app/packages/core/component/DocumentPreview.tsx
+++ b/js/app/packages/core/component/DocumentPreview.tsx
@@ -14,15 +14,12 @@ import {
import { ClippedPanel } from '@core/component/ClippedPanel';
import { toast } from '@core/component/Toast/Toast';
import {
+ type AccessiblePreviewItem,
isAccessiblePreviewItem,
isChannelPreviewItem,
- type PreviewChannelAccess,
- type PreviewDocumentAccess,
- type PreviewItem,
- type PreviewItemAccess,
type PreviewItemNoAccess,
- type PreviewProjectAccess,
} from '@queries/preview';
+import { blockNameToItemType } from '@service-storage/client';
import { tryMacroId, useDisplayName } from '@core/user';
import { matches } from '@core/util/match';
// Icon imports
@@ -48,14 +45,14 @@ import { createCallback } from '@solid-primitives/rootless';
import { useNavigate } from '@solidjs/router';
import { globalSplitManager } from 'app/signal/splitLayout';
import type { Component, JSX } from 'solid-js';
-import { type Accessor, Match, Show, Switch } from 'solid-js';
+import { Match, Show, Switch } from 'solid-js';
import { Dynamic } from 'solid-js/web';
import { beveledCorners } from '../../block-theme/signals/themeSignals';
import { formatDate, isoToUnixTimestamp } from '../util/date';
import NotFound from './AccessErrorViews/NotFound';
import Unauthorized from './AccessErrorViews/Unauthorized';
-import { EntityIcon } from './EntityIcon';
import { Tooltip } from './Tooltip';
+import { useItemPreviewData } from './ItemPreview';
/**
* Container for displaying mentions with optional collapsing
@@ -268,7 +265,6 @@ function UserInfo(props: { userId: string }) {
* Popup preview component for document references
*/
export function PopupPreview(props: {
- item: Accessor<PreviewItem>;
mouseEnter: () => void;
mouseLeave: () => void;
delete?: () => void;
@@ -299,6 +295,11 @@ export function PopupPreview(props: {
const blockName = useMaybeBlockName();
const blockId = useMaybeBlockId();
+ const { item, ItemEntityIcon } = useItemPreviewData(() => ({
+ id: props.documentInfo.id,
+ type: blockNameToItemType(props.documentInfo.type),
+ }));
+
// Derived state
const canOpenInChat = createCallback(() => {
if (blockName && ['chat'].includes(blockName)) {
@@ -488,12 +489,7 @@ export function PopupPreview(props: {
* Renders the metadata info for the document
*/
const renderDocumentMetadata = (
- accessibleItem: NonNullable<
- | PreviewItemAccess
- | PreviewDocumentAccess
- | PreviewProjectAccess
- | PreviewChannelAccess
- >
+ accessibleItem: NonNullable<AccessiblePreviewItem>
) => {
const accessories = mentionsAccessories(
props.documentInfo.type,
@@ -534,7 +530,7 @@ export function PopupPreview(props: {
<Show
when={messageContext}
fallback={
- <Show when={props.item().owner}>
+ <Show when={item().owner}>
{(owner) => (
<MetadataInfo icon={UserIcon} align="left">
{owner().replace('macro|', '')}
@@ -549,7 +545,7 @@ export function PopupPreview(props: {
<Show
when={messageContext}
fallback={
- <Show when={props.item().updatedAt}>
+ <Show when={item().updatedAt}>
{(time) => (
<MetadataInfo icon={ClockIcon} align="right">
{formatDate(time())}
@@ -579,79 +575,50 @@ export function PopupPreview(props: {
<div class="p-3">
<Switch>
{/* Loading state */}
- <Match when={props.item().loading}>
+ <Match when={item().loading}>
<Loading />
</Match>
{/* Accessible preview */}
- <Match when={matches(props.item(), isAccessiblePreviewItem)}>
- {(accessibleItem) => {
- const { type, fileType, subType } = accessibleItem();
- return (
- <div class="w-full h-full flex-col">
- {/* Header with icon and actions */}
- <div class="flex w-full mb-2">
- <div class="w-full size-10">
- <Show
- when={type === 'channel'}
- fallback={
- <EntityIcon
- targetType={
- type === 'document'
- ? (subType?.type ?? fileType)
- : type
- }
- size="md"
- />
- }
- >
- <EntityIcon
- size="md"
- targetType={
- accessibleItem().channelType === 'direct_message'
- ? 'directMessage'
- : accessibleItem().channelType ===
- 'organization'
- ? 'company'
- : 'channel'
- }
- />
- </Show>
- </div>
- <div class="flex w-fit h-full justify-right">
- {renderActionButtons()}
- </div>
+ <Match when={matches(item(), isAccessiblePreviewItem)}>
+ {(accessibleItem) => (
+ <div class="w-full h-full flex-col">
+ {/* Header with icon and actions */}
+ <div class="flex w-full mb-2">
+ <div class="w-full size-10">
+ <ItemEntityIcon size="md" />
</div>
+ <div class="flex w-fit h-full justify-right">
+ {renderActionButtons()}
+ </div>
+ </div>
- {/* Document metadata */}
- {renderDocumentMetadata(accessibleItem())}
-
- {/* Snapshot info */}
- <Show when={props.snapshotInfo}>
- {(snapshot) => (
- <div class="mt-3 pt-2 border-t border-edge">
- <div class="flex items-center gap-1.5 text-ink-muted">
- <ClockIcon class="size-4" />
- <span class="text-xs font-medium">
- Snapshot from{' '}
- {formatDate(isoToUnixTimestamp(snapshot().date), {
- showTime: true,
- })}
- </span>
- </div>
+ {/* Document metadata */}
+ {renderDocumentMetadata(accessibleItem())}
+
+ {/* Snapshot info */}
+ <Show when={props.snapshotInfo}>
+ {(snapshot) => (
+ <div class="mt-3 pt-2 border-t border-edge">
+ <div class="flex items-center gap-1.5 text-ink-muted">
+ <ClockIcon class="size-4" />
+ <span class="text-xs font-medium">
+ Snapshot from{' '}
+ {formatDate(isoToUnixTimestamp(snapshot().date), {
+ showTime: true,
+ })}
+ </span>
</div>
- )}
- </Show>
- </div>
- );
- }}
+ </div>
+ )}
+ </Show>
+ </div>
+ )}
</Match>
{/* No access error */}
<Match
- when={
- (props.item() as PreviewItemNoAccess).access === 'no_access'
- }
+ when={(item() as PreviewItemNoAccess).access === 'no_access'}
>
<div class="text-sm p-4">
<Unauthorized />
@@ -660,10 +627,7 @@ export function PopupPreview(props: {
{/* Does not exist error */}
<Match
- when={
- (props.item() as PreviewItemNoAccess).access ===
- 'does_not_exist'
- }
+ when={(item() as PreviewItemNoAccess).access === 'does_not_exist'}
>
<div class="text-sm p-4">
<NotFound />
diff --git a/js/app/packages/core/component/EntityIcon.tsx b/js/app/packages/core/component/EntityIcon.tsx
index 9b4d3ca3bd..4d7266130a 100644
--- a/js/app/packages/core/component/EntityIcon.tsx
+++ b/js/app/packages/core/component/EntityIcon.tsx
@@ -41,7 +41,10 @@ import WideTask from '@macro-icons/wide/task.svg';
import WideUnknown from '@macro-icons/wide/unknown.svg';
import WideUser from '@macro-icons/wide/user.svg';
import WideVideo from '@macro-icons/wide/video.svg';
+import GlobeIcon from '@icon/duotone/globe-duotone.svg';
+import ThreeUsersIcon from '@icon/duotone/users-three-duotone.svg';
import { FileTypeMap } from '@service-storage/fileTypeMap';
+import type { ChannelType } from '@service-cognition/generated/schemas/channelType';
import type { FileType } from '@service-storage/generated/schemas/fileType';
import type { Component, JSX } from 'solid-js';
import { Dynamic } from 'solid-js/web';
@@ -386,3 +389,18 @@ export function getIconConfig(
}
return config;
}
+
+export function channelTypeIcon(channelType: ChannelType | undefined) {
+ switch (channelType) {
+ case 'direct_message':
+ return User;
+ case 'private':
+ return ThreeUsersIcon;
+ case 'organization':
+ return Building;
+ case 'public':
+ return GlobeIcon;
+ default:
+ return Channel;
+ }
+}
diff --git a/js/app/packages/core/component/ItemPreview.tsx b/js/app/packages/core/component/ItemPreview.tsx
index 9cc49eee20..60d301eca3 100644
--- a/js/app/packages/core/component/ItemPreview.tsx
+++ b/js/app/packages/core/component/ItemPreview.tsx
@@ -1,46 +1,36 @@
import type { BlockAlias, BlockName } from '@core/block';
import { fileTypeToBlockName } from '@core/constant/allBlocks';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
-import { isAccessiblePreviewItem, useItemPreview } from '@queries/preview';
+import {
+ isAccessiblePreviewItem,
+ useItemPreview,
+ type ItemEntity,
+} from '@queries/preview';
import { matches } from '@core/util/match';
import { openInNewSplitForMention } from '@core/util/openInNewSplit';
import { truncateString } from '@core/util/string';
import { useSplitNavigationHandler } from '@core/util/useSplitNavigationHandler';
-import BuildingIcon from '@icon/duotone/building-office-duotone.svg';
import EyeSlash from '@icon/duotone/eye-slash-duotone.svg';
-import GlobeIcon from '@icon/duotone/globe-duotone.svg';
-import ChannelIcon from '@icon/duotone/hash-duotone.svg';
import TrashSimple from '@icon/duotone/trash-simple-duotone.svg';
-import User from '@icon/duotone/user-duotone.svg';
-import ThreeUsersIcon from '@icon/duotone/users-three-duotone.svg';
import LoadingSpinner from '@icon/regular/spinner.svg';
import type { NamedSubType } from '@macro-entity';
-import type { ChannelType } from '@service-cognition/generated/schemas/channelType';
import type { ItemType } from '@service-storage/client';
import type { FileType } from '@service-storage/generated/schemas/fileType';
-import { Match, Switch, Suspense } from 'solid-js';
-import { Dynamic } from 'solid-js/web';
+import {
+ Match,
+ Switch,
+ Suspense,
+ type ComponentProps,
+ type Accessor,
+} from 'solid-js';
import { PopupPreview } from './DocumentPreview';
import { HoverCard } from './HoverCard';
import { useSplitLayout } from '../../app/component/split-layout/layout';
import { DeprecatedTextButton } from './DeprecatedTextButton';
-import {
- ENTITY_ICON_CONFIGS,
- EntityIcon,
- ICON_SIZE_CLASSES,
-} from './EntityIcon';
-
-type ItemPreviewProps = {
- itemId: string;
- itemType?: ItemType;
- cacheTimeSeconds?: number;
-};
+import { EntityIcon } from './EntityIcon';
-function useItemPreviewData(props: ItemPreviewProps) {
- const [item] = useItemPreview(() => ({
- id: props.itemId,
- type: props.itemType,
- }));
+export function useItemPreviewData(entity: Accessor<ItemEntity>) {
+ const [item] = useItemPreview(entity);
const { replaceOrInsertSplit, insertSplit } = useSplitLayout();
@@ -68,7 +58,7 @@ function useItemPreviewData(props: ItemPreviewProps) {
}
async function onPreviewClick(
- type: ItemPreviewProps['itemType'],
+ type: ItemType | undefined,
id: string,
fileType?: FileType,
subType?: NamedSubType,
@@ -91,33 +81,41 @@ function useItemPreviewData(props: ItemPreviewProps) {
return baseName;
};
- const blockConfig = () => ENTITY_ICON_CONFIGS['channel'];
- const sizeClass = () => ICON_SIZE_CLASSES['xs'];
- const className = () => {
- return `${sizeClass()} ${blockConfig().foreground}`;
- };
+ const targetType = () => {
+ const currentItem = item();
+ if (currentItem.loading || currentItem.access !== 'access') {
+ return undefined;
+ }
- const channelTypeIcon = (channelType: ChannelType | undefined) => {
- switch (channelType) {
- case 'direct_message':
- return User;
- case 'private':
- return ThreeUsersIcon;
- case 'organization':
- return BuildingIcon;
- case 'public':
- return GlobeIcon;
+ switch (currentItem.type) {
+ case 'document':
+ return currentItem.subType?.type ?? currentItem.fileType;
+ case 'channel':
+ switch (currentItem.channelType) {
+ case 'direct_message':
+ return 'directMessage';
+ case 'organization':
+ return 'company';
+ default:
+ return 'channel';
+ }
default:
- return ChannelIcon;
+ return currentItem.type;
}
};
+ const ItemEntityIcon = (
+ localProps?: Partial<Omit<ComponentProps<typeof EntityIcon>, 'targetType'>>
+ ) => {
+ return <EntityIcon targetType={targetType()} {...localProps} />;
+ };
+
return {
item,
name,
onPreviewClick,
- className,
- channelTypeIcon,
+ targetType,
+ ItemEntityIcon,
};
}
@@ -191,7 +189,7 @@ function InlineLoading() {
);
}
-export function ItemPreview(props: ItemPreviewProps) {
+export function ItemPreview(props: ItemEntity) {
return (
<Suspense>
<ItemPreviewInner {...props} />
@@ -199,9 +197,9 @@ export function ItemPreview(props: ItemPreviewProps) {
);
}
-function ItemPreviewInner(props: ItemPreviewProps) {
- const { item, name, onPreviewClick, className, channelTypeIcon } =
- useItemPreviewData(props);
+function ItemPreviewInner(props: ItemEntity) {
+ const { item, name, onPreviewClick, targetType, ItemEntityIcon } =
+ useItemPreviewData(() => props);
return (
<Switch>
@@ -213,51 +211,32 @@ function ItemPreviewInner(props: ItemPreviewProps) {
<Switch>
<Match when={matches(loadedItem(), isAccessiblePreviewItem)}>
{(accessibleItem) => {
- const itemData = accessibleItem();
- const fileType = itemData.fileType;
- const subType = itemData.subType?.type as
- | NamedSubType
- | undefined;
- const blockName = fileTypeToBlockName(
- subType ?? fileType ?? itemData.type
- );
+ const blockName = () => {
+ const type = targetType();
+ const itemType = accessibleItem().type;
+ return fileTypeToBlockName(type ?? itemType);
+ };
const navHandlers =
- useSplitNavigationHandler<HTMLButtonElement>((e) =>
+ useSplitNavigationHandler<HTMLButtonElement>((e) => {
+ const item = accessibleItem();
onPreviewClick(
- itemData.type,
- itemData.id,
- fileType,
- subType,
+ item.type,
+ item.id,
+ item.fileType,
+ item.subType?.type as NamedSubType | undefined,
e.altKey
- )
- );
+ );
+ });
return (
<HoverCard
- disabled={isTouchDevice() || !blockName}
+ disabled={isTouchDevice() || !blockName()}
trigger={
<button
class="text-ink-base text-sm ring-1 ring-edge-muted rounded-xs hover:bg-panel-hover flex flex-row h-6 px-2 justify-center items-center"
{...navHandlers}
>
<div class="flex justify-start items-center h-3.5 mr-2">
- {itemData.type === 'channel' ? (
- <div class={className()}>
- <Dynamic
- component={channelTypeIcon(
- itemData.channelType
- )}
- />
- </div>
- ) : (
- <EntityIcon
- targetType={
- itemData.type === 'document'
- ? (subType ?? fileType)
- : itemData.type
- }
- size="fill"
- />
- )}
+ <ItemEntityIcon size="fill" />
</div>
<div class="flex-1 text-left leading-5 min-w-0 truncate">
{truncateString(name(), 80)}
@@ -266,12 +245,11 @@ function ItemPreviewInner(props: ItemPreviewProps) {
}
content={
<PopupPreview
- item={item}
mouseEnter={() => {}}
mouseLeave={() => {}}
documentInfo={{
- id: itemData.id,
- type: blockName as BlockName,
+ id: accessibleItem().id,
+ type: blockName() as BlockName,
params: {},
isOpenable: true,
}}
@@ -294,8 +272,8 @@ function ItemPreviewInner(props: ItemPreviewProps) {
);
}
-export function InlineItemPreview(props: ItemPreviewProps) {
- const { item, name, className, channelTypeIcon } = useItemPreviewData(props);
+export function InlineItemPreview(props: ItemEntity) {
+ const { item, name, ItemEntityIcon } = useItemPreviewData(() => props);
return (
<Switch>
@@ -306,36 +284,14 @@ export function InlineItemPreview(props: ItemPreviewProps) {
{(loadedItem) => (
<Switch>
<Match when={matches(loadedItem(), isAccessiblePreviewItem)}>
- {(accessibleItem) => {
- const itemData = accessibleItem();
- const fileType = itemData.fileType;
- const subType = itemData.subType?.type;
- return (
- <span class="inline-flex items-center gap-1">
- <span class="w-4 h-4">
- {itemData.type === 'channel' ? (
- <div class={className()}>
- <Dynamic
- component={channelTypeIcon(itemData.channelType)}
- />
- </div>
- ) : (
- <EntityIcon
- targetType={
- itemData.type === 'document'
- ? (subType ?? fileType)
- : itemData.type
- }
- size="xs"
- />
- )}
- </span>
- <span class="underline decoration-current/20 decoration-[max(1px,0.1em)] underline-offset-2">
- {truncateString(name(), 80)}
- </span>
- </span>
- );
- }}
+ <span class="inline-flex items-center gap-1">
+ <span class="w-4 h-4">
+ <ItemEntityIcon size="xs" />
+ </span>
+ <span class="underline decoration-current/20 decoration-[max(1px,0.1em)] underline-offset-2">
+ {truncateString(name(), 80)}
+ </span>
+ </span>
</Match>
<Match when={loadedItem().access === 'no_access'}>
<InlineNoAccess />
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/decorator/DocumentCard.tsx b/js/app/packages/core/component/LexicalMarkdown/component/decorator/DocumentCard.tsx
index 7a1c9709d3..91f2ad9721 100644
--- a/js/app/packages/core/component/LexicalMarkdown/component/decorator/DocumentCard.tsx
+++ b/js/app/packages/core/component/LexicalMarkdown/component/decorator/DocumentCard.tsx
@@ -17,10 +17,7 @@ import { ENABLE_BLOCK_IN_BLOCK } from '@core/constant/featureFlags';
import { canNestBlock, createBlockInstance } from '@core/orchestrator';
import {
isAccessiblePreviewItem,
- type PreviewChannelAccess,
- type PreviewDocumentAccess,
- type PreviewItemAccess,
- type PreviewProjectAccess,
+ type AccessiblePreviewItem,
useItemPreview,
} from '@queries/preview';
import { matches } from '@core/util/match';
@@ -332,11 +329,7 @@ function DocumentCardInner(props: DocumentCardDecoratorProps) {
});
const DocumentInfo = (props: {
- item:
- | PreviewItemAccess
- | PreviewProjectAccess
- | PreviewDocumentAccess
- | PreviewChannelAccess;
+ item: AccessiblePreviewItem;
blockName: string;
}) => {
return (
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/decorator/DocumentMention.tsx b/js/app/packages/core/component/LexicalMarkdown/component/decorator/DocumentMention.tsx
index 582b3c8b0e..38b739723a 100644
--- a/js/app/packages/core/component/LexicalMarkdown/component/decorator/DocumentMention.tsx
+++ b/js/app/packages/core/component/LexicalMarkdown/component/decorator/DocumentMention.tsx
@@ -9,20 +9,14 @@ import {
mentionsAccessories,
PopupPreview,
} from '@core/component/DocumentPreview';
-import { EntityIcon } from '@core/component/EntityIcon';
+import { useItemPreviewData } from '@core/component/ItemPreview';
import { resolveBlockAlias, verifyBlockName } from '@core/constant/allBlocks';
import { ENABLE_BLOCK_IN_BLOCK } from '@core/constant/featureFlags';
import { URL_PARAMS as CHANNEL_URL_PARAMS } from '@block-channel/constants';
import { canNestBlock } from '@core/orchestrator';
import {
isAccessiblePreviewItem,
- type PreviewChannelAccess,
- type PreviewDocumentAccess,
- type PreviewItem,
- type PreviewItemAccess,
type PreviewItemNoAccess,
- type PreviewProjectAccess,
- useItemPreview,
type ItemEntity,
} from '@queries/preview';
import { matches } from '@core/util/match';
@@ -98,101 +92,68 @@ function Loading(props: { collapsed?: boolean }) {
);
}
-type AccessiblePreviewItem =
- | PreviewItemAccess
- | PreviewProjectAccess
- | PreviewDocumentAccess
- | PreviewChannelAccess;
-
-function isAccessible(item: PreviewItem): item is AccessiblePreviewItem {
- return isAccessiblePreviewItem(item);
-}
-
function InlinePreview(props: {
- item: () => PreviewItem;
+ entity: ItemEntity;
blockName: BlockName | BlockAlias;
blockParams: Record<string, string>;
theme?: EditorThemeClasses;
collapsed?: boolean;
}) {
+ const { item, ItemEntityIcon } = useItemPreviewData(() => props.entity);
+
return (
<Switch>
- <Match when={props.item().loading}>
+ <Match when={item().loading}>
<Loading />
</Match>
- <Match when={matches(props.item(), isAccessible)}>
- {(accessibleItem) => {
- const { type, fileType, channelType, subType } = accessibleItem();
- return (
- <MentionContainer
- icon={
- <Show
- when={type === 'channel'}
- fallback={
- <EntityIcon
- targetType={
- type === 'document' ? (subType?.type ?? fileType) : type
- }
- size="fill"
- theme={
- props.theme?.['document-mention'] === 'chat-blue'
- ? 'monochrome'
- : undefined
- }
- />
- }
- >
- <EntityIcon
- size="fill"
- targetType={
- channelType === 'direct_message'
- ? 'directMessage'
- : channelType === 'organization'
- ? 'company'
- : 'channel'
- }
- />
- </Show>
- }
- text={
- <span
- data-document-mention="true"
- data-document-id={accessibleItem().id}
- data-block-name={props.blockName}
- data-document-name={accessibleItem().name}
- >
- {accessibleItem().name.replaceAll('\n', ' ').trim()}
- <span class="relative text-[0.8em] text-current/50 rounded-xs">
- {(() => {
- const accessories = mentionsAccessories(
- props.blockName as BlockName,
- props.blockParams
+ <Match when={matches(item(), isAccessiblePreviewItem)}>
+ {(accessibleItem) => (
+ <MentionContainer
+ icon={
+ <ItemEntityIcon
+ size="fill"
+ theme={
+ accessibleItem().type !== 'channel' &&
+ props.theme?.['document-mention'] === 'chat-blue'
+ ? 'monochrome'
+ : undefined
+ }
+ />
+ }
+ text={
+ <span
+ data-document-mention="true"
+ data-document-id={accessibleItem().id}
+ data-block-name={props.blockName}
+ data-document-name={accessibleItem().name}
+ >
+ {accessibleItem().name.replaceAll('\n', ' ').trim()}
+ <span class="relative text-[0.8em] text-current/50 rounded-xs">
+ {(() => {
+ const accessories = mentionsAccessories(
+ props.blockName as BlockName,
+ props.blockParams
+ );
+ if (accessories) {
+ return (
+ <>
+ {` ${accessories.note ?? ''}`}
+ {getMentionsIcon(accessories.icon)}
+ </>
);
- if (accessories) {
- return (
- <>
- {` ${accessories.note ?? ''}`}
- {getMentionsIcon(accessories.icon)}
- </>
- );
- }
- })()}
- </span>
+ }
+ })()}
</span>
- }
- collapsed={props.collapsed}
- />
- );
- }}
+ </span>
+ }
+ collapsed={props.collapsed}
+ />
+ )}
</Match>
- <Match
- when={(props.item() as PreviewItemNoAccess).access === 'no_access'}
- >
+ <Match when={(item() as PreviewItemNoAccess).access === 'no_access'}>
<MentionContainer icon={<EyeSlashDuo />} text="No Access" />
</Match>
- <Match
- when={(props.item() as PreviewItemNoAccess).access === 'does_not_exist'}
- >
+ <Match when={(item() as PreviewItemNoAccess).access === 'does_not_exist'}>
<MentionContainer icon={<TrashSimple />} text="Deleted" />
</Match>
</Switch>
@@ -235,16 +196,14 @@ export function DocumentMentionInner(props: DocumentMentionDecoratorProps) {
return canNestBlock(resolveBlockAlias(blockName), currentBlockName);
});
- const previewType = () =>
- blockNameToItemType(verifyBlockName(props.blockName));
-
const itemEntity = (): ItemEntity => {
+ const previewType = blockNameToItemType(verifyBlockName(props.blockName));
const baseEntity = {
id: props.documentId,
- type: previewType(),
+ type: previewType,
};
if (
- previewType() === 'channel' &&
+ previewType === 'channel' &&
props.blockParams &&
CHANNEL_URL_PARAMS.message in props.blockParams
) {
@@ -256,7 +215,7 @@ export function DocumentMentionInner(props: DocumentMentionDecoratorProps) {
return baseEntity;
};
- const [item] = useItemPreview(itemEntity);
+ const { item } = useItemPreviewData(itemEntity);
const isSelectedAsNode = createMemo(() => {
const sel = selection();
@@ -361,7 +320,7 @@ export function DocumentMentionInner(props: DocumentMentionDecoratorProps) {
</Match>
<Match when={item()}>
<InlinePreview
- item={item}
+ entity={itemEntity()}
blockName={verifyBlockName(props.blockName)}
blockParams={props.blockParams || {}}
theme={props.theme}
@@ -375,7 +334,6 @@ export function DocumentMentionInner(props: DocumentMentionDecoratorProps) {
}
content={
<PopupPreview
- item={item}
mouseEnter={() => {}}
mouseLeave={() => {}}
delete={editor?.isEditable() ? deleteMention : undefined}
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/decorator/Snapshot.tsx b/js/app/packages/core/component/LexicalMarkdown/component/decorator/Snapshot.tsx
index 1fa833a57d..cece90610a 100644
--- a/js/app/packages/core/component/LexicalMarkdown/component/decorator/Snapshot.tsx
+++ b/js/app/packages/core/component/LexicalMarkdown/component/decorator/Snapshot.tsx
@@ -186,7 +186,6 @@ function SnapshotInner(props: SnapshotDecoratorProps) {
}
content={
<PopupPreview
- item={item}
mouseEnter={() => {}}
mouseLeave={() => {}}
delete={editor?.isEditable() ? deleteSnapshot : undefined}
diff --git a/js/app/packages/core/component/NotificationRenderer.tsx b/js/app/packages/core/component/NotificationRenderer.tsx
index 0dc4359936..083dc792c4 100644
--- a/js/app/packages/core/component/NotificationRenderer.tsx
+++ b/js/app/packages/core/component/NotificationRenderer.tsx
@@ -46,10 +46,7 @@ export function NotificationRenderer(props: NotificationRendererProps) {
<span class="font-normal">{d().action}</span>
<Show when={d().target?.type === 'channel' && d().target?.id}>
<div class="self-center max-h-[1lh]">
- <InlineItemPreview
- itemId={d().target!.id!}
- itemType="channel"
- />
+ <InlineItemPreview id={d().target!.id!} type="channel" />
</div>
</Show>
<Show when={d().target?.name && d().target?.type !== 'channel'}>
@@ -67,10 +64,7 @@ export function NotificationRenderer(props: NotificationRendererProps) {
<div class="text-sm text-ink inline-flex items-center gap-1">
<span class="font-medium">{displayName()}</span> {d().action}{' '}
<Show when={d().target?.type === 'channel' && d().target?.id}>
- <InlineItemPreview
- itemId={d().target!.id!}
- itemType="channel"
- />
+ <InlineItemPreview id={d().target!.id!} type="channel" />
</Show>
<Show when={d().target?.name && d().target?.type !== 'channel'}>
<span class="font-medium">{d().target!.name}</span>
diff --git a/js/app/packages/core/component/Properties/hooks/usePropertyEntityDisplay.tsx b/js/app/packages/core/component/Properties/hooks/usePropertyEntityDisplay.tsx
index 0dcdbec020..fef7f18d3c 100644
--- a/js/app/packages/core/component/Properties/hooks/usePropertyEntityDisplay.tsx
+++ b/js/app/packages/core/component/Properties/hooks/usePropertyEntityDisplay.tsx
@@ -2,12 +2,7 @@ import { useChannelName } from '@core/context/channels';
import { EntityIcon as CoreEntityIcon } from '@core/component/EntityIcon';
import { UserIcon } from '@core/component/UserIcon';
import { fileTypeToBlockName } from '@core/constant/allBlocks';
-import {
- isAccessiblePreviewItem,
- type PreviewItem,
- type PreviewItemAccess,
- useItemPreview,
-} from '@queries/preview';
+import { isAccessiblePreviewItem, useItemPreview } from '@queries/preview';
import { tryMacroId, useDisplayName } from '@core/user';
import type { EntityType } from '@service-properties/generated/schemas/entityType';
import { type Accessor, createMemo, type JSX } from 'solid-js';
@@ -45,13 +40,6 @@ type PropertyEntityDisplayResult = {
linkParams: Accessor<Record<string, string> | undefined>;
};
-const checkPreviewItem = (item?: PreviewItem): item is PreviewItemAccess => {
- if (!item) return false;
- if (!isAccessiblePreviewItem(item)) return false;
- if (item.loading) return false;
- return true;
-};
-
/**
* Hook to resolve entity display information (name, icon) for property entity values.
* Handles preview fetching, channel name resolution, and user display names.
@@ -129,7 +117,7 @@ export function usePropertyEntityDisplay(
.with('TASK', () => <CoreEntityIcon targetType="task" size="xs" />)
.with('DOCUMENT', () => {
const item = preview();
- if (!checkPreviewItem(item)) {
+ if (!item || !isAccessiblePreviewItem(item)) {
return <CoreEntityIcon targetType="unknown" size="xs" />;
}
const { subType, fileType } = item;
@@ -157,7 +145,7 @@ export function usePropertyEntityDisplay(
.with('THREAD', () => 'email')
.with('DOCUMENT', () => {
const item = preview();
- if (!checkPreviewItem(item)) {
+ if (!item || !isAccessiblePreviewItem(item)) {
return null;
}
if (item.subType?.type === 'task') {
diff --git a/js/app/packages/core/component/RecipientSelector.tsx b/js/app/packages/core/component/RecipientSelector.tsx
index 4a2543897c..5c8a3c4c35 100644
--- a/js/app/packages/core/component/RecipientSelector.tsx
+++ b/js/app/packages/core/component/RecipientSelector.tsx
@@ -1,4 +1,4 @@
-import { CustomEntityIcon } from '@core/component/EntityIcon';
+import { CustomEntityIcon, channelTypeIcon } from '@core/component/EntityIcon';
import { toast } from '@core/component/Toast/Toast';
import { UserIcon } from '@core/component/UserIcon';
import {
@@ -12,9 +12,6 @@ import {
import { matches } from '@core/util/match';
import { clamp } from '@core/util/math';
import { truncateString } from '@core/util/string';
-import BuildingIcon from '@icon/duotone/building-office-duotone.svg';
-import GlobeIcon from '@icon/duotone/globe-duotone.svg';
-import ThreeUsersIcon from '@icon/duotone/users-three-duotone.svg';
import CheckIcon from '@icon/regular/check.svg';
import HashIcon from '@icon/regular/hash.svg';
import XIcon from '@icon/regular/x.svg';
@@ -24,7 +21,6 @@ import {
type ComboboxTriggerMode,
useComboboxContext,
} from '@kobalte/core/combobox';
-import type { Channel } from '@service-comms/generated/models/channel';
import { useEmail, useUserId } from '@core/context/user';
import { debounce } from '@solid-primitives/scheduled';
import { createFreshSearch, FreshSearchPresets } from '@core/util/freshSort';
@@ -116,21 +112,6 @@ function getRecipientOptionTextValue(option: CombinedRecipientItem) {
type RecipientComboboxItemProps = CollectionNode<CombinedRecipientItem>;
function RecipientComboboxItem(props: RecipientComboboxItemProps): JSX.Element {
- function channelTypeIcon(channel: Channel) {
- switch (channel.channel_type) {
- case 'direct_message':
- return UserIcon;
- case 'private':
- return ThreeUsersIcon;
- case 'organization':
- return BuildingIcon;
- case 'public':
- return GlobeIcon;
- default:
- return HashIcon;
- }
- }
-
const handleMouseEnter = () => {
const items = document.querySelectorAll('[data-highlighted]');
items.forEach((item) => {
@@ -190,7 +171,7 @@ function RecipientComboboxItem(props: RecipientComboboxItemProps): JSX.Element {
<Combobox.ItemLabel class="flex flex-row w-full gap-1.5 text-ink-muted select-none text-sm">
<div class="flex flex-col items-center justify-center p-1">
<CustomEntityIcon
- icon={channelTypeIcon(item().data)}
+ icon={channelTypeIcon(item().data.channel_type)}
size="xs"
/>
</div>
diff --git a/js/app/packages/core/component/References.tsx b/js/app/packages/core/component/References.tsx
index 2bb2a2194e..2250bdc186 100644
--- a/js/app/packages/core/component/References.tsx
+++ b/js/app/packages/core/component/References.tsx
@@ -194,10 +194,7 @@ export function References(props: ReferenceProps) {
<span class="text-ink-extra-muted">
{hasMessageContent ? 'referenced in' : 'attached in'}
</span>
- <InlineItemPreview
- itemId={ref.channel_id}
- itemType="channel"
- />
+ <InlineItemPreview id={ref.channel_id} type="channel" />
</span>
<Show when={hasMessageContent}>
<div class="pl-4 text-ink-muted text-xs">
@@ -237,8 +234,8 @@ export function References(props: ReferenceProps) {
<span class="font-medium text-ink">{userName()}</span>
<span class="text-ink-extra-muted">mentioned in</span>
<InlineItemPreview
- itemId={ref.source_entity_id}
- itemType={ref.source_entity_type as ItemType}
+ id={ref.source_entity_id}
+ type={ref.source_entity_type as ItemType}
/>
</span>
</button>
diff --git a/js/app/packages/core/internal/App.tsx b/js/app/packages/core/internal/App.tsx
index c01e4a1a26..8e4e7fcb41 100644
--- a/js/app/packages/core/internal/App.tsx
+++ b/js/app/packages/core/internal/App.tsx
@@ -184,9 +184,7 @@ const App: Component = () => {
<div class="w-full flex gap-2 justify-center flex-wrap">
<For each={testIds}>
{(item) => {
- return (
- <ItemPreview itemId={item.id} itemType={item.type as ItemType} />
- );
+ return <ItemPreview id={item.id} type={item.type as ItemType} />;
}}
</For>
</div>
diff --git a/js/app/packages/macro-entity/src/queries/rename.ts b/js/app/packages/macro-entity/src/queries/rename.ts
index 1cabe8a674..562a1575b7 100644
--- a/js/app/packages/macro-entity/src/queries/rename.ts
+++ b/js/app/packages/macro-entity/src/queries/rename.ts
@@ -12,8 +12,9 @@ import { queryKeys } from './key';
import { type InfiniteData, useMutation } from '@tanstack/solid-query';
import { toast } from '@core/component/Toast/Toast';
import type { SoupPage } from '@service-storage/generated/schemas';
-import { setPreviewData } from '@queries/preview';
+import { setPreviewName } from '@queries/preview';
import { setHistoryItemName } from '@queries/history/history';
+import { createCognitionWebsocketEffect } from '@service-cognition/websocket';
type RenamableEntity = Pick<EntityData, 'id' | 'type' | 'name'> &
Partial<EntityData>;
@@ -167,11 +168,12 @@ const renameChannelSetData = (
};
const renamePreviewSetData = (entities: EntityRenameData[]) => {
- entities.forEach(({ id, newName }) => {
- setPreviewData(id, (prev) => ({
- ...prev,
+ entities.forEach(({ id, newName, itemType }) => {
+ setPreviewName({
+ itemId: id,
name: newName,
- }));
+ itemType,
+ });
});
};
@@ -338,3 +340,33 @@ export function createBulkRenameDssEntityMutation() {
onSettled: bulkRenameOnSettled,
}));
}
+
+const CHAT_RENAME_TIMEOUT_MS = 20000;
+
+/**
+ * Waits for a chat rename to complete and updates the query cache(s).
+ * If noDispose is true, the effect will not be disposed after completion/timeout.
+ * Returns a dispose function to cancel the wait.
+ */
+export function useWaitChatRename(chatId: string, noDispose?: boolean) {
+ if (!noDispose) {
+ setTimeout(() => {
+ dispose();
+ }, CHAT_RENAME_TIMEOUT_MS);
+ }
+
+ const dispose = createCognitionWebsocketEffect('chat_renamed', (data) => {
+ if (data.chat_id !== chatId) return;
+ setHistoryItemName(chatId, data.name);
+ setPreviewName({
+ itemId: chatId,
+ name: data.name,
+ itemType: 'chat',
+ });
+ if (!noDispose) {
+ dispose();
+ }
+ });
+
+ return dispose;
+}
diff --git a/js/app/packages/queries/preview/index.ts b/js/app/packages/queries/preview/index.ts
index fabf5eb803..a4ef562058 100644
--- a/js/app/packages/queries/preview/index.ts
+++ b/js/app/packages/queries/preview/index.ts
@@ -3,15 +3,12 @@ export {
getItemPreview,
useItemPreview,
invalidatePreview,
- setPreviewData,
+ setPreviewName,
} from './preview';
export type {
PreviewItem,
PreviewItemNoAccess,
- PreviewItemAccess,
- PreviewProjectAccess,
- PreviewDocumentAccess,
- PreviewChannelAccess,
+ AccessiblePreviewItem,
ItemEntity,
MessageContext,
} from './types';
diff --git a/js/app/packages/queries/preview/preview.ts b/js/app/packages/queries/preview/preview.ts
index f01d5c4979..f9e55e162e 100644
--- a/js/app/packages/queries/preview/preview.ts
+++ b/js/app/packages/queries/preview/preview.ts
@@ -1,4 +1,4 @@
-import { DEFAULT_ITEM_TYPE } from '@service-storage/client';
+import { DEFAULT_ITEM_TYPE, type ItemType } from '@service-storage/client';
import { useQuery } from '@tanstack/solid-query';
import type { Accessor, Setter } from 'solid-js';
import { createMemo } from 'solid-js';
@@ -6,7 +6,7 @@ import { queryClient } from '../client';
import { previewDataLoader } from './dataloader';
import { defaultNameTransform, fetchMessageContext } from './fetchers';
import { previewKeys } from './keys';
-import type { ItemEntity, PreviewItem } from './types';
+import type { ItemEntity, PreviewItem, AccessiblePreviewItem } from './types';
import { queryReadyGate } from '@queries/gate';
const PREVIEW_STALE_TIME = 60 * 1000 * 60 * 24; // 24 hours
@@ -76,10 +76,54 @@ export function invalidatePreview(itemId?: string) {
});
}
+function getPreviewData(itemId: string): PreviewItem | undefined {
+ return queryClient.getQueryData<PreviewItem>(
+ previewKeys.item(itemId).queryKey
+ );
+}
+
/** Directly update preview data in the cache without refetching */
-export function setPreviewData(itemId: string, updater: Setter<PreviewItem>) {
+function setPreviewData(itemId: string, updater: Setter<PreviewItem>) {
return queryClient.setQueryData<PreviewItem>(
previewKeys.item(itemId).queryKey,
updater
);
}
+
+/** Sets the preview name in the cache. If the item is not in the cache,
+ * we will optimistically update the name and prefetch the item. */
+export function setPreviewName({
+ itemId,
+ name,
+ itemType,
+}: {
+ itemId: string;
+ name: string;
+ itemType?: ItemType;
+}) {
+ const prev = getPreviewData(itemId);
+ if (prev) return setPreviewData(itemId, (prev) => ({ ...prev, name }));
+
+ if (!itemType) {
+ console.warn('no preview item type provided for cache miss, using default');
+ }
+
+ let defaultPreviewItem: AccessiblePreviewItem = {
+ id: itemId,
+ name,
+ loading: false,
+ access: 'access',
+ type: itemType ?? DEFAULT_ITEM_TYPE,
+ };
+
+ // if the item isn't in the cache, we can optimistically create a new item
+ const res = setPreviewData(itemId, (_prev) => defaultPreviewItem);
+
+ // invalidate the item so that we can refetch on next render
+ // note that we cannot directly call the fetch here because the item name is not necessarily updated on the backend
+ queryClient.invalidateQueries({
+ queryKey: previewKeys.item(itemId).queryKey,
+ });
+
+ return res;
+}
diff --git a/js/app/packages/queries/preview/types.ts b/js/app/packages/queries/preview/types.ts
index 7d578c5f7d..f3bee6f81d 100644
--- a/js/app/packages/queries/preview/types.ts
+++ b/js/app/packages/queries/preview/types.ts
@@ -20,16 +20,17 @@ type BasePreviewItem<T extends ItemType = ItemType> = {
updatedAt?: number;
};
-export type PreviewItemAccess = {
+/** this is a catch-all type for access items that do not have a more specific type */
+type PreviewItemAccess = {
access: Extract<AccessType, 'access'>;
loading: false;
name: string;
fileType?: FileType;
subType?: SubType;
channelType?: never;
-} & BasePreviewItem<Exclude<ItemType, 'project'>>;
+} & BasePreviewItem<Exclude<ItemType, 'project' | 'document' | 'channel'>>;
-export type PreviewProjectAccess = {
+type PreviewProjectAccess = {
access: Extract<AccessType, 'access'>;
loading: false;
name: string;
@@ -38,11 +39,11 @@ export type PreviewProjectAccess = {
channelType?: never;
} & BasePreviewItem<'project'>;
-export type PreviewDocumentAccess = {
+type PreviewDocumentAccess = {
access: Extract<AccessType, 'access'>;
loading: false;
name: string;
- fileType: FileType;
+ fileType?: FileType;
subType?: SubType;
channelType?: never;
} & BasePreviewItem<'document'>;
@@ -57,16 +58,19 @@ export type PreviewChannelAccess = {
subType?: never;
channelType?: ChannelType;
messageContext?: MessageContext | undefined;
-} & BasePreviewItem<Exclude<ItemType, 'project'>>;
+} & BasePreviewItem<'channel'>;
-export type PreviewItem =
- | PreviewItemLoading
- | PreviewItemNoAccess
+export type AccessiblePreviewItem =
| PreviewItemAccess
| PreviewProjectAccess
| PreviewDocumentAccess
| PreviewChannelAccess;
+export type PreviewItem =
+ | PreviewItemLoading
+ | PreviewItemNoAccess
+ | AccessiblePreviewItem;
+
type BaseItemEntity = {
id: string;
type?: Exclude<ItemType, 'channel'>;
@@ -80,7 +84,9 @@ type ChannelItemEntity = {
export type ItemEntity = BaseItemEntity | ChannelItemEntity;
-export const isAccessiblePreviewItem = (item: PreviewItem) => {
+export const isAccessiblePreviewItem = (
+ item: PreviewItem
+): item is AccessiblePreviewItem => {
return !item.loading && item.access === 'access';
};