Persistent search panel across document changes

Hello!

Given the following scenario:

  1. User views document 1
  2. User does Ctrl+F and searches for “abcd”
  3. User switches to document 2

I would like the search panel to remain open with the content of “abcd”.

From what I understand, the best practice when switching documents is to create a new State from scratch.

    const newState = EditorState.create({
      doc: content,
      extensions,
      selection: EditorSelection.single(from, to),
    });

    const isSearchOpen = searchPanelOpen(oldState);
    const searchQuery = getSearchQuery(oldState);

    _view.setState(newState);

    if (isSearchOpen) {
      openSearchPanel(_view);

      const transaction = _view.state.update({
        effects: [setSearchQuery.of(searchQuery)],
      });

      _view.dispatch(transaction);
    }

This works, but because we call openSearchPanel, the search panel takes focus (which is not what I want in this case). I would like the focus to remain unchanged.

Alternatively, I could call view.dispatch to update my document instead of creating a new state. This would keep the search panel/state persistent. The problem is that the undo history does not get cleared.

Any ideas on the best way to achieve this?

Came up with this to restore focus after calling openSearchPanel.

const activeElement = document.activeElement;

openSearchPanel(_view);

if (activeElement instanceof HTMLElement) {
  activeElement.focus();
}

I’m open to an alternative if there’s a more codemirror specific solution :slight_smile: