This is an automated email from the ASF dual-hosted git repository.
DImuthuUpe pushed a commit to branch jupyter-ui-poc
in repository https://gitbox.apache.org/repos/asf/airavata.git
The following commit(s) were added to refs/heads/jupyter-ui-poc by this push:
new ee39c92d57 Implemented the file browser for the notebook viewer
ee39c92d57 is described below
commit ee39c92d571b148df6d5ea0e192fe971517ebf67
Author: DImuthuUpe <[email protected]>
AuthorDate: Mon Nov 9 15:49:29 2026 -0500
Implemented the file browser for the notebook viewer
---
INSTALL.md | 3 +-
dashboard/README.md | 7 +-
dashboard/package-lock.json | 1 +
dashboard/package.json | 1 +
dashboard/src/app/globals.css | 185 +++++++++++++
dashboard/src/app/notebooks/page.tsx | 2 +-
dashboard/src/components/NotebookFiles.tsx | 421 +++++++++++++++++++++++++++++
dashboard/src/components/NotebookView.tsx | 285 +++++++++++++++----
8 files changed, 847 insertions(+), 58 deletions(-)
diff --git a/INSTALL.md b/INSTALL.md
index 4a83a5419a..b9b8c96b4d 100644
--- a/INSTALL.md
+++ b/INSTALL.md
@@ -333,7 +333,8 @@ launch and monitor processes; register, upload and download
data products; and a
interactive SSH logins (password, OTP, Duo) as they happen. Its **Notebooks**
page is a
Python notebook ([jupyter-ui](https://github.com/datalayer/jupyter-ui)) whose
kernel runs
in the browser on Pyodide, with an `airavata(path)` helper that calls this API
as the
-signed-in user. Notebooks are kept in each browser's storage, not on the
server, and the
+signed-in user, and a file browser to create, rename, upload and download
notebooks and
+files. Notebooks and files are kept in each browser's storage, not on the
server, and the
kernel downloads Pyodide from the jsDelivr CDN when it first starts, so
browsers using it
need internet access.
diff --git a/dashboard/README.md b/dashboard/README.md
index aa4cd7d8a2..70ab23d196 100644
--- a/dashboard/README.md
+++ b/dashboard/README.md
@@ -31,9 +31,10 @@ src/lib/session.tsx the signed-in token and whether it is
an admin
src/lib/interactive-auth.tsx
subscription to waiting SSH logins (socket, polling
fallback)
src/lib/types.ts wire shapes, mirroring api/*/dto
-src/components/NotebookView.tsx
- the Notebooks page: a @datalayer/jupyter-react notebook
on an
- in-browser Pyodide kernel, autosaved to local storage
+src/components/NotebookView.tsx, NotebookFiles.tsx
+ the Notebooks page: a file browser and a
@datalayer/jupyter-react
+ notebook on an in-browser Pyodide kernel; files live in
the
+ browser's IndexedDB through jupyter-react's lite contents
service
```
The build uses webpack (`next build --webpack`), not Turbopack: the JupyterLab
packages
diff --git a/dashboard/package-lock.json b/dashboard/package-lock.json
index c70c2747c9..c8960c470b 100644
--- a/dashboard/package-lock.json
+++ b/dashboard/package-lock.json
@@ -12,6 +12,7 @@
"@jupyterlab/coreutils": "6.6.6",
"@jupyterlab/nbformat": "4.6.6",
"@jupyterlab/notebook": "4.6.6",
+ "@jupyterlab/services": "7.6.6",
"next": "16.4.4",
"react": "19.2.9",
"react-dom": "19.2.9"
diff --git a/dashboard/package.json b/dashboard/package.json
index 03bcc86df5..dbd3841939 100644
--- a/dashboard/package.json
+++ b/dashboard/package.json
@@ -12,6 +12,7 @@
"@jupyterlab/coreutils": "6.6.6",
"@jupyterlab/nbformat": "4.6.6",
"@jupyterlab/notebook": "4.6.6",
+ "@jupyterlab/services": "7.6.6",
"next": "16.4.4",
"react": "19.2.9",
"react-dom": "19.2.9"
diff --git a/dashboard/src/app/globals.css b/dashboard/src/app/globals.css
index 0cb7687118..5c53299a3d 100644
--- a/dashboard/src/app/globals.css
+++ b/dashboard/src/app/globals.css
@@ -953,3 +953,188 @@ dd.chips {
justify-self: center;
}
}
+
+/* Notebooks: a file browser beside the open notebook. */
+.nb-workspace {
+ display: grid;
+ grid-template-columns: 280px minmax(0, 1fr);
+ gap: 16px;
+ align-items: start;
+}
+.nb-files {
+ display: flex;
+ flex-direction: column;
+ height: calc(100vh - 150px);
+ min-height: 360px;
+ overflow: hidden;
+}
+.nb-files.dragging {
+ outline: 2px dashed var(--accent);
+ outline-offset: -4px;
+ background: var(--accent-soft);
+}
+.nb-files-toolbar {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+ padding: 10px 12px;
+ border-bottom: 1px solid var(--border);
+}
+.nb-crumbs {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 4px;
+ padding: 8px 12px;
+ font-size: 13px;
+ border-bottom: 1px solid var(--border);
+}
+.nb-crumbs > span {
+ display: inline-flex;
+ gap: 4px;
+}
+.nb-crumbs button.link:disabled {
+ color: var(--text);
+ font-weight: 600;
+ opacity: 1;
+}
+.nb-files-alert {
+ padding: 8px 12px 0;
+}
+.nb-file-list {
+ list-style: none;
+ margin: 0;
+ padding: 4px 0;
+ overflow-y: auto;
+ flex: 1;
+}
+.nb-file-list li {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ padding: 0 8px 0 4px;
+ position: relative;
+}
+.nb-file-list li.active {
+ background: var(--accent-soft);
+}
+.nb-file-list li:hover:not(.empty) {
+ background: var(--surface-2);
+}
+.nb-file-list li.active:hover {
+ background: var(--accent-soft);
+}
+button.nb-file-name {
+ flex: 1;
+ min-width: 0;
+ border: none;
+ background: none;
+ justify-content: flex-start;
+ padding: 6px 8px;
+ font-weight: 400;
+}
+button.nb-file-name:hover:not(:disabled) {
+ background: none;
+}
+button.nb-file-name:disabled {
+ cursor: default;
+ opacity: 1;
+ color: var(--muted);
+}
+button.nb-file-name .truncate {
+ max-width: 100%;
+}
+.nb-file-list li.active button.nb-file-name {
+ color: var(--accent);
+ font-weight: 600;
+}
+/* The row menu button shows on hover, keyboard focus, or while its menu is
open. */
+.nb-row-menu {
+ position: relative;
+ flex-shrink: 0;
+ visibility: hidden;
+}
+.nb-file-list li:hover .nb-row-menu,
+.nb-file-list li:focus-within .nb-row-menu,
+.nb-row-menu.open {
+ visibility: visible;
+}
+button.nb-row-menu-button {
+ border-color: transparent;
+ background: none;
+ padding: 0 8px;
+ letter-spacing: 1px;
+}
+button.nb-row-menu-button:hover:not(:disabled) {
+ border-color: var(--border);
+}
+.nb-row-menu-items {
+ position: absolute;
+ right: 0;
+ top: calc(100% + 2px);
+ z-index: 10;
+ display: flex;
+ flex-direction: column;
+ min-width: 170px;
+ padding: 4px;
+ background: var(--surface);
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ box-shadow: 0 4px 12px rgba(16, 24, 40, 0.14);
+}
+.nb-row-menu-items button {
+ border: none;
+ background: none;
+ justify-content: flex-start;
+ font-weight: 400;
+ padding: 6px 10px;
+}
+.nb-row-menu-items button.danger {
+ color: var(--danger);
+}
+.nb-icon {
+ flex-shrink: 0;
+ fill: none;
+ stroke: currentColor;
+ stroke-width: 1.2;
+ color: var(--muted);
+}
+.nb-icon.folder {
+ fill: var(--warn-soft);
+ stroke: var(--warn);
+}
+.nb-icon.notebook {
+ stroke: var(--accent);
+}
+.nb-editor {
+ min-width: 0;
+}
+.nb-editor-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ margin-bottom: 8px;
+}
+.nb-editor-head .truncate {
+ max-width: 70%;
+}
+.nb-save {
+ font-size: 12px;
+}
+.nb-save.error {
+ color: var(--danger);
+}
+
+@media (max-width: 900px) {
+ .nb-workspace {
+ grid-template-columns: 1fr;
+ }
+ .nb-files {
+ height: auto;
+ max-height: 320px;
+ }
+ .nb-row-menu {
+ visibility: visible;
+ }
+}
diff --git a/dashboard/src/app/notebooks/page.tsx
b/dashboard/src/app/notebooks/page.tsx
index 27993e48a0..21a0a24485 100644
--- a/dashboard/src/app/notebooks/page.tsx
+++ b/dashboard/src/app/notebooks/page.tsx
@@ -16,7 +16,7 @@ export default function NotebooksPage() {
<div className="stack">
<PageHead
title="Notebooks"
- sub="A Python notebook that runs entirely in your browser on Pyodide.
It is saved in this browser's storage, not on the server."
+ sub="Python notebooks that run entirely in your browser on Pyodide.
Notebooks and files are kept in this browser, not on the server."
/>
<NotebookView />
</div>
diff --git a/dashboard/src/components/NotebookFiles.tsx
b/dashboard/src/components/NotebookFiles.tsx
new file mode 100644
index 0000000000..cc9b6fa048
--- /dev/null
+++ b/dashboard/src/components/NotebookFiles.tsx
@@ -0,0 +1,421 @@
+"use client";
+
+import type { Contents } from "@jupyterlab/services";
+import { useCallback, useEffect, useRef, useState } from "react";
+import { Alert, Field, Modal } from "./ui";
+
+// The file side of the Notebooks page: a browser over jupyter-react's
contents service.
+// In lite mode that service keeps files in this browser's IndexedDB, so
everything here
+// is local to the browser, the same store the in-browser kernel's notebooks
live in.
+
+export const EMPTY_NOTEBOOK = {
+ nbformat: 4,
+ nbformat_minor: 5,
+ metadata: {
+ kernelspec: { name: "python", display_name: "Python (Pyodide)", language:
"python" },
+ language_info: { name: "python" },
+ },
+ cells: [],
+};
+
+export function joinPath(dir: string, name: string) {
+ return dir ? `${dir}/${name}` : name;
+}
+
+export function isNotebook(path: string) {
+ return path.toLowerCase().endsWith(".ipynb");
+}
+
+function parentOf(path: string) {
+ const i = path.lastIndexOf("/");
+ return i < 0 ? "" : path.slice(0, i);
+}
+
+async function exists(contents: Contents.IManager, path: string) {
+ try {
+ await contents.get(path, { content: false });
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+// Folders first, then files, each alphabetically.
+function sortItems(items: Contents.IModel[]) {
+ return [...items].sort((a, b) => {
+ const da = a.type === "directory" ? 0 : 1;
+ const db = b.type === "directory" ? 0 : 1;
+ return da - db || a.name.localeCompare(b.name, undefined, { numeric: true
});
+ });
+}
+
+async function download(contents: Contents.IManager, item: Contents.IModel) {
+ const model = await contents.get(item.path, { content: true });
+ let blob: Blob;
+ if (model.type === "notebook") {
+ blob = new Blob([JSON.stringify(model.content, null, 1)], { type:
"application/x-ipynb+json" });
+ } else if (model.format === "base64") {
+ const bin = atob(model.content as string);
+ const bytes = new Uint8Array(bin.length);
+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
+ blob = new Blob([bytes], { type: model.mimetype ||
"application/octet-stream" });
+ } else {
+ blob = new Blob([String(model.content ?? "")], { type: model.mimetype ||
"text/plain" });
+ }
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ a.href = url;
+ a.download = item.name;
+ a.click();
+ setTimeout(() => URL.revokeObjectURL(url), 0);
+}
+
+function readAsBase64(file: File): Promise<string> {
+ return new Promise((resolve, reject) => {
+ const reader = new FileReader();
+ reader.onload = () =>
resolve(String(reader.result).replace(/^data:[^,]*,/, ""));
+ reader.onerror = () => reject(reader.error);
+ reader.readAsDataURL(file);
+ });
+}
+
+async function upload(contents: Contents.IManager, dir: string, file: File) {
+ const path = joinPath(dir, file.name);
+ if (isNotebook(file.name)) {
+ const content = JSON.parse(await file.text());
+ await contents.save(path, { type: "notebook", format: "json", content });
+ } else {
+ await contents.save(path, { type: "file", format: "base64", content: await
readAsBase64(file) });
+ }
+}
+
+type Dialog =
+ | { kind: "notebook" }
+ | { kind: "folder" }
+ | { kind: "rename"; item: Contents.IModel };
+
+const DIALOG_TITLE = { notebook: "New notebook", folder: "New folder", rename:
"Rename" } as const;
+
+export function NotebookFiles({
+ contents,
+ openPath,
+ onOpen,
+}: {
+ contents: Contents.IManager;
+ openPath: string | null;
+ onOpen: (path: string) => void;
+}) {
+ const [dir, setDir] = useState(() => (openPath ? parentOf(openPath) : ""));
+ const [items, setItems] = useState<Contents.IModel[] | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [dialog, setDialog] = useState<Dialog | null>(null);
+ const [dragging, setDragging] = useState(false);
+ const uploadInput = useRef<HTMLInputElement>(null);
+
+ const refresh = useCallback(async () => {
+ try {
+ const model = await contents.get(dir, { content: true });
+ setItems(sortItems(model.content as Contents.IModel[]));
+ } catch (e) {
+ // The folder went away (deleted or renamed elsewhere): fall back to the
root.
+ if (dir) setDir("");
+ else setError(String(e));
+ }
+ }, [contents, dir]);
+
+ useEffect(() => {
+ void refresh();
+ const onChange = () => void refresh();
+ contents.fileChanged.connect(onChange);
+ return () => {
+ contents.fileChanged.disconnect(onChange);
+ };
+ }, [contents, refresh]);
+
+ const run = async (action: () => Promise<unknown>) => {
+ setError(null);
+ try {
+ await action();
+ } catch (e) {
+ setError(e instanceof Error ? e.message : String(e));
+ }
+ };
+
+ const uploadFiles = (files: FileList | null) =>
+ files &&
+ run(async () => {
+ for (const file of Array.from(files)) await upload(contents, dir, file);
+ });
+
+ const crumbs = dir ? dir.split("/") : [];
+
+ return (
+ <section
+ className={`nb-files card${dragging ? " dragging" : ""}`}
+ onDragOver={(e) => {
+ if (!e.dataTransfer.types.includes("Files")) return;
+ e.preventDefault();
+ setDragging(true);
+ }}
+ onDragLeave={(e) => e.currentTarget === e.target && setDragging(false)}
+ onDrop={(e) => {
+ if (!e.dataTransfer.files.length) return;
+ e.preventDefault();
+ setDragging(false);
+ void uploadFiles(e.dataTransfer.files);
+ }}
+ >
+ <div className="nb-files-toolbar">
+ <button className="small primary" onClick={() => setDialog({ kind:
"notebook" })}>
+ New notebook
+ </button>
+ <button className="small" onClick={() => setDialog({ kind: "folder"
})} title="New folder">
+ New folder
+ </button>
+ <button className="small" onClick={() => uploadInput.current?.click()}
title="Upload files">
+ Upload
+ </button>
+ <input
+ ref={uploadInput}
+ type="file"
+ multiple
+ hidden
+ onChange={(e) => {
+ void uploadFiles(e.target.files);
+ e.target.value = "";
+ }}
+ />
+ </div>
+
+ <nav className="nb-crumbs" aria-label="Folder">
+ <button className="link" onClick={() => setDir("")} disabled={!dir}>
+ Files
+ </button>
+ {crumbs.map((name, i) => (
+ <span key={i}>
+ <span className="muted">/</span>
+ <button
+ className="link"
+ onClick={() => setDir(crumbs.slice(0, i + 1).join("/"))}
+ disabled={i === crumbs.length - 1}
+ >
+ {name}
+ </button>
+ </span>
+ ))}
+ </nav>
+
+ {error && (
+ <div className="nb-files-alert">
+ <Alert>{error}</Alert>
+ </div>
+ )}
+
+ <ul className="nb-file-list">
+ {items === null && <li className="empty">Loading…</li>}
+ {items?.length === 0 && <li className="empty">Empty folder. Create a
notebook or drop files here.</li>}
+ {items?.map((item) => {
+ const folder = item.type === "directory";
+ const opens = folder || isNotebook(item.path);
+ return (
+ <li key={item.path} className={item.path === openPath ? "active" :
""}>
+ <button
+ className="nb-file-name"
+ title={opens ? item.name : `${item.name} — only notebooks open
here; use Download`}
+ onClick={() => (folder ? setDir(item.path) : opens ?
onOpen(item.path) : undefined)}
+ disabled={!opens}
+ >
+ <FileIcon kind={folder ? "folder" : isNotebook(item.path) ?
"notebook" : "file"} />
+ <span className="truncate">{item.name}</span>
+ </button>
+ <RowMenu
+ label={item.name}
+ onRename={() => setDialog({ kind: "rename", item })}
+ onDownload={folder ? undefined : () => void run(() =>
download(contents, item))}
+ onDelete={() => run(() => contents.delete(item.path))}
+ />
+ </li>
+ );
+ })}
+ </ul>
+
+ {dialog && (
+ <NameDialog
+ title={DIALOG_TITLE[dialog.kind]}
+ initial={dialog.kind === "rename" ? dialog.item.name : dialog.kind
=== "notebook" ? "Untitled.ipynb" : "New folder"}
+ onClose={() => setDialog(null)}
+ onSubmit={async (raw) => {
+ let name = raw.trim();
+ if (!name || name.includes("/")) throw new Error("Enter a name
without slashes.");
+ if (dialog.kind === "notebook" && !isNotebook(name)) name +=
".ipynb";
+ const base = dialog.kind === "rename" ? parentOf(dialog.item.path)
: dir;
+ const path = joinPath(base, name);
+ if (dialog.kind === "rename" && path === dialog.item.path) return;
+ if (await exists(contents, path)) throw new Error(`“${name}”
already exists here.`);
+ if (dialog.kind === "rename") {
+ await contents.rename(dialog.item.path, path);
+ } else if (dialog.kind === "notebook") {
+ await contents.save(path, { type: "notebook", format: "json",
content: EMPTY_NOTEBOOK });
+ onOpen(path);
+ } else {
+ const created = await contents.newUntitled({ path: dir, type:
"directory" });
+ await contents.rename(created.path, path);
+ }
+ }}
+ />
+ )}
+ </section>
+ );
+}
+
+// RowMenu is a row's actions behind one "⋯" button, so long names keep the
row's width.
+// Delete asks again in place before it acts.
+function RowMenu({
+ label,
+ onRename,
+ onDownload,
+ onDelete,
+}: {
+ label: string;
+ onRename: () => void;
+ onDownload?: () => void;
+ onDelete: () => Promise<unknown>;
+}) {
+ const [open, setOpen] = useState(false);
+ const [confirming, setConfirming] = useState(false);
+ const ref = useRef<HTMLSpanElement>(null);
+
+ useEffect(() => {
+ if (!open) return;
+ const onDown = (e: MouseEvent) => !ref.current?.contains(e.target as Node)
&& setOpen(false);
+ const onKey = (e: KeyboardEvent) => e.key === "Escape" && setOpen(false);
+ document.addEventListener("mousedown", onDown);
+ document.addEventListener("keydown", onKey);
+ return () => {
+ document.removeEventListener("mousedown", onDown);
+ document.removeEventListener("keydown", onKey);
+ };
+ }, [open]);
+
+ const close = () => {
+ setOpen(false);
+ setConfirming(false);
+ };
+
+ return (
+ <span className={`nb-row-menu${open ? " open" : ""}`} ref={ref}>
+ <button
+ className="small nb-row-menu-button"
+ aria-label={`Actions for ${label}`}
+ aria-haspopup="menu"
+ aria-expanded={open}
+ onClick={() => (open ? close() : setOpen(true))}
+ >
+ ⋯
+ </button>
+ {open && (
+ <span className="nb-row-menu-items" role="menu">
+ <button role="menuitem" onClick={() => (close(), onRename())}>
+ Rename
+ </button>
+ {onDownload && (
+ <button role="menuitem" onClick={() => (close(), onDownload())}>
+ Download
+ </button>
+ )}
+ <button
+ role="menuitem"
+ className="danger"
+ onClick={() => (confirming ? (close(), void onDelete()) :
setConfirming(true))}
+ >
+ {confirming ? "Click again to delete" : "Delete"}
+ </button>
+ </span>
+ )}
+ </span>
+ );
+}
+
+function NameDialog({
+ title,
+ initial,
+ onClose,
+ onSubmit,
+}: {
+ title: string;
+ initial: string;
+ onClose: () => void;
+ onSubmit: (name: string) => Promise<void>;
+}) {
+ const [name, setName] = useState(initial);
+ const [error, setError] = useState<string | null>(null);
+ const [busy, setBusy] = useState(false);
+ const input = useRef<HTMLInputElement>(null);
+
+ // Select the name without its extension, as file managers do.
+ useEffect(() => {
+ const el = input.current;
+ if (!el) return;
+ el.focus();
+ const dot = initial.lastIndexOf(".");
+ el.setSelectionRange(0, dot > 0 ? dot : initial.length);
+ }, [initial]);
+
+ const submit = async (e: React.FormEvent) => {
+ e.preventDefault();
+ setBusy(true);
+ setError(null);
+ try {
+ await onSubmit(name);
+ onClose();
+ } catch (err) {
+ setError(err instanceof Error ? err.message : String(err));
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ return (
+ <Modal
+ title={title}
+ onClose={onClose}
+ footer={
+ <>
+ <button onClick={onClose}>Cancel</button>
+ <button className="primary" type="submit" form="nb-name-form"
disabled={busy}>
+ {busy ? "Working…" : "Save"}
+ </button>
+ </>
+ }
+ >
+ <form id="nb-name-form" className="stack" onSubmit={submit}>
+ <Alert>{error}</Alert>
+ <Field label="Name">
+ <input ref={input} value={name} onChange={(e) =>
setName(e.target.value)} />
+ </Field>
+ </form>
+ </Modal>
+ );
+}
+
+function FileIcon({ kind }: { kind: "folder" | "notebook" | "file" }) {
+ const common = { width: 16, height: 16, viewBox: "0 0 16 16", "aria-hidden":
true, className: `nb-icon ${kind}` };
+ if (kind === "folder")
+ return (
+ <svg {...common}>
+ <path d="M1.5 3.5A1 1 0 0 1 2.5 2.5h3.6l1.5 1.5h5.9a1 1 0 0 1 1 1v7a1
1 0 0 1-1 1h-11a1 1 0 0 1-1-1z" />
+ </svg>
+ );
+ if (kind === "notebook")
+ return (
+ <svg {...common}>
+ <rect x="2.5" y="1.5" width="11" height="13" rx="1.5" />
+ <path d="M5 1.5v13M7.5 5h4M7.5 7.5h4" />
+ </svg>
+ );
+ return (
+ <svg {...common}>
+ <path d="M3.5 1.5h6l3 3v10h-9z M9.5 1.5v3h3" />
+ </svg>
+ );
+}
diff --git a/dashboard/src/components/NotebookView.tsx
b/dashboard/src/components/NotebookView.tsx
index cf393a4a65..3ed26db62b 100644
--- a/dashboard/src/components/NotebookView.tsx
+++ b/dashboard/src/components/NotebookView.tsx
@@ -1,11 +1,14 @@
"use client";
import { JupyterReactTheme, Notebook, NotebookToolbar, useJupyter } from
"@datalayer/jupyter-react";
+import type { Kernel } from "@datalayer/jupyter-react";
import { PageConfig } from "@jupyterlab/coreutils";
import type { INotebookContent } from "@jupyterlab/nbformat";
import type { NotebookModel } from "@jupyterlab/notebook";
+import type { Contents, ServiceManager } from "@jupyterlab/services";
import { useEffect, useMemo, useRef, useState } from "react";
import { API_BASE, getToken } from "@/lib/api";
+import { isNotebook, NotebookFiles } from "./NotebookFiles";
// jupyter-react's lite server registers a service worker at the origin root,
which would
// sit in front of every request to the API server. It only syncs files
between the
@@ -13,7 +16,9 @@ import { API_BASE, getToken } from "@/lib/api";
// treats it as optional. Disable it before the lite server starts.
PageConfig.Extension.disabled.push("@jupyterlite/server-extension:service-worker");
-const STORAGE_KEY = "airavata.notebook";
+// The last notebook opened, reopened on the next visit (a per-browser
convenience).
+const LAST_OPEN_KEY = "airavata.notebook.open";
+const WELCOME_PATH = "Welcome.ipynb";
const SAVE_DELAY_MS = 1000;
// Run in the kernel when it starts, so cells can call the Airavata API as the
signed-in
@@ -41,7 +46,7 @@ async def airavata(path, method="GET", body=None):
`;
}
-const STARTER: INotebookContent = {
+const WELCOME: INotebookContent = {
nbformat: 4,
nbformat_minor: 5,
metadata: {
@@ -57,7 +62,8 @@ const STARTER: INotebookContent = {
"# Airavata notebook\n\n" +
"Python runs in your browser on [Pyodide](https://pyodide.org). " +
"`await airavata(path)` calls the Airavata API as you; install
pure-Python " +
- "packages with `%pip install <name>`.",
+ "packages with `%pip install <name>`.\n\n" +
+ "Notebooks and files in the panel on the left are kept in this
browser, not on the server.",
},
{
cell_type: "code",
@@ -70,82 +76,255 @@ const STARTER: INotebookContent = {
],
};
-function loadSaved(): INotebookContent {
+function readLastOpen(): string | null {
try {
- const saved = window.localStorage.getItem(STORAGE_KEY);
- if (saved) return JSON.parse(saved) as INotebookContent;
+ return window.localStorage.getItem(LAST_OPEN_KEY);
} catch {
- // Unreadable or unavailable storage: start from the starter notebook.
+ return null;
}
- return STARTER;
}
-// NotebookView is one notebook backed by an in-browser Pyodide kernel
(jupyter-react's
-// "lite" mode), kept in local storage so it survives reloads.
+function writeLastOpen(path: string | null) {
+ try {
+ if (path) window.localStorage.setItem(LAST_OPEN_KEY, path);
+ else window.localStorage.removeItem(LAST_OPEN_KEY);
+ } catch {}
+}
+
+function useColorMode(): "light" | "dark" {
+ const [dark, setDark] = useState(() =>
window.matchMedia("(prefers-color-scheme: dark)").matches);
+ useEffect(() => {
+ const mq = window.matchMedia("(prefers-color-scheme: dark)");
+ const on = () => setDark(mq.matches);
+ mq.addEventListener("change", on);
+ return () => mq.removeEventListener("change", on);
+ }, []);
+ return dark ? "dark" : "light";
+}
+
+// NotebookView is the Notebooks page: a file browser over the in-browser
contents store
+// beside the open notebook, all on jupyter-react's "lite" mode (a Pyodide
kernel and
+// IndexedDB-backed contents, no Jupyter server).
export default function NotebookView() {
const code = useMemo(() => initCode(API_BASE || window.location.origin,
getToken()), []);
const { serviceManager, defaultKernel } = useJupyter({ lite: true,
startDefaultKernel: true, initCode: code });
- const [nbformat, setNbformat] = useState(loadSaved);
- // Bumped by "Reset" to remount the notebook on the starter content.
- const [generation, setGeneration] = useState(0);
- const saveTimer = useRef<ReturnType<typeof setTimeout>>(undefined);
- const disconnect = useRef<() => void>(undefined);
+ const [openPath, setOpenPathState] = useState<string | null>(null);
+ const [ready, setReady] = useState(false);
+ // Changes only when a different file is opened, not when the open one is
renamed, so a
+ // rename keeps the editor (and any unsaved edits) in place.
+ const [docId, setDocId] = useState(0);
+ const colorMode = useColorMode();
- useEffect(() => () => {
- clearTimeout(saveTimer.current);
- disconnect.current?.();
- }, []);
+ const setOpenPath = (path: string | null, newDoc: boolean) => {
+ setOpenPathState(path);
+ writeLastOpen(path);
+ if (newDoc) setDocId((d) => d + 1);
+ };
- const onModel = (model: NotebookModel | null) => {
- disconnect.current?.();
- disconnect.current = undefined;
- if (!model) return;
- const save = () => {
- clearTimeout(saveTimer.current);
- saveTimer.current = setTimeout(() => {
+ // Pick the notebook to show first: the last one opened if it is still
there, else the
+ // welcome notebook, created on the very first visit.
+ useEffect(() => {
+ if (!serviceManager) return;
+ const contents = serviceManager.contents;
+ let cancelled = false;
+ (async () => {
+ const last = readLastOpen();
+ let path: string | null = null;
+ if (last) {
try {
- window.localStorage.setItem(STORAGE_KEY,
JSON.stringify(model.toJSON()));
- } catch {
- // Storage full or unavailable; the notebook still works for this
page.
+ await contents.get(last, { content: false });
+ path = last;
+ } catch {}
+ }
+ if (!path) {
+ const root = await contents.get("", { content: true });
+ if ((root.content as Contents.IModel[]).length === 0) {
+ await contents.save(WELCOME_PATH, { type: "notebook", format:
"json", content: WELCOME });
+ path = WELCOME_PATH;
}
- }, SAVE_DELAY_MS);
+ }
+ if (cancelled) return;
+ setOpenPath(path, true);
+ setReady(true);
+ })().catch(() => !cancelled && setReady(true));
+ return () => {
+ cancelled = true;
};
- model.contentChanged.connect(save);
- disconnect.current = () => model.contentChanged.disconnect(save);
- };
+ }, [serviceManager]);
+
+ // Follow the open notebook when it, or a folder above it, is renamed or
deleted.
+ useEffect(() => {
+ if (!serviceManager) return;
+ const contents = serviceManager.contents;
+ const onChange = (_: unknown, change: Contents.IChangedArgs) => {
+ if (change.type !== "rename" && change.type !== "delete") return;
+ const oldPath = change.oldValue?.path;
+ if (!oldPath) return;
+ setOpenPathState((current) => {
+ if (!current || (current !== oldPath && !current.startsWith(oldPath +
"/"))) return current;
+ const newPath = change.type === "rename" ? change.newValue?.path :
undefined;
+ const next = newPath ? newPath + current.slice(oldPath.length) : null;
+ writeLastOpen(next);
+ return next;
+ });
+ };
+ contents.fileChanged.connect(onChange);
+ return () => {
+ contents.fileChanged.disconnect(onChange);
+ };
+ }, [serviceManager]);
+
+ if (!serviceManager || !defaultKernel || !ready) return <p
className="muted">Starting the Python kernel…</p>;
- const reset = () => {
- if (!window.confirm("Replace this notebook with the starter notebook? Your
cells will be lost.")) return;
- clearTimeout(saveTimer.current);
+ return (
+ <div className="nb-workspace">
+ <NotebookFiles
+ contents={serviceManager.contents}
+ openPath={openPath}
+ onOpen={(path) => path !== openPath && setOpenPath(path, true)}
+ />
+ <div className="nb-editor">
+ {openPath && isNotebook(openPath) ? (
+ <NotebookEditor
+ key={docId}
+ docId={docId}
+ path={openPath}
+ serviceManager={serviceManager}
+ kernel={defaultKernel}
+ colorMode={colorMode}
+ />
+ ) : (
+ <div className="empty card">Open a notebook from the panel on the
left, or create one.</div>
+ )}
+ </div>
+ </div>
+ );
+}
+
+type SaveState = "saved" | "pending" | "saving" | "error";
+
+const SAVE_LABEL: Record<SaveState, string> = {
+ saved: "Saved",
+ pending: "Unsaved changes",
+ saving: "Saving…",
+ error: "Save failed",
+};
+
+// NotebookEditor loads one notebook from the contents store and writes it
back a moment
+// after each change. jupyter-react's Notebook is given the content, not the
path: with a
+// path it would hand the file to JupyterLab's document context, which this
page does not
+// drive. All notebooks share the page's one kernel.
+function NotebookEditor({
+ docId,
+ path,
+ serviceManager,
+ kernel,
+ colorMode,
+}: {
+ docId: number;
+ path: string;
+ serviceManager: ServiceManager.IManager;
+ kernel: Kernel;
+ colorMode: "light" | "dark";
+}) {
+ const contents = serviceManager.contents;
+ const [nbformat, setNbformat] = useState<INotebookContent | null>(null);
+ const [loadError, setLoadError] = useState<string | null>(null);
+ const [saveState, setSaveState] = useState<SaveState>("saved");
+ // The current path, so a save after a rename goes to the new name.
+ const pathRef = useRef(path);
+ pathRef.current = path;
+ const modelRef = useRef<NotebookModel | null>(null);
+ const timer = useRef<ReturnType<typeof setTimeout>>(undefined);
+ const dirty = useRef(false);
+
+ useEffect(() => {
+ let cancelled = false;
+ contents
+ .get(path, { content: true })
+ .then((m) => !cancelled && setNbformat(m.content as INotebookContent))
+ .catch((e) => !cancelled && setLoadError(e instanceof Error ? e.message
: String(e)));
+ return () => {
+ cancelled = true;
+ };
+ // Loaded once per document; a rename changes the path but not the content.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [docId]);
+
+ const save = async () => {
+ clearTimeout(timer.current);
+ const model = modelRef.current;
+ if (!model || !dirty.current) return;
+ dirty.current = false;
+ const target = pathRef.current;
+ // Deleted while edits were pending: do not bring it back.
+ try {
+ await contents.get(target, { content: false });
+ } catch {
+ return;
+ }
+ setSaveState("saving");
try {
- window.localStorage.removeItem(STORAGE_KEY);
- } catch {}
- setNbformat(STARTER);
- setGeneration((g) => g + 1);
+ await contents.save(target, { type: "notebook", format: "json", content:
model.toJSON() });
+ setSaveState(dirty.current ? "pending" : "saved");
+ } catch {
+ dirty.current = true;
+ setSaveState("error");
+ }
};
+ const saveRef = useRef(save);
+ saveRef.current = save;
- if (!serviceManager || !defaultKernel) return <p className="muted">Starting
the Python kernel…</p>;
+ // Write any pending edits when switching away from this notebook or leaving
the page.
+ useEffect(
+ () => () => {
+ void saveRef.current();
+ },
+ [],
+ );
+
+ const disconnect = useRef<() => void>(undefined);
+ useEffect(() => () => disconnect.current?.(), []);
+ const onModel = useMemo(
+ () => (model: NotebookModel | null) => {
+ disconnect.current?.();
+ disconnect.current = undefined;
+ modelRef.current = model;
+ if (!model) return;
+ const changed = () => {
+ dirty.current = true;
+ setSaveState("pending");
+ clearTimeout(timer.current);
+ timer.current = setTimeout(() => void saveRef.current(),
SAVE_DELAY_MS);
+ };
+ model.contentChanged.connect(changed);
+ disconnect.current = () => model.contentChanged.disconnect(changed);
+ },
+ [],
+ );
+
+ if (loadError) return <div className="alert error">Could not open {path}:
{loadError}</div>;
+ if (!nbformat) return <p className="muted">Opening {path}…</p>;
return (
- <div className="notebook-view">
- <div className="row">
- <span className="muted">Saved in this browser automatically.</span>
- <button className="small" onClick={reset}>
- Reset notebook
- </button>
+ <>
+ <div className="nb-editor-head">
+ <strong className="truncate" title={path}>
+ {path}
+ </strong>
+ <span className={`muted nb-save
${saveState}`}>{SAVE_LABEL[saveState]}</span>
</div>
- <JupyterReactTheme colormode="light" useBaseStyles={false}>
+ <JupyterReactTheme colormode={colorMode} useBaseStyles={false}>
<Notebook
- key={generation}
- id={`airavata-notebook-${generation}`}
- kernel={defaultKernel}
+ id={`airavata-notebook-${docId}`}
+ kernel={kernel}
serviceManager={serviceManager}
nbformat={nbformat}
- height="calc(100vh - 200px)"
+ height="calc(100vh - 230px)"
Toolbar={NotebookToolbar}
onNotebookModelChanged={onModel}
/>
</JupyterReactTheme>
- </div>
+ </>
);
}