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
feat(projects): give project descriptions the full markdown editor (#7425)
teo2688402fc3e6
diff --git a/apps/web/src/features/block-md/component/MarkdownEditor.tsx b/apps/web/src/features/block-md/component/MarkdownEditor.tsxindex f426db2cf4..630df0b43c 100644--- a/apps/web/src/features/block-md/component/MarkdownEditor.tsx+++ b/apps/web/src/features/block-md/component/MarkdownEditor.tsx@@ -1,87 +1,45 @@-import { URL_PARAMS as CHANNEL_PARAMS } from '@block-channel/constants';import { MessageCommentsProvider } from '@block-md/comments/MessageCommentsProvider';import { URL_PARAMS } from '@block-md/constants';import { keyNavigationPlugin } from '@block-md/plugins/keyboardNavigation';import { SplitBottomPanel } from '@components/app/split-layout/components/SplitBottomPanel';-import type { BlockName } from '@core/block';-import { DecoratorRenderer } from '@core/component/LexicalMarkdown/component/core/DecoratorRenderer';import { FocusClickTarget } from '@core/component/LexicalMarkdown/component/core/FocusClickTarget';import {HighlightLayer,LocationHighlight,} from '@core/component/LexicalMarkdown/component/core/Highlights';-import { NodeAccessoryRenderer } from '@core/component/LexicalMarkdown/component/core/NodeAccessoryRenderer';import { LexicalStateDebugger } from '@core/component/LexicalMarkdown/component/debug/LexicalStateDebugger';-import { ActionMenu } from '@core/component/LexicalMarkdown/component/menu/ActionsMenu';-import { EmojiMenu } from '@core/component/LexicalMarkdown/component/menu/EmojiMenu';-import { FloatingEquationMenu } from '@core/component/LexicalMarkdown/component/menu/FloatingEquationMenu';-import { FloatingLinkMenu } from '@core/component/LexicalMarkdown/component/menu/FloatingLinkMenu';-import { FloatingTableMenu } from '@core/component/LexicalMarkdown/component/menu/FloatingTableMenu';import { GenerateMenu } from '@core/component/LexicalMarkdown/component/menu/GenerateMenu';-import { MentionsMenu } from '@core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu';-import { SnippetsMenu } from '@core/component/LexicalMarkdown/component/menu/SnippetsMenu';import { TagsMenu } from '@core/component/LexicalMarkdown/component/menu/TagsMenu';-import { DraggableBlockMenu } from '@core/component/LexicalMarkdown/component/misc/DraggableBlockMenu';-import { DragInsertIndicator } from '@core/component/LexicalMarkdown/component/misc/DragInsertIndicator';-import { TableCellResizer } from '@core/component/LexicalMarkdown/component/misc/TableCellResizer';-import { TableDeleteButtons } from '@core/component/LexicalMarkdown/component/misc/TableDeleteButtons';-import { TableInsertButton } from '@core/component/LexicalMarkdown/component/misc/TableInsertButton';-import { TableMoveHandle } from '@core/component/LexicalMarkdown/component/misc/TableMoveHandle';-import { TableSelectionActionBar } from '@core/component/LexicalMarkdown/component/misc/TableSelectionActionBar';import {getErrorDescription,MarkdownEditorErrors,} from '@core/component/LexicalMarkdown/constants';-import { FloatingMenuGroup } from '@core/component/LexicalMarkdown/context/FloatingMenuContext';import {createLexicalWrapper,LexicalWrapperContext,} from '@core/component/LexicalMarkdown/context/LexicalWrapperContext';+import { useEditorEntityDrop } from '@core/component/LexicalMarkdown/editing/entityDrop';+import { MarkdownEditingOverlays } from '@core/component/LexicalMarkdown/editing/MarkdownEditingOverlays';+import {+ type MarkdownEditingSource,+ registerMarkdownEditing,+} from '@core/component/LexicalMarkdown/editing/registerMarkdownEditing';import {- awaitPlugin,CLOSE_INLINE_SEARCH_COMMAND,- createDraggableBlockStore,- createDragInsertStore,createProgressStatsStore,createWordcountStatsStore,- DefaultShortcuts,diffPlugin,- documentMetadataPlugin,- draggableBlockPlugin,- dragInsertPlugin,- filePastePlugin,generatePlugin,- horizontalRulePlugin,- keyboardShortcutsPlugin,- listSwipeIndentPlugin,- listToTablePlugin,- markdownPastePlugin,- mentionsPlugin,pinnedPropertiesPlugin,progressPlugin,- selectionDataPlugin,- tabIndentationPlugin,- tableCellResizerPlugin,- tablePlugin,- tableTouchSelectionPlugin,tagsPlugin,- textPastePlugin,- trailingParagraphPlugin,wordcountPlugin,} from '@core/component/LexicalMarkdown/plugins';-import { actionsPlugin } from '@core/component/LexicalMarkdown/plugins/actions/actionsPlugin';import {BlameTooltip,blameTooltipPlugin,createBlameTooltipStore,} from '@core/component/LexicalMarkdown/plugins/blame-tooltip';-import { blockDecoratorNavigationPlugin } from '@core/component/LexicalMarkdown/plugins/block-decorator-navigation';-import {- CONVERT_CHECKBOXES_TO_TASKS,- checkboxToTaskPlugin,-} from '@core/component/LexicalMarkdown/plugins/checkbox-to-task';-import { codePlugin } from '@core/component/LexicalMarkdown/plugins/code/codePlugin';-import { emojisPlugin } from '@core/component/LexicalMarkdown/plugins/emojis/emojisPlugin';import {DO_SEARCH_COMMAND,FloatingSearchHighlight,@@ -89,7 +47,6 @@ import {type NodekeyOffset,SearchHighlight,} from '@core/component/LexicalMarkdown/plugins/find-and-replace';-import { iosCursorScrollPlugin } from '@core/component/LexicalMarkdown/plugins/ios-cursor-scroll';import {GO_TO_LOCATION_COMMAND,GO_TO_NODE_ID_COMMAND,@@ -97,19 +54,11 @@ import {type PersistentLocation,parsePersistentLocation,} from '@core/component/LexicalMarkdown/plugins/location';-import {- INSERT_MEDIA_COMMAND,- mediaPlugin,-} from '@core/component/LexicalMarkdown/plugins/media';-import { createAccessoryStore } from '@core/component/LexicalMarkdown/plugins/node-accessory';-import { normalizeEnterPlugin } from '@core/component/LexicalMarkdown/plugins/normalize-enter/';-import { restoreFocusPlugin } from '@core/component/LexicalMarkdown/plugins/restore-focus';import {autoRegister,lazyRegister,registerInternalLayoutShiftListener,} from '@core/component/LexicalMarkdown/plugins/shared/utils';-import { snippetsPlugin } from '@core/component/LexicalMarkdown/plugins/snippets';import type { MentionLinkResolver } from '@core/component/LexicalMarkdown/plugins/text-paste/textPastePlugin';import { createMenuOperations } from '@core/component/LexicalMarkdown/shared/inlineMenu';import {@@ -120,18 +69,8 @@ import {initializeEditorWithState,setEditorStateFromMarkdown,} from '@core/component/LexicalMarkdown/utils';-import {- getValidDragInsertPosition,- insertDocumentMentionAtDragInsertPosition,- updateDragInsertPreviewFromCoordinates,-} from '@core/component/LexicalMarkdown/utils/dragInsertUtils';-import {- createFilesReadyHandler,- getDragDropPosition,-} from '@core/component/LexicalMarkdown/utils/fileUploadUtils';import { useUrlParams } from '@core/component/ParamsProvider';import { toast } from '@core/component/Toast/Toast';-import { itemToBlockName } from '@core/constant/allBlocks';import {ENABLE_MARKDOWN_AI_GENERATE,ENABLE_MARKDOWN_COMMENTS,@@ -140,32 +79,21 @@ import {enableGitBlame,isFeatureEnabled,} from '@core/constant/featureFlags';-import { IS_MAC } from '@core/constant/isMac';-import { useUserId } from '@core/context/user';import { fileFolderDrop } from '@core/directive/fileFolderDrop';import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';-import { isTouchDevice } from '@core/mobile/isTouchDevice';-import { trackMention } from '@core/signal/mention';import { bufToString } from '@core/util/string';-import { handleFileFolderDrop } from '@core/util/upload';-import { type EntityDragEvent, isEntityDragEvent } from '@entity';import type { LoroManager } from '@macro-inc/collaboration/collab/manager';import {$isInlineSearchNode,- AwaitNode,- CommentNode,createPeerIdValidator,- InlineSearchNode,type PeerIdValidator,- peerIdPlugin,} from '@macro-inc/lexical-core';import { useDocTags } from '@property/tags';import { EntityType } from '@service-properties/generated/schemas/entityType';import { onElementConnect } from '@solid-primitives/lifecycle';import { isIOS } from '@solid-primitives/platform';import { createCallback } from '@solid-primitives/rootless';-import { debounce, throttle } from '@solid-primitives/scheduled';-import { createDroppable, useDragDropContext } from '@thisbeyond/solid-dnd';+import { debounce } from '@solid-primitives/scheduled';import { $getRoot, $isElementNode, type EditorState } from 'lexical';import {type Accessor,@@ -220,7 +148,6 @@ export function MarkdownEditor(props: {} = useMarkdownDocument();const { canEdit, canComment } = permissions;const blockId = documentId();- const userId = useUserId();const documentKind = kind();const sourceBlockName = documentKind === 'document' ? 'md' : documentKind;const documentTags = useDocTags(@@ -334,132 +261,7 @@ export function MarkdownEditor(props: {const [editorFocus, setEditorFocus] = createSignal(false);autoRegister(editorFocusSignal(editor, setEditorFocus));- const mentionsMenuOperations = createMenuOperations();const tagsMenuOperations = createMenuOperations();- const emojiMenuOperations = createMenuOperations();- const actionsMenuOperations = createMenuOperations();- const snippetsMenuOperations = createMenuOperations();-- // store for the drag insert pluign.- const [dragInsertStore, setDragInsertStore] = createDragInsertStore();-- // store for the draggable block (drag-to-rearrange) plugin.- const [draggableBlockStore, setDraggableBlockStore] =- createDraggableBlockStore();-- // set up the solid-dnd stuff- const droppable = createDroppable(editor._config.namespace, {- type: 'markdown-editor',- });-- const [dragDropState, { onDragEnd, onDragMove }] = useDragDropContext() ?? [- undefined,- {- onDragEnd: () => {},- onDragMove: () => {},- },- ];-- // turn the solid dnd events into something we can use.- const wrapDndEvent = (event: EntityDragEvent) => {- const currentPos = dragDropState?.active.sensor?.coordinates?.current;- if (!currentPos) return;- const mousePos = {- clientX: currentPos.x,- clientY: currentPos.y,- };- const item = event.draggable.data;- if (item.type === 'foreign') return;- const blockName = itemToBlockName(item);- if (!blockName) return;- let id = event.draggable.data.id as string;- if (event.draggable.data.type === 'channel_message') {- id = event.draggable.data.channelId;- }- return {- id,- blockName: blockName as BlockName,- mousePos,- item,- };- };-- const dndDragEnd = async (event: EntityDragEvent) => {- if (!dragInsertStore.visible) return;- setDragInsertStore({ visible: false });- if (!canEdit()) return;-- const res = wrapDndEvent(event);- if (!res) return;-- if (res.blockName === 'image' || res.blockName === 'video') {- getDragDropPosition(editor, res.mousePos, true);- editor.dispatchCommand(INSERT_MEDIA_COMMAND, {- type: 'dss',- id: res.id,- mediaType: res.blockName,- });- return;- }-- if (res.blockName === undefined) return;- const dragInsertPosition = getValidDragInsertPosition(editor, res.mousePos);- if (!dragInsertPosition) return;-- const mentionId = await trackMention(- blockId,- res.item.type === 'agent_session' ? 'agent_session' : 'document',- res.id- );-- 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;- }- }-- insertDocumentMentionAtDragInsertPosition(editor, dragInsertPosition, {- documentId: res.id,- documentName: res.item.name,- blockName: res.blockName,- blockParams,- mentionUuid: mentionId,- createdAt: Date.now(),- });- };-- const dndDragMove = throttle((event: EntityDragEvent) => {- if (!droppable.isActiveDroppable) {- return setDragInsertStore({ visible: false });- }- const res = wrapDndEvent(event);- if (!res) return;- const { mousePos } = res;- updateDragInsertPreviewFromCoordinates({- editor,- coordinates: mousePos,- setState: setDragInsertStore,- });- }, 60);-- onDragEnd((event) => {- // dndDragMove is a trailing throttle, so a callback scheduled just before- // the drop would otherwise fire after it and could re-show the indicator.- dndDragMove.clear();- // Only soup entity drags insert mentions (not e.g. sidebar favorite drags).- if (!isEntityDragEvent(event)) return;- dndDragEnd(event);- });-- onDragMove((event) => {- if (!isEntityDragEvent(event)) return;- dndDragMove(event);- });const onSetListOffset = (listOffset: NodekeyOffset[]) => {setFindAndReplaceStore('listOffset', listOffset);@@ -551,6 +353,12 @@ export function MarkdownEditor(props: {return createPeerIdValidator(peerId, true);};+ const editingSource: MarkdownEditingSource = {+ id: blockId,+ blockName: sourceBlockName,+ trackMentions: true,+ };+// pluginsplugins.richText()@@ -558,157 +366,59 @@ export function MarkdownEditor(props: {.markdownShortcuts().delete().state<EditorState>(setState, 'json')- .history(400, props.loroManager)- .use(tabIndentationPlugin())- .use(listSwipeIndentPlugin(isContentEditable))- .use(selectionDataPlugin(lexicalWrapper))- .use(horizontalRulePlugin())- .use(- emojisPlugin({- menu: emojiMenuOperations,- peerIdValidator: peerIdValidator(),- })- )- .use(- mentionsPlugin({- menu: mentionsMenuOperations,- peerIdValidator: peerIdValidator(),- sourceDocumentId: blockId,- })- )- .use(- tagsPlugin({- menu: tagsMenuOperations,- peerIdValidator: peerIdValidator(),- })- )- .use(- snippetsPlugin({- menu: snippetsMenuOperations,- peerIdValidator: peerIdValidator(),- sourceDocumentId: blockId,- })- )- .use(- actionsPlugin({- menu: actionsMenuOperations,- peerIdValidator: peerIdValidator(),- })- )- .use(mediaPlugin())- .use(blockDecoratorNavigationPlugin())- .use(- tablePlugin({- hasCellMerge: true,- hasCellBackgroundColor: true,- hasTabHandler: true,- hasHorizontalScroll: true,- })- )- .use(tableCellResizerPlugin())- .use(tableTouchSelectionPlugin())- .use(- filePastePlugin({- onPasteFilesAndDirs: (fileEntries, directories) =>- handleFileFolderDrop(- fileEntries,- directories,- createFilesReadyHandler(editor, blockId)- ),- })- )- .use(- findAndReplacePlugin({- getListOffset: () => findAndReplaceStore.listOffset,- setListOffset: onSetListOffset,- })- )- .use(- dragInsertPlugin({- setState: setDragInsertStore,- dragListenerRef: editorContainerRef,- })- )- .use(textPastePlugin(props.resolveAppLink))- .use(restoreFocusPlugin())- .use(markdownPastePlugin())- .use(normalizeEnterPlugin())- .use(trailingParagraphPlugin())- .use(- checkboxToTaskPlugin({- currentUserId: userId(),- parentTaskId: documentKind === 'task' ? blockId : undefined,- })- )- .use(- keyboardShortcutsPlugin({- shortcuts: [- ...DefaultShortcuts,- {- label: `${IS_MAC ? 'meta' : 'ctrl'}+shift+o`,- test: (e) =>- e.code === 'KeyO' &&- e.shiftKey &&- (IS_MAC ? e.metaKey : e.ctrlKey),- handler: (editor) => {- const userId = useUserId()();- if (!userId) return;- editor.dispatchCommand(CONVERT_CHECKBOXES_TO_TASKS, {});- },- priority: 0,- },- ],- })- )- .use(- documentMetadataPlugin({- onVersionError: (error) => setEditorError(error),- })- )- .use(pinnedPropertiesPlugin())- .use(awaitPlugin());-- if (isIOS || isNativeMobilePlatform()) {- plugins.use(- iosCursorScrollPlugin({ scrollContainer: () => md.scrollContainer })- );- }-- if (ENABLE_MARKDOWN_LIVE_COLLABORATION) {- const peerId = () => props.loroManager.peerIdStr;- plugins.use(- peerIdPlugin({- peerId,- nodes: [InlineSearchNode, CommentNode, AwaitNode],- })- );- }-- if (ENABLE_MARKDOWN_DIFF) {- plugins.use(diffPlugin());- }-- const [accessoryStore, setAccessoryStore] = createAccessoryStore();- if (ENABLE_MARKDOWN_AI_GENERATE) {- plugins.use(- generatePlugin({- completionSignal: completionSignal,- isGeneratingSignal,- generatedAndWaitingSignal,- menuSignal: generateMenuSignal,- setContext: setGenerateContext,- accessories: accessoryStore,- setAccessories: setAccessoryStore,- })- );- }- plugins.use(- codePlugin({- accessories: accessoryStore,- setAccessories: setAccessoryStore,- })- );- plugins.use(listToTablePlugin());+ .history(400, props.loroManager);+ const editing = registerMarkdownEditing({+ lexicalWrapper,+ isContentEditable,+ peerIdValidator: peerIdValidator(),+ source: editingSource,+ resolveAppLink: props.resolveAppLink,+ parentTaskId: documentKind === 'task' ? blockId : undefined,+ onVersionError: (error) => setEditorError(error),+ peerId: ENABLE_MARKDOWN_LIVE_COLLABORATION+ ? () => props.loroManager.peerIdStr+ : undefined,+ iosScrollContainer:+ isIOS || isNativeMobilePlatform() ? () => md.scrollContainer : undefined,+ slots: {+ afterMentions: [+ tagsPlugin({+ menu: tagsMenuOperations,+ peerIdValidator: peerIdValidator(),+ }),+ ],+ afterFilePaste: [+ findAndReplacePlugin({+ getListOffset: () => findAndReplaceStore.listOffset,+ setListOffset: onSetListOffset,+ }),+ ],+ beforeAwait: [pinnedPropertiesPlugin()],+ beforeCode: ([accessoryStore, setAccessoryStore]) => [+ ...(ENABLE_MARKDOWN_DIFF ? [diffPlugin()] : []),+ ...(ENABLE_MARKDOWN_AI_GENERATE+ ? [+ generatePlugin({+ completionSignal: completionSignal,+ isGeneratingSignal,+ generatedAndWaitingSignal,+ menuSignal: generateMenuSignal,+ setContext: setGenerateContext,+ accessories: accessoryStore,+ setAccessories: setAccessoryStore,+ }),+ ]+ : []),+ ],+ },+ });+ const droppable = useEditorEntityDrop({+ editor,+ canEdit: () => canEdit() ?? false,+ dragInsert: editing.dragInsert,+ source: editingSource,+ });+ false && droppable;const [editorHasNoContent, setEditorHasNoContent] = createSignal(false);@@ -729,18 +439,7 @@ export function MarkdownEditor(props: {editor.setRootElement(el);// Register plugins that require the container ref.- plugins.use(- dragInsertPlugin({- setState: setDragInsertStore,- dragListenerRef: editorContainerRef,- })- );- plugins.use(- draggableBlockPlugin({- setState: setDraggableBlockStore,- anchorElem: editorContainerRef,- })- );+ editing.connectContainer(editorContainerRef);const editorRefObserver = new ResizeObserver(observeClickTargetHeight);@@ -777,13 +476,7 @@ export function MarkdownEditor(props: {// Are are any of the inline menus open? This effects the behavior of the// array keys.const isInlineMenuOpen = createMemo(() => {- return (- mentionsMenuOperations.isOpen() ||- emojiMenuOperations.isOpen() ||- actionsMenuOperations.isOpen() ||- snippetsMenuOperations.isOpen() ||- titleEditorMenuOpen()- );+ return editing.isInlineMenuOpen() || titleEditorMenuOpen();});createEffect(() => {@@ -983,13 +676,7 @@ export function MarkdownEditor(props: {use:fileFolderDrop={{onDrop: (fileEntries, folderEntries, e) => {if (!e) return;- handleFileFolderDrop(- fileEntries,- folderEntries,- createFilesReadyHandler(editor, blockId, 'md', () =>- getDragDropPosition(editor, e, true)- )- );+ editing.dropFiles(fileEntries, folderEntries, e, 'md');},}}use:droppable@@ -1051,9 +738,6 @@ export function MarkdownEditor(props: {<BlameTooltip state={blameTooltipStore} documentId={blockId} /></Suspense></Show>- <DecoratorRenderer editor={editor} />- <NodeAccessoryRenderer editor={editor} store={accessoryStore} />-<HighlightLayereditor={editor}ref={(el) => {@@ -1071,28 +755,19 @@ export function MarkdownEditor(props: {/></Show>- <DragInsertIndicator- state={dragInsertStore}- active={canEdit() ?? false}- />-- <DraggableBlockMenu- state={draggableBlockStore}- setState={setDraggableBlockStore}- active={canEdit() ?? false}- />-- <EmojiMenu- editor={editor}- menu={emojiMenuOperations}- useBlockBoundary={true}- />-- <MentionsMenu+ <MarkdownEditingOverlayseditor={editor}- menu={mentionsMenuOperations}+ editing={editing}+ source={editingSource}+ canEdit={() => canEdit() ?? false}useBlockBoundary={true}showOpenTabs+ floatingMenus={+ <MarkdownPopup+ highlightLayerRef={highlightLayerRef() ?? editorContainerRef}+ lexicalMapping={lexicalWrapper.mapping}+ />+ }/><TagsMenu@@ -1107,32 +782,6 @@ export function MarkdownEditor(props: {}}/>- <SnippetsMenu- editor={editor}- menu={snippetsMenuOperations}- useBlockBoundary={true}- sourceDocumentId={blockId}- />-- <ActionMenu- editor={editor}- menu={actionsMenuOperations}- actionContext={{- sourceDocumentId: blockId,- sourceBlockName,- }}- />-- <FloatingMenuGroup>- <FloatingLinkMenu autoLinkMatchMode="common-tlds" />- <FloatingEquationMenu canEdit={canEdit} />- <FloatingTableMenu canEdit={canEdit} />- <MarkdownPopup- highlightLayerRef={highlightLayerRef() ?? editorContainerRef}- lexicalMapping={lexicalWrapper.mapping}- />- </FloatingMenuGroup>-<Show when={findAndReplaceStore.searchIsOpen}><SearchHighlightanchorElem={highlightLayerRef() ?? editorContainerRef}@@ -1160,20 +809,6 @@ export function MarkdownEditor(props: {</Suspense></Show>- <Show when={canEdit()}>- {/* On touch devices the hover-driven controls are unusable */}- {isTouchDevice() ? (- <TableSelectionActionBar />- ) : (- <>- <TableInsertButton />- <TableDeleteButtons />- </>- )}- <TableCellResizer />- <TableMoveHandle />- </Show>-<Show when={ENABLE_MARKDOWN_AI_GENERATE}><GenerateMenugenerateCallback={_generateContentCallback}diff --git a/apps/web/src/features/projects/project-description.tsx b/apps/web/src/features/projects/project-description.tsxindex 69a9052e82..c6a8864737 100644--- a/apps/web/src/features/projects/project-description.tsx+++ b/apps/web/src/features/projects/project-description.tsx@@ -21,8 +21,12 @@ function DescriptionSession(props: {canComment={() => false}label="Project description"namespace="project-description"- class="min-h-24 text-sm"- placeholder={props.canEdit ? 'Add a description…' : 'No description'}+ class="min-h-24 mt-1.5 text-base"+ placeholder={+ props.canEdit+ ? "Add a description. Press '/' for commands, '@' to mention…"+ : 'No description'+ }/><Show when={session.connectionError()}><Button size="sm" onClick={props.onRetry}>diff --git a/apps/web/src/lib/core/collab-surface/CollabMarkdownEditor.test.tsx b/apps/web/src/lib/core/collab-surface/CollabMarkdownEditor.test.tsxnew file mode 100644index 0000000000..6bf94f22d8--- /dev/null+++ b/apps/web/src/lib/core/collab-surface/CollabMarkdownEditor.test.tsx@@ -0,0 +1,134 @@+import { cleanup, render } from '@solidjs/testing-library';+import { afterEach, expect, it, vi } from 'vitest';++const fakes = vi.hoisted(() => {+ const plugins: Record<string, unknown> = {};+ for (const step of [+ 'richText',+ 'list',+ 'markdownShortcuts',+ 'delete',+ 'state',+ 'history',+ 'use',+ ]) {+ plugins[step] = () => plugins;+ }+ return {+ plugins,+ editing: {+ dragInsert: [{ visible: false }, () => {}],+ isInlineMenuOpen: () => false,+ connectContainer: vi.fn(),+ dropFiles: vi.fn(),+ },+ overlays: [] as Array<Record<string, unknown>>,+ };+});++vi.mock('@core/component/LexicalMarkdown/collaboration/CollabProvider', () => ({+ CollabProvider: () => null,+}));+vi.mock('@core/component/LexicalMarkdown/constants', () => ({+ getErrorDescription: () => '',+}));+vi.mock(+ '@core/component/LexicalMarkdown/context/LexicalWrapperContext',+ async () => {+ const { createContext } = await import('solid-js');+ return {+ LexicalWrapperContext: createContext(),+ createLexicalWrapper: () => ({+ editor: {+ _config: { namespace: 'collab-surface' },+ focus: () => {},+ registerUpdateListener: () => () => {},+ setEditable: () => {},+ setRootElement: () => {},+ },+ plugins: fakes.plugins,+ cleanup: () => {},+ mapping: {},+ }),+ };+ }+);+vi.mock('@core/component/LexicalMarkdown/editing/entityDrop', () => ({+ useEditorEntityDrop: () => () => {},+}));+vi.mock(+ '@core/component/LexicalMarkdown/editing/MarkdownEditingOverlays',+ () => ({+ MarkdownEditingOverlays: (props: Record<string, unknown>) => {+ fakes.overlays.push(props);+ return null;+ },+ })+);+vi.mock(+ '@core/component/LexicalMarkdown/editing/registerMarkdownEditing',+ () => ({ registerMarkdownEditing: vi.fn(() => fakes.editing) })+);+vi.mock('@core/component/LexicalMarkdown/utils', () => ({+ editorFocusSignal: () => {},+ editorIsEmpty: () => true,+ initializeEditorEmpty: () => {},+}));+vi.mock('@core/directive/fileFolderDrop', () => ({ fileFolderDrop: () => {} }));+vi.mock('@macro-inc/lexical-core', () => ({+ createPeerIdValidator: () => () => true,+}));+vi.mock('@solid-primitives/lifecycle', () => ({+ onElementConnect: (_el: Element, connect: () => void) => connect(),+}));++import { registerMarkdownEditing } from '@core/component/LexicalMarkdown/editing/registerMarkdownEditing';+import { CollabMarkdownEditor } from './CollabMarkdownEditor';+import type { CollabMarkdownSession } from './types';++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+ fakes.overlays.length = 0;+});++const session = {+ loroManager: { peerIdStr: 'peer-1' },+ syncSource: () => undefined,+ connectionError: () => undefined,+} as unknown as CollabMarkdownSession;++it('gives a collaborative surface the document editing features without tracked mentions', () => {+ const view = render(() => (+ <CollabMarkdownEditor+ sourceId="project-1"+ session={session}+ label="Project description"+ />+ ));++ expect(registerMarkdownEditing).toHaveBeenCalledTimes(1);+ const [options] = vi.mocked(registerMarkdownEditing).mock.calls[0];+ expect(options.source).toEqual({+ id: 'project-1',+ blockName: undefined,+ trackMentions: false,+ });+ expect(options.peerId?.()).toBe('peer-1');++ expect(fakes.overlays).toHaveLength(1);+ const overlays = fakes.overlays[0] as {+ source: unknown;+ useBlockBoundary: boolean;+ canEdit: () => boolean;+ };+ expect(overlays.source).toBe(options.source);+ expect(overlays.useBlockBoundary).toBe(true);+ expect(overlays.canEdit()).toBe(true);++ const content = view.getByRole('textbox', { name: 'Project description' });+ expect(content.classList.contains('ph-no-capture')).toBe(true);+ expect(fakes.editing.connectContainer).toHaveBeenCalledWith(+ content.parentElement+ );+});diff --git a/apps/web/src/lib/core/collab-surface/CollabMarkdownEditor.tsx b/apps/web/src/lib/core/collab-surface/CollabMarkdownEditor.tsxindex 31a2a3bbab..ab2c88952f 100644--- a/apps/web/src/lib/core/collab-surface/CollabMarkdownEditor.tsx+++ b/apps/web/src/lib/core/collab-surface/CollabMarkdownEditor.tsx@@ -1,8 +1,4 @@import { CollabProvider } from '@core/component/LexicalMarkdown/collaboration/CollabProvider';-import { DecoratorRenderer } from '@core/component/LexicalMarkdown/component/core/DecoratorRenderer';-import { EmojiMenu } from '@core/component/LexicalMarkdown/component/menu/EmojiMenu';-import { MentionsMenu } from '@core/component/LexicalMarkdown/component/menu/MentionsMenu';-import { SnippetsMenu } from '@core/component/LexicalMarkdown/component/menu/SnippetsMenu';import {getErrorDescription,type MarkdownEditorErrors,@@ -11,31 +7,20 @@ import {createLexicalWrapper,LexicalWrapperContext,} from '@core/component/LexicalMarkdown/context/LexicalWrapperContext';+import { useEditorEntityDrop } from '@core/component/LexicalMarkdown/editing/entityDrop';+import { MarkdownEditingOverlays } from '@core/component/LexicalMarkdown/editing/MarkdownEditingOverlays';import {- awaitPlugin,- DefaultShortcuts,- documentMetadataPlugin,- keyboardShortcutsPlugin,- markdownPastePlugin,- mentionsPlugin,- textPastePlugin,-} from '@core/component/LexicalMarkdown/plugins';-import { emojisPlugin } from '@core/component/LexicalMarkdown/plugins/emojis/emojisPlugin';-import { snippetsPlugin } from '@core/component/LexicalMarkdown/plugins/snippets';+ type MarkdownEditingSource,+ registerMarkdownEditing,+} from '@core/component/LexicalMarkdown/editing/registerMarkdownEditing';import type { MentionLinkResolver } from '@core/component/LexicalMarkdown/plugins/text-paste/textPastePlugin';-import { createMenuOperations } from '@core/component/LexicalMarkdown/shared/inlineMenu';import {editorFocusSignal,editorIsEmpty,initializeEditorEmpty,} from '@core/component/LexicalMarkdown/utils';-import {- AwaitNode,- CommentNode,- createPeerIdValidator,- InlineSearchNode,- peerIdPlugin,-} from '@macro-inc/lexical-core';+import { fileFolderDrop } from '@core/directive/fileFolderDrop';+import { createPeerIdValidator } from '@macro-inc/lexical-core';import { onElementConnect } from '@solid-primitives/lifecycle';import type { LexicalEditor } from 'lexical';import {@@ -71,6 +56,10 @@ export type CollabMarkdownControls = {export type CollabMarkdownEditorProps = {/** Stable identity of the document or collaborative surface. */sourceId: string;+ /** The block hosting the surface, for actions such as the slash task. */+ sourceBlockName?: string;+ /** Keep inline menus inside the hosting block. Defaults to true. */+ useBlockBoundary?: boolean;session: CollabMarkdownSession;/*** Whether the caller may edit. UI-only: the server enforces the real@@ -100,7 +89,12 @@ export type CollabMarkdownEditorProps = {statusChrome?: JSX.Element;};-/** Existing collaborative Markdown editor with explicit session ownership. */+false && fileFolderDrop;++/**+ * Collaborative markdown editor with the document editor's editing features,+ * over an explicitly owned session.+ */export function CollabMarkdownEditor(props: CollabMarkdownEditorProps) {const canEdit = props.canEdit ?? (() => true);const canComment = props.canComment ?? (() => false);@@ -130,63 +124,42 @@ export function CollabMarkdownEditor(props: CollabMarkdownEditorProps) {// Markdown-serialized view of the editor state, for `controls.getMarkdown`.const [markdownState, setMarkdownState] = createSignal('');- const mentionsMenuOperations = createMenuOperations();- const emojiMenuOperations = createMenuOperations();- const snippetsMenuOperations = createMenuOperations();-// Collab is the point of this component, so the validator is always live:// it keeps this peer from committing another peer's in-flight inline nodes// (mentions, emoji searches, snippets).const peerId = () => session.loroManager.peerIdStr;const peerIdValidator = createPeerIdValidator(peerId, true);+ // A surface is not a document, so its mentions are not tracked references.+ const editingSource: MarkdownEditingSource = {+ id: props.sourceId,+ blockName: props.sourceBlockName,+ trackMentions: false,+ };+plugins.richText().list().markdownShortcuts().delete().state<string>(setMarkdownState, 'markdown')- .history(400, session.loroManager)- .use(- emojisPlugin({- menu: emojiMenuOperations,- peerIdValidator,- })- )- .use(- mentionsPlugin({- menu: mentionsMenuOperations,- peerIdValidator,- sourceDocumentId: props.sourceId,- disableMentionTracking: true,- })- )- .use(- snippetsPlugin({- menu: snippetsMenuOperations,- peerIdValidator,- sourceDocumentId: props.sourceId,- })- )- .use(textPastePlugin(props.resolveAppLink))- .use(markdownPastePlugin())- .use(awaitPlugin())- .use(- keyboardShortcutsPlugin({- shortcuts: DefaultShortcuts,- })- )- .use(- documentMetadataPlugin({- onVersionError: (error) => setEditorError(error),- })- )- .use(- peerIdPlugin({- peerId,- nodes: [InlineSearchNode, CommentNode, AwaitNode],- })- );+ .history(400, session.loroManager);+ const editing = registerMarkdownEditing({+ lexicalWrapper,+ isContentEditable,+ peerIdValidator,+ source: editingSource,+ resolveAppLink: props.resolveAppLink,+ onVersionError: (error) => setEditorError(error),+ peerId,+ });+ const droppable = useEditorEntityDrop({+ editor,+ canEdit,+ dragInsert: editing.dragInsert,+ source: editingSource,+ });+ false && droppable;createEffect(() => {editor.setEditable(isContentEditable());@@ -197,10 +170,7 @@ export function CollabMarkdownEditor(props: CollabMarkdownEditorProps) {clear: () => initializeEditorEmpty(editor, peerId),focus: () => editor.focus(),getLexical: () => editor,- isInlineMenuOpen: () =>- mentionsMenuOperations.isOpen() ||- emojiMenuOperations.isOpen() ||- snippetsMenuOperations.isOpen(),+ isInlineMenuOpen: editing.isInlineMenuOpen,});createEffect(() => {@@ -234,11 +204,23 @@ export function CollabMarkdownEditor(props: CollabMarkdownEditorProps) {Could not connect to the content.</div></Show>- <div class="relative" ref={editorContainerRef}>+ <div+ class="relative"+ ref={editorContainerRef}+ use:fileFolderDrop={{+ disabled: !isContentEditable(),+ onDrop: (fileEntries, folderEntries, e) => {+ if (!e) return;+ editing.dropFiles(fileEntries, folderEntries, e);+ },+ }}+ use:droppable+ ><divref={(el) => {onElementConnect(el, () => {editor.setRootElement(el);+ editing.connectContainer(editorContainerRef);});}}contentEditable={isContentEditable()}@@ -246,7 +228,7 @@ export function CollabMarkdownEditor(props: CollabMarkdownEditorProps) {aria-label={props.label ?? 'Document content'}aria-multiline="true"aria-readonly={!canEdit()}- class="w-full max-w-full outline-none"+ class="ph-no-capture w-full max-w-full outline-none"classList={{'select-auto': !canEdit(),'md-no-comments': true,@@ -288,24 +270,12 @@ export function CollabMarkdownEditor(props: CollabMarkdownEditorProps) {/></Show>- <DecoratorRenderer editor={editor} />-- <EmojiMenu- editor={editor}- menu={emojiMenuOperations}- useBlockBoundary={false}- />- <MentionsMenu- editor={editor}- menu={mentionsMenuOperations}- useBlockBoundary={false}- disableMentionTracking={true}- />- <SnippetsMenu+ <MarkdownEditingOverlayseditor={editor}- menu={snippetsMenuOperations}- useBlockBoundary={false}- sourceDocumentId={props.sourceId}+ editing={editing}+ source={editingSource}+ canEdit={canEdit}+ useBlockBoundary={props.useBlockBoundary ?? true}/></div></div>diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/editing/MarkdownEditingOverlays.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/editing/MarkdownEditingOverlays.tsxnew file mode 100644index 0000000000..521b6d29e6--- /dev/null+++ b/apps/web/src/lib/core/component/LexicalMarkdown/editing/MarkdownEditingOverlays.tsx@@ -0,0 +1,113 @@+import { isTouchDevice } from '@core/mobile/isTouchDevice';+import type { LexicalEditor } from 'lexical';+import { type Accessor, type JSX, Show } from 'solid-js';+import { DecoratorRenderer } from '../component/core/DecoratorRenderer';+import { NodeAccessoryRenderer } from '../component/core/NodeAccessoryRenderer';+import { ActionMenu } from '../component/menu/ActionsMenu';+import { EmojiMenu } from '../component/menu/EmojiMenu';+import { FloatingEquationMenu } from '../component/menu/FloatingEquationMenu';+import { FloatingLinkMenu } from '../component/menu/FloatingLinkMenu';+import { FloatingTableMenu } from '../component/menu/FloatingTableMenu';+import { MentionsMenu } from '../component/menu/MentionsMenu/MentionsMenu';+import { SnippetsMenu } from '../component/menu/SnippetsMenu';+import { DraggableBlockMenu } from '../component/misc/DraggableBlockMenu';+import { DragInsertIndicator } from '../component/misc/DragInsertIndicator';+import { TableCellResizer } from '../component/misc/TableCellResizer';+import { TableDeleteButtons } from '../component/misc/TableDeleteButtons';+import { TableInsertButton } from '../component/misc/TableInsertButton';+import { TableMoveHandle } from '../component/misc/TableMoveHandle';+import { TableSelectionActionBar } from '../component/misc/TableSelectionActionBar';+import { FloatingMenuGroup } from '../context/FloatingMenuContext';+import type {+ MarkdownEditing,+ MarkdownEditingSource,+} from './registerMarkdownEditing';++/**+ * Menus, floating editors, and block and table controls for the features+ * `registerMarkdownEditing` registered. Render inside the editor's+ * `LexicalWrapperContext`.+ */+export function MarkdownEditingOverlays(props: {+ editor: LexicalEditor;+ editing: MarkdownEditing;+ source: MarkdownEditingSource;+ canEdit: Accessor<boolean>;+ /** Keep inline menus inside the hosting block. */+ useBlockBoundary: boolean;+ /** Offer the user's open tabs in the mentions menu. */+ showOpenTabs?: boolean;+ /** More floating menus sharing the group, e.g. a document's popups. */+ floatingMenus?: JSX.Element;+}) {+ const [dragInsertStore] = props.editing.dragInsert;+ const [draggableBlockStore, setDraggableBlockStore] =+ props.editing.draggableBlock;+ const [accessoryStore] = props.editing.accessories;+ return (+ <>+ <DecoratorRenderer editor={props.editor} />+ <NodeAccessoryRenderer editor={props.editor} store={accessoryStore} />++ <DragInsertIndicator state={dragInsertStore} active={props.canEdit()} />++ <DraggableBlockMenu+ state={draggableBlockStore}+ setState={setDraggableBlockStore}+ active={props.canEdit()}+ />++ <EmojiMenu+ editor={props.editor}+ menu={props.editing.menus.emoji}+ useBlockBoundary={props.useBlockBoundary}+ />++ <MentionsMenu+ editor={props.editor}+ menu={props.editing.menus.mentions}+ useBlockBoundary={props.useBlockBoundary}+ showOpenTabs={props.showOpenTabs}+ disableMentionTracking={!props.source.trackMentions}+ />++ <SnippetsMenu+ editor={props.editor}+ menu={props.editing.menus.snippets}+ useBlockBoundary={props.useBlockBoundary}+ sourceDocumentId={props.source.id}+ />++ <ActionMenu+ editor={props.editor}+ menu={props.editing.menus.actions}+ actionContext={{+ sourceDocumentId: props.source.id,+ sourceBlockName: props.source.blockName,+ disableMentionTracking: !props.source.trackMentions,+ }}+ />++ <FloatingMenuGroup>+ <FloatingLinkMenu autoLinkMatchMode="common-tlds" />+ <FloatingEquationMenu canEdit={props.canEdit} />+ <FloatingTableMenu canEdit={props.canEdit} />+ {props.floatingMenus}+ </FloatingMenuGroup>++ <Show when={props.canEdit()}>+ {/* On touch devices the hover-driven controls are unusable */}+ {isTouchDevice() ? (+ <TableSelectionActionBar />+ ) : (+ <>+ <TableInsertButton />+ <TableDeleteButtons />+ </>+ )}+ <TableCellResizer />+ <TableMoveHandle />+ </Show>+ </>+ );+}diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/editing/entityDrop.ts b/apps/web/src/lib/core/component/LexicalMarkdown/editing/entityDrop.tsnew file mode 100644index 0000000000..fdeafb7d56--- /dev/null+++ b/apps/web/src/lib/core/component/LexicalMarkdown/editing/entityDrop.ts@@ -0,0 +1,153 @@+/**+ * @file Dropping app items (documents, channels, media...) dragged from lists+ * into a markdown editor: media becomes inline media, everything else a+ * mention at the drop point.+ */++import { URL_PARAMS as CHANNEL_PARAMS } from '@block-channel/constants';+import type { BlockName } from '@core/block';+import { itemToBlockName } from '@core/constant/allBlocks';+import { trackMention } from '@core/signal/mention';+import { type EntityDragEvent, isEntityDragEvent } from '@entity';+import { throttle } from '@solid-primitives/scheduled';+import { createDroppable, useDragDropContext } from '@thisbeyond/solid-dnd';+import type { LexicalEditor } from 'lexical';+import type { Accessor } from 'solid-js';+import { INSERT_MEDIA_COMMAND } from '../plugins/media';+import {+ getValidDragInsertPosition,+ insertDocumentMentionAtDragInsertPosition,+ updateDragInsertPreviewFromCoordinates,+} from '../utils/dragInsertUtils';+import { getDragDropPosition } from '../utils/fileUploadUtils';+import type {+ MarkdownEditing,+ MarkdownEditingSource,+} from './registerMarkdownEditing';++/** Accept item drags over the editor; returns the `use:` droppable directive. */+export function useEditorEntityDrop(props: {+ editor: LexicalEditor;+ canEdit: Accessor<boolean>;+ dragInsert: MarkdownEditing['dragInsert'];+ source: MarkdownEditingSource;+}) {+ const { editor } = props;+ const [dragInsertStore, setDragInsertStore] = props.dragInsert;+ const droppable = createDroppable(editor._config.namespace, {+ type: 'markdown-editor',+ });++ const [dragDropState, { onDragEnd, onDragMove }] = useDragDropContext() ?? [+ undefined,+ {+ onDragEnd: () => {},+ onDragMove: () => {},+ },+ ];++ // turn the solid dnd events into something we can use.+ const wrapDndEvent = (event: EntityDragEvent) => {+ const currentPos = dragDropState?.active.sensor?.coordinates?.current;+ if (!currentPos) return;+ const mousePos = {+ clientX: currentPos.x,+ clientY: currentPos.y,+ };+ const item = event.draggable.data;+ if (item.type === 'foreign') return;+ const blockName = itemToBlockName(item);+ if (!blockName) return;+ let id = event.draggable.data.id as string;+ if (event.draggable.data.type === 'channel_message') {+ id = event.draggable.data.channelId;+ }+ return {+ id,+ blockName: blockName as BlockName,+ mousePos,+ item,+ };+ };++ const dndDragEnd = async (event: EntityDragEvent) => {+ if (!dragInsertStore.visible) return;+ setDragInsertStore({ visible: false });+ if (!props.canEdit()) return;++ const res = wrapDndEvent(event);+ if (!res) return;++ if (res.blockName === 'image' || res.blockName === 'video') {+ getDragDropPosition(editor, res.mousePos, true);+ editor.dispatchCommand(INSERT_MEDIA_COMMAND, {+ type: 'dss',+ id: res.id,+ mediaType: res.blockName,+ });+ return;+ }++ if (res.blockName === undefined) return;+ const dragInsertPosition = getValidDragInsertPosition(editor, res.mousePos);+ if (!dragInsertPosition) return;++ const mentionId = props.source.trackMentions+ ? await trackMention(+ props.source.id,+ res.item.type === 'agent_session' ? 'agent_session' : 'document',+ res.id+ )+ : undefined;++ 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;+ }+ }++ insertDocumentMentionAtDragInsertPosition(editor, dragInsertPosition, {+ documentId: res.id,+ documentName: res.item.name,+ blockName: res.blockName,+ blockParams,+ mentionUuid: mentionId,+ createdAt: Date.now(),+ });+ };++ const dndDragMove = throttle((event: EntityDragEvent) => {+ if (!droppable.isActiveDroppable) {+ return setDragInsertStore({ visible: false });+ }+ const res = wrapDndEvent(event);+ if (!res) return;+ const { mousePos } = res;+ updateDragInsertPreviewFromCoordinates({+ editor,+ coordinates: mousePos,+ setState: setDragInsertStore,+ });+ }, 60);++ onDragEnd((event) => {+ // dndDragMove is a trailing throttle, so a callback scheduled just before+ // the drop would otherwise fire after it and could re-show the indicator.+ dndDragMove.clear();+ // Only soup entity drags insert mentions (not e.g. sidebar favorite drags).+ if (!isEntityDragEvent(event)) return;+ dndDragEnd(event);+ });++ onDragMove((event) => {+ if (!isEntityDragEvent(event)) return;+ dndDragMove(event);+ });++ return droppable;+}diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/editing/registerMarkdownEditing.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/editing/registerMarkdownEditing.test.tsnew file mode 100644index 0000000000..3e3708a43b--- /dev/null+++ b/apps/web/src/lib/core/component/LexicalMarkdown/editing/registerMarkdownEditing.test.ts@@ -0,0 +1,245 @@+import { createRoot } from 'solid-js';+import { createStore } from 'solid-js/store';+import { describe, expect, it, vi } from 'vitest';++type Tagged = ((...args: unknown[]) => () => void) & {+ tag: string;+ args: unknown[];+};++const factory = vi.hoisted(+ () =>+ (tag: string) =>+ (...args: unknown[]) =>+ Object.assign(() => () => {}, { tag, args })+);++vi.mock('@core/constant/isMac', () => ({ IS_MAC: false }));+vi.mock('@core/context/user', () => ({+ useUserId: () => () => 'macro|[email protected]',+}));+vi.mock('@core/util/upload', () => ({ handleFileFolderDrop: vi.fn() }));+vi.mock('@macro-inc/lexical-core', () => ({+ AwaitNode: {},+ CommentNode: {},+ InlineSearchNode: {},+ peerIdPlugin: factory('peerId'),+}));+vi.mock('../plugins', () => ({+ awaitPlugin: factory('await'),+ createDraggableBlockStore: () => createStore({}),+ createDragInsertStore: () => createStore({ visible: false }),+ DefaultShortcuts: [],+ documentMetadataPlugin: factory('documentMetadata'),+ draggableBlockPlugin: factory('draggableBlock'),+ dragInsertPlugin: factory('dragInsert'),+ filePastePlugin: factory('filePaste'),+ horizontalRulePlugin: factory('horizontalRule'),+ keyboardShortcutsPlugin: factory('keyboardShortcuts'),+ listSwipeIndentPlugin: factory('listSwipeIndent'),+ listToTablePlugin: factory('listToTable'),+ markdownPastePlugin: factory('markdownPaste'),+ mentionsPlugin: factory('mentions'),+ selectionDataPlugin: factory('selectionData'),+ tabIndentationPlugin: factory('tabIndentation'),+ tableCellResizerPlugin: factory('tableCellResizer'),+ tablePlugin: factory('table'),+ tableTouchSelectionPlugin: factory('tableTouchSelection'),+ textPastePlugin: factory('textPaste'),+ trailingParagraphPlugin: factory('trailingParagraph'),+}));+vi.mock('../plugins/actions/actionsPlugin', () => ({+ actionsPlugin: factory('actions'),+}));+vi.mock('../plugins/block-decorator-navigation', () => ({+ blockDecoratorNavigationPlugin: factory('blockDecoratorNavigation'),+}));+vi.mock('../plugins/checkbox-to-task', () => ({+ CONVERT_CHECKBOXES_TO_TASKS: 'convert',+ checkboxToTaskPlugin: factory('checkboxToTask'),+}));+vi.mock('../plugins/code/codePlugin', () => ({ codePlugin: factory('code') }));+vi.mock('../plugins/emojis/emojisPlugin', () => ({+ emojisPlugin: factory('emojis'),+}));+vi.mock('../plugins/ios-cursor-scroll', () => ({+ iosCursorScrollPlugin: factory('iosCursorScroll'),+}));+vi.mock('../plugins/media', () => ({ mediaPlugin: factory('media') }));+vi.mock('../plugins/node-accessory', () => ({+ createAccessoryStore: () => createStore({}),+}));+vi.mock('../plugins/normalize-enter/', () => ({+ normalizeEnterPlugin: factory('normalizeEnter'),+}));+vi.mock('../plugins/restore-focus', () => ({+ restoreFocusPlugin: factory('restoreFocus'),+}));+vi.mock('../plugins/snippets', () => ({ snippetsPlugin: factory('snippets') }));+vi.mock('../utils/fileUploadUtils', () => ({+ createFilesReadyHandler: vi.fn(),+ getDragDropPosition: vi.fn(),+}));++import { handleFileFolderDrop } from '@core/util/upload';+import type { LexicalWrapper } from '../context/LexicalWrapperContext';+import { createFilesReadyHandler } from '../utils/fileUploadUtils';+import {+ type MarkdownEditingOptions,+ registerMarkdownEditing,+} from './registerMarkdownEditing';++const slot = (tag: string) => factory(tag)();++function register(options: Partial<MarkdownEditingOptions> = {}) {+ const registered: Tagged[] = [];+ const plugins = {+ use(pluginFn: Tagged) {+ registered.push(pluginFn);+ return plugins;+ },+ };+ const lexicalWrapper = {+ editor: {},+ plugins,+ } as unknown as LexicalWrapper;+ const editing = createRoot(() =>+ registerMarkdownEditing({+ lexicalWrapper,+ isContentEditable: () => true,+ peerIdValidator: (() => true) as never,+ source: { id: 'doc-1', trackMentions: true },+ onVersionError: () => {},+ ...options,+ })+ );+ return { editing, registered, tags: () => registered.map((p) => p.tag) };+}++const SHARED_HEAD = [+ 'tabIndentation',+ 'listSwipeIndent',+ 'selectionData',+ 'horizontalRule',+ 'emojis',+ 'mentions',+];+const SHARED_MIDDLE = [+ 'snippets',+ 'actions',+ 'media',+ 'blockDecoratorNavigation',+ 'table',+ 'tableCellResizer',+ 'tableTouchSelection',+ 'filePaste',+];+const SHARED_TAIL = [+ 'dragInsert',+ 'textPaste',+ 'restoreFocus',+ 'markdownPaste',+ 'normalizeEnter',+ 'trailingParagraph',+ 'checkboxToTask',+ 'keyboardShortcuts',+ 'documentMetadata',+];++describe('registerMarkdownEditing', () => {+ it('registers document features at their fixed points in the document editor order', () => {+ const { tags } = register({+ peerId: () => 'peer',+ iosScrollContainer: () => undefined,+ slots: {+ afterMentions: [slot('tags')],+ afterFilePaste: [slot('findAndReplace')],+ beforeAwait: [slot('pinnedProperties')],+ beforeCode: () => [slot('diff'), slot('generate')],+ },+ });+ expect(tags()).toEqual([+ ...SHARED_HEAD,+ 'tags',+ ...SHARED_MIDDLE,+ 'findAndReplace',+ ...SHARED_TAIL,+ 'pinnedProperties',+ 'await',+ 'iosCursorScroll',+ 'peerId',+ 'diff',+ 'generate',+ 'code',+ 'listToTable',+ ]);+ });++ it('gives a surface the same editing features without document slots', () => {+ const { tags } = register({ peerId: () => 'peer' });+ expect(tags()).toEqual([+ ...SHARED_HEAD,+ ...SHARED_MIDDLE,+ ...SHARED_TAIL,+ 'await',+ 'peerId',+ 'code',+ 'listToTable',+ ]);+ });++ it('shares the code block accessories with the before-code slot', () => {+ const beforeCode = vi.fn(() => []);+ const { registered } = register({ slots: { beforeCode } });+ const [[accessories]] = beforeCode.mock.calls as unknown as [+ [[object, unknown]],+ ];+ const code = registered.find((p) => p.tag === 'code');+ expect(code?.args[0]).toMatchObject({+ accessories: accessories[0],+ setAccessories: accessories[1],+ });+ });++ it('tracks mentions and uploads only for document sources', () => {+ const tracked = register();+ const untracked = register({+ source: { id: 'surface-1', trackMentions: false },+ });+ const mentions = (r: ReturnType<typeof register>) =>+ r.registered.find((p) => p.tag === 'mentions')?.args[0];+ expect(mentions(tracked)).toMatchObject({+ sourceDocumentId: 'doc-1',+ disableMentionTracking: false,+ });+ expect(mentions(untracked)).toMatchObject({+ sourceDocumentId: 'surface-1',+ disableMentionTracking: true,+ });++ untracked.editing.dropFiles([], [], {} as DragEvent);+ tracked.editing.dropFiles([], [], {} as DragEvent, 'md');+ expect(handleFileFolderDrop).toHaveBeenCalledTimes(2);+ expect(vi.mocked(createFilesReadyHandler).mock.calls).toEqual([+ [{}, undefined, undefined, expect.any(Function)],+ [{}, 'doc-1', 'md', expect.any(Function)],+ ]);+ });++ it('tracks drags over the connected container', () => {+ const { editing, registered } = register();+ const container = document.createElement('div');+ editing.connectContainer(container);+ expect(registered.slice(-2).map((p) => [p.tag, p.args[0]])).toEqual([+ ['dragInsert', expect.objectContaining({ dragListenerRef: container })],+ ['draggableBlock', expect.objectContaining({ anchorElem: container })],+ ]);+ });++ it('reports open inline menus', () => {+ const { editing } = register();+ expect(editing.isInlineMenuOpen()).toBe(false);+ editing.menus.actions.setIsOpen(true);+ expect(editing.isInlineMenuOpen()).toBe(true);+ });+});diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/editing/registerMarkdownEditing.ts b/apps/web/src/lib/core/component/LexicalMarkdown/editing/registerMarkdownEditing.tsnew file mode 100644index 0000000000..b58fa648e1--- /dev/null+++ b/apps/web/src/lib/core/component/LexicalMarkdown/editing/registerMarkdownEditing.ts@@ -0,0 +1,295 @@+/**+ * @file The general editing features of a markdown document editor: block+ * types, inline menus, tables, code, media, file paste and drop, and block+ * dragging. Document editors and collaborative surfaces register the same set.+ * Features that belong to a document (tags, find and replace, pinned+ * properties, diff, AI generation) plug into named slots, so the registration+ * order stays the document editor's.+ */++import type { BlockName } from '@core/block';+import { IS_MAC } from '@core/constant/isMac';+import { useUserId } from '@core/context/user';+import { handleFileFolderDrop } from '@core/util/upload';+import {+ AwaitNode,+ CommentNode,+ InlineSearchNode,+ type PeerIdValidator,+ peerIdPlugin,+} from '@macro-inc/lexical-core';+import type { Accessor } from 'solid-js';+import type { MarkdownEditorErrors } from '../constants';+import type { LexicalWrapper } from '../context/LexicalWrapperContext';+import {+ awaitPlugin,+ createDraggableBlockStore,+ createDragInsertStore,+ DefaultShortcuts,+ documentMetadataPlugin,+ draggableBlockPlugin,+ dragInsertPlugin,+ filePastePlugin,+ horizontalRulePlugin,+ keyboardShortcutsPlugin,+ listSwipeIndentPlugin,+ listToTablePlugin,+ markdownPastePlugin,+ mentionsPlugin,+ type PluginFunction,+ selectionDataPlugin,+ tabIndentationPlugin,+ tableCellResizerPlugin,+ tablePlugin,+ tableTouchSelectionPlugin,+ textPastePlugin,+ trailingParagraphPlugin,+} from '../plugins';+import { actionsPlugin } from '../plugins/actions/actionsPlugin';+import { blockDecoratorNavigationPlugin } from '../plugins/block-decorator-navigation';+import {+ CONVERT_CHECKBOXES_TO_TASKS,+ checkboxToTaskPlugin,+} from '../plugins/checkbox-to-task';+import { codePlugin } from '../plugins/code/codePlugin';+import { emojisPlugin } from '../plugins/emojis/emojisPlugin';+import { iosCursorScrollPlugin } from '../plugins/ios-cursor-scroll';+import { mediaPlugin } from '../plugins/media';+import { createAccessoryStore } from '../plugins/node-accessory';+import { normalizeEnterPlugin } from '../plugins/normalize-enter/';+import { restoreFocusPlugin } from '../plugins/restore-focus';+import { snippetsPlugin } from '../plugins/snippets';+import type { MentionLinkResolver } from '../plugins/text-paste/textPastePlugin';+import { createMenuOperations } from '../shared/inlineMenu';+import {+ createFilesReadyHandler,+ getDragDropPosition,+} from '../utils/fileUploadUtils';++/** Where the edited content lives. */+export type MarkdownEditingSource = {+ /** The document or surface id: the source of snippets and mentions. */+ id: string;+ /** The block hosting the editor, for actions such as the slash task. */+ blockName?: string;+ /**+ * Record inserted mentions as references from this source. Only documents+ * are mention sources, so other surfaces insert untracked mentions.+ */+ trackMentions: boolean;+};++type AccessoryStoreSignal = ReturnType<typeof createAccessoryStore>;++/** Document features registered at fixed points of the shared chain. */+export type MarkdownEditingSlots = {+ /** After mentions, e.g. tags. */+ afterMentions?: PluginFunction[];+ /** After file paste, e.g. find and replace. */+ afterFilePaste?: PluginFunction[];+ /** Before the await plugin, e.g. pinned properties. */+ beforeAwait?: PluginFunction[];+ /** Before code blocks, sharing their node accessories, e.g. diff and AI generation. */+ beforeCode?: (accessories: AccessoryStoreSignal) => PluginFunction[];+};++export type MarkdownEditingOptions = {+ lexicalWrapper: LexicalWrapper;+ isContentEditable: Accessor<boolean>;+ /** Keeps this peer from committing another peer's in-flight inline nodes. */+ peerIdValidator: PeerIdValidator;+ source: MarkdownEditingSource;+ resolveAppLink?: MentionLinkResolver;+ /** Checklist items converted to tasks become subtasks of this task. */+ parentTaskId?: string;+ onVersionError: (error: MarkdownEditorErrors) => void;+ /** The local collaboration peer, for collaborative editors. */+ peerId?: () => string;+ /** On iOS, keeps the caret visible inside this scroll container. */+ iosScrollContainer?: () => HTMLElement | undefined;+ slots?: MarkdownEditingSlots;+};++/** Register the general editing features after the base rich-text plugins. */+export function registerMarkdownEditing(options: MarkdownEditingOptions) {+ const { lexicalWrapper, peerIdValidator, source, slots } = options;+ const { editor, plugins } = lexicalWrapper;+ const userId = useUserId();+ const filesBlockId = source.trackMentions ? source.id : undefined;++ const menus = {+ emoji: createMenuOperations(),+ mentions: createMenuOperations(),+ actions: createMenuOperations(),+ snippets: createMenuOperations(),+ };+ const dragInsert = createDragInsertStore();+ const draggableBlock = createDraggableBlockStore();+ const accessories = createAccessoryStore();+ const [, setDragInsertStore] = dragInsert;+ const [, setDraggableBlockStore] = draggableBlock;+ const [accessoryStore, setAccessoryStore] = accessories;+ let container: HTMLDivElement | undefined;++ const useAll = (pluginFns: PluginFunction[] | undefined) => {+ for (const pluginFn of pluginFns ?? []) plugins.use(pluginFn);+ };++ plugins+ .use(tabIndentationPlugin())+ .use(listSwipeIndentPlugin(options.isContentEditable))+ .use(selectionDataPlugin(lexicalWrapper))+ .use(horizontalRulePlugin())+ .use(emojisPlugin({ menu: menus.emoji, peerIdValidator }))+ .use(+ mentionsPlugin({+ menu: menus.mentions,+ peerIdValidator,+ sourceDocumentId: source.id,+ disableMentionTracking: !source.trackMentions,+ })+ );+ useAll(slots?.afterMentions);+ plugins+ .use(+ snippetsPlugin({+ menu: menus.snippets,+ peerIdValidator,+ sourceDocumentId: source.id,+ })+ )+ .use(actionsPlugin({ menu: menus.actions, peerIdValidator }))+ .use(mediaPlugin())+ .use(blockDecoratorNavigationPlugin())+ .use(+ tablePlugin({+ hasCellMerge: true,+ hasCellBackgroundColor: true,+ hasTabHandler: true,+ hasHorizontalScroll: true,+ })+ )+ .use(tableCellResizerPlugin())+ .use(tableTouchSelectionPlugin())+ .use(+ filePastePlugin({+ onPasteFilesAndDirs: (fileEntries, directories) =>+ handleFileFolderDrop(+ fileEntries,+ directories,+ createFilesReadyHandler(editor, filesBlockId)+ ),+ })+ );+ useAll(slots?.afterFilePaste);+ plugins+ .use(+ dragInsertPlugin({+ setState: setDragInsertStore,+ dragListenerRef: container,+ })+ )+ .use(textPastePlugin(options.resolveAppLink))+ .use(restoreFocusPlugin())+ .use(markdownPastePlugin())+ .use(normalizeEnterPlugin())+ .use(trailingParagraphPlugin())+ .use(+ checkboxToTaskPlugin({+ currentUserId: userId(),+ parentTaskId: options.parentTaskId,+ })+ )+ .use(+ keyboardShortcutsPlugin({+ shortcuts: [+ ...DefaultShortcuts,+ {+ label: `${IS_MAC ? 'meta' : 'ctrl'}+shift+o`,+ test: (e) =>+ e.code === 'KeyO' &&+ e.shiftKey &&+ (IS_MAC ? e.metaKey : e.ctrlKey),+ handler: (editor) => {+ const userId = useUserId()();+ if (!userId) return;+ editor.dispatchCommand(CONVERT_CHECKBOXES_TO_TASKS, {});+ },+ priority: 0,+ },+ ],+ })+ )+ .use(documentMetadataPlugin({ onVersionError: options.onVersionError }));+ useAll(slots?.beforeAwait);+ plugins.use(awaitPlugin());++ if (options.iosScrollContainer) {+ plugins.use(+ iosCursorScrollPlugin({ scrollContainer: options.iosScrollContainer })+ );+ }+ if (options.peerId) {+ plugins.use(+ peerIdPlugin({+ peerId: options.peerId,+ nodes: [InlineSearchNode, CommentNode, AwaitNode],+ })+ );+ }+ useAll(slots?.beforeCode?.(accessories));+ plugins+ .use(+ codePlugin({+ accessories: accessoryStore,+ setAccessories: setAccessoryStore,+ })+ )+ .use(listToTablePlugin());++ return {+ menus,+ dragInsert,+ draggableBlock,+ accessories,+ /** Whether an inline menu owns the arrow and enter keys. */+ isInlineMenuOpen: () =>+ menus.mentions.isOpen() ||+ menus.emoji.isOpen() ||+ menus.actions.isOpen() ||+ menus.snippets.isOpen(),+ /** Register the plugins that track drags over the editor's container. */+ connectContainer(element: HTMLDivElement) {+ container = element;+ plugins.use(+ dragInsertPlugin({+ setState: setDragInsertStore,+ dragListenerRef: element,+ })+ );+ plugins.use(+ draggableBlockPlugin({+ setState: setDraggableBlockStore,+ anchorElem: element,+ })+ );+ },+ /** Upload files dropped on the editor and insert them at the drop point. */+ dropFiles(+ fileEntries: FileSystemFileEntry[],+ folderEntries: FileSystemDirectoryEntry[],+ event: DragEvent,+ blockName?: BlockName+ ) {+ handleFileFolderDrop(+ fileEntries,+ folderEntries,+ createFilesReadyHandler(editor, filesBlockId, blockName, () =>+ getDragDropPosition(editor, event, true)+ )+ );+ },+ };+}++export type MarkdownEditing = ReturnType<typeof registerMarkdownEditing>;diff --git a/docs/AGENT_GUIDE/tasks.md b/docs/AGENT_GUIDE/tasks.mdindex 8674e1376b..be8b08d326 100644--- a/docs/AGENT_GUIDE/tasks.md+++ b/docs/AGENT_GUIDE/tasks.md@@ -245,6 +245,15 @@ project's collab surface and saves automatically; its access follows projectaccess. Edit/owner access allows typing; view/comment access is read-only. Twotabs on the same project see each other's edits live. The description is partof the native project view and does not open a separate document block.+It edits like a markdown document body: `/` opens the commands menu (headings,+lists, checklists, quotes, code blocks, tables, equations, links, images,+video, dividers, and creating a task), `@` mentions, `:` emoji, `;` snippets,+and markdown shortcuts work. Tables have the document's insert, resize, move,+and delete controls; blocks have drag handles; files and images can be pasted+or dropped in, and items dragged from lists insert mentions. Mentions in a+description are not tracked as document references, so mentioned users are not+notified. Document-only tools (comments, tags, AI writing, find and replace) are+not available in descriptions.Discussion appears below the description, using the same discussion componentas tasks. The surface has the project's id and is created on first open, or atcreation when one is given (agents can pass a description). Projects no longer