Repository navigation
feat(code-mirror-search): add replace and replace-all with search position, debouncing and tests - #8585
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughThe CodeMirror search component was refactored into reusable utilities. Search, replace, highlighting, keyboard interactions, editor integration, read-only behavior, styling, and unit and end-to-end coverage were expanded. ChangesSearch and Replace
Estimated code review effort: 4 (Complex) | ~60 minutes Possibly related PRs
Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/bruno-app/src/components/FileEditor/CodeEditor/index.js (1)
97-110: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Cmd-H/Ctrl-Hshould match the new replace flow. These bindings still map to CodeMirror’s built-in'replace'command, whileCmd-Alt-F/Ctrl-Alt-FuseopenReplace(). Align them withpackages/bruno-app/src/components/CodeEditor/index.js.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/bruno-app/src/components/FileEditor/CodeEditor/index.js` around lines 97 - 110, Update the Cmd-H and Ctrl-H keybindings in the CodeEditor component to use the same replace flow as Cmd-Alt-F and Ctrl-Alt-F: honor readOnly, show the search bar, focus searchBarRef, and call openReplace(). Match the implementation used by the other CodeEditor component instead of mapping these keys to CodeMirror’s built-in replace command.
🧹 Nitpick comments (2)
tests/code-editor/search-replace.spec.ts (2)
31-31: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winHardcoded
waitForTimeout(50)after setting editor content.Consider waiting on an observable signal (e.g. an updated match count or exposed doc-version testid) instead of a fixed sleep, to avoid flakiness under CI load.
As per path instructions: "Try to reduce usage of page.waitForTimeout(); in code unless absolutely necessary and the locator cannot be found using existing expect() playwright calls."
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tests/code-editor/search-replace.spec.ts` at line 31, Replace the fixed page.waitForTimeout(50) after setting editor content with an observable Playwright wait, such as an expect assertion on the updated match count or exposed document-version testid. Reuse an existing locator and wait for the editor update to complete before continuing the test.Source: Path instructions
104-361: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winNo
test.stepusage across the suite.None of the ~20 tests use
test.stepto break down arrange/act/assert phases, even though most have a clear multi-step shape (e.g. Lines 167-176, 308-321).As per path instructions: "Promote the use of
test.stepas much as possible so the generated reports are easier to read."🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tests/code-editor/search-replace.spec.ts` around lines 104 - 361, Organize the multi-phase tests in the search/replace suite with test.step blocks for setup, actions, and assertions, prioritizing flows such as “reopening restores previous search text...” and “match count updates when the document is edited while search is open.” Apply the same structure across the suite where steps are clearly separable, using descriptive step names while preserving the existing test behavior and assertions.Source: Path instructions
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/bruno-app/src/components/CodeMirrorSearch/index.js`:
- Around line 369-377: Add accessible names to the regex, case-sensitive, and
whole-word toggle buttons in CodeMirrorSearch by adding descriptive aria-label
or title attributes, matching the naming behavior of the neighboring
prev/next/close buttons.
In `@tests/code-editor/search-replace.spec.ts`:
- Around line 18-79: Move the locators and interactions used by
openScriptEditor, setEditorContent, resetSearchOptions, openSearchBar,
openReplaceBar, and closeSearchBar into the appropriate page module under
tests/utils/page/*. Update the spec helpers to call those page-module actions,
keeping expectMatchCount’s assertion in the spec while obtaining its locator
through the page module; ensure actions synchronize with waits and do not call
expect.
---
Outside diff comments:
In `@packages/bruno-app/src/components/FileEditor/CodeEditor/index.js`:
- Around line 97-110: Update the Cmd-H and Ctrl-H keybindings in the CodeEditor
component to use the same replace flow as Cmd-Alt-F and Ctrl-Alt-F: honor
readOnly, show the search bar, focus searchBarRef, and call openReplace(). Match
the implementation used by the other CodeEditor component instead of mapping
these keys to CodeMirror’s built-in replace command.
---
Nitpick comments:
In `@tests/code-editor/search-replace.spec.ts`:
- Line 31: Replace the fixed page.waitForTimeout(50) after setting editor
content with an observable Playwright wait, such as an expect assertion on the
updated match count or exposed document-version testid. Reuse an existing
locator and wait for the editor update to complete before continuing the test.
- Around line 104-361: Organize the multi-phase tests in the search/replace
suite with test.step blocks for setup, actions, and assertions, prioritizing
flows such as “reopening restores previous search text...” and “match count
updates when the document is edited while search is open.” Apply the same
structure across the suite where steps are clearly separable, using descriptive
step names while preserving the existing test behavior and assertions.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 2fe01ac7-53c3-49db-ad44-d325dd347ba1
📒 Files selected for processing (12)
packages/bruno-app/src/components/CodeEditor/index.jspackages/bruno-app/src/components/CodeMirrorSearch/CodeMirrorSearch.spec.jsxpackages/bruno-app/src/components/CodeMirrorSearch/StyledWrapper.jspackages/bruno-app/src/components/CodeMirrorSearch/index.jspackages/bruno-app/src/components/CodeMirrorSearch/markingUtils.jspackages/bruno-app/src/components/CodeMirrorSearch/replaceUtils.jspackages/bruno-app/src/components/CodeMirrorSearch/replaceUtils.spec.jspackages/bruno-app/src/components/CodeMirrorSearch/searchUtils.jspackages/bruno-app/src/components/CodeMirrorSearch/searchUtils.spec.jspackages/bruno-app/src/components/Documentation/index.jspackages/bruno-app/src/components/FileEditor/CodeEditor/index.jstests/code-editor/search-replace.spec.ts
| <ToolHint text="Regex search" toolhintId="searchbar-regex-toolhint" place="top"> | ||
| <button type="button" className={`searchbar-icon-btn ${regex ? 'active' : ''}`} onClick={handleToggleRegex} data-testid="search-regex-btn"><IconRegex size={16} /></button> | ||
| </ToolHint> | ||
| <ToolHint text="Case sensitive" toolhintId="searchbar-case-toolhint" place="top"> | ||
| <button type="button" className={`searchbar-icon-btn ${caseSensitive ? 'active' : ''}`} onClick={handleToggleCase} data-testid="search-case-btn"><IconLetterCase size={14} /></button> | ||
| </ToolHint> | ||
| <ToolHint text="Whole word" toolhintId="searchbar-wholeword-toolhint" place="top"> | ||
| <button type="button" className={`searchbar-icon-btn ${wholeWord ? 'active' : ''}`} onClick={handleToggleWholeWord} data-testid="search-wholeword-btn"><IconLetterW size={14} /></button> | ||
| </ToolHint> |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Add accessible names to the toggle buttons.
prev/next/close carry title, but the regex, case-sensitive, and whole-word buttons have neither title nor aria-label, so screen readers announce them without a name. Add aria-label (or title) to match the sibling buttons.
♿ Proposed fix
- <button type="button" className={`searchbar-icon-btn ${regex ? 'active' : ''}`} onClick={handleToggleRegex} data-testid="search-regex-btn"><IconRegex size={16} /></button>
+ <button type="button" aria-label="Regex search" className={`searchbar-icon-btn ${regex ? 'active' : ''}`} onClick={handleToggleRegex} data-testid="search-regex-btn"><IconRegex size={16} /></button>(apply the same for the case-sensitive and whole-word buttons)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@packages/bruno-app/src/components/CodeMirrorSearch/index.js` around lines 369
- 377, Add accessible names to the regex, case-sensitive, and whole-word toggle
buttons in CodeMirrorSearch by adding descriptive aria-label or title
attributes, matching the naming behavior of the neighboring prev/next/close
buttons.
bdd553a to
384e59c
Compare
…ition, debouncing and tests
384e59c to
5ea98c9
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
packages/bruno-app/src/components/CodeMirrorSearch/replaceUtils.spec.js (1)
78-86: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winCover a match that spans a newline.
This test uses two single-line matches, leaving the
to.lineoffset path untested.Proposed test
+ it('replaces a match spanning multiple lines', () => { + const editor = makeEditor('foo\nbar'); + const matches = [ + { from: { line: 0, ch: 1 }, to: { line: 1, ch: 2 } } + ]; + + replaceAll(editor, matches, 'X'); + + expect(editor.replaceRange.mock.calls[0][0]).toBe('fXr'); + });As per coding guidelines, “Cover both the happy path and the realistically problematic paths.”
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/bruno-app/src/components/CodeMirrorSearch/replaceUtils.spec.js` around lines 78 - 86, Extend the replacement test around replaceAll to use a single match whose from and to positions span different lines, exercising the to.line offset calculation. Assert that replaceRange receives the expected multiline replacement while preserving the existing single-line replacement coverage.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/bruno-app/src/components/CodeMirrorSearch/index.js`:
- Around line 50-57: Reset searchCacheKey.current in the empty-text branch
alongside searchMatches.current and the other search state resets. This ensures
re-entering the same term with the same docVersion performs a fresh search
instead of reusing the cleared cache.
---
Nitpick comments:
In `@packages/bruno-app/src/components/CodeMirrorSearch/replaceUtils.spec.js`:
- Around line 78-86: Extend the replacement test around replaceAll to use a
single match whose from and to positions span different lines, exercising the
to.line offset calculation. Assert that replaceRange receives the expected
multiline replacement while preserving the existing single-line replacement
coverage.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: da099788-ab95-4896-8b3f-c359438be1db
📒 Files selected for processing (12)
packages/bruno-app/src/components/CodeEditor/index.jspackages/bruno-app/src/components/CodeMirrorSearch/CodeMirrorSearch.spec.jsxpackages/bruno-app/src/components/CodeMirrorSearch/StyledWrapper.jspackages/bruno-app/src/components/CodeMirrorSearch/index.jspackages/bruno-app/src/components/CodeMirrorSearch/markingUtils.jspackages/bruno-app/src/components/CodeMirrorSearch/replaceUtils.jspackages/bruno-app/src/components/CodeMirrorSearch/replaceUtils.spec.jspackages/bruno-app/src/components/CodeMirrorSearch/searchUtils.jspackages/bruno-app/src/components/CodeMirrorSearch/searchUtils.spec.jspackages/bruno-app/src/components/Documentation/index.jspackages/bruno-app/src/components/FileEditor/CodeEditor/index.jstests/code-editor/search-replace.spec.ts
🚧 Files skipped from review as they are similar to previous changes (8)
- packages/bruno-app/src/components/Documentation/index.js
- packages/bruno-app/src/components/CodeMirrorSearch/CodeMirrorSearch.spec.jsx
- packages/bruno-app/src/components/FileEditor/CodeEditor/index.js
- packages/bruno-app/src/components/CodeMirrorSearch/StyledWrapper.js
- packages/bruno-app/src/components/CodeMirrorSearch/markingUtils.js
- packages/bruno-app/src/components/CodeMirrorSearch/searchUtils.spec.js
- packages/bruno-app/src/components/CodeEditor/index.js
- tests/code-editor/search-replace.spec.ts
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/bruno-app/src/components/CodeMirrorSearch/index.js`:
- Around line 283-293: Update handleNext and handlePrev in the CodeMirror search
component so navigation is blocked while the current query differs from
debouncedSearchText, preventing stale searchMatches.current results from being
used. Ensure pressing Enter after editing either searches the current input
immediately or otherwise waits until both query values match before navigating.
- Around line 196-207: Update the useEffect handling initialIndexRef so a
pending initial search that no longer matches debouncedSearchText is cleared,
allowing subsequent searches to enter the normal cursor-based doSearch path.
Preserve the existing indexed search and cleanup when forText matches.
In `@packages/bruno-app/src/components/CodeMirrorSearch/searchUtils.js`:
- Line 1: Update MAX_MATCHES and the match-producing logic used by
handleReplaceAll so replaceAll never receives a truncated list; either scan and
collect all matches for replacement or detect truncation and block Replace all
with the existing appropriate failure behavior. Preserve the cap for ordinary
search results if needed, but ensure handleReplaceAll can distinguish complete
results from capped results.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 0aadb618-8bb6-4b6c-9f17-b1b84cf7fd92
📒 Files selected for processing (12)
packages/bruno-app/src/components/CodeEditor/index.jspackages/bruno-app/src/components/CodeMirrorSearch/CodeMirrorSearch.spec.jsxpackages/bruno-app/src/components/CodeMirrorSearch/StyledWrapper.jspackages/bruno-app/src/components/CodeMirrorSearch/index.jspackages/bruno-app/src/components/CodeMirrorSearch/markingUtils.jspackages/bruno-app/src/components/CodeMirrorSearch/replaceUtils.jspackages/bruno-app/src/components/CodeMirrorSearch/replaceUtils.spec.jspackages/bruno-app/src/components/CodeMirrorSearch/searchUtils.jspackages/bruno-app/src/components/CodeMirrorSearch/searchUtils.spec.jspackages/bruno-app/src/components/Documentation/index.jspackages/bruno-app/src/components/FileEditor/CodeEditor/index.jstests/code-editor/search-replace.spec.ts
🚧 Files skipped from review as they are similar to previous changes (10)
- packages/bruno-app/src/components/CodeMirrorSearch/replaceUtils.js
- packages/bruno-app/src/components/Documentation/index.js
- packages/bruno-app/src/components/CodeMirrorSearch/searchUtils.spec.js
- packages/bruno-app/src/components/CodeMirrorSearch/CodeMirrorSearch.spec.jsx
- packages/bruno-app/src/components/CodeMirrorSearch/StyledWrapper.js
- packages/bruno-app/src/components/CodeMirrorSearch/replaceUtils.spec.js
- tests/code-editor/search-replace.spec.ts
- packages/bruno-app/src/components/CodeMirrorSearch/markingUtils.js
- packages/bruno-app/src/components/FileEditor/CodeEditor/index.js
- packages/bruno-app/src/components/CodeEditor/index.js
There was a problem hiding this comment.
🧹 Nitpick comments (1)
tests/utils/page/code-editor-search.ts (1)
50-50: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider replacing
page.waitForTimeout().As per path instructions, try to reduce the usage of
page.waitForTimeout()unless absolutely necessary. If you are just waiting for the editor DOM to reflect the newly set value, consider waiting for a specific locator state to keep the tests robust and snappy!🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tests/utils/page/code-editor-search.ts` at line 50, Replace the fixed delay after setting the editor value with an explicit wait for the relevant editor DOM locator state in the surrounding search test. Use the existing locator and an assertion or state condition that confirms the newly set value is reflected before continuing, and remove the page.waitForTimeout call.Source: Path instructions
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@tests/utils/page/code-editor-search.ts`:
- Line 50: Replace the fixed delay after setting the editor value with an
explicit wait for the relevant editor DOM locator state in the surrounding
search test. Use the existing locator and an assertion or state condition that
confirms the newly set value is reflected before continuing, and remove the
page.waitForTimeout call.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 03f3433f-b37c-414c-9da2-51636f8cd4b3
📒 Files selected for processing (5)
packages/bruno-app/src/components/CodeMirrorSearch/index.jspackages/bruno-app/src/components/CodeMirrorSearch/searchUtils.jstests/code-editor/search-replace.spec.tstests/utils/page/code-editor-search.tstests/utils/page/index.ts
🚧 Files skipped from review as they are similar to previous changes (3)
- packages/bruno-app/src/components/CodeMirrorSearch/searchUtils.js
- tests/code-editor/search-replace.spec.ts
- packages/bruno-app/src/components/CodeMirrorSearch/index.js
| this.searchBarRef.current?.openReplace(); | ||
| }); | ||
| }, | ||
| 'Ctrl-Alt-F': this.props.readOnly ? false : () => { |
There was a problem hiding this comment.
The actions for (Cmd+F or Ctrl+F), (Cmd+H or Ctrl+H), and (Cmd+Alt+F) or (Ctrl+Alt+F) have the same function implementation. Can we extract these into methods which takes in the cm instance and runs something. Helps us not drift the implementation across two bindings when some logic changes.
There was a problem hiding this comment.
Yes sure good idea. created a util and used it from there
| 'Esc': () => { | ||
| if (this.state.searchBarVisible) { | ||
| this.setState({ searchBarVisible: false }); | ||
| this.searchBarRef.current?.close(); |
There was a problem hiding this comment.
Do we need the null/undefined check here with ?? Isn't it always available when the searchBarVisible is true?
There was a problem hiding this comment.
Yes it will be there but since we don't have typescript currently here its added for safety. Also ?. costs nothing at runtime and protects against any edge case where the ref hasn't been committed yet
| const marks = []; | ||
| return { | ||
| getSearchCursor: jest.fn(() => { | ||
| let i = -1; |
There was a problem hiding this comment.
This is a doubt that I have. Maybe I am wrong here. Doesn't invoking getSearchCursor again reset the value of i to -1? Should we have it outside the getSearchCursor method? This is just to ensure that the state remains stable. Let me know if I am wrong here and my assumptions are a little off.
There was a problem hiding this comment.
actually this is the correct behavior, since each getSearchCursor call should represent an independent cursor scan from the top of the document.
|
|
||
| it('renders search input when visible', () => { | ||
| renderSearch(); | ||
| expect(screen.getByPlaceholderText('Search...')).toBeInTheDocument(); |
There was a problem hiding this comment.
Placeholders are fine, but is it better to have data-testid? Maybe useful for later E2E tests? Same for every other place we are doing a DOM search via placeholders and text.
There was a problem hiding this comment.
using the test ids now
| describe('result count', () => { | ||
| it('shows "0 results" when search is empty', () => { | ||
| renderSearch(); | ||
| expect(screen.getByText('0 results')).toBeInTheDocument(); |
There was a problem hiding this comment.
Can this test be more precise. For whatever reason, if we have a text saying "0 results" in our editor instance, this will fail. This is not a case in this specific test but can be an issue if the test evolves. Maybe we can target the specific text label which shows the results.
| ]; | ||
| renderSearch({ editor: makeMockEditor(matches) }); | ||
| typeSearch('test'); | ||
| expect(screen.getByText('1 / 3')).toBeInTheDocument(); |
There was a problem hiding this comment.
Same here, maybe we can do a more targeted search than to depend on the screen instance. Let me know your thoughts.
There was a problem hiding this comment.
using the test ids now for these assertions.
| describe('imperative handle', () => { | ||
| it('focus() focuses the search input', () => { | ||
| const ref = createRef(); | ||
| renderSearch({}, ref); |
There was a problem hiding this comment.
Am I missing something here? renderSearch renders the CodeMirror instance. But onFocus, why is the search bar appearing? Is this because of some property in makeMockEditor?
There was a problem hiding this comment.
When the parent opens the search bar (sets visible={true}), it also needs to move keyboard focus into the search input so the user can start typing immediately. It does that by calling ref.current.focus().
So the test is for: calling focus() on the ref moves focus to the search input
Description
JIRA
Curently users can only search a text in codemirror. There is no option to replace the selected text.
Adding replace and replace all feature in code mirror. Users can select a text for search and can replace the selected text by replace one-by-one or replace all. Adding the keyboard shortcuts for opening the serach and replace.
Screen.Recording.2026-06-16.at.3.39.41.PM.mov
CodeMirrorSearch/index.js
Replace functionality
replaceTextstate andreplaceVisibletogglehandleReplace— replaces the current match viaeditor.replaceRange, invalidates the search cache, and re-runs search at the same indexhandleReplaceAll— replaces all matches in reverse order (to preserve character positions) insideeditor.operation()for a single undo stepLayout
IconChevronRight) extracted as a full-height left column — spans both rows when expanded, matching VS Code's widget.toggle-replace-btn+.search-replace-rows(column of.search-row/.replace-row)IconReplaceandIconArrowsExchange2withToolHinttooltipsKeyboard & focus
keydownlistener attached in the capture phase ({ capture: true }) on the container — ensuresEscapeis intercepted before CodeMirror or the browser can act on ittype="button"added to all buttons for correct focusabilityImperative handle — exposes four methods via
useImperativeHandle:focus()setSearch(text)openReplace()close()onCloseCodeMirrorSearch/StyledWrapper.js
flex-direction: row— chevron column on the left, rows column on the right.toggle-replace-btnusesalign-self: stretchfor full-heightborderbox, fixed180pxwidth — both rows visually identical.search-rowgets aborder-bottomonly when replace is expanded.searchbar-text-btnstyles (replaced by icon buttons)CodeEditor/index.js
Cmd/Ctrl+H— replaced'replace'string command with a handler that opens the search bar and callssearchBarRef.current?.openReplace()Cmd/Ctrl+F— updated to checkcm.getSelection():setSearch(selectedText)to prefill and re-run search (works whether bar is open or closed)focus()to move cursor to the input without clearing existing search textEscextraKey — updated from baresetStatetosearchBarRef.current?.close()so marks are properly cleaned up when Esc is pressed while the editor has focusPerformance Improvements
1. Only highlight what's visible
The search still finds all matches in the document, but it only creates highlights (
markText()) for matches that are currently visible in the editor (plus a small buffer of ±100 lines). The currently selected match is always highlighted, even if it's outside the viewport.For example, in a 10,000-line file with 500 matches, the editor typically creates only 5–10 highlights instead of 500, significantly reducing DOM work. As you scroll, old highlights are removed and new ones are drawn for the visible area.
Files
components/CodeMirrorSearch/markingUtils.js2. Cache search results
Scanning the entire document with CodeMirror's
getSearchCursor()can be expensive on large files.Search results are cached and reused until something that affects the results changes:
This means actions like Next, Previous, scrolling, or component re-renders reuse the existing match list instead of rescanning the document every time.
Files
components/CodeMirrorSearch/searchUtils.js(createCacheKey)components/CodeMirrorSearch/index.js(searchCacheKey,isCacheHit)3. Debounce search while typing
Instead of performing a full document scan on every keystroke, the search waits until the user stops typing for 250 ms before running.
Typing stays responsive because intermediate keystrokes only update the input field without triggering an expensive search.
Files
components/CodeMirrorSearch/index.js(useDebounce(searchText, 250))4. Jump directly to visible matches
When drawing highlights, the code uses a binary search to quickly locate the first match inside the current viewport instead of checking every match from the beginning.
This reduces the work from scanning the entire match list to only processing the matches that are actually visible.
Files
components/CodeMirrorSearch/markingUtils.js5. Limit extremely large searches
To avoid freezing the UI on pathological searches (for example, searching for a single character in a very large minified file), the search stops after 99,999 matches.
This provides a reasonable safety limit while still supporting very large result sets.
Files
components/CodeMirrorSearch/searchUtils.js(MAX_MATCHES)6. Scroll only when it makes sense
Searching no longer automatically scrolls the editor every time results are updated.
The editor scrolls only when explicitly requested, such as:
It does not scroll during:
This prevents the editor from unexpectedly jumping away from the user's current position.
Files
components/CodeMirrorSearch/index.js(doSearch(..., shouldScroll = false))Contribution Checklist:
Note: Keeping the PR small and focused helps make it easier to review and merge. If you have multiple changes you want to make, please consider submitting them as separate pull requests.
Publishing to New Package Managers
Please see here for more information.
Summary by CodeRabbit