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
misc: allow uploading notebook as shared page (#519)
Myles Scolnick642b47979b84
diff --git a/frontend/src/components/editor/actions/useNotebookActions.tsx b/frontend/src/components/editor/actions/useNotebookActions.tsxindex c355d14ef6..f18100c215 100644--- a/frontend/src/components/editor/actions/useNotebookActions.tsx+++ b/frontend/src/components/editor/actions/useNotebookActions.tsx@@ -10,6 +10,7 @@ import {BookMarkedIcon,FolderDownIcon,ClipboardCopyIcon,+ Share2Icon,} from "lucide-react";import { commandPalletteAtom } from "../CommandPallette";import {@@ -24,9 +25,12 @@ import { ActionButton } from "./types";import { downloadAsHTML } from "@/core/static/download-html";import { toast } from "@/components/ui/use-toast";import { useFilename } from "@/core/saving/filename";+import { useImperativeModal } from "@/components/modal/ImperativeModal";+import { ShareStaticNotebookModal } from "@/components/static-html/share-modal";export function useNotebookActions() {const [filename] = useFilename();+ const { openModal, closeModal } = useImperativeModal();const notebook = useNotebook();const { updateCellConfig } = useCellActions();@@ -64,6 +68,13 @@ export function useNotebookActions() {await downloadAsHTML({ filename });},},+ {+ icon: <Share2Icon size={14} strokeWidth={1.5} />,+ label: "Share as static notebook",+ handle: async () => {+ openModal(<ShareStaticNotebookModal onClose={closeModal} />);+ },+ },{icon: <ZapIcon size={14} strokeWidth={1.5} />,label: "Enable all cells",diff --git a/frontend/src/components/editor/chrome/footer/feedback-button.tsx b/frontend/src/components/editor/chrome/footer/feedback-button.tsxindex d4769cf3ab..bb89ea1efa 100644--- a/frontend/src/components/editor/chrome/footer/feedback-button.tsx+++ b/frontend/src/components/editor/chrome/footer/feedback-button.tsx@@ -12,6 +12,7 @@ import React, { PropsWithChildren } from "react";import { Button } from "@/components/ui/button";import { Textarea } from "@/components/ui/textarea";import { toast } from "@/components/ui/use-toast";+import { Constants } from "@/core/constants";export const FeedbackButton: React.FC<PropsWithChildren> = ({ children }) => {const { openModal, closeModal } = useImperativeModal();@@ -68,7 +69,7 @@ const FeedbackModal: React.FC<{Let us know what you think about marimo! If you have a bug that youwould like to report, please use the{" "}<a- href="https://github.com/marimo-team/marimo/issues"+ href={Constants.issuesPage}target="_blank"rel="noreferrer"className="underline"diff --git a/frontend/src/components/static-html/share-modal.tsx b/frontend/src/components/static-html/share-modal.tsxnew file mode 100644index 0000000000..35b480fd8c--- /dev/null+++ b/frontend/src/components/static-html/share-modal.tsx@@ -0,0 +1,163 @@+/* Copyright 2023 Marimo. All rights reserved. */+import {+ DialogFooter,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogDescription,+} from "@/components/ui/dialog";+import React, { useRef, useState } from "react";+import { Button } from "@/components/ui/button";+import { toast } from "@/components/ui/use-toast";+import { Input } from "../ui/input";+import { CopyIcon } from "lucide-react";+import { Events } from "@/utils/events";+import { Tooltip } from "../ui/tooltip";+import { createStaticHTMLNotebook } from "@/core/static/download-html";+import { Constants } from "@/core/constants";++const BASE_URL = "https://marimo.io";++export const ShareStaticNotebookModal: React.FC<{+ onClose: () => void;+}> = ({ onClose }) => {+ const [slug, setSlug] = useState("");+ // 4 character random string+ const randomHash = useRef(Math.random().toString(36).slice(2, 6)).current;++ // Globally unique path+ const path = `${slug}-${randomHash}`;+ const url = `${BASE_URL}/static/${path}`;++ return (+ <DialogContent className="w-fit">+ <form+ onSubmit={async (e) => {+ e.preventDefault();++ onClose();+ const html = await createStaticHTMLNotebook();++ const prevToast = toast({+ title: "Uploading static notebook...",+ description: "Please wait.",+ });++ await fetch(`${BASE_URL}/api/static`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ html: html,+ path: path,+ }),+ }).catch(() => {+ prevToast.dismiss();+ toast({+ title: "Error uploading static page",+ description: (+ <div>+ Please try again later. If the problem persists, please file a+ bug report on{" "}+ <a+ href={Constants.issuesPage}+ target="_blank"+ rel="noreferrer"+ className="underline"+ >+ GitHub+ </a>+ .+ </div>+ ),+ });+ });++ prevToast.dismiss();+ toast({+ title: "Static page uploaded!",+ description: (+ <div>+ The URL has been copied to your clipboard.+ <br />+ You can share it with anyone.+ </div>+ ),+ });+ }}+ >+ <DialogHeader>+ <DialogTitle>Share static notebook</DialogTitle>+ <DialogDescription>+ You can share a static, non-interactive version of this notebook. We+ will create a link for you that lives on{" "}+ <a href={BASE_URL} target="_blank" rel="noreferrer">+ {BASE_URL}+ </a>+ .+ </DialogDescription>+ </DialogHeader>+ <div className="flex flex-col gap-6 py-4">+ <Input+ id="slug"+ autoFocus={true}+ value={slug}+ placeholder="Notebook slug"+ onChange={(e) => {+ const newSlug = e.target.value+ .toLowerCase()+ .replaceAll(/\s/g, "-")+ .replaceAll(/[^\da-z-]/g, "");+ setSlug(newSlug);+ }}+ required={true}+ autoComplete="off"+ />++ <div className="font-semibold text-sm text-muted-foreground gap-2 flex flex-col">+ You will be able to access your notebook at this URL:+ <div className="flex items-center gap-2">+ <CopyButton text={url} />+ <span className="text-primary">{url}</span>+ </div>+ </div>+ </div>+ <DialogFooter>+ <Button variant="secondary" onClick={onClose}>+ Cancel+ </Button>+ <Button+ aria-label="Save"+ variant="default"+ type="submit"+ onClick={() => {+ navigator.clipboard.writeText(url);+ }}+ >+ Create+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ );+};++const CopyButton = (props: { text: string }) => {+ const [copied, setCopied] = React.useState(false);++ const copy = Events.stopPropagation((e) => {+ e.preventDefault();+ navigator.clipboard.writeText(props.text);+ setCopied(true);+ setTimeout(() => setCopied(false), 2000);+ });++ return (+ <Tooltip content="Copied!" open={copied}>+ <Button onClick={copy} size="xs" variant="secondary">+ <CopyIcon size={14} strokeWidth={1.5} />+ </Button>+ </Tooltip>+ );+};diff --git a/frontend/src/components/ui/use-toast.ts b/frontend/src/components/ui/use-toast.tsindex 24e9808ab2..41d4a87fc5 100644--- a/frontend/src/components/ui/use-toast.ts+++ b/frontend/src/components/ui/use-toast.ts@@ -140,7 +140,7 @@ type Toast = Omit<ToasterToast, "id">;function toast({ ...props }: Toast) {const id = genId();- const update = (props: ToasterToast) =>+ const update = (props: Toast) =>dispatch({type: "UPDATE_TOAST",toast: { ...props, id },diff --git a/frontend/src/core/constants.ts b/frontend/src/core/constants.tsnew file mode 100644index 0000000000..092943d13d--- /dev/null+++ b/frontend/src/core/constants.ts@@ -0,0 +1,4 @@+/* Copyright 2023 Marimo. All rights reserved. */+export const Constants = {+ issuesPage: "https://github.com/marimo-team/marimo/issues",+};diff --git a/frontend/src/core/static/__tests__/download-html.test.ts b/frontend/src/core/static/__tests__/download-html.test.tsindex bc4d00c894..39d9f82cb3 100644--- a/frontend/src/core/static/__tests__/download-html.test.ts+++ b/frontend/src/core/static/__tests__/download-html.test.ts@@ -98,7 +98,6 @@ describe("download-html", () => {},code: "import marimo as mo\n\nmo.html('<h1>hello</h1>')",assetUrl: `https://cdn.jsdelivr.net/npm/@marimo-team/frontend@${version}/dist`,- filename: "app",existingDocument: new JSDOM(DOC).window.document,});diff --git a/frontend/src/core/static/download-html.ts b/frontend/src/core/static/download-html.tsindex 6831fa110f..9d37f1e1c8 100644--- a/frontend/src/core/static/download-html.ts+++ b/frontend/src/core/static/download-html.ts@@ -17,8 +17,7 @@ const ENABLE_LOCAL_ASSETS = false;/*** Downloads the current notebook as an HTML file.*/-export async function downloadAsHTML(opts: { filename: string }) {- const { filename } = opts;+export async function createStaticHTMLNotebook() {const notebook = getNotebook();const version = getMarimoVersion();@@ -38,20 +37,29 @@ export async function downloadAsHTML(opts: { filename: string }) {throw error;});- const filenameWithoutPath = filename.split("/").pop() ?? "app.py";- const filenameWithoutExtension =- filenameWithoutPath.split(".").shift() ?? "app";-const html = constructHTML({notebookState: notebook,version: version,assetUrl: assetUrl,- filename: filenameWithoutPath,existingDocument: document,files: await downloadVirtualFiles(),code: codeResponse.contents,});+ return html;+}++/**+ * Downloads the current notebook as an HTML file.+ */+export async function downloadAsHTML(opts: { filename: string }) {+ const { filename } = opts;+ const html = await createStaticHTMLNotebook();++ const filenameWithoutPath = filename.split("/").pop() ?? "app.py";+ const filenameWithoutExtension =+ filenameWithoutPath.split(".").shift() ?? "app";+downloadBlob(new Blob([html], { type: "text/html" }),`${filenameWithoutExtension}.html`@@ -65,7 +73,6 @@ export function constructHTML(opts: {version: string;notebookState: Pick<NotebookState, "cellIds" | "cellData" | "cellRuntime">;assetUrl: string;- filename: string;files: StaticVirtualFiles;existingDocument: Document;code: string;diff --git a/frontend/src/utils/events.ts b/frontend/src/utils/events.tsindex 5484608141..acce73857e 100644--- a/frontend/src/utils/events.ts+++ b/frontend/src/utils/events.ts@@ -1,6 +1,8 @@/* Copyright 2023 Marimo. All rights reserved. */export const Events = {- stopPropagation: <E extends Pick<Event, "stopPropagation">>(+ stopPropagation: <+ E extends Pick<Event, "stopPropagation" | "preventDefault">+ >(callback?: (evt: E) => void) => {return (event: E) => {