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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
feat: add find count, restore focus after closing popups (#46)
Myles Scolnickfec055a50591
diff --git a/frontend/package.json b/frontend/package.jsonindex dd953e2426..76419e6200 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -49,6 +49,7 @@"@radix-ui/react-toggle": "^1.0.3","@radix-ui/react-tooltip": "^1.0.6","@radix-ui/react-use-controllable-state": "^1.0.1",+ "@react-aria/focus": "^3.14.0","@storybook/addon-styling": "^1.3.7","@tanstack/react-table": "^8.9.3","@textea/json-viewer": "^3.1.1",diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yamlindex 92fd8ccb7b..3e665a48db 100644--- a/frontend/pnpm-lock.yaml+++ b/frontend/pnpm-lock.yaml@@ -119,6 +119,9 @@ dependencies:'@radix-ui/react-use-controllable-state':specifier: ^1.0.1version: 1.0.1(@types/[email protected])([email protected])+ '@react-aria/focus':+ specifier: ^3.14.0+ version: 3.14.0([email protected])'@storybook/addon-styling':specifier: ^1.3.7version: 1.3.7(@types/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])@@ -4075,6 +4078,71 @@ packages:dependencies:'@babel/runtime': 7.22.5+ /@react-aria/[email protected]([email protected]):+ resolution: {integrity: sha512-Xw7PxLT0Cqcz22OVtTZ8+HvurDogn9/xntzoIbVjpRFWzhlYe5WHnZL+2+gIiKf7EZ18Ma9/QsCnrVnvrky/Kw==}+ peerDependencies:+ react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0+ dependencies:+ '@react-aria/interactions': 3.17.0([email protected])+ '@react-aria/utils': 3.19.0([email protected])+ '@react-types/shared': 3.19.0([email protected])+ '@swc/helpers': 0.5.1+ clsx: 1.2.1+ react: 18.2.0+ dev: false++ /@react-aria/[email protected]([email protected]):+ resolution: {integrity: sha512-v4BI5Nd8gi8s297fHpgjDDXOyufX+FPHJ31rkMwY6X1nR5gtI0+2jNOL4lh7s+cWzszpA0wpwIrKUPGhhLyUjQ==}+ peerDependencies:+ react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0+ dependencies:+ '@react-aria/ssr': 3.7.1([email protected])+ '@react-aria/utils': 3.19.0([email protected])+ '@react-types/shared': 3.19.0([email protected])+ '@swc/helpers': 0.5.1+ react: 18.2.0+ dev: false++ /@react-aria/[email protected]([email protected]):+ resolution: {integrity: sha512-ovVPSD1WlRpZHt7GI9DqJrWG3OIYS+NXQ9y5HIewMJpSe+jPQmMQfyRmgX4EnvmxSlp0u04Wg/7oItcoSIb/RA==}+ engines: {node: '>= 12'}+ peerDependencies:+ react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0+ dependencies:+ '@swc/helpers': 0.5.1+ react: 18.2.0+ dev: false++ /@react-aria/[email protected]([email protected]):+ resolution: {integrity: sha512-5GXqTCrUQtr78aiLVHZoeeGPuAxO4lCM+udWbKpSCh5xLfCZ7zFlZV9Q9FS0ea+IQypUcY8ngXCLsf22nSu/yg==}+ peerDependencies:+ react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0+ dependencies:+ '@react-aria/ssr': 3.7.1([email protected])+ '@react-stately/utils': 3.7.0([email protected])+ '@react-types/shared': 3.19.0([email protected])+ '@swc/helpers': 0.5.1+ clsx: 1.2.1+ react: 18.2.0+ dev: false++ /@react-stately/[email protected]([email protected]):+ resolution: {integrity: sha512-VbApRiUV2rhozOfk0Qj9xt0qjVbQfLTgAzXLdrfeZSBnyIgo1bFRnjDpnDZKZUUCeGQcJJI03I9niaUtY+kwJQ==}+ peerDependencies:+ react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0+ dependencies:+ '@swc/helpers': 0.5.1+ react: 18.2.0+ dev: false++ /@react-types/[email protected]([email protected]):+ resolution: {integrity: sha512-h852l8bWhqUxbXIG8vH3ab7gE19nnP3U1kuWf6SNSMvgmqjiRN9jXKPIFxF/PbfdvnXXm0yZSgSMWfUCARF0Cg==}+ peerDependencies:+ react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0+ dependencies:+ react: 18.2.0+ dev: false+/@rollup/[email protected]:resolution: {integrity: sha512-pTd9rIsP92h+B6wWwFbW8RkZv4hiR/xKsqre4SIuAOaOEQRxi0lqLke9k2/7WegC85GgUs9pjmOjCUi3In4vwA==}engines: {node: '>=14.0.0'}@@ -5258,6 +5326,12 @@ packages:'@swc/core-win32-x64-msvc': 1.3.62dev: true+ /@swc/[email protected]:+ resolution: {integrity: sha512-sJ902EfIzn1Fa+qYmjdQqh8tPsoxyBz+8yBKC2HKUxyezKJFwPGOn7pv4WY6QuQW//ySQi5lJjA/ZT9sNWWNTg==}+ dependencies:+ tslib: 2.5.0+ dev: false+resolution: {integrity: sha512-Ng9rdm3JPoSCi6cVZvANsYnF+UoGVRxflMb270tVj0+LjeT/ZtZ9ckxF6oLPLcKesza6VKBqtdF9mQ+vaz24Aw==}engines: {node: '>=12'}diff --git a/frontend/src/components/find-replace/find-replace.tsx b/frontend/src/components/find-replace/find-replace.tsxindex 5004c6806f..59dcf0ef9c 100644--- a/frontend/src/components/find-replace/find-replace.tsx+++ b/frontend/src/components/find-replace/find-replace.tsx@@ -4,10 +4,11 @@ import {openFindReplacePanel,} from "@/core/codemirror/find-replace/state";import { useAtom } from "jotai";-import React from "react";+import React, { useEffect, useState } from "react";import { Input } from "../ui/input";import { Button } from "../ui/button";import {+ getMatches,findNext,findPrev,replaceAll,@@ -23,10 +24,17 @@ import {XIcon,} from "lucide-react";import { useHotkey } from "@/hooks/useHotkey";+import { EditorView } from "codemirror";+import { FocusScope } from "@react-aria/focus";export const FindReplace: React.FC = () => {- const [isFocused, setIsFocused] = React.useState(false);+ const [isFocused, setIsFocused] = useState(false);const [state, dispatch] = useAtom(findReplaceAtom);+ const [matches, setMatches] = useState<{+ count: number;+ position: Map<EditorView, Map<string, number>>;+ }>();+useHotkey("cell.findAndReplace", () => {// if already open and focused, fallback to default behaviorif (isFocused && state.isOpen) {@@ -36,119 +44,159 @@ export const FindReplace: React.FC = () => {return openFindReplacePanel();});+ useEffect(() => {+ if (!state.isOpen) {+ return;+ }++ if (state.findText === "") {+ setMatches(undefined);+ return;+ }++ const matches = getMatches();+ // False count means an invalid regex+ setMatches(matches === false ? undefined : matches);+ }, [state.findText, state.isOpen]);+if (!state.isOpen) {return null;}+ const selection = state.currentView;+ const currentMatch =+ selection && matches+ ? matches.position+ .get(selection.view)+ ?.get(`${selection.range.from}:${selection.range.to}`)+ : undefined;+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 });- }}- />+ <FocusScope restoreFocus={true} autoFocus={true}>+ <div+ onFocus={() => setIsFocused(true)}+ onClick={(e) => {+ e.stopPropagation();+ e.preventDefault();+ }}+ 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 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 })+ <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 === ""}>- <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 })- }+ Replace Next+ </Button>+ <Button+ size="xs"+ variant="outline"+ className="h-6 text-xs"+ onClick={() => replaceAll()}+ disabled={state.findText === "" || state.replaceText === ""}>- <RegexIcon className="w-4 h-4" />- </Toggle>- </Tooltip>+ Replace All+ </Button>+ </div></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+ </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>- <Button- size="xs"- variant="outline"- className="h-6 text-xs"- onClick={() => replaceAll()}- disabled={state.findText === "" || state.replaceText === ""}- >- Replace All+ </Tooltip>+ <Tooltip content="Find Next">+ <Button size="xs" variant="secondary" onClick={() => findNext()}>+ <ArrowRightIcon className="w-4 h-4" /></Button>- </div>+ </Tooltip>+ {matches != null && currentMatch == null && (+ <span className="text-sm">{matches.count} matches</span>+ )}+ {matches != null && currentMatch != null && (+ <span className="text-sm">+ {currentMatch + 1} of {matches.count}+ </span>+ )}</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>+ </FocusScope>);};diff --git a/frontend/src/components/modal/ImperativeModal.tsx b/frontend/src/components/modal/ImperativeModal.tsxindex e789439e1f..7e25eeb002 100644--- a/frontend/src/components/modal/ImperativeModal.tsx+++ b/frontend/src/components/modal/ImperativeModal.tsx@@ -81,7 +81,9 @@ export function useImperativeModal() {<AlertDialogContent>{content}<AlertDialogFooter>- <AlertDialogAction onClick={closeModal}>Ok</AlertDialogAction>+ <AlertDialogAction autoFocus={true} onClick={closeModal}>+ Ok+ </AlertDialogAction></AlertDialogFooter></AlertDialogContent></AlertDialog>diff --git a/frontend/src/components/ui/alert-dialog.tsx b/frontend/src/components/ui/alert-dialog.tsxindex d931f06faf..74350cb805 100644--- a/frontend/src/components/ui/alert-dialog.tsx+++ b/frontend/src/components/ui/alert-dialog.tsx@@ -4,6 +4,7 @@ import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog";import { cn } from "@/lib/utils";import { buttonVariants } from "@/components/ui/button";+import { useRestoreFocus } from "./use-restore-focus";const AlertDialog = AlertDialogPrimitive.Root;@@ -40,19 +41,25 @@ AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName;const AlertDialogContent = React.forwardRef<React.ElementRef<typeof AlertDialogPrimitive.Content>,React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Content>->(({ className, ...props }, ref) => (- <AlertDialogPortal>- <AlertDialogOverlay />- <AlertDialogPrimitive.Content- ref={ref}- className={cn(- "fixed z-50 grid w-full max-w-lg scale-100 gap-4 border bg-background p-6 opacity-100 shadow-sm animate-in fade-in-90 slide-in-from-bottom-10 sm:rounded-lg sm:zoom-in-90 sm:slide-in-from-bottom-0 md:w-full",- className- )}- {...props}- />- </AlertDialogPortal>-));+>(({ className, ...props }, ref) => {+ // store the last focused element so we can restore it when the dialog closes+ const restoreFocus = useRestoreFocus();++ return (+ <AlertDialogPortal>+ <AlertDialogOverlay />+ <AlertDialogPrimitive.Content+ ref={ref}+ className={cn(+ "fixed z-50 grid w-full max-w-lg scale-100 gap-4 border bg-background p-6 opacity-100 shadow-sm animate-in fade-in-90 slide-in-from-bottom-10 sm:rounded-lg sm:zoom-in-90 sm:slide-in-from-bottom-0 md:w-full",+ className+ )}+ {...restoreFocus}+ {...props}+ />+ </AlertDialogPortal>+ );+});AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName;const AlertDialogHeader = ({diff --git a/frontend/src/components/ui/dialog.tsx b/frontend/src/components/ui/dialog.tsxindex 110347f809..72a1b77d38 100644--- a/frontend/src/components/ui/dialog.tsx+++ b/frontend/src/components/ui/dialog.tsx@@ -4,6 +4,7 @@ import * as DialogPrimitive from "@radix-ui/react-dialog";import { X } from "lucide-react";import { cn } from "@/lib/utils";+import { useRestoreFocus } from "./use-restore-focus";const Dialog = DialogPrimitive.Root;@@ -48,6 +49,9 @@ const DialogContent = React.forwardRef<typeof DialogPrimitive.Content>>(({ className, children, usePortal = true, ...props }, ref) => {+ // store the last focused element so we can restore it when the dialog closes+ const restoreFocus = useRestoreFocus();+const content = (<DialogPrimitive.Contentref={ref}@@ -55,6 +59,7 @@ const DialogContent = React.forwardRef<"fixed z-50 grid w-full gap-4 rounded-b-lg border bg-background p-6 shadow-sm animate-in data-[state=open]:fade-in-90 data-[state=open]:slide-in-from-bottom-10 sm:max-w-lg sm:rounded-lg sm:zoom-in-90 data-[state=open]:sm:slide-in-from-bottom-0",className)}+ {...restoreFocus}{...props}>{children}diff --git a/frontend/src/components/ui/use-restore-focus.ts b/frontend/src/components/ui/use-restore-focus.tsnew file mode 100644index 0000000000..01e90cb018--- /dev/null+++ b/frontend/src/components/ui/use-restore-focus.ts@@ -0,0 +1,24 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { useState } from "react";++/**+ * Hook to restore focus to the element that was focused before the current,+ * specifically for Radix Dialogs.+ */+export function useRestoreFocus() {+ // store the last focused element so we can restore it when the dialog closes+ const [lastFocused, setLastFocused] = useState<Element | null>(null);++ const onOpenAutoFocus = () => {+ setLastFocused(document.activeElement);+ };++ const onCloseAutoFocus = (evt: Event) => {+ if (lastFocused instanceof HTMLElement) {+ lastFocused.focus();+ }+ evt.preventDefault();+ };++ return { onOpenAutoFocus, onCloseAutoFocus };+}diff --git a/frontend/src/core/codemirror/find-replace/navigate.ts b/frontend/src/core/codemirror/find-replace/navigate.tsindex 241c05619b..76eaadf438 100644--- a/frontend/src/core/codemirror/find-replace/navigate.ts+++ b/frontend/src/core/codemirror/find-replace/navigate.ts@@ -195,3 +195,28 @@ export const replaceNext = searchCommand(({ query }) => {return false; // If no matches are found in any view, return false});++/**+ * @returns The number of matches in the document for each view.+ */+export const getMatches = searchCommand(({ query }) => {+ const views = getAllEditorViews();+ let count = 0;++ // Position in the document, keyed by view and then by to:from+ const position = new Map<EditorView, Map<string, number>>();+ for (const view of views) {+ const matches = query.matchAll(view.state, 1e9) || [];+ for (const match of matches) {+ const { from, to } = match;+ const viewPosition = position.get(view) || new Map<string, number>();+ viewPosition.set(`${from}:${to}`, count++);+ position.set(view, viewPosition);+ }+ }++ return {+ count: count,+ position: position,+ };+});diff --git a/frontend/src/css/App.css b/frontend/src/css/App.cssindex 79e0aaeaaf..f17dceca5d 100644--- a/frontend/src/css/App.css+++ b/frontend/src/css/App.css@@ -2,7 +2,7 @@@import url("./Cell.css");@import url("./md.css");@import url("./table.css");-@import url("./CodeMirrorSearchPanel.css");+@import url("./codemirror.css");/* stylelint-disable unit-allowed-list */diff --git a/frontend/src/css/CodeMirrorSearchPanel.css b/frontend/src/css/CodeMirrorSearchPanel.cssdeleted file mode 100644index b065737820..0000000000--- a/frontend/src/css/CodeMirrorSearchPanel.css+++ /dev/null@@ -1,67 +0,0 @@-.cm-editor .cm-panels.cm-panels-bottom {- border: 1px solid hsl(var(--input) / 20%);- background-color: hsl(var(--muted));- border-radius: 14px;- margin-bottom: 0.5rem;- width: fit-content;- margin-left: auto;- margin-right: auto;- box-shadow: var(--shadow-lg);-}--.cm-editor .cm-panel.cm-search {- font-family: var(--text-font);- padding: 1rem 2rem 1rem 1rem;-}--.cm-editor .cm-panel.cm-search input[type="checkbox"] {- vertical-align: middle;-}--.cm-editor .cm-panel.cm-search input.cm-textfield {- border-radius: 4px;- box-shadow: var(--shadow-xs-solid);- border: 1px solid transparent;- font-size: 0.75rem;-}--.cm-editor .cm-panel.cm-search input.cm-textfield:hover {- box-shadow: var(--shadow-sm-solid);-}--.cm-editor .cm-panel.cm-search input.cm-textfield:active,-.cm-editor .cm-panel.cm-search input.cm-textfield:focus,-.cm-editor .cm-panel.cm-search input.cm-textfield:focus-visible {- border: 1px solid hsl(var(--accent));- outline: none;-}--.cm-editor .cm-panel.cm-search label {- color: hsl(var(--muted-foreground));- font-size: 0.75rem;-}--.cm-editor .cm-panel.cm-search button:not([name="close"]) {- border-radius: calc(var(--radius) - 2px);- border-color: hsl(var(--input) / 80%);- box-shadow: var(--shadow-xs-solid);- background-color: hsl(var(--secondary));- background-image: none;- font-size: 0.75rem;-}--.cm-editor .cm-panel.cm-search button:hover:not([name="close"]),-.cm-editor .cm-panel.cm-search button:active:not([name="close"]),-.cm-editor .cm-panel.cm-search button:focus:not([name="close"]),-.cm-editor .cm-panel.cm-search button:focus-visible:not([name="close"]) {- background-color: hsl(var(--card));-}--.cm-editor .cm-panel.cm-search button:active {- box-shadow: var(--shadow-xs);-}--.cm-editor .cm-panel.cm-search [name="close"] {- font-size: 1rem;- margin-right: 0.25rem;-}diff --git a/frontend/src/css/codemirror.css b/frontend/src/css/codemirror.cssnew file mode 100644index 0000000000..4bfabb867e--- /dev/null+++ b/frontend/src/css/codemirror.css@@ -0,0 +1,6 @@+.cm-selectionBackground {+ /* This is the background for selected text when focused,+ but we want to use it when not in focus either because we+ will often lose focus during find/replace or in another editor */+ background-color: #d7d4f0 !important;+}