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(md): add MarkdownShell and fluent config builder for simple md feature sharing (#1704)
Seamus4eba5026df2e
diff --git a/js/app/packages/app/component/SoupChatInput.tsx b/js/app/packages/app/component/SoupChatInput.tsxindex 8d69e50589..3c2dd32be8 100644--- a/js/app/packages/app/component/SoupChatInput.tsx+++ b/js/app/packages/app/component/SoupChatInput.tsx@@ -1,27 +1,41 @@import { useSoup } from '@app/component/next-soup/soup-context';import type { ChatSendInput } from '@core/component/AI/component/input/buildRequest';-import { useChatMarkdownArea } from '@core/component/AI/component/input/useChatMarkdownArea';import {ChatInputProvider,useChatInputContext,} from '@core/component/AI/context';+import { useGetChatAttachmentInfo } from '@core/component/AI/signal/attachment';import { setPendingSendData } from '@core/component/AI/signal/pendingSend';+import { buildChatEditor } from '@core/component/AI/component/input/buildChatEditor';+import { ENABLE_SNAPSHOT_NODE } from '@core/constant/featureFlags';import { TOKENS } from '@core/hotkey/tokens';import { isErr } from '@core/util/maybeResult';+import { withAnalytics } from '@coparse/analytics';import { cognitionApiServiceClient } from '@service-cognition/client';import { ChatInput } from 'core/component/AI/component/input/ChatInput';import { registerHotkey, useHotkeyDOMScope } from 'core/hotkey/hotkeys';import { onMount, Show } from 'solid-js';import { useSplitPanelOrThrow } from './split-layout/layoutUtils';+const { track, TrackingEvents } = withAnalytics();+function SoupChatInputInner() {let containerRef!: HTMLDivElement;const splitPanelContext = useSplitPanelOrThrow();const soup = useSoup();const input = useChatInputContext();- const chatMarkdownArea = useChatMarkdownArea({- addAttachment: (a) => input.attachments.addAttachment(a),+ const { getAttachmentFromMention } = useGetChatAttachmentInfo();++ const editor = buildChatEditor().withMentions({+ onCreate: (mention) => {+ track(TrackingEvents.CHAT.MENTION.SELECT);+ const attachment = getAttachmentFromMention(mention);+ if (attachment) input.attachments.addAttachment(attachment);+ },+ block: 'chat',+ showOpenTabs: true,+ useSnapshotForDocuments: ENABLE_SNAPSHOT_NODE,});const [attachHotkeys] = useHotkeyDOMScope('soup.chatInput');@@ -37,7 +51,7 @@ function SoupChatInputInner() {hotkeyToken: TOKENS.chat.input.focus,description: 'Focus chat input',keyDownHandler: () => {- chatMarkdownArea.focus();+ editor.controls.focus();return true;},});@@ -78,7 +92,7 @@ function SoupChatInputInner() {<div class="w-full max-w-3xl"><div class="pointer-events-auto"><ChatInput- markdown={chatMarkdownArea}+ editor={editor}onSend={handleSend}onEscape={() => {splitPanelContext.panelRef()?.focus();diff --git a/js/app/packages/app/component/split-layout/componentRegistry.tsx b/js/app/packages/app/component/split-layout/componentRegistry.tsxindex d1e9120090..6f69626ab3 100644--- a/js/app/packages/app/component/split-layout/componentRegistry.tsx+++ b/js/app/packages/app/component/split-layout/componentRegistry.tsx@@ -170,4 +170,10 @@ if (DEV_MODE_ENV) {)));+ registerComponent(+ 'md-builder',+ lazy(+ () => import('@core/component/LexicalMarkdown/builder/BuilderTestPage')+ )+ );}diff --git a/js/app/packages/block-chat/component/Chat.tsx b/js/app/packages/block-chat/component/Chat.tsxindex c92a51aa74..789a1a03a0 100644--- a/js/app/packages/block-chat/component/Chat.tsx+++ b/js/app/packages/block-chat/component/Chat.tsx@@ -7,7 +7,6 @@ import { useBlockId } from '@core/block';import { DragDropWrapper } from '@core/component/AI/component/DragDrop';import type { ChatSendInput } from '@core/component/AI/component/input/buildRequest';import { useSendChatMessage } from '@core/component/AI/component/input/buildRequest';-import { useChatMarkdownArea } from '@core/component/AI/component/input/useChatMarkdownArea';import { ChatMessages } from '@core/component/AI/component/message/ChatMessages';import {ChatInputProvider,@@ -17,14 +16,19 @@ import {} from '@core/component/AI/context';import { useEntityDropAttachment } from '@core/component/AI/hook/useEntityDropAttachment';import { getPendingSend } from '@core/component/AI/signal/pendingSend';+import { useGetChatAttachmentInfo } from '@core/component/AI/signal/attachment';import { registerToolHandler } from '@core/component/AI/signal/tool';import {getChatInputStoredState,type StoredStuff,storeChatState,} from '@core/component/AI/util/storage';+import { buildChatEditor } from '@core/component/AI/component/input/buildChatEditor';import { CustomScrollbar } from '@core/component/CustomScrollbar';-import { DEV_MODE_ENV } from '@core/constant/featureFlags';+import {+ DEV_MODE_ENV,+ ENABLE_SNAPSHOT_NODE,+} from '@core/constant/featureFlags';import { usePaywallState } from '@core/constant/PaywallState';import { TOKENS } from '@core/hotkey/tokens';import { registerScopeSignalHotkey } from '@core/hotkey/utils';@@ -35,12 +39,14 @@ import {} from '@core/signal/blockElement';import { blockHandleSignal } from '@core/signal/load';import { useCanEdit } from '@core/signal/permissions';+import { withAnalytics } from '@coparse/analytics';import { invalidateUserQuota } from '@queries/auth';import { createCallback } from '@solid-primitives/rootless';import { ChatInput } from 'core/component/AI/component/input/ChatInput';-import type { LexicalEditor } from 'lexical';import { createEffect, createSignal, Show } from 'solid-js';+const { track, TrackingEvents } = withAnalytics();+export function Chat(props: { data: ChatData }) {const loadedState = getChatInputStoredState(props.data.chat.id);@@ -70,12 +76,23 @@ function ChatInner(props: {const scopeId = blockHotkeyScopeSignal.get;const blockElement = blockElementSignal.get;const { navigatedFromJK } = useNavigatedFromJK();- const [chatEditor, setChatEditor] = createSignal<LexicalEditor>();const [scrollRef, setScrollRef] = createSignal<HTMLElement>();const [showStreamDebug, setShowStreamDebug] = createSignal(false);- const chatMarkdownArea = useChatMarkdownArea({- initialValue: props.loadedInputText,- addAttachment: (a) => input.attachments.addAttachment(a),+ const [markdownText, setMarkdownText] = createSignal(+ props.loadedInputText ?? ''+ );++ const { getAttachmentFromMention } = useGetChatAttachmentInfo();++ const editor = buildChatEditor().withMentions({+ onCreate: (mention) => {+ track(TrackingEvents.CHAT.MENTION.SELECT);+ const attachment = getAttachmentFromMention(mention);+ if (attachment) input.attachments.addAttachment(attachment);+ },+ block: 'chat',+ showOpenTabs: true,+ useSnapshotForDocuments: ENABLE_SNAPSHOT_NODE,});// Local stream signal for registerToolHandler@@ -140,7 +157,7 @@ function ChatInner(props: {};createEffect(() => {- const inputText = chatMarkdownArea.markdownText();+ const inputText = markdownText();const attached = input.attachments.attached();const model_ = input.model();saveChatState({ attachments: attached, input: inputText, model: model_ });@@ -177,12 +194,8 @@ function ChatInner(props: {hotkey: 'enter',description: 'Focus Chat Input',keyDownHandler: () => {- const editor = chatEditor();- if (editor) {- editor.focus(undefined, { defaultSelection: 'rootStart' });- return true;- }- return false;+ editor.controls.focus();+ return true;},hotkeyToken: TOKENS.block.focus,hide: true,@@ -244,10 +257,11 @@ function ChatInner(props: {<div class="flex w-full justify-center pb-2 px-4"><div class="w-3xl"><ChatInput- markdown={chatMarkdownArea}+ editor={editor}+ initialValue={props.loadedInputText}+ onChange={setMarkdownText}chatId={chat.chatId()}onSend={onSend}- captureEditor={setChatEditor}autoFocusOnMount={true}/></div>diff --git a/js/app/packages/block-md/component/ComposeTask.tsx b/js/app/packages/block-md/component/ComposeTask.tsxindex 6bf9c982f3..e960b79331 100644--- a/js/app/packages/block-md/component/ComposeTask.tsx+++ b/js/app/packages/block-md/component/ComposeTask.tsx@@ -1,12 +1,10 @@import { useSplitLayout } from '@app/component/split-layout/layout';import { useSplitPanelOrThrow } from '@app/component/split-layout/layoutUtils';import { CircleSpinner } from '@core/component/CircleSpinner';-import { DeprecatedIconButton } from '@core/component/DeprecatedIconButton';import { EntityIcon } from '@core/component/EntityIcon';import { MiniToggleSwitch } from '@core/component/FormControls/MiniToggleSwitch';import { Hotkey } from '@core/component/Hotkey';import { BlockLink } from '@core/component/LexicalMarkdown/component/core/BlockLink';-import { MarkdownTextarea } from '@core/component/LexicalMarkdown/component/core/MarkdownTextarea';import { StaticMarkdown } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';import { unifiedListMarkdownTheme } from '@core/component/LexicalMarkdown/theme';import { initializeEditorEmpty } from '@core/component/LexicalMarkdown/utils';@@ -57,6 +55,8 @@ import {saveTaskComposerDraft,updateDraftTimestamp,} from '../util/taskComposerStorage';+import { buildConfig } from '@core/component/LexicalMarkdown/builder/MarkdownConfigBuilder';+import { MarkdownShell } from '@core/component/LexicalMarkdown/builder/MarkdownShell';// Show these props in the composer.const COMPOSER_PROPERTIES = [@@ -242,6 +242,7 @@ export function ComposeTask(props: ComposeTaskProps) {return {title: draft.title,content: draft.content,+ editorState: draft.editorState,propertyValues: draft.propertyValues,isDraftLoaded: true,};@@ -250,6 +251,7 @@ export function ComposeTask(props: ComposeTaskProps) {return {title: props.initialTitle ?? '',content: props.initialContent ?? '',+ editorState: undefined,propertyValues: getDefaultPropertyValues(),isDraftLoaded: false,};@@ -295,6 +297,7 @@ export function ComposeTask(props: ComposeTaskProps) {debouncedSave({title: currentTitle,content: currentContent,+ editorState: bodyEditor()?.getEditorState().toJSON(),propertyValues: currentProperties,});});@@ -508,6 +511,25 @@ export function ComposeTask(props: ComposeTaskProps) {runWithInputFocused: true,});+ const editorConfig = buildConfig('markdown')+ .withMentions()+ .withEmojis()+ .withActions()+ .withCode()+ .withMedia({ fileDrop: true })+ .onChange(setContent)+ .onFocusLeave({+ onStart: (e) => editorFocusChange(e, -1),+ onEnd: (e) => editorFocusChange(e, +1),+ })+ .onEscape(() => {+ containerRef()?.focus();+ return true;+ });++ const editor = editorConfig.buildHandle().lexical;+ setBodyEditor(editor);+return (<divclass="flex flex-col relative bracket-never h-full max-h-full min-h-0"@@ -516,13 +538,9 @@ export function ComposeTask(props: ComposeTaskProps) {><div class="flex items-center gap-1 p-2"><Show when={splitPanel?.handle.isPopover()}>- <DeprecatedIconButton- icon={XIcon}- onClick={handleClose}- size="sm"- tabIndex={-1}- theme="current"- />+ <Button onMouseDown={handleClose} tabIndex={-1}>+ <XIcon class="size-4" />+ </Button></Show><div class="flex items-center gap-2 flex-1"><span class="text-sm font-medium text-ink-disabled/50">@@ -530,14 +548,13 @@ export function ComposeTask(props: ComposeTaskProps) {</span></div><Show when={title() || content()}>- <DeprecatedIconButton- icon={TrashIcon}- onClick={handleClearDraft}- size="sm"+ <Button+ onMouseDown={handleClearDraft}tabIndex={-1}- theme="current"- title="Clear draft"- />+ tooltip="Clear Draft"+ >+ <TrashIcon class="size-4" />+ </Button></Show></div><div class="border-b border-edge-muted/50" />@@ -577,18 +594,10 @@ export function ComposeTask(props: ComposeTaskProps) {/></div>- <MarkdownTextarea- editable={() => !isCreating()}- onChange={(value) => setContent(value)}- initialValue={content()}+ <MarkdownShell+ config={editorConfig}+ initialState={initialState.editorState}placeholder={props.placeholder ?? 'Add description...'}- captureEditor={setBodyEditor}- onEscape={() => {- containerRef()?.focus();- return true;- }}- onFocusLeaveStart={(e) => editorFocusChange(e, -1)}- onFocusLeaveEnd={(e) => editorFocusChange(e, +1)}portalScope={splitPanel.handle.isPopover() ? 'local' : 'block'}class="shrink-1 min-h-0 h-[unset] text-base m-2 overflow-y-auto"/>diff --git a/js/app/packages/block-md/util/taskComposerStorage.ts b/js/app/packages/block-md/util/taskComposerStorage.tsindex 38c5770968..acf99d9c25 100644--- a/js/app/packages/block-md/util/taskComposerStorage.ts+++ b/js/app/packages/block-md/util/taskComposerStorage.ts@@ -1,10 +1,14 @@import type { PropertyApiValues } from '@core/component/Properties/types';+import type { SerializedEditorState } from 'lexical';const STORAGE_KEY = 'task-composer-draft';const EXPIRY_TIME_MS = 2 * 60 * 1000; // 2 minutesexport interface TaskComposerDraft {title: string;+ /** Serialized Lexical editor state (lossless — preserves images, dimensions, etc.) */+ editorState?: SerializedEditorState;+ /** Markdown text fallback (used by older drafts and for the createTask API) */content: string;propertyValues: Record<string, PropertyApiValues>;timestamp: number;diff --git a/js/app/packages/core/component/AI/component/debug/Component.tsx b/js/app/packages/core/component/AI/component/debug/Component.tsxindex 1410a0de84..9e875546d2 100644--- a/js/app/packages/core/component/AI/component/debug/Component.tsx+++ b/js/app/packages/core/component/AI/component/debug/Component.tsx@@ -1,6 +1,8 @@import type { ChatSendInput } from '@core/component/AI/component/input/buildRequest';import type { Model } from '@core/component/AI/types';import { DeprecatedTextButton } from '@core/component/DeprecatedTextButton';+import { buildChatEditor } from '@core/component/AI/component/input/buildChatEditor';+import { MarkdownShell } from '@core/component/LexicalMarkdown/builder/MarkdownShell';import { isErr } from '@core/util/maybeResult';import { cognitionApiServiceClient } from '@service-cognition/client';import type { ChatMessageStream } from '@service-connection/stream';@@ -12,11 +14,9 @@ import {useChatContext,useChatInputContext,} from '../../context';-import { useAttachments } from '../../signal/attachment';import { pausableStream } from '../../util/stream';import { ChatInput } from '../input/ChatInput';import { ModelSelector } from '../input/ModelSelector';-import { useChatMarkdownArea } from '../input/useChatMarkdownArea';import { ChatMessages } from '../message/ChatMessages';import {@@ -56,20 +56,11 @@ export default function Debug() {}function ChatMarkdownArea() {- const attachments = useAttachments();- const { MarkdownArea, ref } = useChatMarkdownArea({- addAttachment: attachments.addAttachment,- });- createEffect(() => {- const el = ref();- if (el) {- el.classList.add('bg-accent/10');- }- });+ const editor = buildChatEditor();return (<Item label="chat markown area">- <MarkdownArea />+ <MarkdownShell config={editor} /></Item>);}@@ -100,9 +91,7 @@ function ChatInputBox() {function ChatInputBoxInner() {const input = useChatInputContext();- const chatMarkdownArea = useChatMarkdownArea({- addAttachment: (a) => input.attachments.addAttachment(a),- });+ const editor = buildChatEditor();return (<Item label="Chat input - not connected to backend">@@ -120,7 +109,7 @@ function ChatInputBoxInner() {/></div><ChatInput- markdown={chatMarkdownArea}+ editor={editor}onSend={(request) => console.log('request', request)}/></div>@@ -137,10 +126,7 @@ function ChatInputBoxConnected() {}function ChatInputBoxConnectedInner() {- const input = useChatInputContext();- const chatMarkdownArea = useChatMarkdownArea({- addAttachment: (a) => input.attachments.addAttachment(a),- });+ const editor = buildChatEditor();const [_gen, setGen] = createSignal(false);const onSend = async (input: ChatSendInput) => {@@ -172,7 +158,7 @@ function ChatInputBoxConnectedInner() {return (<Item label="Chat input - connected (console)"><div class="w-full h-full">- <ChatInput markdown={chatMarkdownArea} onSend={onSend} />+ <ChatInput editor={editor} onSend={onSend} /></div></Item>);@@ -240,11 +226,8 @@ function FullChat() {}function FullChatInner() {- const input = useChatInputContext();const chat = useChatContext();- const chatMarkdownArea = useChatMarkdownArea({- addAttachment: (a) => input.attachments.addAttachment(a),- });+ const editor = buildChatEditor();const [_isGen, setIsGen] = createSignal(false);const [debugStream, _setDebugStream] = createSignal<ChatMessageStream>();@@ -300,7 +283,7 @@ function FullChatInner() {<StreamStatus stream={debugStream} /><ChatMessages /><ChatInput- markdown={chatMarkdownArea}+ editor={editor}chatId={chat.chatId()}onSend={onSend}onStop={() => {}}diff --git a/js/app/packages/core/component/AI/component/input/ChatInput.tsx b/js/app/packages/core/component/AI/component/input/ChatInput.tsxindex 3044cdeab9..edb8ff5558 100644--- a/js/app/packages/core/component/AI/component/input/ChatInput.tsx+++ b/js/app/packages/core/component/AI/component/input/ChatInput.tsx@@ -1,13 +1,17 @@import { withAnalytics } from '@coparse/analytics';import type { ChatSendInput } from '@core/component/AI/component/input/buildRequest';import { useChatInputContext } from '@core/component/AI/context';-import { useChatAttachableHistory } from '@core/component/AI/signal/attachment';import type { Model, ToolSet } from '@core/component/AI/types';+import type { EditorConfigBuilder } from '@core/component/LexicalMarkdown/builder/MarkdownConfigBuilder';+import { MarkdownShell } from '@core/component/LexicalMarkdown/builder/MarkdownShell';import { DeprecatedIconButton } from '@core/component/DeprecatedIconButton';import { Hotkey } from '@core/component/Hotkey';import { Tooltip } from '@core/component/Tooltip';+import { toast } from '@core/component/Toast/Toast';+import { isMobile } from '@core/mobile/isMobile';import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';import { isTouchDevice } from '@core/mobile/isTouchDevice';+import { handleFileFolderDrop } from '@core/util/upload';import ArrowUp from '@icon/bold/arrow-up-bold.svg';import PlusIcon from '@icon/regular/plus.svg';import XIcon from '@icon/regular/x.svg';@@ -15,12 +19,10 @@ import Stop from '@phosphor-icons/core/regular/stop.svg';import { createCallback } from '@solid-primitives/rootless';import { Button } from '@ui/components/Button';import { cn } from '@ui/utils/classname';-import type { LexicalEditor } from 'lexical';import { createEffect, createSignal, Match, Show, Switch } from 'solid-js';import { AttachmentList } from './Attachment';import { ChatAttachMenu } from './ChatAttachMenu';import { useAiDataConsentGate } from './useAiDataConsent';-import type { UseChatMarkdown } from './useChatMarkdownArea';const { track, TrackingEvents } = withAnalytics();@@ -30,13 +32,14 @@ export type ChatInputProps = {onEscape?: (e: KeyboardEvent) => boolean;isPersistent?: boolean;showActiveTabs?: boolean;- captureEditor?: (editor: LexicalEditor) => void;autoFocusOnMount?: boolean;chatId?: string;};export type ChatInputComponentProps = {- markdown: UseChatMarkdown;+ editor: EditorConfigBuilder;+ initialValue?: string;+ onChange?: (markdown: string) => void;} & ChatInputProps;export function ChatInput(props: ChatInputComponentProps) {@@ -53,6 +56,7 @@ export function ChatInput(props: ChatInputComponentProps) {const [showAttachMenu, setShowAttachMenu] = createSignal(false);const [attachMenuAnchorRef, setAttachMenuAnchorRef] =createSignal<HTMLDivElement>();+ const [markdownText, setMarkdownText] = createSignal('');createEffect(() => {const uploaded = uploadQueue.popComplete();@@ -64,7 +68,7 @@ export function ChatInput(props: ChatInputComponentProps) {});});- const isEmptyInput = () => props.markdown.markdownText().trim().length === 0;+ const isEmptyInput = () => markdownText().trim().length === 0;const hasUploadingAttachments = () => uploadQueue.uploading().length > 0;const canSendMessage = () =>!isEmptyInput() && !generating() && !hasUploadingAttachments();@@ -73,7 +77,7 @@ export function ChatInput(props: ChatInputComponentProps) {let mdRef: undefined | HTMLDivElement;const isMultiline = () => {// Access markdownText to create reactive dependency- const text = props.markdown.markdownText();+ const text = markdownText();if (text.trim().length === 0) return false;if (!mdRef) return false;return mdRef.scrollHeight > LINE_HEIGHT_THRESHOLD;@@ -87,30 +91,39 @@ export function ChatInput(props: ChatInputComponentProps) {return;}- const input: ChatSendInput = {- content: props.markdown.markdownText(),+ const sendInput: ChatSendInput = {+ content: markdownText(),model: modelOverride ?? model(),attachments: attachments.attached(),toolset: toolsetSignal[0](),};- props.markdown.clear();- props.onSend(input);+ props.editor.controls.clear();+ props.onSend(sendInput);});- function handleEnter(e: KeyboardEvent): boolean {- if (e.key === 'Enter' && !e.shiftKey) {- e.preventDefault();-+ props.editor+ .withFilePaste({+ onPasteFilesAndDirs: (files, directories) => {+ if (directories.length > 0) {+ toast.failure('Folder upload not supported here');+ return;+ }+ handleFileFolderDrop(files, directories, (entries) => {+ uploadQueue.upload(entries.map((e) => e.file));+ });+ },+ })+ .onEnter(() => {if (canSendMessage()) {sendMessage();}return true;- } else {- return false;- }- }-- const availableAttachments = useChatAttachableHistory();+ })+ .onEscape((e) => props.onEscape?.(e) ?? false)+ .onChange((md) => {+ setMarkdownText(md);+ props.onChange?.(md);+ });const hasAttachments = () =>attachments.attached().length > 0 || uploadQueue.uploading().length > 0;@@ -211,16 +224,15 @@ export function ChatInput(props: ChatInputComponentProps) {}}ref={mdRef}>- <props.markdown.MarkdownArea- onEnter={handleEnter}- onEscape={props.onEscape}+ <MarkdownShell+ config={props.editor}placeholder="Ask AI, @mention anything"- history={availableAttachments}- dontFocusOnMount={- isTouchDevice() || props.autoFocusOnMount === false+ initialValue={props.initialValue}+ autofocus={+ !isMobile() &&+ !isTouchDevice() &&+ props.autoFocusOnMount !== false}- onPasteFile={uploadQueue.upload}- captureEditor={props.captureEditor}/></div>diff --git a/js/app/packages/core/component/AI/component/input/buildChatEditor.ts b/js/app/packages/core/component/AI/component/input/buildChatEditor.tsnew file mode 100644index 0000000000..099998dcc0--- /dev/null+++ b/js/app/packages/core/component/AI/component/input/buildChatEditor.ts@@ -0,0 +1,32 @@+import { buildConfig } from '@core/component/LexicalMarkdown/builder/MarkdownConfigBuilder';+import {+ DefaultShortcuts,+ keyboardShortcutsPlugin,+} from '@core/component/LexicalMarkdown/plugins';+import { tableCellResizerPlugin } from '@core/component/LexicalMarkdown/plugins/tables/tableCellResizerPlugin';+import { tablePlugin } from '@core/component/LexicalMarkdown/plugins/tables/tablePlugin';++/**+ * Shared chat editor builder with all standard plugins.+ * Consumers chain `.withMentions({ onCreate })` for mention handling.+ */+export function buildChatEditor() {+ return buildConfig('chat')+ .namespace('chat-markdown-area')+ .withEmojis()+ .withLinks({ floatingMenu: true })+ .withHistory({ timeGap: 400 })+ .withCode()+ .withRestoreFocus()+ .withSelectionData()+ .use(+ tablePlugin({+ hasCellMerge: true,+ hasCellBackgroundColor: false,+ hasTabHandler: true,+ hasHorizontalScroll: true,+ })+ )+ .use(tableCellResizerPlugin())+ .use(keyboardShortcutsPlugin({ shortcuts: DefaultShortcuts }));+}diff --git a/js/app/packages/core/component/AI/component/input/useChatMarkdownArea.tsx b/js/app/packages/core/component/AI/component/input/useChatMarkdownArea.tsxdeleted file mode 100644index bb41a84a25..0000000000--- a/js/app/packages/core/component/AI/component/input/useChatMarkdownArea.tsx+++ /dev/null@@ -1,457 +0,0 @@-import { withAnalytics } from '@coparse/analytics';-import { useGetChatAttachmentInfo } from '@core/component/AI/signal/attachment';-import type { Attachment } from '@core/component/AI/types';-import { DecoratorRenderer } from '@core/component/LexicalMarkdown/component/core/DecoratorRenderer';-import { NodeAccessoryRenderer } from '@core/component/LexicalMarkdown/component/core/NodeAccessoryRenderer';-import { EmojiMenu } from '@core/component/LexicalMarkdown/component/menu/EmojiMenu';-import { FloatingLinkMenu } from '@core/component/LexicalMarkdown/component/menu/FloatingLinkMenu';-import { MentionsMenu } from '@core/component/LexicalMarkdown/component/menu/MentionsMenu';-import { FloatingMenuGroup } from '@core/component/LexicalMarkdown/context/FloatingMenuContext';-import {- createLexicalWrapper,- type LexicalWrapper,- LexicalWrapperContext,-} from '@core/component/LexicalMarkdown/context/LexicalWrapperContext';-import {- autoRegister,- customSelectionDataPlugin,- DefaultShortcuts,- defaultSelectionData,- type ItemMention,- keyboardFocusPlugin,- keyboardShortcutsPlugin,- markdownPastePlugin,- mentionsPlugin,- NODE_TRANSFORM,- type NodeTransformType,- type SelectionData,- tabIndentationPlugin,- tableCellResizerPlugin,- tablePlugin,-} from '@core/component/LexicalMarkdown/plugins';-import { codePlugin } from '@core/component/LexicalMarkdown/plugins/code/codePlugin';-import { emojisPlugin } from '@core/component/LexicalMarkdown/plugins/emojis/emojisPlugin';-import { normalizeEnterPlugin } from '@core/component/LexicalMarkdown/plugins/normalize-enter/';-import { restoreFocusPlugin } from '@core/component/LexicalMarkdown/plugins/restore-focus';-import { createMenuOperations } from '@core/component/LexicalMarkdown/shared/inlineMenu';-import {- $traverseNodes,- editorIsEmpty,- initializeEditorEmpty,- insertText,- setEditorStateFromMarkdown,-} from '@core/component/LexicalMarkdown/utils';-import type { PortalScope } from '@core/component/ScopedPortal';-import { shortcutBadgeStyles } from '@core/component/Themes';-import { toast } from '@core/component/Toast/Toast';-import { ENABLE_SNAPSHOT_NODE } from '@core/constant/featureFlags';-import { TOKENS } from '@core/hotkey/tokens';-import { getPrettyHotkeyStringByToken } from '@core/hotkey/utils';-import { isMobile } from '@core/mobile/isMobile';-import type { IOrganizationUser } from '@core/user';-import { handleFileFolderDrop } from '@core/util/upload';-import { $isDocumentMentionNode } from '@lexical-core';-import type { HistoryItem } from '@queries/history/history';-import { onElementConnect } from '@solid-primitives/lifecycle';-import { activeElement } from 'app/signal/focus';-import { filePastePlugin } from 'core/component/LexicalMarkdown/plugins/file-paste/filePastePlugin';-import { createAccessoryStore } from 'core/component/LexicalMarkdown/plugins/node-accessory/nodeAccessoryPlugin';-import { textPastePlugin } from 'core/component/LexicalMarkdown/plugins/text-paste/textPastePlugin';-import {- $getRoot,- COMMAND_PRIORITY_CRITICAL,- COMMAND_PRIORITY_HIGH,- FORMAT_TEXT_COMMAND,- KEY_ENTER_COMMAND,- KEY_ESCAPE_COMMAND,- type LexicalEditor,- type TextFormatType,-} from 'lexical';-import {- type Accessor,- createEffect,- createSignal,- type JSXElement,- onCleanup,- type Setter,- Show,-} from 'solid-js';-import { createStore, type SetStoreFunction } from 'solid-js/store';--const { track, TrackingEvents } = withAnalytics();--export type UseChatMarkdown = {- focus: () => void;- mentions: Accessor<ItemMention[]>;- markdownText: Accessor<string>;- formatState: SelectionData;- clear: () => void;- ref: Accessor<HTMLDivElement | undefined>;- insert: (value: string) => void;- MarkdownArea: (props: ConsumableChatMarkdownAreaProps) => JSXElement;- setInlineFormat: (format: TextFormatType) => void;- setNodeFormat: (transform: NodeTransformType) => void;- removeMention: (mentionId: string) => void;-};--export type useChatMarkdownAreaArgs = {- initialValue?: string;- addAttachment: (attachment: Attachment) => void;-};--export function useChatMarkdownArea(- args: useChatMarkdownAreaArgs-): UseChatMarkdown {- const [mentions, setMentions] = createSignal<ItemMention[]>([]);- const [state, setState] = createSignal<string>('');- const [mountRef, setMountRef] = createSignal<HTMLDivElement>();- const [formatState, setFormatState] = createStore<SelectionData>(- structuredClone(defaultSelectionData)- );-- const lexicalWrapper = createLexicalWrapper({- type: 'chat',- namespace: 'chat-markdown-area',- isInteractable: () => true,- });-- function focus() {- setTimeout(() => {- lexicalWrapper.editor.focus();- }, 0);- }-- function insert(text: string) {- insertText(lexicalWrapper.editor, text);- }-- function inlineFormat(format: TextFormatType): void {- lexicalWrapper.editor.focus();- lexicalWrapper.editor.dispatchCommand(FORMAT_TEXT_COMMAND, format);- }-- function nodeFormat(transform: NodeTransformType): void {- lexicalWrapper.editor.focus();- lexicalWrapper.editor.dispatchCommand(NODE_TRANSFORM, transform);- }-- function clear() {- initializeEditorEmpty(lexicalWrapper.editor);- setMentions([]);- }- function removeMention(mentionId: string) {- lexicalWrapper.editor.update(() => {- const root = $getRoot();- let nodeToRemove: any = null;-- // Find the document mention node with the given ID- $traverseNodes(root, (node: any) => {- if (- $isDocumentMentionNode(node) &&- node.getDocumentId() === mentionId- ) {- nodeToRemove = node;- return true;- }- return false;- });-- if (nodeToRemove) {- // Remove the node from the editor- nodeToRemove.remove();-- // Update the mentions state to remove this mention- setMentions((prev) => prev.filter((m) => m.itemId !== mentionId));- }- });- }-- const { getAttachmentFromMention } = useGetChatAttachmentInfo();- const addAttachmentFromMention = (mention: ItemMention) => {- track(TrackingEvents.CHAT.MENTION.SELECT);- const attachment = getAttachmentFromMention(mention);- if (attachment) args.addAttachment(attachment);- };-- function ChatMarkdownArea(props: ConsumableChatMarkdownAreaProps) {- return (- <MarkdownArea- initialValue={args.initialValue}- mountRef={mountRef}- setMountRef={setMountRef}- markdownState={state}- setMarkdownState={setState}- lexicalWrapper={lexicalWrapper}- formatState={formatState}- setFormatState={setFormatState}- onCreateMention={addAttachmentFromMention}- {...props}- />- );- }-- return {- insert,- MarkdownArea: ChatMarkdownArea,- focus,- mentions,- markdownText: state,- ref: mountRef,- clear,- formatState,- setInlineFormat: inlineFormat,- setNodeFormat: nodeFormat,- removeMention,- };-}--type MarkdownAreaProps = {- mountRef: Accessor<HTMLDivElement | undefined>;- setMountRef: Setter<HTMLDivElement | undefined>;- onCreateMention: (mention: ItemMention) => void;- markdownState: Accessor<string>;- setMarkdownState: Setter<string>;- lexicalWrapper: LexicalWrapper;- setFormatState: SetStoreFunction<SelectionData>;- formatState: SelectionData;-};--export type ConsumableChatMarkdownAreaProps = {- onChange?: (value: string) => void;- onEnter?: (e: KeyboardEvent) => boolean;- onEscape?: (e: KeyboardEvent) => boolean;- onBlur?: () => void;- initialValue?: string;- placeholder?: string;- users?: Accessor<IOrganizationUser[]>;- history?: Accessor<HistoryItem[]>;- onPasteFile?: (files: File[]) => void;- dontFocusOnMount?: boolean;- portalScope?: PortalScope;- onFocusLeaveStart?: (e: KeyboardEvent) => void;- onFocusLeaveEnd?: (e: KeyboardEvent) => void;- captureEditor?: (editor: LexicalEditor) => void;-};--function MarkdownArea(- props: MarkdownAreaProps & ConsumableChatMarkdownAreaProps-) {- const { editor, plugins, cleanup } = props.lexicalWrapper;-- const isActiveElementInBlock = () => {- return false;- };-- const focusShortcut = getPrettyHotkeyStringByToken(TOKENS.chat.input.focus);-- const onConnect = () => {- editor.setEditable(true);- if (props.initialValue) {- setEditorStateFromMarkdown(editor, props.initialValue);- } else {- initializeEditorEmpty(editor);- }- if (!isMobile() && !props.dontFocusOnMount) {- editor.focus();- }- };-- if (props.captureEditor) {- props.captureEditor(editor);- }-- createEffect(() => {- props.onChange?.(props.markdownState());- });-- const [showPlaceholder, setShowPlaceholder] = createSignal(true);-- const mentionsMenuOperations = createMenuOperations();- const emojisMenuOperations = createMenuOperations();-- const [accessories, setAccessories] = createAccessoryStore();-- onCleanup(() => {- cleanup();- });-- createEffect(() => {- props.markdownState();- setShowPlaceholder(editorIsEmpty(editor));- });-- plugins- .richText()- .list()- .markdownShortcuts()- .delete()- .state<string>(props.setMarkdownState, 'markdown')- .history(400)- .use(- customSelectionDataPlugin(- props.lexicalWrapper,- props.formatState,- props.setFormatState- )- )- .use(emojisPlugin({ menu: emojisMenuOperations }))- .use(codePlugin({ accessories, setAccessories }))- .use(tabIndentationPlugin())- .use(- filePastePlugin({- onPasteFilesAndDirs: (files, directories) => {- const onPasteFile = props.onPasteFile;- if (onPasteFile) {- if (directories.length > 0) {- toast.failure('Folder upload not supported here');- return;- }- handleFileFolderDrop(files, [], (entries) => {- const files = entries.map((entry) => entry.file);- onPasteFile(files);- });- }- },- })- )- .use(textPastePlugin())- .use(markdownPastePlugin())- .use(restoreFocusPlugin())- .use(normalizeEnterPlugin())- .use(- tablePlugin({- hasCellMerge: true,- hasCellBackgroundColor: false,- hasTabHandler: true,- hasHorizontalScroll: true,- })- )- .use(- keyboardShortcutsPlugin({- shortcuts: DefaultShortcuts,- })- )- .use(tableCellResizerPlugin())- .use(- mentionsPlugin({- menu: mentionsMenuOperations,- onCreateMention: props.onCreateMention,- })- );-- if (props.onFocusLeaveEnd && props.onFocusLeaveStart) {- plugins.use(- keyboardFocusPlugin({- onFocusLeaveStart: props.onFocusLeaveStart,- onFocusLeaveEnd: props.onFocusLeaveEnd,- ignoreKeys: () =>- mentionsMenuOperations.isOpen() || emojisMenuOperations.isOpen(),- })- );- }-- if (props.onEnter !== undefined) {- autoRegister(- editor.registerCommand(- KEY_ENTER_COMMAND,- (e) => {- if (!e) return false;- // TODO (seamus) : This is hacky. If we got a props.onEnter,then shift+enter becomes- // the new "", so we delete the shiftKey and pass along to lexical.- if (e.shiftKey) {- Object.defineProperty(e, 'shiftKey', { value: false });- return false;- }-- const captured = props.onEnter!(e);- setTimeout(() => {- editor.focus();- }, 0);- if (captured) {- e.preventDefault();- e.stopPropagation();- }- return captured;- },- // Run at HIGH here to that the mentions menu can run at CRITICAL- COMMAND_PRIORITY_HIGH- )- );- }-- if (props.onEscape !== undefined) {- autoRegister(- editor.registerCommand(- KEY_ESCAPE_COMMAND,- (e) => (props.onEscape ? props.onEscape(e) : false),- COMMAND_PRIORITY_CRITICAL- )- );- }-- onCleanup(() => {- cleanup();- });-- return (- <LexicalWrapperContext.Provider value={props.lexicalWrapper}>- <div class="relative w-full">- <div- ref={(el) => {- onElementConnect(el, () => {- editor.setRootElement(el);- onConnect();- props.setMountRef(el);- });- }}- contentEditable={true}- class="overflow-y-auto max-h-40 p-0 m-0"- ></div>- <DecoratorRenderer editor={editor} />- <NodeAccessoryRenderer editor={editor} store={accessories} />- <Show when={showPlaceholder()}>- <div class="pointer-events-none absolute top-0">- <Show- when={- activeElement() !== props.mountRef() && isActiveElementInBlock()- }- fallback={- <p class="py-1.5 p-0 text-ink-extra-muted">- {props.placeholder ?? 'Ask AI, @mention anything'}- </p>- }- >- <p class="p-0 m-0 text-ink-extra-muted">- Press{' '}- <span- class={`rounded-md px-1.5 py-0.5 space-x-1 ${shortcutBadgeStyles['muted']}`}- >- {focusShortcut}- </span>{' '}- to chat with AI- </p>- </Show>- </div>- </Show>- <EmojiMenu- editor={editor}- menu={emojisMenuOperations}- useBlockBoundary={true}- portalScope={props.portalScope}- />- <MentionsMenu- editor={editor}- menu={mentionsMenuOperations}- block={'chat'}- useBlockBoundary={true}- portalScope={props.portalScope}- useSnapshotForDocuments={ENABLE_SNAPSHOT_NODE}- showOpenTabs- />- <FloatingMenuGroup>- <FloatingLinkMenu />- </FloatingMenuGroup>- </div>- </LexicalWrapperContext.Provider>- );-}diff --git a/js/app/packages/core/component/AI/component/message/EditableChatMessage.tsx b/js/app/packages/core/component/AI/component/message/EditableChatMessage.tsxindex fbeb05eb91..944207b8ea 100644--- a/js/app/packages/core/component/AI/component/message/EditableChatMessage.tsx+++ b/js/app/packages/core/component/AI/component/message/EditableChatMessage.tsx@@ -1,13 +1,18 @@import type { ChatSendInput } from '@core/component/AI/component/input/buildRequest';import { ChatInput } from '@core/component/AI/component/input/ChatInput';-import { useChatMarkdownArea } from '@core/component/AI/component/input/useChatMarkdownArea';import {ChatInputProvider,useChatInputContext,} from '@core/component/AI/context';+import { useGetChatAttachmentInfo } from '@core/component/AI/signal/attachment';import type { Attachment, Model } from '@core/component/AI/types';+import { buildChatEditor } from '@core/component/AI/component/input/buildChatEditor';+import { ENABLE_SNAPSHOT_NODE } from '@core/constant/featureFlags';+import { withAnalytics } from '@coparse/analytics';import { onMount } from 'solid-js';+const { track, TrackingEvents } = withAnalytics();+function EditableChatMessageInner(props: {chatId: string;initialText: string;@@ -17,13 +22,21 @@ function EditableChatMessageInner(props: {model: Model;}) {const input = useChatInputContext();- const chatMarkdownArea = useChatMarkdownArea({- initialValue: props.initialText,- addAttachment: (a) => input.attachments.addAttachment(a),+ const { getAttachmentFromMention } = useGetChatAttachmentInfo();++ const editor = buildChatEditor().withMentions({+ onCreate: (mention) => {+ track(TrackingEvents.CHAT.MENTION.SELECT);+ const attachment = getAttachmentFromMention(mention);+ if (attachment) input.attachments.addAttachment(attachment);+ },+ block: 'chat',+ showOpenTabs: true,+ useSnapshotForDocuments: ENABLE_SNAPSHOT_NODE,});onMount(() => {- chatMarkdownArea.focus();+ editor.controls.focus();});const handleKey = (e: KeyboardEvent) => {@@ -35,7 +48,8 @@ function EditableChatMessageInner(props: {return (<div onKeyDown={handleKey} class="w-full"><ChatInput- markdown={chatMarkdownArea}+ editor={editor}+ initialValue={props.initialText}chatId={props.chatId}onSend={(request) => props.onAccept(request)}/>diff --git a/js/app/packages/core/component/LexicalMarkdown/builder/BuilderTestPage.tsx b/js/app/packages/core/component/LexicalMarkdown/builder/BuilderTestPage.tsxnew file mode 100644index 0000000000..83352511db--- /dev/null+++ b/js/app/packages/core/component/LexicalMarkdown/builder/BuilderTestPage.tsx@@ -0,0 +1,69 @@+import { SplitHeaderLeft } from '@app/component/split-layout/components/SplitHeader';+import { StaticSplitLabel } from '@app/component/split-layout/components/SplitLabel';+import type { JSX } from 'solid-js';+import { buildConfig } from './MarkdownConfigBuilder';+import { MarkdownShell } from './MarkdownShell';++function Container(props: {+ label: string;+ description?: string;+ children: JSX.Element;+ footer?: JSX.Element;+}) {+ return (+ <div class="flex flex-col gap-2 w-full max-w-4xl p-4 bg-panel rounded-lg border border-edge min-h-100">+ <div class="flex flex-col gap-1">+ <label class="text-sm font-medium text-ink">{props.label}</label>+ {props.description && (+ <span class="text-xs text-ink-muted">{props.description}</span>+ )}+ </div>+ <div class="h-px bg-edge" />+ <div class="h-48 overflow-y-auto">{props.children}</div>+ {props.footer && (+ <>+ <div class="h-px bg-edge" />+ <div class="text-xs text-ink-muted">{props.footer}</div>+ </>+ )}+ </div>+ );+}++function Editor() {+ const editor = buildConfig('markdown')+ .namespace('test-page')+ .withHistory()+ .withEmojis()+ .withMedia()+ .withMentions()+ .withActions()+ .onEscape(() => {+ console.log('ESCAPE');+ return false;+ });++ editor.use((editor) => {+ console.log('CUSTOM PLUGIN', editor);+ return () => {};+ });++ return (+ <Container label="Builder Pattern">+ <MarkdownShell config={editor} placeholder="Cool test placeholder" />+ </Container>+ );+}++export default function BuilderTestPage() {+ return (+ <div class="flex flex-col h-full w-full">+ <SplitHeaderLeft>+ <StaticSplitLabel label="Markdown Editor Builder Pattern Test" />+ </SplitHeaderLeft>+ <div class="w-full h-full p-8 flex-1 flex flex-row flex-wrap gap-4 overflow-y-auto items-start justify-center content-start">+ <Editor />+ </div>+ </div>+ );+}diff --git a/js/app/packages/core/component/LexicalMarkdown/builder/MarkdownConfigBuilder.ts b/js/app/packages/core/component/LexicalMarkdown/builder/MarkdownConfigBuilder.tsnew file mode 100644index 0000000000..d9b6552b5f--- /dev/null+++ b/js/app/packages/core/component/LexicalMarkdown/builder/MarkdownConfigBuilder.ts@@ -0,0 +1,238 @@+import type { LexicalEditor } from 'lexical';+import type { Store } from 'solid-js/store';+import type { PluginManager, SelectionData } from '../plugins';+import { buildHandleFromConfig } from './buildHandleFromConfig';+import type {+ ActionsOptions,+ EditorBuilder,+ EditorCallbacks,+ EditorConfig,+ EditorControls,+ EditorHandle,+ EmojisOptions,+ FilePasteOptions,+ FocusLeaveCallbacks,+ HistoryOptions,+ LinksOptions,+ MediaOptions,+ MentionsOptions,+} from './types';+import type { EditorType } from '@lexical-core';++export class EditorConfigBuilder implements EditorBuilder {+ private state: EditorConfig;+ private _handle?: EditorHandle;+ private _queuedPlugins: Array<(editor: LexicalEditor) => () => void> = [];++ constructor(type: EditorType = 'markdown') {+ this.state = {+ type,+ namespace: 'builder-editor',+ singleLine: false,+ handlers: {},+ media: false,+ code: false,+ checkboxToTask: false,+ restoreFocus: false,+ withIds: false,+ selectionData: false,+ actions: false as const,+ };+ }++ namespace(name: string): this {+ this.state.namespace = name;+ return this;+ }++ withMentions(config: MentionsOptions = {}): this {+ this.state.mentions = {+ ...config,+ };+ return this;+ }++ withEmojis(config: EmojisOptions = {}): this {+ this.state.emojis = config;+ return this;+ }++ withLinks(config: LinksOptions = {}): this {+ this.state.links = {+ floatingMenu: true,+ ...config,+ };+ return this;+ }++ withHistory(config: HistoryOptions = {}): this {+ this.state.history = {+ timeGap: 400,+ ...config,+ };+ return this;+ }++ withMedia(config?: MediaOptions): this {+ this.state.media = config ?? {};+ return this;+ }++ withCode(): this {+ this.state.code = true;+ return this;+ }++ withCheckboxToTask(): this {+ this.state.checkboxToTask = true;+ return this;+ }++ withFilePaste(config: FilePasteOptions): this {+ this.state.filePaste = config;+ return this;+ }++ withRestoreFocus(): this {+ this.state.restoreFocus = true;+ return this;+ }++ withIds(): this {+ this.state.withIds = true;+ return this;+ }++ withSelectionData(): this {+ this.state.selectionData = true;+ return this;+ }++ withActions(config: ActionsOptions = {}): this {+ this.state.actions = config;+ return this;+ }++ singleLine(): this {+ this.state.singleLine = true;+ return this;+ }++ onEnter(handler: EditorCallbacks['onEnter']): this {+ this.state.handlers.onEnter = handler;+ return this;+ }++ onEscape(handler: EditorCallbacks['onEscape']): this {+ this.state.handlers.onEscape = handler;+ return this;+ }++ onTab(handler: EditorCallbacks['onTab']): this {+ this.state.handlers.onTab = handler;+ return this;+ }++ onChange(handler: EditorCallbacks['onChange']): this {+ this.state.handlers.onChange = handler;+ return this;+ }++ onFocusLeave(config: FocusLeaveCallbacks): this {+ this.state.focusLeave = config;+ return this;+ }++ /**+ * Register a custom Lexical plugin as part of the builder chain.+ * Plugins are queued here and applied during `buildHandle()` after all+ * built-in plugins have been registered.+ */+ use(pluginFn: (editor: LexicalEditor) => () => void): this {+ this._queuedPlugins.push(pluginFn);+ return this;+ }++ /**+ * Instantiates the reactive editor state and returns the handle.+ * Called once by `<MarkdownShell>` on mount; subsequent calls return the+ * cached handle. Can also be called directly when a component needs+ * low-level access to the Lexical editor before or outside of+ * `<MarkdownShell>`.+ */+ buildHandle(): EditorHandle {+ if (this._handle) return this._handle;+ this._handle = buildHandleFromConfig(this.state);+ for (const plugin of this._queuedPlugins) {+ this._handle.plugins.use(plugin);+ }+ return this._handle;+ }++ /** Imperative controls (focus, blur, clear, get/set content). Available after `<MarkdownShell>` mounts. */+ get controls(): EditorControls {+ if (!this._handle)+ throw new Error(+ 'editor.controls accessed before <MarkdownShell> mounted'+ );+ return this._handle.controls;+ }++ /** The underlying Lexical editor instance. Available after `<MarkdownShell>` mounts. */+ get lexical(): LexicalEditor {+ if (!this._handle)+ throw new Error('editor.lexical accessed before <MarkdownShell> mounted');+ return this._handle.lexical;+ }++ /** The plugin manager. Available after `<MarkdownShell>` mounts. */+ get plugins(): PluginManager {+ if (!this._handle)+ throw new Error('editor.plugins accessed before <MarkdownShell> mounted');+ return this._handle.plugins;+ }++ /** Reactive selection state, if `.withSelectionData()` was enabled. Available after `<MarkdownShell>` mounts. */+ get selection(): Store<SelectionData> | undefined {+ return this._handle?.selection;+ }+}++/**+ * Creates a fluent builder for configuring a markdown editor.+ *+ * Chain feature methods to opt into capabilities, then pass the builder to+ * directly to `<MarkdownShell editor={...} />`.+ *+ * Use the builder variable to access `controls`, `lexical`, `plugins`, and+ * `selection` after the component has mounted.+ *+ * @param type - Lexical editor mode. Defaults to `'markdown'` (full rich-text).+ * Use `'chat'` for a mode that supports mention nodes but omits heading+ * shortcuts, or `'plain-text'` for a plain-text-only editor.+ *+ * @example+ * ```tsx+ * const editor = buildMarkdownEditor()+ * .namespace('my-editor')+ * .withMentions()+ * .withEmojis()+ * .withLinks()+ * .withHistory()+ * .withMedia({ fileDrop: true })+ * .onChange((markdown) => setValue(markdown))+ * .onEscape(() => { containerRef()?.focus(); return true; });+ *+ * // In JSX — no .build() needed:+ * <MarkdownShell editor={editor} placeholder="Write something..." />+ *+ * // Access controls after mount (e.g. in event handlers):+ * editor.controls.focus();+ * editor.controls.clear();+ * ```+ */+export function buildConfig(+ type: EditorType = 'markdown'+): EditorConfigBuilder {+ return new EditorConfigBuilder(type);+}diff --git a/js/app/packages/core/component/LexicalMarkdown/builder/MarkdownShell.tsx b/js/app/packages/core/component/LexicalMarkdown/builder/MarkdownShell.tsxnew file mode 100644index 0000000000..77b28625f2--- /dev/null+++ b/js/app/packages/core/component/LexicalMarkdown/builder/MarkdownShell.tsx@@ -0,0 +1,278 @@+import { cn } from '@ui/utils/classname';+import { fileFolderDrop } from '@core/directive/fileFolderDrop';+import { handleFileFolderDrop } from '@core/util/upload';+import { onElementConnect } from '@solid-primitives/lifecycle';+import {+ COMMAND_PRIORITY_CRITICAL,+ COMMAND_PRIORITY_HIGH,+ KEY_ENTER_COMMAND,+ KEY_ESCAPE_COMMAND,+ KEY_TAB_COMMAND,+} from 'lexical';+import {+ type Component,+ createEffect,+ createSignal,+ on,+ onCleanup,+ Show,+} from 'solid-js';+import { FloatingMenuGroup } from '../context/FloatingMenuContext';+import { LexicalWrapperContext } from '../context/LexicalWrapperContext';+import { registerCommandEffect } from '../plugins';+import {+ createFilesReadyHandler,+ getDragDropPosition,+} from '../utils/fileUploadUtils';+import {+ editorIsEmpty,+ initializeEditorEmpty,+ initializeEditorWithState,+ setEditorStateFromMarkdown,+} from '../utils';+import { DecoratorRenderer } from '../component/core/DecoratorRenderer';+import { DragInsertIndicator } from '../component/misc/DragInsertIndicator';+import { NodeAccessoryRenderer } from '../component/core/NodeAccessoryRenderer';+import { EmojiMenu } from '../component/menu/EmojiMenu';+import { FloatingLinkMenu } from '../component/menu/FloatingLinkMenu';+import { MentionsMenu } from '../component/menu/MentionsMenu';+import { ActionMenu } from '../component/menu/ActionsMenu';+import type { EditorBuilder, EditorComponentProps } from './types';++export const MarkdownShell: Component<+ { config: EditorBuilder } & EditorComponentProps+> = (props) => {+ const handle = props.config.buildHandle();+ const state = handle._internal;+ const {+ editor,+ lexicalWrapper,+ cleanupLexical,+ builderConfig,+ markdownState,+ } = state;++ const [showPlaceholder, setShowPlaceholder] = createSignal(true);++ // Track initialization so onChange is not fired during setup+ let didInitializeContent = false;++ const onConnect = () => {+ if (props.autofocus) {+ setTimeout(() => editor.focus());+ }++ if (props.initialState) {+ initializeEditorWithState(editor, props.initialState);+ } else if (props.initialValue) {+ setEditorStateFromMarkdown(editor, props.initialValue);+ } else {+ initializeEditorEmpty(editor);+ }++ didInitializeContent = true;+ };++ // Track editable state+ createEffect(() => {+ const enabled = !props.disabled;+ editor.setEditable(enabled);+ state.setIsInteractable(enabled);+ });++ // onChange callback+ createEffect(+ on(+ markdownState,+ () => {+ if (!didInitializeContent) return;+ builderConfig.handlers.onChange?.(markdownState());+ },+ { defer: true }+ )+ );++ // Placeholder visibility+ createEffect(() => {+ markdownState();+ setShowPlaceholder(editorIsEmpty(editor));+ });++ // Register key handlers+ registerCommandEffect(+ editor,+ KEY_ENTER_COMMAND,+ () => {+ const onEnter = builderConfig.handlers.onEnter;+ if (!onEnter) return undefined;+ return (e) => {+ if (!e) return false;+ if (e.shiftKey) {+ // Shift+enter = regular newline+ Object.defineProperty(e, 'shiftKey', { value: false });+ return false;+ }+ const captured = onEnter(e, markdownState());+ if (captured) {+ e.preventDefault();+ e.stopPropagation();+ }+ return captured;+ };+ },+ COMMAND_PRIORITY_HIGH+ );++ registerCommandEffect(+ editor,+ KEY_ESCAPE_COMMAND,+ () => {+ const onEscape = builderConfig.handlers.onEscape;+ return onEscape ? (e) => onEscape(e) : undefined;+ },+ COMMAND_PRIORITY_CRITICAL+ );++ registerCommandEffect(+ editor,+ KEY_TAB_COMMAND,+ () => {+ const onTab = builderConfig.handlers.onTab;+ return onTab ? (e) => onTab(e) : undefined;+ },+ COMMAND_PRIORITY_CRITICAL+ );++ onCleanup(cleanupLexical);++ // File drop handler — wired to fileFolderDrop directive+ const onFileDrop = state.fileDropConfig+ ? (+ fileEntries: FileSystemFileEntry[],+ folderEntries: FileSystemDirectoryEntry[],+ e?: DragEvent+ ) => {+ if (!e) return;+ handleFileFolderDrop(+ fileEntries,+ folderEntries,+ createFilesReadyHandler(+ editor,+ undefined,+ undefined,+ () => getDragDropPosition(editor, e, true),+ undefined,+ state.fileDropConfig!.constrainedMediaDimensions+ )+ );+ }+ : undefined;++ // Keep TS happy — ensures the directive import is not tree-shaken+ void fileFolderDrop;++ return (+ <LexicalWrapperContext.Provider value={lexicalWrapper}>+ <div+ class={cn('relative h-full overflow-y-auto min-h-8', props.class)}+ on:keydown={(e) => e.stopPropagation()}+ on:click={(e) => {+ e.stopPropagation();+ editor.focus();+ }}+ on:mousedown={(e) => e.stopPropagation()}+ on:mouseup={(e) => e.stopPropagation()}+ use:fileFolderDrop={+ onFileDrop+ ? {+ onDrop: onFileDrop,+ disabled: props.disabled,+ }+ : undefined+ }+ >+ {/* Content Editable */}+ <div+ ref={(el) => {+ onElementConnect(el, () => {+ editor.setRootElement(el);+ onConnect();+ });+ }}+ contentEditable={!props.disabled}+ />++ <DecoratorRenderer editor={editor} />++ {/* Node Accessories (code blocks) */}+ <Show when={state.accessoryStore}>+ {(store) => <NodeAccessoryRenderer editor={editor} store={store()} />}+ </Show>++ <Show when={showPlaceholder()}>+ <div class="pointer-events-none text-ink-placeholder/50 absolute top-0">+ <p class="my-1.5 pointer-events-none">+ {props.placeholder ?? '...'}+ </p>+ </div>+ </Show>++ <Show when={state.dragInsertStore}>+ {(store) => (+ <DragInsertIndicator state={store()} active={!props.disabled} />+ )}+ </Show>++ <Show when={state.mentionsMenuOps}>+ {(menu) => (+ <MentionsMenu+ editor={editor}+ menu={menu()}+ useBlockBoundary={false}+ portalScope={props.portalScope}+ block={builderConfig.mentions?.block as any}+ showOpenTabs={builderConfig.mentions?.showOpenTabs}+ useSnapshotForDocuments={+ builderConfig.mentions?.useSnapshotForDocuments+ }+ />+ )}+ </Show>++ <Show when={state.actionsMenuOps}>+ {(menu) => (+ <ActionMenu+ editor={editor}+ menu={menu()}+ useBlockBoundary={+ typeof builderConfig.actions === 'object'+ ? (builderConfig.actions.useBlockBoundary ?? false)+ : false+ }+ portalScope={props.portalScope}+ />+ )}+ </Show>++ {/* Emoji Menu */}+ <Show when={state.emojisMenuOps}>+ {(menu) => (+ <EmojiMenu+ editor={editor}+ menu={menu()}+ useBlockBoundary={false}+ portalScope={props.portalScope}+ />+ )}+ </Show>++ {/* Floating Link Menu */}+ <Show when={builderConfig.links?.floatingMenu}>+ <FloatingMenuGroup>+ <FloatingLinkMenu />+ </FloatingMenuGroup>+ </Show>+ </div>+ </LexicalWrapperContext.Provider>+ );+};diff --git a/js/app/packages/core/component/LexicalMarkdown/builder/buildHandleFromConfig.ts b/js/app/packages/core/component/LexicalMarkdown/builder/buildHandleFromConfig.tsnew file mode 100644index 0000000000..b596beefe1--- /dev/null+++ b/js/app/packages/core/component/LexicalMarkdown/builder/buildHandleFromConfig.ts@@ -0,0 +1,272 @@+import type { EditorType } from '@lexical-core';+import { createLexicalWrapper } from '../context/LexicalWrapperContext';+import {+ codePlugin,+ createAccessoryStore,+ createDragInsertStore,+ dragInsertPlugin,+ emojisPlugin,+ filePastePlugin,+ horizontalRulePlugin,+ keyboardFocusPlugin,+ markdownPastePlugin,+ mediaPlugin,+ mentionsPlugin,+ selectionDataPlugin,+ singleLinePlugin,+ tabIndentationPlugin,+ actionsPlugin,+ textPastePlugin,+} from '../plugins';+import { createFilesReadyHandler } from '../utils/fileUploadUtils';+import { handleFileFolderDrop } from '@core/util/upload';+import { checkboxToTaskPlugin } from '../plugins/checkbox-to-task';+import { normalizeEnterPlugin } from '../plugins/normalize-enter';+import { restoreFocusPlugin } from '../plugins/restore-focus';+import { createMenuOperations } from '../shared/inlineMenu';+import type { SerializedEditorState } from 'lexical';+import {+ getSaveState,+ initializeEditorEmpty,+ initializeEditorWithState,+ setEditorStateFromMarkdown,+} from '../utils';+import { createSignal } from 'solid-js';+import type {+ EditorConfig,+ EditorControls,+ EditorHandle,+ MediaDropOptions,+ MediaOptions,+} from './types';++export function buildHandleFromConfig(config: EditorConfig): EditorHandle {+ const [isInteractable, setIsInteractable] = createSignal(true);++ const lexicalWrapper = config.withIds+ ? createLexicalWrapper({+ type: config.type as EditorType,+ namespace: config.namespace,+ isInteractable,+ withIds: true,+ })+ : createLexicalWrapper({+ type: config.type as EditorType,+ namespace: config.namespace,+ isInteractable,+ });++ const { editor, plugins, cleanup: cleanupLexical } = lexicalWrapper;++ const [markdownState, setMarkdownState] = createSignal<string>('');++ const actionsMenuOps =+ config.actions !== false && config.type !== 'plain-text'+ ? createMenuOperations()+ : undefined;+ const mentionsMenuOps = config.mentions ? createMenuOperations() : undefined;+ const emojisMenuOps = config.emojis ? createMenuOperations() : undefined;++ const accessoryStoreResult = config.code ? createAccessoryStore() : undefined;+ const accessoryStore = accessoryStoreResult?.[0];+ const setAccessoryStore = accessoryStoreResult?.[1];++ if (config.type === 'plain-text') {+ plugins.plainText().state<string>(setMarkdownState, 'plain');+ } else if (config.singleLine) {+ plugins.richText().state<string>(setMarkdownState, 'markdown');+ } else {+ // Full markdown: everything+ plugins+ .richText()+ .list()+ .markdownShortcuts()+ .delete()+ .state<string>(setMarkdownState, 'markdown');+ }++ // History+ if (config.history) {+ plugins.history(config.history.timeGap);+ }++ // Single line mode+ if (config.singleLine) {+ plugins.use(singleLinePlugin());+ }++ // Restore focus (registered early, before other plugins)+ if (config.restoreFocus) {+ plugins.use(restoreFocusPlugin());+ }++ // Text paste handling+ plugins.use(textPastePlugin());++ // Markdown paste handling (rich & full editors only)+ if (config.type !== 'plain-text') {+ plugins.use(markdownPastePlugin());+ }++ // Tab indentation (unless custom handler)+ if (!config.handlers.onTab) {+ plugins.use(tabIndentationPlugin());+ }++ // Horizontal rules & normalize-enter (full multi-line markdown only)+ if (config.type !== 'plain-text' && !config.singleLine) {+ plugins.use(horizontalRulePlugin());+ plugins.use(normalizeEnterPlugin());+ }++ // Selection / formatting state+ if (config.selectionData) {+ plugins.use(selectionDataPlugin(lexicalWrapper));+ }++ // Actions / slash-command menu (not available for plain-text)+ if (actionsMenuOps) {+ plugins.use(actionsPlugin({ menu: actionsMenuOps }));+ }++ // Mentions & Emojis (not available for plain-text — nodes not registered)+ if (config.type !== 'plain-text') {+ if (config.mentions && mentionsMenuOps) {+ plugins.use(+ mentionsPlugin({+ menu: mentionsMenuOps,+ onCreateMention: config.mentions.onCreate,+ onRemoveMention: config.mentions.onRemove,+ })+ );+ }++ if (emojisMenuOps) {+ plugins.use(emojisPlugin({ menu: emojisMenuOps }));+ }+ }++ // Media (images, videos)+ const mediaEnabled = !!config.media;+ const mediaConfig: MediaOptions | undefined =+ typeof config.media === 'object' ? config.media : undefined;+ const fileDropConfig: MediaDropOptions | undefined =+ mediaConfig?.fileDrop === true ? {} : mediaConfig?.fileDrop || undefined;++ // Drag-insert store (shared between plugin and indicator)+ const dragInsertStoreResult = fileDropConfig+ ? createDragInsertStore()+ : undefined;+ const dragInsertStore = dragInsertStoreResult?.[0];+ const setDragInsertStore = dragInsertStoreResult?.[1];++ if (mediaEnabled) {+ plugins.use(mediaPlugin());+ }++ // File drag-and-drop from desktop+ if (fileDropConfig && setDragInsertStore) {+ plugins.use(dragInsertPlugin({ setState: setDragInsertStore }));+ }++ // File clipboard paste — auto-register when fileDrop is enabled, since+ // dragInsertPlugin blocks DRAG_DROP_PASTE (Lexical's built-in paste-files+ // path) without processing the files. A custom filePaste config from+ // withFilePaste() takes precedence.+ if (fileDropConfig && !config.filePaste) {+ plugins.use(+ filePastePlugin({+ onPasteFilesAndDirs: (fileEntries, directories) => {+ handleFileFolderDrop(+ fileEntries,+ directories,+ createFilesReadyHandler(+ editor,+ undefined,+ undefined,+ undefined,+ undefined,+ fileDropConfig.constrainedMediaDimensions+ )+ );+ },+ })+ );+ }++ // Code blocks with syntax highlighting+ if (config.code && accessoryStore && setAccessoryStore) {+ plugins.use(+ codePlugin({+ accessories: accessoryStore,+ setAccessories: setAccessoryStore,+ })+ );+ }++ // Checkbox to task conversion+ if (config.checkboxToTask) {+ plugins.use(checkboxToTaskPlugin());+ }++ // File paste handling+ if (config.filePaste) {+ plugins.use(+ filePastePlugin({+ onPasteFilesAndDirs: config.filePaste.onPasteFilesAndDirs,+ })+ );+ }++ // Keyboard focus leave detection+ if (config.focusLeave) {+ plugins.use(+ keyboardFocusPlugin({+ onFocusLeaveStart: config.focusLeave.onStart,+ onFocusLeaveEnd: config.focusLeave.onEnd,+ ignoreKeys: () =>+ (actionsMenuOps?.isOpen() ?? false) ||+ (mentionsMenuOps?.isOpen() ?? false) ||+ (emojisMenuOps?.isOpen() ?? false),+ })+ );+ }++ const controls: EditorControls = {+ focus: () => editor.focus(),+ blur: () => {+ editor.getRootElement()?.blur();+ },+ clear: () => {+ initializeEditorEmpty(editor);+ },+ getMarkdown: () => markdownState(),+ setMarkdown: (md: string) => setEditorStateFromMarkdown(editor, md),+ getState: () => getSaveState(editor.getEditorState()),+ setState: (state: SerializedEditorState) =>+ initializeEditorWithState(editor, state),+ getLexical: () => editor,+ };++ return {+ controls,+ lexical: editor,+ plugins,+ selection: lexicalWrapper.selection,+ _internal: {+ builderConfig: config,+ lexicalWrapper,+ editor,+ cleanupLexical,+ isInteractable,+ setIsInteractable,+ markdownState,+ actionsMenuOps,+ mentionsMenuOps,+ emojisMenuOps,+ accessoryStore,+ dragInsertStore,+ fileDropConfig,+ },+ };+}diff --git a/js/app/packages/core/component/LexicalMarkdown/builder/types.ts b/js/app/packages/core/component/LexicalMarkdown/builder/types.tsnew file mode 100644index 0000000000..f38d0fb01d--- /dev/null+++ b/js/app/packages/core/component/LexicalMarkdown/builder/types.ts@@ -0,0 +1,155 @@+import type { EditorType } from '@lexical-core';+import type { PortalScope } from '@core/component/ScopedPortal';+import type { LexicalEditor, SerializedEditorState } from 'lexical';+import type { Store } from 'solid-js/store';+import type { createLexicalWrapper } from '../context/LexicalWrapperContext';+import type {+ createAccessoryStore,+ createDragInsertStore,+ ItemMention,+ PluginManager,+ SelectionData,+} from '../plugins';+import type { createMenuOperations } from '../shared/inlineMenu';++export interface ActionsOptions {+ useBlockBoundary?: boolean;+}++export interface MentionsOptions {+ sources?: Array<'users' | 'documents'>;+ onRemove?: (mention: ItemMention) => void;+ onCreate?: (mention: ItemMention) => void;+ block?: string;+ showOpenTabs?: boolean;+ useSnapshotForDocuments?: boolean;+}++/** Intentional extension point — no options yet. */+export type EmojisOptions = Record<string, never>;++export interface LinksOptions {+ floatingMenu?: boolean;+}++export interface HistoryOptions {+ timeGap?: number;+}++export interface FilePasteOptions {+ onPasteFilesAndDirs: (+ files: FileSystemFileEntry[],+ directories: FileSystemDirectoryEntry[]+ ) => void;+}++export interface MediaDropOptions {+ constrainedMediaDimensions?: { width: number; height: number };+}++export interface MediaOptions {+ fileDrop?: boolean | MediaDropOptions;+}++export interface FocusLeaveCallbacks {+ /** Called when keyboard focus leaves the start of the editor (e.g. Shift+Tab, ArrowUp) */+ onStart: (e: KeyboardEvent) => void;+ /** Called when keyboard focus leaves the end of the editor (e.g. Tab, ArrowDown) */+ onEnd: (e: KeyboardEvent) => void;+}++/**+ * Basic interaction callbacks that can be registered with .onEnter(myCallback)+ * on the builder.+ */+export interface EditorCallbacks {+ onEnter?: (event: KeyboardEvent, markdown: string) => boolean;+ onEscape?: (event: KeyboardEvent) => boolean;+ onTab?: (event: KeyboardEvent) => boolean;+ onChange?: (markdown: string) => void;+}++/**+ * The controls likely to be needed to by the markdown editor host component.+ */+export interface EditorControls {+ focus: () => void;+ blur: () => void;+ clear: () => void;+ getMarkdown: () => string;+ setMarkdown: (markdown: string) => void;+ getState: () => SerializedEditorState;+ setState: (state: SerializedEditorState) => void;+ getLexical: () => LexicalEditor;+}++/**+ * Props of an Editor component.+ */+export interface EditorComponentProps {+ placeholder?: string;+ /** Initialize with markdown text */+ initialValue?: string;+ /** Initialize with a serialized editor state. Takes precedence over initialValue. */+ initialState?: SerializedEditorState;+ disabled?: boolean;+ autofocus?: boolean;+ class?: string;+ portalScope?: PortalScope;+}++export interface EditorConfig {+ type: EditorType;+ namespace: string;+ mentions?: MentionsOptions;+ emojis?: EmojisOptions;+ links?: LinksOptions;+ history?: HistoryOptions;+ singleLine: boolean;+ handlers: EditorCallbacks;+ media: MediaOptions | false;+ code: boolean;+ checkboxToTask: boolean;+ filePaste?: FilePasteOptions;+ restoreFocus: boolean;+ focusLeave?: FocusLeaveCallbacks;+ withIds: boolean;+ selectionData: boolean;+ actions: ActionsOptions | false;+}++/** @internal consumed by MarkdownShell; do not access directly */+export interface EditorInternals {+ builderConfig: EditorConfig;+ lexicalWrapper: ReturnType<typeof createLexicalWrapper>;+ editor: LexicalEditor;+ cleanupLexical: () => void;+ isInteractable: () => boolean;+ setIsInteractable: (v: boolean) => void;+ markdownState: () => string;+ actionsMenuOps: ReturnType<typeof createMenuOperations> | undefined;+ mentionsMenuOps: ReturnType<typeof createMenuOperations> | undefined;+ emojisMenuOps: ReturnType<typeof createMenuOperations> | undefined;+ accessoryStore: ReturnType<typeof createAccessoryStore>[0] | undefined;+ dragInsertStore: ReturnType<typeof createDragInsertStore>[0] | undefined;+ fileDropConfig: MediaDropOptions | undefined;+}++export interface EditorHandle {+ controls: EditorControls;+ lexical: LexicalEditor;+ plugins: PluginManager;+ selection?: Store<SelectionData>;+ /** @internal consumed by MarkdownShell component; do not access directly */+ _internal: EditorInternals;+}++/**+ * Minimal interface satisfied by {@link MarkdownConfigBuilder}.+ * `MarkdownShell` accepts this instead of the concrete class to avoid a+ * circular module dependency.+ */+export interface EditorBuilder {+ /** Called once by `<MarkdownShell>` to instantiate reactive state. Can also be called directly for low-level Lexical access. */+ buildHandle(): EditorHandle;+}diff --git a/js/app/packages/core/component/LexicalMarkdown/component/decorator/HorizontalRule.tsx b/js/app/packages/core/component/LexicalMarkdown/component/decorator/HorizontalRule.tsxindex 56b5867c01..dde9bddbfc 100644--- a/js/app/packages/core/component/LexicalMarkdown/component/decorator/HorizontalRule.tsx+++ b/js/app/packages/core/component/LexicalMarkdown/component/decorator/HorizontalRule.tsx@@ -1,4 +1,3 @@-import { DeprecatedIconButton } from '@core/component/DeprecatedIconButton';import Trash from '@icon/regular/x.svg';import type { HorizontalRuleDecoratorProps } from '@lexical-core';import { debounce } from '@solid-primitives/scheduled';@@ -9,6 +8,7 @@ import {$setSelection,} from 'lexical';import { createSignal, useContext } from 'solid-js';+import { Button } from '@ui/components/Button';import { LexicalWrapperContext } from '../../context/LexicalWrapperContext';export function HorizontalRule(props: HorizontalRuleDecoratorProps) {@@ -82,20 +82,20 @@ export function HorizontalRule(props: HorizontalRuleDecoratorProps) {}}/>- {/* Add hover overlay similar to the image component */}{(isSelectedAsNode() || ruleHover()) && (<div class="absolute h-full top-0 right-2 flex flex-row gap-1 items-center">{editor()?.isEditable() && (- <DeprecatedIconButton- class="m-0"- theme="clear"- icon={() => <Trash class="size-4" />}- tooltip={{ label: 'Remove' }}- onClick={(e: MouseEvent | KeyboardEvent) => {+ <Button+ class="size-8 p-0 border-0 bg-transparent hover:bg-hover"+ tooltip="Remove"+ on:mousedown={(e: MouseEvent) => {e.preventDefault();+ e.stopPropagation();deleteRule();}}- />+ >+ <Trash class="size-4" />+ </Button>)}</div>)}diff --git a/js/app/packages/core/component/LexicalMarkdown/component/decorator/MediaButtons.tsx b/js/app/packages/core/component/LexicalMarkdown/component/decorator/MediaButtons.tsxindex 245e201a40..ccc3f4fef4 100644--- a/js/app/packages/core/component/LexicalMarkdown/component/decorator/MediaButtons.tsx+++ b/js/app/packages/core/component/LexicalMarkdown/component/decorator/MediaButtons.tsx@@ -1,4 +1,3 @@-import { DeprecatedIconButton } from '@core/component/DeprecatedIconButton';import {DropdownMenuContent,MenuItem,@@ -12,6 +11,7 @@ import ThreeDotsIcon from '@icon/regular/dots-three.svg';import Trash from '@icon/regular/trash.svg';import { Dialog } from '@kobalte/core/dialog';import { DropdownMenu } from '@kobalte/core/dropdown-menu';+import { Button } from '@ui/components/Button';import { createSignal, onCleanup, onMount, Show } from 'solid-js';false && clickOutside;@@ -49,39 +49,44 @@ export function MediaButtons(props: MediaButtonsProps) {const ButtonContent = () => (<><Show when={props.enlarge}>- <Dialog.Trigger>- <DeprecatedIconButton- class="m-0"- icon={() => <ArrowsOut class="size-5" />}- tooltip={{ label: 'View full screen' }}- onClick={(e: MouseEvent | KeyboardEvent) => {- e.preventDefault();- props.enlarge && props.enlarge();- }}- />+ <Dialog.Trigger+ as={Button}+ class="size-8 p-0 border-0 bg-transparent hover:bg-hover"+ tooltip="View full screen"+ on:mousedown={(e: MouseEvent) => {+ e.preventDefault();+ e.stopPropagation();+ props.enlarge?.();+ }}+ >+ <ArrowsOut class="size-5" /></Dialog.Trigger></Show><Show when={props.newTab && !isMobile()}>- <DeprecatedIconButton- class="m-0"- icon={() => <NewTab class="size-5" />}- tooltip={{ label: 'Open in new tab' }}- onClick={(e: MouseEvent | KeyboardEvent) => {+ <Button+ class="size-8 p-0 border-0 bg-transparent hover:bg-hover"+ tooltip="Open in new tab"+ on:mousedown={(e: MouseEvent) => {e.preventDefault();- props.newTab && props.newTab();+ e.stopPropagation();+ props.newTab?.();}}- />+ >+ <NewTab class="size-5" />+ </Button></Show><Show when={props.delete}>- <DeprecatedIconButton- class="m-0"- icon={() => <Trash class="size-5" />}- tooltip={{ label: 'Remove' }}- onClick={(e: MouseEvent | KeyboardEvent) => {+ <Button+ class="size-8 p-0 border-0 bg-transparent hover:bg-hover"+ tooltip="Remove"+ on:mousedown={(e: MouseEvent) => {e.preventDefault();- props.delete && props.delete();+ e.stopPropagation();+ props.delete?.();}}- />+ >+ <Trash class="size-5" />+ </Button></Show></>);@@ -97,12 +102,12 @@ export function MediaButtons(props: MediaButtonsProps) {onOpenChange={setMenuOpen}placement="bottom-end">- <DropdownMenu.Trigger>- <DeprecatedIconButton- class="m-0"- icon={() => <ThreeDotsIcon class="size-4" />}- tooltip={{ label: 'More options' }}- />+ <DropdownMenu.Trigger+ as={Button}+ class="size-8 p-0 border-0 bg-transparent hover:bg-hover"+ tooltip="More options"+ >+ <ThreeDotsIcon class="size-4" /></DropdownMenu.Trigger><DropdownMenu.Portal><DropdownMenuContent>@@ -121,7 +126,7 @@ export function MediaButtons(props: MediaButtonsProps) {text="View full screen"icon={ArrowsOut}onClick={() => {- props.enlarge && props.enlarge();+ props.enlarge?.();setMenuOpen(false);}}/>@@ -131,7 +136,7 @@ export function MediaButtons(props: MediaButtonsProps) {text="Open in new tab"icon={NewTab}onClick={() => {- props.newTab && props.newTab();+ props.newTab?.();setMenuOpen(false);}}/>@@ -143,7 +148,7 @@ export function MediaButtons(props: MediaButtonsProps) {icon={Trash}iconClass="text-failure"onClick={() => {- props.delete && props.delete();+ props.delete?.();setMenuOpen(false);}}/>diff --git a/js/app/packages/core/component/LexicalMarkdown/component/decorator/ResizeHandle.tsx b/js/app/packages/core/component/LexicalMarkdown/component/decorator/ResizeHandle.tsxindex bc86bb10a0..32ab63ee27 100644--- a/js/app/packages/core/component/LexicalMarkdown/component/decorator/ResizeHandle.tsx+++ b/js/app/packages/core/component/LexicalMarkdown/component/decorator/ResizeHandle.tsx@@ -130,7 +130,7 @@ export function ResizeHandle(props: ResizeHandleProps) {return (<divref={handleRef}- class="w-4 absolute top-0 h-full cursor-col-resize z-1 pattern-diagonal-4 transition-colors duration-200 flex flex-col justify-center group"+ class="w-4 absolute top-0 h-full cursor-col-resize z-1 transition-colors duration-200 flex flex-col justify-center group"classList={{'right-0': props.side === 'right','left-0': props.side === 'left',diff --git a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsxindex 9b17eff1de..ac12cb02f6 100644--- a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx+++ b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx@@ -89,7 +89,7 @@ function MentionsMenuInner(props: MentionsMenuProps) {const blockId = useMaybeBlockId();- const { usersAndGroups } = useUsersMention({+ const { usersAndGroups, groups } = useUsersMention({users: props.users,searchTerm,isChannelBlock: props.block === 'channel',@@ -191,7 +191,7 @@ function MentionsMenuInner(props: MentionsMenuProps) {const buckets: BucketConfig[] = [{id: 'users',- label: 'People & Groups',+ label: groups().length > 0 ? 'People & Groups' : 'People',getData: () => usersAndGroups() ?? [],getFullCount: () => usersAndGroups()?.length ?? 0,},diff --git a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mentionHandlers.ts b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mentionHandlers.tsindex 115c7af167..5baf04ecaf 100644--- a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mentionHandlers.ts+++ b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mentionHandlers.ts@@ -12,6 +12,10 @@ import type {MentionItem,} from '../../../../utils/mentionsUtils';import { handleUserMention } from '../../../../utils/mentionsUtils';+import {+ handleSnapshotMention,+ supportsSnapshotNode,+} from '../../../../utils/snapshotMention';import type { DateOption } from '@core/util/dateSearch/useDateSearch';import { getBlockNameFromEntity } from './entityUtils';@@ -33,6 +37,27 @@ export async function handleEntityMention(const entity = item.data;+ const blockNameForMention = getBlockNameFromEntity(item);+ const itemName = entity.name ?? (item.bucket === 'email' ? 'No Subject' : '');++ // For document entities, check if snapshot insertion is requested and supported.+ // This restores the behaviour that existed before the quick-access refactor where+ // handleBasicMention (which calls handleSnapshotMention) was used for 'item' picks.+ if (+ dependencies.useSnapshotNode &&+ item.bucket !== 'channel' &&+ item.bucket !== 'dm' &&+ item.bucket !== 'email' &&+ supportsSnapshotNode(blockNameForMention)+ ) {+ // EntityBase is a superset of the fields DocumentHistoryItem needs, so the+ // cast is safe for the document buckets we've already filtered to.+ const historyLike = entity as unknown as Parameters<+ typeof handleSnapshotMention+ >[0];+ return await handleSnapshotMention(historyLike, dependencies);+ }+let mentionId: string | undefined;if (blockId &&@@ -47,9 +72,6 @@ export async function handleEntityMention(mentionId = await trackMention(blockId, trackType, entity.id);}- const blockNameForMention = getBlockNameFromEntity(item);- const itemName = entity.name ?? (item.bucket === 'email' ? 'No Subject' : '');-if (item.bucket === 'email') {onEmailMention?.(entity as unknown as EmailEntity);} else {diff --git a/js/app/packages/core/component/LexicalMarkdown/plugins/shared/utils.ts b/js/app/packages/core/component/LexicalMarkdown/plugins/shared/utils.tsindex c9b8b3a526..c3e8021f40 100644--- a/js/app/packages/core/component/LexicalMarkdown/plugins/shared/utils.ts+++ b/js/app/packages/core/component/LexicalMarkdown/plugins/shared/utils.ts@@ -1,11 +1,13 @@import { mergeRegister } from '@lexical/utils';import {COMMAND_PRIORITY_NORMAL,+ type CommandListener,type CommandListenerPriority,createCommand,DELETE_CHARACTER_COMMAND,DELETE_LINE_COMMAND,DELETE_WORD_COMMAND,+ type LexicalCommand,type LexicalEditor,type UpdateListener,} from 'lexical';@@ -134,6 +136,40 @@ export function autoRegister(...fns: Array<() => void>) {onCleanup(cleanup);}+/**+ * Reactively register a Lexical command for the lifetime of the calling+ * component. The `handler` accessor is tracked inside a `createEffect`:+ *+ * - When it returns `undefined` no command is registered.+ * - When it returns a function the command is registered.+ * - If the accessor is reactive and its value changes, the previous+ * registration is cleaned up and a new one is created automatically.+ * - On component unmount the registration is always cleaned up.+ *+ * @example+ * // Register only when an optional prop is provided:+ * registerCommandEffect(+ * editor,+ * KEY_TAB_COMMAND,+ * () => props.onTab ? (e) => props.onTab!(e) : undefined,+ * COMMAND_PRIORITY_CRITICAL,+ * );+ */+export function registerCommandEffect<T>(+ editor: LexicalEditor,+ command: LexicalCommand<T>,+ handler: Accessor<CommandListener<T> | undefined>,+ priority: CommandListenerPriority+): void {+ let cleanup: () => void = () => {};+ createEffect(() => {+ cleanup();+ const fn = handler();+ cleanup = fn ? editor.registerCommand(command, fn, priority) : () => {};+ });+ onCleanup(() => cleanup());+}+const LAYOUT_SHFIT_COMMAND = createCommand<void>('LAYOUT_SHIFT_COMMAND');/**