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: documentation panel (#591)
Myles Scolnicka3adf8f564d9
diff --git a/frontend/src/components/editor/Cell.tsx b/frontend/src/components/editor/Cell.tsxindex 756726030f..32756cb208 100644--- a/frontend/src/components/editor/Cell.tsx+++ b/frontend/src/components/editor/Cell.tsx@@ -13,7 +13,6 @@ import {import { saveCellConfig, sendRun, sendStdin } from "@/core/network/requests";import { autocompletionKeymap } from "@/core/codemirror/cm";-import { clearTooltips } from "@/core/codemirror/completion/hints";import { UserConfig } from "../../core/config/config-schema";import { CellConfig, CellData, CellRuntimeState } from "../../core/cells/types";import { CellActions } from "../../core/cells/cells";@@ -213,7 +212,6 @@ const CellComponent = (editorView.current !== null) {closeCompletion(editorView.current);- clearTooltips(editorView.current);}}, []);diff --git a/frontend/src/components/editor/chrome/panels/documentation-panel.css b/frontend/src/components/editor/chrome/panels/documentation-panel.cssnew file mode 100644index 0000000000..029356f181--- /dev/null+++ b/frontend/src/components/editor/chrome/panels/documentation-panel.css@@ -0,0 +1,6 @@+.docs-panel pre,+code {+ white-space: break-spaces;+ font-size: 0.875rem;+ line-height: 150%;+}diff --git a/frontend/src/components/editor/chrome/panels/documentation-panel.tsx b/frontend/src/components/editor/chrome/panels/documentation-panel.tsxnew file mode 100644index 0000000000..ba1e14d55d--- /dev/null+++ b/frontend/src/components/editor/chrome/panels/documentation-panel.tsx@@ -0,0 +1,28 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { documentationAtom } from "@/core/documentation/state";+import { renderHTML } from "@/plugins/core/RenderHTML";+import { useAtomValue } from "jotai";+import React from "react";+import "./documentation-panel.css";+import { BookMarkedIcon } from "lucide-react";++export const DocumentationPanel: React.FC = () => {+ const { documentation } = useAtomValue(documentationAtom);++ if (!documentation) {+ return (+ <div className="mx-6 my-6 flex flex-row gap-2 items-center rounded-lg">+ <BookMarkedIcon className="text-accent-foreground" />+ <span className="mt-[0.25rem] text-accent-foreground">+ No documentation+ </span>+ </div>+ );+ }++ return (+ <div className="p-4 overflow-y-auto overflow-x-hidden h-full docs-panel flex flex-col gap-6">+ {renderHTML({ html: documentation })}+ </div>+ );+};diff --git a/frontend/src/components/editor/chrome/types.ts b/frontend/src/components/editor/chrome/types.tsindex ce51ae334b..647ba477da 100644--- a/frontend/src/components/editor/chrome/types.ts+++ b/frontend/src/components/editor/chrome/types.ts@@ -4,4 +4,5 @@ export type PanelType =| "variables"| "outline"| "dependencies"+ | "documentation"| "logs";diff --git a/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx b/frontend/src/components/editor/chrome/wrapper/app-chrome.tsxindex 773f231779..32660d923d 100644--- a/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx+++ b/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx@@ -18,6 +18,7 @@ import { OutlinePanel } from "../panels/outline-panel";import { DependencyGraphPanel } from "@/components/editor/chrome/panels/dependency-graph-panel";import { VariablePanel } from "../panels/variable-panel";import { LogsPanel } from "../panels/logs-panel";+import { DocumentationPanel } from "../panels/documentation-panel";export const AppChrome: React.FC<PropsWithChildren> = ({ children }) => {const { isOpen, selectedPanel, panelLocation } = useChromeState();@@ -89,6 +90,7 @@ export const AppChrome: React.FC<PropsWithChildren> = ({ children }) => {{selectedPanel === "variables" && <VariablePanel />}{selectedPanel === "dependencies" && <DependencyGraphPanel />}{selectedPanel === "outline" && <OutlinePanel />}+ {selectedPanel === "documentation" && <DocumentationPanel />}{selectedPanel === "logs" && <LogsPanel />}</div>);diff --git a/frontend/src/components/editor/chrome/wrapper/footer.tsx b/frontend/src/components/editor/chrome/wrapper/footer.tsxindex 2e255413b7..2c387c5990 100644--- a/frontend/src/components/editor/chrome/wrapper/footer.tsx+++ b/frontend/src/components/editor/chrome/wrapper/footer.tsx@@ -9,6 +9,7 @@ import {NetworkIcon,FileTextIcon,MessageCircleQuestionIcon,+ BookMarkedIcon,} from "lucide-react";import { cn } from "@/utils/cn";import { useChromeActions, useChromeState } from "../state";@@ -57,6 +58,13 @@ export const Footer: React.FC = () => {><ScrollTextIcon className={cn("h-5 w-5")} /></FooterItem>+ <FooterItem+ tooltip="View documentation"+ selected={selectedPanel === "documentation"}+ onClick={() => openApplication("documentation")}+ >+ <BookMarkedIcon className={cn("h-5 w-5")} />+ </FooterItem><FooterItemtooltip="Notebook logs"selected={selectedPanel === "logs"}diff --git a/frontend/src/core/codemirror/__tests__/__snapshots__/setup.test.ts.snap b/frontend/src/core/codemirror/__tests__/__snapshots__/setup.test.ts.snapindex 598f45f9b6..9f3aa804a7 100644--- a/frontend/src/core/codemirror/__tests__/__snapshots__/setup.test.ts.snap+++ b/frontend/src/core/codemirror/__tests__/__snapshots__/setup.test.ts.snap@@ -39,10 +39,6 @@ exports[`snapshot all duplicate keymaps > default keymaps 2`] = `},],"Backspace": [- {- "key": "Backspace",- "run": "run",- },{"key": "Backspace","run": "deleteBracketPair",@@ -64,10 +60,6 @@ exports[`snapshot all duplicate keymaps > default keymaps 2`] = `},],"Escape": [- {- "key": "Escape",- "run": "clearTooltips",- },{"key": "Escape","run": "closeCompletion",@@ -163,10 +155,6 @@ exports[`snapshot all duplicate keymaps > vim keymaps 2`] = `},],"Backspace": [- {- "key": "Backspace",- "run": "run",- },{"key": "Backspace","run": "deleteBracketPair",@@ -188,10 +176,6 @@ exports[`snapshot all duplicate keymaps > vim keymaps 2`] = `},],"Escape": [- {- "key": "Escape",- "run": "clearTooltips",- },{"key": "Escape","run": "closeCompletion",diff --git a/frontend/src/core/codemirror/__tests__/setup.test.ts b/frontend/src/core/codemirror/__tests__/setup.test.tsindex e7f04957be..c2e177327e 100644--- a/frontend/src/core/codemirror/__tests__/setup.test.ts+++ b/frontend/src/core/codemirror/__tests__/setup.test.ts@@ -89,7 +89,7 @@ describe("snapshot all duplicate keymaps", () => {);// Total duplicates:// if this changes, please make sure to validate they are not conflicting- expect(Object.values(duplicates).flat().length).toMatchInlineSnapshot(`22`);+ expect(Object.values(duplicates).flat().length).toMatchInlineSnapshot(`20`);expect(duplicates).toMatchSnapshot();});@@ -102,7 +102,7 @@ describe("snapshot all duplicate keymaps", () => {);// Total duplicates:// if this changes, please make sure to validate they are not conflicting- expect(Object.values(duplicates).flat().length).toMatchInlineSnapshot(`21`);+ expect(Object.values(duplicates).flat().length).toMatchInlineSnapshot(`19`);expect(duplicates).toMatchSnapshot();});});diff --git a/frontend/src/core/codemirror/cells/extensions.ts b/frontend/src/core/codemirror/cells/extensions.tsindex 4a2497e635..fae6da3821 100644--- a/frontend/src/core/codemirror/cells/extensions.ts+++ b/frontend/src/core/codemirror/cells/extensions.ts@@ -7,7 +7,6 @@ import { formatKeymapExtension } from "../extensions";import { CellActions } from "@/core/cells/cells";import { getEditorCodeAsPython } from "../language/utils";import { formattingChangeEffect } from "../format";-import { clearTooltips } from "../completion/hints";import { closeCompletion } from "@codemirror/autocomplete";export interface MovementCallbacks@@ -204,7 +203,6 @@ export function cellMovementBundle(run: (ev) => {const isHidden = toggleHideCode();closeCompletion(ev);- clearTooltips(ev);// If we are newly hidden, blur the editorif (isHidden) {ev.contentDOM.blur();diff --git a/frontend/src/core/codemirror/completion/Autocompleter.ts b/frontend/src/core/codemirror/completion/Autocompleter.tsindex 4f2d844cb4..c63ea9851a 100644--- a/frontend/src/core/codemirror/completion/Autocompleter.ts+++ b/frontend/src/core/codemirror/completion/Autocompleter.ts@@ -75,7 +75,7 @@ export const Autocompleter = {limitToType?: "tooltip";excludeTypes?: string[];exactName?: string;- }): Tooltip | undefined {+ }): (Tooltip & { html?: string }) | undefined {const firstOption = getFirstOption(message.options, exactName);if (!firstOption) {return undefined;@@ -97,6 +97,7 @@ export const Autocompleter = {return {pos: from,+ html: firstOption.completion_info,end: from + firstOption.name.length,above: true,create: () => ({ dom, resize: false }),diff --git a/frontend/src/core/codemirror/completion/completer.ts b/frontend/src/core/codemirror/completion/completer.tsindex 6617ce5041..41eefb746b 100644--- a/frontend/src/core/codemirror/completion/completer.ts+++ b/frontend/src/core/codemirror/completion/completer.ts@@ -4,8 +4,8 @@ import { CompletionContext, CompletionResult } from "@codemirror/autocomplete";import { AUTOCOMPLETER, Autocompleter } from "./Autocompleter";import { Logger } from "../../../utils/Logger";import { CellId, HTMLCellId } from "@/core/cells/ids";-import { getCellEditorView } from "@/core/cells/cells";-import { dispatchShowTooltip } from "./hints";+import { store } from "@/core/state/jotai";+import { documentationAtom } from "@/core/documentation/state";export async function completer(context: CompletionContext@@ -39,10 +39,10 @@ export async function completer(message: result,limitToType: "tooltip",});- // Find EditorView for the cell- const editorView = getCellEditorView(cellId);- if (editorView) {- dispatchShowTooltip(editorView, tooltip);+ if (tooltip) {+ store.set(documentationAtom, {+ documentation: tooltip.html ?? null,+ });}if (tooltip) {return null;diff --git a/frontend/src/core/codemirror/completion/hints.ts b/frontend/src/core/codemirror/completion/hints.tsindex 2d23235cd6..10ed849d30 100644--- a/frontend/src/core/codemirror/completion/hints.ts+++ b/frontend/src/core/codemirror/completion/hints.ts@@ -1,134 +1,61 @@/* Copyright 2024 Marimo. All rights reserved. */import { HTMLCellId } from "@/core/cells/ids";-import {- EditorView,- Tooltip,- hasHoverTooltips,- hoverTooltip,- keymap,- showTooltip,-} from "@codemirror/view";+import { EditorView, hoverTooltip } from "@codemirror/view";import { AUTOCOMPLETER, Autocompleter } from "./Autocompleter";import { Logger } from "@/utils/Logger";-import { StateField, StateEffect, Prec, Text } from "@codemirror/state";+import { EditorState, Text } from "@codemirror/state";+import { debounce } from "lodash-es";+import { documentationAtom } from "@/core/documentation/state";+import { store } from "@/core/state/jotai";export function hintTooltip() {return [hoverTooltip(async (view, pos) => {- const cellContainer = HTMLCellId.findElement(view.dom);- if (!cellContainer) {- Logger.error("Failed to find active cell.");+ const result = await requestDocumentation(view, pos, ["tooltip"]);+ if (result === null || result === "cancelled") {return null;}-- const cellId = HTMLCellId.parse(cellContainer.id);-- const { startToken, endToken } = getPositionAtWordBounds(- view.state.doc,- pos- );-- const result = await AUTOCOMPLETER.request({- document: view.state.doc.slice(0, endToken).toString(), // convert Text to string- cellId: cellId,- });- if (!result) {- return null;- }-- const fullWord = view.state.doc.slice(startToken, endToken).toString();- const tooltip = Autocompleter.asHoverTooltip({- position: endToken,- message: result,- exactName: fullWord,- excludeTypes: ["tooltip"],- });- return tooltip ?? null;+ return result;},- {- hideOnChange: true,- }- ),- Prec.highest(- keymap.of([- {- key: "Escape",- run: clearTooltips,- },- ])+ { hideOnChange: true }),- Prec.highest(- keymap.of([- {- key: "Backspace",- run: (view) => {- clearTooltips(view);- return false; // don't stop propagation- },- },- ])- ),- // Removing tooltips (and completion) on blur is handled by cell editor, so- // that text is selectable+ cursorPositionDocumentation,];}-/**- * Dispatch an effect that shows a tooltip- */-export function dispatchShowTooltip(+async function requestDocumentation(view: EditorView,- tooltip: Tooltip | undefined-): void {- view.dispatch({- effects: TooltipFromCompletionApi.of([tooltip].filter(Boolean)),- });-}--export function clearTooltips(view: EditorView): boolean {- // We stopped showing cursorTooltipField- // const hasCompletionTooltip = view.state.field(cursorTooltipField).length > 0;- // if (hasCompletionTooltip) {- // view.dispatch({- // effects: TooltipFromCompletionApi.of([]),- // });- // return true;- // }- return false;-}--// Effect that dispatches a tooltip-const TooltipFromCompletionApi = StateEffect.define<Tooltip[]>();+ pos: number,+ excludeTypes?: string[]+) {+ const cellContainer = HTMLCellId.findElement(view.dom);+ if (!cellContainer) {+ Logger.error("Failed to find active cell.");+ return null;+ }-// Field that stores the current tooltips-export const cursorTooltipField = StateField.define<Tooltip[]>({- create: () => {- return [];- },- update(tooltips, tr) {- // If the effect is a tooltip, return it- for (const effect of tr.effects) {- if (effect.is(TooltipFromCompletionApi)) {- return effect.value;- }- }+ const cellId = HTMLCellId.parse(cellContainer.id);- // Hide if hover tooltips are enabled- if (hasHoverTooltips(tr.state)) {- return [];- }+ const { startToken, endToken } = getPositionAtWordBounds(view.state.doc, pos);- // Otherwise, return the current tooltips- return tooltips;- },+ const result = await AUTOCOMPLETER.request({+ document: view.state.doc.slice(0, endToken).toString(), // convert Text to string+ cellId: cellId,+ });+ if (!result) {+ return "cancelled" as const;+ }- provide: (field) => {- return showTooltip.computeN([field], (state) => {- return state.field(field);- });- },-});+ const fullWord = view.state.doc.slice(startToken, endToken).toString();+ const tooltip = Autocompleter.asHoverTooltip({+ position: endToken,+ message: result,+ exactName: fullWord,+ excludeTypes: excludeTypes,+ });+ return tooltip ?? null;+}export function getPositionAtWordBounds(doc: Text, pos: number) {let startToken = pos;@@ -156,3 +83,33 @@ export function getPositionAtWordBounds(doc: Text, pos: number) {return { startToken, endToken };}++// Checks if the cursor is in a text element+function isCursorInText(state: EditorState) {+ const { head } = state.selection.main;+ const text = state.doc.sliceString(head - 1, head);+ return /\w/.test(text);+}++// Debounce the request to avoid spamming the server+const debouncedAutocomplete = debounce(+ async (view: EditorView, position: number) => {+ const tooltip = await requestDocumentation(view, position);+ // If cancelled, don't update the documentation+ if (tooltip === "cancelled") {+ return;+ }+ store.set(documentationAtom, {+ documentation: tooltip?.html ?? null,+ });+ },+ 300+);++// Listen to cursor movement and send documentation requests+const cursorPositionDocumentation = EditorView.updateListener.of((update) => {+ if (update.selectionSet && isCursorInText(update.state)) {+ const cursorPos = update.state.selection.main.head;+ debouncedAutocomplete(update.view, cursorPos);+ }+});diff --git a/frontend/src/core/documentation/state.ts b/frontend/src/core/documentation/state.tsnew file mode 100644index 0000000000..d0a7d07a38--- /dev/null+++ b/frontend/src/core/documentation/state.ts@@ -0,0 +1,13 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { atom } from "jotai";++interface DocumentationState {+ documentation: string | null;+}++/**+ * Stores the last seen function documentation+ */+export const documentationAtom = atom<DocumentationState>({+ documentation: null,+});diff --git a/frontend/src/css/App.css b/frontend/src/css/App.cssindex a52e3e61e1..1dbc2374e3 100644--- a/frontend/src/css/App.css+++ b/frontend/src/css/App.css@@ -22,7 +22,7 @@ html {--content-width: 740px;--monospace-font: "Fira Mono";--text-font: "PT Sans", sans-serif;- --heading-font: Lora, serif;+ --heading-font: "Lora", serif;}#App {diff --git a/marimo/_runtime/complete.py b/marimo/_runtime/complete.pyindex 57e86baf2a..5b79e7b039 100644--- a/marimo/_runtime/complete.py+++ b/marimo/_runtime/complete.py@@ -218,6 +218,29 @@ def complete(# Don't complete ...completions = []+ # Get docstring in function context. A bit of a hack, since+ # this isn't actually a completion, just a tooltip.+ #+ # If no completions, we might be getting a signature ...+ # for example, if the document is "mo.ui.slider(start=1,+ signatures = script.get_signatures()+ if signatures:+ _write_completion_result(+ stream=stream,+ completion_id=request.completion_id,+ prefix_length=0,+ options=[+ CompletionOption(+ name=signatures[0].name,+ type="tooltip",+ completion_info=_get_completion_info(+ signatures[0]+ ),+ )+ ],+ )+ continue+if not completions:# If there are still no completions, then bail._write_no_completions(stream, request.completion_id)