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.

fix: Update plugin state on Python argument changes (#2623)

Wasim Sandhu495f38adb11e
diff --git a/frontend/src/components/data-table/__test__/useColumnPinning.test.ts b/frontend/src/components/data-table/__test__/useColumnPinning.test.ts
index efd79edb7a..e17569164b 100644
--- a/frontend/src/components/data-table/__test__/useColumnPinning.test.ts
+++ b/frontend/src/components/data-table/__test__/useColumnPinning.test.ts
@@ -61,7 +61,7 @@ describe("useColumnPinning", () => {
const { result } = renderHook(() => useColumnPinning(["initialLeft"]));
act(() => {
- result.current.setColumnPinning((prev: object) => ({
+ result.current.setColumnPinning((prev) => ({
...prev,
right: ["newRight"],
}));
diff --git a/frontend/src/components/data-table/hooks/useColumnPinning.ts b/frontend/src/components/data-table/hooks/useColumnPinning.ts
index de516ba66b..175d5f64ff 100644
--- a/frontend/src/components/data-table/hooks/useColumnPinning.ts
+++ b/frontend/src/components/data-table/hooks/useColumnPinning.ts
@@ -2,6 +2,8 @@
import React from "react";
import { SELECT_COLUMN_ID } from "../types";
import type { ColumnPinningState } from "@tanstack/react-table";
+import { useInternalStateWithSync } from "@/hooks/useInternalStateWithSync";
+import { isEqual } from "lodash-es";
interface UseColumnPinningResult {
columnPinning: ColumnPinningState;
@@ -12,10 +14,14 @@ export function useColumnPinning(
freezeColumnsLeft?: string[],
freezeColumnsRight?: string[],
): UseColumnPinningResult {
- const [columnPinning, setColumnPinning] = React.useState<ColumnPinningState>({
- left: maybeAddSelectColumnId(freezeColumnsLeft),
- right: freezeColumnsRight,
- });
+ const [columnPinning, setColumnPinning] =
+ useInternalStateWithSync<ColumnPinningState>(
+ {
+ left: maybeAddSelectColumnId(freezeColumnsLeft),
+ right: freezeColumnsRight,
+ },
+ isEqual,
+ );
const setColumnPinningWithFreeze = (
newState: React.SetStateAction<ColumnPinningState>,
diff --git a/frontend/src/hooks/__tests__/useInternalStateWithSync.test.tsx b/frontend/src/hooks/__tests__/useInternalStateWithSync.test.tsx
new file mode 100644
index 0000000000..ab06b20b98
--- /dev/null
+++ b/frontend/src/hooks/__tests__/useInternalStateWithSync.test.tsx
@@ -0,0 +1,76 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { renderHook, act } from "@testing-library/react";
+import { useInternalStateWithSync } from "../useInternalStateWithSync";
+import { describe, it, expect, vi } from "vitest";
+
+describe("useInternalStateWithSync", () => {
+ it("should initialize with the given initial value", () => {
+ const { result } = renderHook(() => useInternalStateWithSync("initial"));
+ expect(result.current[0]).toBe("initial");
+ });
+
+ it("should update internal state when setState is called", () => {
+ const { result } = renderHook(() => useInternalStateWithSync("initial"));
+
+ act(() => {
+ result.current[1]("updated");
+ });
+
+ expect(result.current[0]).toBe("updated");
+ });
+
+ it("should update internal state when initial value changes", () => {
+ const { result, rerender } = renderHook(
+ ({ value }) => useInternalStateWithSync(value),
+ { initialProps: { value: "initial" } },
+ );
+
+ expect(result.current[0]).toBe("initial");
+
+ rerender({ value: "new value" });
+
+ expect(result.current[0]).toBe("new value");
+ });
+
+ it("should not update internal state if initial value remains the same", () => {
+ const { result, rerender } = renderHook(
+ ({ value }) => useInternalStateWithSync(value),
+ { initialProps: { value: "initial" } },
+ );
+
+ act(() => {
+ result.current[1]("internal update");
+ });
+
+ expect(result.current[0]).toBe("internal update");
+
+ rerender({ value: "initial" });
+
+ expect(result.current[0]).toBe("internal update");
+ });
+
+ it("should use custom equality function when provided", () => {
+ const customEqualityFn = vi.fn(
+ (a, b) => JSON.stringify(a) === JSON.stringify(b),
+ );
+ const initialValue = { key: "value" };
+
+ const { result, rerender } = renderHook(
+ ({ value }) => useInternalStateWithSync(value, customEqualityFn),
+ { initialProps: { value: initialValue } },
+ );
+
+ expect(result.current[0]).toEqual(initialValue);
+
+ // Rerender with a new object that has the same content
+ rerender({ value: { key: "value" } });
+
+ expect(customEqualityFn).toHaveBeenCalled();
+ expect(result.current[0]).toEqual(initialValue);
+
+ // Rerender with a new object that has different content
+ rerender({ value: { key: "new value" } });
+
+ expect(result.current[0]).toEqual({ key: "new value" });
+ });
+});
diff --git a/frontend/src/hooks/useInternalStateWithSync.ts b/frontend/src/hooks/useInternalStateWithSync.ts
new file mode 100644
index 0000000000..b97d0acb6c
--- /dev/null
+++ b/frontend/src/hooks/useInternalStateWithSync.ts
@@ -0,0 +1,26 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { useState, useRef } from "react";
+
+type EqualityFn<T> = (a: T, b: T) => boolean;
+
+const defaultEqualityFn = <T>(a: T, b: T) => a === b;
+
+/**
+ * A hook that holds state that is synced with outside state.
+ * If the outside state changes, the internal state is updated.
+ */
+export function useInternalStateWithSync<T>(
+ initial: T,
+ equalityFn: EqualityFn<T> = defaultEqualityFn,
+) {
+ const [state, setState] = useState(initial);
+ const ref = useRef(initial);
+
+ // Whenever the outside state changes, update the internal state
+ if (!equalityFn(ref.current, initial)) {
+ setState(initial); // react is ok to setState during render
+ ref.current = initial;
+ }
+
+ return [state, setState] as const;
+}
diff --git a/frontend/src/plugins/impl/FileBrowserPlugin.tsx b/frontend/src/plugins/impl/FileBrowserPlugin.tsx
index 0b3f86c269..cdb78f0022 100644
--- a/frontend/src/plugins/impl/FileBrowserPlugin.tsx
+++ b/frontend/src/plugins/impl/FileBrowserPlugin.tsx
@@ -21,6 +21,7 @@ import { Checkbox } from "@/components/ui/checkbox";
import { cn } from "@/utils/cn";
import { Label } from "@/components/ui/label";
import { PluralWords } from "@/utils/pluralize";
+import { useInternalStateWithSync } from "@/hooks/useInternalStateWithSync";
/**
* Arguments for a file browser component.
@@ -135,7 +136,7 @@ export const FileBrowser = ({
restrictNavigation,
list_directory,
}: FileBrowserProps): JSX.Element | null => {
- const [path, setPath] = useState(initialPath);
+ const [path, setPath] = useInternalStateWithSync(initialPath);
const [selectAllLabel, setSelectAllLabel] = useState("Select all");
const [isUpdatingPath, setIsUpdatingPath] = useState(false);
diff --git a/marimo/_smoke_tests/issues/2648_file_browser_reset.py b/marimo/_smoke_tests/issues/2648_file_browser_reset.py
new file mode 100644
index 0000000000..9ddecbd639
--- /dev/null
+++ b/marimo/_smoke_tests/issues/2648_file_browser_reset.py
@@ -0,0 +1,45 @@
+import marimo
+
+__generated_with = "0.9.9"
+app = marimo.App(width="medium")
+
+
+def __():
+ import marimo as mo
+ return (mo,)
+
+
+def __(mo):
+ source = mo.ui.text()
+ source
+ return (source,)
+
+
+def __(mo, source):
+ mo.ui.file_browser(initial_path=source.value)
+ return
+
+
+def __(mo):
+ from vega_datasets import data
+
+ df = data.cars()
+ columns = df.columns.tolist()
+ slider = mo.ui.slider(0, len(columns), label="frozen columns")
+ slider
+ return columns, data, df, slider
+
+
+def __(columns, df, mo, slider):
+ frozen = columns[: slider.value]
+ mo.ui.table(df, freeze_columns_left=frozen)
+ return (frozen,)
+
+
+if __name__ == "__main__":
+ app.run()