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
Elevate `preferObjectParams` linting severity from "warn" to "error" (#5581)
Trevor Manzf1c13cc7726f
diff --git a/frontend/e2e-tests/mode.spec.ts b/frontend/e2e-tests/mode.spec.tsindex 3ae1c5100e..b63c51ecf2 100644--- a/frontend/e2e-tests/mode.spec.ts+++ b/frontend/e2e-tests/mode.spec.ts@@ -11,11 +11,14 @@ import { maybeRestartKernel, takeScreenshot } from "./helper";const _filename = fileURLToPath(import.meta.url);-async function gotoPage(- app: ApplicationNames,- page: Page,- context: BrowserContext,-) {+async function gotoPage({+ app,+ page,+}: {+ app: ApplicationNames;+ page: Page;+ context: BrowserContext;+}) {const url = getAppUrl(app);const mode = getAppMode(app);@@ -37,7 +40,7 @@ test.afterAll(async () => {});test.skip("page renders edit feature in edit mode", async ({ context }) => {- await gotoPage("title.py", page, context);+ await gotoPage({ app: "title.py", page, context });// 'title.py' to be in the document.expect(await page.getByText("title.py").count()).toBeGreaterThan(0);@@ -52,7 +55,7 @@ test.skip("page renders edit feature in edit mode", async ({ context }) => {});test.skip("can bring up the find/replace dialog", async ({ context }) => {- await gotoPage("title.py", page, context);+ await gotoPage({ app: "title.py", page, context });// Wait for the cells to loadawait expect(page.locator("h1").getByText("Hello Marimo!")).toBeVisible();@@ -68,7 +71,7 @@ test.skip("can bring up the find/replace dialog", async ({ context }) => {});test("can toggle to presenter mode", async ({ context }) => {- await gotoPage("title.py", page, context);+ await gotoPage({ app: "title.py", page, context });// Can see output and codeawait expect(page.locator("h1").getByText("Hello Marimo!")).toBeVisible();@@ -93,7 +96,7 @@ test("can toggle to presenter mode", async ({ context }) => {});test("page renders read only view in read mode", async ({ context }) => {- await gotoPage("components.py", page, context);+ await gotoPage({ app: "components.py", page, context });// Filename is not visibleawait expect(page.getByText("components.py").last()).not.toBeVisible();diff --git a/frontend/lint/preferObjectParams.grit b/frontend/lint/preferObjectParams.gritindex 59fabab9e4..194c7a9784 100644--- a/frontend/lint/preferObjectParams.grit+++ b/frontend/lint/preferObjectParams.grit@@ -15,9 +15,5 @@// Methods`$name($p1, $p2, $p3, $...) { $body }`},- register_diagnostic(- span=$name,- message="Avoid multiple positional arguments. Prefer an options object instead, e.g., fn(options) or fn(arg, options).",- severity="warn"- )+ register_diagnostic(span=$name, message="Avoid multiple positional arguments. Prefer an options object instead, e.g., fn(options) or fn(arg, options).", severity="warn")}diff --git a/frontend/src/components/charts/chart-skeleton.tsx b/frontend/src/components/charts/chart-skeleton.tsxindex e085dbc038..fdd945a980 100644--- a/frontend/src/components/charts/chart-skeleton.tsx+++ b/frontend/src/components/charts/chart-skeleton.tsx@@ -19,7 +19,15 @@ const hashString = (str: string) => {};// Utility function to generate deterministic random heights based on a seed-const generateHeights = (numBars: number, maxHeight: number, seed: string) => {+const generateHeights = ({+ numBars,+ maxHeight,+ seed,+}: {+ numBars: number;+ maxHeight: number;+ seed: string;+}) => {const heights = [];let randomSeed = hashString(seed);for (let i = 0; i < numBars; i++) {@@ -34,7 +42,7 @@ const generateHeights = (numBars: number, maxHeight: number, seed: string) => {export const ChartSkeleton: React.FC<Props> = ({ seed, width, height }) => {const numBars = 9;const barWidth = width / numBars;- const heights = generateHeights(numBars, height - 15, seed);+ const heights = generateHeights({ numBars, maxHeight: height - 15, seed });return (<div className="flex items-end gap-[1px] pb-2" style={{ width, height }}>{heights.map((barHeight, index) => (diff --git a/frontend/src/components/data-table/__tests__/column_formatting.test.ts b/frontend/src/components/data-table/__tests__/column_formatting.test.tsindex a3aafce81d..983b7f0158 100644--- a/frontend/src/components/data-table/__tests__/column_formatting.test.ts+++ b/frontend/src/components/data-table/__tests__/column_formatting.test.ts@@ -8,69 +8,108 @@ import { applyFormat } from "../column-formatting/feature";describe("applyFormat", () => {it("should return an empty string for null, undefined, or empty string values", () => {- expect(applyFormat(null, "Date", "date")).toBe("");- expect(applyFormat(undefined, "Date", "date")).toBe("");- expect(applyFormat("", "Date", "date")).toBe("");+ expect(applyFormat(null, { format: "Date", dataType: "date" })).toBe("");+ expect(applyFormat(undefined, { format: "Date", dataType: "date" })).toBe(+ "",+ );+ expect(applyFormat("", { format: "Date", dataType: "date" })).toBe("");});describe("date formatting", () => {it("should format date values correctly", () => {const date = "2023-10-01T12:00:00Z";- expect(applyFormat(date, "Date", "date")).toBe("10/1/23");- expect(applyFormat(date, "Datetime", "date")).toBe(+ expect(applyFormat(date, { format: "Date", dataType: "date" })).toBe(+ "10/1/23",+ );+ expect(applyFormat(date, { format: "Datetime", dataType: "date" })).toBe("10/1/23, 12:00:00 PM UTC",);});it("should format time values correctly", () => {const time = "12:00:00Z";- expect(applyFormat(time, "Time", "time")).toBe("12:00:00Z");+ expect(applyFormat(time, { format: "Time", dataType: "time" })).toBe(+ "12:00:00Z",+ );});it("should format datetime values correctly", () => {const datetime = "2023-10-01T12:00:00Z";- expect(applyFormat(datetime, "Datetime", "datetime")).toBe(- "10/1/23, 12:00:00 PM UTC",- );+ expect(+ applyFormat(datetime, {+ format: "Datetime",+ dataType: "datetime",+ }),+ ).toBe("10/1/23, 12:00:00 PM UTC");});});describe("number formatting", () => {it("should format number values correctly", () => {const number = "1234.567";- expect(applyFormat(number, "Auto", "number")).toBe("1,234.57");- expect(applyFormat(number, "Percent", "number")).toBe("123,456.7%");- expect(applyFormat(number, "Scientific", "number")).toBe(- prettyScientificNumber(1234.567, { shouldRound: true }),+ expect(applyFormat(number, { format: "Auto", dataType: "number" })).toBe(+ "1,234.57",);- expect(applyFormat(number, "Engineering", "number")).toBe(- prettyEngineeringNumber(1234.567),- );- expect(applyFormat(number, "Integer", "number")).toBe("1,235");+ expect(+ applyFormat(number, { format: "Percent", dataType: "number" }),+ ).toBe("123,456.7%");+ expect(+ applyFormat(number, {+ format: "Scientific",+ dataType: "number",+ }),+ ).toBe(prettyScientificNumber(1234.567, { shouldRound: true }));+ expect(+ applyFormat(number, {+ format: "Engineering",+ dataType: "number",+ }),+ ).toBe(prettyEngineeringNumber(1234.567));+ expect(+ applyFormat(number, { format: "Integer", dataType: "number" }),+ ).toBe("1,235");});});describe("string formatting", () => {it("should format string values correctly", () => {const str = "hello world";- expect(applyFormat(str, "Uppercase", "string")).toBe("HELLO WORLD");- expect(applyFormat(str, "Lowercase", "string")).toBe("hello world");- expect(applyFormat(str, "Capitalize", "string")).toBe("Hello world");- expect(applyFormat(str, "Title", "string")).toBe("Hello World");+ expect(+ applyFormat(str, { format: "Uppercase", dataType: "string" }),+ ).toBe("HELLO WORLD");+ expect(+ applyFormat(str, { format: "Lowercase", dataType: "string" }),+ ).toBe("hello world");+ expect(+ applyFormat(str, { format: "Capitalize", dataType: "string" }),+ ).toBe("Hello world");+ expect(applyFormat(str, { format: "Title", dataType: "string" })).toBe(+ "Hello World",+ );});});describe("boolean formatting", () => {it("should format boolean values correctly", () => {- expect(applyFormat(true, "Yes/No", "boolean")).toBe("Yes");- expect(applyFormat(false, "Yes/No", "boolean")).toBe("No");- expect(applyFormat(true, "On/Off", "boolean")).toBe("On");- expect(applyFormat(false, "On/Off", "boolean")).toBe("Off");+ expect(applyFormat(true, { format: "Yes/No", dataType: "boolean" })).toBe(+ "Yes",+ );+ expect(+ applyFormat(false, { format: "Yes/No", dataType: "boolean" }),+ ).toBe("No");+ expect(applyFormat(true, { format: "On/Off", dataType: "boolean" })).toBe(+ "On",+ );+ expect(+ applyFormat(false, { format: "On/Off", dataType: "boolean" }),+ ).toBe("Off");});});it("should return the original value for unknown data types or formats", () => {- expect(applyFormat("some value", "Auto", "unknown")).toBe("some value");- expect(applyFormat(123, "Auto", "unknown")).toBe(123);+ expect(+ applyFormat("some value", { format: "Auto", dataType: "unknown" }),+ ).toBe("some value");+ expect(applyFormat(123, { format: "Auto", dataType: "unknown" })).toBe(123);});});diff --git a/frontend/src/components/data-table/cell-selection/__tests__/feature.test.ts b/frontend/src/components/data-table/cell-selection/__tests__/feature.test.tsindex d45d50d9a4..c1e5ed6e4b 100644--- a/frontend/src/components/data-table/cell-selection/__tests__/feature.test.ts+++ b/frontend/src/components/data-table/cell-selection/__tests__/feature.test.ts@@ -34,7 +34,15 @@ describe("CellSelectionFeature", () => {return { table, state };};- const createMockCell = (rowId: string, columnId: string, table: any) => {+ const createMockCell = ({+ rowId,+ columnId,+ table,+ }: {+ rowId: string;+ columnId: string;+ table: any;+ }) => {// Create mock rowconst row: Partial<Row<any>> = {id: rowId,@@ -63,7 +71,11 @@ describe("CellSelectionFeature", () => {describe("toggleSelected", () => {it("should add cell to selection when not selected", () => {const { table } = createMockTable();- const { cell } = createMockCell("row1", "col1", table);+ const { cell } = createMockCell({+ rowId: "row1",+ columnId: "col1",+ table,+ });cell.toggleSelected!(true);@@ -83,7 +95,11 @@ describe("CellSelectionFeature", () => {{ rowId: "row2", columnName: "col1" },];- const { cell } = createMockCell("row1", "col1", table);+ const { cell } = createMockCell({+ rowId: "row1",+ columnId: "col1",+ table,+ });// Deselect the cellcell.toggleSelected!(false);@@ -105,7 +121,11 @@ describe("CellSelectionFeature", () => {{ rowId: "row1", columnName: "col3" },];- const { cell } = createMockCell("row1", "col1", table);+ const { cell } = createMockCell({+ rowId: "row1",+ columnId: "col1",+ table,+ });// Deselect the cellcell.toggleSelected!(false);@@ -127,7 +147,11 @@ describe("CellSelectionFeature", () => {{ rowId: "row3", columnName: "col1" },];- const { cell } = createMockCell("row1", "col1", table);+ const { cell } = createMockCell({+ rowId: "row1",+ columnId: "col1",+ table,+ });// Deselect the cellcell.toggleSelected!(false);@@ -141,7 +165,11 @@ describe("CellSelectionFeature", () => {it("should toggle cell selection correctly", () => {const { table } = createMockTable();- const { cell } = createMockCell("row1", "col1", table);+ const { cell } = createMockCell({+ rowId: "row1",+ columnId: "col1",+ table,+ });// First selectcell.toggleSelected!();diff --git a/frontend/src/components/data-table/charts/charts.tsx b/frontend/src/components/data-table/charts/charts.tsxindex 35082459ee..b177cc812d 100644--- a/frontend/src/components/data-table/charts/charts.tsx+++ b/frontend/src/components/data-table/charts/charts.tsx@@ -109,11 +109,15 @@ export const TablePanel: React.FC<TablePanelProps> = ({setTabNum(tabNum - 1);};- const saveTabChart = (- tabName: TabName,- chartType: ChartType,- chartConfig: ChartSchemaType,- ) => {+ const saveTabChart = ({+ tabName,+ chartType,+ chartConfig,+ }: {+ tabName: TabName;+ chartType: ChartType;+ chartConfig: ChartSchemaType;+ }) => {if (!cellId) {return;}@@ -198,7 +202,11 @@ export const TablePanel: React.FC<TablePanelProps> = ({</TabsContent>{tabs.map((tab, idx) => {const saveChart = (formValues: ChartSchemaType) => {- saveTabChart(tab.tabName, tab.chartType, formValues);+ saveTabChart({+ tabName: tab.tabName,+ chartType: tab.chartType,+ chartConfig: formValues,+ });};const saveChartType = (chartType: ChartType) => {saveTabChartType(tab.tabName, chartType);diff --git a/frontend/src/components/data-table/charts/components/form-fields.tsx b/frontend/src/components/data-table/charts/components/form-fields.tsxindex eddc632ac1..a6d49d01a3 100644--- a/frontend/src/components/data-table/charts/components/form-fields.tsx+++ b/frontend/src/components/data-table/charts/components/form-fields.tsx@@ -649,11 +649,15 @@ export const AggregationSelect = ({return <span className="text-xs text-muted-foreground pr-10">{text}</span>;};- const renderSelectItem = (- value: string,- Icon: React.ElementType,- subtitle: React.ReactNode,- ) => {+ const renderSelectItem = ({+ value,+ Icon,+ subtitle,+ }: {+ value: string;+ Icon: React.ElementType;+ subtitle: React.ReactNode;+ }) => {return (<SelectItemkey={value}@@ -669,11 +673,15 @@ export const AggregationSelect = ({);};- const handleFieldChange = (- value: string,- previousValue: string,- onChange: (value: string) => void,- ) => {+ const handleFieldChange = ({+ value,+ previousValue,+ onChange,+ }: {+ value: string;+ previousValue: string;+ onChange: (value: string) => void;+ }) => {// Special handling for binning, as this is not a valid aggregationif (value === BIN_AGGREGATION) {form.setValue(binFieldName, true);@@ -700,7 +708,11 @@ export const AggregationSelect = ({NONE_VALUE).toString()}onValueChange={(value) => {- handleFieldChange(value, field.value, field.onChange);+ handleFieldChange({+ value,+ previousValue: field.value,+ onChange: field.onChange,+ });}}><SelectTrigger variant="ghost">@@ -714,7 +726,11 @@ export const AggregationSelect = ({const subtitle = renderSubtitle(AGGREGATION_TYPE_DESCRIPTIONS[agg],);- const selectItem = renderSelectItem(agg, Icon, subtitle);+ const selectItem = renderSelectItem({+ value: agg,+ Icon,+ subtitle,+ });if (agg === BIN_AGGREGATION) {if (!isBinningAllowed) {return null;diff --git a/frontend/src/components/data-table/column-explorer-panel/column-explorer.tsx b/frontend/src/components/data-table/column-explorer-panel/column-explorer.tsxindex 53ca5c6593..1488ec2eb6 100644--- a/frontend/src/components/data-table/column-explorer-panel/column-explorer.tsx+++ b/frontend/src/components/data-table/column-explorer-panel/column-explorer.tsx@@ -202,7 +202,11 @@ const ColumnPreview = ({const errorState =previewError &&- renderPreviewError(previewError, missing_packages, refetchPreview);+ renderPreviewError({+ error: previewError,+ missingPackages: missing_packages,+ refetchPreview,+ });const previewStats = stats && renderStats(stats, dataType);diff --git a/frontend/src/components/data-table/column-formatting/feature.ts b/frontend/src/components/data-table/column-formatting/feature.tsindex 81b1bcf8e9..5f26f5a79c 100644--- a/frontend/src/components/data-table/column-formatting/feature.ts+++ b/frontend/src/components/data-table/column-formatting/feature.ts@@ -74,7 +74,7 @@ export const ColumnFormattingFeature: TableFeature = {const dataType = column.columnDef.meta?.dataType;const format = column.getColumnFormatting?.();if (format) {- return applyFormat(value, format, dataType);+ return applyFormat(value, { format, dataType });}return value;};@@ -109,9 +109,12 @@ const integerFormatter = new Intl.NumberFormat(undefined, {// Apply formatting to a value given a format and data typeexport const applyFormat = (value: unknown,- format: FormatOption,- dataType: DataType | undefined,+ options: {+ format: FormatOption;+ dataType: DataType | undefined;+ },) => {+ const { format, dataType } = options;// If the value is null, return an empty stringif (value === null || value === undefined || value === "") {return "";@@ -198,21 +201,46 @@ export function formattingExample(): string | number | undefined | null {switch (format) {case "Date":- return String(applyFormat(new Date(), "Date", "date"));+ return String(+ applyFormat(new Date(), { format: "Date", dataType: "date" }),+ );case "Datetime":- return String(applyFormat(new Date(), "Datetime", "date"));+ return String(+ applyFormat(new Date(), {+ format: "Datetime",+ dataType: "date",+ }),+ );case "Time":- return String(applyFormat(new Date(), "Time", "date"));+ return String(+ applyFormat(new Date(), { format: "Time", dataType: "date" }),+ );case "Percent":- return String(applyFormat(0.1234, "Percent", "number"));+ return String(+ applyFormat(0.1234, { format: "Percent", dataType: "number" }),+ );case "Scientific":- return String(applyFormat(12_345_678_910, "Scientific", "number"));+ return String(+ applyFormat(12_345_678_910, {+ format: "Scientific",+ dataType: "number",+ }),+ );case "Engineering":- return String(applyFormat(12_345_678_910, "Engineering", "number"));+ return String(+ applyFormat(12_345_678_910, {+ format: "Engineering",+ dataType: "number",+ }),+ );case "Integer":- return String(applyFormat(1234.567, "Integer", "number"));+ return String(+ applyFormat(1234.567, { format: "Integer", dataType: "number" }),+ );case "Auto":- return String(applyFormat(1234.567, "Auto", "number"));+ return String(+ applyFormat(1234.567, { format: "Auto", dataType: "number" }),+ );default:return null;}diff --git a/frontend/src/components/data-table/row-viewer-panel/__tests__/filter-rows.test.ts b/frontend/src/components/data-table/row-viewer-panel/__tests__/filter-rows.test.tsindex a936122b9f..5c1399022e 100644--- a/frontend/src/components/data-table/row-viewer-panel/__tests__/filter-rows.test.ts+++ b/frontend/src/components/data-table/row-viewer-panel/__tests__/filter-rows.test.ts@@ -5,17 +5,29 @@ import { inSearchQuery } from "../row-viewer";describe("inSearchQuery", () => {it("should filter rows based on column name", () => {- const result = inSearchQuery("name", "John", "name");+ const result = inSearchQuery({+ columnName: "name",+ columnValue: "John",+ searchQuery: "name",+ });expect(result).toBe(true);});it("should filter rows based on cell value", () => {- const result = inSearchQuery("name", "John", "John");+ const result = inSearchQuery({+ columnName: "name",+ columnValue: "John",+ searchQuery: "John",+ });expect(result).toBe(true);});it("should return false when no matches found", () => {- const result = inSearchQuery("name", "John", "xyz");+ const result = inSearchQuery({+ columnName: "name",+ columnValue: "John",+ searchQuery: "xyz",+ });expect(result).toBe(false);});@@ -24,27 +36,47 @@ describe("inSearchQuery", () => {data: { key: "value" },};- const result = inSearchQuery("data", rowValues, "value");+ const result = inSearchQuery({+ columnName: "data",+ columnValue: rowValues,+ searchQuery: "value",+ });expect(result).toBe(true);});it("should be case insensitive", () => {- const result = inSearchQuery("name", "John", "john");+ const result = inSearchQuery({+ columnName: "name",+ columnValue: "John",+ searchQuery: "john",+ });expect(result).toBe(true);});it("should handle partial matches", () => {- const result = inSearchQuery("name", "Johnathan Clark", "john");+ const result = inSearchQuery({+ columnName: "name",+ columnValue: "Johnathan Clark",+ searchQuery: "john",+ });expect(result).toBe(true);});it("should handle empty search query", () => {- const result = inSearchQuery("name", "John", "");+ const result = inSearchQuery({+ columnName: "name",+ columnValue: "John",+ searchQuery: "",+ });expect(result).toBe(true);});it("should handle null values", () => {- const result = inSearchQuery("name", null, "null");+ const result = inSearchQuery({+ columnName: "name",+ columnValue: null,+ searchQuery: "null",+ });expect(result).toBe(true);});});diff --git a/frontend/src/components/data-table/row-viewer-panel/row-viewer.tsx b/frontend/src/components/data-table/row-viewer-panel/row-viewer.tsxindex ba18c5f566..7196443962 100644--- a/frontend/src/components/data-table/row-viewer-panel/row-viewer.tsx+++ b/frontend/src/components/data-table/row-viewer-panel/row-viewer.tsx@@ -189,7 +189,7 @@ export const RowViewerPanel: React.FC<RowViewerPanelProps> = ({{fieldTypes?.map(([columnName, [dataType, externalType]]) => {const columnValue = rowValues[columnName];- if (!inSearchQuery(columnName, columnValue, searchQuery)) {+ if (!inSearchQuery({ columnName, columnValue, searchQuery })) {return null;}@@ -330,11 +330,15 @@ export const RowViewerPanel: React.FC<RowViewerPanelProps> = ({);};-export function inSearchQuery(- columnName: string,- columnValue: unknown,- searchQuery: string,-) {+export function inSearchQuery({+ columnName,+ columnValue,+ searchQuery,+}: {+ columnName: string;+ columnValue: unknown;+ searchQuery: string;+}) {const colName = columnName.toLowerCase();const searchQueryLower = searchQuery.toLowerCase();diff --git a/frontend/src/components/datasources/__tests__/utils.test.ts b/frontend/src/components/datasources/__tests__/utils.test.tsindex 423f119f40..8f67d5fcd5 100644--- a/frontend/src/components/datasources/__tests__/utils.test.ts+++ b/frontend/src/components/datasources/__tests__/utils.test.ts@@ -19,7 +19,7 @@ describe("sqlCode", () => {} as DataTableColumn;it("should generate basic SQL without sqlTableContext", () => {- const result = sqlCode(mockTable, mockColumn.name);+ const result = sqlCode({ table: mockTable, columnName: mockColumn.name });expect(result).toBe("_df = mo.sql(f'SELECT \"email\" FROM users LIMIT 100')",);@@ -34,7 +34,11 @@ describe("sqlCode", () => {database: "mydb",};- const result = sqlCode(mockTable, mockColumn.name, sqlTableContext);+ const result = sqlCode({+ table: mockTable,+ columnName: mockColumn.name,+ sqlTableContext,+ });expect(result).toBe('_df = mo.sql(f"SELECT email FROM users LIMIT 100")');});@@ -47,7 +51,11 @@ describe("sqlCode", () => {database: "mydb",};- const result = sqlCode(mockTable, mockColumn.name, sqlTableContext);+ const result = sqlCode({+ table: mockTable,+ columnName: mockColumn.name,+ sqlTableContext,+ });expect(result).toBe('_df = mo.sql(f"SELECT email FROM analytics.users LIMIT 100")',);@@ -62,7 +70,11 @@ describe("sqlCode", () => {database: "mydb",};- const result = sqlCode(mockTable, mockColumn.name, sqlTableContext);+ const result = sqlCode({+ table: mockTable,+ columnName: mockColumn.name,+ sqlTableContext,+ });expect(result).toBe('_df = mo.sql(f"SELECT email FROM users LIMIT 100", engine=snowflake)',);@@ -77,7 +89,11 @@ describe("sqlCode", () => {database: "mydb",};- const result = sqlCode(mockTable, mockColumn.name, sqlTableContext);+ const result = sqlCode({+ table: mockTable,+ columnName: mockColumn.name,+ sqlTableContext,+ });expect(result).toBe('_df = mo.sql(f"SELECT email FROM sales.users LIMIT 100", engine=bigquery)',);@@ -92,7 +108,11 @@ describe("sqlCode", () => {database: "remote",};- const result = sqlCode(mockTable, mockColumn.name, sqlTableContext);+ const result = sqlCode({+ table: mockTable,+ columnName: mockColumn.name,+ sqlTableContext,+ });expect(result).toBe('_df = mo.sql(f"SELECT email FROM remote.users LIMIT 100")',);@@ -107,7 +127,11 @@ describe("sqlCode", () => {database: "remote",};- const result = sqlCode(mockTable, mockColumn.name, sqlTableContext);+ const result = sqlCode({+ table: mockTable,+ columnName: mockColumn.name,+ sqlTableContext,+ });expect(result).toBe('_df = mo.sql(f"SELECT email FROM remote.sales.users LIMIT 100", engine=bigquery)',);@@ -121,7 +145,11 @@ describe("sqlCode", () => {database: "mydb",};- const result = sqlCode(mockTable, mockColumn.name, sqlTableContext);+ const result = sqlCode({+ table: mockTable,+ columnName: mockColumn.name,+ sqlTableContext,+ });expect(result).toBe('_df = mo.sql(f"SELECT email FROM users LIMIT 100")');const sqlTableContext2: SQLTableContext = {@@ -131,7 +159,11 @@ describe("sqlCode", () => {database: "another_db",};- const result2 = sqlCode(mockTable, mockColumn.name, sqlTableContext2);+ const result2 = sqlCode({+ table: mockTable,+ columnName: mockColumn.name,+ sqlTableContext: sqlTableContext2,+ });expect(result2).toBe('_df = mo.sql(f"SELECT email FROM another_db.users LIMIT 100")',);diff --git a/frontend/src/components/datasources/column-preview.tsx b/frontend/src/components/datasources/column-preview.tsxindex 835e0bb85f..2eb592ba7c 100644--- a/frontend/src/components/datasources/column-preview.tsx+++ b/frontend/src/components/datasources/column-preview.tsx@@ -74,7 +74,9 @@ export const DatasetColumnPreview: React.FC<{variant="outline"size="xs"onClick={Events.stopPropagation(() => {- onAddColumnChart(sqlCode(table, column.name, sqlTableContext));+ onAddColumnChart(+ sqlCode({ table, columnName: column.name, sqlTableContext }),+ );})}><PlusSquareIcon className="h-3 w-3 mr-1" /> Add SQL cell@@ -97,7 +99,11 @@ export const DatasetColumnPreview: React.FC<{const error =preview.error &&- renderPreviewError(preview.error, preview.missing_packages, previewColumn);+ renderPreviewError({+ error: preview.error,+ missingPackages: preview.missing_packages,+ refetchPreview: previewColumn,+ });const stats = preview.stats && renderStats(preview.stats, column.type);@@ -115,7 +121,9 @@ export const DatasetColumnPreview: React.FC<{size="icon"className="z-10 bg-background absolute right-1 -top-1"onClick={Events.stopPropagation(() => {- onAddColumnChart(sqlCode(table, column.name, sqlTableContext));+ onAddColumnChart(+ sqlCode({ table, columnName: column.name, sqlTableContext }),+ );})}><PlusSquareIcon className="h-3 w-3" />@@ -138,17 +146,21 @@ export const DatasetColumnPreview: React.FC<{);};-export function renderPreviewError(- error: string,- missing_packages?: string[] | null,- refetchPreview?: () => void,-) {+export function renderPreviewError({+ error,+ missingPackages,+ refetchPreview,+}: {+ error: string;+ missingPackages?: string[] | null;+ refetchPreview?: () => void;+}) {return (<div className="text-xs text-muted-foreground p-2 border border-border rounded flex items-center justify-between"><span>{error}</span>- {missing_packages && (+ {missingPackages && (<InstallPackageButton- packages={missing_packages}+ packages={missingPackages}showMaxPackages={1}className="w-32"onInstall={refetchPreview}diff --git a/frontend/src/components/datasources/datasources.tsx b/frontend/src/components/datasources/datasources.tsxindex 283af913d2..fb80506eb0 100644--- a/frontend/src/components/datasources/datasources.tsx+++ b/frontend/src/components/datasources/datasources.tsx@@ -544,7 +544,7 @@ const DatasetTableItem: React.FC<{}if (sqlTableContext) {- return sqlCode(table, "*", sqlTableContext);+ return sqlCode({ table, columnName: "*", sqlTableContext });}switch (table.source_type) {@@ -552,7 +552,7 @@ const DatasetTableItem: React.FC<{return `mo.ui.table(${table.name})`;case "duckdb":case "connection":- return sqlCode(table, "*", sqlTableContext);+ return sqlCode({ table, columnName: "*", sqlTableContext });default:logNever(table.source_type);return "";diff --git a/frontend/src/components/datasources/utils.ts b/frontend/src/components/datasources/utils.tsindex ef4d9f1909..0be4cdfd56 100644--- a/frontend/src/components/datasources/utils.ts+++ b/frontend/src/components/datasources/utils.ts@@ -9,11 +9,15 @@ export function isSchemaless(schemaName: string) {return schemaName === "";}-export function sqlCode(- table: DataTable,- columnName: string,- sqlTableContext?: SQLTableContext,-) {+export function sqlCode({+ table,+ columnName,+ sqlTableContext,+}: {+ table: DataTable;+ columnName: string;+ sqlTableContext?: SQLTableContext;+}) {if (sqlTableContext) {const { engine, schema, defaultSchema, defaultDatabase, database } =sqlTableContext;diff --git a/frontend/src/components/dependency-graph/dependency-graph-tree.tsx b/frontend/src/components/dependency-graph/dependency-graph-tree.tsxindex 13d3736bd0..ea8482805f 100644--- a/frontend/src/components/dependency-graph/dependency-graph-tree.tsx+++ b/frontend/src/components/dependency-graph/dependency-graph-tree.tsx@@ -59,7 +59,9 @@ export const DependencyGraphTree: React.FC<PropsWithChildren<Props>> = ({variables,settings.hidePureMarkdown,);- elements = layoutElements(elements.nodes, elements.edges, {+ elements = layoutElements({+ nodes: elements.nodes,+ edges: elements.edges,direction: layoutDirection,});@@ -74,7 +76,9 @@ export const DependencyGraphTree: React.FC<PropsWithChildren<Props>> = ({const syncChanges = useEvent((elements: { nodes: Array<Node<NodeData>>; edges: Edge[] }) => {// Layout the elements- const result = layoutElements(elements.nodes, elements.edges, {+ const result = layoutElements({+ nodes: elements.nodes,+ edges: elements.edges,direction: layoutDirection,});setNodes(result.nodes);diff --git a/frontend/src/components/dependency-graph/utils/layout.ts b/frontend/src/components/dependency-graph/utils/layout.tsindex f9d5d1cce7..9e6d059be0 100644--- a/frontend/src/components/dependency-graph/utils/layout.ts+++ b/frontend/src/components/dependency-graph/utils/layout.ts@@ -5,13 +5,17 @@ import type { LayoutDirection } from "../types";const g = new graphlib.Graph().setDefaultEdgeLabel(() => ({}));-export const layoutElements = (- nodes: Node[],- edges: Edge[],- options: { direction: LayoutDirection },-) => {+export const layoutElements = ({+ nodes,+ edges,+ direction,+}: {+ nodes: Node[];+ edges: Edge[];+ direction: LayoutDirection;+}) => {g.setGraph({- rankdir: options.direction,+ rankdir: direction,nodesep: 150,ranksep: 200,// So far, longest-path seems to give the best results as trees arediff --git a/frontend/src/components/editor/Cell.tsx b/frontend/src/components/editor/Cell.tsxindex 2a3e62e12a..80d6322425 100644--- a/frontend/src/components/editor/Cell.tsx+++ b/frontend/src/components/editor/Cell.tsx@@ -127,19 +127,29 @@ function useCellCompletion(/*** Hook for handling cell hotkeys*/-function useCellHotkeys(- cellRef: React.RefObject<HTMLDivElement | null> | null,- cellId: CellId,- runCell: () => void,- actions: CellComponentActions,- canMoveX: boolean,- cellConfig: CellConfig,- editorView: React.RefObject<EditorView | null>,+function useCellHotkeys({+ cellRef,+ cellId,+ runCell,+ actions,+ canMoveX,+ cellConfig,+ editorView,+ setAiCompletionCell,+ cellActionDropdownRef,+}: {+ cellRef: React.RefObject<HTMLDivElement | null> | null;+ cellId: CellId;+ runCell: () => void;+ actions: CellComponentActions;+ canMoveX: boolean;+ cellConfig: CellConfig;+ editorView: React.RefObject<EditorView | null>;setAiCompletionCell: ReturnType<typeof useSetAtom<typeof aiCompletionCellAtom>- >,- cellActionDropdownRef: React.RefObject<CellActionsDropdownHandle | null>,-) {+ >;+ cellActionDropdownRef: React.RefObject<CellActionsDropdownHandle | null>;+}) {useHotkeysOnElement(cellRef, {"cell.run": runCell,"cell.runAndNewBelow": () => {@@ -203,14 +213,21 @@ function useCellHotkeys(/*** Hook for handling cell keyboard listeners*/-function useCellKeyboardListener(- cellRef: React.RefObject<HTMLDivElement | null> | null,- cellId: CellId,- actions: CellComponentActions,- showHiddenMarkdownCode: () => void,- userConfig: UserConfig,- isCellCodeShown: boolean,-) {+function useCellKeyboardListener({+ cellRef,+ cellId,+ actions,+ showHiddenMarkdownCode,+ userConfig,+ isCellCodeShown,+}: {+ cellRef: React.RefObject<HTMLDivElement | null> | null;+ cellId: CellId;+ actions: CellComponentActions;+ showHiddenMarkdownCode: () => void;+ userConfig: UserConfig;+ isCellCodeShown: boolean;+}) {useKeydownOnElement(cellRef, {ArrowDown: (evt) => {if (evt && Events.fromInput(evt)) {@@ -256,12 +273,17 @@ function useCellKeyboardListener(/*** Hook for handling hidden cell logic*/-function useCellHiddenLogic(- cellConfig: CellConfig,- languageAdapter: LanguageAdapterType | undefined,- editorView: React.RefObject<EditorView | null>,- editorViewParentRef: React.RefObject<HTMLDivElement | null>,-) {+function useCellHiddenLogic({+ cellConfig,+ languageAdapter,+ editorView,+ editorViewParentRef,+}: {+ cellConfig: CellConfig;+ languageAdapter: LanguageAdapterType | undefined;+ editorView: React.RefObject<EditorView | null>;+ editorViewParentRef: React.RefObject<HTMLDivElement | null>;+}) {const [temporarilyVisible, setTemporarilyVisible] = useState(false);// The cell code is shown if the cell is not configured to be hidden or if the code is temporarily visible (i.e. when focused).@@ -615,15 +637,15 @@ const EditableCellComponent = ({isMarkdownCodeHidden,temporarilyShowCode,showHiddenMarkdownCode,- } = useCellHiddenLogic(+ } = useCellHiddenLogic({cellConfig,languageAdapter,editorView,editorViewParentRef,- );+ });// Hotkey listeners- useCellHotkeys(+ useCellHotkeys({cellRef,cellId,runCell,@@ -633,17 +655,17 @@ const EditableCellComponent = ({editorView,setAiCompletionCell,cellActionDropdownRef,- );+ });// Other keyboard listeners- useCellKeyboardListener(+ useCellKeyboardListener({cellRef,cellId,actions,showHiddenMarkdownCode,userConfig,isCellCodeShown,- );+ });const canCollapse = canCollapseOutline(outline);const hasOutput = !isOutputEmpty(output);@@ -1179,7 +1201,7 @@ const SetupCellComponent = ({);// Hotkey listeners- useCellHotkeys(+ useCellHotkeys({cellRef,cellId,runCell,@@ -1189,17 +1211,17 @@ const SetupCellComponent = ({editorView,setAiCompletionCell,cellActionDropdownRef,- );+ });// Other keyboard listeners- useCellKeyboardListener(+ useCellKeyboardListener({cellRef,cellId,actions,- Functions.NOOP,+ showHiddenMarkdownCode: Functions.NOOP,userConfig,- true,- );+ isCellCodeShown: true,+ });const hasOutput = !isOutputEmpty(output);const hasConsoleOutput = consoleOutputs.length > 0;diff --git a/frontend/src/components/editor/actions/useCellActionButton.tsx b/frontend/src/components/editor/actions/useCellActionButton.tsxindex e487fcc6ba..4f087476a6 100644--- a/frontend/src/components/editor/actions/useCellActionButton.tsx+++ b/frontend/src/components/editor/actions/useCellActionButton.tsx@@ -274,7 +274,10 @@ export function useCellActionButtons({ cell }: Props) {return;}maybeAddMarimoImport(autoInstantiate, createCell);- switchLanguage(editorView, "markdown", { keepCodeAsIs: false });+ switchLanguage(editorView, {+ language: "markdown",+ keepCodeAsIs: false,+ });},},{@@ -286,7 +289,7 @@ export function useCellActionButtons({ cell }: Props) {return;}maybeAddMarimoImport(autoInstantiate, createCell);- switchLanguage(editorView, "sql", { keepCodeAsIs: false });+ switchLanguage(editorView, { language: "sql", keepCodeAsIs: false });},},{diff --git a/frontend/src/components/editor/cell/RunButton.tsx b/frontend/src/components/editor/cell/RunButton.tsxindex eed00544d0..e0bae06399 100644--- a/frontend/src/components/editor/cell/RunButton.tsx+++ b/frontend/src/components/editor/cell/RunButton.tsx@@ -10,12 +10,17 @@ import type { WebSocketState } from "@/core/websocket/types";import { renderShortcut } from "../../shortcuts/renderShortcut";import { ToolbarItem } from "./toolbar";-function computeColor(- connectionState: WebSocketState,- needsRun: boolean,- loading: boolean,- inactive: boolean,-) {+function computeColor({+ connectionState,+ needsRun,+ loading,+ inactive,+}: {+ connectionState: WebSocketState;+ needsRun: boolean;+ loading: boolean;+ inactive: boolean;+}) {if (isAppInteractionDisabled(connectionState)) {return "disabled";}@@ -44,7 +49,12 @@ export const RunButton = (props: {isAppInteractionDisabled(connectionState) ||loading ||(!config.disabled && blockedStatus && !edited);- const variant = computeColor(connectionState, needsRun, loading, inactive);+ const variant = computeColor({+ connectionState,+ needsRun,+ loading,+ inactive,+ });if (config.disabled) {return (diff --git a/frontend/src/components/editor/cell/code/cell-editor.tsx b/frontend/src/components/editor/cell/code/cell-editor.tsxindex 3b074007d2..c8534042e2 100644--- a/frontend/src/components/editor/cell/code/cell-editor.tsx+++ b/frontend/src/components/editor/cell/code/cell-editor.tsx@@ -259,7 +259,9 @@ const CellEditorInternal = ({setEditorView(ev);// Initialize the language adapterif (!rtcEnabled) {- switchLanguage(ev, getInitialLanguageAdapter(ev.state).type);+ switchLanguage(ev, {+ language: getInitialLanguageAdapter(ev.state).type,+ });}});@@ -278,15 +280,16 @@ const CellEditorInternal = ({editorViewRef.current.dispatch({effects: [StateEffect.reconfigure.of([extensions]),- reconfigureLanguageEffect(- editorViewRef.current,- userConfig.completion,- new OverridingHotkeyProvider(userConfig.keymap.overrides ?? {}),- {+ reconfigureLanguageEffect(editorViewRef.current, {+ completionConfig: userConfig.completion,+ hotkeysProvider: new OverridingHotkeyProvider(+ userConfig.keymap.overrides ?? {},+ ),+ lspConfig: {...userConfig.language_servers,diagnostics: userConfig.diagnostics,},- ),+ }),],});});@@ -319,7 +322,9 @@ const CellEditorInternal = ({});// Initialize the language adapterif (!rtcEnabled) {- switchLanguage(ev, getInitialLanguageAdapter(ev.state).type);+ switchLanguage(ev, {+ language: getInitialLanguageAdapter(ev.state).type,+ });}setEditorView(ev);// Clear the serialized state so that we don't re-create the editor next timediff --git a/frontend/src/components/editor/cell/code/language-toggle.tsx b/frontend/src/components/editor/cell/code/language-toggle.tsxindex 40dcb8b816..88482eadec 100644--- a/frontend/src/components/editor/cell/code/language-toggle.tsx+++ b/frontend/src/components/editor/cell/code/language-toggle.tsx@@ -112,7 +112,7 @@ export const LanguageToggle: React.FC<Props> = ({if (!editorView) {return;}- switchLanguage(editorView, toType);+ switchLanguage(editorView, { language: toType });onAfterToggle();};diff --git a/frontend/src/components/editor/controls/command-palette.tsx b/frontend/src/components/editor/controls/command-palette.tsxindex aa9f67e327..b6c2845f97 100644--- a/frontend/src/components/editor/controls/command-palette.tsx+++ b/frontend/src/components/editor/controls/command-palette.tsx@@ -101,12 +101,17 @@ export const CommandPalette = () => {);};- const renderCommandItem = (- label: string,- handle: () => void,- props: { disabled?: boolean; tooltip?: React.ReactNode } = {},- hotkey?: HotkeyAction,- ) => {+ const renderCommandItem = ({+ label,+ handle,+ props = {},+ hotkey,+ }: {+ label: string;+ handle: () => void;+ props?: { disabled?: boolean; tooltip?: React.ReactNode };+ hotkey?: HotkeyAction;+ }) => {return (<CommandItemdisabled={props.disabled}@@ -152,11 +157,14 @@ export const CommandPalette = () => {}// Other actionif (action && !isParentAction(action)) {- return renderCommandItem(- action.label,- action.handleHeadless || action.handle,- { disabled: action.disabled, tooltip: action.tooltip },- );+ return renderCommandItem({+ label: action.label,+ handle: action.handleHeadless || action.handle,+ props: {+ disabled: action.disabled,+ tooltip: action.tooltip,+ },+ });}return null;})}@@ -179,21 +187,21 @@ export const CommandPalette = () => {if (recentCommandsSet.has(action.label)) {return null; // Don't show recent commands in the main list}- return renderCommandItem(- action.label,- action.handleHeadless || action.handle,- { disabled: action.disabled, tooltip: action.tooltip },- );+ return renderCommandItem({+ label: action.label,+ handle: action.handleHeadless || action.handle,+ props: { disabled: action.disabled, tooltip: action.tooltip },+ });})}{cellActions.map((action) => {if (recentCommandsSet.has(action.label)) {return null; // Don't show recent commands in the main list}- return renderCommandItem(- `Cell > ${action.label}`,- action.handleHeadless || action.handle,- { disabled: action.disabled, tooltip: action.tooltip },- );+ return renderCommandItem({+ label: `Cell > ${action.label}`,+ handle: action.handleHeadless || action.handle,+ props: { disabled: action.disabled, tooltip: action.tooltip },+ });})}</CommandGroup></CommandList>diff --git a/frontend/src/components/editor/renderers/plugins.ts b/frontend/src/components/editor/renderers/plugins.tsindex d62121ecdd..425d2cb045 100644--- a/frontend/src/components/editor/renderers/plugins.ts+++ b/frontend/src/components/editor/renderers/plugins.ts@@ -14,11 +14,15 @@ export const cellRendererPlugins: Array<ICellRendererPlugin<any, any>> = [VerticalLayoutPlugin,];-export function deserializeLayout(- type: LayoutType,- data: unknown,- cells: CellData[],-) {+export function deserializeLayout({+ type,+ data,+ cells,+}: {+ type: LayoutType;+ data: unknown;+ cells: CellData[];+}) {const plugin = cellRendererPlugins.find((plugin) => plugin.type === type);if (plugin === undefined) {throw new Error(`Unknown layout type: ${type}`);diff --git a/frontend/src/components/variables/variables-table.tsx b/frontend/src/components/variables/variables-table.tsxindex ab483801d0..e61df5231f 100644--- a/frontend/src/components/variables/variables-table.tsx+++ b/frontend/src/components/variables/variables-table.tsx@@ -196,11 +196,15 @@ const COLUMNS = [* Sort the variables by the specified column sort* Defaults to the order they are defined in the notebook*/-function sortData(- variables: ResolvedVariable[],- sort: ColumnSort | undefined,- cellIdToIndex: Map<CellId, number>,-) {+function sortData({+ variables,+ sort,+ cellIdToIndex,+}: {+ variables: ResolvedVariable[];+ sort: ColumnSort | undefined;+ cellIdToIndex: Map<CellId, number>;+}) {// Default to sort by the cell that defined itif (!sort) {sort = { id: ColumnIds.defs, desc: false };@@ -251,7 +255,11 @@ export const VariableTable: React.FC<Props> = memo(const sortedVariables = useMemo(() => {const cellIdToIndex = new Map<CellId, number>();cellIds.forEach((id, index) => cellIdToIndex.set(id, index));- return sortData(resolvedVariables, sorting[0], cellIdToIndex);+ return sortData({+ variables: resolvedVariables,+ sort: sorting[0],+ cellIdToIndex,+ });}, [resolvedVariables, sorting, cellIds]);const table = useReactTable({diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.tsindex e7113963bc..39dd74a77c 100644--- a/frontend/src/core/cells/cells.ts+++ b/frontend/src/core/cells/cells.ts@@ -623,11 +623,15 @@ const {},clearSerializedEditorState: (state, action: { cellId: CellId }) => {const { cellId } = action;- return updateCellData(state, cellId, (cell) => {- return {- ...cell,- serializedEditorState: null,- };+ return updateCellData({+ state,+ cellId,+ cellReducer: (cell) => {+ return {+ ...cell,+ serializedEditorState: null,+ };+ },});},updateCellCode: (@@ -647,29 +651,37 @@ const {return state;}- return updateCellData(state, cellId, (cell) => {- // Formatting-only change means we can re-use the last code run- // if it was not previously edited. And we don't change the edited state.- return formattingChange- ? {- ...cell,- code: code,- lastCodeRun: cell.edited ? cell.lastCodeRun : code,- }- : {- ...cell,- code: code,- edited: code.trim() !== cell.lastCodeRun,- };+ return updateCellData({+ state,+ cellId,+ cellReducer: (cell) => {+ // Formatting-only change means we can re-use the last code run+ // if it was not previously edited. And we don't change the edited state.+ return formattingChange+ ? {+ ...cell,+ code: code,+ lastCodeRun: cell.edited ? cell.lastCodeRun : code,+ }+ : {+ ...cell,+ code: code,+ edited: code.trim() !== cell.lastCodeRun,+ };+ },});},updateCellName: (state, action: { cellId: CellId; name: string }) => {const { cellId, name } = action;- return updateCellData(state, cellId, (cell) => {- return {- ...cell,- name: name,- };+ return updateCellData({+ state,+ cellId,+ cellReducer: (cell) => {+ return {+ ...cell,+ name: name,+ };+ },});},updateCellConfig: (@@ -677,29 +689,45 @@ const {action: { cellId: CellId; config: Partial<CellConfig> },) => {const { cellId, config } = action;- return updateCellData(state, cellId, (cell) => {- return {- ...cell,- config: { ...cell.config, ...config },- };+ return updateCellData({+ state,+ cellId,+ cellReducer: (cell) => {+ return {+ ...cell,+ config: { ...cell.config, ...config },+ };+ },});},prepareForRun: (state, action: { cellId: CellId }) => {- const newState = updateCellRuntimeState(state, action.cellId, (cell) => {- return prepareCellForExecution(cell);+ const newState = updateCellRuntimeState({+ state,+ cellId: action.cellId,+ cellReducer: (cell) => {+ return prepareCellForExecution(cell);+ },});- return updateCellData(newState, action.cellId, (cell) => {- return {- ...cell,- edited: false,- lastCodeRun: cell.code.trim(),- };+ return updateCellData({+ state: newState,+ cellId: action.cellId,+ cellReducer: (cell) => {+ return {+ ...cell,+ edited: false,+ lastCodeRun: cell.code.trim(),+ };+ },});},handleCellMessage: (state, message: CellMessage) => {const cellId = message.cell_id as CellId;- const nextState = updateCellRuntimeState(state, cellId, (cell) => {- return transitionCell(cell, message);+ const nextState = updateCellRuntimeState({+ state,+ cellId,+ cellReducer: (cell) => {+ return transitionCell(cell, message);+ },});return {...nextState,@@ -748,11 +776,15 @@ const {let nextState = { ...state };- const cellReducer = (- cell: CellData | undefined,- code: string,- cellId: CellId,- ) => {+ const cellReducer = ({+ cell,+ code,+ cellId,+ }: {+ cell: CellData | undefined;+ code: string;+ cellId: CellId;+ }) => {if (!cell) {return createCell({id: cellId,@@ -805,7 +837,11 @@ const {...nextState,cellData: {...nextState.cellData,- [cellId]: cellReducer(nextState.cellData[cellId], code, cellId),+ [cellId]: cellReducer({+ cell: nextState.cellData[cellId],+ code,+ cellId,+ }),},};}@@ -817,27 +853,31 @@ const {action: { cellId: CellId; response: string; outputIndex: number },) => {const { cellId, response, outputIndex } = action;- return updateCellRuntimeState(state, cellId, (cell) => {- const consoleOutputs = [...cell.consoleOutputs];- const stdinOutput = consoleOutputs[outputIndex];- if (stdinOutput.channel !== "stdin") {- Logger.warn("Expected stdin output");- return cell;- }+ return updateCellRuntimeState({+ state,+ cellId,+ cellReducer: (cell) => {+ const consoleOutputs = [...cell.consoleOutputs];+ const stdinOutput = consoleOutputs[outputIndex];+ if (stdinOutput.channel !== "stdin") {+ Logger.warn("Expected stdin output");+ return cell;+ }- consoleOutputs[outputIndex] = {- channel: "stdin",- mimetype: stdinOutput.mimetype,- data: stdinOutput.data,- timestamp: stdinOutput.timestamp,- response,- };+ consoleOutputs[outputIndex] = {+ channel: "stdin",+ mimetype: stdinOutput.mimetype,+ data: stdinOutput.data,+ timestamp: stdinOutput.timestamp,+ response,+ };- return {- ...cell,- interrupted: false,- consoleOutputs,- };+ return {+ ...cell,+ interrupted: false,+ consoleOutputs,+ };+ },});},setCells: (state, cells: CellData[]) => {@@ -1203,21 +1243,29 @@ const {},clearCellOutput: (state, action: { cellId: CellId }) => {const { cellId } = action;- return updateCellRuntimeState(state, cellId, (cell) => ({- ...cell,- output: null,- consoleOutputs: [],- }));+ return updateCellRuntimeState({+ state,+ cellId,+ cellReducer: (cell) => ({+ ...cell,+ output: null,+ consoleOutputs: [],+ }),+ });},clearCellConsoleOutput: (state, action: { cellId: CellId }) => {const { cellId } = action;- return updateCellRuntimeState(state, cellId, (cell) => ({- ...cell,- // Remove everything except unresponsed stdin- consoleOutputs: cell.consoleOutputs.filter(- (output) => output.channel === "stdin" && output.response == null,- ),- }));+ return updateCellRuntimeState({+ state,+ cellId,+ cellReducer: (cell) => ({+ ...cell,+ // Remove everything except unresponsed stdin+ consoleOutputs: cell.consoleOutputs.filter(+ (output) => output.channel === "stdin" && output.response == null,+ ),+ }),+ });},clearAllCellOutputs: (state) => {const newCellRuntime = { ...state.cellRuntime };@@ -1239,11 +1287,15 @@ const {// First check if setup cell already existsif (SETUP_CELL_ID in state.cellData) {// Update existing setup cell- return updateCellData(state, SETUP_CELL_ID, (cell) => ({- ...cell,- code,- edited: code.trim() !== cell.lastCodeRun?.trim(),- }));+ return updateCellData({+ state,+ cellId: SETUP_CELL_ID,+ cellReducer: (cell) => ({+ ...cell,+ code,+ edited: code.trim() !== cell.lastCodeRun?.trim(),+ }),+ });}return {@@ -1275,11 +1327,15 @@ const {});// Helper function to update a cell in the array-function updateCellRuntimeState(- state: NotebookState,- cellId: CellId,- cellReducer: ReducerWithoutAction<CellRuntimeState>,-) {+function updateCellRuntimeState({+ state,+ cellId,+ cellReducer,+}: {+ state: NotebookState;+ cellId: CellId;+ cellReducer: ReducerWithoutAction<CellRuntimeState>;+}) {if (!(cellId in state.cellRuntime)) {Logger.warn(`Cell ${cellId} not found in state`);return state;@@ -1294,11 +1350,15 @@ function updateCellRuntimeState(};}-function updateCellData(- state: NotebookState,- cellId: CellId,- cellReducer: ReducerWithoutAction<CellData>,-) {+function updateCellData({+ state,+ cellId,+ cellReducer,+}: {+ state: NotebookState;+ cellId: CellId;+ cellReducer: ReducerWithoutAction<CellData>;+}) {if (!(cellId in state.cellData)) {Logger.warn(`Cell ${cellId} not found in state`);return state;diff --git a/frontend/src/core/codemirror/__tests__/extensions.test.ts b/frontend/src/core/codemirror/__tests__/extensions.test.tsindex 8c92d23667..4ee2bdf55d 100644--- a/frontend/src/core/codemirror/__tests__/extensions.test.ts+++ b/frontend/src/core/codemirror/__tests__/extensions.test.ts@@ -73,8 +73,10 @@ describe("scrollActiveLineIntoView", () => {// Check that smartScrollIntoView was called with the right argumentsexpect(vi.mocked(scrollUtils.smartScrollIntoView)).toHaveBeenCalledWith(activeLine,- { top: 30, bottom: 150 },- mockAppElement,+ {+ offset: { top: 30, bottom: 150 },+ body: mockAppElement,+ },);});diff --git a/frontend/src/core/codemirror/__tests__/format.test.ts b/frontend/src/core/codemirror/__tests__/format.test.tsindex f337a563b0..a86178ab46 100644--- a/frontend/src/core/codemirror/__tests__/format.test.ts+++ b/frontend/src/core/codemirror/__tests__/format.test.ts@@ -187,7 +187,7 @@ describe("format", () => {it("should format SQL code", async () => {const cellId = "1" as CellId;const editor = createEditor("SELECT * FROM table WHERE id = 1", cellId);- switchLanguage(editor, "sql");+ switchLanguage(editor, { language: "sql" });await formatSQL(editor);@@ -210,7 +210,7 @@ describe("format", () => {it("should not format if language adapter is not SQL", async () => {const cellId = "1" as CellId;const editor = createEditor("SELECT * FROM table WHERE id = 1", cellId);- switchLanguage(editor, "python");+ switchLanguage(editor, { language: "python" });await formatSQL(editor);diff --git a/frontend/src/core/codemirror/cm.ts b/frontend/src/core/codemirror/cm.tsindex 2138fd4e99..1367b6e305 100644--- a/frontend/src/core/codemirror/cm.ts+++ b/frontend/src/core/codemirror/cm.ts@@ -114,13 +114,13 @@ export const setupCodeMirror = (opts: CodeMirrorSetupOpts): Extension[] => {pasteBundle(),jupyterHelpExtension(),// Cell editing- cellConfigExtension(+ cellConfigExtension({completionConfig,hotkeys,placeholderType,lspConfig,diagnosticsConfig,- ),+ }),cellBundle(cellId, hotkeys, cellActions),// Comes last so that it can be overriddenbasicBundle(opts),diff --git a/frontend/src/core/codemirror/completion/hints.ts b/frontend/src/core/codemirror/completion/hints.tsindex 2a779a72b7..a9eb059533 100644--- a/frontend/src/core/codemirror/completion/hints.ts+++ b/frontend/src/core/codemirror/completion/hints.ts@@ -20,7 +20,11 @@ export function hintTooltip(lspConfig: LSPConfig) {? []: hoverTooltip(async (view, pos) => {- const result = await requestDocumentation(view, pos, ["tooltip"]);+ const result = await requestDocumentation({+ view,+ pos,+ excludeTypes: ["tooltip"],+ });if (result === null || result === "cancelled") {return null;}@@ -32,11 +36,15 @@ export function hintTooltip(lspConfig: LSPConfig) {];}-async function requestDocumentation(- view: EditorView,- pos: number,- excludeTypes?: string[],-) {+async function requestDocumentation({+ view,+ pos,+ excludeTypes,+}: {+ view: EditorView;+ pos: number;+ excludeTypes?: string[];+}) {const cellContainer = HTMLCellId.findElement(view.dom);if (!cellContainer) {Logger.error("Failed to find active cell.");@@ -114,7 +122,7 @@ const debouncedAutocomplete = debounce(return;}- const tooltip = await requestDocumentation(view, position);+ const tooltip = await requestDocumentation({ view, pos: position });// If cancelled, don't update the documentationif (tooltip === "cancelled") {return;diff --git a/frontend/src/core/codemirror/config/extension.ts b/frontend/src/core/codemirror/config/extension.tsindex 9ed2d85dbb..68215cda12 100644--- a/frontend/src/core/codemirror/config/extension.ts+++ b/frontend/src/core/codemirror/config/extension.ts@@ -40,13 +40,19 @@ export const lspConfigState = singleFacet</*** Extension for cell config*/-export function cellConfigExtension(- completionConfig: CompletionConfig,- hotkeys: HotkeyProvider,- placeholderType: PlaceholderType,- lspConfig: LSPConfig,- diagnosticsConfig: DiagnosticsConfig,-) {+export function cellConfigExtension({+ completionConfig,+ hotkeys,+ placeholderType,+ lspConfig,+ diagnosticsConfig,+}: {+ completionConfig: CompletionConfig;+ hotkeys: HotkeyProvider;+ placeholderType: PlaceholderType;+ lspConfig: LSPConfig;+ diagnosticsConfig: DiagnosticsConfig;+}) {return [// Store statecompletionConfigState.of(completionConfig),diff --git a/frontend/src/core/codemirror/copilot/__tests__/getCode.test.ts b/frontend/src/core/codemirror/copilot/__tests__/getCode.test.tsindex 805f0df67e..efc43f0c5b 100644--- a/frontend/src/core/codemirror/copilot/__tests__/getCode.test.ts+++ b/frontend/src/core/codemirror/copilot/__tests__/getCode.test.ts@@ -43,17 +43,17 @@ function createMockEditorView(code: string) {placeholderType: "marimo-import",lspConfig: {},}),- cellConfigExtension(- {+ cellConfigExtension({+ completionConfig: {copilot: false,activate_on_typing: true,codeium_api_key: null,},- new OverridingHotkeyProvider({}),- "marimo-import",- {},- {},- ),+ hotkeys: new OverridingHotkeyProvider({}),+ placeholderType: "marimo-import",+ lspConfig: {},+ diagnosticsConfig: {},+ }),],}),});diff --git a/frontend/src/core/codemirror/extensions.ts b/frontend/src/core/codemirror/extensions.tsindex 85297907d1..6f5f94cabd 100644--- a/frontend/src/core/codemirror/extensions.ts+++ b/frontend/src/core/codemirror/extensions.ts@@ -85,7 +85,10 @@ export function scrollActiveLineIntoView() {const activeLine = activeLines[0] as HTMLElement;const appEl = document.getElementById("App");invariant(appEl, "App not found");- smartScrollIntoView(activeLine, { top: 30, bottom: 150 }, appEl);+ smartScrollIntoView(activeLine, {+ offset: { top: 30, bottom: 150 },+ body: appEl,+ });}}});diff --git a/frontend/src/core/codemirror/language/__tests__/extension.test.ts b/frontend/src/core/codemirror/language/__tests__/extension.test.tsindex a2b4e36694..0bd9f2cbb2 100644--- a/frontend/src/core/codemirror/language/__tests__/extension.test.ts+++ b/frontend/src/core/codemirror/language/__tests__/extension.test.ts@@ -30,17 +30,17 @@ function createState(content: string, selection?: { anchor: number }) {hotkeys: new OverridingHotkeyProvider({}),placeholderType: "marimo-import",}),- cellConfigExtension(- {+ cellConfigExtension({+ completionConfig: {copilot: false,activate_on_typing: true,codeium_api_key: null,},- new OverridingHotkeyProvider({}),- "marimo-import",- {},- {},- ),+ hotkeys: new OverridingHotkeyProvider({}),+ placeholderType: "marimo-import",+ lspConfig: {},+ diagnosticsConfig: {},+ }),],selection,});@@ -74,7 +74,7 @@ describe("switchLanguage", () => {anchor: 2,});const mockEditor = new EditorView({ state });- switchLanguage(mockEditor, "python", { keepCodeAsIs: true });+ switchLanguage(mockEditor, { language: "python", keepCodeAsIs: true });expect(mockEditor.state.field(languageAdapterState).type).toBe("python");expect(mockEditor.state.doc.toString()).toEqual("print('Hello')\nprint('Goodbye')",@@ -87,14 +87,14 @@ describe("switchLanguage", () => {expect(getInitialLanguageAdapter(mockEditor.state).type).toBe("python");// Switch to markdown- switchLanguage(mockEditor, "markdown", { keepCodeAsIs: true });+ switchLanguage(mockEditor, { language: "markdown", keepCodeAsIs: true });expect(mockEditor.state.field(languageAdapterState).type).toBe("markdown");expect(mockEditor.state.doc.toString()).toEqual("print('Hello')\nprint('Goodbye')",);// Switch back to python- switchLanguage(mockEditor, "python", { keepCodeAsIs: true });+ switchLanguage(mockEditor, { language: "python", keepCodeAsIs: true });expect(mockEditor.state.field(languageAdapterState).type).toBe("python");expect(mockEditor.state.doc.toString()).toEqual("print('Hello')\nprint('Goodbye')",@@ -104,7 +104,7 @@ describe("switchLanguage", () => {expect(mockEditor.state.selection.main.from).toEqual(2);// Switch to sql- switchLanguage(mockEditor, "sql", { keepCodeAsIs: true });+ switchLanguage(mockEditor, { language: "sql", keepCodeAsIs: true });expect(mockEditor.state.field(languageAdapterState).type).toBe("sql");expect(mockEditor.state.doc.toString()).toEqual("print('Hello')\nprint('Goodbye')",@@ -114,7 +114,7 @@ describe("switchLanguage", () => {expect(mockEditor.state.selection.main.from).toEqual(2);// Switch back to python- switchLanguage(mockEditor, "python", { keepCodeAsIs: true });+ switchLanguage(mockEditor, { language: "python", keepCodeAsIs: true });expect(mockEditor.state.field(languageAdapterState).type).toBe("python");expect(mockEditor.state.doc.toString()).toEqual("print('Hello')\nprint('Goodbye')",@@ -129,7 +129,7 @@ describe("switchLanguage", () => {anchor: 2,});const mockEditor = new EditorView({ state });- switchLanguage(mockEditor, "python", { keepCodeAsIs: false });+ switchLanguage(mockEditor, { language: "python", keepCodeAsIs: false });expect(mockEditor.state.doc.toString()).toEqual("print('Hello')\nprint('Goodbye')",);@@ -138,13 +138,13 @@ describe("switchLanguage", () => {expect(mockEditor.state.selection.main.from).toEqual(2);// Switch to markdown- switchLanguage(mockEditor, "markdown", { keepCodeAsIs: false });+ switchLanguage(mockEditor, { language: "markdown", keepCodeAsIs: false });expect(mockEditor.state.doc.toString()).toEqual("print('Hello')\nprint('Goodbye')",);// Switch back to python- switchLanguage(mockEditor, "python", { keepCodeAsIs: false });+ switchLanguage(mockEditor, { language: "python", keepCodeAsIs: false });expect(mockEditor.state.doc.toString()).toMatchInlineSnapshot(`"mo.md(r"""@@ -155,14 +155,14 @@ describe("switchLanguage", () => {`);// Switch to sql- switchLanguage(mockEditor, "sql", { keepCodeAsIs: false });+ switchLanguage(mockEditor, { language: "sql", keepCodeAsIs: false });expect(mockEditor.state.doc.toString()).toMatchInlineSnapshot(`"print('Hello')print('Goodbye')"`);// Switch back to python- switchLanguage(mockEditor, "python", { keepCodeAsIs: false });+ switchLanguage(mockEditor, { language: "python", keepCodeAsIs: false });expect(mockEditor.state.doc.toString()).toMatchInlineSnapshot(`"_df = mo.sql(f"""@@ -180,7 +180,7 @@ describe("switchLanguage", () => {expect(mockEditor.state.field(languageMetadataField)).toEqual({});// Switch to SQL- switchLanguage(mockEditor, "sql", { keepCodeAsIs: false });+ switchLanguage(mockEditor, { language: "sql", keepCodeAsIs: false });// Check that the language was switchedexpect(mockEditor.state.field(languageAdapterState).type).toBe("sql");@@ -206,7 +206,7 @@ describe("switchLanguage", () => {const mockEditor = new EditorView({ state });expect(mockEditor.state.field(languageMetadataField)).toEqual({});- switchLanguage(mockEditor, "markdown", { keepCodeAsIs: true });+ switchLanguage(mockEditor, { language: "markdown", keepCodeAsIs: true });expect(mockEditor.state.doc.toString()).toEqual("# hello");expect(mockEditor.state.field(languageMetadataField)).toEqual({quotePrefix: "r",@@ -218,13 +218,13 @@ describe("switchLanguage", () => {const mockEditor = new EditorView({ state });expect(mockEditor.state.field(languageMetadataField)).toEqual({});- switchLanguage(mockEditor, "markdown", { keepCodeAsIs: true });+ switchLanguage(mockEditor, { language: "markdown", keepCodeAsIs: true });expect(mockEditor.state.doc.toString()).toEqual("SELECT * FROM df");expect(mockEditor.state.field(languageMetadataField)).toEqual({quotePrefix: "r",});- switchLanguage(mockEditor, "sql", { keepCodeAsIs: true });+ switchLanguage(mockEditor, { language: "sql", keepCodeAsIs: true });expect(mockEditor.state.doc.toString()).toEqual("SELECT * FROM df");expect(mockEditor.state.field(languageMetadataField)).toEqual({commentLines: [],@@ -235,7 +235,7 @@ describe("switchLanguage", () => {});// Switch back to markdown- switchLanguage(mockEditor, "markdown", { keepCodeAsIs: true });+ switchLanguage(mockEditor, { language: "markdown", keepCodeAsIs: true });expect(mockEditor.state.doc.toString()).toEqual("SELECT * FROM df");expect(mockEditor.state.field(languageMetadataField)).toEqual({quotePrefix: "r",diff --git a/frontend/src/core/codemirror/language/__tests__/markdown.test.ts b/frontend/src/core/codemirror/language/__tests__/markdown.test.tsindex eb69f804c2..16a0da963b 100644--- a/frontend/src/core/codemirror/language/__tests__/markdown.test.ts+++ b/frontend/src/core/codemirror/language/__tests__/markdown.test.ts@@ -429,31 +429,67 @@ describe("MarkdownLanguageAdapter", () => {describe("getQuotePrefix", () => {it("should return the correct quote prefix when checked", () => {- expect(getQuotePrefix("", true, "r")).toBe("r");- expect(getQuotePrefix("", true, "f")).toBe("f");- expect(getQuotePrefix("r", true, "f")).toBe("rf");- expect(getQuotePrefix("f", true, "r")).toBe("rf");+ expect(+ getQuotePrefix({ currentQuotePrefix: "", checked: true, prefix: "r" }),+ ).toBe("r");+ expect(+ getQuotePrefix({ currentQuotePrefix: "", checked: true, prefix: "f" }),+ ).toBe("f");+ expect(+ getQuotePrefix({ currentQuotePrefix: "r", checked: true, prefix: "f" }),+ ).toBe("rf");+ expect(+ getQuotePrefix({ currentQuotePrefix: "f", checked: true, prefix: "r" }),+ ).toBe("rf");});it("should return the correct quote prefix when unchecked", () => {- expect(getQuotePrefix("r", false, "r")).toBe("");- expect(getQuotePrefix("f", false, "f")).toBe("");- expect(getQuotePrefix("rf", false, "r")).toBe("f");- expect(getQuotePrefix("rf", false, "f")).toBe("r");+ expect(+ getQuotePrefix({ currentQuotePrefix: "r", checked: false, prefix: "r" }),+ ).toBe("");+ expect(+ getQuotePrefix({ currentQuotePrefix: "f", checked: false, prefix: "f" }),+ ).toBe("");+ expect(+ getQuotePrefix({ currentQuotePrefix: "rf", checked: false, prefix: "r" }),+ ).toBe("f");+ expect(+ getQuotePrefix({ currentQuotePrefix: "rf", checked: false, prefix: "f" }),+ ).toBe("r");});it("should return the correct quote prefix even when not possible to toggle", () => {- expect(getQuotePrefix("", false, "r")).toBe("");- expect(getQuotePrefix("", false, "f")).toBe("");- expect(getQuotePrefix("r", false, "f")).toBe("r");- expect(getQuotePrefix("f", false, "r")).toBe("f");-- expect(getQuotePrefix("rf", true, "r")).toBe("rf");- expect(getQuotePrefix("rf", true, "f")).toBe("rf");- expect(getQuotePrefix("f", true, "f")).toBe("f");- expect(getQuotePrefix("r", true, "r")).toBe("r");-- expect(getQuotePrefix("", false, "")).toBe("");- expect(getQuotePrefix("", true, "")).toBe("");+ expect(+ getQuotePrefix({ currentQuotePrefix: "", checked: false, prefix: "r" }),+ ).toBe("");+ expect(+ getQuotePrefix({ currentQuotePrefix: "", checked: false, prefix: "f" }),+ ).toBe("");+ expect(+ getQuotePrefix({ currentQuotePrefix: "r", checked: false, prefix: "f" }),+ ).toBe("r");+ expect(+ getQuotePrefix({ currentQuotePrefix: "f", checked: false, prefix: "r" }),+ ).toBe("f");++ expect(+ getQuotePrefix({ currentQuotePrefix: "rf", checked: true, prefix: "r" }),+ ).toBe("rf");+ expect(+ getQuotePrefix({ currentQuotePrefix: "rf", checked: true, prefix: "f" }),+ ).toBe("rf");+ expect(+ getQuotePrefix({ currentQuotePrefix: "f", checked: true, prefix: "f" }),+ ).toBe("f");+ expect(+ getQuotePrefix({ currentQuotePrefix: "r", checked: true, prefix: "r" }),+ ).toBe("r");++ expect(+ getQuotePrefix({ currentQuotePrefix: "", checked: false, prefix: "" }),+ ).toBe("");+ expect(+ getQuotePrefix({ currentQuotePrefix: "", checked: true, prefix: "" }),+ ).toBe("");});});diff --git a/frontend/src/core/codemirror/language/__tests__/utils.test.ts b/frontend/src/core/codemirror/language/__tests__/utils.test.tsindex d42c4a0554..35d743ae31 100644--- a/frontend/src/core/codemirror/language/__tests__/utils.test.ts+++ b/frontend/src/core/codemirror/language/__tests__/utils.test.ts@@ -29,21 +29,21 @@ function createEditor(doc: string) {placeholderType: "marimo-import",lspConfig: {},}),- cellConfigExtension(- {+ cellConfigExtension({+ completionConfig: {activate_on_typing: true,copilot: false,codeium_api_key: null,},- new OverridingHotkeyProvider({}),- "marimo-import",- {+ hotkeys: new OverridingHotkeyProvider({}),+ placeholderType: "marimo-import",+ lspConfig: {pylsp: {enabled: true,},},- {},- ),+ diagnosticsConfig: {},+ }),],}),});@@ -140,7 +140,7 @@ describe("splitEditor", () => {it("handles markdown", () => {const mockEditor = createEditor("mo.md('Hello, World!')");// Set to markdown- switchLanguage(mockEditor, "markdown");+ switchLanguage(mockEditor, { language: "markdown" });// Set cursor positionmockEditor.dispatch({selection: { anchor: "Hello,".length },@@ -154,7 +154,7 @@ describe("splitEditor", () => {it.skip("handles markdown with variables", () => {const mockEditor = createEditor('mo.md(f"""{a}\n{b}!""")');// Set to markdown- switchLanguage(mockEditor, "markdown");+ switchLanguage(mockEditor, { language: "markdown" });// Set cursor positionmockEditor.dispatch({selection: { anchor: "{a}\n".length },diff --git a/frontend/src/core/codemirror/language/commands.ts b/frontend/src/core/codemirror/language/commands.tsindex 8d4bef6f74..6d62cf1216 100644--- a/frontend/src/core/codemirror/language/commands.ts+++ b/frontend/src/core/codemirror/language/commands.ts@@ -53,7 +53,7 @@ export function toggleToLanguage(return false;}- switchLanguage(editorView, language);+ switchLanguage(editorView, { language });return language;}diff --git a/frontend/src/core/codemirror/language/extension.ts b/frontend/src/core/codemirror/language/extension.tsindex b38490897d..c5a1b727a9 100644--- a/frontend/src/core/codemirror/language/extension.ts+++ b/frontend/src/core/codemirror/language/extension.ts@@ -102,8 +102,12 @@ function languageToggleKeymaps() {return false;}- updateLanguageAdapterAndCode(cm, nextLanguage, {- keepCodeAsIs: false,+ updateLanguageAdapterAndCode({+ view: cm,+ nextLanguage,+ opts: {+ keepCodeAsIs: false,+ },});return true;},@@ -112,11 +116,15 @@ function languageToggleKeymaps() {];}-function updateLanguageAdapterAndCode(- view: EditorView,- nextLanguage: LanguageAdapter,- opts: { keepCodeAsIs: boolean },-) {+function updateLanguageAdapterAndCode({+ view,+ nextLanguage,+ opts,+}: {+ view: EditorView;+ nextLanguage: LanguageAdapter;+ opts: { keepCodeAsIs: boolean };+}) {const currentLanguage = view.state.field(languageAdapterState);const code = view.state.doc.toString();const completionConfig = view.state.facet(completionConfigState);@@ -254,17 +262,23 @@ export function languageAdapterFromCode(doc: string): LanguageAdapter {*/export function switchLanguage(view: EditorView,- language: LanguageAdapter["type"],- opts: { keepCodeAsIs?: boolean } = {},+ opts: {+ language: LanguageAdapter["type"];+ keepCodeAsIs?: boolean;+ },) {// If the existing language is the same as the new language, do nothingconst currentLanguage = view.state.field(languageAdapterState);- if (currentLanguage.type === language) {+ if (currentLanguage.type === opts.language) {return;}- updateLanguageAdapterAndCode(view, LanguageAdapters[language], {- keepCodeAsIs: opts.keepCodeAsIs ?? false,+ updateLanguageAdapterAndCode({+ view,+ nextLanguage: LanguageAdapters[opts.language],+ opts: {+ keepCodeAsIs: opts.keepCodeAsIs ?? false,+ },});}@@ -277,9 +291,15 @@ export function switchLanguage(*/export function reconfigureLanguageEffect(view: EditorView,- completionConfig: CompletionConfig,- hotkeysProvider: HotkeyProvider,- lspConfig: LSPConfig & { diagnostics?: DiagnosticsConfig },+ {+ completionConfig,+ hotkeysProvider,+ lspConfig,+ }: {+ completionConfig: CompletionConfig;+ hotkeysProvider: HotkeyProvider;+ lspConfig: LSPConfig & { diagnostics?: DiagnosticsConfig };+ },) {const language = view.state.field(languageAdapterState);const placeholderType = view.state.facet(placeholderState);diff --git a/frontend/src/core/codemirror/language/panel/markdown.tsx b/frontend/src/core/codemirror/language/panel/markdown.tsxindex 477f51a527..077e1328af 100644--- a/frontend/src/core/codemirror/language/panel/markdown.tsx+++ b/frontend/src/core/codemirror/language/panel/markdown.tsx@@ -2,11 +2,15 @@import type { QuotePrefixKind } from "../utils/quotes";// Based on the current quote prefix and the checkbox state, return the new quote prefix-export function getQuotePrefix(- currentQuotePrefix: QuotePrefixKind,- checked: boolean,- prefix: QuotePrefixKind,-) {+export function getQuotePrefix({+ currentQuotePrefix,+ checked,+ prefix,+}: {+ currentQuotePrefix: QuotePrefixKind;+ checked: boolean;+ prefix: QuotePrefixKind;+}) {let newQuotePrefix = currentQuotePrefix;if (checked) {// Add a prefixdiff --git a/frontend/src/core/codemirror/language/panel/panel.tsx b/frontend/src/core/codemirror/language/panel/panel.tsxindex 88fef3d2b2..3138d559ae 100644--- a/frontend/src/core/codemirror/language/panel/panel.tsx+++ b/frontend/src/core/codemirror/language/panel/panel.tsx@@ -137,7 +137,11 @@ export const LanguagePanelComponent: React.FC<{if (typeof checked !== "boolean") {return;}- const newPrefix = getQuotePrefix(quotePrefix, checked, prefix);+ const newPrefix = getQuotePrefix({+ currentQuotePrefix: quotePrefix,+ checked,+ prefix,+ });triggerUpdate<Metadata2>({quotePrefix: newPrefix,});diff --git a/frontend/src/core/codemirror/markdown/commands.ts b/frontend/src/core/codemirror/markdown/commands.tsindex 8c30d57d54..a8272e6edd 100644--- a/frontend/src/core/codemirror/markdown/commands.ts+++ b/frontend/src/core/codemirror/markdown/commands.ts@@ -17,11 +17,15 @@ function hasSelection(view: EditorView) {return !view.state.selection.main.empty;}-function toggleAllLines(- view: EditorView,- selection: SelectionRange,- markup: string,-) {+function toggleAllLines({+ view,+ selection,+ markup,+}: {+ view: EditorView;+ selection: SelectionRange;+ markup: string;+}) {const changes = [];let allLinesHaveMarkup = true;@@ -67,12 +71,17 @@ function toggleAllLines(return changes;}-function wrapWithMarkup(- view: EditorView,- range: SelectionRange,- markupBefore: string,- markupAfter: string,-) {+function wrapWithMarkup({+ view,+ range,+ markupAfter,+ markupBefore,+}: {+ view: EditorView;+ range: SelectionRange;+ markupBefore: string;+ markupAfter: string;+}) {if (range.empty) {const wordRange = view.state.wordAt(range.head);if (wordRange) {@@ -133,7 +142,11 @@ export function insertBlockquote(view: EditorView) {const markup = "> ";- const changes = toggleAllLines(view, view.state.selection.main, markup);+ const changes = toggleAllLines({+ view,+ selection: view.state.selection.main,+ markup,+ });if (changes.length > 0) {view.dispatch(@@ -160,7 +173,12 @@ export function insertBoldMarker(view: EditorView) {}}- return wrapWithMarkup(view, range, "**", "**");+ return wrapWithMarkup({+ view,+ range,+ markupBefore: "**",+ markupAfter: "**",+ });});view.dispatch(@@ -194,7 +212,12 @@ export function insertCodeMarker(view: EditorView) {const fenceBefore = isMultiline ? "```\n" : "`";const fenceAfter = isMultiline ? "\n```" : "`";- return wrapWithMarkup(view, range, fenceBefore, fenceAfter);+ return wrapWithMarkup({+ view,+ range,+ markupBefore: fenceBefore,+ markupAfter: fenceAfter,+ });});view.dispatch(@@ -220,7 +243,7 @@ export function insertItalicMarker(view: EditorView) {}}- return wrapWithMarkup(view, range, "_", "_");+ return wrapWithMarkup({ view, range, markupBefore: "_", markupAfter: "_" });});view.dispatch(@@ -415,7 +438,7 @@ export function insertUL(view: EditorView) {return {range,- changes: toggleAllLines(view, range, rangeText),+ changes: toggleAllLines({ view, selection: range, markup: rangeText }),};});@@ -439,7 +462,7 @@ export function insertOL(view: EditorView) {const markup = "1. ";return {range,- changes: toggleAllLines(view, range, markup),+ changes: toggleAllLines({ view, selection: range, markup }),};});diff --git a/frontend/src/core/codemirror/rtc/extension.ts b/frontend/src/core/codemirror/rtc/extension.tsindex 3e3cb9c982..0000b76d5b 100644--- a/frontend/src/core/codemirror/rtc/extension.ts+++ b/frontend/src/core/codemirror/rtc/extension.ts@@ -231,7 +231,7 @@ function languageObserverExtension(cellId: CellId) {logger.debug(`[incoming] setting language type: ${currentLang} -> ${newLang}`,);- switchLanguage(view, newLang, { keepCodeAsIs: true });+ switchLanguage(view, { language: newLang, keepCodeAsIs: true });}};@@ -341,13 +341,13 @@ function languageListenerExtension(cellId: CellId) {// If the language is not set, set it to the current language// and update the LoroDocif (!isInitialized) {- const lang = getInitialLanguageAdapter(update.state).type;- switchLanguage(update.view, lang);- logger.debug("no initial language, setting default to", lang);+ const language = getInitialLanguageAdapter(update.state).type;+ switchLanguage(update.view, { language });+ logger.debug("no initial language, setting default to", language);// Sync the language to the LoroDoccurrentLang.delete(0, currentLang.length);- currentLang.insert(0, lang);+ currentLang.insert(0, language);// Sync the language metadata to the LoroDoclogger.debug(diff --git a/frontend/src/core/codemirror/rtc/loro/awareness.ts b/frontend/src/core/codemirror/rtc/loro/awareness.tsindex 669cbf5fb9..78651d7555 100644--- a/frontend/src/core/codemirror/rtc/loro/awareness.ts+++ b/frontend/src/core/codemirror/rtc/loro/awareness.ts@@ -401,12 +401,12 @@ export class AwarenessPlugin implements PluginValue {}const selection = update.state.selection.main;if (this.view.hasFocus && !this.doc.isDetached()) {- const cursorState = getCursorState(- this.doc,- this.getTextFromDoc,- selection.anchor,- selection.head,- );+ const cursorState = getCursorState({+ doc: this.doc,+ getTextFromDoc: this.getTextFromDoc,+ anchor: selection.anchor,+ head: selection.head,+ });this.awareness.setLocalState({type: "update",uid: this.getUserId ? this.getUserId() : this.doc.peerIdStr,@@ -465,12 +465,17 @@ export class RemoteAwarenessPlugin implements PluginValue {}}-const getCursorState = (- doc: LoroDoc,- getTextFromDoc: (doc: LoroDoc) => LoroText,- anchor: number,- head: number | undefined,-) => {+const getCursorState = ({+ doc,+ getTextFromDoc,+ anchor,+ head,+}: {+ doc: LoroDoc;+ getTextFromDoc: (doc: LoroDoc) => LoroText;+ anchor: number;+ head: number | undefined;+}) => {if (anchor === head) {head = undefined;}diff --git a/frontend/src/core/kernel/handlers.ts b/frontend/src/core/kernel/handlers.tsindex 8059a91dc8..5bafa19ce1 100644--- a/frontend/src/core/kernel/handlers.ts+++ b/frontend/src/core/kernel/handlers.ts@@ -84,7 +84,11 @@ export function handleKernelReady(const layoutState = initialLayoutState();if (layout) {const layoutType = layout.type as LayoutType;- const layoutData = deserializeLayout(layoutType, layout.data, cells);+ const layoutData = deserializeLayout({+ type: layoutType,+ data: layout.data,+ cells,+ });layoutState.selectedLayout = layoutType;layoutState.layoutData[layoutType] = layoutData;setLayoutData({ layoutView: layoutType, data: layoutData });diff --git a/frontend/src/core/saving/state.ts b/frontend/src/core/saving/state.tsindex 63536faef8..a1186596a8 100644--- a/frontend/src/core/saving/state.ts+++ b/frontend/src/core/saving/state.ts@@ -21,14 +21,18 @@ export const needsSaveAtom = atom((get) => {const lastSavedNotebook = get(lastSavedNotebookAtom);const state = get(notebookAtom);const layout = get(layoutStateAtom);- return notebookNeedsSave(state, layout, lastSavedNotebook);+ return notebookNeedsSave({ state, layout, lastSavedNotebook });});-export function notebookNeedsSave(- state: NotebookState,- layout: LayoutState,- lastSavedNotebook: LastSavedNotebook | undefined,-) {+function notebookNeedsSave({+ state,+ layout,+ lastSavedNotebook,+}: {+ state: NotebookState;+ layout: LayoutState;+ lastSavedNotebook: LastSavedNotebook | undefined;+}) {if (!lastSavedNotebook) {return false;}diff --git a/frontend/src/plugins/impl/FileBrowserPlugin.tsx b/frontend/src/plugins/impl/FileBrowserPlugin.tsxindex fa24910469..d1cb649c91 100644--- a/frontend/src/plugins/impl/FileBrowserPlugin.tsx+++ b/frontend/src/plugins/impl/FileBrowserPlugin.tsx@@ -217,11 +217,15 @@ export const FileBrowser = ({setIsUpdatingPath(false);}- function createFileInfo(- path: string,- name: string,- isDirectory: boolean,- ): FileInfo {+ function createFileInfo({+ path,+ name,+ isDirectory,+ }: {+ path: string;+ name: string;+ isDirectory: boolean;+ }): FileInfo {return {id: path,name: name,@@ -230,8 +234,16 @@ export const FileBrowser = ({};}- function handleSelection(path: string, name: string, isDirectory: boolean) {- const fileInfo = createFileInfo(path, name, isDirectory);+ function handleSelection({+ path,+ name,+ isDirectory,+ }: {+ path: string;+ name: string;+ isDirectory: boolean;+ }) {+ const fileInfo = createFileInfo({ path, name, isDirectory });if (multiple) {if (selectedPaths.has(path)) {@@ -264,7 +276,11 @@ export const FileBrowser = ({if (selectedPaths.has(file.path)) {continue;}- const fileInfo = createFileInfo(file.path, file.name, file.is_directory);+ const fileInfo = createFileInfo({+ path: file.path,+ name: file.name,+ isDirectory: file.is_directory,+ });filesInView.push(fileInfo);}@@ -297,7 +313,9 @@ export const FileBrowser = ({}// Click handler- const handleClick = file.is_directory ? setNewPath : handleSelection;+ const handleClick = file.is_directory+ ? ({ path }: { path: string }) => setNewPath(path)+ : handleSelection;// Iconconst fileType: FileType = file.is_directory@@ -317,7 +335,11 @@ export const FileBrowser = ({<Checkboxchecked={isSelected}onClick={(e) => {- handleSelection(filePath, file.name, file.is_directory);+ handleSelection({+ path: filePath,+ name: file.name,+ isDirectory: file.is_directory,+ });e.stopPropagation();}}className={cn("", {@@ -347,7 +369,13 @@ export const FileBrowser = ({"bg-primary bg-opacity-25": isSelected,},)}- onClick={() => handleClick(filePath, file.name, file.is_directory)}+ onClick={() =>+ handleClick({+ path: filePath,+ name: file.name,+ isDirectory: file.is_directory,+ })+ }><TableCell className="w-[50px] pl-4">{renderCheckboxOrIcon()}@@ -361,12 +389,12 @@ export const FileBrowser = ({//// Assumes that path contains at least one delimiter, which is true// only if this is an absolute path.- const { parentDirectories } = getProtocolAndParentDirectories(+ const { parentDirectories } = getProtocolAndParentDirectories({path,delimiter,initialPath,restrictNavigation,- );+ });const selectionKindLabel =selectionMode === "all"diff --git a/frontend/src/plugins/impl/anywidget/__tests__/model.test.ts b/frontend/src/plugins/impl/anywidget/__tests__/model.test.tsindex 9e976accca..3db8065053 100644--- a/frontend/src/plugins/impl/anywidget/__tests__/model.test.ts+++ b/frontend/src/plugins/impl/anywidget/__tests__/model.test.ts@@ -278,11 +278,15 @@ describe("Model", () => {describe("ModelManager", () => {let modelManager = new ModelManager(50);- const handle = (- modelId: string,- message: AnyWidgetMessage,- buffers: Base64String[],- ) => {+ const handle = ({+ modelId,+ message,+ buffers,+ }: {+ modelId: string;+ message: AnyWidgetMessage;+ buffers: Base64String[];+ }) => {return handleWidgetMessage(modelId, message, buffers, modelManager);};@@ -318,7 +322,7 @@ describe("ModelManager", () => {buffer_paths: [],};- await handle("test-id", openMessage, []);+ await handle({ modelId: "test-id", message: openMessage, buffers: [] });const model = await modelManager.get("test-id");expect(model.get("count")).toBe(0);@@ -328,7 +332,7 @@ describe("ModelManager", () => {buffer_paths: [],};- await handle("test-id", updateMessage, []);+ await handle({ modelId: "test-id", message: updateMessage, buffers: [] });expect(model.get("count")).toBe(1);});@@ -336,7 +340,11 @@ describe("ModelManager", () => {const model = new Model({ count: 0 }, vi.fn(), vi.fn(), new Set());modelManager.set("test-id", model);- await handle("test-id", { method: "close" }, []);+ await handle({+ modelId: "test-id",+ message: { method: "close" },+ buffers: [],+ });await expect(modelManager.get("test-id")).rejects.toThrow();});});diff --git a/frontend/src/utils/math.ts b/frontend/src/utils/math.tsindex 45659e1f8b..9434be7829 100644--- a/frontend/src/utils/math.ts+++ b/frontend/src/utils/math.ts@@ -1,5 +1,6 @@/* Copyright 2024 Marimo. All rights reserved. */+// biome-ignore lint: preferObjectParams ok to ignore for common utilexport function clamp(value: number, min: number, max: number) {return Math.min(Math.max(value, min), max);}diff --git a/frontend/src/utils/pathUtils.test.ts b/frontend/src/utils/pathUtils.test.tsindex 992553d2b6..d61e39c90a 100644--- a/frontend/src/utils/pathUtils.test.ts+++ b/frontend/src/utils/pathUtils.test.ts@@ -9,12 +9,12 @@ describe("getProtocolAndParentDirectories", () => {const initialPath = "http://example.com/folder";const restrictNavigation = true;- const { protocol, parentDirectories } = getProtocolAndParentDirectories(+ const { protocol, parentDirectories } = getProtocolAndParentDirectories({path,delimiter,initialPath,restrictNavigation,- );+ });expect(protocol).toBe("http://");expect(parentDirectories).toEqual([@@ -29,12 +29,12 @@ describe("getProtocolAndParentDirectories", () => {const initialPath = "gs://bucket/folder";const restrictNavigation = true;- const { protocol, parentDirectories } = getProtocolAndParentDirectories(+ const { protocol, parentDirectories } = getProtocolAndParentDirectories({path,delimiter,initialPath,restrictNavigation,- );+ });expect(protocol).toBe("gs://");expect(parentDirectories).toEqual([@@ -49,12 +49,12 @@ describe("getProtocolAndParentDirectories", () => {const initialPath = "s3://bucket/folder";const restrictNavigation = true;- const { protocol, parentDirectories } = getProtocolAndParentDirectories(+ const { protocol, parentDirectories } = getProtocolAndParentDirectories({path,delimiter,initialPath,restrictNavigation,- );+ });expect(protocol).toBe("s3://");expect(parentDirectories).toEqual([@@ -69,12 +69,12 @@ describe("getProtocolAndParentDirectories", () => {const initialPath = "/folder";const restrictNavigation = false;- const { protocol, parentDirectories } = getProtocolAndParentDirectories(+ const { protocol, parentDirectories } = getProtocolAndParentDirectories({path,delimiter,initialPath,restrictNavigation,- );+ });expect(protocol).toBe("/");expect(parentDirectories).toEqual(["/folder/subfolder", "/folder", "/"]);@@ -85,12 +85,12 @@ describe("getProtocolAndParentDirectories", () => {const initialPath = "C:\\folder";const restrictNavigation = false;- const { protocol, parentDirectories } = getProtocolAndParentDirectories(+ const { protocol, parentDirectories } = getProtocolAndParentDirectories({path,delimiter,initialPath,restrictNavigation,- );+ });expect(protocol).toBe("C:\\");expect(parentDirectories).toEqual([diff --git a/frontend/src/utils/pathUtils.ts b/frontend/src/utils/pathUtils.tsindex d123d44fca..33228fd5e8 100644--- a/frontend/src/utils/pathUtils.ts+++ b/frontend/src/utils/pathUtils.ts@@ -3,12 +3,17 @@/*** Get the protocol and parent directories of a path.*/-export function getProtocolAndParentDirectories(- path: string,- delimiter: string,- initialPath: string,- restrictNavigation: boolean,-) {+export function getProtocolAndParentDirectories({+ path,+ delimiter,+ initialPath,+ restrictNavigation,+}: {+ path: string;+ delimiter: string;+ initialPath: string;+ restrictNavigation: boolean;+}) {// Determine protocol (http://, gs://, C:\, s3://, or /)const protocolMatch = path.match(/^[\dA-Za-z]+:\/\//);const isWindowsPath = /^[A-Za-z]:\\/.test(path);diff --git a/frontend/src/utils/scroll.ts b/frontend/src/utils/scroll.tsindex 0677ede283..609b0ca446 100644--- a/frontend/src/utils/scroll.ts+++ b/frontend/src/utils/scroll.ts@@ -5,8 +5,13 @@*/export function smartScrollIntoView(element: HTMLElement,- offset?: { top: number; bottom: number },- body: HTMLElement | typeof window = window,+ {+ offset,+ body = window,+ }: {+ offset?: { top: number; bottom: number };+ body?: HTMLElement | typeof window;+ },) {const topOffset = offset?.top ?? 0;const bottomOffset = offset?.bottom ?? 0;