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 md util for truncating around <macro_em> search tags for soup (#768)
Seamus11a5c8a528d4
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/debug/MarkdownParseTestPage.tsx b/js/app/packages/core/component/LexicalMarkdown/component/debug/MarkdownParseTestPage.tsxindex dd47606dfb..fb9407cb1f 100644--- a/js/app/packages/core/component/LexicalMarkdown/component/debug/MarkdownParseTestPage.tsx+++ b/js/app/packages/core/component/LexicalMarkdown/component/debug/MarkdownParseTestPage.tsx@@ -4,9 +4,9 @@ import { debounce } from '@solid-primitives/scheduled';import {type Accessor,createEffect,+ createMemo,createSignal,onCleanup,- onMount,Show,} from 'solid-js';import {@@ -21,6 +21,14 @@ import {tabIndentationPlugin,tablePlugin,} from '../../plugins';+import {+ aiChatTheme,+ channelTheme,+ channelThemeSender,+ embeddedCodeBlock,+ theme,+ unifiedListMarkdownTheme,+} from '../../theme';import {editorIsEmpty,initializeEditorWithState,@@ -35,6 +43,8 @@ const KEYS = {outputType: 'internal-markdown-output-type',targetType: 'internal-markdown-target-type',inputType: 'internal-markdown-input-type',+ themeType: 'internal-markdown-theme-type',+ singleLine: 'internal-markdown-single-line',};const getSavedStringFromLocalStorage = () => {@@ -77,18 +87,88 @@ const getSavedInputType = (): 'markdown' | 'lexical-json' => {return 'markdown';};+type ThemeType =+ | 'default'+ | 'aiChat'+ | 'channel'+ | 'channelSender'+ | 'embeddedCode'+ | 'unifiedList';++const getSavedThemeType = (): ThemeType => {+ try {+ const saved = localStorage.getItem(KEYS.themeType);+ if (+ saved === 'default' ||+ saved === 'aiChat' ||+ saved === 'channel' ||+ saved === 'channelSender' ||+ saved === 'embeddedCode' ||+ saved === 'unifiedList'+ ) {+ return saved as ThemeType;+ }+ } catch (_) {}+ return 'default';+};++const getSavedSingleLine = (): boolean => {+ try {+ const saved = localStorage.getItem(KEYS.singleLine);+ return saved === 'true';+ } catch (_) {}+ return false;+};++const getThemeByType = (themeType: ThemeType) => {+ switch (themeType) {+ case 'aiChat':+ return aiChatTheme;+ case 'channel':+ return channelTheme;+ case 'channelSender':+ return channelThemeSender;+ case 'embeddedCode':+ return embeddedCodeBlock;+ case 'unifiedList':+ return unifiedListMarkdownTheme;+ default:+ return theme;+ }+};+export function TestEditor(props: {value: Accessor<string>;target: Accessor<'internal' | 'external' | 'both'>;inputType: Accessor<'markdown' | 'lexical-json'>;+ themeType: Accessor<ThemeType>;}) {let mountRef!: HTMLDivElement;- const lexicalWrapper = createLexicalWrapper({- type: 'markdown',- namespace: 'markdown-textarea',- isInteractable: () => true,- });- const { editor, plugins, cleanup: cleanupLexical } = lexicalWrapper;++ const lexicalWrapper = createMemo(() =>+ createLexicalWrapper({+ type: 'markdown',+ namespace: 'markdown-textarea',+ isInteractable: () => true,+ theme: getThemeByType(props.themeType()),+ })+ );++ const editor = () => lexicalWrapper().editor;+ const plugins = () => lexicalWrapper().plugins;+ const cleanup = () => lexicalWrapper().cleanup;++ const debouncedUpdateContent = debounce(+ (+ content: string,+ target: 'internal' | 'external' | 'both',+ inputType: 'markdown' | 'lexical-json'+ ) => {+ setEditorContent(content, target, inputType);+ },+ 50+ );+const setEditorContent = (content: string,target: 'internal' | 'external' | 'both',@@ -97,74 +177,73 @@ export function TestEditor(props: {if (inputType === 'lexical-json') {try {const parsed = JSON.parse(content);- initializeEditorWithState(editor, parsed);+ initializeEditorWithState(editor(), parsed);} catch (error) {console.error('Invalid JSON:', error);}} else {- setEditorStateFromMarkdown(editor, content, target);+ setEditorStateFromMarkdown(editor(), content, target);}};- setEditorContent(props.value(), props.target(), props.inputType());- const debouncedUpdateContent = debounce(- (- content: string,- target: 'internal' | 'external' | 'both',- inputType: 'markdown' | 'lexical-json'- ) => {- setEditorContent(content, target, inputType);- },- 50- );-createEffect(() => {const value = props.value();const target = props.target();const inputType = props.inputType();- debouncedUpdateContent(value, target, inputType);+ if (value || inputType === 'lexical-json') {+ debouncedUpdateContent(value, target, inputType);+ }});const [showPlaceholder, setShowPlaceholder] = createSignal(true);+ const [accessoryStore, setAccessoryStore] = createAccessoryStore();- plugins- .richText()- .list()- .markdownShortcuts()- .delete()- .history(400)- .use(tabIndentationPlugin())- .use(mentionsPlugin({}))- .use(mediaPlugin())- .use(tablePlugin({}));+ // Setup plugins whenever the wrapper changes+ createEffect(() => {+ const currentPlugins = plugins();+ const currentAccessoryStore = accessoryStore;- const [accessoryStore, setAccessoryStore] = createAccessoryStore();- plugins.use(- codePlugin({- accessories: accessoryStore,- setAccessories: setAccessoryStore,- })- );+ currentPlugins+ .richText()+ .list()+ .markdownShortcuts()+ .delete()+ .history(400)+ .use(tabIndentationPlugin())+ .use(mentionsPlugin({}))+ .use(mediaPlugin())+ .use(tablePlugin({}))+ .use(+ codePlugin({+ accessories: currentAccessoryStore,+ setAccessories: setAccessoryStore,+ })+ );+ });- onMount(() => {- editor.setRootElement(mountRef);- editor.setEditable(false);+ // Setup editor whenever it changes+ createEffect(() => {+ const currentEditor = editor();+ if (mountRef) {+ currentEditor.setRootElement(mountRef);+ currentEditor.setEditable(false);+ }});onCleanup(() => {- cleanupLexical();+ cleanup();});createEffect(() => {props.value();- setShowPlaceholder(editorIsEmpty(editor));+ setShowPlaceholder(editorIsEmpty(editor()));});return (- <LexicalWrapperContext.Provider value={lexicalWrapper}>+ <LexicalWrapperContext.Provider value={lexicalWrapper()}><div ref={mountRef} contentEditable={false}></div>- <DecoratorRenderer editor={editor} />- <NodeAccessoryRenderer editor={editor} store={accessoryStore} />+ <DecoratorRenderer editor={editor()} />+ <NodeAccessoryRenderer editor={editor()} store={accessoryStore} /><Show when={showPlaceholder()}><div class="pointer-events-none text-ink-extra-muted absolute top-0"><p class="my-1.5">...</p>@@ -187,18 +266,28 @@ export default function MarkdownParseTestPage() {const [inputType, setInputType] = createSignal<'markdown' | 'lexical-json'>(getSavedInputType());+ const [themeType, setThemeType] = createSignal<ThemeType>(+ getSavedThemeType()+ );+ const [singleLine, setSingleLine] = createSignal<boolean>(+ getSavedSingleLine()+ );const debouncedLocalSave = debounce(() => {const content = rawContent();const output = outputType();const target = targetType();const input = inputType();+ const theme = themeType();+ const single = singleLine();try {localStorage.setItem(KEYS.content, content);localStorage.setItem(KEYS.outputType, output);localStorage.setItem(KEYS.targetType, target);localStorage.setItem(KEYS.inputType, input);+ localStorage.setItem(KEYS.themeType, theme);+ localStorage.setItem(KEYS.singleLine, single.toString());} catch (_) {}});@@ -207,6 +296,8 @@ export default function MarkdownParseTestPage() {outputType();targetType();inputType();+ themeType();+ singleLine();debouncedLocalSave();});@@ -296,13 +387,44 @@ export default function MarkdownParseTestPage() {</div></div>+ <div class="flex items-center gap-2 mb-4">+ <span class="text-sm text-ink-extra-muted">Theme</span>+ <select+ class="px-3 py-1 text-sm bg-edge/50 border-1 border-edge rounded"+ value={themeType()}+ onChange={(e) => setThemeType(e.target.value as ThemeType)}+ >+ <option value="default">Default</option>+ <option value="aiChat">AI Chat</option>+ <option value="channel">Channel</option>+ <option value="channelSender">Channel Sender</option>+ <option value="embeddedCode">Embedded Code</option>+ <option value="unifiedList">Unified List</option>+ </select>+ </div>++ <Show when={outputType() === 'static'}>+ <div class="flex items-center gap-2 mb-4">+ <label class="flex items-center gap-2 cursor-pointer">+ <input+ type="checkbox"+ checked={singleLine()}+ onChange={(e) => setSingleLine(e.target.checked)}+ class="rounded border-edge"+ />+ <span class="text-sm text-ink-extra-muted">Single Line</span>+ </label>+ </div>+ </Show>+<div class="flex-1 overflow-auto bg-input border border-edge rounded p-4"><Show when={outputType() === 'static'}>- <StaticMarkdownContext>+ <StaticMarkdownContext theme={getThemeByType(themeType())}><Show when={inputType() === 'markdown'}><StaticMarkdownmarkdown={rawContent()}target={targetType()}+ singleLine={singleLine()}/></Show><Show when={inputType() === 'lexical-json'}>@@ -320,6 +442,7 @@ export default function MarkdownParseTestPage() {value={rawContent}target={targetType}inputType={inputType}+ themeType={themeType}/></div></Show>diff --git a/js/app/packages/core/component/LexicalMarkdown/utils.ts b/js/app/packages/core/component/LexicalMarkdown/utils.tsindex 86d7032158..7d4cc9f016 100644--- a/js/app/packages/core/component/LexicalMarkdown/utils.ts+++ b/js/app/packages/core/component/LexicalMarkdown/utils.ts@@ -14,6 +14,7 @@ import {$convertToMarkdownString,type Transformer,} from '@lexical/markdown';+import { $isHeadingNode, $isQuoteNode } from '@lexical/rich-text';import {$dfsIterator,$findMatchingParent,@@ -1184,7 +1185,7 @@ function takeInlineUntilLineBreak(parent: ElementNode): LexicalNode[] {if ($isLineBreakNode(child)) {break;}- if ($isTextNode(child) && child.getTextContent().trim() === '') {+ if ($isTextNode(child) && child.getTextContent() === '') {continue;}out.push(child);@@ -1193,7 +1194,7 @@ function takeInlineUntilLineBreak(parent: ElementNode): LexicalNode[] {}const $singleLineNode = (node: ElementNode): ElementNode | null => {- if ($isParagraphNode(node)) {+ if ($isParagraphNode(node) || $isHeadingNode(node) || $isQuoteNode(node)) {const inline = takeInlineUntilLineBreak(node);if (!inline.length) return null;node.clear();diff --git a/js/app/packages/core/util/searchHighlight.ts b/js/app/packages/core/util/searchHighlight.tsindex 7310d7b2e5..0bd4d40191 100644--- a/js/app/packages/core/util/searchHighlight.ts+++ b/js/app/packages/core/util/searchHighlight.ts@@ -62,3 +62,53 @@ export function extractSearchSnippet(highlightedContent: string): string {export function mergeAdjacentMacroEmTags(highlightedContent: string): string {return highlightedContent.replace(/<\/macro_em>(\s+)<macro_em>/g, '$1');}++/**+ * Truncate markdown returned from the search service so that the *first*+ * <macro_em> match is visible within a fixed character window.+ *+ * Behavior:+ * - Only the first line containing a <macro_em> tag is considered.+ * - Other <macro_em> tags on the same line are preserved verbatim.+ * - If the match line is not the first line, the result is prefixed with "...".+ * - If the opening <macro_em> tag starts beyond the allowed window,+ * content is trimmed from the front (preferably at a word boundary)+ * until the tag is within the window.+ * - When front-trimming occurs, "..." is prepended.+ *+ * @param text - Markdown source content from search results.+ * @param chars - Maximum visible character window (excluding ellipsis).+ * @returns A truncated string that guarantees visibility of the first match.+ */+export function truncateSearchMatch(text: string, chars: number): string {+ const lines = text.split('\n');+ const macroOpen = '<macro_em>';++ const lineIndex = lines.findIndex((l) => l.includes(macroOpen));+ if (lineIndex === -1) {+ return text;+ }++ let line = lines[lineIndex];+ let needsEllipsis = lineIndex > 0;++ const tagIndex = line.indexOf(macroOpen);++ if (tagIndex <= chars) {+ return (needsEllipsis ? '...' : '') + line;+ }++ const targetStart = Math.max(0, tagIndex - chars);++ // prefer trimming at a word boundary+ let cutIndex = targetStart;+ for (let i = targetStart; i < tagIndex; i++) {+ if (/\s/.test(line[i])) {+ cutIndex = i + 1;+ break;+ }+ }++ line = line.slice(cutIndex);+ return '...' + line;+}diff --git a/js/app/packages/macro-entity/src/queries/search.ts b/js/app/packages/macro-entity/src/queries/search.tsindex a547c7ebd1..d3422fb333 100644--- a/js/app/packages/macro-entity/src/queries/search.ts+++ b/js/app/packages/macro-entity/src/queries/search.ts@@ -7,6 +7,7 @@ import {extractSearchSnippet,extractSearchTerms,mergeAdjacentMacroEmTags,+ truncateSearchMatch,} from '@core/util/searchHighlight';import type { ChannelType } from '@service-comms/generated/models';import { type PaginatedSearchArgs, searchClient } from '@service-search/client';@@ -26,6 +27,8 @@ import type { ContentHitData, SearchData, WithSearch } from '../types/search';import type { EntityInfiniteQuery } from './entity';import { queryKeys } from './key';+const SEARCH_MATCH_LENGTH = 60;+type InnerSearchResult =| DocumentSearchResult| EmailSearchResult@@ -57,7 +60,10 @@ const getSearchData = (data: TypedInnerSearchResult): SearchData => {return contents.map((content) => ({type: 'channel' as const,id: r.message_id!,- content: mergeAdjacentMacroEmTags(content),+ content: truncateSearchMatch(+ mergeAdjacentMacroEmTags(content),+ SEARCH_MATCH_LENGTH+ ),senderId: r.sender_id!,sentAt: r.created_at!,location: {@@ -76,7 +82,10 @@ const getSearchData = (data: TypedInnerSearchResult): SearchData => {const mergedContent = mergeAdjacentMacroEmTags(content);return {type: 'pdf' as const,- content: mergeAdjacentMacroEmTags(content),+ content: truncateSearchMatch(+ mergeAdjacentMacroEmTags(content),+ SEARCH_MATCH_LENGTH+ ),location: {type: 'pdf' as const,searchPage: Number(r.node_id),@@ -97,7 +106,10 @@ const getSearchData = (data: TypedInnerSearchResult): SearchData => {const contents = r.highlight.content ?? [];return contents.map((content) => ({type: 'md' as const,- content: mergeAdjacentMacroEmTags(content),+ content: truncateSearchMatch(+ mergeAdjacentMacroEmTags(content),+ SEARCH_MATCH_LENGTH+ ),location: { type: 'md' as const, nodeId: r.node_id! },}));});@@ -108,7 +120,10 @@ const getSearchData = (data: TypedInnerSearchResult): SearchData => {const contents = r.highlight.content ?? [];return contents.map((content) => ({type: 'email' as const,- content: mergeAdjacentMacroEmTags(content),+ content: truncateSearchMatch(+ mergeAdjacentMacroEmTags(content),+ SEARCH_MATCH_LENGTH+ ),sender: r.pretty_sender!,senderId: emailToId(r.sender),sentAt: r.sent_at!,@@ -124,7 +139,10 @@ const getSearchData = (data: TypedInnerSearchResult): SearchData => {contentHitData = data.results.flatMap((r) => {const contents = r.highlight.content ?? [];return contents.map((content) => ({- content: mergeAdjacentMacroEmTags(content),+ content: truncateSearchMatch(+ mergeAdjacentMacroEmTags(content),+ SEARCH_MATCH_LENGTH+ ),location: undefined,}));});