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(channel): drag entities into channel input (#3821)

Peter Chinmance4293200810
diff --git a/js/app/packages/block-md/component/MarkdownEditor.tsx b/js/app/packages/block-md/component/MarkdownEditor.tsx
index f26c1ff42c..e0978f0830 100644
--- a/js/app/packages/block-md/component/MarkdownEditor.tsx
+++ b/js/app/packages/block-md/component/MarkdownEditor.tsx
@@ -98,8 +98,6 @@ import { createAccessoryStore } from '@core/component/LexicalMarkdown/plugins/no
import { restoreFocusPlugin } from '@core/component/LexicalMarkdown/plugins/restore-focus';
import { createMenuOperations } from '@core/component/LexicalMarkdown/shared/inlineMenu';
import {
- $insertWrappedAfter,
- $insertWrappedBefore,
editorFocusSignal,
editorIsEmpty,
getSaveState,
@@ -107,6 +105,11 @@ import {
initializeEditorWithState,
setEditorStateFromMarkdown,
} from '@core/component/LexicalMarkdown/utils';
+import {
+ getValidDragInsertPosition,
+ insertDocumentMentionAtDragInsertPosition,
+ updateDragInsertPreviewFromCoordinates,
+} from '@core/component/LexicalMarkdown/utils/dragInsertUtils';
import {
createFilesReadyHandler,
getDragDropPosition,
@@ -140,7 +143,6 @@ import { bufToString } from '@core/util/string';
import { handleFileFolderDrop } from '@core/util/upload';
import type { EntityDragEvent } from '@entity';
import {
- $createDocumentMentionNode,
$isInlineSearchNode,
AwaitNode,
CommentNode,
@@ -342,9 +344,9 @@ export function MarkdownEditor(props: {
const res = wrapDndEvent(event);
if (!res) return;
- const { key, position } = getDragDropPosition(editor, res.mousePos, true);
if (res.blockName === 'image' || res.blockName === 'video') {
+ getDragDropPosition(editor, res.mousePos, true);
editor.dispatchCommand(INSERT_MEDIA_COMMAND, {
type: 'dss',
id: res.id,
@@ -354,36 +356,29 @@ export function MarkdownEditor(props: {
}
if (res.blockName === undefined) return;
- if (!key || !position) return;
+ const dragInsertPosition = getValidDragInsertPosition(editor, res.mousePos);
+ if (!dragInsertPosition) return;
const mentionId = await trackMention(blockId, 'document', res.id);
- editor.update(() => {
- let blockParams: Record<string, string> | undefined;
- if (res.blockName === 'channel') {
- blockParams = {};
- if (res.item.messageId) {
- blockParams[CHANNEL_PARAMS.message] = res.item.messageId;
- }
- if (res.item.threadId) {
- blockParams[CHANNEL_PARAMS.thread] = res.item.threadId;
- }
+ let blockParams: Record<string, string> | undefined;
+ if (res.blockName === 'channel') {
+ blockParams = {};
+ if (res.item.messageId) {
+ blockParams[CHANNEL_PARAMS.message] = res.item.messageId;
}
- const mention = $createDocumentMentionNode({
- documentId: res.id,
- documentName: res.item.name,
- blockName: res.blockName,
- blockParams,
- mentionUuid: mentionId,
- createdAt: Date.now(),
- });
-
- if (position === 'before') {
- $insertWrappedBefore(key, mention);
- } else {
- $insertWrappedAfter(key, mention);
+ if (res.item.threadId) {
+ blockParams[CHANNEL_PARAMS.thread] = res.item.threadId;
}
- mention.selectEnd();
+ }
+
+ insertDocumentMentionAtDragInsertPosition(editor, dragInsertPosition, {
+ documentId: res.id,
+ documentName: res.item.name,
+ blockName: res.blockName,
+ blockParams,
+ mentionUuid: mentionId,
+ createdAt: Date.now(),
});
};
@@ -394,10 +389,11 @@ export function MarkdownEditor(props: {
const res = wrapDndEvent(event);
if (!res) return;
const { mousePos } = res;
- const { key, position } = getDragDropPosition(editor, mousePos, false);
- if (key !== null && position !== null) {
- setDragInsertStore({ nodeKey: key, position, visible: true });
- }
+ updateDragInsertPreviewFromCoordinates({
+ editor,
+ coordinates: mousePos,
+ setState: setDragInsertStore,
+ });
}, 60);
onDragEnd((event: EntityDragEvent) => {
diff --git a/js/app/packages/channel/Channel/Channel.tsx b/js/app/packages/channel/Channel/Channel.tsx
index dccd5bb2d7..1cf54e6051 100644
--- a/js/app/packages/channel/Channel/Channel.tsx
+++ b/js/app/packages/channel/Channel/Channel.tsx
@@ -236,7 +236,6 @@ export function Channel(props: ChannelProps) {
const dragState = createChannelDragState({
channelId: props.channelId,
- attachmentTracker,
});
const channelName = useChannelName(props.channelId);
@@ -559,6 +558,7 @@ export function Channel(props: ChannelProps) {
})}
onReady={(handle) => {
dragState.setAttachFilesToChannel(handle.attachFiles);
+ dragState.setEntityMentionInputHandlers(handle);
setChannelInputHandle(handle);
}}
onChange={(snapshot) =>
diff --git a/js/app/packages/channel/Channel/create-channel-drag-state.ts b/js/app/packages/channel/Channel/create-channel-drag-state.ts
index df68b3a56b..645e4e7568 100644
--- a/js/app/packages/channel/Channel/create-channel-drag-state.ts
+++ b/js/app/packages/channel/Channel/create-channel-drag-state.ts
@@ -1,11 +1,12 @@
+import type { EntityData } from '@entity';
import { type Accessor, createSignal } from 'solid-js';
-import type { InputAttachmentTracker } from '../Input';
-import { createInputAttachmentTracker } from '../Input';
-import { createEntityDropZone } from './create-entity-drop-zone';
+import {
+ createEntityDropZone,
+ type EntityDropCoordinates,
+} from './create-entity-drop-zone';
type CreateChannelDragStateOptions = {
channelId: string;
- attachmentTracker: InputAttachmentTracker;
};
export type ChannelDragState = {
@@ -16,18 +17,36 @@ export type ChannelDragState = {
setIsValidChannelDrag: (value: boolean) => void;
attachFilesToChannel: ((files: File[]) => Promise<void>) | undefined;
setAttachFilesToChannel: (fn: (files: File[]) => Promise<void>) => void;
+ setEntityMentionInputHandlers: (handlers: {
+ insertEntityMention?: (
+ entity: EntityData,
+ coordinates?: EntityDropCoordinates
+ ) => void;
+ previewEntityMentionInsertion?: (
+ coordinates: EntityDropCoordinates
+ ) => void;
+ clearEntityMentionInsertionPreview?: () => void;
+ }) => void;
};
export function createChannelDragState(
options: CreateChannelDragStateOptions
): ChannelDragState {
- const tracker = createInputAttachmentTracker();
const [isDraggingOverChannel, setIsDraggingOverChannel] = createSignal(false);
const [isValidChannelDrag, setIsValidChannelDrag] = createSignal(true);
+ let entityMentionInputHandlers: Parameters<
+ ChannelDragState['setEntityMentionInputHandlers']
+ >[0] = {};
+
const entityDropZone = createEntityDropZone({
droppableId: `channel-entity-drop-${options.channelId}`,
- tracker,
+ onDropEntity: (entity, coordinates) =>
+ entityMentionInputHandlers.insertEntityMention?.(entity, coordinates),
+ onDragEntityMove: (coordinates) =>
+ entityMentionInputHandlers.previewEntityMentionInsertion?.(coordinates),
+ onDragEntityEnd: () =>
+ entityMentionInputHandlers.clearEntityMentionInsertionPreview?.(),
});
let attachFilesToChannel: ((files: File[]) => Promise<void>) | undefined;
@@ -45,5 +64,8 @@ export function createChannelDragState(
setAttachFilesToChannel: (fn) => {
attachFilesToChannel = fn;
},
+ setEntityMentionInputHandlers: (handlers) => {
+ entityMentionInputHandlers = handlers;
+ },
};
}
diff --git a/js/app/packages/channel/Channel/create-entity-drop-zone.ts b/js/app/packages/channel/Channel/create-entity-drop-zone.ts
index a9a2ecec3f..972b0cde4e 100644
--- a/js/app/packages/channel/Channel/create-entity-drop-zone.ts
+++ b/js/app/packages/channel/Channel/create-entity-drop-zone.ts
@@ -1,11 +1,23 @@
-import type { EntityDragData, EntityDragEvent } from '@entity';
+import type { EntityData, EntityDragData, EntityDragEvent } from '@entity';
import { createDroppable, useDragDropContext } from '@thisbeyond/solid-dnd';
import { type Accessor, createMemo } from 'solid-js';
-import type { InputAttachmentTracker } from '../Input';
+
+export type EntityDropCoordinates = {
+ clientX: number;
+ clientY: number;
+};
type CreateEntityDropZoneOptions = {
droppableId: string;
- tracker: InputAttachmentTracker;
+ /** Called when a soup entity is dropped onto this zone. */
+ onDropEntity: (
+ entity: EntityData,
+ coordinates?: EntityDropCoordinates
+ ) => void;
+ /** Called while a soup entity is dragged over this zone. */
+ onDragEntityMove?: (coordinates: EntityDropCoordinates) => void;
+ /** Called when the active entity drag leaves this zone or ends. */
+ onDragEntityEnd?: () => void;
};
type EntityDropZone = {
@@ -18,11 +30,24 @@ export function createEntityDropZone(
): EntityDropZone {
const droppable = createDroppable(options.droppableId);
- const [state, { onDragEnd }] = useDragDropContext() ?? [
+ const [state, { onDragEnd, onDragMove }] = useDragDropContext() ?? [
undefined,
- { onDragEnd: () => {} },
+ { onDragEnd: () => {}, onDragMove: () => {} },
];
+ const currentCoordinates = (): EntityDropCoordinates | undefined => {
+ const coordinates = state?.active.sensor?.coordinates.current;
+ if (!coordinates) return undefined;
+ return {
+ clientX: coordinates.x,
+ clientY: coordinates.y,
+ };
+ };
+
+ const isOverThisDropZone = () =>
+ droppable.isActiveDroppable ||
+ state?.active.droppable?.id === options.droppableId;
+
const entityDragData = createMemo(() => {
const draggable = state?.active.draggable;
if (!draggable) return;
@@ -40,20 +65,27 @@ export function createEntityDropZone(
});
onDragEnd((event: EntityDragEvent) => {
+ const data = event.draggable?.data;
+ if (!data || data.dragType !== 'entity') return;
+
+ options.onDragEntityEnd?.();
if (!event.droppable) return;
if (event.droppable.id !== options.droppableId) return;
- const data = event.draggable?.data;
- if (!data || data.dragType !== 'entity') return;
+ const coordinates = currentCoordinates();
+ options.onDropEntity(data, coordinates);
+ });
- const fileType = 'fileType' in data ? data.fileType : undefined;
+ onDragMove((event: EntityDragEvent) => {
+ const data = event.draggable?.data;
+ if (!data || data.dragType !== 'entity' || !isOverThisDropZone()) {
+ options.onDragEntityEnd?.();
+ return;
+ }
- options.tracker.addAttachment({
- id: data.id,
- name: data.name,
- kind: 'document',
- iconType: fileType ?? data.type,
- });
+ const coordinates = currentCoordinates();
+ if (!coordinates) return;
+ options.onDragEntityMove?.(coordinates);
});
return { droppable, isDraggingOver };
diff --git a/js/app/packages/channel/Input/ChannelInput.tsx b/js/app/packages/channel/Input/ChannelInput.tsx
index 1dcbeaa896..43ce287d26 100644
--- a/js/app/packages/channel/Input/ChannelInput.tsx
+++ b/js/app/packages/channel/Input/ChannelInput.tsx
@@ -1,4 +1,14 @@
import { MarkdownShell } from '@core/component/LexicalMarkdown/builder/MarkdownShell';
+import { DragInsertIndicator } from '@core/component/LexicalMarkdown/component/misc/DragInsertIndicator';
+import {
+ createDragInsertStore,
+ INSERT_DOCUMENT_MENTION_COMMAND,
+} from '@core/component/LexicalMarkdown/plugins';
+import {
+ clearDragInsertPreview,
+ insertDocumentMentionAtDragCoordinates,
+ updateDragInsertPreviewFromCoordinates,
+} from '@core/component/LexicalMarkdown/utils/dragInsertUtils';
import { registerHotkey, useHotkeyDOMScope } from '@core/hotkey/hotkeys';
import { isMobile } from '@core/mobile/isMobile';
import type { IUser } from '@core/user/types';
@@ -8,8 +18,10 @@ import {
handleFileFolderDrop,
uploadFile,
} from '@core/util/upload';
+import type { EntityData } from '@entity';
import { isIOS } from '@solid-primitives/platform';
import { Surface } from '@ui';
+import { $getRoot } from 'lexical';
import {
type Accessor,
createSignal,
@@ -27,6 +39,7 @@ import { FormatButtons } from './FormatButtons';
import { Input } from './Input';
import { createMentionsTracker } from './mentions-tracker';
import type {
+ EntityMentionInsertCoordinates,
InputAttachmentTracker,
InputCallbacks,
InputData,
@@ -35,6 +48,7 @@ import type {
} from './types';
import { isReplyInput } from './types';
import { uploadInputAttachments } from './upload-attachments';
+import { entityToDocumentMentionInfo } from './utils/entity-mention';
import { applyInlineFormat, applyNodeFormat } from './utils/formatting';
export type ChannelInputProps = InputCallbacks & {
@@ -200,6 +214,25 @@ export function ChannelInput(props: ChannelInputProps) {
},
onAttachFromDisk: (files) => inputState.commands.attachFiles(files),
});
+ const markdownHandle = markdownEditor.buildHandle();
+ const lexicalEditor = () => markdownHandle.lexical;
+ const [entityDragInsertStore, setEntityDragInsertStore] =
+ createDragInsertStore();
+
+ const isInsideEditorDropBounds = (
+ coordinates: EntityMentionInsertCoordinates
+ ) => {
+ const rect =
+ scrollContainer()?.getBoundingClientRect() ??
+ lexicalEditor().getRootElement()?.getBoundingClientRect();
+ if (!rect) return false;
+ return (
+ coordinates.clientX >= rect.left &&
+ coordinates.clientX <= rect.right &&
+ coordinates.clientY >= rect.top &&
+ coordinates.clientY <= rect.bottom
+ );
+ };
// On iOS, blur before clearing so dictation finalizes and discards its buffer
// (otherwise it re-injects the sent text into the cleared editor). Re-focus
// via rAF so the keyboard stays up: rAF fires after Lexical's update commits,
@@ -214,10 +247,56 @@ export function ChannelInput(props: ChannelInputProps) {
}
};
+ const previewEntityMentionInsertion = (
+ coordinates: EntityMentionInsertCoordinates
+ ) => {
+ updateDragInsertPreviewFromCoordinates({
+ editor: lexicalEditor(),
+ coordinates,
+ setState: setEntityDragInsertStore,
+ isValidDropTarget: isInsideEditorDropBounds,
+ });
+ };
+
+ const clearEntityMentionInsertionPreview = () => {
+ clearDragInsertPreview(setEntityDragInsertStore);
+ };
+
+ // Insert a mention for an entity dragged in from the soup. When the drop
+ // happens over editor content, mirror markdown documents by inserting before
+ // or after the nearest top-level node; otherwise keep the old append fallback.
+ const insertEntityMention = (
+ entity: EntityData,
+ coordinates?: EntityMentionInsertCoordinates
+ ) => {
+ clearEntityMentionInsertionPreview();
+ const mentionInfo = entityToDocumentMentionInfo(entity);
+ if (!mentionInfo) return;
+
+ if (
+ !insertDocumentMentionAtDragCoordinates({
+ editor: lexicalEditor(),
+ coordinates,
+ mentionInfo,
+ isValidDropTarget: isInsideEditorDropBounds,
+ })
+ ) {
+ const editor = lexicalEditor();
+ editor.update(() => {
+ $getRoot().selectEnd();
+ });
+ editor.dispatchCommand(INSERT_DOCUMENT_MENTION_COMMAND, mentionInfo);
+ }
+ markdownEditor.controls.focus();
+ };
+
props.onReady?.({
clear: () => markdownEditor.controls.clear(),
focus: () => markdownEditor.controls.focus(),
attachFiles: (files) => inputState.commands.attachFiles(files),
+ insertEntityMention,
+ previewEntityMentionInsertion,
+ clearEntityMentionInsertionPreview,
restoreSnapshot: (snapshot) => {
if (!isEditorConnected) {
pendingRestoreSnapshot = snapshot;
@@ -295,6 +374,11 @@ export function ChannelInput(props: ChannelInputProps) {
flushPendingRestore();
}}
/>
+ <DragInsertIndicator
+ editor={lexicalEditor()}
+ state={entityDragInsertStore}
+ active
+ />
</Input.Editor>
</Input.EditorShell>
<Input.Attachments kind="media" />
diff --git a/js/app/packages/channel/Input/tests/entity-mention.test.ts b/js/app/packages/channel/Input/tests/entity-mention.test.ts
new file mode 100644
index 0000000000..68e5846f46
--- /dev/null
+++ b/js/app/packages/channel/Input/tests/entity-mention.test.ts
@@ -0,0 +1,117 @@
+import type {
+ ChannelEntity,
+ ChannelMessageEntity,
+ DocumentEntity,
+ EntityData,
+} from '@entity';
+import { describe, expect, it, vi } from 'vitest';
+import { entityToDocumentMentionInfo } from '../utils/entity-mention';
+
+vi.mock('@core/constant/allBlocks', () => ({
+ itemToBlockName: (entity: EntityData) => {
+ if (entity.type === 'document') {
+ return entity.fileType === 'md' ? 'md' : 'unknown';
+ }
+ if (entity.type === 'channel' || entity.type === 'channel_message') {
+ return 'channel';
+ }
+ return entity.type;
+ },
+}));
+
+const base = {
+ ownerId: 'owner-1',
+};
+
+describe('entityToDocumentMentionInfo', () => {
+ it('builds a document mention for a document entity', () => {
+ const entity: DocumentEntity = {
+ ...base,
+ type: 'document',
+ id: 'doc-1',
+ name: 'My Doc',
+ fileType: 'md',
+ };
+
+ expect(entityToDocumentMentionInfo(entity)).toEqual({
+ documentId: 'doc-1',
+ documentName: 'My Doc',
+ blockName: 'md',
+ channelType: undefined,
+ });
+ });
+
+ it('builds a channel mention deep-linked to the message and thread', () => {
+ const entity: ChannelMessageEntity = {
+ ...base,
+ type: 'channel_message',
+ id: 'channel-1:msg-1',
+ name: 'feature-requests',
+ channelId: 'channel-1',
+ channelName: 'feature-requests',
+ channelType: 'public',
+ messageId: 'msg-1',
+ threadId: 'thread-1',
+ senderId: 'sender-1',
+ content: 'hello',
+ };
+
+ expect(entityToDocumentMentionInfo(entity)).toEqual({
+ documentId: 'channel-1',
+ documentName: 'feature-requests',
+ blockName: 'channel',
+ blockParams: {
+ channel_message_id: 'msg-1',
+ channel_thread_id: 'thread-1',
+ },
+ channelType: 'public',
+ });
+ });
+
+ it('omits the thread param when a channel message has no thread', () => {
+ const entity: ChannelMessageEntity = {
+ ...base,
+ type: 'channel_message',
+ id: 'channel-1:msg-1',
+ name: 'feature-requests',
+ channelId: 'channel-1',
+ channelName: 'feature-requests',
+ channelType: 'public',
+ messageId: 'msg-1',
+ senderId: 'sender-1',
+ content: 'hello',
+ };
+
+ const info = entityToDocumentMentionInfo(entity);
+ expect(info?.blockParams).toEqual({ channel_message_id: 'msg-1' });
+ });
+
+ it('returns undefined when the entity has no recognizable block', () => {
+ const entity: DocumentEntity = {
+ ...base,
+ type: 'document',
+ id: 'doc-1',
+ name: 'Mystery',
+ fileType: 'not-a-real-file-type',
+ };
+
+ expect(entityToDocumentMentionInfo(entity)).toBeUndefined();
+ });
+
+ it('carries the channel type for a channel entity', () => {
+ const entity: ChannelEntity = {
+ ...base,
+ type: 'channel',
+ id: 'channel-1',
+ name: 'feature-requests',
+ channelType: 'private',
+ };
+
+ expect(entityToDocumentMentionInfo(entity)).toEqual({
+ documentId: 'channel-1',
+ documentName: 'feature-requests',
+ blockName: 'channel',
+ channelType: 'private',
+ });
+ });
+});
diff --git a/js/app/packages/channel/Input/tests/input-slots.test.tsx b/js/app/packages/channel/Input/tests/input-slots.test.tsx
index 6a0e1889f2..adc407621a 100644
--- a/js/app/packages/channel/Input/tests/input-slots.test.tsx
+++ b/js/app/packages/channel/Input/tests/input-slots.test.tsx
@@ -93,6 +93,24 @@ vi.mock(
'@core/component/LexicalMarkdown/builder/MarkdownConfigBuilder',
() => ({
buildConfig: () => {
+ const controls = {
+ clear: vi.fn(),
+ focus: vi.fn(),
+ };
+ const lexical = {
+ focus: vi.fn(),
+ dispatchCommand: vi.fn(),
+ getElementByKey: vi.fn(),
+ getRootElement: vi.fn(),
+ update: vi.fn((callback: () => void) => callback()),
+ };
+ const handle = {
+ controls,
+ lexical,
+ plugins: { use: vi.fn() },
+ selection: undefined,
+ _internal: {},
+ };
const builder: any = {
namespace: () => builder,
withMentions: () => builder,
@@ -107,14 +125,9 @@ vi.mock(
use: () => builder,
onChange: () => builder,
onEnter: () => builder,
- controls: {
- clear: vi.fn(),
- focus: vi.fn(),
- },
- lexical: {
- focus: vi.fn(),
- dispatchCommand: vi.fn(),
- },
+ buildHandle: () => handle,
+ controls,
+ lexical,
selection: undefined,
};
return builder;
@@ -123,7 +136,12 @@ vi.mock(
);
vi.mock('@core/component/LexicalMarkdown/plugins', () => ({
+ createDragInsertStore: () => [
+ { nodeKey: null, position: null, visible: false },
+ vi.fn(),
+ ],
DefaultShortcuts: {},
+ INSERT_DOCUMENT_MENTION_COMMAND: 'INSERT_DOCUMENT_MENTION_COMMAND',
NODE_TRANSFORM: 'NODE_TRANSFORM',
keyboardShortcutsPlugin: () => () => () => {},
}));
diff --git a/js/app/packages/channel/Input/types.ts b/js/app/packages/channel/Input/types.ts
index 4a0966da67..14712acc65 100644
--- a/js/app/packages/channel/Input/types.ts
+++ b/js/app/packages/channel/Input/types.ts
@@ -1,5 +1,6 @@
import type { EntityIconSelector } from '@core/component/EntityIcon';
import type { ItemMention } from '@core/component/LexicalMarkdown/plugins';
+import type { EntityData } from '@entity';
import type { PersistenceKey } from '@queries/persistence';
import type { InputAttachmentTracker as Tracker } from './attachment-tracker';
@@ -48,6 +49,11 @@ export type InputSnapshot = {
attachments: InputAttachmentData[];
};
+export type EntityMentionInsertCoordinates = {
+ clientX: number;
+ clientY: number;
+};
+
export type InputCallbacks = {
onChange?: (snapshot: InputSnapshot) => void | Promise<void>;
onSend?: (snapshot: InputSnapshot) => void | Promise<void>;
@@ -74,6 +80,22 @@ export type InputHandle = {
focus: () => void;
attachFiles: (files: File[]) => Promise<void>;
restoreSnapshot: (snapshot: InputSnapshot) => void;
+ /**
+ * Inserts a mention for a dragged soup entity into the editor. Only provided
+ * by inputs that support entity drag-and-drop (e.g. channel inputs).
+ */
+ insertEntityMention?: (
+ entity: EntityData,
+ coordinates?: EntityMentionInsertCoordinates
+ ) => void;
+ /**
+ * Updates the insertion preview for a dragged soup entity. Coordinates are
+ * client-space pointer coordinates from the drag sensor.
+ */
+ previewEntityMentionInsertion?: (
+ coordinates: EntityMentionInsertCoordinates
+ ) => void;
+ clearEntityMentionInsertionPreview?: () => void;
};
export type InputAttachmentTracker = Tracker;
diff --git a/js/app/packages/channel/Input/utils/entity-mention.ts b/js/app/packages/channel/Input/utils/entity-mention.ts
new file mode 100644
index 0000000000..deae8502f2
--- /dev/null
+++ b/js/app/packages/channel/Input/utils/entity-mention.ts
@@ -0,0 +1,46 @@
+import { itemToBlockName } from '@core/constant/allBlocks';
+import type { EntityData } from '@entity';
+import type { DocumentMentionInfo } from '@lexical-core';
+
+// Keep these in sync with `@block-channel/constants` `URL_PARAMS`. They are
+// inlined here to avoid a circular dependency (`@block-channel` imports
+// `@channel`).
+const CHANNEL_MESSAGE_PARAM = 'channel_message_id';
+const CHANNEL_THREAD_PARAM = 'channel_thread_id';
+
+/**
+ * Converts a dragged soup entity into the payload needed to insert a document
+ * mention into a channel input. Mirrors the behavior of dropping an entity into
+ * a markdown document. Returns `undefined` when the entity cannot be mentioned.
+ */
+export function entityToDocumentMentionInfo(
+ entity: EntityData
+): DocumentMentionInfo | undefined {
+ const blockName = itemToBlockName(entity);
+ if (!blockName || blockName === 'unknown') return undefined;
+
+ // A dragged channel message mentions its parent channel, deep-linked to the
+ // specific message (and thread, when present).
+ if (entity.type === 'channel_message') {
+ const blockParams: Record<string, string> = {
+ [CHANNEL_MESSAGE_PARAM]: entity.messageId,
+ };
+ if (entity.threadId) {
+ blockParams[CHANNEL_THREAD_PARAM] = entity.threadId;
+ }
+ return {
+ documentId: entity.channelId,
+ documentName: entity.name,
+ blockName,
+ blockParams,
+ channelType: entity.channelType,
+ };
+ }
+
+ return {
+ documentId: entity.id,
+ documentName: entity.name,
+ blockName,
+ channelType: entity.type === 'channel' ? entity.channelType : undefined,
+ };
+}
diff --git a/js/app/packages/channel/Thread/ThreadReplyInput.tsx b/js/app/packages/channel/Thread/ThreadReplyInput.tsx
index 7e60eaa81e..ac1cebda34 100644
--- a/js/app/packages/channel/Thread/ThreadReplyInput.tsx
+++ b/js/app/packages/channel/Thread/ThreadReplyInput.tsx
@@ -45,13 +45,19 @@ export function ThreadReplyInput(props: ThreadReplyInputProps) {
initialAttachments: props.replyInputState()?.attachments,
});
+ const [replyInputHandle, setLocalReplyInputHandle] =
+ createSignal<InputHandle>();
+
const entityDropZone = createEntityDropZone({
droppableId: `thread-reply-entity-drop-${props.messageId}`,
- tracker,
+ onDropEntity: (entity, coordinates) =>
+ replyInputHandle()?.insertEntityMention?.(entity, coordinates),
+ onDragEntityMove: (coordinates) =>
+ replyInputHandle()?.previewEntityMentionInsertion?.(coordinates),
+ onDragEntityEnd: () =>
+ replyInputHandle()?.clearEntityMentionInsertionPreview?.(),
});
- const [replyInputHandle, setLocalReplyInputHandle] =
- createSignal<InputHandle>();
const setReplyInputHandle = (handle: InputHandle) => {
setLocalReplyInputHandle(handle);
props.setReplyInputHandle?.(handle);
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/misc/DragInsertIndicator.tsx b/js/app/packages/core/component/LexicalMarkdown/component/misc/DragInsertIndicator.tsx
index c42ad77e43..2237723917 100644
--- a/js/app/packages/core/component/LexicalMarkdown/component/misc/DragInsertIndicator.tsx
+++ b/js/app/packages/core/component/LexicalMarkdown/component/misc/DragInsertIndicator.tsx
@@ -1,3 +1,4 @@
+import type { LexicalEditor } from 'lexical';
import { Show, useContext } from 'solid-js';
import type { Store } from 'solid-js/store';
import { Portal } from 'solid-js/web';
@@ -7,9 +8,10 @@ import type { DragInsertState } from '../../plugins';
export function DragInsertIndicator(props: {
state: Store<DragInsertState>;
active: boolean;
+ editor?: LexicalEditor;
}) {
const lexicalWrapper = useContext(LexicalWrapperContext);
- const editor = () => lexicalWrapper?.editor;
+ const editor = () => props.editor ?? lexicalWrapper?.editor;
const elementRect = () => {
const key = props.state.nodeKey;
diff --git a/js/app/packages/core/component/LexicalMarkdown/utils.ts b/js/app/packages/core/component/LexicalMarkdown/utils.ts
index ef498c4692..fa1610abf4 100644
--- a/js/app/packages/core/component/LexicalMarkdown/utils.ts
+++ b/js/app/packages/core/component/LexicalMarkdown/utils.ts
@@ -768,28 +768,6 @@ export default function caretFromPoint(
}
}
-export function $insertWrappedBefore(
- key: NodeKey,
- node: LexicalNode,
- wrapper: () => ElementNode = $createParagraphNode
-) {
- const targetNode = $getNodeByKey(key);
- if (!targetNode) return;
- const wrappedElem = wrapper().append(node);
- targetNode.insertBefore(wrappedElem);
-}
-
-export function $insertWrappedAfter(
- key: NodeKey,
- node: LexicalNode,
- wrapper: () => ElementNode = $createParagraphNode
-) {
- const targetNode = $getNodeByKey(key);
- if (!targetNode) return;
- const wrappedElem = wrapper().append(node);
- targetNode.insertAfter(wrappedElem);
-}
-
/**
* @deprecated
* Moving from this to the cleanState functionality as the bottom of this file.
diff --git a/js/app/packages/core/component/LexicalMarkdown/utils/dragInsertUtils.ts b/js/app/packages/core/component/LexicalMarkdown/utils/dragInsertUtils.ts
new file mode 100644
index 0000000000..b50e96d205
--- /dev/null
+++ b/js/app/packages/core/component/LexicalMarkdown/utils/dragInsertUtils.ts
@@ -0,0 +1,145 @@
+import {
+ $createDocumentMentionNode,
+ type DocumentMentionInfo,
+} from '@lexical-core';
+import {
+ $createParagraphNode,
+ $getNodeByKey,
+ type ElementNode,
+ type LexicalEditor,
+ type LexicalNode,
+ type NodeKey,
+} from 'lexical';
+import type { SetStoreFunction } from 'solid-js/store';
+import {
+ calculateInsertPoint,
+ type DragInsertState,
+ type InsertionMarker,
+} from '../plugins/drag-insert/dragInsertPlugin';
+
+const DRAG_INSERT_COLLISION_PADDING = 8;
+
+export type DragInsertCoordinates = {
+ clientX: number;
+ clientY: number;
+};
+
+export type ValidDragInsertPosition = {
+ key: NodeKey;
+ position: InsertionMarker;
+};
+
+export type DragInsertTargetValidator = (
+ coordinates: DragInsertCoordinates
+) => boolean;
+
+function $insertWrappedBefore(
+ key: NodeKey,
+ node: LexicalNode,
+ wrapper: () => ElementNode = $createParagraphNode
+) {
+ const targetNode = $getNodeByKey(key);
+ if (!targetNode) return;
+ const wrappedElem = wrapper().append(node);
+ targetNode.insertBefore(wrappedElem);
+}
+
+function $insertWrappedAfter(
+ key: NodeKey,
+ node: LexicalNode,
+ wrapper: () => ElementNode = $createParagraphNode
+) {
+ const targetNode = $getNodeByKey(key);
+ if (!targetNode) return;
+ const wrappedElem = wrapper().append(node);
+ targetNode.insertAfter(wrappedElem);
+}
+
+export function getValidDragInsertPosition(
+ editor: LexicalEditor,
+ coordinates: DragInsertCoordinates,
+ isValidDropTarget?: DragInsertTargetValidator
+): ValidDragInsertPosition | undefined {
+ if (isValidDropTarget && !isValidDropTarget(coordinates)) return undefined;
+
+ const { key, position } = calculateInsertPoint(
+ editor,
+ coordinates,
+ DRAG_INSERT_COLLISION_PADDING
+ );
+ if (!key || !position) return undefined;
+
+ return { key, position };
+}
+
+export function clearDragInsertPreview(
+ setState: SetStoreFunction<DragInsertState>
+) {
+ setState({ visible: false });
+}
+
+export function updateDragInsertPreviewFromCoordinates(args: {
+ editor: LexicalEditor;
+ coordinates: DragInsertCoordinates;
+ setState: SetStoreFunction<DragInsertState>;
+ isValidDropTarget?: DragInsertTargetValidator;
+}): ValidDragInsertPosition | undefined {
+ const dragInsertPosition = getValidDragInsertPosition(
+ args.editor,
+ args.coordinates,
+ args.isValidDropTarget
+ );
+ if (!dragInsertPosition) {
+ clearDragInsertPreview(args.setState);
+ return undefined;
+ }
+
+ args.setState({
+ nodeKey: dragInsertPosition.key,
+ position: dragInsertPosition.position,
+ visible: true,
+ });
+ return dragInsertPosition;
+}
+
+export function insertDocumentMentionAtDragInsertPosition(
+ editor: LexicalEditor,
+ dragInsertPosition: ValidDragInsertPosition,
+ mentionInfo: DocumentMentionInfo
+) {
+ editor.update(() => {
+ const mention = $createDocumentMentionNode({
+ ...mentionInfo,
+ createdAt: mentionInfo.createdAt ?? Date.now(),
+ });
+
+ if (dragInsertPosition.position === 'before') {
+ $insertWrappedBefore(dragInsertPosition.key, mention);
+ } else {
+ $insertWrappedAfter(dragInsertPosition.key, mention);
+ }
+ mention.selectEnd();
+ });
+}
+
+export function insertDocumentMentionAtDragCoordinates(args: {
+ editor: LexicalEditor;
+ coordinates?: DragInsertCoordinates;
+ mentionInfo: DocumentMentionInfo;
+ isValidDropTarget?: DragInsertTargetValidator;
+}) {
+ if (!args.coordinates) return false;
+ const dragInsertPosition = getValidDragInsertPosition(
+ args.editor,
+ args.coordinates,
+ args.isValidDropTarget
+ );
+ if (!dragInsertPosition) return false;
+
+ insertDocumentMentionAtDragInsertPosition(
+ args.editor,
+ dragInsertPosition,
+ args.mentionInfo
+ );
+ return true;
+}