Skip to content

armgit / macro

Public Imported from GitHub
0

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

feat(channels): upgrade stand-alone-mentions to document cards in channels (#1163)

Seamus44fdb38596ab
diff --git a/js/app/packages/block-channel/component/BaseInput.tsx b/js/app/packages/block-channel/component/BaseInput.tsx
index 8f2cb4be5c..eddb4ae665 100644
--- a/js/app/packages/block-channel/component/BaseInput.tsx
+++ b/js/app/packages/block-channel/component/BaseInput.tsx
@@ -5,6 +5,7 @@ import {
import type { SendMessageArgs } from '@block-channel/signal/channel';
import { handleFileUpload } from '@block-channel/utils/inputAttachments';
import {
+ $convertSingleMentionToCard,
expandGroupParticipants,
toSimpleMention,
} from '@block-channel/utils/mentionExpansion';
@@ -16,7 +17,11 @@ import { useTaskMode } from '@block-channel/utils/useTaskMode';
import { isInBlock } from '@core/block';
import { LabelAndHotKey } from '@core/component/Tooltip';
import { FileDropOverlay } from '@core/component/FileDropOverlay';
-import { setEditorStateFromMarkdown } from '@core/component/LexicalMarkdown/utils';
+import {
+ pendingEditorState,
+ editorStateAsMarkdown,
+ setEditorStateFromMarkdown,
+} from '@core/component/LexicalMarkdown/utils';
import { fileFolderDrop } from '@core/directive/fileFolderDrop';
import { TOKENS } from '@core/hotkey/tokens';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
@@ -36,6 +41,7 @@ import PlusIcon from '@icon/regular/plus.svg';
import FormatIcon from '@icon/regular/text-aa.svg';
import Trash from '@icon/regular/trash.svg';
import XIcon from '@icon/regular/x.svg';
+import { $getRoot } from 'lexical';
import { logger } from '@observability';
import type { SimpleMention } from '@service-comms/generated/models/simpleMention';
import { staticFileClient } from '@service-static-files/client';
@@ -361,7 +367,18 @@ export function BaseInput(props: BaseInputProps) {
async function handleSend() {
if (isPendingSend()) return false;
setIsPendingSend(true);
- let content = markdownState();
+
+ const statePromise = pendingEditorState(editor);
+ editor.update(
+ () => {
+ $getRoot().markDirty();
+ $convertSingleMentionToCard();
+ },
+ { discrete: true }
+ );
+
+ const state = await statePromise;
+ let content = editorStateAsMarkdown(state);
const originalContent = content;
if (taskModeEnabled() && potentialTasks().length > 0) {
diff --git a/js/app/packages/block-channel/tests/mentionExpansion.test.ts b/js/app/packages/block-channel/tests/mentionExpansion.test.ts
deleted file mode 100644
index 4fd98d9549..0000000000
--- a/js/app/packages/block-channel/tests/mentionExpansion.test.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-import { describe, expect, it } from 'vitest';
-import {
- expandGroupParticipants,
- toSimpleMention,
-} from '../utils/mentionExpansion';
-
-describe('expandGroupParticipants', () => {
- it('converts participant IDs to SimpleMentions', () => {
- const seen = new Set<string>();
- const result = expandGroupParticipants(['u1', 'u2'], seen);
- expect(result).toEqual([
- { entity_type: 'user', entity_id: 'u1' },
- { entity_type: 'user', entity_id: 'u2' },
- ]);
- });
-
- it('deduplicates against seen set', () => {
- const seen = new Set(['u1']);
- const result = expandGroupParticipants(['u1', 'u2'], seen);
- expect(result).toEqual([{ entity_type: 'user', entity_id: 'u2' }]);
- });
-});
-
-describe('toSimpleMention', () => {
- it('converts user mention to SimpleMention', () => {
- const seen = new Set<string>();
- const result = toSimpleMention({ itemType: 'user', itemId: 'u1' }, seen);
- expect(result).toEqual({ entity_type: 'user', entity_id: 'u1' });
- });
-
- it('returns null for duplicate user mentions', () => {
- const seen = new Set(['u1']);
- const result = toSimpleMention({ itemType: 'user', itemId: 'u1' }, seen);
- expect(result).toBeNull();
- });
-
- it('passes through non-user types', () => {
- const seen = new Set<string>();
- const result = toSimpleMention(
- { itemType: 'document', itemId: 'd1' },
- seen
- );
- expect(result).toEqual({ entity_type: 'document', entity_id: 'd1' });
- });
-});
diff --git a/js/app/packages/block-channel/utils/mentionExpansion.ts b/js/app/packages/block-channel/utils/mentionExpansion.ts
index 946ea6f58d..131f2d88bb 100644
--- a/js/app/packages/block-channel/utils/mentionExpansion.ts
+++ b/js/app/packages/block-channel/utils/mentionExpansion.ts
@@ -1,4 +1,7 @@
+import { $isSingleDocumentMention } from '@core/component/LexicalMarkdown/utils';
+import { $convertMentionToCard, $isDocumentMentionNode } from '@lexical-core';
import type { SimpleMention } from '@service-comms/generated/models/simpleMention';
+import { $getRoot, $isParagraphNode } from 'lexical';
export type MentionItem = {
itemType: string;
@@ -36,3 +39,23 @@ export function toSimpleMention(
}
return { entity_type: mention.itemType, entity_id: mention.itemId };
}
+
+export function $convertSingleMentionToCard() {
+ if ($isSingleDocumentMention()) {
+ const root = $getRoot();
+ const rootChildren = root.getChildren();
+ if (rootChildren.length > 0) {
+ const firstChild = rootChildren[0];
+ if ($isParagraphNode(firstChild)) {
+ const paragraphChildren = firstChild.getChildren();
+ if (paragraphChildren.length > 0) {
+ const mention = paragraphChildren[0];
+ console.log({ mention });
+ if ($isDocumentMentionNode(mention)) {
+ $convertMentionToCard(mention);
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx b/js/app/packages/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx
index e454c11eea..e8883dc274 100644
--- a/js/app/packages/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx
+++ b/js/app/packages/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx
@@ -15,6 +15,7 @@ import {
type ContactMentionNode,
type DateMentionNode,
DEFAULT_LANGUAGE,
+ type DocumentCardNode,
type DocumentMentionNode,
type EquationNode,
type GroupMentionNode,
@@ -62,6 +63,7 @@ import { forceSingleLine, setEditorStateFromMarkdown } from '../../utils';
import { StaticCodeBoxAccessory } from '../accessory/CodeBoxAccessory';
import { ContactMention as ContactMentionDecorator } from '../decorator/ContactMention';
import { DateMention as DateMentionDecorator } from '../decorator/DateMention';
+import { DocumentCard as DocumentCardDecorator } from '../decorator/DocumentCard';
import { DocumentMention as DocumentMentionDecorator } from '../decorator/DocumentMention';
import { GroupMention as GroupMentionDecorator } from '../decorator/GroupMention';
import { Equation as EquationDecorator } from '../decorator/Equation';
@@ -535,6 +537,17 @@ const Equation: RenderableEntity<EquationNode> = {
),
};
+const DocumentCard: RenderableEntity<DocumentCardNode> = {
+ guard: (node: LexicalNode): node is DocumentCardNode =>
+ node.__type === 'document-card',
+ render: (props) =>
+ DocumentCardDecorator({
+ ...props.node.exportComponentProps(),
+ key: props.node.getKey(),
+ theme: props.theme,
+ }),
+};
+
// Table rendering components for Lexical tables
const Table: RenderableElement<TableNode> = {
guard: (node: LexicalNode): node is TableNode => node.__type === 'table',
@@ -610,6 +623,7 @@ const InlineEntities: Array<RenderableEntity> = [
LineBreak,
UserMention,
DocumentMention,
+ DocumentCard,
ContactMention,
DateMention,
GroupMention,
diff --git a/js/app/packages/core/component/LexicalMarkdown/utils.ts b/js/app/packages/core/component/LexicalMarkdown/utils.ts
index 7d4cc9f016..0cade17300 100644
--- a/js/app/packages/core/component/LexicalMarkdown/utils.ts
+++ b/js/app/packages/core/component/LexicalMarkdown/utils.ts
@@ -21,6 +21,7 @@ import {
mergeRegister,
} from '@lexical/utils';
import {
+ $isDocumentMentionNode,
$isWatermarkNode,
ALL_TRANSFORMERS,
EXTERNAL_TRANSFORMERS,
@@ -1266,3 +1267,47 @@ export function forceSingleLine(editor: LexicalEditor) {
{ discrete: true, tag: 'force-single-line' }
);
}
+
+/**
+ * Check if the editor content is only a single document mention and nothing else.
+ * This is used to determine if a document mention should be converted to a card
+ * before sending in channels.
+ */
+export function $isSingleDocumentMention(): boolean {
+ const root = $getRoot();
+ const rootChildren = root.getChildren();
+
+ // Must have exactly one child
+ if (rootChildren.length !== 1) return false;
+
+ const firstChild = rootChildren[0];
+
+ // The child must be a paragraph
+ if (!$isParagraphNode(firstChild)) return false;
+
+ const paragraphChildren = firstChild.getChildren();
+
+ // The paragraph must have exactly one child
+ if (paragraphChildren.length !== 1) return false;
+
+ const onlyChild = paragraphChildren[0];
+
+ // That child must be a DocumentMentionNode
+ return $isDocumentMentionNode(onlyChild);
+}
+
+/**
+ * Resolves with the *next committed* EditorState, then unregisters itself.
+ * Useful when you're already inside an implicit update (e.g. command handler)
+ * and need the post-commit state.
+ */
+export function pendingEditorState(
+ editor: LexicalEditor
+): Promise<EditorState> {
+ return new Promise<EditorState>((resolve) => {
+ const unregister = editor.registerUpdateListener(({ editorState }) => {
+ unregister();
+ resolve(editorState);
+ });
+ });
+}
diff --git a/js/app/packages/lexical-core/node-list.ts b/js/app/packages/lexical-core/node-list.ts
index 186403d1ba..7599df06b4 100644
--- a/js/app/packages/lexical-core/node-list.ts
+++ b/js/app/packages/lexical-core/node-list.ts
@@ -114,6 +114,6 @@ export const RegisteredNodesByType: { [K in EditorType]: ValidNode[] } = {
'plain-text': [ParagraphNode, TextNode],
markdown: [...SupportedNodeTypes],
'markdown-sync': [...SupportedNodeTypes],
- chat: exclude([HeadingNode, ImageNode, VideoNode, DocumentCardNode]),
+ chat: exclude([HeadingNode, ImageNode, VideoNode]),
title: [ParagraphNode, TextNode, InlineSearchNode],
} as const;
diff --git a/js/app/packages/lexical-core/transformers/index.ts b/js/app/packages/lexical-core/transformers/index.ts
index bc758a6465..95aa9fb100 100644
--- a/js/app/packages/lexical-core/transformers/index.ts
+++ b/js/app/packages/lexical-core/transformers/index.ts
@@ -11,11 +11,13 @@ import {
import {
E_CONTACT_MENTION,
E_DATE_MENTION,
+ E_DOCUMENT_CARD,
E_DOCUMENT_MENTION,
E_GROUP_MENTION,
E_USER_MENTION,
I_CONTACT_MENTION,
I_DATE_MENTION,
+ I_DOCUMENT_CARD,
I_DOCUMENT_MENTION,
I_GROUP_MENTION,
I_USER_MENTION,
@@ -48,6 +50,7 @@ export const INTERNAL_TRANSFORMERS: Transformer[] = [
I_USER_MENTION,
I_GROUP_MENTION,
I_DOCUMENT_MENTION,
+ I_DOCUMENT_CARD,
I_CONTACT_MENTION,
I_DATE_MENTION,
I_TABLE_NODE,
@@ -70,6 +73,8 @@ export const EXTERNAL_TRANSFORMERS: Transformer[] = [
E_GROUP_MENTION,
I_DOCUMENT_MENTION, // for chat attachments
E_DOCUMENT_MENTION,
+ I_DOCUMENT_CARD, // for internal representation
+ E_DOCUMENT_CARD,
E_CONTACT_MENTION,
E_DATE_MENTION,
// order matters
@@ -101,6 +106,8 @@ export const ALL_TRANSFORMERS: Transformer[] = [
E_GROUP_MENTION,
I_DOCUMENT_MENTION,
E_DOCUMENT_MENTION,
+ I_DOCUMENT_CARD,
+ E_DOCUMENT_CARD,
I_CONTACT_MENTION,
E_CONTACT_MENTION,
I_DATE_MENTION,
diff --git a/js/app/packages/lexical-core/transformers/mentions.ts b/js/app/packages/lexical-core/transformers/mentions.ts
index 4b8bbe9fb0..b7fb14333b 100644
--- a/js/app/packages/lexical-core/transformers/mentions.ts
+++ b/js/app/packages/lexical-core/transformers/mentions.ts
@@ -5,6 +5,7 @@ import type {
import type { ElementNode, LexicalNode, TextNode } from 'lexical';
import { ContactMentionNode } from '../nodes/ContactMentionNode';
import { DateMentionNode } from '../nodes/DateMentionNode';
+import { DocumentCardNode } from '../nodes/DocumentCardNode';
import { DocumentMentionNode } from '../nodes/DocumentMentionNode';
import { GroupMentionNode } from '../nodes/GroupMentionNode';
import { UserMentionNode } from '../nodes/UserMentionNode';
@@ -313,3 +314,78 @@ export const E_GROUP_MENTION: ElementTransformer = {
return false;
},
};
+
+// Internal Document Cards
+
+export const I_DOCUMENT_CARD: ElementTransformer = {
+ dependencies: [DocumentCardNode],
+ type: 'element',
+ regExp: /<m-document-card>(.*?)<\/m-document-card>/,
+ export: (node) => {
+ if (!(node instanceof DocumentCardNode)) return null;
+ const data = JSON.stringify({
+ documentId: node.getDocumentId(),
+ blockName: node.getBlockName(),
+ documentName: node.getDocumentName(),
+ blockParams: node.getBlockParams(),
+ previewBox: node.getPreviewBox(),
+ previewData: node.getPreviewData(),
+ mentionUuid: node.getMentionUuid(),
+ });
+ return `<m-document-card>${data}</m-document-card>`;
+ },
+ replace: (
+ parentNode: ElementNode,
+ _children: Array<LexicalNode>,
+ match: Array<string>
+ ) => {
+ try {
+ const data = JSON.parse(match[1]);
+ for (const field of ['documentId', 'documentName', 'blockName']) {
+ if (!(field in data)) throw new Error(`Missing field ${field}`);
+ }
+ const documentCardNode = new DocumentCardNode(
+ data.documentId,
+ data.documentName,
+ data.blockName,
+ data.blockParams,
+ data.previewBox,
+ data.previewData,
+ data.mentionUuid
+ );
+ parentNode.replace(documentCardNode);
+ } catch (e) {
+ console.error('Error in I_DOCUMENT_CARD replace:', e);
+ }
+ },
+};
+
+// External Document Cards
+export const E_DOCUMENT_CARD: ElementTransformer = {
+ dependencies: [DocumentCardNode],
+ type: 'element',
+ regExp: /$^/,
+ export: (node) => {
+ if (!(node instanceof DocumentCardNode)) return null;
+
+ const documentName = node.getDocumentName();
+ const documentId = node.getDocumentId();
+ const blockType = node.getBlockName();
+
+ if (!documentName || !documentId || !blockType) {
+ return null;
+ }
+
+ const hostname = cleanHostname(window.location.hostname);
+ const documentUrl = `https://${hostname}/app/${blockType}/${documentId}`;
+ return `[${documentName}](${documentUrl})`;
+ },
+ replace: (
+ _parentNode: ElementNode,
+ _children: Array<LexicalNode>,
+ _match: Array<string>,
+ _isImport: boolean
+ ) => {
+ return false;
+ },
+};