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.

dataframe: load values from backend and distaply in better dropdowns (#263)

Myles Scolnick26139d0cfa17
diff --git a/frontend/src/components/forms/switchable-multi-select.tsx b/frontend/src/components/forms/switchable-multi-select.tsx
index 9731a00818..f4bf872df1 100644
--- a/frontend/src/components/forms/switchable-multi-select.tsx
+++ b/frontend/src/components/forms/switchable-multi-select.tsx
@@ -33,21 +33,15 @@ export const SwitchableMultiSelect: React.FC<Props> = ({
comboBoxClassName,
}) => {
const [showTextArea, setShowTextArea] = useState(false);
- const valueAsArray = Array.isArray(value) ? value : [value];
+ const valueAsArray = ensureStringArray(value);
const renderInput = () => {
if (showTextArea) {
return (
- <Textarea
- value={valueAsArray.join(DELIMINATOR)}
+ <TextAreaMultiSelect
+ value={valueAsArray}
className={textAreaClassName}
- onChange={(e) => {
- if (e.target.value === "") {
- onChange([]);
- return;
- }
- onChange(e.target.value.split(DELIMINATOR));
- }}
+ onChange={onChange}
placeholder={
placeholder ? `${placeholder}: one per line` : "One value per line"
}
@@ -59,12 +53,13 @@ export const SwitchableMultiSelect: React.FC<Props> = ({
<Combobox
placeholder={placeholder}
displayValue={(option: string) => option}
- className={comboBoxClassName}
+ className={cn("w-full max-w-[400px]", comboBoxClassName)}
multiple={true}
value={valueAsArray}
onValueChange={onChange}
keepPopoverOpenOnSelect={true}
chips={true}
+ chipsClassName="flex-row flex-wrap min-w-[210px]"
>
{options.map((option) => (
<ComboboxItem key={option} value={option}>
@@ -92,3 +87,46 @@ export const SwitchableMultiSelect: React.FC<Props> = ({
</div>
);
};
+
+/**
+ * Treat a textarea as a multi-select,
+ * where each line is a value.
+ */
+export const TextAreaMultiSelect: React.FC<{
+ value: string[];
+ onChange: (value: string[]) => void;
+ className?: string;
+ placeholder?: string;
+}> = (props) => {
+ const { className, value, onChange, placeholder } = props;
+ const valueAsArray = ensureStringArray(value);
+ return (
+ <Textarea
+ value={valueAsArray.join(DELIMINATOR)}
+ className={className}
+ onChange={(e) => {
+ if (e.target.value === "") {
+ onChange([]);
+ return;
+ }
+ onChange(e.target.value.split(DELIMINATOR));
+ }}
+ placeholder={
+ placeholder ? `${placeholder}: one per line` : "One value per line"
+ }
+ />
+ );
+};
+
+export function ensureStringArray<T extends string>(
+ value: T | T[] | null | undefined
+): T[] {
+ if (value == null) {
+ return [];
+ }
+
+ if (Array.isArray(value)) {
+ return value;
+ }
+ return [value].filter((v) => v != null || v !== "");
+}
diff --git a/frontend/src/components/ui/combobox.tsx b/frontend/src/components/ui/combobox.tsx
index 1fe0eca4ce..75c8fa191e 100644
--- a/frontend/src/components/ui/combobox.tsx
+++ b/frontend/src/components/ui/combobox.tsx
@@ -53,6 +53,7 @@ type ComboboxValueProps<TValue> =
| {
multiple?: false;
chips?: false;
+ chipsClassName?: never;
value?: TValue | null;
defaultValue?: TValue | null;
onValueChange?(value: TValue | null): void;
@@ -60,6 +61,7 @@ type ComboboxValueProps<TValue> =
| {
multiple: true;
chips?: boolean;
+ chipsClassName?: string;
value?: TValue[] | null;
defaultValue?: TValue[] | null;
onValueChange?(value: TValue[] | null): void;
@@ -73,7 +75,7 @@ export const Combobox = <TValue,>({
children,
displayValue,
className,
- placeholder = "--",
+ placeholder,
value: valueProp,
defaultValue,
onValueChange,
@@ -88,7 +90,8 @@ export const Combobox = <TValue,>({
onSearchChange,
emptyState = "Nothing found.",
chips = false,
- keepPopoverOpenOnSelect = false,
+ chipsClassName,
+ keepPopoverOpenOnSelect,
}: ComboboxProps<TValue>) => {
const [open = false, setOpen] = useControllableState({
prop: openProp,
@@ -117,7 +120,7 @@ export const Combobox = <TValue,>({
if (Array.isArray(value)) {
if (value.includes(newValue)) {
const newArr = value.filter((val) => val !== selectedValue);
- newValue = newArr.length > 0 ? newArr : null;
+ newValue = newArr.length > 0 ? newArr : [];
} else {
newValue = [...value, newValue];
}
@@ -129,21 +132,22 @@ export const Combobox = <TValue,>({
}
setValue(newValue);
- if (!keepPopoverOpenOnSelect) {
+ const keepOpen = keepPopoverOpenOnSelect ?? multiple;
+ if (!keepOpen) {
setOpen(false);
}
};
const renderValue = (): string => {
// If we show chips, we don't want to change the placeholder
- if (multiple && chips) {
+ if (multiple && chips && placeholder) {
return placeholder;
}
if (value) {
if (Array.isArray(value)) {
if (value.length === 0) {
- return placeholder;
+ return placeholder ?? "--";
}
if (value.length === 1 && displayValue !== undefined) {
return displayValue(value[0]);
@@ -153,63 +157,71 @@ export const Combobox = <TValue,>({
if (displayValue !== undefined) {
return displayValue(value as unknown as TValue);
}
- return placeholder;
+ return placeholder ?? "--";
}
- return placeholder;
+ return placeholder ?? "--";
};
return (
- <Popover open={open} onOpenChange={setOpen}>
- <PopoverTrigger asChild={true}>
- <div
- className={cn(
- "flex h-6 w-fit mb-1 shadow-xsSolid items-center justify-between rounded-sm border border-input bg-transparent px-2 text-sm font-prose ring-offset-background placeholder:text-muted-foreground hover:shadow-smSolid focus:outline-none focus:ring-1 focus:ring-ring focus:border-primary focus:shadow-mdSolid disabled:cursor-not-allowed disabled:opacity-50",
- className
- )}
- aria-expanded={open}
+ <div className={cn("relative")}>
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild={true}>
+ <div
+ className={cn(
+ "flex h-6 w-fit mb-1 shadow-xsSolid items-center justify-between rounded-sm border border-input bg-transparent px-2 text-sm font-prose ring-offset-background placeholder:text-muted-foreground hover:shadow-smSolid focus:outline-none focus:ring-1 focus:ring-ring focus:border-primary focus:shadow-mdSolid disabled:cursor-not-allowed disabled:opacity-50",
+ className
+ )}
+ aria-expanded={open}
+ >
+ {renderValue()}{" "}
+ <ChevronDownIcon className="ml-3 w-4 h-4 opacity-50" />
+ </div>
+ </PopoverTrigger>
+ <PopoverContent
+ className="w-full min-w-[var(--radix-popover-trigger-width)] p-0"
+ align="start"
>
- {renderValue()} <ChevronDownIcon className="ml-3 w-4 h-4" />
- </div>
- </PopoverTrigger>
- <PopoverContent
- className="w-full min-w-[var(--radix-popover-trigger-width)] p-0"
- align="start"
- >
- <Command filter={filterFn} shouldFilter={shouldFilter}>
- <CommandInput
- placeholder={inputPlaceholder}
- rootClassName={"px-2 h-10"}
- autoFocus={true}
- value={search}
- onValueChange={onSearchChange}
- />
- <CommandList className="max-h-60 py-.5">
- <CommandEmpty>{emptyState}</CommandEmpty>
- <ComboboxContext.Provider
- value={{ isSelected, onSelect: handleSelect }}
- >
- {children}
- </ComboboxContext.Provider>
- </CommandList>
- </Command>
- </PopoverContent>
+ <Command filter={filterFn} shouldFilter={shouldFilter}>
+ <CommandInput
+ placeholder={inputPlaceholder}
+ rootClassName={"px-1 h-8"}
+ autoFocus={true}
+ value={search}
+ onValueChange={onSearchChange}
+ />
+ <CommandList className="max-h-60 py-.5">
+ <CommandEmpty>{emptyState}</CommandEmpty>
+ <ComboboxContext.Provider
+ value={{ isSelected, onSelect: handleSelect }}
+ >
+ {children}
+ </ComboboxContext.Provider>
+ </CommandList>
+ </Command>
+ </PopoverContent>
+ </Popover>
{multiple && chips && (
- <div className="flex flex-col gap-1 items-start">
+ <div className={cn("flex flex-col gap-1 items-start", chipsClassName)}>
{Array.isArray(value) &&
- value.map((val) => (
- <Badge key={String(val)} variant="secondary">
- {displayValue?.(val) ?? String(val)}
- <XCircle
- onClick={() => {
- handleSelect(val);
- }}
- className="w-3 h-3 opacity-50 hover:opacity-100 ml-1 cursor-pointer"
- />
- </Badge>
- ))}
+ value.map((val) => {
+ if (!val) {
+ return null;
+ }
+ return (
+ <Badge key={String(val)} variant="secondary">
+ {displayValue?.(val) ?? String(val)}
+ <XCircle
+ onClick={() => {
+ handleSelect(val);
+ }}
+ className="w-3 h-3 opacity-50 hover:opacity-100 ml-1 cursor-pointer"
+ />
+ </Badge>
+ );
+ })}
</div>
)}
- </Popover>
+ </div>
);
};
diff --git a/frontend/src/components/ui/form.tsx b/frontend/src/components/ui/form.tsx
index 25c0edbbb5..b3ee4be5ba 100644
--- a/frontend/src/components/ui/form.tsx
+++ b/frontend/src/components/ui/form.tsx
@@ -13,7 +13,7 @@ import {
import { cn } from "@/lib/utils";
import { Label } from "@/components/ui/label";
-import { Tooltip, TooltipProvider } from "@/components/ui/tooltip";
+import { Tooltip } from "@/components/ui/tooltip";
import { AlertCircleIcon } from "lucide-react";
const Form = FormProvider;
@@ -187,11 +187,9 @@ const FormMessageTooltip = ({ className }: { className: string }) => {
}
return (
- <TooltipProvider>
- <Tooltip content={body}>
- <AlertCircleIcon className={cn("stroke-[1.8px]", className)} />
- </Tooltip>
- </TooltipProvider>
+ <Tooltip content={body}>
+ <AlertCircleIcon className={cn("stroke-[1.8px]", className)} />
+ </Tooltip>
);
};
FormMessageTooltip.displayName = "FormMessageTooltip";
diff --git a/frontend/src/components/ui/native-select.tsx b/frontend/src/components/ui/native-select.tsx
index 10dad5b8d2..19ca35916c 100644
--- a/frontend/src/components/ui/native-select.tsx
+++ b/frontend/src/components/ui/native-select.tsx
@@ -3,6 +3,14 @@ import * as React from "react";
import { cn } from "@/lib/utils";
import { Events } from "@/utils/events";
+import { cva } from "class-variance-authority";
+
+export const selectStyles = cva(
+ "flex h-6 w-fit mb-1 shadow-xsSolid items-center justify-between rounded-sm border border-input bg-transparent px-2 text-sm font-prose ring-offset-background placeholder:text-muted-foreground hover:shadow-smSolid focus:outline-none focus:ring-1 focus:ring-ring focus:border-primary focus:shadow-mdSolid disabled:cursor-not-allowed disabled:opacity-50 cursor-pointer",
+ {
+ variants: {},
+ }
+);
const NativeSelect = React.forwardRef<
HTMLSelectElement,
@@ -11,10 +19,7 @@ const NativeSelect = React.forwardRef<
<select
ref={ref}
onClick={Events.stopPropagation()}
- className={cn(
- "flex h-6 w-fit mb-1 shadow-xsSolid items-center justify-between rounded-sm border border-input bg-transparent px-2 text-sm font-prose ring-offset-background placeholder:text-muted-foreground hover:shadow-smSolid focus:outline-none focus:ring-1 focus:ring-ring focus:border-primary focus:shadow-mdSolid disabled:cursor-not-allowed disabled:opacity-50 cursor-pointer",
- className
- )}
+ className={cn(selectStyles({}), className)}
{...props}
>
{children}
diff --git a/frontend/src/components/ui/select.tsx b/frontend/src/components/ui/select.tsx
index 88c846f565..6b74a0607b 100644
--- a/frontend/src/components/ui/select.tsx
+++ b/frontend/src/components/ui/select.tsx
@@ -10,6 +10,7 @@ import {
} from "lucide-react";
import { cn } from "@/lib/utils";
+import { selectStyles } from "./native-select";
const Select = SelectPrimitive.Root;
@@ -25,10 +26,7 @@ const SelectTrigger = React.forwardRef<
>(({ className, children, onClear, ...props }, ref) => (
<SelectPrimitive.Trigger
ref={ref}
- className={cn(
- "flex h-7 items-center justify-between rounded-md border border-input shadow-sm bg-transparent px-2 py-1 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50",
- className
- )}
+ className={cn(selectStyles({}), "mb-0", className)}
{...props}
>
{children}
@@ -67,7 +65,7 @@ const SelectContent = React.forwardRef<
position={position}
{...props}
>
- <SelectPrimitive.ScrollUpButton className="flex items-center justify-center h-[20px] bg-white text-muted-foreground cursor-default">
+ <SelectPrimitive.ScrollUpButton className="flex items-center justify-center h-[20px] bg-background text-muted-foreground cursor-default">
<ChevronUpIcon className="h-4 w-4" />
</SelectPrimitive.ScrollUpButton>
@@ -81,8 +79,8 @@ const SelectContent = React.forwardRef<
{children}
</SelectPrimitive.Viewport>
- <SelectPrimitive.ScrollDownButton className="flex items-center justify-center h-[20px] bg-white text-muted-foreground cursor-default">
- <ChevronDownIcon className="h-4 w-4" />
+ <SelectPrimitive.ScrollDownButton className="flex items-center justify-center h-[20px] bg-background text-muted-foreground cursor-default">
+ <ChevronDownIcon className="h-4 w-4 opacity-50" />
</SelectPrimitive.ScrollDownButton>
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
diff --git a/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx b/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx
index 2d5352f6d3..c01e3e2d6a 100644
--- a/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx
+++ b/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx
@@ -23,6 +23,7 @@ import {
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
+import { TooltipProvider } from "@/components/ui/tooltip";
/**
* Arguments for a data table
@@ -42,6 +43,10 @@ type PluginFunctions = {
url: string;
row_headers: Array<[string, string[]]>;
}>;
+ get_column_values: (req: { column: string }) => Promise<{
+ values: unknown[];
+ too_many_values: boolean;
+ }>;
};
// Value is selection, but it is not currently exposed to the user
@@ -66,14 +71,22 @@ export const DataFramePlugin = createPlugin<S>("marimo-dataframe")
row_headers: z.array(z.tuple([z.string(), z.array(z.any())])),
})
),
+ get_column_values: rpc.input(z.object({ column: z.string() })).output(
+ z.object({
+ values: z.array(z.any()),
+ too_many_values: z.boolean(),
+ })
+ ),
})
.renderer((props) => (
- <DataFrameComponent
- {...props.data}
- {...props.functions}
- value={props.value}
- setValue={props.setValue}
- />
+ <TooltipProvider>
+ <DataFrameComponent
+ {...props.data}
+ {...props.functions}
+ value={props.value}
+ setValue={props.setValue}
+ />
+ </TooltipProvider>
));
interface DataTableProps extends Data, PluginFunctions {
@@ -91,6 +104,7 @@ export const DataFrameComponent = ({
value,
setValue,
get_dataframe,
+ get_column_values,
}: DataTableProps): JSX.Element => {
const { data, error } = useAsyncData(
() => get_dataframe({}),
@@ -115,7 +129,10 @@ export const DataFrameComponent = ({
Code
</TabsTrigger>
</TabsList>
- <TabsContent value="transform" className="mt-1">
+ <TabsContent
+ value="transform"
+ className="mt-1 border-x border-t rounded-t"
+ >
<TransformPanel
initialValue={internalValue}
columns={columns}
@@ -125,16 +142,20 @@ export const DataFrameComponent = ({
setInternalValue(v);
}}
onInvalidChange={setInternalValue}
+ getColumnValues={get_column_values}
/>
</TabsContent>
- <TabsContent value="code" className="mt-1">
+ <TabsContent
+ value="code"
+ className="mt-1 border-x border-t rounded-t overflow-hidden"
+ >
<CodePanel dataframeName={dataframeName} transforms={value} />
</TabsContent>
</Tabs>
{error && <ErrorBanner error={error} />}
<LoadingDataTableComponent
label={null}
- className="rounded-b border"
+ className="rounded-b border-x border-b"
data={url || ""}
pageSize={5}
pagination={true}
diff --git a/frontend/src/plugins/impl/data-frames/forms/context.ts b/frontend/src/plugins/impl/data-frames/forms/context.ts
index 86e8d47e56..61356d9a39 100644
--- a/frontend/src/plugins/impl/data-frames/forms/context.ts
+++ b/frontend/src/plugins/impl/data-frames/forms/context.ts
@@ -2,4 +2,12 @@
import { createContext } from "react";
import { ColumnDataTypes } from "../types";
-export const ColumnContext = createContext<ColumnDataTypes>({});
+export const ColumnInfoContext = createContext<ColumnDataTypes>({});
+
+export const ColumnNameContext = createContext<string>("");
+export const ColumnFetchValuesContext = createContext<
+ (req: { column: string }) => Promise<{
+ values: unknown[];
+ too_many_values: boolean;
+ }>
+>(() => Promise.resolve({ values: [], too_many_values: false }));
diff --git a/frontend/src/plugins/impl/data-frames/forms/form.tsx b/frontend/src/plugins/impl/data-frames/forms/form.tsx
index 4ef587b301..a79558931e 100644
--- a/frontend/src/plugins/impl/data-frames/forms/form.tsx
+++ b/frontend/src/plugins/impl/data-frames/forms/form.tsx
@@ -4,7 +4,6 @@ import { z } from "zod";
import {
DebouncedInput,
DebouncedNumberInput,
- Input,
} from "../../../../components/ui/input";
import { Checkbox } from "../../../../components/ui/checkbox";
import {
@@ -31,10 +30,13 @@ import { PlusIcon, Trash2Icon } from "lucide-react";
import { FieldOptions } from "@/plugins/impl/data-frames/forms/options";
import { cn } from "@/lib/utils";
import React, { useContext, useEffect } from "react";
-import { ColumnContext } from "@/plugins/impl/data-frames/forms/context";
+import {
+ ColumnFetchValuesContext,
+ ColumnInfoContext,
+ ColumnNameContext,
+} from "@/plugins/impl/data-frames/forms/context";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { getOperatorForDtype, getSchemaForOperator } from "../utils/operators";
-import { Textarea } from "@/components/ui/textarea";
import { Strings } from "@/utils/strings";
import { Label } from "@/components/ui/label";
import { NativeSelect } from "@/components/ui/native-select";
@@ -48,6 +50,13 @@ import {
} from "@/components/ui/select";
import { DataTypeIcon } from "./datatype-icon";
import { Events } from "@/utils/events";
+import { useAsyncData } from "@/hooks/useAsyncData";
+import { Combobox, ComboboxItem } from "@/components/ui/combobox";
+import {
+ SwitchableMultiSelect,
+ TextAreaMultiSelect,
+ ensureStringArray,
+} from "@/components/forms/switchable-multi-select";
interface Props<T extends FieldValues> {
form: UseFormReturn<T>;
@@ -73,8 +82,6 @@ function renderZodSchema<T extends FieldValues, S>(
const {
label,
description,
- placeholder,
- disabled,
special,
direction = "column",
} = FieldOptions.parse(schema._def.description || "");
@@ -124,32 +131,14 @@ function renderZodSchema<T extends FieldValues, S>(
);
} else if (schema instanceof z.ZodString) {
if (special === "column_id") {
- return <ColumnSelector schema={schema} form={form} path={path} />;
+ return <ColumnFormField schema={schema} form={form} path={path} />;
}
- return (
- <FormField
- control={form.control}
- name={path}
- render={({ field }) => (
- <FormItem>
- <FormLabel>{label}</FormLabel>
- <FormDescription>{description}</FormDescription>
- <FormControl>
- <DebouncedInput
- {...field}
- value={field.value}
- onValueChange={field.onChange}
- className="my-0"
- placeholder={placeholder}
- disabled={disabled}
- />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- );
+ if (special === "column_values") {
+ return <ColumnValuesFormField schema={schema} form={form} path={path} />;
+ }
+
+ return <StringFormField schema={schema} form={form} path={path} />;
} else if (schema instanceof z.ZodBoolean) {
return (
<FormField
@@ -217,136 +206,57 @@ function renderZodSchema<T extends FieldValues, S>(
/>
);
} else if (schema instanceof z.ZodAny) {
+ return <StringFormField schema={schema} form={form} path={path} />;
+ } else if (schema instanceof z.ZodEnum) {
return (
- <FormField
- control={form.control}
- name={path}
- render={({ field }) => (
- <FormItem>
- <FormLabel>{label}</FormLabel>
- <FormDescription>{description}</FormDescription>
- <FormControl>
- <DebouncedInput
- {...field}
- onValueChange={field.onChange}
- className="my-0"
- />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
+ <SelectFormField
+ schema={schema}
+ form={form}
+ path={path}
+ options={schema._def.values}
/>
);
- } else if (schema instanceof z.ZodEnum) {
- if (special === "radio_group") {
+ } else if (schema instanceof z.ZodArray) {
+ if (special === "text_area_multiline") {
+ return <MultiStringFormField schema={schema} form={form} path={path} />;
+ }
+ if (special === "column_values") {
return (
- <FormField
- control={form.control}
- name={path}
- render={({ field }) => (
- <FormItem>
- <FormLabel>{label}</FormLabel>
- <FormDescription>{description}</FormDescription>
- <FormControl>
- <RadioGroup
- className="flex flex-row gap-2 pt-1 items-center"
- value={field.value}
- onValueChange={field.onChange}
- >
- {schema._def.values.map((value: string) => {
- return (
- <div className="flex items-center gap-1" key={value}>
- <RadioGroupItem
- key={value}
- value={value}
- id={`${path}-${value}`}
- />
- <FormLabel
- className="whitespace-pre"
- htmlFor={`${path}-${value}`}
- >
- {Strings.startCase(value)}
- </FormLabel>
- </div>
- );
- })}
- </RadioGroup>
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
+ <MultiColumnValuesFormField schema={schema} form={form} path={path} />
+ );
+ }
+
+ // Inspect child type for a better input
+ const childType = schema._def.type;
+ const childSpecial = FieldOptions.parse(childType._def.description).special;
+
+ // Show column multi-select for array with column_id
+ if (childType instanceof z.ZodString && childSpecial === "column_id") {
+ return (
+ <MultiColumnFormField
+ schema={childType}
+ form={form}
+ path={path}
+ itemLabel={label}
/>
);
}
- return (
- <FormField
- control={form.control}
- name={path}
- render={({ field }) => (
- <FormItem>
- <FormLabel className="whitespace-pre">{label}</FormLabel>
- <FormDescription>{description}</FormDescription>
- <FormControl>
- <Select value={field.value} onValueChange={field.onChange}>
- <SelectTrigger className="min-w-[210px]">
- <SelectValue placeholder="--" />
- </SelectTrigger>
- <SelectContent>
- <SelectGroup>
- {schema._def.values.map((value: string) => {
- return (
- <SelectItem key={value} value={value}>
- {Strings.startCase(value)}
- </SelectItem>
- );
- })}
- </SelectGroup>
- </SelectContent>
- </Select>
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- );
- } else if (schema instanceof z.ZodArray) {
- if (special === "text_area_multiline") {
- // new-line separated
- const delimiter = "\n";
+ // Show multi-select for enum array
+ if (childType instanceof z.ZodEnum) {
+ const childOptions: string[] = childType._def.values;
return (
- <FormField
- control={form.control}
- name={path}
- render={({ field }) => (
- <FormItem>
- <FormLabel>{label}</FormLabel>
- <FormDescription>{description}</FormDescription>
- <FormControl>
- <Textarea
- value={
- Array.isArray(field.value)
- ? field.value.join(delimiter)
- : field.value
- }
- onChange={(e) => {
- if (e.target.value === "") {
- field.onChange([]);
- return;
- }
- field.onChange(e.target.value.split(delimiter));
- }}
- placeholder={placeholder}
- disabled={disabled}
- />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
+ <MultiSelectFormField
+ schema={schema}
+ form={form}
+ path={path}
+ itemLabel={label}
+ options={childOptions}
/>
);
}
+ // Fallback to generic array
return (
<div className="flex flex-col gap-1">
<Label>{label}</Label>
@@ -411,23 +321,6 @@ function renderZodSchema<T extends FieldValues, S>(
["refinement", "transform"].includes(schema._def.effect.type)
) {
return renderZodSchema(schema._def.schema, form, path);
- } else if (schema instanceof z.ZodRecord) {
- return (
- <FormField
- control={form.control}
- name={path}
- render={({ field }) => (
- <FormItem>
- <FormLabel>{label}</FormLabel>
- <FormDescription>{description}</FormDescription>
- <FormMessage />
- <FormControl>
- <Input {...field} className="my-0" />
- </FormControl>
- </FormItem>
- )}
- />
- );
} else {
return (
<div>
@@ -449,6 +342,9 @@ const StyledFormMessage = ({ className }: { className?: string }) => {
);
};
+/**
+ * Type: T[]
+ */
const FormArray = ({
schema,
form,
@@ -488,7 +384,7 @@ const FormArray = ({
{renderZodSchema(schema, form, `${path}[${index}]`)}
{canRemove && (
<Trash2Icon
- className="w-4 h-4 ml-2 my-1 text-muted-foreground hover-action hover:text-destructive cursor-pointer absolute right-0 bottom-0"
+ className="w-4 h-4 ml-2 my-1 text-muted-foreground hover:text-destructive cursor-pointer absolute right-0 top-5"
onClick={() => {
remove(index);
}}
@@ -519,7 +415,11 @@ const FormArray = ({
);
};
-const ColumnSelector = ({
+/**
+ * Type: string
+ * Special: column_id
+ */
+const ColumnFormField = ({
schema,
form,
path,
@@ -530,7 +430,7 @@ const ColumnSelector = ({
path: Path<any>;
onChange?: (value: string) => void;
}) => {
- const columns = useContext(ColumnContext);
+ const columns = useContext(ColumnInfoContext);
const { label, description } = FieldOptions.parse(schema._def.description);
return (
@@ -568,6 +468,11 @@ const ColumnSelector = ({
</SelectItem>
);
})}
+ {Objects.keys(columns).length === 0 && (
+ <SelectItem disabled={true} value="--">
+ No columns
+ </SelectItem>
+ )}
</SelectGroup>
</SelectContent>
</Select>
@@ -578,6 +483,76 @@ const ColumnSelector = ({
);
};
+/**
+ * Type: string[]
+ * Special: column_ids
+ */
+const MultiColumnFormField = ({
+ schema,
+ form,
+ path,
+ itemLabel,
+}: {
+ schema: z.ZodString;
+ form: UseFormReturn<any>;
+ path: Path<any>;
+ itemLabel?: string;
+}) => {
+ const columns = useContext(ColumnInfoContext);
+ const { description } = FieldOptions.parse(schema._def.description);
+ const placeholder = itemLabel
+ ? `Select ${itemLabel.toLowerCase()}`
+ : undefined;
+ return (
+ <FormField
+ control={form.control}
+ name={path}
+ render={({ field }) => {
+ const values = ensureStringArray(field.value);
+ return (
+ <FormItem>
+ <FormLabel>{itemLabel}</FormLabel>
+ <FormDescription>{description}</FormDescription>
+ <FormControl>
+ <Combobox
+ className="min-w-[210px]"
+ placeholder={placeholder}
+ displayValue={(option: string) => option}
+ multiple={true}
+ chips={true}
+ keepPopoverOpenOnSelect={true}
+ value={values}
+ onValueChange={(v) => {
+ field.onChange(v);
+ }}
+ >
+ {Objects.entries(columns).map(([name, dtype]) => {
+ return (
+ <ComboboxItem key={name} value={name.toString()}>
+ <span className="flex items-center gap-2 flex-1">
+ <DataTypeIcon type={dtype} />
+ <span className="flex-1">{name}</span>
+ <span className="text-muted-foreground text-xs font-semibold">
+ ({dtype})
+ </span>
+ </span>
+ </ComboboxItem>
+ );
+ })}
+ </Combobox>
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ );
+ }}
+ />
+ );
+};
+
+/**
+ * Type: { column_id: string; operator: string; value: any }
+ * Special: column_filter
+ */
const FilterForm = ({
path,
form,
@@ -588,7 +563,7 @@ const FilterForm = ({
path: Path<any>;
}) => {
const { description } = FieldOptions.parse(schema._def.description);
- const columns = useContext(ColumnContext);
+ const columns = useContext(ColumnInfoContext);
const { field } = useController({ name: path });
const columnIdSchema = Objects.entries(schema._def.shape()).find(
@@ -601,7 +576,7 @@ const FilterForm = ({
const { column_id: columnId, operator } = field.value || {};
const children = [
- <ColumnSelector
+ <ColumnFormField
key={`column_id`}
schema={columnIdSchema}
form={form}
@@ -657,7 +632,7 @@ const FilterForm = ({
<FormControl>
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger className="min-w-[210px]">
- <SelectValue placeholder="Select a fruit" />
+ <SelectValue placeholder="--" />
</SelectTrigger>
<SelectContent>
<SelectGroup>
@@ -686,7 +661,9 @@ const FilterForm = ({
if (operandSchemas.length === 1) {
children.push(
<React.Fragment key={`value`}>
- {renderZodSchema(operandSchemas[0], form, `${path}.value`)}
+ <ColumnNameContext.Provider value={columnId}>
+ {renderZodSchema(operandSchemas[0], form, `${path}.value`)}
+ </ColumnNameContext.Provider>
</React.Fragment>
);
}
@@ -698,12 +675,362 @@ const FilterForm = ({
name={path}
render={() => (
<div className="flex flex-col gap-2 bg-red">
- <div className={cn("flex flex-row gap-3 items-center")}>
- {children}
- </div>
+ <div className={cn("flex flex-row gap-3")}>{children}</div>
<FormMessage />
</div>
)}
/>
);
};
+
+/**
+ * Type: string
+ */
+const StringFormField = ({
+ schema,
+ form,
+ path,
+}: {
+ schema: z.ZodAny | z.ZodString;
+ form: UseFormReturn<any>;
+ path: Path<any>;
+}) => {
+ const { label, description, placeholder, disabled } = FieldOptions.parse(
+ schema._def.description
+ );
+
+ return (
+ <FormField
+ control={form.control}
+ name={path}
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>{label}</FormLabel>
+ <FormDescription>{description}</FormDescription>
+ <FormControl>
+ <DebouncedInput
+ {...field}
+ value={field.value}
+ onValueChange={field.onChange}
+ className="my-0"
+ placeholder={placeholder}
+ disabled={disabled}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ );
+};
+
+/**
+ * Type: string[]
+ */
+const MultiStringFormField = ({
+ schema,
+ form,
+ path,
+}: {
+ schema: z.ZodAny | z.ZodString | z.ZodArray<any>;
+ form: UseFormReturn<any>;
+ path: Path<any>;
+}) => {
+ const { label, description, placeholder } = FieldOptions.parse(
+ schema._def.description
+ );
+
+ return (
+ <FormField
+ control={form.control}
+ name={path}
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>{label}</FormLabel>
+ <FormDescription>{description}</FormDescription>
+ <FormControl>
+ <TextAreaMultiSelect {...field} placeholder={placeholder} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ );
+};
+
+/**
+ * Type: string
+ * Known options
+ */
+const SelectFormField = ({
+ schema,
+ form,
+ path,
+ options,
+ textTransform,
+}: {
+ schema: z.ZodEnum<any> | z.ZodString;
+ form: UseFormReturn<any>;
+ path: Path<any>;
+ options: string[];
+ textTransform?: (value: string) => string;
+}) => {
+ const { label, description, disabled, special } = FieldOptions.parse(
+ schema._def.description
+ );
+
+ if (special === "radio_group") {
+ return (
+ <FormField
+ control={form.control}
+ name={path}
+ disabled={disabled}
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>{label}</FormLabel>
+ <FormDescription>{description}</FormDescription>
+ <FormControl>
+ <RadioGroup
+ className="flex flex-row gap-2 pt-1 items-center"
+ value={field.value}
+ onValueChange={field.onChange}
+ >
+ {options.map((value: string) => {
+ return (
+ <div className="flex items-center gap-1" key={value}>
+ <RadioGroupItem
+ key={value}
+ value={value}
+ id={`${path}-${value}`}
+ />
+ <FormLabel
+ className="whitespace-pre"
+ htmlFor={`${path}-${value}`}
+ >
+ {Strings.startCase(value)}
+ </FormLabel>
+ </div>
+ );
+ })}
+ </RadioGroup>
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ );
+ }
+
+ return (
+ <FormField
+ control={form.control}
+ name={path}
+ disabled={disabled}
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel className="whitespace-pre">{label}</FormLabel>
+ <FormDescription>{description}</FormDescription>
+ <FormControl>
+ <Select value={field.value} onValueChange={field.onChange}>
+ <SelectTrigger className="min-w-[210px]">
+ <SelectValue placeholder="--" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectGroup>
+ {options.map((value: string) => {
+ return (
+ <SelectItem key={value} value={value}>
+ {textTransform?.(value) ?? value}
+ </SelectItem>
+ );
+ })}
+ {options.length === 0 && (
+ <SelectItem disabled={true} value="--">
+ No options
+ </SelectItem>
+ )}
+ </SelectGroup>
+ </SelectContent>
+ </Select>
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ );
+};
+
+/**
+ * Type: string[]
+ * Known options
+ */
+const MultiSelectFormField = ({
+ schema,
+ form,
+ path,
+ options,
+ itemLabel,
+ showSwitchable,
+}: {
+ schema: z.ZodEnum<any> | z.ZodString | z.ZodEnum<any> | z.ZodArray<any>;
+ form: UseFormReturn<any>;
+ path: Path<any>;
+ itemLabel?: string;
+ options: string[];
+ showSwitchable?: boolean;
+}) => {
+ const { label, description, placeholder } = FieldOptions.parse(
+ schema._def.description
+ );
+
+ const resolvePlaceholder =
+ placeholder ??
+ (itemLabel ? `Select ${itemLabel?.toLowerCase()}` : undefined);
+
+ return (
+ <FormField
+ control={form.control}
+ name={path}
+ render={({ field }) => {
+ const valueAsArray = ensureStringArray(field.value);
+ return (
+ <FormItem>
+ <FormLabel className="whitespace-pre">{label}</FormLabel>
+ <FormDescription>{description}</FormDescription>
+ <FormControl>
+ {showSwitchable ? (
+ <SwitchableMultiSelect
+ {...field}
+ value={valueAsArray}
+ options={options}
+ placeholder={resolvePlaceholder}
+ />
+ ) : (
+ <Combobox
+ className="min-w-[210px]"
+ placeholder={resolvePlaceholder}
+ displayValue={(option: string) => Strings.startCase(option)}
+ multiple={true}
+ chips={true}
+ keepPopoverOpenOnSelect={true}
+ value={valueAsArray}
+ onValueChange={field.onChange}
+ >
+ {options.map((option) => (
+ <ComboboxItem key={option} value={option}>
+ {option}
+ </ComboboxItem>
+ ))}
+ </Combobox>
+ )}
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ );
+ }}
+ />
+ );
+};
+
+/**
+ * Type: string
+ * Special: column_values
+ */
+const ColumnValuesFormField = ({
+ schema,
+ form,
+ path,
+}: {
+ schema: z.ZodString;
+ form: UseFormReturn<any>;
+ path: Path<any>;
+}) => {
+ const { label, description, placeholder } = FieldOptions.parse(
+ schema._def.description
+ );
+ const column = useContext(ColumnNameContext);
+ const fetchValues = useContext(ColumnFetchValuesContext);
+ const { data, loading } = useAsyncData(() => {
+ return fetchValues({ column });
+ }, [column]);
+
+ const options = data?.values || [];
+
+ // loaded with no options
+ if (options.length === 0 && !loading) {
+ return <StringFormField schema={schema} form={form} path={path} />;
+ }
+
+ const optionsAsStrings = options.map(String);
+ return (
+ <FormField
+ control={form.control}
+ name={path}
+ render={({ field }) => {
+ return (
+ <FormItem>
+ <FormLabel className="whitespace-pre">{label}</FormLabel>
+ <FormDescription>{description}</FormDescription>
+ <FormControl>
+ <Combobox
+ className="min-w-[210px]"
+ placeholder={placeholder}
+ multiple={false}
+ displayValue={(option: string) => option}
+ value={
+ Array.isArray(field.value) ? field.value[0] : field.value
+ }
+ onValueChange={field.onChange}
+ >
+ {optionsAsStrings.map((option) => (
+ <ComboboxItem key={option} value={option}>
+ {option}
+ </ComboboxItem>
+ ))}
+ </Combobox>
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ );
+ }}
+ />
+ );
+};
+
+/**
+ * Type: string[]
+ * Special: column_values
+ */
+const MultiColumnValuesFormField = ({
+ schema,
+ form,
+ path,
+}: {
+ schema: z.ZodString | z.ZodArray<any>;
+ form: UseFormReturn<any>;
+ path: Path<any>;
+}) => {
+ const column = useContext(ColumnNameContext);
+ const fetchValues = useContext(ColumnFetchValuesContext);
+ const { data, loading } = useAsyncData(() => {
+ return fetchValues({ column });
+ }, [column]);
+
+ const options = data?.values || [];
+
+ // loaded with no options
+ if (options.length === 0 && !loading) {
+ return <MultiStringFormField schema={schema} form={form} path={path} />;
+ }
+
+ const optionsAsStrings = options.map(String);
+ return (
+ <MultiSelectFormField
+ schema={schema}
+ form={form}
+ path={path}
+ showSwitchable={true}
+ options={optionsAsStrings}
+ />
+ );
+};
diff --git a/frontend/src/plugins/impl/data-frames/forms/options.ts b/frontend/src/plugins/impl/data-frames/forms/options.ts
index 5b7dadd04f..3f9532f2e0 100644
--- a/frontend/src/plugins/impl/data-frames/forms/options.ts
+++ b/frontend/src/plugins/impl/data-frames/forms/options.ts
@@ -11,7 +11,8 @@ export interface FieldOptions {
| "column_type"
| "radio_group"
| "column_filter"
- | "text_area_multiline";
+ | "text_area_multiline"
+ | "column_values";
}
// eslint-disable-next-line @typescript-eslint/no-redeclare
diff --git a/frontend/src/plugins/impl/data-frames/panel.tsx b/frontend/src/plugins/impl/data-frames/panel.tsx
index f0826acdd4..6b40638963 100644
--- a/frontend/src/plugins/impl/data-frames/panel.tsx
+++ b/frontend/src/plugins/impl/data-frames/panel.tsx
@@ -34,7 +34,10 @@ import {
Trash2Icon,
} from "lucide-react";
import { cn } from "../../../lib/utils";
-import { ColumnContext } from "@/plugins/impl/data-frames/forms/context";
+import {
+ ColumnFetchValuesContext,
+ ColumnInfoContext,
+} from "@/plugins/impl/data-frames/forms/context";
import useEvent from "react-use-event-hook";
import { ColumnDataTypes } from "./types";
import { getUpdatedColumnTypes } from "./utils/getUpdatedColumnTypes";
@@ -45,6 +48,10 @@ interface Props {
initialValue: Transformations;
onChange: (value: Transformations) => void;
onInvalidChange: (value: Transformations) => void;
+ getColumnValues: (req: { column: string }) => Promise<{
+ values: unknown[];
+ too_many_values: boolean;
+ }>;
}
export const TransformPanel: React.FC<Props> = ({
@@ -52,6 +59,7 @@ export const TransformPanel: React.FC<Props> = ({
columns,
onChange,
onInvalidChange,
+ getColumnValues,
}) => {
const form = useForm<z.infer<typeof TransformationsSchema>>({
resolver: zodResolver(TransformationsSchema),
@@ -113,46 +121,48 @@ export const TransformPanel: React.FC<Props> = ({
};
return (
- <ColumnContext.Provider value={effectiveColumns}>
- <form
- onSubmit={(e) => e.preventDefault()}
- className="flex flex-row max-h-[400px] overflow-hidden bg-white border rounded-t"
- >
- <Sidebar
- items={form.watch("transforms")}
- selected={selectedTransform}
- onSelect={(index) => {
- setSelectedTransform(index);
- }}
- onDelete={(index) => {
- transformsField.remove(index);
- const indexBefore = index - 1;
- setSelectedTransform(Math.max(indexBefore, 0));
- }}
- onAdd={handleAddTransform}
- />
- <div className="flex flex-col flex-1 p-4 overflow-auto min-h-[200px] border-l">
- {selectedTransform !== undefined && selectedTransformSchema && (
- <ZodForm
- key={`transforms.${selectedTransform}`}
- form={form}
- schema={selectedTransformSchema}
- path={`transforms.${selectedTransform}`}
- />
- )}
- {(selectedTransform === undefined || !selectedTransformSchema) && (
- <div className="flex flex-col items-center justify-center flex-grow gap-3">
- <MousePointerSquareDashedIcon className="w-8 h-8 text-muted-foreground" />
- <AddTransformDropdown onAdd={handleAddTransform}>
- <Button variant="text" size="xs">
- <div className="text-sm">Select a transform to begin</div>
- </Button>
- </AddTransformDropdown>
- </div>
- )}
- </div>
- </form>
- </ColumnContext.Provider>
+ <ColumnInfoContext.Provider value={effectiveColumns}>
+ <ColumnFetchValuesContext.Provider value={getColumnValues}>
+ <form
+ onSubmit={(e) => e.preventDefault()}
+ className="flex flex-row max-h-[400px] overflow-hidden bg-background"
+ >
+ <Sidebar
+ items={form.watch("transforms")}
+ selected={selectedTransform}
+ onSelect={(index) => {
+ setSelectedTransform(index);
+ }}
+ onDelete={(index) => {
+ transformsField.remove(index);
+ const indexBefore = index - 1;
+ setSelectedTransform(Math.max(indexBefore, 0));
+ }}
+ onAdd={handleAddTransform}
+ />
+ <div className="flex flex-col flex-1 p-4 overflow-auto min-h-[200px] border-l">
+ {selectedTransform !== undefined && selectedTransformSchema && (
+ <ZodForm
+ key={`transforms.${selectedTransform}`}
+ form={form}
+ schema={selectedTransformSchema}
+ path={`transforms.${selectedTransform}`}
+ />
+ )}
+ {(selectedTransform === undefined || !selectedTransformSchema) && (
+ <div className="flex flex-col items-center justify-center flex-grow gap-3">
+ <MousePointerSquareDashedIcon className="w-8 h-8 text-muted-foreground" />
+ <AddTransformDropdown onAdd={handleAddTransform}>
+ <Button variant="text" size="xs">
+ <div className="text-sm">Select a transform to begin</div>
+ </Button>
+ </AddTransformDropdown>
+ </div>
+ )}
+ </div>
+ </form>
+ </ColumnFetchValuesContext.Provider>
+ </ColumnInfoContext.Provider>
);
};
@@ -203,7 +213,7 @@ export const Sidebar: React.FC<SidebarProps> = ({
);
})}
</div>
- <div className="flex flex-row flex-shrink-0 border-t">
+ <div className="flex flex-row flex-shrink-0">
<AddTransformDropdown onAdd={onAdd}>
<Button
variant="text"
diff --git a/frontend/src/plugins/impl/data-frames/python/code-panel.tsx b/frontend/src/plugins/impl/data-frames/python/code-panel.tsx
index 8d27ea3387..a4a2d75005 100644
--- a/frontend/src/plugins/impl/data-frames/python/code-panel.tsx
+++ b/frontend/src/plugins/impl/data-frames/python/code-panel.tsx
@@ -26,7 +26,7 @@ const PythonCode = (props: { code: string }) => {
return (
<div className="border-t border-x rounded-t overflow-hidden">
<CodeMirror
- minHeight="100px"
+ minHeight="200px"
height="100%"
editable={true}
extensions={[python()]}
diff --git a/frontend/src/plugins/impl/data-frames/schema.ts b/frontend/src/plugins/impl/data-frames/schema.ts
index 87fc30cb45..a08c5fd0fc 100644
--- a/frontend/src/plugins/impl/data-frames/schema.ts
+++ b/frontend/src/plugins/impl/data-frames/schema.ts
@@ -19,7 +19,7 @@ const column_id = z
const column_id_array = z
.array(column_id.describe(FieldOptions.of({ special: "column_id" })))
.min(1, "At least one column is required")
- .default([""])
+ .default([])
.describe(FieldOptions.of({ label: "Columns" }));
const ColumnConversionTransformSchema = z
@@ -112,6 +112,7 @@ const AggregateTransformSchema = z
column_ids: column_id_array,
aggregations: z
.array(z.enum(AGGREGATION_FNS))
+ .min(1, "At least one aggregation is required")
.default(["count"])
.describe(FieldOptions.of({ label: "Aggregations" })),
})
diff --git a/frontend/src/plugins/impl/data-frames/utils/operators.ts b/frontend/src/plugins/impl/data-frames/utils/operators.ts
index 51b2826c41..6f6827905e 100644
--- a/frontend/src/plugins/impl/data-frames/utils/operators.ts
+++ b/frontend/src/plugins/impl/data-frames/utils/operators.ts
@@ -8,6 +8,14 @@ const Schema = {
.string()
.min(1)
.describe(FieldOptions.of({ label: "Value" })),
+ stringColumnValues: z
+ .string()
+ .min(1)
+ .describe(FieldOptions.of({ label: "Value", special: "column_values" })),
+ stringMultiColumnValues: z
+ .array(z.string())
+ .min(1)
+ .describe(FieldOptions.of({ label: "Value", special: "column_values" })),
date: z.coerce.date().describe(FieldOptions.of({ label: "Value" })),
stringArray: z
.array(z.string())
@@ -49,13 +57,13 @@ export const DATE_OPERATORS = {
};
export const STRING_OPERATORS = {
- equals: [Schema.string],
- does_not_equal: [Schema.string],
+ equals: [Schema.stringColumnValues],
+ does_not_equal: [Schema.stringColumnValues],
contains: [Schema.string],
regex: [Schema.string],
starts_with: [Schema.string],
ends_with: [Schema.string],
- in: [Schema.stringArray],
+ in: [Schema.stringMultiColumnValues],
};
export const ALL_OPERATORS = {
diff --git a/frontend/src/stories/dataframe.stories.tsx b/frontend/src/stories/dataframe.stories.tsx
index 7ffacc139b..38d600056a 100644
--- a/frontend/src/stories/dataframe.stories.tsx
+++ b/frontend/src/stories/dataframe.stories.tsx
@@ -17,6 +17,10 @@ export const DataFrame: StoryObj = {
const [value, setValue] = useState<Transformations>();
return (
<DataFrameComponent
+ get_column_values={async () => ({
+ values: Array.from({ length: 100 }).map((_, i) => `value ${i}`),
+ too_many_values: false,
+ })}
columns={{
name: "object",
age: "int",
@@ -25,7 +29,10 @@ export const DataFrame: StoryObj = {
}}
dataframeName={"df"}
value={value}
- setValue={setValue}
+ setValue={(v) => {
+ console.log(v);
+ setValue(v);
+ }}
get_dataframe={() => Promise.reject({})}
/>
);
diff --git a/marimo/_plugins/ui/_impl/dataframes/dataframe.py b/marimo/_plugins/ui/_impl/dataframes/dataframe.py
index 7102f6d9ac..4746a83cc5 100644
--- a/marimo/_plugins/ui/_impl/dataframes/dataframe.py
+++ b/marimo/_plugins/ui/_impl/dataframes/dataframe.py
@@ -14,24 +14,30 @@ import marimo._output.data.data as mo_data
from marimo._output.rich_help import mddoc
from marimo._plugins.ui._core.ui_element import UIElement
from marimo._plugins.ui._impl.utils.dataframe import get_row_headers
-from marimo._runtime.functions import Function
+from marimo._runtime.functions import EmptyArgs, Function
from marimo._utils.parse_dataclass import parse_raw
from .handlers import TransformsContainer
from .transforms import Transformations
-@dataclass
-class EmptyArgs:
- ...
-
-
@dataclass
class GetDataFrameResponse:
url: str
row_headers: List[tuple[str, List[str | int | float]]]
+@dataclass
+class GetColumnValuesArgs:
+ column: str
+
+
+@dataclass
+class GetColumnValuesResponse:
+ values: List[str | int | float]
+ too_many_values: bool
+
+
@mddoc
class dataframe(UIElement[Dict[str, Any], "pd.DataFrame"]):
"""
@@ -96,6 +102,11 @@ class dataframe(UIElement[Dict[str, Any], "pd.DataFrame"]):
arg_cls=EmptyArgs,
function=self.get_dataframe,
),
+ Function(
+ name=self.get_column_values.__name__,
+ arg_cls=GetColumnValuesArgs,
+ function=self.get_column_values,
+ ),
),
)
@@ -109,6 +120,29 @@ class dataframe(UIElement[Dict[str, Any], "pd.DataFrame"]):
row_headers=get_row_headers(self._value),
)
+ def get_column_values(
+ self, args: GetColumnValuesArgs
+ ) -> GetColumnValuesResponse:
+ """Get all the unique values in a column."""
+ LIMIT = 500
+
+ if args.column not in self._data.columns:
+ raise Exception("Column %s does not exist" % args.column)
+
+ # We get the unique values from the original dataframe, not the
+ # transformed one
+ unique_values = self._data[args.column].unique().tolist()
+ if len(unique_values) <= LIMIT:
+ return GetColumnValuesResponse(
+ values=list(sorted(unique_values, key=str)),
+ too_many_values=False,
+ )
+ else:
+ return GetColumnValuesResponse(
+ values=[],
+ too_many_values=True,
+ )
+
def _convert_value(self, value: Dict[str, Any]) -> pd.DataFrame:
if value is None:
self._error = None