Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

feat: global find replace (#43)

Myles Scolnick4b90a44f6056
diff --git a/frontend/package.json b/frontend/package.json
index 04ca527a12..dd953e2426 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -46,6 +46,7 @@
"@radix-ui/react-switch": "^1.0.3",
"@radix-ui/react-tabs": "^1.0.4",
"@radix-ui/react-toast": "^1.1.4",
+ "@radix-ui/react-toggle": "^1.0.3",
"@radix-ui/react-tooltip": "^1.0.6",
"@radix-ui/react-use-controllable-state": "^1.0.1",
"@storybook/addon-styling": "^1.3.7",
diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml
index 9a6a6fabee..92fd8ccb7b 100644
--- a/frontend/pnpm-lock.yaml
+++ b/frontend/pnpm-lock.yaml
@@ -110,6 +110,9 @@ dependencies:
'@radix-ui/react-toast':
specifier: ^1.1.4
+ '@radix-ui/react-toggle':
+ specifier: ^1.0.3
'@radix-ui/react-tooltip':
specifier: ^1.0.6
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index b2754076a5..7a4125e57e 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -273,7 +273,9 @@ export const App: React.FC<AppProps> = ({
// HOTKEYS
useHotkey("global.runStale", runStaleCells);
useHotkey("global.save", saveOrNameNotebook);
- useHotkey("global.interrupt", sendInterrupt);
+ useHotkey("global.interrupt", () => {
+ sendInterrupt();
+ });
useHotkey("global.hideCode", () => {
if (isReading) {
return;
diff --git a/frontend/src/components/find-replace/find-replace.tsx b/frontend/src/components/find-replace/find-replace.tsx
new file mode 100644
index 0000000000..5004c6806f
--- /dev/null
+++ b/frontend/src/components/find-replace/find-replace.tsx
@@ -0,0 +1,154 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import {
+ findReplaceAtom,
+ openFindReplacePanel,
+} from "@/core/codemirror/find-replace/state";
+import { useAtom } from "jotai";
+import React from "react";
+import { Input } from "../ui/input";
+import { Button } from "../ui/button";
+import {
+ findNext,
+ findPrev,
+ replaceAll,
+ replaceNext,
+} from "@/core/codemirror/find-replace/navigate";
+import { Toggle } from "../ui/toggle";
+import { Tooltip } from "../ui/tooltip";
+import {
+ ArrowLeftIcon,
+ ArrowRightIcon,
+ CaseSensitiveIcon,
+ RegexIcon,
+ XIcon,
+} from "lucide-react";
+import { useHotkey } from "@/hooks/useHotkey";
+
+export const FindReplace: React.FC = () => {
+ const [isFocused, setIsFocused] = React.useState(false);
+ const [state, dispatch] = useAtom(findReplaceAtom);
+ useHotkey("cell.findAndReplace", () => {
+ // if already open and focused, fallback to default behavior
+ if (isFocused && state.isOpen) {
+ return false;
+ }
+
+ return openFindReplacePanel();
+ });
+
+ if (!state.isOpen) {
+ return null;
+ }
+
+ return (
+ <div
+ onFocus={() => setIsFocused(true)}
+ onBlur={() => setIsFocused(false)}
+ className="fixed top-0 right-0 w-[500px] flex flex-col bg-[var(--sage-1)] p-4 z-50 mt-2 mr-3 rounded-md shadow-lg border gap-2"
+ onKeyDown={(e) => {
+ if (e.key === "Escape") {
+ dispatch({ type: "setIsOpen", isOpen: false });
+ }
+ }}
+ >
+ <div className="absolute top-0 right-0">
+ <Button
+ onClick={() => dispatch({ type: "setIsOpen", isOpen: false })}
+ size="xs"
+ variant="text"
+ >
+ <XIcon className="w-4 h-4" />
+ </Button>
+ </div>
+ <div className="flex items-center gap-3">
+ <div className="flex flex-col flex-2 gap-2 w-[55%]">
+ <Input
+ value={state.findText}
+ autoFocus={true}
+ className="mr-2 mb-0"
+ placeholder="Find"
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ if (e.shiftKey) {
+ findPrev();
+ } else {
+ findNext();
+ }
+ }
+ }}
+ onChange={(e) => {
+ dispatch({ type: "setFind", find: e.target.value });
+ }}
+ />
+ <Input
+ value={state.replaceText}
+ placeholder="Replace"
+ onChange={(e) => {
+ dispatch({ type: "setReplace", replace: e.target.value });
+ }}
+ />
+ </div>
+ <div className="flex flex-col gap-2">
+ <div className="flex items-center gap-[2px]">
+ <Tooltip content="Case Sensitive">
+ <Toggle
+ size="sm"
+ pressed={state.caseSensitive}
+ data-state={state.caseSensitive ? "on" : "off"}
+ onPressedChange={(pressed) =>
+ dispatch({ type: "setCaseSensitive", caseSensitive: pressed })
+ }
+ >
+ <CaseSensitiveIcon className="w-4 h-4" />
+ </Toggle>
+ </Tooltip>
+ <Tooltip content="Use Regular Expression">
+ <Toggle
+ size="sm"
+ pressed={state.regexp}
+ data-state={state.regexp ? "on" : "off"}
+ onPressedChange={(pressed) =>
+ dispatch({ type: "setRegex", regexp: pressed })
+ }
+ >
+ <RegexIcon className="w-4 h-4" />
+ </Toggle>
+ </Tooltip>
+ </div>
+ <div className="flex items-center gap-[2px]">
+ <Button
+ size="xs"
+ variant="outline"
+ className="h-6 text-xs"
+ onClick={() => replaceNext()}
+ disabled={state.findText === "" || state.replaceText === ""}
+ >
+ Replace Next
+ </Button>
+ <Button
+ size="xs"
+ variant="outline"
+ className="h-6 text-xs"
+ onClick={() => replaceAll()}
+ disabled={state.findText === "" || state.replaceText === ""}
+ >
+ Replace All
+ </Button>
+ </div>
+ </div>
+ </div>
+ <div className="flex items-center gap-2">
+ <Tooltip content="Find Previous">
+ <Button size="xs" variant="secondary" onClick={() => findPrev()}>
+ <ArrowLeftIcon className="w-4 h-4" />
+ </Button>
+ </Tooltip>
+ <Tooltip content="Find Next">
+ <Button size="xs" variant="secondary" onClick={() => findNext()}>
+ <ArrowRightIcon className="w-4 h-4" />
+ </Button>
+ </Tooltip>
+ </div>
+ </div>
+ );
+};
diff --git a/frontend/src/components/ui/button.tsx b/frontend/src/components/ui/button.tsx
index 41a96e3028..9af1ccd4af 100644
--- a/frontend/src/components/ui/button.tsx
+++ b/frontend/src/components/ui/button.tsx
@@ -53,6 +53,7 @@ const buttonVariants = cva(
"border border-input shadow-smSolid",
activeCommon
),
+ text: cn("opacity-60 hover:opacity-100", "active:opacity-100"),
ghost: cn(
"hover:bg-accent/90 hover:text-accent-foreground hover:shadow-smSolid border border-transparent",
activeCommon,
diff --git a/frontend/src/components/ui/toggle.tsx b/frontend/src/components/ui/toggle.tsx
new file mode 100644
index 0000000000..af911f6afc
--- /dev/null
+++ b/frontend/src/components/ui/toggle.tsx
@@ -0,0 +1,47 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import * as React from "react";
+import * as TogglePrimitive from "@radix-ui/react-toggle";
+import { cva, type VariantProps } from "class-variance-authority";
+
+import { cn } from "@/lib/utils";
+
+const toggleVariants = cva(
+ cn(
+ "inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",
+ "data-[state=on]:bg-muted data-[state=on]:text-muted-foreground"
+ ),
+ {
+ variants: {
+ variant: {
+ default: "bg-transparent",
+ outline:
+ "border border-input bg-transparent hover:bg-muted hover:text-muted-foreground",
+ },
+ size: {
+ default: "h-9 px-3",
+ sm: "h-6 px-2",
+ lg: "h-10 px-5",
+ },
+ },
+ defaultVariants: {
+ variant: "default",
+ size: "default",
+ },
+ }
+);
+
+const Toggle = React.forwardRef<
+ React.ElementRef<typeof TogglePrimitive.Root>,
+ React.ComponentPropsWithoutRef<typeof TogglePrimitive.Root> &
+ VariantProps<typeof toggleVariants>
+>(({ className, variant, size, ...props }, ref) => (
+ <TogglePrimitive.Root
+ ref={ref}
+ className={cn(toggleVariants({ variant, size, className }))}
+ {...props}
+ />
+));
+
+Toggle.displayName = TogglePrimitive.Root.displayName;
+
+export { Toggle, toggleVariants };
diff --git a/frontend/src/core/codemirror/cm.ts b/frontend/src/core/codemirror/cm.ts
index e8fb8a76a7..994eb6dc46 100644
--- a/frontend/src/core/codemirror/cm.ts
+++ b/frontend/src/core/codemirror/cm.ts
@@ -42,18 +42,15 @@ import {
tooltips,
EditorView,
} from "@codemirror/view";
-import {
- closeSearchPanel,
- openSearchPanel,
- highlightSelectionMatches,
-} from "@codemirror/search";
+
import { EditorState, Extension } from "@codemirror/state";
import { oneDark } from "@codemirror/theme-one-dark";
import { CompletionConfig } from "../config";
import { Theme } from "../../theme/useTheme";
-import { HOTKEYS } from "@/core/hotkeys/hotkeys";
+
import { completer } from "@/core/codemirror/completion/completer";
+import { findReplaceBundle } from "./find-replace/extension";
// Customize python to support folding some additional syntax nodes
const customizedPython = pythonLanguage.configure({
@@ -103,7 +100,6 @@ export const setup = (
closeBrackets(),
rectangularSelection(),
highlightActiveLine(),
- highlightSelectionMatches(),
keymap.of([
{
key: "Tab",
@@ -131,21 +127,7 @@ export const setup = (
},
},
]),
- keymap.of([
- {
- key: HOTKEYS.getHotkey("cell.findAndReplace").key,
- preventDefault: true,
- run: openSearchPanel,
- },
- ]),
- keymap.of([
- {
- key: "Escape",
- preventDefault: true,
- run: closeSearchPanel,
- scope: "editor search-panel",
- },
- ]),
+ findReplaceBundle(),
new LanguageSupport(customizedPython, [
customizedPython.data.of({ autocomplete: localCompletionSource }),
customizedPython.data.of({ autocomplete: globalCompletion }),
diff --git a/frontend/src/core/codemirror/find-replace/extension.ts b/frontend/src/core/codemirror/find-replace/extension.ts
new file mode 100644
index 0000000000..f60b63ad52
--- /dev/null
+++ b/frontend/src/core/codemirror/find-replace/extension.ts
@@ -0,0 +1,31 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import { HOTKEYS } from "@/core/hotkeys/hotkeys";
+import {
+ highlightSelectionMatches,
+ selectNextOccurrence,
+} from "@codemirror/search";
+import { keymap } from "@codemirror/view";
+import { closeFindReplacePanel, openFindReplacePanel } from "./state";
+
+export function findReplaceBundle() {
+ return [
+ keymap.of([
+ {
+ key: "Escape",
+ preventDefault: true,
+ run: closeFindReplacePanel,
+ },
+ {
+ key: HOTKEYS.getHotkey("cell.selectNextOccurrence").key,
+ preventDefault: true,
+ run: selectNextOccurrence,
+ },
+ {
+ key: HOTKEYS.getHotkey("cell.findAndReplace").key,
+ preventDefault: true,
+ run: openFindReplacePanel,
+ },
+ ]),
+ highlightSelectionMatches(),
+ ];
+}
diff --git a/frontend/src/core/codemirror/find-replace/navigate.ts b/frontend/src/core/codemirror/find-replace/navigate.ts
new file mode 100644
index 0000000000..241c05619b
--- /dev/null
+++ b/frontend/src/core/codemirror/find-replace/navigate.ts
@@ -0,0 +1,197 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import { store } from "@/core/state/jotai";
+import { SearchCursor, SearchQuery } from "@codemirror/search";
+import { EditorSelection, EditorState } from "@codemirror/state";
+import { EditorView } from "codemirror";
+import { findReplaceAtom } from "./state";
+import { getAllEditorViews } from "@/core/state/cells";
+
+type SearchResult = typeof SearchCursor.prototype.value;
+
+// Copied from https://github.com/codemirror/search/blob/6.5.2/src/search.ts#L164
+interface QueryType<Result extends SearchResult = SearchResult> {
+ nextMatch(state: EditorState, curFrom: number, curTo: number): Result | null;
+ prevMatch(state: EditorState, curFrom: number, curTo: number): Result | null;
+ getReplacement(result: Result): string;
+ matchAll(state: EditorState, limit: number): readonly Result[] | null;
+ highlight(
+ state: EditorState,
+ from: number,
+ to: number,
+ add: (from: number, to: number) => void
+ ): void;
+}
+
+interface QueryCreator {
+ create(): QueryType;
+}
+
+function searchCommand<T>(f: (state: { query: QueryType }) => T) {
+ return () => {
+ const state = store.get(findReplaceAtom);
+ const search = new SearchQuery({
+ search: state.findText,
+ caseSensitive: state.caseSensitive,
+ regexp: state.regexp,
+ replace: state.replaceText,
+ wholeWord: state.wholeWord,
+ });
+ return search.valid
+ ? f({ query: (search as unknown as QueryCreator).create() })
+ : false;
+ };
+}
+
+/**
+ * Move the selection to the first match (next or previous) after the global selection.
+ * Will wrap around to the start of the document when it reaches the end.
+ *
+ * This is a modified version of the original findNext/findPrev function,
+ * that searches through all views, instead of just the current one.
+ */
+const findInDirection = (direction: "next" | "prev") =>
+ searchCommand(({ query }) => {
+ const views = getAllEditorViews();
+ // Get starting view from the store
+ const currentView = store.get(findReplaceAtom).currentView || {
+ view: views[0],
+ range: { from: 0, to: 0 },
+ };
+
+ let startingPosition: number | null = currentView.range.to;
+
+ // We are going backwards so update the starting position and views to search
+ if (direction === "prev") {
+ views.reverse();
+ startingPosition = currentView.range.from;
+ }
+
+ let startingViewIndex = views.indexOf(currentView.view);
+ if (startingViewIndex < 0) {
+ startingViewIndex = 0;
+ }
+
+ const viewsToSearch = [...views, ...views].slice(startingViewIndex);
+
+ for (const view of viewsToSearch) {
+ const next =
+ direction === "next"
+ ? query.nextMatch(view.state, 0, startingPosition ?? 0)
+ : query.prevMatch(
+ view.state,
+ startingPosition ?? view.state.doc.length,
+ view.state.doc.length
+ );
+
+ if (!next) {
+ startingPosition = null; // Unset the starting position
+ // If no match found in this view, continue to the next one
+ // and remove the selection
+ view.dispatch({
+ selection: EditorSelection.single(0),
+ });
+ continue;
+ }
+
+ // Set selection
+ const selection = EditorSelection.single(next.from, next.to);
+ view.dispatch({
+ selection,
+ effects: [EditorView.scrollIntoView(selection.main, { y: "center" })],
+ userEvent: "select.search",
+ });
+ store.set(findReplaceAtom, {
+ type: "setCurrentView",
+ view,
+ range: { from: next.from, to: next.to },
+ });
+
+ return next; // If a match is found, stop searching and return true
+ }
+
+ return false; // If no matches are found in any view, return false
+ });
+
+/**
+ * Find the next match after the global selection.
+ */
+export const findNext = findInDirection("next");
+/**
+ * Find the previous match before the global selection.
+ */
+export const findPrev = findInDirection("prev");
+
+/**
+ * Replace the next match after the global selection.
+ */
+export const replaceAll = searchCommand(({ query }) => {
+ const views = getAllEditorViews();
+ for (const view of views) {
+ if (view.state.readOnly) {
+ continue;
+ }
+
+ const changes = query.matchAll(view.state, 1e9)?.map((match) => {
+ const { from, to } = match;
+ return { from, to, insert: query.getReplacement(match) };
+ });
+
+ if (changes && changes.length === 0) {
+ continue;
+ }
+
+ view.dispatch({
+ changes,
+ userEvent: "input.replace.all",
+ });
+ }
+
+ return true;
+});
+
+/**
+ * Replace the next match after the global selection.
+ */
+export const replaceNext = searchCommand(({ query }) => {
+ const views = getAllEditorViews();
+ // Get starting view from the store
+ const currentView = store.get(findReplaceAtom).currentView || {
+ view: views[0],
+ range: { from: 0, to: 0 },
+ };
+
+ // Start from the start of the selection to include the current match
+ let startingPosition: number | null = currentView.range.from;
+
+ let startingViewIndex = views.indexOf(currentView.view);
+ if (startingViewIndex < 0) {
+ startingViewIndex = 0;
+ }
+ const viewsToSearch = [...views, ...views].slice(startingViewIndex);
+
+ for (const view of viewsToSearch) {
+ const next = query.nextMatch(view.state, 0, startingPosition ?? 0);
+
+ if (!next) {
+ startingPosition = null; // Unset the starting position
+ // If no match found in this view, continue to the next one
+ // and remove the selection
+ view.dispatch({
+ selection: EditorSelection.single(0),
+ });
+ continue;
+ }
+
+ // Replace the match
+ const replacement = view.state.toText(query.getReplacement(next));
+ view.dispatch({
+ changes: [{ from: next.from, to: next.to, insert: replacement }],
+ userEvent: "input.replace",
+ });
+
+ // Find next match
+ return findNext();
+ }
+
+ return false; // If no matches are found in any view, return false
+});
diff --git a/frontend/src/core/codemirror/find-replace/state.ts b/frontend/src/core/codemirror/find-replace/state.ts
new file mode 100644
index 0000000000..7cc3d084f2
--- /dev/null
+++ b/frontend/src/core/codemirror/find-replace/state.ts
@@ -0,0 +1,154 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import { store } from "@/core/state/jotai";
+import { EditorView } from "codemirror";
+import { atomWithReducer } from "jotai/utils";
+
+interface FindReplaceState {
+ findText: string;
+ replaceText: string;
+ caseSensitive: boolean;
+ wholeWord: boolean;
+ regexp: boolean;
+ isOpen: boolean;
+ currentView?: {
+ view: EditorView;
+ range: { from: number; to: number };
+ };
+}
+
+type Action =
+ | {
+ type: "setFind";
+ find: string;
+ }
+ | {
+ type: "setReplace";
+ replace: string;
+ }
+ | {
+ type: "setCaseSensitive";
+ caseSensitive: boolean;
+ }
+ | {
+ type: "setWholeWord";
+ wholeWord: boolean;
+ }
+ | {
+ type: "setRegex";
+ regexp: boolean;
+ }
+ | {
+ type: "setIsOpen";
+ isOpen: boolean;
+ }
+ | {
+ type: "setCurrentView";
+ view: EditorView;
+ range: { from: number; to: number };
+ }
+ | {
+ type: "clearCurrentView";
+ };
+
+export const findReplaceAtom = atomWithReducer<FindReplaceState, Action>(
+ {
+ findText: "",
+ replaceText: "",
+ caseSensitive: false,
+ wholeWord: false,
+ regexp: false,
+ isOpen: false,
+ currentView: undefined,
+ },
+ (state, action) => {
+ if (action === undefined) {
+ return state;
+ }
+
+ switch (action.type) {
+ case "setFind":
+ return { ...state, findText: action.find };
+ case "setReplace":
+ return { ...state, replaceText: action.replace };
+ case "setCaseSensitive":
+ return { ...state, caseSensitive: action.caseSensitive };
+ case "setWholeWord":
+ return { ...state, wholeWord: action.wholeWord };
+ case "setRegex":
+ return { ...state, regexp: action.regexp };
+ case "setIsOpen":
+ return { ...state, isOpen: action.isOpen };
+ case "setCurrentView":
+ return {
+ ...state,
+ currentView: { view: action.view, range: action.range },
+ };
+ case "clearCurrentView":
+ return { ...state, currentView: undefined };
+ }
+ }
+);
+
+export function openFindReplacePanel(initialView?: EditorView): boolean {
+ if (initialView) {
+ // Set the selected text and focus
+ const selection = initialView.state.selection.main;
+ const query = initialView.state.sliceDoc(selection.from, selection.to);
+ if (query) {
+ store.set(findReplaceAtom, {
+ type: "setFind",
+ find: query,
+ });
+ store.set(findReplaceAtom, {
+ type: "setCurrentView",
+ view: initialView,
+ range: { from: selection.from, to: selection.to },
+ });
+ } else {
+ // If there is no selection, just set the current view
+ store.set(findReplaceAtom, {
+ type: "setCurrentView",
+ view: initialView,
+ range: { from: 0, to: 0 },
+ });
+ }
+ }
+
+ // HACK: If open, close it and re-open it to gain focus
+ const isOpen = store.get(findReplaceAtom).isOpen;
+ if (isOpen) {
+ store.set(findReplaceAtom, {
+ type: "setIsOpen",
+ isOpen: false,
+ });
+ requestAnimationFrame(() => {
+ // Open the panel
+ store.set(findReplaceAtom, {
+ type: "setIsOpen",
+ isOpen: true,
+ });
+ });
+ return true;
+ }
+
+ // Open the panel
+ store.set(findReplaceAtom, {
+ type: "setIsOpen",
+ isOpen: true,
+ });
+ return true;
+}
+
+export function closeFindReplacePanel(): boolean {
+ const isOpen = store.get(findReplaceAtom).isOpen;
+ // If the panel is already closed, return false.
+ if (!isOpen) {
+ return false;
+ }
+
+ store.set(findReplaceAtom, {
+ type: "setIsOpen",
+ isOpen: false,
+ });
+ return true;
+}
diff --git a/frontend/src/core/hotkeys/hotkeys.ts b/frontend/src/core/hotkeys/hotkeys.ts
index 5061911b54..8cac952a1e 100644
--- a/frontend/src/core/hotkeys/hotkeys.ts
+++ b/frontend/src/core/hotkeys/hotkeys.ts
@@ -127,6 +127,11 @@ const DEFAULT_HOT_KEY = {
group: "Editing",
key: "Mod-f",
},
+ "cell.selectNextOccurrence": {
+ name: "Select next occurrence",
+ group: "Editing",
+ key: "Mod-d",
+ },
"cell.fold": {
name: "Fold",
group: "Editing",
diff --git a/frontend/src/core/state/cells.ts b/frontend/src/core/state/cells.ts
index 66f6b9f014..09147ef38f 100644
--- a/frontend/src/core/state/cells.ts
+++ b/frontend/src/core/state/cells.ts
@@ -11,6 +11,7 @@ import {
import { arrayMove } from "@dnd-kit/sortable";
import { CellId } from "../model/ids";
import { prepareCellForExecution, transitionCell } from "./cell";
+import { store } from "./jotai";
/* The array of cells on the page, together with a history of
* deleted cells to implement an "undo delete" action
@@ -467,6 +468,13 @@ const cellsAtom = atom<CellsAndHistory>(initialCellState());
export const useCells = () => useAtomValue(cellsAtom);
+export const getAllEditorViews = () => {
+ const cells = store.get(cellsAtom).present;
+ return cells
+ .map((cell) => cell.ref.current?.editorView)
+ .flatMap((x) => (x ? [x] : []));
+};
+
/**
* Use this hook to dispatch cell actions. This hook will not cause a re-render
* when cells change.
diff --git a/frontend/src/core/state/jotai.ts b/frontend/src/core/state/jotai.ts
new file mode 100644
index 0000000000..80fa804a4e
--- /dev/null
+++ b/frontend/src/core/state/jotai.ts
@@ -0,0 +1,7 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import { createStore } from "jotai";
+
+/**
+ * Global store allows getting and setting global state outside of React components.
+ */
+export const store = createStore();
diff --git a/frontend/src/editor/Controls.tsx b/frontend/src/editor/Controls.tsx
index c97ada96ee..80e0c8642a 100644
--- a/frontend/src/editor/Controls.tsx
+++ b/frontend/src/editor/Controls.tsx
@@ -19,6 +19,7 @@ import { renderShortcut } from "../components/shortcuts/renderShortcut";
import { useCellActions } from "../core/state/cells";
import { AppConfigButton } from "../components/app-config/app-config-button";
import { useState, useEffect } from "react";
+import { FindReplace } from "@/components/find-replace/find-replace";
interface ControlsProps {
filename: string | null;
@@ -77,7 +78,9 @@ export const Controls = ({
return (
<>
- {closed ? null : (
+ {!presenting && <FindReplace />}
+
+ {!closed && (
<div className={styles.topRightControls}>
<AppConfigButton />
<ShutdownButton onShutdown={onShutdown} />
diff --git a/frontend/src/hooks/useHotkey.ts b/frontend/src/hooks/useHotkey.ts
index 64c5a1a95d..949a011c13 100644
--- a/frontend/src/hooks/useHotkey.ts
+++ b/frontend/src/hooks/useHotkey.ts
@@ -11,8 +11,12 @@ import { HOTKEYS, HotkeyAction } from "@/core/hotkeys/hotkeys";
* Registers a hotkey listener for the given shortcut.
*
* @param callback The callback to run when the shortcut is pressed. It does not need to be memoized as this hook will always use the latest callback.
+ * If the callback returns false, preventDefault will not be called on the event.
*/
-export function useHotkey(shortcut: HotkeyAction, callback: () => void) {
+export function useHotkey(
+ shortcut: HotkeyAction,
+ callback: () => boolean | void | undefined
+) {
const { registerAction, unregisterAction } = useSetRegisteredAction();
const memoizeCallback = useEvent(() => callback());
@@ -20,8 +24,11 @@ export function useHotkey(shortcut: HotkeyAction, callback: () => void) {
const listener = useEvent((e: KeyboardEvent) => {
const key = HOTKEYS.getHotkey(shortcut).key;
if (parseShortcut(key)(e)) {
- e.preventDefault();
- callback();
+ const response = callback();
+ // Prevent default if the callback does not return false
+ if (response !== false) {
+ e.preventDefault();
+ }
}
});
diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx
index e4ca92b354..efebea612e 100644
--- a/frontend/src/main.tsx
+++ b/frontend/src/main.tsx
@@ -9,6 +9,7 @@ import { getInitialAppMode } from "./core/mode";
import { Logger } from "./utils/Logger";
import { reportVitals } from "./utils/vitals";
import { Provider } from "jotai";
+import { store } from "./core/state/jotai";
/**
* Main entry point for the Marimo app.
@@ -36,7 +37,7 @@ try {
const initialMode = getInitialAppMode();
root.render(
<React.StrictMode>
- <Provider>
+ <Provider store={store}>
<ThemeProvider>
<MarimoApp initialMode={initialMode} />
</ThemeProvider>