Skip to content

armgit / macro

Public Imported from GitHub
0

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

fix(md): improve md find and replace highlight logic and responsiveness (#4055)

Seamus2a9792772423
diff --git a/js/app/packages/block-md/component/Block.tsx b/js/app/packages/block-md/component/Block.tsx
index 5c6496efa1..dafbf27faf 100644
--- a/js/app/packages/block-md/component/Block.tsx
+++ b/js/app/packages/block-md/component/Block.tsx
@@ -203,10 +203,9 @@ function BlockMarkdownContent({ optimisticSnapshot }: BlockMarkdownProps) {
<TopBar name={displayName} />
</Show>
</Suspense>
- {/* off until - https://linear.app/macro-eng/issue/M-5203/markdown-unloads-completely-after-find */}
<Suspense>
- <Show when={!isInstructionsMd() && false}>
- <div class="absolute right-4 bottom-[-12] translate-y-full z-action-menu flex justify-end">
+ <Show when={!isInstructionsMd()}>
+ <div class="absolute right-4 top-1.5 z-action-menu flex justify-end">
<FindAndReplace />
</div>
</Show>
diff --git a/js/app/packages/block-md/component/FindAndReplace.tsx b/js/app/packages/block-md/component/FindAndReplace.tsx
index a780f36349..7e211f1e83 100644
--- a/js/app/packages/block-md/component/FindAndReplace.tsx
+++ b/js/app/packages/block-md/component/FindAndReplace.tsx
@@ -5,9 +5,9 @@ import {
DO_REPLACE_ONCE_COMMAND,
DO_SEARCH_COMMAND,
} from '@core/component/LexicalMarkdown/plugins';
-import type { FloatingStyle } from '@core/component/LexicalMarkdown/plugins/find-and-replace';
-import { IS_MAC } from '@core/constant/isMac';
-import { blockElementSignal } from '@core/signal/blockElement';
+import { registerHotkey } from '@core/hotkey/hotkeys';
+import { TOKENS } from '@core/hotkey/tokens';
+import { blockHotkeyScopeSignal } from '@core/signal/blockElement';
import { useCanEdit } from '@core/signal/permissions';
import ReplaceAll from '@phosphor/arrow-bend-double-up-right.svg';
import Replace from '@phosphor/arrow-bend-up-right.svg';
@@ -17,7 +17,7 @@ import CaretUp from '@phosphor/caret-up.svg';
import MagnifyingGlass from '@phosphor/magnifying-glass.svg';
import X from '@phosphor/x.svg';
import { createCallback } from '@solid-primitives/rootless';
-import { cn, Tooltip } from '@ui';
+import { cn, Panel, Tooltip } from '@ui';
import type { JSX } from 'solid-js';
import { createEffect, createSignal, on, onCleanup, Show } from 'solid-js';
@@ -25,7 +25,7 @@ export function FindAndReplace() {
const mdData = mdStore.get;
const canEdit = useCanEdit();
const editor = () => mdData.editor;
- const blockElement = blockElementSignal.get;
+ const scopeId = blockHotkeyScopeSignal.get;
let inputRef: HTMLInputElement | undefined;
let inputReplaceRef: HTMLInputElement | undefined;
@@ -52,22 +52,36 @@ export function FindAndReplace() {
);
};
- const scrollToCurrentHighlight = (nextHighlight: boolean = false) => {
- const scrollContainer = mdData.scrollContainer;
- if (!scrollContainer) return;
+ const focusSearchInput = (select = false) => {
+ queueMicrotask(() => {
+ inputRef?.focus();
+ if (select) {
+ inputRef?.select();
+ }
+ });
+ };
- let highlightIndex: number = findAndReplaceStore.currentMatch;
- if (nextHighlight) {
- highlightIndex = (highlightIndex + 1) % findAndReplaceStore.styles.length;
- }
+ const getMatchDocumentElement = (matchIndex: number) => {
+ const editorInstance = editor();
+ if (!editorInstance) return;
+
+ const offset = findAndReplaceStore.listOffset.find(
+ (item) => item.pairKey === matchIndex + 1
+ );
+ if (!offset) return;
- const transform =
- findAndReplaceStore.styles?.[highlightIndex]?.style?.transform;
- const yPos = transform ? parseFloat(transform.split(',')[1]) : 0;
+ const element = editorInstance.getElementByKey(offset.key);
+ return element?.parentElement ?? element ?? undefined;
+ };
+
+ const scrollToCurrentHighlight = (matchIndex: number) => {
+ const matchElement = getMatchDocumentElement(matchIndex);
+ if (!matchElement) return;
- scrollContainer.scrollTo({
- top: Math.max(0, yPos - 20),
+ matchElement.scrollIntoView({
behavior: 'smooth',
+ block: 'center',
+ inline: 'nearest',
});
};
@@ -76,23 +90,33 @@ export function FindAndReplace() {
createEffect(
on(scrollToNext, () => {
const currentMatch: number = findAndReplaceStore.currentMatch;
- const styles: { style: FloatingStyle; idx: number | undefined }[] =
- findAndReplaceStore.styles;
- if (scrollToNext() && currentMatch === -1 && styles.length > 0) {
+ if (
+ scrollToNext() &&
+ currentMatch === -1 &&
+ findAndReplaceStore.listOffset.length > 0
+ ) {
let highlightToScrollTo: number = 0;
const scrollContainer = mdData.scrollContainer;
if (scrollContainer) {
- for (let i = 0; i < styles.length; i++) {
- const transform = styles?.[i]?.style?.transform;
- const yPos = transform ? parseFloat(transform.split(',')[1]) : 0;
- if (yPos >= scrollContainer.scrollTop - 100) {
- highlightToScrollTo = i;
+ const scrollRect = scrollContainer.getBoundingClientRect();
+ const seenMatchIndexes = new Set<number>();
+ for (const offset of findAndReplaceStore.listOffset) {
+ const matchIndex = (offset.pairKey ?? 1) - 1;
+ if (seenMatchIndexes.has(matchIndex)) continue;
+ seenMatchIndexes.add(matchIndex);
+
+ const element = getMatchDocumentElement(matchIndex);
+ if (!element) continue;
+
+ const rect = element.getBoundingClientRect();
+ if (rect.top >= scrollRect.top - 100) {
+ highlightToScrollTo = matchIndex;
break;
}
}
}
setFindAndReplaceStore('currentMatch', highlightToScrollTo);
- scrollToCurrentHighlight();
+ scrollToCurrentHighlight(highlightToScrollTo);
setScrollToNext(false);
}
})
@@ -126,7 +150,7 @@ export function FindAndReplace() {
}
}
}
- scrollToCurrentHighlight();
+ scrollToCurrentHighlight(highlightToScrollTo);
});
// Search
@@ -187,7 +211,9 @@ export function FindAndReplace() {
return;
}
- scrollToCurrentHighlight(true);
+ scrollToCurrentHighlight(
+ (findAndReplaceStore.currentMatch + 1) % findAndReplaceStore.matches
+ );
editor()?.dispatchCommand(DO_REPLACE_ONCE_COMMAND, {
replaceString: replaceString,
nodeKeyOffsetList: findAndReplaceStore.listOffset.filter(
@@ -233,23 +259,32 @@ export function FindAndReplace() {
}
});
- const keyDownHandler = (e: KeyboardEvent) => {
- if ((IS_MAC ? e.metaKey : e.ctrlKey) && e.key === 'f') {
- e.stopPropagation();
- e.preventDefault();
- if (findAndReplaceStore.searchIsOpen) {
- if (inputRef === document.activeElement) {
- closeSearch();
+ createEffect(() => {
+ if (!scopeId()) return;
+
+ const registration = registerHotkey({
+ hotkey: 'cmd+f',
+ scopeId: scopeId(),
+ hotkeyToken: TOKENS.md.find,
+ description: 'Find in Document',
+ runWithInputFocused: true,
+ keyDownHandler: () => {
+ if (findAndReplaceStore.searchIsOpen) {
+ if (inputRef === document.activeElement) {
+ closeSearch();
+ } else {
+ focusSearchInput(true);
+ }
} else {
- inputRef?.focus();
- inputRef?.select();
+ setFindAndReplaceStore('searchIsOpen', true);
+ focusSearchInput();
}
- } else {
- setFindAndReplaceStore('searchIsOpen', true);
- inputRef?.focus();
- }
- }
- };
+ return true;
+ },
+ });
+
+ onCleanup(() => registration.dispose());
+ });
const replaceKeyDownHandler: JSX.EventHandler<
HTMLInputElement,
@@ -270,20 +305,12 @@ export function FindAndReplace() {
}
});
- createEffect(() => {
- const element = blockElement();
- if (!element) return;
- element.addEventListener('keydown', keyDownHandler);
- document.addEventListener('keydown', keyDownHandler);
- onCleanup(() => {
- element.removeEventListener('keydown', keyDownHandler);
- document.removeEventListener('keydown', keyDownHandler);
- });
- });
-
return (
<Show when={findAndReplaceStore.searchIsOpen}>
- <div class="flex items-center justify-start rounded-md border border-edge bg-surface p-1 shadow w-fit">
+ <Panel
+ depth={3}
+ class="flex items-center justify-start rounded-xl bg-surface p-2 shadow-lg shadow-drop-shadow w-fit"
+ >
<div class="flex items-center px-1">
<Tooltip
label={`${findAndReplaceStore.replaceInputOpen ? 'Collapse' : 'Expand'} Search Bar`}
@@ -411,7 +438,7 @@ export function FindAndReplace() {
</div>
</Show>
</div>
- </div>
+ </Panel>
</Show>
);
}
diff --git a/js/app/packages/block-md/component/MarkdownEditor.tsx b/js/app/packages/block-md/component/MarkdownEditor.tsx
index 534058de57..03f71ba252 100644
--- a/js/app/packages/block-md/component/MarkdownEditor.tsx
+++ b/js/app/packages/block-md/component/MarkdownEditor.tsx
@@ -421,12 +421,9 @@ export function MarkdownEditor(props: {
dndDragMove(event);
});
- // handler for the find and replace directive
const onSetListOffset = (listOffset: NodekeyOffset[]) => {
setFindAndReplaceStore('listOffset', listOffset);
- if (
- findAndReplaceStore.currentMatch >= findAndReplaceStore.listOffset.length
- ) {
+ if (findAndReplaceStore.currentMatch >= listOffset.length) {
setFindAndReplaceStore('currentMatch', 0);
}
};
@@ -577,6 +574,7 @@ export function MarkdownEditor(props: {
)
.use(
findAndReplacePlugin({
+ getListOffset: () => findAndReplaceStore.listOffset,
setListOffset: onSetListOffset,
})
)
@@ -806,9 +804,12 @@ export function MarkdownEditor(props: {
);
};
- // handle updates to the highlights if the document is modified
- additionalCleanups.push(
- editor.registerUpdateListener(() => {
+ let searchRefreshQueued = false;
+ const queueSearchRefresh = () => {
+ if (searchRefreshQueued) return;
+ searchRefreshQueued = true;
+ queueMicrotask(() => {
+ searchRefreshQueued = false;
if (
findAndReplaceStore.searchIsOpen &&
findAndReplaceStore.searchInputText
@@ -818,6 +819,18 @@ export function MarkdownEditor(props: {
findAndReplaceStore.searchInputText
);
}
+ });
+ };
+
+ // Refresh highlights only after content mutations. Selection-only updates
+ // still fire Lexical update listeners and must not synchronously dispatch
+ // another command from inside the commit.
+ additionalCleanups.push(
+ editor.registerUpdateListener(({ dirtyElements, dirtyLeaves }) => {
+ if (dirtyElements.size === 0 && dirtyLeaves.size === 0) return;
+ if (!findAndReplaceStore.searchIsOpen) return;
+ if (!findAndReplaceStore.searchInputText) return;
+ queueSearchRefresh();
})
);
diff --git a/js/app/packages/core/component/LexicalMarkdown/plugins/find-and-replace/findAndReplacePlugin.ts b/js/app/packages/core/component/LexicalMarkdown/plugins/find-and-replace/findAndReplacePlugin.ts
index 48ac11e09d..bfa034cae4 100644
--- a/js/app/packages/core/component/LexicalMarkdown/plugins/find-and-replace/findAndReplacePlugin.ts
+++ b/js/app/packages/core/component/LexicalMarkdown/plugins/find-and-replace/findAndReplacePlugin.ts
@@ -62,6 +62,7 @@ interface NoneBreakNode {
}
type FindAndReplaceProps = {
+ getListOffset: () => NodekeyOffset[];
setListOffset: (listOffset: NodekeyOffset[]) => void;
};
@@ -450,16 +451,36 @@ function buildNodeKeyOffsetList(
}
function selectNextKey(key: NodeKey) {
+ if (!key) return;
const nodeSelection = $createNodeSelection();
nodeSelection.add(key);
$setSelection(nodeSelection);
}
+function areListOffsetsEqual(left: NodekeyOffset[], right: NodekeyOffset[]) {
+ if (left.length !== right.length) return false;
+ for (let i = 0; i < left.length; i += 1) {
+ const leftItem = left[i];
+ const rightItem = right[i];
+ if (leftItem.key !== rightItem.key) return false;
+ if (leftItem.pairKey !== rightItem.pairKey) return false;
+ if (leftItem.offset.start !== rightItem.offset.start) return false;
+ if (leftItem.offset.end !== rightItem.offset.end) return false;
+ if (leftItem.offset.isReplace !== rightItem.offset.isReplace) {
+ return false;
+ }
+ }
+ return true;
+}
+
function registerFindAndReplacePlugin(
editor: LexicalEditor,
props: FindAndReplaceProps
) {
const updateListOffset = (nodeKeyOffsetList: NodekeyOffset[]) => {
+ if (areListOffsetsEqual(props.getListOffset(), nodeKeyOffsetList)) {
+ return;
+ }
props.setListOffset(nodeKeyOffsetList);
};
@@ -567,61 +588,59 @@ function registerFindAndReplacePlugin(
editor.registerCommand(
DO_SEARCH_COMMAND,
(searchString: string) => {
- editor.getEditorState().read(() => {
- const root = $getRoot();
- const regex = new RegExp(preg_quote(searchString, '/'), 'gi');
- var rootText = traverseNodeGetText(root);
- rootText = rootText.replace(/\n+/g, '\n').replace(/^(\n)+/, '');
-
- const indexes: number[] = [];
- let found = regex.exec(rootText);
- while (found) {
- indexes.push(found.index);
- found = regex.exec(rootText);
- }
- const nodes = getNoneBreakNodes(root, searchString, indexes, {
- currentMatchIndex: 0,
- previousLength: 0,
- });
+ const root = $getRoot();
+ const regex = new RegExp(preg_quote(searchString, '/'), 'gi');
+ var rootText = traverseNodeGetText(root);
+ rootText = rootText.replace(/\n+/g, '\n').replace(/^(\n)+/, '');
+
+ const indexes: number[] = [];
+ let found = regex.exec(rootText);
+ while (found) {
+ indexes.push(found.index);
+ found = regex.exec(rootText);
+ }
+ const nodes = getNoneBreakNodes(root, searchString, indexes, {
+ currentMatchIndex: 0,
+ previousLength: 0,
+ });
- const nodeKeyOffsetList: NodekeyOffset[] = [];
- nodes.map((node) => {
- const hightlightTarget = highlightMultipleNode(
- node.node,
- searchString,
- { startIndex: 0, totalLength: node.node.getTextContent().length }
- );
- const originalLocations: StringLocation[] = node.realLocations.map(
- (rLocation) => {
- return {
- searchStart: rLocation.location,
- searchLength: rLocation.matched.length,
- };
- }
- );
- const additionLocations: StringLocation[] = [];
- const mainIndex = { currentIndex: 0 };
- hightlightTarget.map((hNode) => {
- buildNodeKeyOffsetList(
- hNode,
- additionLocations,
- originalLocations,
- mainIndex,
- nodeKeyOffsetList
- );
- });
- });
- let previousPairKey = 0;
- nodeKeyOffsetList.map(function (item) {
- if (item.offset.isReplace) {
- previousPairKey += 1;
- item.pairKey = previousPairKey;
- } else {
- item.pairKey = previousPairKey;
+ const nodeKeyOffsetList: NodekeyOffset[] = [];
+ nodes.map((node) => {
+ const hightlightTarget = highlightMultipleNode(
+ node.node,
+ searchString,
+ { startIndex: 0, totalLength: node.node.getTextContent().length }
+ );
+ const originalLocations: StringLocation[] = node.realLocations.map(
+ (rLocation) => {
+ return {
+ searchStart: rLocation.location,
+ searchLength: rLocation.matched.length,
+ };
}
+ );
+ const additionLocations: StringLocation[] = [];
+ const mainIndex = { currentIndex: 0 };
+ hightlightTarget.map((hNode) => {
+ buildNodeKeyOffsetList(
+ hNode,
+ additionLocations,
+ originalLocations,
+ mainIndex,
+ nodeKeyOffsetList
+ );
});
- updateListOffset(nodeKeyOffsetList);
});
+ let previousPairKey = 0;
+ nodeKeyOffsetList.map(function (item) {
+ if (item.offset.isReplace) {
+ previousPairKey += 1;
+ item.pairKey = previousPairKey;
+ } else {
+ item.pairKey = previousPairKey;
+ }
+ });
+ updateListOffset(nodeKeyOffsetList);
return true;
},
COMMAND_PRIORITY_HIGH
diff --git a/js/app/packages/core/component/LexicalMarkdown/plugins/find-and-replace/searchHighlight.tsx b/js/app/packages/core/component/LexicalMarkdown/plugins/find-and-replace/searchHighlight.tsx
index e8dc48cb0e..7f97aca9f7 100644
--- a/js/app/packages/core/component/LexicalMarkdown/plugins/find-and-replace/searchHighlight.tsx
+++ b/js/app/packages/core/component/LexicalMarkdown/plugins/find-and-replace/searchHighlight.tsx
@@ -1,9 +1,16 @@
import { FindAndReplaceStore } from '@block-md/signal/findAndReplaceStore';
import { mdStore } from '@block-md/signal/markdownBlockData';
+import { mergeRegister } from '@lexical/utils';
import { createCallback } from '@solid-primitives/rootless';
import { cn } from '@ui';
-import { createEffect, For, onCleanup, onMount } from 'solid-js';
+import { createEffect, For } from 'solid-js';
import { Portal } from 'solid-js/web';
+import {
+ autoRegister,
+ lazyRegister,
+ registerEditorWidthObserver,
+ registerInternalLayoutShiftListener,
+} from '../shared/utils';
import type { NodekeyOffset } from './findAndReplacePlugin';
import {
type FloatingStyle,
@@ -17,6 +24,21 @@ function getFirstChild(htmlEl: ChildNode | null | undefined) {
return htmlEl;
}
+function registerEventListener<K extends keyof HTMLElementEventMap>(
+ target: HTMLElement | null,
+ type: K,
+ listener: (event: HTMLElementEventMap[K]) => void
+): () => void;
+function registerEventListener(
+ target: HTMLElement | null,
+ type: string,
+ listener: EventListener
+) {
+ if (!target) return () => {};
+ target.addEventListener(type, listener);
+ return () => target.removeEventListener(type, listener);
+}
+
export function SearchHighlight({
anchorElem = document.body,
}: {
@@ -25,6 +47,7 @@ export function SearchHighlight({
const mdData = mdStore.get;
const editor = () => mdData.editor;
let stateListOffsetRef: NodekeyOffset[] = [];
+ let animationFrame: number | undefined;
const updateTextFormatFloatingToolbar = createCallback(
(listOffset: NodekeyOffset[]) => {
@@ -67,37 +90,52 @@ export function SearchHighlight({
}
);
+ const update = createCallback(() => {
+ if (animationFrame !== undefined) {
+ cancelAnimationFrame(animationFrame);
+ }
+
+ animationFrame = requestAnimationFrame(() => {
+ animationFrame = undefined;
+ const editorInstance = editor();
+ if (!editorInstance) return;
+
+ editorInstance.getEditorState().read(() => {
+ updateTextFormatFloatingToolbar(stateListOffsetRef);
+ });
+ });
+ });
+
createEffect(() => {
stateListOffsetRef = FindAndReplaceStore.get.listOffset;
- updateTextFormatFloatingToolbar(stateListOffsetRef);
+ update();
});
- onMount(() => {
- const scrollerElem = anchorElem.parentElement;
-
- const update = () => {
- if (stateListOffsetRef) {
- const editorInstance = editor();
- if (!editorInstance) return;
+ lazyRegister(editor, (editorInstance) =>
+ mergeRegister(
+ registerInternalLayoutShiftListener(editorInstance, update),
+ registerEditorWidthObserver(
+ editorInstance,
+ update,
+ '[data-block-content]'
+ ),
+ editorInstance.registerUpdateListener(
+ ({ dirtyElements, dirtyLeaves }) => {
+ if (dirtyElements.size === 0 && dirtyLeaves.size === 0) return;
+ update();
+ }
+ )
+ )
+ );
- editorInstance.getEditorState().read(() => {
- updateTextFormatFloatingToolbar(stateListOffsetRef);
- });
+ autoRegister(
+ registerEventListener(anchorElem.parentElement, 'scroll', update),
+ () => {
+ if (animationFrame !== undefined) {
+ cancelAnimationFrame(animationFrame);
}
- };
-
- window.addEventListener('resize', update);
- if (scrollerElem) {
- scrollerElem.addEventListener('scroll', update);
}
-
- onCleanup(() => {
- window.removeEventListener('resize', update);
- if (scrollerElem) {
- scrollerElem.removeEventListener('scroll', update);
- }
- });
- });
+ );
return null;
}
@@ -107,7 +145,6 @@ export function FloatingSearchHighlight({
}: {
anchorElem?: HTMLElement;
}) {
- // SCUFFED THEME: how should we define the highlight color?
return (
<Portal mount={anchorElem}>
<For each={FindAndReplaceStore.get.styles}>
@@ -117,8 +154,8 @@ export function FloatingSearchHighlight({
class={cn(
'z-150 m-0 text-transparent h-4.5 absolute top-0 left-0 opacity-50 pointer-events-none',
item.idx === FindAndReplaceStore.get.currentMatch + 1
- ? 'bg-[oklch(0.827_0.119_306.383)]'
- : 'bg-[oklch(0.827_0.119_306.383)]/50'
+ ? 'bg-accent'
+ : 'bg-accent/50'
)}
/>
)}
diff --git a/js/app/packages/core/component/LexicalMarkdown/plugins/shared/utils.ts b/js/app/packages/core/component/LexicalMarkdown/plugins/shared/utils.ts
index c3e8021f40..eb2d7500ec 100644
--- a/js/app/packages/core/component/LexicalMarkdown/plugins/shared/utils.ts
+++ b/js/app/packages/core/component/LexicalMarkdown/plugins/shared/utils.ts
@@ -90,6 +90,9 @@ export function registerEditorWidthObserver(
() => {
const editorEntry = observersByEditor.get(editor);
if (editorEntry) {
+ editorEntry.callbacks.delete(onWidthChange);
+ }
+ if (editorEntry && editorEntry.callbacks.size === 0) {
editorEntry.observer.disconnect();
observersByEditor.delete(editor);
}
diff --git a/js/app/packages/core/hotkey/tokens.ts b/js/app/packages/core/hotkey/tokens.ts
index 0ee40dce6c..dfbeb1a8bb 100644
--- a/js/app/packages/core/hotkey/tokens.ts
+++ b/js/app/packages/core/hotkey/tokens.ts
@@ -201,6 +201,7 @@ export const TOKENS = {
// markdown editor
md: {
+ find: 'md.find',
bold: 'md.bold',
italic: 'md.italic',
underline: 'md.underline',