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.

chore: charts tab name & refactor (#4841)

Shahmir Varqha249d81df4eb4
diff --git a/frontend/src/components/data-table/chart-transforms/chart-components.tsx b/frontend/src/components/data-table/chart-transforms/chart-components.tsx
deleted file mode 100644
index 9d26868051..0000000000
--- a/frontend/src/components/data-table/chart-transforms/chart-components.tsx
+++ /dev/null
@@ -1,265 +0,0 @@
-/* Copyright 2024 Marimo. All rights reserved. */
-
-import type { LucideProps } from "lucide-react";
-import { cn } from "@/utils/cn";
-import {
- ArrowDownWideNarrowIcon,
- ArrowUpWideNarrowIcon,
- ChevronDown,
- Loader2,
-} from "lucide-react";
-import { capitalize } from "lodash-es";
-import * as SelectPrimitive from "@radix-ui/react-select";
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectValue,
-} from "@/components/ui/select";
-import { CHART_TYPE_ICON, COUNT_FIELD } from "./constants";
-import { ErrorBanner } from "@/plugins/impl/common/error-banner";
-import { buttonVariants } from "@/components/ui/button";
-import { type UseFormReturn, useWatch } from "react-hook-form";
-import type { z } from "zod";
-import type { ChartSchema } from "./chart-schemas";
-import { FieldValidators, TypeConverters } from "./chart-spec";
-import {
- ColumnSelector,
- AggregationSelect,
- DataTypeSelect,
- TimeUnitSelect,
- SelectField,
- BooleanField,
- type Field,
-} from "./form-components";
-import { CHART_TYPES, type ChartType, SORT_TYPES } from "./types";
-
-export const IconWithText: React.FC<{
- Icon: React.ForwardRefExoticComponent<
- Omit<LucideProps, "ref"> & React.RefAttributes<SVGSVGElement>
- >;
- text: string;
-}> = ({ Icon, text }) => {
- return (
- <div className="flex items-center">
- <Icon className="w-3 h-3 mr-2" />
- <span>{text}</span>
- </div>
- );
-};
-
-export const Title: React.FC<{ text: string }> = ({ text }) => {
- return <span className="font-semibold my-0">{text}</span>;
-};
-
-export const TabContainer: React.FC<{
- className?: string;
- children: React.ReactNode;
-}> = ({ children, className }) => {
- return <div className={cn("flex flex-col gap-2", className)}>{children}</div>;
-};
-
-export const ChartLoadingState: React.FC = () => (
- <div className="flex items-center gap-2 justify-center h-full w-full">
- <Loader2 className="w-10 h-10 animate-spin" strokeWidth={1} />
- <span>Loading chart...</span>
- </div>
-);
-
-export const ChartErrorState: React.FC<{ error: Error }> = ({ error }) => (
- <div className="flex items-center justify-center h-full w-full">
- <ErrorBanner error={error} />
- </div>
-);
-
-export const ChartTypeSelect: React.FC<{
- value: ChartType;
- onValueChange: (value: ChartType) => void;
-}> = ({ value, onValueChange }) => {
- return (
- <Select value={value} onValueChange={onValueChange}>
- <div className="flex flex-row gap-2 items-center">
- <SelectPrimitive.Trigger
- className={buttonVariants({
- variant: "outline",
- className: "user-select-none w-full justify-between px-3",
- })}
- >
- <SelectValue />
- <SelectPrimitive.Icon asChild={true}>
- <ChevronDown className="h-4 w-4 opacity-50" />
- </SelectPrimitive.Icon>
- </SelectPrimitive.Trigger>
- <SelectContent>
- {CHART_TYPES.map((chartType) => (
- <ChartSelectItem key={chartType} chartType={chartType} />
- ))}
- </SelectContent>
- </div>
- </Select>
- );
-};
-
-const ChartSelectItem: React.FC<{ chartType: ChartType }> = ({ chartType }) => {
- const Icon = CHART_TYPE_ICON[chartType];
- return (
- <SelectItem value={chartType} className="gap-2">
- <div className="flex items-center">
- <Icon className="w-4 h-4 mr-2" />
- {capitalize(chartType)}
- </div>
- </SelectItem>
- );
-};
-
-export const XAxis: React.FC<{
- form: UseFormReturn<z.infer<typeof ChartSchema>>;
- fields: Field[];
-}> = ({ form, fields }) => {
- const formValues = useWatch({ control: form.control });
- const xColumn = formValues.general?.xColumn;
- const xColumnExists = FieldValidators.exists(xColumn?.field);
-
- const inferredXDataType = xColumn?.type
- ? TypeConverters.toSelectableDataType(xColumn.type)
- : "string";
-
- const selectedXDataType = xColumn?.selectedDataType || inferredXDataType;
- const isXCountField = xColumn?.field === COUNT_FIELD;
-
- const shouldShowXAggregation =
- xColumnExists && selectedXDataType !== "temporal" && !isXCountField;
-
- const shouldShowXTimeUnit =
- xColumnExists && selectedXDataType === "temporal" && !isXCountField;
-
- return (
- <>
- <Title text="X-Axis" />
- <div className="flex flex-row gap-2 justify-between">
- <ColumnSelector
- form={form}
- name="general.xColumn.field"
- columns={fields}
- />
- {shouldShowXAggregation && (
- <AggregationSelect form={form} name="general.xColumn.aggregate" />
- )}
- </div>
- {xColumnExists && !isXCountField && (
- <DataTypeSelect
- form={form}
- formFieldLabel="Data Type"
- name="general.xColumn.selectedDataType"
- defaultValue={inferredXDataType}
- />
- )}
- {shouldShowXTimeUnit && (
- <TimeUnitSelect
- form={form}
- name="general.xColumn.timeUnit"
- formFieldLabel="Time Resolution"
- />
- )}
- {xColumnExists && !isXCountField && (
- <SelectField
- form={form}
- name="general.xColumn.sort"
- formFieldLabel="Sort"
- options={SORT_TYPES.map((type) => ({
- display: (
- <IconWithText
- Icon={
- type === "ascending"
- ? ArrowUpWideNarrowIcon
- : ArrowDownWideNarrowIcon
- }
- text={capitalize(type)}
- />
- ),
- value: type,
- }))}
- defaultValue={formValues.general?.xColumn?.sort ?? "ascending"}
- />
- )}
- </>
- );
-};
-
-export const YAxis: React.FC<{
- form: UseFormReturn<z.infer<typeof ChartSchema>>;
- fields: Field[];
-}> = ({ form, fields }) => {
- const formValues = useWatch({ control: form.control });
- const yColumn = formValues.general?.yColumn;
- const yColumnExists = FieldValidators.exists(yColumn?.field);
-
- const inferredYDataType = yColumn?.type
- ? TypeConverters.toSelectableDataType(yColumn.type)
- : "string";
-
- const selectedYDataType = yColumn?.selectedDataType || inferredYDataType;
- const isYCountField = yColumn?.field === COUNT_FIELD;
-
- const shouldShowYAggregation =
- yColumnExists && selectedYDataType !== "temporal" && !isYCountField;
-
- const shouldShowYTimeUnit =
- yColumnExists && selectedYDataType === "temporal" && !isYCountField;
-
- return (
- <>
- <Title text="Y-Axis" />
- <div className="flex flex-row gap-2 justify-between">
- <ColumnSelector
- form={form}
- name="general.yColumn.field"
- columns={fields}
- />
- {shouldShowYAggregation && (
- <AggregationSelect form={form} name="general.yColumn.aggregate" />
- )}
- </div>
-
- {yColumnExists && !isYCountField && (
- <DataTypeSelect
- form={form}
- formFieldLabel="Data Type"
- name="general.yColumn.selectedDataType"
- defaultValue={inferredYDataType}
- />
- )}
- {shouldShowYTimeUnit && (
- <TimeUnitSelect
- form={form}
- name="general.yColumn.timeUnit"
- formFieldLabel="Time Resolution"
- />
- )}
- </>
- );
-};
-
-export const ColorByAxis: React.FC<{
- form: UseFormReturn<z.infer<typeof ChartSchema>>;
- fields: Field[];
-}> = ({ form, fields }) => {
- return (
- <>
- <BooleanField
- form={form}
- name="general.horizontal"
- formFieldLabel="Horizontal chart"
- />
- <Title text="Color by" />
- <div className="flex flex-row justify-between">
- <ColumnSelector
- form={form}
- name="general.colorByColumn.field"
- columns={fields}
- />
- <AggregationSelect form={form} name="general.colorByColumn.aggregate" />
- </div>
- </>
- );
-};
diff --git a/frontend/src/components/data-table/chart-transforms/chart-spec.tsx b/frontend/src/components/data-table/chart-transforms/chart-spec.tsx
deleted file mode 100644
index f21f99b8ac..0000000000
--- a/frontend/src/components/data-table/chart-transforms/chart-spec.tsx
+++ /dev/null
@@ -1,450 +0,0 @@
-/* Copyright 2024 Marimo. All rights reserved. */
-import type { TopLevelSpec } from "vega-lite";
-import type { ResolvedTheme } from "@/theme/useTheme";
-import type { DataType } from "@/core/kernel/messages";
-import {
- type BinSchema,
- DEFAULT_BIN_VALUE,
- type ChartSchema,
- type AxisSchema,
-} from "./chart-schemas";
-import {
- ChartType,
- NONE_AGGREGATION,
- type SelectableDataType,
- type TimeUnitTooltip,
-} from "./types";
-import type { z } from "zod";
-import type { Mark } from "@/plugins/impl/vega/types";
-import { logNever } from "@/utils/assertNever";
-import type { Type } from "vega-lite/build/src/type";
-import type {
- ColorDef,
- OffsetDef,
- PolarDef,
- PositionDef,
- StringFieldDef,
-} from "vega-lite/build/src/channeldef";
-import type { ColorScheme } from "vega";
-import type { TypedString } from "@/utils/typed";
-import { COUNT_FIELD, DEFAULT_COLOR_SCHEME, EMPTY_VALUE } from "./constants";
-import type { Tooltip } from "./form-components";
-
-/**
- * Convert marimo chart configuration to Vega-Lite specification.
- */
-
-export type ErrorMessage = TypedString<"ErrorMessage">;
-
-export function createVegaSpec(
- chartType: ChartType,
- data: object[],
- formValues: z.infer<typeof ChartSchema>,
- theme: ResolvedTheme,
- width: number | "container",
- height: number,
-): TopLevelSpec | ErrorMessage {
- const { xColumn, yColumn, colorByColumn, horizontal, stacking, title } =
- formValues.general;
-
- if (chartType === ChartType.PIE) {
- return getPieChartSpec(data, formValues, theme, width, height);
- }
-
- // Validate required fields
- if (!FieldValidators.exists(xColumn?.field)) {
- return "X-axis column is required" as ErrorMessage;
- }
- if (!FieldValidators.exists(yColumn?.field)) {
- return "Y-axis column is required" as ErrorMessage;
- }
-
- // Get axis labels
- const xAxisLabel = FieldValidators.getLabel(
- xColumn.field,
- formValues.xAxis?.label,
- );
- const yAxisLabel = FieldValidators.getLabel(
- FieldValidators.getAggregatedLabel(yColumn.field, yColumn.aggregate),
- formValues.yAxis?.label,
- );
-
- // Determine encoding keys based on chart type
- const xEncodingKey = "x";
- const yEncodingKey = "y";
-
- // Create encodings
- const xEncoding = getAxisEncoding(
- xColumn,
- formValues.xAxis?.bin,
- xAxisLabel,
- colorByColumn?.field && horizontal ? stacking : undefined,
- chartType,
- );
-
- const yEncoding = getAxisEncoding(
- yColumn,
- formValues.yAxis?.bin,
- yAxisLabel,
- colorByColumn?.field && !horizontal ? stacking : undefined,
- chartType,
- );
-
- // Create the final spec
- return {
- ...getBaseSpec(data, formValues, theme, width, height, title),
- mark: { type: TypeConverters.toMark(chartType) },
- encoding: {
- [xEncodingKey]: horizontal ? yEncoding : xEncoding,
- [yEncodingKey]: horizontal ? xEncoding : yEncoding,
- xOffset: EncodingUtils.getOffset(chartType, formValues),
- ...ColorUtils.getColor(chartType, formValues),
- tooltip: EncodingUtils.getTooltips(formValues),
- },
- };
-}
-
-export function getAxisEncoding(
- column: NonNullable<z.infer<typeof AxisSchema>>,
- binValues: z.infer<typeof BinSchema> | undefined,
- label: string | undefined,
- stack: boolean | undefined,
- chartType: ChartType,
-): PositionDef<string> {
- if (column.field === COUNT_FIELD) {
- return {
- aggregate: "count",
- type: "quantitative",
- bin: EncodingUtils.getBin(binValues),
- title: label === COUNT_FIELD ? undefined : label,
- stack: stack,
- };
- }
-
- return {
- field: column.field,
- type: TypeConverters.toVegaType(column.selectedDataType || "unknown"),
- bin: EncodingUtils.getBin(binValues, chartType),
- title: label,
- stack: stack,
- aggregate:
- column.aggregate === NONE_AGGREGATION ? undefined : column.aggregate,
- timeUnit:
- column.selectedDataType === "temporal" ? column.timeUnit : undefined,
- };
-}
-
-function getPieChartSpec(
- data: object[],
- formValues: z.infer<typeof ChartSchema>,
- theme: ResolvedTheme,
- width: number | "container",
- height: number,
-) {
- const { yColumn, colorByColumn, title } = formValues.general;
-
- if (!FieldValidators.exists(colorByColumn?.field)) {
- return "Color by column is required" as ErrorMessage;
- }
-
- if (!FieldValidators.exists(yColumn?.field)) {
- return "Size by column is required" as ErrorMessage;
- }
-
- const colorFieldLabel = FieldValidators.getLabel(
- colorByColumn.field,
- formValues.xAxis?.label,
- );
-
- const thetaFieldLabel = FieldValidators.getLabel(
- yColumn.field,
- formValues.xAxis?.label,
- );
-
- const thetaEncoding: PolarDef<string> = getAxisEncoding(
- yColumn,
- formValues.xAxis?.bin,
- thetaFieldLabel,
- undefined,
- ChartType.PIE,
- );
-
- const colorEncoding: ColorDef<string> = {
- field: colorByColumn.field,
- type: TypeConverters.toVegaType(
- colorByColumn.selectedDataType || "unknown",
- ),
- scale: EncodingUtils.getColorInScale(formValues),
- title: colorFieldLabel,
- };
-
- return {
- ...getBaseSpec(data, formValues, theme, width, height, title),
- mark: {
- type: TypeConverters.toMark(ChartType.PIE),
- innerRadius: formValues.style?.innerRadius,
- },
- encoding: {
- theta: thetaEncoding,
- color: colorEncoding,
- tooltip: EncodingUtils.getTooltips(formValues),
- },
- };
-}
-
-function getBaseSpec(
- data: object[],
- formValues: z.infer<typeof ChartSchema>,
- theme: ResolvedTheme,
- width: number | "container",
- height: number,
- title?: string,
-) {
- return {
- $schema: "https://vega.github.io/schema/vega-lite/v5.json",
- background: theme === "dark" ? "dark" : "white",
- title: title,
- data: { values: data },
- height: formValues.yAxis?.height ?? height,
- width: formValues.xAxis?.width ?? width,
- };
-}
-
-// Type conversion utilities
-export const TypeConverters = {
- toVegaType(dataType: DataType | SelectableDataType): Type | undefined {
- switch (dataType) {
- case "number":
- case "integer":
- return "quantitative";
- case "string":
- case "boolean":
- case "unknown":
- return "nominal";
- case "date":
- case "datetime":
- case "time":
- case "temporal":
- return "temporal";
- default:
- logNever(dataType);
- return undefined;
- }
- },
-
- toSelectableDataType(type: DataType): SelectableDataType {
- switch (type) {
- case "number":
- case "integer":
- return "number";
- case "string":
- case "boolean":
- case "unknown":
- return "string";
- case "date":
- case "datetime":
- case "time":
- return "temporal";
- default:
- logNever(type);
- return "string";
- }
- },
-
- toMark(chartType: ChartType): Mark {
- switch (chartType) {
- case ChartType.PIE:
- return "arc";
- case ChartType.SCATTER:
- return "point";
- case ChartType.HEATMAP:
- return "rect";
- default:
- return chartType;
- }
- },
-};
-
-// Field validation utilities
-export const FieldValidators = {
- exists(field: string | undefined): field is string {
- return field !== undefined && field.trim() !== EMPTY_VALUE;
- },
-
- getLabel(field: string, label?: string): string {
- return label?.trim() || field;
- },
-
- getAggregatedLabel(field: string, agg?: string): string {
- if (!agg || agg === NONE_AGGREGATION) {
- return field;
- }
- return `${agg.toUpperCase()}(${field})`;
- },
-};
-
-// Encoding utilities
-const EncodingUtils = {
- getBin(binValues?: z.infer<typeof BinSchema>, chartType?: ChartType) {
- if (chartType === ChartType.HEATMAP) {
- return { maxbins: binValues?.maxbins };
- }
-
- if (!binValues?.binned) {
- return undefined;
- }
-
- return binValues.step === DEFAULT_BIN_VALUE
- ? true
- : { binned: true, step: binValues.step };
- },
-
- getColorInScale(formValues: z.infer<typeof ChartSchema>) {
- const colorRange = formValues.color?.range;
- if (colorRange?.length) {
- return { range: colorRange };
- }
-
- const scheme = formValues.color?.scheme;
- return scheme === DEFAULT_COLOR_SCHEME
- ? undefined
- : { scheme: scheme as ColorScheme };
- },
-
- getOffset(
- chartType: ChartType,
- formValues: z.infer<typeof ChartSchema>,
- ): OffsetDef<string> | undefined {
- // Offset only applies to bar charts, to unstack them
- if (
- formValues.general.stacking ||
- !FieldValidators.exists(formValues.general.colorByColumn?.field) ||
- chartType !== ChartType.BAR
- ) {
- return undefined;
- }
- return { field: formValues.general.colorByColumn?.field };
- },
-
- getTooltipAggregate(
- field: string,
- yColumn?: z.infer<typeof AxisSchema>,
- ): "count" | "sum" | "mean" | "median" | "min" | "max" | undefined {
- if (field !== yColumn?.field) {
- return undefined;
- }
- return yColumn.aggregate === NONE_AGGREGATION
- ? undefined
- : (yColumn.aggregate as
- | "count"
- | "sum"
- | "mean"
- | "median"
- | "min"
- | "max");
- },
-
- getTooltipFormat(dataType: DataType): string | undefined {
- switch (dataType) {
- case "integer":
- return ",.0f"; // Use comma grouping and no decimals
- case "number":
- return ",.2f"; // Use comma grouping and 2 decimal places
- default:
- return undefined;
- }
- },
-
- getTooltipTimeUnit(
- tooltip: Tooltip,
- formValues: z.infer<typeof ChartSchema>,
- ): TimeUnitTooltip | undefined {
- const xColumn = formValues.general.xColumn;
- const yColumn = formValues.general.yColumn;
- const colorByColumn = formValues.general.colorByColumn;
- const columns = [xColumn, yColumn, colorByColumn];
-
- // Check if tooltip field matches any temporal column with timeUnit
- const matchingColumn = columns.find(
- (col) =>
- tooltip.field === col?.field &&
- col?.selectedDataType === "temporal" &&
- col?.timeUnit,
- );
-
- if (matchingColumn?.timeUnit) {
- return matchingColumn.timeUnit;
- }
-
- switch (tooltip.type) {
- case "datetime":
- return "yearmonthdatehoursminutesseconds";
- case "date":
- return "yearmonthdate";
- case "time":
- return "hoursminutesseconds";
- default:
- return undefined;
- }
- },
-
- getTooltips(formValues: z.infer<typeof ChartSchema>) {
- if (!formValues.general.tooltips) {
- return undefined;
- }
-
- return formValues.general.tooltips.map(
- (tooltip): StringFieldDef<string> => {
- const timeUnit = this.getTooltipTimeUnit(tooltip, formValues);
- return {
- field: tooltip.field,
- aggregate: this.getTooltipAggregate(
- tooltip.field,
- formValues.general.yColumn,
- ),
- format: this.getTooltipFormat(tooltip.type),
- timeUnit: timeUnit,
- title: timeUnit ? tooltip.field : undefined,
- };
- },
- );
- },
-};
-
-// Color encoding utilities
-const ColorUtils = {
- getColor(
- chartType: ChartType,
- formValues: z.infer<typeof ChartSchema>,
- ): { color?: ColorDef<string> } | undefined {
- if (
- chartType === ChartType.PIE ||
- !FieldValidators.exists(formValues.general.colorByColumn?.field)
- ) {
- return undefined;
- }
-
- const colorByColumn = formValues.general.colorByColumn;
- if (colorByColumn.field === COUNT_FIELD) {
- return {
- color: {
- aggregate: "count",
- type: "quantitative",
- },
- };
- }
-
- const aggregate = formValues.general.colorByColumn.aggregate;
-
- return {
- color: {
- field: colorByColumn.field,
- type: TypeConverters.toVegaType(
- colorByColumn.selectedDataType || "unknown",
- ),
- scale: EncodingUtils.getColorInScale(formValues),
- aggregate: aggregate === NONE_AGGREGATION ? undefined : aggregate,
- },
- };
- },
-};
diff --git a/frontend/src/components/data-table/chart-transforms/chart-transforms.tsx b/frontend/src/components/data-table/chart-transforms/chart-transforms.tsx
deleted file mode 100644
index ec1bf14f0e..0000000000
--- a/frontend/src/components/data-table/chart-transforms/chart-transforms.tsx
+++ /dev/null
@@ -1,647 +0,0 @@
-/* Copyright 2024 Marimo. All rights reserved. */
-
-import React, { useState, useMemo } from "react";
-import { Button } from "@/components/ui/button";
-import {
- TableIcon,
- XIcon,
- InfoIcon,
- DatabaseIcon,
- PaintRollerIcon,
-} from "lucide-react";
-import { Tabs, TabsTrigger, TabsList, TabsContent } from "@/components/ui/tabs";
-import type { z } from "zod";
-import { useForm, useWatch, type UseFormReturn } from "react-hook-form";
-import { zodResolver } from "@hookform/resolvers/zod";
-import { ChartSchema } from "./chart-schemas";
-import { Form } from "@/components/ui/form";
-import { getDefaults } from "@/components/forms/form-utils";
-import { useAtom } from "jotai";
-import type { CellId } from "@/core/cells/ids";
-import { capitalize } from "lodash-es";
-import { type TabName, tabsStorageAtom, tabNumberAtom } from "./storage";
-import type { FieldTypesWithExternalType } from "../types";
-import { useAsyncData } from "@/hooks/useAsyncData";
-import { vegaLoadData } from "@/plugins/impl/vega/loader";
-import type { GetDataUrl } from "@/plugins/impl/DataTablePlugin";
-import {
- AggregationSelect,
- BooleanField,
- ColorArrayField,
- ColumnSelector,
- type Field,
- InputField,
- NumberField,
- DataTypeSelect,
- SelectField,
- SliderField,
- TooltipSelect,
-} from "./form-components";
-import { COLOR_SCHEMES, DEFAULT_COLOR_SCHEME } from "./constants";
-import { useDebouncedCallback } from "@/hooks/useDebounce";
-import { inferFieldTypes } from "../columns";
-import { LazyChart } from "./lazy-chart";
-import { FieldValidators, TypeConverters } from "./chart-spec";
-import {
- Accordion,
- AccordionContent,
- AccordionItem,
- AccordionTrigger,
-} from "@/components/ui/accordion";
-import {
- TabContainer,
- Title,
- ChartLoadingState,
- ChartErrorState,
- ChartTypeSelect,
- YAxis,
- ColorByAxis,
- XAxis,
-} from "./chart-components";
-import { ChartType } from "./types";
-
-const NEW_TAB_NAME = "Chart" as TabName;
-const NEW_CHART_TYPE = "line" as ChartType;
-const DEFAULT_TAB_NAME = "table" as TabName;
-const CHART_HEIGHT = 300;
-
-export interface TablePanelProps {
- cellId: CellId | null;
- dataTable: JSX.Element;
- displayHeader: boolean;
- getDataUrl?: GetDataUrl;
- fieldTypes?: FieldTypesWithExternalType | null;
-}
-
-export const TablePanel: React.FC<TablePanelProps> = ({
- cellId,
- dataTable,
- getDataUrl,
- fieldTypes,
- displayHeader,
-}) => {
- const [tabsMap, saveTabsMap] = useAtom(tabsStorageAtom);
- const tabs = cellId ? (tabsMap.get(cellId) ?? []) : [];
-
- const [tabNum, setTabNum] = useAtom(tabNumberAtom);
- const [selectedTab, setSelectedTab] = useState(DEFAULT_TAB_NAME);
-
- if (!displayHeader || (tabs.length === 0 && !displayHeader)) {
- return dataTable;
- }
-
- const handleAddTab = () => {
- if (!cellId) {
- return;
- }
- const tabName =
- tabNum === 0
- ? NEW_TAB_NAME
- : (`${NEW_TAB_NAME} ${tabNum + 1}` as TabName);
-
- const newTabs = new Map(tabsMap);
- newTabs.set(cellId, [
- ...tabs,
- {
- tabName,
- chartType: NEW_CHART_TYPE,
- config: getDefaults(ChartSchema),
- },
- ]);
-
- saveTabsMap(newTabs);
- setTabNum(tabNum + 1);
- setSelectedTab(tabName);
- };
-
- const handleDeleteTab = (tabName: TabName) => {
- if (!cellId) {
- return;
- }
- const newTabs = new Map(tabsMap);
- newTabs.set(
- cellId,
- tabs.filter((tab) => tab.tabName !== tabName),
- );
- saveTabsMap(newTabs);
- setSelectedTab(DEFAULT_TAB_NAME);
- };
-
- const saveTabChart = (
- tabName: TabName,
- chartType: ChartType,
- chartConfig: z.infer<typeof ChartSchema>,
- ) => {
- if (!cellId) {
- return;
- }
-
- const updatedTabs = new Map(tabsMap);
- updatedTabs.set(
- cellId,
- tabs.map((tab) =>
- tab.tabName === tabName
- ? { ...tab, chartType, config: chartConfig }
- : tab,
- ),
- );
- saveTabsMap(updatedTabs);
- };
-
- const saveTabChartType = (tabName: TabName, chartType: ChartType) => {
- if (!cellId) {
- return;
- }
- const newTabs = new Map(tabsMap);
- newTabs.set(
- cellId,
- tabs.map((tab) =>
- tab.tabName === tabName ? { ...tab, chartType } : tab,
- ),
- );
- saveTabsMap(newTabs);
- };
-
- return (
- <Tabs value={selectedTab} className="-mt-1">
- <TabsList>
- <TabsTrigger
- className="text-xs"
- value={DEFAULT_TAB_NAME}
- onClick={() => setSelectedTab(DEFAULT_TAB_NAME)}
- >
- <TableIcon className="w-3 h-3 mr-2" />
- Table
- </TabsTrigger>
- {tabs.map((tab, idx) => (
- <TabsTrigger
- key={idx}
- className="text-xs"
- value={tab.tabName}
- onClick={() => setSelectedTab(tab.tabName)}
- >
- {tab.tabName}
- <XIcon
- className="w-3 h-3 ml-1 mt-[0.5px] hover:text-red-500 hover:font-semibold"
- onClick={(e) => {
- e.stopPropagation();
- handleDeleteTab(tab.tabName);
- }}
- />
- </TabsTrigger>
- ))}
- <Button
- variant="text"
- size="icon"
- onClick={handleAddTab}
- title="Add chart"
- >
- +
- </Button>
- </TabsList>
-
- <TabsContent className="mt-1 overflow-hidden" value={DEFAULT_TAB_NAME}>
- {dataTable}
- </TabsContent>
- {tabs.map((tab, idx) => {
- const saveChart = (formValues: z.infer<typeof ChartSchema>) => {
- saveTabChart(tab.tabName, tab.chartType, formValues);
- };
- const saveChartType = (chartType: ChartType) => {
- saveTabChartType(tab.tabName, chartType);
- };
- return (
- <TabsContent key={idx} value={tab.tabName} className="h-[400px] mt-1">
- <ChartPanel
- chartConfig={tab.config}
- chartType={tab.chartType}
- saveChart={saveChart}
- saveChartType={saveChartType}
- getDataUrl={getDataUrl}
- fieldTypes={fieldTypes ?? inferFieldTypes(dataTable.props.data)}
- />
- </TabsContent>
- );
- })}
- </Tabs>
- );
-};
-
-export const ChartPanel: React.FC<{
- chartConfig: z.infer<typeof ChartSchema> | null;
- chartType: ChartType;
- saveChart: (formValues: z.infer<typeof ChartSchema>) => void;
- saveChartType: (chartType: ChartType) => void;
- getDataUrl?: GetDataUrl;
- fieldTypes?: FieldTypesWithExternalType | null;
-}> = ({
- chartConfig,
- chartType,
- saveChart,
- saveChartType,
- getDataUrl,
- fieldTypes,
-}) => {
- const form = useForm<z.infer<typeof ChartSchema>>({
- defaultValues: chartConfig ?? getDefaults(ChartSchema),
- resolver: zodResolver(ChartSchema),
- });
-
- const [selectedChartType, setSelectedChartType] =
- useState<ChartType>(chartType);
-
- const { data, loading, error } = useAsyncData(async () => {
- if (!getDataUrl) {
- return [];
- }
-
- const response = await getDataUrl({});
- if (Array.isArray(response.data_url)) {
- return response.data_url;
- }
-
- const chartData = await vegaLoadData(
- response.data_url,
- response.format === "arrow"
- ? { type: "arrow" }
- : response.format === "json"
- ? { type: "json" }
- : { type: "csv", parse: "auto" },
- {
- replacePeriod: true,
- },
- );
- return chartData;
- }, []);
-
- const formValues = form.watch();
-
- // This ensures the chart re-renders when the actual values change
- const memoizedFormValues = useMemo(() => {
- return structuredClone(formValues);
- }, [formValues]);
-
- // Prevent unnecessary re-renders of the chart
- const memoizedChart = useMemo(() => {
- if (loading) {
- return <ChartLoadingState />;
- }
- if (error) {
- return <ChartErrorState error={error} />;
- }
- return (
- <LazyChart
- chartType={selectedChartType}
- formValues={memoizedFormValues}
- data={data}
- width="container"
- height={CHART_HEIGHT}
- />
- );
- }, [loading, error, memoizedFormValues, data, selectedChartType]);
-
- return (
- <div className="flex flex-row gap-2 h-full rounded-md border pr-2">
- <div className="flex flex-col gap-2 w-[300px] overflow-auto px-2 py-3 scrollbar-thin">
- <ChartTypeSelect
- value={selectedChartType}
- onValueChange={(value) => {
- setSelectedChartType(value);
- saveChartType(value);
- }}
- />
-
- <ChartFormContainer
- form={form}
- saveChart={saveChart}
- fieldTypes={fieldTypes}
- chartType={selectedChartType}
- />
- </div>
- <div className="flex-1">{memoizedChart}</div>
- </div>
- );
-};
-
-const ChartFormContainer = ({
- form,
- saveChart,
- fieldTypes,
- chartType,
-}: {
- form: UseFormReturn<z.infer<typeof ChartSchema>>;
- chartType: ChartType;
- saveChart: (formValues: z.infer<typeof ChartSchema>) => void;
- fieldTypes?: FieldTypesWithExternalType | null;
-}) => {
- const fields: Field[] | undefined = fieldTypes?.map((field) => {
- return {
- name: field[0],
- type: field[1][0],
- };
- });
-
- const debouncedSave = useDebouncedCallback(() => {
- const values = form.getValues();
- saveChart(values);
- }, 300);
-
- let ChartForm = CommonChartForm;
-
- if (chartType === ChartType.PIE) {
- ChartForm = PieChartForm;
- } else if (chartType === ChartType.HEATMAP) {
- ChartForm = HeatmapChartForm;
- }
-
- return (
- <Form {...form}>
- <form onSubmit={(e) => e.preventDefault()} onChange={debouncedSave}>
- <Tabs defaultValue="data">
- <TabsList className="w-full">
- <TabsTrigger value="data" className="w-1/2 h-6">
- <DatabaseIcon className="w-4 h-4 mr-2" />
- Data
- </TabsTrigger>
- <TabsTrigger value="style" className="w-1/2 h-6">
- <PaintRollerIcon className="w-4 h-4 mr-2" />
- Style
- </TabsTrigger>
- </TabsList>
-
- <TabsContent value="data">
- <hr className="my-2" />
- <TabContainer>
- <ChartForm
- form={form}
- fields={fields ?? []}
- saveForm={debouncedSave}
- chartType={chartType}
- />
- </TabContainer>
- </TabsContent>
-
- <TabsContent value="style">
- <hr className="my-2" />
- <TabContainer>
- <StyleForm
- form={form}
- fields={fields ?? []}
- saveForm={debouncedSave}
- />
- </TabContainer>
- </TabsContent>
- </Tabs>
- </form>
- </Form>
- );
-};
-
-const CommonChartForm: React.FC<{
- form: UseFormReturn<z.infer<typeof ChartSchema>>;
- fields: Field[];
- saveForm: () => void;
- chartType: ChartType;
-}> = ({ form, fields, saveForm, chartType }) => {
- const formValues = useWatch({ control: form.control });
- const yColumn = formValues.general?.yColumn;
- const groupByColumn = formValues.general?.colorByColumn;
-
- const yColumnExists = FieldValidators.exists(yColumn?.field);
- const showStacking = FieldValidators.exists(groupByColumn?.field);
-
- return (
- <>
- <XAxis form={form} fields={fields} />
- <YAxis form={form} fields={fields} />
-
- {yColumnExists && (
- <>
- <ColorByAxis form={form} fields={fields} />
- {showStacking && (
- <div className="flex flex-row gap-2">
- <BooleanField
- form={form}
- name="general.stacking"
- formFieldLabel="Stacked"
- />
- </div>
- )}
- </>
- )}
-
- <hr className="my-2" />
- <TooltipSelect
- form={form}
- name="general.tooltips"
- fields={fields}
- saveFunction={saveForm}
- formFieldLabel="Tooltips"
- />
- </>
- );
-};
-
-const HeatmapChartForm: React.FC<{
- form: UseFormReturn<z.infer<typeof ChartSchema>>;
- fields: Field[];
- saveForm: () => void;
- chartType: ChartType;
-}> = ({ form, fields, saveForm, chartType }) => {
- const formValues = useWatch({ control: form.control });
- const xColumnExists = FieldValidators.exists(
- formValues.general?.xColumn?.field,
- );
- const yColumnExists = FieldValidators.exists(
- formValues.general?.yColumn?.field,
- );
-
- return (
- <>
- <XAxis form={form} fields={fields} />
- {xColumnExists && (
- <NumberField
- form={form}
- name="xAxis.bin.maxbins"
- formFieldLabel="Number of boxes (max)"
- className="justify-between"
- />
- )}
- <YAxis form={form} fields={fields} />
- {yColumnExists && (
- <NumberField
- form={form}
- name="yAxis.bin.maxbins"
- formFieldLabel="Number of boxes (max)"
- className="justify-between"
- />
- )}
- <ColorByAxis form={form} fields={fields} />
- </>
- );
-};
-
-const PieChartForm: React.FC<{
- form: UseFormReturn<z.infer<typeof ChartSchema>>;
- fields: Field[];
- saveForm: () => void;
- chartType: ChartType;
-}> = ({ form, fields, saveForm, chartType }) => {
- const formValues = useWatch({ control: form.control });
- const colorByColumn = formValues.general?.colorByColumn;
-
- const inferredColorByDataType = colorByColumn?.type
- ? TypeConverters.toSelectableDataType(colorByColumn.type)
- : "string";
-
- return (
- <>
- <Title text="Color by" />
- <ColumnSelector
- form={form}
- name="general.colorByColumn.field"
- columns={fields}
- includeCountField={false}
- />
- {FieldValidators.exists(colorByColumn?.field) && (
- <DataTypeSelect
- form={form}
- name="general.colorByColumn.selectedDataType"
- formFieldLabel="Data Type"
- defaultValue={inferredColorByDataType}
- />
- )}
-
- <Title text="Size by" />
- <div className="flex flex-row justify-between">
- <ColumnSelector
- form={form}
- name="general.yColumn.field"
- columns={fields}
- />
- <AggregationSelect form={form} name="general.yColumn.aggregate" />
- </div>
-
- <hr />
- <Title text="General" />
- <TooltipSelect
- form={form}
- name="general.tooltips"
- fields={fields}
- saveFunction={saveForm}
- formFieldLabel="Tooltips"
- />
- <NumberField
- form={form}
- name="style.innerRadius"
- formFieldLabel="Donut size"
- className="w-32"
- />
- </>
- );
-};
-
-const StyleForm: React.FC<{
- form: UseFormReturn<z.infer<typeof ChartSchema>>;
- fields: Field[];
- saveForm: () => void;
-}> = ({ form }) => {
- const renderBinFields = (axis: "x" | "y") => {
- return (
- <div className="flex flex-row gap-2 w-full">
- <BooleanField
- form={form}
- name={`${axis}Axis.bin.binned`}
- formFieldLabel="Binned"
- />
- <NumberField
- form={form}
- name={`${axis}Axis.bin.step`}
- formFieldLabel="Bin step"
- step={0.05}
- className="w-32"
- />
- </div>
- );
- };
-
- return (
- <Accordion type="multiple">
- <AccordionItem value="general" className="border-none">
- <AccordionTrigger className="pt-0 pb-2">
- <Title text="General" />
- </AccordionTrigger>
- <AccordionContent wrapperClassName="pb-2">
- <InputField
- form={form}
- formFieldLabel="Plot title"
- name="general.title"
- />
- </AccordionContent>
- </AccordionItem>
-
- <AccordionItem value="xAxis" className="border-none">
- <AccordionTrigger className="py-2">
- <Title text="X-Axis" />
- </AccordionTrigger>
- <AccordionContent wrapperClassName="pb-2 flex flex-col gap-2">
- <InputField form={form} formFieldLabel="Label" name="xAxis.label" />
- <SliderField
- form={form}
- name="xAxis.width"
- formFieldLabel="Width"
- value={400}
- start={200}
- stop={800}
- />
- {renderBinFields("x")}
- </AccordionContent>
- </AccordionItem>
-
- <AccordionItem value="yAxis" className="border-none">
- <AccordionTrigger className="py-2">
- <Title text="Y-Axis" />
- </AccordionTrigger>
- <AccordionContent wrapperClassName="pb-2 flex flex-col gap-2">
- <InputField form={form} formFieldLabel="Label" name="yAxis.label" />
- <SliderField
- form={form}
- name="yAxis.height"
- formFieldLabel="Height"
- value={300}
- start={150}
- stop={600}
- />
- {renderBinFields("y")}
- </AccordionContent>
- </AccordionItem>
-
- <AccordionItem value="color" className="border-none">
- <AccordionTrigger className="py-2">
- <Title text="Color" />
- </AccordionTrigger>
- <AccordionContent wrapperClassName="pb-2 flex flex-col gap-2">
- <SelectField
- form={form}
- name="color.scheme"
- formFieldLabel="Color scheme"
- defaultValue={DEFAULT_COLOR_SCHEME}
- options={COLOR_SCHEMES.map((scheme) => ({
- display: capitalize(scheme),
- value: scheme,
- }))}
- />
- <ColorArrayField
- form={form}
- name="color.range"
- formFieldLabel="Color range"
- />
- <p className="text-xs">
- <InfoIcon className="w-2.5 h-2.5 inline mb-1 mr-1" />
- If you are using color range, color scheme will be ignored.
- </p>
- </AccordionContent>
- </AccordionItem>
- </Accordion>
- );
-};
diff --git a/frontend/src/components/data-table/charts/README.md b/frontend/src/components/data-table/charts/README.md
new file mode 100644
index 0000000000..7c50d44836
--- /dev/null
+++ b/frontend/src/components/data-table/charts/README.md
@@ -0,0 +1,65 @@
+# Charts
+
+In order to maintain a consistent look and feel across all charts, we have a few components that are used to build the charts.
+
+## Components
+
+#### layouts
+Thin wrappers around @ui components that provide consistent styling and behavior.
+
+#### form-fields
+Form fields that are used for chart forms. Wraps react-hook-form components
+
+#### chart-items
+Components that are used to build the charts. Groups together common form fields and layouts.
+
+## Context
+
+To keep each component light and avoid prop drilling, we can either use react-hook-form's `useFormContext` or `useContext` to access shared state (`context.ts`).
+
+
+Layouts:
+ - TabContainer
+ - AccordionConfigs
+
+
+Chart Components:
+ - ChartTypeSelect
+ - XAxis
+ - YAxis
+ - ColorByAxis
+ - Facet
+
+Forms:
+ - CommonChartForm
+ - PieForm
+ - BarForm
+ - LineForm
+ - ScatterForm
+ - AreaForm
+ - HeatmapForm
+ - Style Form
+
+Field Components:
+ - ColumnSelector
+ - DataTypeSelect
+ - AggregationSelect
+ - TooltipSelect
+ - BooleanField
+ - NumberField
+ - SliderField
+ - ColorArrayField
+ - TimeUnitSelect
+ - SelectField
+
+<TabContainer>
+ <TabsContent value="data">
+ <FormSection>
+ <FieldSection>
+ </FieldSection>
+ </FormSection>
+ </TabsContent>
+ <TabsContent value="style">
+ <StyleForm />
+ </TabsContent>
+</TabContainer>
\ No newline at end of file
diff --git a/frontend/src/components/data-table/chart-transforms/__tests__/__snapshots__/spec-snapshot.test.ts.snap b/frontend/src/components/data-table/charts/__tests__/__snapshots__/spec-snapshot.test.ts.snap
similarity index 82%
rename from frontend/src/components/data-table/chart-transforms/__tests__/__snapshots__/spec-snapshot.test.ts.snap
rename to frontend/src/components/data-table/charts/__tests__/__snapshots__/spec-snapshot.test.ts.snap
index e2c2f2e2de..11c358b43d 100644
--- a/frontend/src/components/data-table/chart-transforms/__tests__/__snapshots__/spec-snapshot.test.ts.snap
+++ b/frontend/src/components/data-table/charts/__tests__/__snapshots__/spec-snapshot.test.ts.snap
@@ -41,12 +41,10 @@ exports[`createVegaSpec > Bar Chart > should create a horizontal bar chart 1`] =
"encoding": {
"x": {
"field": "value",
- "title": "value",
"type": "nominal",
},
"y": {
"field": "category",
- "title": "category",
"type": "nominal",
},
},
@@ -54,6 +52,12 @@ exports[`createVegaSpec > Bar Chart > should create a horizontal bar chart 1`] =
"mark": {
"type": "bar",
},
+ "resolve": {
+ "axis": {
+ "x": "independent",
+ "y": "independent",
+ },
+ },
"title": "Test Chart",
"width": 400,
}
@@ -105,13 +109,11 @@ exports[`createVegaSpec > Bar Chart > should create a stacked bar chart with gro
},
"x": {
"field": "category",
- "title": "category",
"type": "nominal",
},
"y": {
"field": "value",
"stack": true,
- "title": "value",
"type": "nominal",
},
},
@@ -119,70 +121,11 @@ exports[`createVegaSpec > Bar Chart > should create a stacked bar chart with gro
"mark": {
"type": "bar",
},
- "title": "Test Chart",
- "width": 400,
-}
-`;
-
-exports[`createVegaSpec > Edge cases > should handle NONE_GROUP_BY for groupByColumn 1`] = `
-{
- "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
- "background": "white",
- "data": {
- "values": [
- {
- "category": "A",
- "group": "Group 1",
- "value": 10,
- },
- {
- "category": "B",
- "group": "Group 1",
- "value": 20,
- },
- {
- "category": "C",
- "group": "Group 1",
- "value": 15,
- },
- {
- "category": "A",
- "group": "Group 2",
- "value": 5,
- },
- {
- "category": "B",
- "group": "Group 2",
- "value": 10,
- },
- {
- "category": "C",
- "group": "Group 2",
- "value": 25,
- },
- ],
- },
- "encoding": {
- "color": {
- "field": "None",
- "scale": {},
- "type": "nominal",
- },
- "x": {
- "field": "category",
- "title": "category",
- "type": "nominal",
+ "resolve": {
+ "axis": {
+ "x": "independent",
+ "y": "independent",
},
- "y": {
- "field": "value",
- "stack": true,
- "title": "value",
- "type": "nominal",
- },
- },
- "height": 300,
- "mark": {
- "type": "bar",
},
"title": "Test Chart",
"width": 400,
@@ -234,12 +177,10 @@ exports[`createVegaSpec > Line Chart > should create a basic line chart spec 1`]
"encoding": {
"x": {
"field": "category",
- "title": "category",
"type": "nominal",
},
"y": {
"field": "value",
- "title": "value",
"type": "nominal",
},
},
@@ -247,6 +188,12 @@ exports[`createVegaSpec > Line Chart > should create a basic line chart spec 1`]
"mark": {
"type": "line",
},
+ "resolve": {
+ "axis": {
+ "x": "independent",
+ "y": "independent",
+ },
+ },
"title": "Test Chart",
"width": 400,
}
@@ -300,12 +247,10 @@ exports[`createVegaSpec > Scatter Chart > should create a scatter chart with gro
},
"x": {
"field": "category",
- "title": "category",
"type": "nominal",
},
"y": {
"field": "value",
- "title": "value",
"type": "nominal",
},
},
@@ -313,6 +258,12 @@ exports[`createVegaSpec > Scatter Chart > should create a scatter chart with gro
"mark": {
"type": "point",
},
+ "resolve": {
+ "axis": {
+ "x": "independent",
+ "y": "independent",
+ },
+ },
"title": "Test Chart",
"width": 400,
}
@@ -359,12 +310,10 @@ exports[`createVegaSpec > Theme variations > should create a chart with dark the
"encoding": {
"x": {
"field": "category",
- "title": "category",
"type": "nominal",
},
"y": {
"field": "value",
- "title": "value",
"type": "nominal",
},
},
@@ -372,6 +321,12 @@ exports[`createVegaSpec > Theme variations > should create a chart with dark the
"mark": {
"type": "bar",
},
+ "resolve": {
+ "axis": {
+ "x": "independent",
+ "y": "independent",
+ },
+ },
"title": "Test Chart",
"width": 400,
}
@@ -417,14 +372,11 @@ exports[`createVegaSpec > should create a bar chart with binning 1`] = `
},
"encoding": {
"x": {
- "bin": true,
"field": "category",
- "title": "category",
"type": "nominal",
},
"y": {
"field": "value",
- "title": "value",
"type": "nominal",
},
},
@@ -432,6 +384,12 @@ exports[`createVegaSpec > should create a bar chart with binning 1`] = `
"mark": {
"type": "bar",
},
+ "resolve": {
+ "axis": {
+ "x": "independent",
+ "y": "independent",
+ },
+ },
"title": "Test Chart",
"width": 400,
}
diff --git a/frontend/src/components/data-table/chart-transforms/__tests__/spec-snapshot.test.ts b/frontend/src/components/data-table/charts/__tests__/spec-snapshot.test.ts
similarity index 87%
rename from frontend/src/components/data-table/chart-transforms/__tests__/spec-snapshot.test.ts
rename to frontend/src/components/data-table/charts/__tests__/spec-snapshot.test.ts
index 1fe5054bcd..7c3223ccc9 100644
--- a/frontend/src/components/data-table/chart-transforms/__tests__/spec-snapshot.test.ts
+++ b/frontend/src/components/data-table/charts/__tests__/spec-snapshot.test.ts
@@ -1,10 +1,9 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { describe, it, expect } from "vitest";
-import { createVegaSpec } from "../chart-spec";
-import { DEFAULT_BIN_VALUE, NONE_GROUP_BY } from "../chart-schemas";
+import { createVegaSpec } from "../chart-spec/spec";
import type { z } from "zod";
-import type { ChartSchema, ChartSchemaType } from "../chart-schemas";
+import type { ChartSchema, ChartSchemaType } from "../schemas";
import { NONE_AGGREGATION, ChartType } from "../types";
describe("createVegaSpec", () => {
@@ -89,7 +88,7 @@ describe("createVegaSpec", () => {
it("should create a bar chart with binning", () => {
const formValues: ChartSchemaType = {
...createBasicFormValues(),
- xAxis: { bin: { binned: true, step: DEFAULT_BIN_VALUE } },
+ xAxis: { bin: { binned: true, step: 10 } },
};
const spec = createVegaSpec(
@@ -126,7 +125,10 @@ describe("createVegaSpec", () => {
...createBasicFormValues(),
general: {
...createBasicFormValues().general,
- tooltips: [
+ },
+ tooltips: {
+ auto: true,
+ fields: [
{ field: "category", type: "string" as const },
{ field: "value", type: "number" as const },
],
@@ -237,31 +239,6 @@ describe("createVegaSpec", () => {
expect(removeUndefined(spec)).toMatchSnapshot();
});
-
- it("should handle NONE_GROUP_BY for groupByColumn", () => {
- const formValues: ChartSchemaType = {
- ...createBasicFormValues(),
- general: {
- ...createBasicFormValues().general,
- colorByColumn: {
- field: NONE_GROUP_BY,
- type: "string" as const,
- },
- stacking: true,
- },
- };
-
- const spec = createVegaSpec(
- ChartType.BAR,
- sampleData,
- formValues,
- "light",
- width,
- height,
- );
-
- expect(removeUndefined(spec)).toMatchSnapshot();
- });
});
});
diff --git a/frontend/src/components/data-table/chart-transforms/__tests__/spec.test.ts b/frontend/src/components/data-table/charts/__tests__/spec.test.ts
similarity index 67%
rename from frontend/src/components/data-table/chart-transforms/__tests__/spec.test.ts
rename to frontend/src/components/data-table/charts/__tests__/spec.test.ts
index 97a3cbb8ed..237991115d 100644
--- a/frontend/src/components/data-table/chart-transforms/__tests__/spec.test.ts
+++ b/frontend/src/components/data-table/charts/__tests__/spec.test.ts
@@ -1,8 +1,8 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { describe, expect, it } from "vitest";
-import { getAxisEncoding } from "../chart-spec";
-import { ChartType } from "../types";
+import { getAxisEncoding } from "../chart-spec/spec";
+import { AGGREGATION_FNS, ChartType, STRING_AGGREGATION_FNS } from "../types";
import { COUNT_FIELD } from "../constants";
import { NONE_AGGREGATION } from "../types";
@@ -24,7 +24,7 @@ describe("getAxisEncoding", () => {
expect(result).toEqual({
aggregate: "count",
type: "quantitative",
- bin: { binned: true, step: 10 },
+ bin: { bin: true, step: 10 },
title: undefined,
stack: true,
});
@@ -136,4 +136,50 @@ describe("getAxisEncoding", () => {
expect((result as { title?: string }).title).toBeUndefined();
});
+
+ it("should invalid aggregation for string data types", () => {
+ for (const agg of AGGREGATION_FNS) {
+ const result = getAxisEncoding(
+ {
+ field: "value",
+ selectedDataType: "string",
+ aggregate: agg,
+ timeUnit: undefined,
+ },
+ undefined,
+ "Value",
+ false,
+ ChartType.BAR,
+ );
+
+ const expectedAggregate = (result as { aggregate?: string }).aggregate;
+
+ // For aggregations that are not valid for string data types, we should return undefined
+ if (agg === NONE_AGGREGATION || !STRING_AGGREGATION_FNS.includes(agg)) {
+ expect(expectedAggregate).toBeUndefined();
+ } else if (STRING_AGGREGATION_FNS.includes(agg)) {
+ expect(expectedAggregate).toEqual(agg);
+ }
+ }
+ });
+
+ it("should return undefined for temporal data types", () => {
+ for (const agg of AGGREGATION_FNS) {
+ const result = getAxisEncoding(
+ {
+ field: "date",
+ selectedDataType: "temporal",
+ aggregate: agg,
+ timeUnit: undefined,
+ },
+ undefined,
+ "Date",
+ false,
+ ChartType.BAR,
+ );
+
+ const expectedAggregate = (result as { aggregate?: string }).aggregate;
+ expect(expectedAggregate).toBeUndefined();
+ }
+ });
});
diff --git a/frontend/src/components/data-table/chart-transforms/__tests__/storage.test.ts b/frontend/src/components/data-table/charts/__tests__/storage.test.ts
similarity index 98%
rename from frontend/src/components/data-table/chart-transforms/__tests__/storage.test.ts
rename to frontend/src/components/data-table/charts/__tests__/storage.test.ts
index 231e28aeef..7750920849 100644
--- a/frontend/src/components/data-table/chart-transforms/__tests__/storage.test.ts
+++ b/frontend/src/components/data-table/charts/__tests__/storage.test.ts
@@ -3,7 +3,7 @@
import { describe, it, expect, beforeEach, vi } from "vitest";
import { getDefaultStore } from "jotai";
import { tabsStorageAtom, KEY } from "../storage";
-import { ChartSchema } from "../chart-schemas";
+import { ChartSchema } from "../schemas";
import type { CellId } from "@/core/cells/ids";
import type { TabName } from "../storage";
import { ChartType } from "../types";
diff --git a/frontend/src/components/data-table/charts/chart-spec/encodings.ts b/frontend/src/components/data-table/charts/chart-spec/encodings.ts
new file mode 100644
index 0000000000..c53a3163b5
--- /dev/null
+++ b/frontend/src/components/data-table/charts/chart-spec/encodings.ts
@@ -0,0 +1,102 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import type { z } from "zod";
+import type { BinSchema, ChartSchema } from "../schemas";
+
+import { ChartType, NONE_AGGREGATION, type SelectableDataType } from "../types";
+
+import { DEFAULT_BIN_SIZE } from "../constants";
+import { isFieldSet } from "./spec";
+import { COUNT_FIELD, DEFAULT_COLOR_SCHEME } from "../constants";
+import type { ColorDef, OffsetDef } from "vega-lite/build/src/channeldef";
+import { convertDataTypeToVega } from "./types";
+import type { ColorScheme } from "vega";
+
+export function getBinEncoding(
+ selectedDataType: SelectableDataType,
+ binValues?: z.infer<typeof BinSchema>,
+ chartType?: ChartType,
+) {
+ if (chartType === ChartType.HEATMAP) {
+ return { maxbins: binValues?.maxbins };
+ }
+
+ if (!binValues?.binned) {
+ return undefined;
+ }
+
+ // Don't bin non-numeric data
+ if (selectedDataType !== "number") {
+ return undefined;
+ }
+
+ const binstep =
+ binValues.step === DEFAULT_BIN_SIZE ? undefined : binValues.step;
+ const binmaxbins =
+ binValues.maxbins === DEFAULT_BIN_SIZE ? undefined : binValues.maxbins;
+
+ return { bin: true, step: binstep, maxbins: binmaxbins };
+}
+
+export function getColorInScale(formValues: z.infer<typeof ChartSchema>) {
+ const colorRange = formValues.color?.range;
+ if (colorRange?.length) {
+ return { range: colorRange };
+ }
+
+ const scheme = formValues.color?.scheme;
+ return scheme === DEFAULT_COLOR_SCHEME
+ ? undefined
+ : { scheme: scheme as ColorScheme };
+}
+
+export function getColorEncoding(
+ chartType: ChartType,
+ formValues: z.infer<typeof ChartSchema>,
+): { color?: ColorDef<string> } | undefined {
+ if (
+ chartType === ChartType.PIE ||
+ !isFieldSet(formValues.general.colorByColumn?.field)
+ ) {
+ return undefined;
+ }
+
+ const colorByColumn = formValues.general.colorByColumn;
+ if (colorByColumn.field === COUNT_FIELD) {
+ return {
+ color: {
+ aggregate: "count",
+ type: "quantitative",
+ },
+ };
+ }
+
+ const colorBin = formValues.color?.bin;
+ const selectedDataType = colorByColumn.selectedDataType || "string";
+ const aggregate = formValues.general.colorByColumn.aggregate;
+
+ return {
+ color: {
+ field: colorByColumn.field,
+ type: convertDataTypeToVega(selectedDataType),
+ scale: getColorInScale(formValues),
+ aggregate: aggregate === NONE_AGGREGATION ? undefined : aggregate,
+ bin: getBinEncoding(selectedDataType, colorBin, chartType),
+ },
+ };
+}
+
+export function getOffsetEncoding(
+ chartType: ChartType,
+ formValues: z.infer<typeof ChartSchema>,
+): OffsetDef<string> | undefined {
+ // Offset only applies to bar charts, to unstack them
+ if (
+ formValues.general.stacking ||
+ !isFieldSet(formValues.general.colorByColumn?.field) ||
+ chartType !== ChartType.BAR
+ ) {
+ return undefined;
+ }
+ return { field: formValues.general.colorByColumn?.field };
+}
diff --git a/frontend/src/components/data-table/charts/chart-spec/spec.ts b/frontend/src/components/data-table/charts/chart-spec/spec.ts
new file mode 100644
index 0000000000..092e4f40c3
--- /dev/null
+++ b/frontend/src/components/data-table/charts/chart-spec/spec.ts
@@ -0,0 +1,274 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import type { TopLevelSpec } from "vega-lite";
+import type { ResolvedTheme } from "@/theme/useTheme";
+import type {
+ BinSchema,
+ ChartSchema,
+ AxisSchema,
+ RowFacet,
+ ColumnFacet,
+} from "../schemas";
+import {
+ type AggregationFn,
+ ChartType,
+ NONE_AGGREGATION,
+ type SelectableDataType,
+ STRING_AGGREGATION_FNS,
+} from "../types";
+import type { z } from "zod";
+import type {
+ ColorDef,
+ Field,
+ PolarDef,
+ PositionDef,
+} from "vega-lite/build/src/channeldef";
+import type { ExprRef, SignalRef } from "vega";
+import type { TypedString } from "@/utils/typed";
+import { COUNT_FIELD, EMPTY_VALUE } from "../constants";
+import type { FacetFieldDef } from "vega-lite/build/src/spec/facet";
+import type { Aggregate } from "vega-lite/build/src/aggregate";
+import {
+ getBinEncoding,
+ getColorEncoding,
+ getColorInScale,
+ getOffsetEncoding,
+} from "./encodings";
+import { convertChartTypeToMark, convertDataTypeToVega } from "./types";
+import { getTooltips } from "./tooltips";
+
+/**
+ * Convert marimo chart configuration to Vega-Lite specification.
+ */
+
+export type ErrorMessage = TypedString<"ErrorMessage">;
+
+export function createVegaSpec(
+ chartType: ChartType,
+ data: object[],
+ formValues: z.infer<typeof ChartSchema>,
+ theme: ResolvedTheme,
+ width: number | "container",
+ height: number,
+ // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
+): TopLevelSpec | ErrorMessage {
+ const {
+ xColumn,
+ yColumn,
+ colorByColumn,
+ horizontal,
+ stacking,
+ title,
+ facet,
+ } = formValues.general;
+
+ if (chartType === ChartType.PIE) {
+ return getPieChartSpec(data, formValues, theme, width, height);
+ }
+
+ // Validate required fields
+ if (!isFieldSet(xColumn?.field)) {
+ return "X-axis column is required" as ErrorMessage;
+ }
+ if (!isFieldSet(yColumn?.field)) {
+ return "Y-axis column is required" as ErrorMessage;
+ }
+
+ // Determine encoding keys based on chart type
+ const xEncodingKey = "x";
+ const yEncodingKey = "y";
+
+ // Create encodings
+ const xEncoding = getAxisEncoding(
+ xColumn,
+ formValues.xAxis?.bin,
+ getFieldLabel(formValues.xAxis?.label),
+ colorByColumn?.field && horizontal ? stacking : undefined,
+ chartType,
+ );
+
+ const yEncoding = getAxisEncoding(
+ yColumn,
+ formValues.yAxis?.bin,
+ getFieldLabel(formValues.yAxis?.label),
+ colorByColumn?.field && !horizontal ? stacking : undefined,
+ chartType,
+ );
+
+ const rowFacet = facet?.row.field ? getFacetEncoding(facet.row) : undefined;
+ const columnFacet = facet?.column.field
+ ? getFacetEncoding(facet.column)
+ : undefined;
+
+ // Create the final spec
+ return {
+ ...getBaseSpec(data, formValues, theme, width, height, title),
+ mark: { type: convertChartTypeToMark(chartType) },
+ encoding: {
+ [xEncodingKey]: horizontal ? yEncoding : xEncoding,
+ [yEncodingKey]: horizontal ? xEncoding : yEncoding,
+ xOffset: getOffsetEncoding(chartType, formValues),
+ ...getColorEncoding(chartType, formValues),
+ tooltip: getTooltips(formValues),
+ row: rowFacet,
+ column: columnFacet,
+ },
+ resolve: {
+ axis: {
+ x: facet?.column.linkXAxis ? "shared" : "independent",
+ y: facet?.row.linkYAxis ? "shared" : "independent",
+ },
+ },
+ };
+}
+
+export function getAxisEncoding(
+ column: NonNullable<z.infer<typeof AxisSchema>>,
+ binValues: z.infer<typeof BinSchema> | undefined,
+ label: string | undefined,
+ stack: boolean | undefined,
+ chartType: ChartType,
+): PositionDef<string> {
+ const selectedDataType = column.selectedDataType || "string";
+
+ if (column.field === COUNT_FIELD) {
+ return {
+ aggregate: "count",
+ type: "quantitative",
+ bin: getBinEncoding(selectedDataType, binValues, chartType),
+ title: label === COUNT_FIELD ? undefined : label,
+ stack: stack,
+ };
+ }
+
+ return {
+ field: column.field,
+ type: convertDataTypeToVega(column.selectedDataType || "unknown"),
+ bin: getBinEncoding(selectedDataType, binValues, chartType),
+ title: label,
+ stack: stack,
+ aggregate: getAggregate(column.aggregate, selectedDataType),
+ timeUnit: getTimeUnit(column),
+ };
+}
+
+export function getFacetEncoding(
+ facet: z.infer<typeof RowFacet> | z.infer<typeof ColumnFacet>,
+): FacetFieldDef<Field, ExprRef | SignalRef> {
+ let binValues = undefined;
+ // Only allow binning for number data types
+ if (facet.binned && facet.selectedDataType === "number") {
+ binValues = {
+ maxbins: facet.maxbins,
+ };
+ }
+
+ return {
+ field: facet.field,
+ sort: facet.sort,
+ timeUnit: getTimeUnit(facet),
+ type: convertDataTypeToVega(facet.selectedDataType || "unknown"),
+ bin: binValues,
+ };
+}
+
+function getPieChartSpec(
+ data: object[],
+ formValues: z.infer<typeof ChartSchema>,
+ theme: ResolvedTheme,
+ width: number | "container",
+ height: number,
+) {
+ const { yColumn, colorByColumn, title } = formValues.general;
+
+ if (!isFieldSet(colorByColumn?.field)) {
+ return "Color by column is required" as ErrorMessage;
+ }
+
+ if (!isFieldSet(yColumn?.field)) {
+ return "Size by column is required" as ErrorMessage;
+ }
+
+ const thetaEncoding: PolarDef<string> = getAxisEncoding(
+ yColumn,
+ formValues.xAxis?.bin,
+ getFieldLabel(formValues.xAxis?.label),
+ undefined,
+ ChartType.PIE,
+ );
+
+ const colorEncoding: ColorDef<string> = {
+ field: colorByColumn.field,
+ type: convertDataTypeToVega(colorByColumn.selectedDataType || "unknown"),
+ scale: getColorInScale(formValues),
+ title: getFieldLabel(formValues.yAxis?.label),
+ };
+
+ return {
+ ...getBaseSpec(data, formValues, theme, width, height, title),
+ mark: {
+ type: convertChartTypeToMark(ChartType.PIE),
+ innerRadius: formValues.style?.innerRadius,
+ },
+ encoding: {
+ theta: thetaEncoding,
+ color: colorEncoding,
+ tooltip: getTooltips(formValues),
+ },
+ };
+}
+
+function getBaseSpec(
+ data: object[],
+ formValues: z.infer<typeof ChartSchema>,
+ theme: ResolvedTheme,
+ width: number | "container",
+ height: number,
+ title?: string,
+) {
+ return {
+ $schema: "https://vega.github.io/schema/vega-lite/v5.json",
+ background: theme === "dark" ? "dark" : "white",
+ title: title,
+ data: { values: data },
+ height: formValues.yAxis?.height ?? height,
+ width: formValues.xAxis?.width ?? width,
+ };
+}
+
+export function isFieldSet(field: string | undefined): field is string {
+ return field !== undefined && field.trim() !== EMPTY_VALUE;
+}
+
+// Returns undefined if the label is empty, as Vega-Lite will use the proper name
+function getFieldLabel(label?: string): string | undefined {
+ const trimmedLabel = label?.trim();
+ return trimmedLabel === EMPTY_VALUE ? undefined : trimmedLabel;
+}
+
+function getAggregate(
+ aggregate: AggregationFn | undefined,
+ selectedDataType: SelectableDataType,
+): Aggregate | undefined {
+ // temporal data types don't support aggregation
+ if (selectedDataType === "temporal") {
+ return undefined;
+ }
+
+ if (aggregate === NONE_AGGREGATION || !aggregate) {
+ return undefined;
+ }
+
+ if (selectedDataType === "string") {
+ return STRING_AGGREGATION_FNS.includes(aggregate)
+ ? (aggregate as Aggregate)
+ : undefined;
+ }
+ return aggregate as Aggregate;
+}
+
+function getTimeUnit(column: z.infer<typeof AxisSchema>) {
+ if (column.selectedDataType === "temporal") {
+ return column.timeUnit;
+ }
+ return undefined;
+}
diff --git a/frontend/src/components/data-table/charts/chart-spec/tooltips.ts b/frontend/src/components/data-table/charts/chart-spec/tooltips.ts
new file mode 100644
index 0000000000..c748e4a716
--- /dev/null
+++ b/frontend/src/components/data-table/charts/chart-spec/tooltips.ts
@@ -0,0 +1,120 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import type { StringFieldDef } from "vega-lite/build/src/channeldef";
+import type { z } from "zod";
+import type { AxisSchema, ChartSchema } from "../schemas";
+import { NONE_AGGREGATION, type TimeUnitTooltip } from "../types";
+import type { DataType } from "@/core/kernel/messages";
+import type { Tooltip } from "../components/form-fields";
+import type { Aggregate } from "vega-lite/build/src/aggregate";
+import { isFieldSet } from "./spec";
+import { COUNT_FIELD } from "../constants";
+
+function getTooltipAggregate(
+ field: string,
+ yColumn?: z.infer<typeof AxisSchema>,
+): Aggregate | undefined {
+ if (field !== yColumn?.field) {
+ return undefined;
+ }
+
+ if (yColumn?.field === COUNT_FIELD) {
+ return "count";
+ }
+
+ return yColumn.aggregate === NONE_AGGREGATION ? undefined : yColumn.aggregate;
+}
+
+function getTooltipFormat(dataType: DataType): string | undefined {
+ switch (dataType) {
+ case "integer":
+ return ",.0f"; // Use comma grouping and no decimals
+ case "number":
+ return ",.2f"; // Use comma grouping and 2 decimal places
+ default:
+ return undefined;
+ }
+}
+
+function getTooltipTimeUnit(
+ tooltip: Tooltip,
+ formValues: z.infer<typeof ChartSchema>,
+): TimeUnitTooltip | undefined {
+ const xColumn = formValues.general.xColumn;
+ const yColumn = formValues.general.yColumn;
+ const colorByColumn = formValues.general.colorByColumn;
+ const columns = [xColumn, yColumn, colorByColumn];
+
+ // Check if tooltip field matches any temporal column with timeUnit
+ const matchingColumn = columns.find(
+ (col) =>
+ tooltip.field === col?.field &&
+ col?.selectedDataType === "temporal" &&
+ col?.timeUnit,
+ );
+
+ if (matchingColumn?.timeUnit) {
+ return matchingColumn.timeUnit;
+ }
+
+ switch (tooltip.type) {
+ case "datetime":
+ return "yearmonthdatehoursminutesseconds";
+ case "date":
+ return "yearmonthdate";
+ case "time":
+ return "hoursminutesseconds";
+ default:
+ return undefined;
+ }
+}
+
+export function getTooltips(formValues: z.infer<typeof ChartSchema>) {
+ if (!formValues.tooltips) {
+ return undefined;
+ }
+
+ let tooltips = formValues.tooltips.fields ?? [];
+
+ // If autoTooltips is enabled, we manually add the x, y, and color columns to the tooltips
+ if (formValues.tooltips.auto) {
+ const newTooltips: Tooltip[] = [];
+ const xColumn = formValues.general.xColumn;
+ const yColumn = formValues.general.yColumn;
+ const colorByColumn = formValues.general.colorByColumn;
+
+ if (isFieldSet(xColumn?.field)) {
+ newTooltips.push({
+ field: xColumn.field,
+ type: xColumn.type || "string",
+ });
+ }
+
+ if (isFieldSet(yColumn?.field)) {
+ newTooltips.push({
+ field: yColumn.field,
+ type: yColumn.type || "string",
+ });
+ }
+
+ if (isFieldSet(colorByColumn?.field)) {
+ newTooltips.push({
+ field: colorByColumn.field,
+ type: colorByColumn.type || "string",
+ });
+ }
+
+ tooltips = newTooltips;
+ }
+
+ return tooltips.map((tooltip): StringFieldDef<string> => {
+ const timeUnit = getTooltipTimeUnit(tooltip, formValues);
+ return {
+ field: tooltip.field,
+ aggregate: getTooltipAggregate(tooltip.field, formValues.general.yColumn),
+ format: getTooltipFormat(tooltip.type),
+ timeUnit: timeUnit,
+ title: timeUnit ? tooltip.field : undefined,
+ };
+ });
+}
diff --git a/frontend/src/components/data-table/charts/chart-spec/types.ts b/frontend/src/components/data-table/charts/chart-spec/types.ts
new file mode 100644
index 0000000000..ebd0546a1c
--- /dev/null
+++ b/frontend/src/components/data-table/charts/chart-spec/types.ts
@@ -0,0 +1,63 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import type { DataType } from "@/core/kernel/messages";
+import { ChartType, type SelectableDataType } from "../types";
+import type { StandardType } from "vega-lite/build/src/type";
+import { logNever } from "@/utils/assertNever";
+import type { Mark } from "@/plugins/impl/vega/types";
+
+export function convertDataTypeToVega(
+ dataType: DataType | SelectableDataType,
+): StandardType {
+ switch (dataType) {
+ case "number":
+ case "integer":
+ return "quantitative";
+ case "string":
+ case "boolean":
+ case "unknown":
+ return "nominal";
+ case "date":
+ case "datetime":
+ case "time":
+ case "temporal":
+ return "temporal";
+ default:
+ logNever(dataType);
+ return "nominal";
+ }
+}
+
+export function convertDataTypeToSelectable(
+ type: DataType,
+): SelectableDataType {
+ switch (type) {
+ case "number":
+ case "integer":
+ return "number";
+ case "string":
+ case "boolean":
+ case "unknown":
+ return "string";
+ case "date":
+ case "datetime":
+ case "time":
+ return "temporal";
+ default:
+ logNever(type);
+ return "string";
+ }
+}
+
+export function convertChartTypeToMark(chartType: ChartType): Mark {
+ switch (chartType) {
+ case ChartType.PIE:
+ return "arc";
+ case ChartType.SCATTER:
+ return "point";
+ case ChartType.HEATMAP:
+ return "rect";
+ default:
+ return chartType;
+ }
+}
diff --git a/frontend/src/components/data-table/charts/charts.tsx b/frontend/src/components/data-table/charts/charts.tsx
new file mode 100644
index 0000000000..00d7ec8efd
--- /dev/null
+++ b/frontend/src/components/data-table/charts/charts.tsx
@@ -0,0 +1,376 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import React, { useState, useMemo } from "react";
+import { Button } from "@/components/ui/button";
+import { TableIcon, XIcon, DatabaseIcon, PaintRollerIcon } from "lucide-react";
+import { Tabs, TabsTrigger, TabsList, TabsContent } from "@/components/ui/tabs";
+import type { z } from "zod";
+import { useForm, type UseFormReturn } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { ChartSchema } from "./schemas";
+import { Form } from "@/components/ui/form";
+import { getDefaults } from "@/components/forms/form-utils";
+import { useAtom } from "jotai";
+import type { CellId } from "@/core/cells/ids";
+import { getChartTabName, type TabName, tabsStorageAtom } from "./storage";
+import type { FieldTypesWithExternalType } from "../types";
+import { useAsyncData } from "@/hooks/useAsyncData";
+import { vegaLoadData } from "@/plugins/impl/vega/loader";
+import type { GetDataUrl } from "@/plugins/impl/DataTablePlugin";
+import type { Field } from "./components/form-fields";
+import { useDebouncedCallback } from "@/hooks/useDebounce";
+import { inferFieldTypes } from "../columns";
+import { LazyChart } from "./lazy-chart";
+import {
+ ChartLoadingState,
+ ChartErrorState,
+ ChartTypeSelect,
+} from "./components/chart-items";
+import { ChartType } from "./types";
+import { HeatmapForm } from "./forms/heatmap";
+import { PieForm } from "./forms/pie";
+import { CommonChartForm, StyleForm } from "./forms/common-chart";
+import { TabContainer } from "./components/layouts";
+import { ChartFormContext } from "./context";
+
+const NEW_CHART_TYPE = "bar" as ChartType;
+const DEFAULT_TAB_NAME = "table" as TabName;
+const CHART_HEIGHT = 300;
+
+export interface TablePanelProps {
+ cellId: CellId | null;
+ dataTable: JSX.Element;
+ displayHeader: boolean;
+ getDataUrl?: GetDataUrl;
+ fieldTypes?: FieldTypesWithExternalType | null;
+}
+
+export const TablePanel: React.FC<TablePanelProps> = ({
+ cellId,
+ dataTable,
+ getDataUrl,
+ fieldTypes,
+ displayHeader,
+}) => {
+ const [tabsMap, saveTabsMap] = useAtom(tabsStorageAtom);
+ const tabs = cellId ? (tabsMap.get(cellId) ?? []) : [];
+
+ const [tabNum, setTabNum] = useState(0);
+ const [selectedTab, setSelectedTab] = useState(DEFAULT_TAB_NAME);
+
+ if (!displayHeader || (tabs.length === 0 && !displayHeader)) {
+ return dataTable;
+ }
+
+ const handleAddTab = () => {
+ if (!cellId) {
+ return;
+ }
+ const tabName = getChartTabName(tabNum, NEW_CHART_TYPE);
+
+ const newTabs = new Map(tabsMap);
+ newTabs.set(cellId, [
+ ...tabs,
+ {
+ tabName,
+ chartType: NEW_CHART_TYPE,
+ config: getDefaults(ChartSchema),
+ },
+ ]);
+
+ saveTabsMap(newTabs);
+ setTabNum(tabNum + 1);
+ setSelectedTab(tabName);
+ };
+
+ const handleDeleteTab = (tabName: TabName) => {
+ if (!cellId) {
+ return;
+ }
+ const newTabs = new Map(tabsMap);
+ newTabs.set(
+ cellId,
+ tabs.filter((tab) => tab.tabName !== tabName),
+ );
+ saveTabsMap(newTabs);
+ setSelectedTab(DEFAULT_TAB_NAME);
+ setTabNum(tabNum - 1);
+ };
+
+ const saveTabChart = (
+ tabName: TabName,
+ chartType: ChartType,
+ chartConfig: z.infer<typeof ChartSchema>,
+ ) => {
+ if (!cellId) {
+ return;
+ }
+
+ const updatedTabs = new Map(tabsMap);
+ updatedTabs.set(
+ cellId,
+ tabs.map((tab) =>
+ tab.tabName === tabName
+ ? { ...tab, chartType, config: chartConfig }
+ : tab,
+ ),
+ );
+ saveTabsMap(updatedTabs);
+ };
+
+ const saveTabChartType = (tabName: TabName, chartType: ChartType) => {
+ if (!cellId) {
+ return;
+ }
+
+ const tabs = tabsMap.get(cellId) ?? [];
+ const tabIndex = tabs.findIndex((tab) => tab.tabName === tabName);
+ if (tabIndex === -1) {
+ return;
+ }
+
+ const newTabs = tabs.map((tab) =>
+ tab.tabName === tabName
+ ? {
+ ...tab,
+ chartType,
+ tabName: getChartTabName(tabIndex, chartType),
+ }
+ : tab,
+ );
+
+ const newTabsMap = new Map(tabsMap).set(cellId, newTabs);
+ saveTabsMap(newTabsMap);
+ setSelectedTab(newTabs[tabIndex].tabName);
+ };
+
+ return (
+ <Tabs value={selectedTab} className="-mt-1">
+ <TabsList>
+ <TabsTrigger
+ className="text-xs"
+ value={DEFAULT_TAB_NAME}
+ onClick={() => setSelectedTab(DEFAULT_TAB_NAME)}
+ >
+ <TableIcon className="w-3 h-3 mr-2" />
+ Table
+ </TabsTrigger>
+ {tabs.map((tab, idx) => (
+ <TabsTrigger
+ key={idx}
+ className="text-xs"
+ value={tab.tabName}
+ onClick={() => setSelectedTab(tab.tabName)}
+ >
+ {tab.tabName}
+ <XIcon
+ className="w-3 h-3 ml-1 mt-[0.5px] hover:text-red-500 hover:font-semibold"
+ onClick={(e) => {
+ e.stopPropagation();
+ handleDeleteTab(tab.tabName);
+ }}
+ />
+ </TabsTrigger>
+ ))}
+ <Button
+ variant="text"
+ size="icon"
+ onClick={handleAddTab}
+ title="Add chart"
+ >
+ +
+ </Button>
+ </TabsList>
+
+ <TabsContent className="mt-1 overflow-hidden" value={DEFAULT_TAB_NAME}>
+ {dataTable}
+ </TabsContent>
+ {tabs.map((tab, idx) => {
+ const saveChart = (formValues: z.infer<typeof ChartSchema>) => {
+ saveTabChart(tab.tabName, tab.chartType, formValues);
+ };
+ const saveChartType = (chartType: ChartType) => {
+ saveTabChartType(tab.tabName, chartType);
+ };
+ return (
+ <TabsContent key={idx} value={tab.tabName} className="h-[400px] mt-1">
+ <ChartPanel
+ chartConfig={tab.config}
+ chartType={tab.chartType}
+ saveChart={saveChart}
+ saveChartType={saveChartType}
+ getDataUrl={getDataUrl}
+ fieldTypes={fieldTypes ?? inferFieldTypes(dataTable.props.data)}
+ />
+ </TabsContent>
+ );
+ })}
+ </Tabs>
+ );
+};
+
+export const ChartPanel: React.FC<{
+ chartConfig: z.infer<typeof ChartSchema> | null;
+ chartType: ChartType;
+ saveChart: (formValues: z.infer<typeof ChartSchema>) => void;
+ saveChartType: (chartType: ChartType) => void;
+ getDataUrl?: GetDataUrl;
+ fieldTypes?: FieldTypesWithExternalType | null;
+}> = ({
+ chartConfig,
+ chartType,
+ saveChart,
+ saveChartType,
+ getDataUrl,
+ fieldTypes,
+}) => {
+ const form = useForm<z.infer<typeof ChartSchema>>({
+ defaultValues: chartConfig ?? getDefaults(ChartSchema),
+ resolver: zodResolver(ChartSchema),
+ });
+
+ const [selectedChartType, setSelectedChartType] =
+ useState<ChartType>(chartType);
+
+ const { data, loading, error } = useAsyncData(async () => {
+ if (!getDataUrl) {
+ return [];
+ }
+
+ const response = await getDataUrl({});
+ if (Array.isArray(response.data_url)) {
+ return response.data_url;
+ }
+
+ const chartData = await vegaLoadData(
+ response.data_url,
+ response.format === "arrow"
+ ? { type: "arrow" }
+ : response.format === "json"
+ ? { type: "json" }
+ : { type: "csv", parse: "auto" },
+ {
+ replacePeriod: true,
+ },
+ );
+ return chartData;
+ }, []);
+
+ const formValues = form.watch();
+
+ // This ensures the chart re-renders when the actual values change
+ const memoizedFormValues = useMemo(() => {
+ return structuredClone(formValues);
+ }, [formValues]);
+
+ // Prevent unnecessary re-renders of the chart
+ const memoizedChart = useMemo(() => {
+ if (loading) {
+ return <ChartLoadingState />;
+ }
+ if (error) {
+ return <ChartErrorState error={error} />;
+ }
+ return (
+ <LazyChart
+ chartType={selectedChartType}
+ formValues={memoizedFormValues}
+ data={data}
+ width="container"
+ height={CHART_HEIGHT}
+ />
+ );
+ }, [loading, error, memoizedFormValues, data, selectedChartType]);
+
+ return (
+ <div className="flex flex-row gap-2 h-full rounded-md border pr-2">
+ <div className="flex flex-col gap-2 w-[300px] overflow-auto px-2 py-3 scrollbar-thin">
+ <ChartTypeSelect
+ value={selectedChartType}
+ onValueChange={(value) => {
+ setSelectedChartType(value);
+ saveChartType(value);
+ }}
+ />
+
+ <ChartFormContainer
+ form={form}
+ saveChart={saveChart}
+ fieldTypes={fieldTypes}
+ chartType={selectedChartType}
+ />
+ </div>
+ <div className="flex-1 overflow-auto h-full w-full">{memoizedChart}</div>
+ </div>
+ );
+};
+
+const ChartFormContainer = ({
+ form,
+ saveChart,
+ fieldTypes,
+ chartType,
+}: {
+ form: UseFormReturn<z.infer<typeof ChartSchema>>;
+ chartType: ChartType;
+ saveChart: (formValues: z.infer<typeof ChartSchema>) => void;
+ fieldTypes?: FieldTypesWithExternalType | null;
+}) => {
+ let fields: Field[] = [];
+ if (fieldTypes) {
+ fields = fieldTypes.map((field) => {
+ return {
+ name: field[0],
+ type: field[1][0],
+ };
+ });
+ }
+
+ const debouncedSave = useDebouncedCallback(() => {
+ const values = form.getValues();
+ saveChart(values);
+ }, 300);
+
+ let ChartForm = CommonChartForm;
+
+ if (chartType === ChartType.PIE) {
+ ChartForm = PieForm;
+ } else if (chartType === ChartType.HEATMAP) {
+ ChartForm = HeatmapForm;
+ }
+
+ return (
+ <ChartFormContext.Provider value={{ fields, saveForm: debouncedSave }}>
+ <Form {...form}>
+ <form onSubmit={(e) => e.preventDefault()} onChange={debouncedSave}>
+ <Tabs defaultValue="data">
+ <TabsList className="w-full">
+ <TabsTrigger value="data" className="w-1/2 h-6">
+ <DatabaseIcon className="w-4 h-4 mr-2" />
+ Data
+ </TabsTrigger>
+ <TabsTrigger value="style" className="w-1/2 h-6">
+ <PaintRollerIcon className="w-4 h-4 mr-2" />
+ Style
+ </TabsTrigger>
+ </TabsList>
+
+ <TabsContent value="data">
+ <hr className="my-2" />
+ <TabContainer>
+ <ChartForm />
+ </TabContainer>
+ </TabsContent>
+
+ <TabsContent value="style">
+ <hr className="my-2" />
+ <TabContainer>
+ <StyleForm />
+ </TabContainer>
+ </TabsContent>
+ </Tabs>
+ </form>
+ </Form>
+ </ChartFormContext.Provider>
+ );
+};
diff --git a/frontend/src/components/data-table/charts/components/chart-items.tsx b/frontend/src/components/data-table/charts/components/chart-items.tsx
new file mode 100644
index 0000000000..a2c298f03a
--- /dev/null
+++ b/frontend/src/components/data-table/charts/components/chart-items.tsx
@@ -0,0 +1,324 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import { ChevronDown, Loader2 } from "lucide-react";
+import { capitalize } from "lodash-es";
+import * as SelectPrimitive from "@radix-ui/react-select";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectValue,
+} from "@/components/ui/select";
+import { CHART_TYPE_ICON, COUNT_FIELD, EMPTY_VALUE } from "../constants";
+import { ErrorBanner } from "@/plugins/impl/common/error-banner";
+import { buttonVariants } from "@/components/ui/button";
+import { useFormContext, useWatch } from "react-hook-form";
+import type { z } from "zod";
+import type { ChartSchema } from "../schemas";
+import { isFieldSet } from "../chart-spec/spec";
+import {
+ ColumnSelector,
+ AggregationSelect,
+ DataTypeSelect,
+ TimeUnitSelect,
+ BooleanField,
+ SortField,
+ NumberField,
+} from "./form-fields";
+import { CHART_TYPES, type ChartType } from "../types";
+import React from "react";
+import { FieldSection, Title } from "./layouts";
+import { useChartFormContext } from "../context";
+import { convertDataTypeToSelectable } from "../chart-spec/types";
+
+export const ChartLoadingState: React.FC = () => (
+ <div className="flex items-center gap-2 justify-center h-full w-full">
+ <Loader2 className="w-10 h-10 animate-spin" strokeWidth={1} />
+ <span>Loading chart...</span>
+ </div>
+);
+
+export const ChartErrorState: React.FC<{ error: Error }> = ({ error }) => (
+ <div className="flex items-center justify-center h-full w-full">
+ <ErrorBanner error={error} />
+ </div>
+);
+
+export const ChartTypeSelect: React.FC<{
+ value: ChartType;
+ onValueChange: (value: ChartType) => void;
+}> = ({ value, onValueChange }) => {
+ return (
+ <Select value={value} onValueChange={onValueChange}>
+ <div className="flex flex-row gap-2 items-center">
+ <SelectPrimitive.Trigger
+ className={buttonVariants({
+ variant: "outline",
+ className: "user-select-none w-full justify-between px-3",
+ })}
+ >
+ <SelectValue />
+ <SelectPrimitive.Icon asChild={true}>
+ <ChevronDown className="h-4 w-4 opacity-50" />
+ </SelectPrimitive.Icon>
+ </SelectPrimitive.Trigger>
+ <SelectContent>
+ {CHART_TYPES.map((chartType) => (
+ <ChartSelectItem key={chartType} chartType={chartType} />
+ ))}
+ </SelectContent>
+ </div>
+ </Select>
+ );
+};
+
+const ChartSelectItem: React.FC<{ chartType: ChartType }> = ({ chartType }) => {
+ const Icon = CHART_TYPE_ICON[chartType];
+ return (
+ <SelectItem value={chartType} className="gap-2">
+ <div className="flex items-center">
+ <Icon className="w-4 h-4 mr-2" />
+ {capitalize(chartType)}
+ </div>
+ </SelectItem>
+ );
+};
+
+export const XAxis: React.FC = () => {
+ const form = useFormContext<z.infer<typeof ChartSchema>>();
+ const formValues = useWatch({ control: form.control });
+ const context = useChartFormContext();
+
+ const xColumn = formValues.general?.xColumn;
+ const xColumnExists = isFieldSet(xColumn?.field);
+
+ const inferredXDataType = xColumn?.type
+ ? convertDataTypeToSelectable(xColumn.type)
+ : "string";
+
+ const selectedXDataType = xColumn?.selectedDataType || inferredXDataType;
+ const isXCountField = xColumn?.field === COUNT_FIELD;
+
+ const shouldShowXAggregation =
+ xColumnExists && selectedXDataType !== "temporal" && !isXCountField;
+
+ const shouldShowXTimeUnit =
+ xColumnExists && selectedXDataType === "temporal" && !isXCountField;
+
+ // const showBinFields = xColumn?.selectedDataType === "number";
+
+ return (
+ <FieldSection>
+ <Title text="X-Axis" />
+ <div className="flex flex-row justify-between">
+ <ColumnSelector
+ fieldName="general.xColumn.field"
+ columns={context.fields}
+ />
+ {shouldShowXAggregation && (
+ <AggregationSelect
+ fieldName="general.xColumn.aggregate"
+ selectedDataType={selectedXDataType}
+ />
+ )}
+ </div>
+ {xColumnExists && !isXCountField && (
+ <DataTypeSelect
+ label="Data Type"
+ fieldName="general.xColumn.selectedDataType"
+ defaultValue={inferredXDataType}
+ />
+ )}
+ {shouldShowXTimeUnit && (
+ <TimeUnitSelect
+ fieldName="general.xColumn.timeUnit"
+ label="Time Resolution"
+ />
+ )}
+ {xColumnExists && !isXCountField && (
+ <>
+ <SortField
+ fieldName="general.xColumn.sort"
+ label="Sort"
+ defaultValue={formValues.general?.xColumn?.sort}
+ />
+ {/* {showBinFields && <BinFields fieldName="xAxis" />} */}
+ </>
+ )}
+ </FieldSection>
+ );
+};
+
+export const YAxis: React.FC = () => {
+ const form = useFormContext<z.infer<typeof ChartSchema>>();
+ const formValues = useWatch({ control: form.control });
+ const context = useChartFormContext();
+
+ const yColumn = formValues.general?.yColumn;
+ const yColumnExists = isFieldSet(yColumn?.field);
+ const xColumn = formValues.general?.xColumn;
+ const xColumnExists = isFieldSet(xColumn?.field);
+
+ const inferredYDataType = yColumn?.type
+ ? convertDataTypeToSelectable(yColumn.type)
+ : "string";
+
+ const selectedYDataType = yColumn?.selectedDataType || inferredYDataType;
+ const isYCountField = yColumn?.field === COUNT_FIELD;
+
+ const shouldShowYAggregation =
+ yColumnExists && selectedYDataType !== "temporal" && !isYCountField;
+
+ const shouldShowYTimeUnit =
+ yColumnExists && selectedYDataType === "temporal" && !isYCountField;
+
+ // const showBinFields =
+ // yColumnExists && !isYCountField && yColumn.selectedDataType === "number";
+
+ return (
+ <FieldSection>
+ <Title text="Y-Axis" />
+ <div className="flex flex-row justify-between">
+ <ColumnSelector
+ fieldName="general.yColumn.field"
+ columns={context.fields}
+ />
+ {shouldShowYAggregation && (
+ <AggregationSelect
+ fieldName="general.yColumn.aggregate"
+ selectedDataType={selectedYDataType}
+ />
+ )}
+ </div>
+
+ {yColumnExists && !isYCountField && (
+ <DataTypeSelect
+ label="Data Type"
+ fieldName="general.yColumn.selectedDataType"
+ defaultValue={inferredYDataType}
+ />
+ )}
+ {shouldShowYTimeUnit && (
+ <TimeUnitSelect
+ fieldName="general.yColumn.timeUnit"
+ label="Time Resolution"
+ />
+ )}
+ {/* {showBinFields && <BinFields fieldName="yAxis" />} */}
+ {yColumnExists && xColumnExists && (
+ <BooleanField fieldName="general.horizontal" label="Invert axis" />
+ )}
+ </FieldSection>
+ );
+};
+
+export const ColorByAxis: React.FC = () => {
+ const { fields } = useChartFormContext();
+ const form = useFormContext<z.infer<typeof ChartSchema>>();
+ const formValues = useWatch({ control: form.control });
+
+ let selectedColorByDataType =
+ formValues.general?.colorByColumn?.selectedDataType;
+ if (selectedColorByDataType === EMPTY_VALUE || !selectedColorByDataType) {
+ selectedColorByDataType = "string";
+ }
+
+ // const showBinFields =
+ // formValues.general?.colorByColumn?.type &&
+ // ["number", "integer"].includes(formValues.general?.colorByColumn?.type) &&
+ // formValues.general?.colorByColumn?.field !== COUNT_FIELD;
+
+ return (
+ <FieldSection>
+ <Title text="Color by" />
+ <div className="flex flex-row justify-between">
+ <ColumnSelector
+ fieldName="general.colorByColumn.field"
+ columns={fields}
+ />
+ <AggregationSelect
+ fieldName="general.colorByColumn.aggregate"
+ selectedDataType={selectedColorByDataType}
+ />
+ </div>
+ {/* {showBinFields && <BinFields fieldName="color" />} */}
+ </FieldSection>
+ );
+};
+
+export const Facet: React.FC = () => {
+ const context = useChartFormContext();
+ const fields = context.fields;
+
+ const form = useFormContext<z.infer<typeof ChartSchema>>();
+ const formValues = useWatch({ control: form.control });
+
+ const renderField = (facet: "column" | "row") => {
+ const field = formValues.general?.facet?.[facet];
+ const fieldExists = isFieldSet(field?.field);
+
+ const inferredDataType = field?.type
+ ? convertDataTypeToSelectable(field.type)
+ : "string";
+ const selectedDataType = field?.selectedDataType || inferredDataType;
+
+ const shouldShowTimeUnit = fieldExists && selectedDataType === "temporal";
+ const canShowBin = fieldExists && selectedDataType === "number";
+
+ const linkFieldName =
+ facet === "row"
+ ? ("general.facet.row.linkYAxis" as const)
+ : ("general.facet.column.linkXAxis" as const);
+
+ return (
+ <div className="flex flex-col gap-1">
+ <div className="flex flex-row justify-between">
+ <p className="font-semibold">{capitalize(facet)}</p>
+ <ColumnSelector
+ fieldName={`general.facet.${facet}.field`}
+ columns={fields}
+ />
+ </div>
+ {fieldExists && (
+ <>
+ <DataTypeSelect
+ label="Data Type"
+ fieldName={`general.facet.${facet}.selectedDataType`}
+ defaultValue={inferredDataType}
+ />
+ {shouldShowTimeUnit && (
+ <TimeUnitSelect
+ fieldName={`general.facet.${facet}.timeUnit`}
+ label="Time Resolution"
+ />
+ )}
+ {canShowBin && (
+ <div className="flex flex-row justify-between">
+ <BooleanField
+ fieldName={`general.facet.${facet}.binned`}
+ label="Binned"
+ />
+ <NumberField
+ fieldName={`general.facet.${facet}.maxbins`}
+ label="Max Bins"
+ />
+ </div>
+ )}
+ <SortField fieldName={`general.facet.${facet}.sort`} label="Sort" />
+ <BooleanField
+ fieldName={linkFieldName}
+ label={`Link ${facet === "row" ? "Y" : "X"} Axes`}
+ />
+ </>
+ )}
+ </div>
+ );
+ };
+
+ return (
+ <FieldSection className="gap-3">
+ {renderField("row")}
+ {renderField("column")}
+ </FieldSection>
+ );
+};
diff --git a/frontend/src/components/data-table/chart-transforms/form-components.tsx b/frontend/src/components/data-table/charts/components/form-fields.tsx
similarity index 51%
rename from frontend/src/components/data-table/chart-transforms/form-components.tsx
rename to frontend/src/components/data-table/charts/components/form-fields.tsx
index 457cdc3bd7..8585d6d5e6 100644
--- a/frontend/src/components/data-table/chart-transforms/form-components.tsx
+++ b/frontend/src/components/data-table/charts/components/form-fields.tsx
@@ -2,13 +2,18 @@
import React from "react";
import { capitalize } from "lodash-es";
-import { XIcon, PlusIcon, SquareFunctionIcon } from "lucide-react";
-import type { UseFormReturn, Path, PathValue } from "react-hook-form";
+import {
+ XIcon,
+ PlusIcon,
+ SquareFunctionIcon,
+ ArrowUpWideNarrowIcon,
+ ArrowDownWideNarrowIcon,
+} from "lucide-react";
+import { type Path, useFormContext, useWatch } from "react-hook-form";
import type { z } from "zod";
import type { DataType } from "@/core/kernel/messages";
-import type { NumberFieldProps } from "@/components/ui/number-field";
-import type { ChartSchema } from "./chart-schemas";
+import type { ChartSchema } from "../schemas";
import {
FormField,
@@ -33,15 +38,18 @@ import { Button } from "@/components/ui/button";
import { cn } from "@/utils/cn";
import { Multiselect } from "@/plugins/impl/MultiselectPlugin";
-import { DEFAULT_BIN_VALUE } from "./chart-schemas";
import {
AGGREGATION_FNS,
+ type AggregationFn,
COMBINED_TIME_UNITS,
NONE_AGGREGATION,
SELECTABLE_DATA_TYPES,
+ type SelectableDataType,
SINGLE_TIME_UNITS,
+ SORT_TYPES,
+ STRING_AGGREGATION_FNS,
type TimeUnit,
-} from "./types";
+} from "../types";
import {
AGGREGATION_TYPE_DESCRIPTIONS,
AGGREGATION_TYPE_ICON,
@@ -49,12 +57,16 @@ import {
EMPTY_VALUE,
SCALE_TYPE_DESCRIPTIONS,
TIME_UNIT_DESCRIPTIONS,
-} from "./constants";
-import { TypeConverters } from "./chart-spec";
-import { IconWithText } from "./chart-components";
+ DEFAULT_BIN_SIZE,
+} from "../constants";
import { Slider } from "@/components/ui/slider";
+import { IconWithText } from "./layouts";
+import { useChartFormContext } from "../context";
+import type { NumberFieldProps } from "@/components/ui/number-field";
+import { convertDataTypeToSelectable } from "../chart-spec/types";
const CLEAR_VALUE = "__clear__";
+type FieldName = Path<z.infer<typeof ChartSchema>>;
export interface Field {
name: string;
@@ -63,49 +75,35 @@ export interface Field {
export interface Tooltip {
field: string;
- type: string;
-}
-
-interface BaseFormFieldProps<T extends object> {
- form: UseFormReturn<T>;
- name: Path<T>;
- formFieldLabel: string;
- className?: string;
+ type: DataType;
}
-export const ColumnSelector = <T extends object>({
- form,
- name,
+export const ColumnSelector = ({
+ fieldName,
columns,
onValueChange,
includeCountField = true,
}: {
- form: UseFormReturn<T>;
- name: Path<T>;
+ fieldName: FieldName;
columns: Array<{ name: string; type: DataType }>;
onValueChange?: (fieldName: string, type: DataType | undefined) => void;
includeCountField?: boolean;
}) => {
- type AnyPath = Path<T>;
- type AnyPathValue = PathValue<T, Path<T>>;
- const ANY_VALUE = EMPTY_VALUE as AnyPathValue;
- const pathType = name.replace(".field", ".type") as AnyPath;
- const pathSelectedDataType = name.replace(
- ".field",
- ".selectedDataType",
- ) as AnyPath;
+ const form = useFormContext();
+ const pathType = fieldName.replace(".field", ".type");
+ const pathSelectedDataType = fieldName.replace(".field", ".selectedDataType");
const clear = () => {
- form.setValue(name, ANY_VALUE);
- form.setValue(pathType, ANY_VALUE);
- form.setValue(pathSelectedDataType, ANY_VALUE);
+ form.setValue(fieldName, EMPTY_VALUE);
+ form.setValue(pathType, EMPTY_VALUE);
+ form.setValue(pathSelectedDataType, EMPTY_VALUE);
onValueChange?.(EMPTY_VALUE, undefined);
};
return (
<FormField
control={form.control}
- name={name}
+ name={fieldName}
render={({ field }) => (
<FormItem>
<FormControl>
@@ -120,25 +118,23 @@ export const ColumnSelector = <T extends object>({
// Handle count
if (value === COUNT_FIELD) {
- form.setValue(name, value as AnyPathValue);
- form.setValue(pathType, ANY_VALUE);
- form.setValue(pathSelectedDataType, ANY_VALUE);
- onValueChange?.(name, "number");
+ form.setValue(fieldName, value);
+ form.setValue(pathType, EMPTY_VALUE);
+ form.setValue(pathSelectedDataType, EMPTY_VALUE);
+ onValueChange?.(fieldName, "number");
return;
}
// Handle column selection
const column = columns.find((column) => column.name === value);
if (column) {
- form.setValue(name, value as AnyPathValue);
- form.setValue(pathType, column.type as AnyPathValue);
+ form.setValue(fieldName, value);
+ form.setValue(pathType, column.type);
form.setValue(
pathSelectedDataType,
- TypeConverters.toSelectableDataType(
- column.type,
- ) as AnyPathValue,
+ convertDataTypeToSelectable(column.type),
);
- onValueChange?.(name, column.type);
+ onValueChange?.(fieldName, column.type);
}
}}
value={field.value ?? EMPTY_VALUE}
@@ -192,145 +188,174 @@ export const ColumnSelector = <T extends object>({
);
};
-export const SelectField = <T extends object>({
- form,
- name,
- formFieldLabel,
+export const SelectField = ({
+ fieldName,
+ label,
options,
defaultValue,
-}: BaseFormFieldProps<T> & {
+}: {
+ fieldName: FieldName;
+ label: string;
options: Array<{ display: React.ReactNode; value: string }>;
defaultValue: string;
-}) => (
- <FormField
- control={form.control}
- name={name}
- render={({ field }) => (
- <FormItem className="flex flex-row items-center justify-between">
- <FormLabel>{formFieldLabel}</FormLabel>
- <FormControl>
- <Select
- {...field}
- onValueChange={field.onChange}
- value={field.value ?? defaultValue}
- >
- <SelectTrigger className="truncate">
- <SelectValue placeholder="Select an option" />
- </SelectTrigger>
- <SelectContent>
- <SelectGroup>
- {options
- .filter((option) => option.value !== EMPTY_VALUE)
- .map((option) => (
- <SelectItem key={option.value} value={option.value}>
- {option.display}
- </SelectItem>
- ))}
- </SelectGroup>
- </SelectContent>
- </Select>
- </FormControl>
- </FormItem>
- )}
- />
-);
-
-export const InputField = <T extends object>({
- form,
- name,
- formFieldLabel,
-}: BaseFormFieldProps<T>) => (
- <FormField
- control={form.control}
- name={name}
- render={({ field }) => (
- <FormItem className="flex flex-row gap-2 items-center">
- <FormLabel>{formFieldLabel}</FormLabel>
- <FormControl>
- <DebouncedInput
- {...field}
- value={field.value ?? EMPTY_VALUE}
- onValueChange={field.onChange}
- className="text-xs h-5"
- />
- </FormControl>
- </FormItem>
- )}
- />
-);
-
-export const NumberField = <T extends object>({
- form,
- name,
- formFieldLabel,
+}) => {
+ const form = useFormContext();
+
+ return (
+ <FormField
+ control={form.control}
+ name={fieldName}
+ render={({ field }) => (
+ <FormItem className="flex flex-row items-center justify-between">
+ <FormLabel>{label}</FormLabel>
+ <FormControl>
+ <Select
+ {...field}
+ onValueChange={field.onChange}
+ value={field.value ?? defaultValue}
+ >
+ <SelectTrigger className="truncate">
+ <SelectValue placeholder="Select an option" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectGroup>
+ {options
+ .filter((option) => option.value !== EMPTY_VALUE)
+ .map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.display}
+ </SelectItem>
+ ))}
+ </SelectGroup>
+ </SelectContent>
+ </Select>
+ </FormControl>
+ </FormItem>
+ )}
+ />
+ );
+};
+
+export const InputField = ({
+ fieldName,
+ label,
+}: {
+ fieldName: FieldName;
+ label: string;
+}) => {
+ const form = useFormContext();
+ return (
+ <FormField
+ control={form.control}
+ name={fieldName}
+ render={({ field }) => (
+ <FormItem className="flex flex-row gap-2 items-center">
+ <FormLabel>{label}</FormLabel>
+ <FormControl>
+ <DebouncedInput
+ {...field}
+ value={field.value ?? EMPTY_VALUE}
+ onValueChange={field.onChange}
+ className="text-xs h-5"
+ />
+ </FormControl>
+ </FormItem>
+ )}
+ />
+ );
+};
+
+export const NumberField = ({
+ fieldName,
+ label,
className,
+ inputClassName,
+ isDisabled,
...props
-}: BaseFormFieldProps<T> &
- Omit<NumberFieldProps, "value" | "onValueChange">) => (
- <FormField
- control={form.control}
- name={name}
- render={({ field }) => (
- <FormItem className={cn("flex flex-row items-center gap-2", className)}>
- <FormLabel className="whitespace-nowrap">{formFieldLabel}</FormLabel>
- <FormControl>
- <DebouncedNumberInput
- {...field}
- value={field.value ?? DEFAULT_BIN_VALUE}
- onValueChange={field.onChange}
- aria-label={formFieldLabel}
- {...props}
- className="w-16"
- />
- </FormControl>
- </FormItem>
- )}
- />
-);
-
-export const BooleanField = <T extends object>({
- form,
- name,
- formFieldLabel,
+}: NumberFieldProps & {
+ fieldName: FieldName;
+ label: string;
+ className?: string;
+ inputClassName?: string;
+ isDisabled?: boolean;
+}) => {
+ const form = useFormContext();
+ return (
+ <FormField
+ control={form.control}
+ name={fieldName}
+ render={({ field }) => (
+ <FormItem className={cn("flex flex-row items-center gap-2", className)}>
+ <FormLabel className="whitespace-nowrap">{label}</FormLabel>
+ <FormControl>
+ <DebouncedNumberInput
+ {...field}
+ value={field.value ?? DEFAULT_BIN_SIZE}
+ onValueChange={field.onChange}
+ aria-label={label}
+ className={cn("w-16", inputClassName)}
+ isDisabled={isDisabled}
+ minValue={0}
+ {...props}
+ />
+ </FormControl>
+ </FormItem>
+ )}
+ />
+ );
+};
+
+export const BooleanField = ({
+ fieldName,
+ label,
className,
-}: BaseFormFieldProps<T>) => (
- <FormField
- control={form.control}
- name={name}
- render={({ field }) => (
- <FormItem className={cn("flex flex-row items-center gap-2", className)}>
- <FormLabel>{formFieldLabel}</FormLabel>
- <FormControl>
- <Checkbox
- checked={field.value}
- onCheckedChange={field.onChange}
- className="w-4 h-4"
- />
- </FormControl>
- </FormItem>
- )}
- />
-);
+}: {
+ fieldName: FieldName;
+ label: string;
+ className?: string;
+}) => {
+ const form = useFormContext();
+ return (
+ <FormField
+ control={form.control}
+ name={fieldName}
+ render={({ field }) => (
+ <FormItem className={cn("flex flex-row items-center gap-2", className)}>
+ <FormLabel>{label}</FormLabel>
+ <FormControl>
+ <Checkbox
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ className="w-4 h-4"
+ />
+ </FormControl>
+ </FormItem>
+ )}
+ />
+ );
+};
-interface SliderFieldProps<T extends object> extends BaseFormFieldProps<T> {
+interface SliderFieldProps {
+ fieldName: FieldName;
+ label: string;
+ className?: string;
value: number;
start: number;
stop: number;
step?: number;
}
-export const SliderField = <T extends object>({
- form,
- name,
- formFieldLabel,
+export const SliderField = ({
+ fieldName,
+ label,
value,
start,
stop,
step,
className,
- ...props
-}: SliderFieldProps<T>) => {
+}: SliderFieldProps) => {
const [internalValue, setInternalValue] = React.useState(value);
+ const form = useFormContext();
// Update internal value on prop change
React.useEffect(() => {
@@ -340,17 +365,16 @@ export const SliderField = <T extends object>({
return (
<FormField
control={form.control}
- name={name}
+ name={fieldName}
render={({ field }) => (
<FormItem
className={cn("flex flex-row items-center gap-2 w-1/2", className)}
>
- <FormLabel>{formFieldLabel}</FormLabel>
+ <FormLabel>{label}</FormLabel>
<FormControl>
<Slider
{...field}
- {...props}
- id={name}
+ id={fieldName}
className="relative flex items-center select-none"
value={[internalValue]}
min={start}
@@ -364,7 +388,7 @@ export const SliderField = <T extends object>({
// Triggered on mouse up
onValueCommit={([nextValue]) => {
field.onChange(nextValue);
- form.setValue(name, nextValue as PathValue<T, Path<T>>);
+ form.setValue(fieldName, nextValue);
}}
valueMap={(value) => value}
/>
@@ -375,41 +399,45 @@ export const SliderField = <T extends object>({
);
};
-export const ColorArrayField = <T extends object>({
- form,
- name,
- formFieldLabel,
+export const ColorArrayField = ({
+ fieldName,
+ label,
className,
-}: BaseFormFieldProps<T>) => {
- const formValue = form.watch(name);
+}: {
+ fieldName: FieldName;
+ label: string;
+ className?: string;
+}) => {
+ const form = useFormContext();
+ const formValue = form.watch(fieldName);
const [colors, setColors] = React.useState<string[]>(formValue ?? []);
const addColor = () => {
const newColors = [...colors, "#000000"];
setColors(newColors);
- form.setValue(name, newColors as PathValue<T, Path<T>>);
+ form.setValue(fieldName, newColors);
};
const removeColor = (index: number) => {
const newColors = colors.filter((_, i) => i !== index);
setColors(newColors);
- form.setValue(name, newColors as PathValue<T, Path<T>>);
+ form.setValue(fieldName, newColors);
};
const updateColor = (index: number, value: string) => {
const newColors = [...colors];
newColors[index] = value;
setColors(newColors);
- form.setValue(name, newColors as PathValue<T, Path<T>>);
+ form.setValue(fieldName, newColors);
};
return (
<FormField
control={form.control}
- name={name}
+ name={fieldName}
render={() => (
<FormItem className={cn("flex flex-col gap-2", className)}>
- <FormLabel>{formFieldLabel}</FormLabel>
+ <FormLabel>{label}</FormLabel>
<div className="flex flex-col gap-2">
{colors.map((color, index) => (
<div key={index} className="flex items-center gap-2">
@@ -448,13 +476,16 @@ export const ColorArrayField = <T extends object>({
);
};
-export const TimeUnitSelect = <T extends object>({
- form,
- name,
- formFieldLabel,
-}: BaseFormFieldProps<T>) => {
+export const TimeUnitSelect = ({
+ fieldName,
+ label,
+}: {
+ fieldName: FieldName;
+ label: string;
+}) => {
+ const form = useFormContext();
const clear = () => {
- form.setValue(name, EMPTY_VALUE as PathValue<T, Path<T>>);
+ form.setValue(fieldName, EMPTY_VALUE);
};
const renderTimeUnit = (unit: TimeUnit) => {
@@ -477,10 +508,10 @@ export const TimeUnitSelect = <T extends object>({
return (
<FormField
control={form.control}
- name={name}
+ name={fieldName}
render={({ field }) => (
<FormItem className="flex flex-row items-center justify-between w-full">
- <FormLabel>{formFieldLabel}</FormLabel>
+ <FormLabel>{label}</FormLabel>
<FormControl>
<Select
{...field}
@@ -522,25 +553,27 @@ export const TimeUnitSelect = <T extends object>({
);
};
-export const DataTypeSelect = <T extends object>({
- form,
- name,
- formFieldLabel,
+export const DataTypeSelect = ({
+ fieldName,
+ label,
defaultValue,
onValueChange,
-}: BaseFormFieldProps<T> & {
+}: {
+ fieldName: FieldName;
+ label: string;
defaultValue: string;
onValueChange?: (value: string) => void;
}) => {
const [isOpen, setIsOpen] = React.useState(false);
+ const form = useFormContext();
return (
<FormField
control={form.control}
- name={name}
+ name={fieldName}
render={({ field }) => (
<FormItem className="flex flex-row items-center justify-between w-full">
- <FormLabel>{formFieldLabel}</FormLabel>
+ <FormLabel>{label}</FormLabel>
<FormControl>
<Select
{...field}
@@ -587,104 +620,182 @@ export const DataTypeSelect = <T extends object>({
};
export const AggregationSelect = <T extends object>({
- form,
- name,
-}: { form: UseFormReturn<T>; name: Path<T> }) => (
- <FormField
- control={form.control}
- name={name}
- render={({ field }) => (
- <FormItem>
- <FormControl>
- <Select
- {...field}
- value={field.value ?? NONE_AGGREGATION}
- onValueChange={field.onChange}
- >
- <SelectTrigger variant="ghost">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectGroup>
- <SelectLabel>Aggregation</SelectLabel>
- {AGGREGATION_FNS.map((agg) => {
- const Icon = AGGREGATION_TYPE_ICON[agg];
- return (
- <SelectItem
- key={agg}
- value={agg}
- className="flex flex-col items-start justify-center"
- subtitle={
- <span className="text-xs text-muted-foreground pr-10">
- {AGGREGATION_TYPE_DESCRIPTIONS[agg]}
- </span>
- }
- >
- <div className="flex items-center">
- <Icon className="w-3 h-3 mr-2" />
- {capitalize(agg)}
- </div>
- </SelectItem>
- );
- })}
- </SelectGroup>
- </SelectContent>
- </Select>
- </FormControl>
- </FormItem>
- )}
- />
-);
-
-export const TooltipSelect = <T extends z.infer<typeof ChartSchema>>({
- form,
- name,
- formFieldLabel,
- fields,
- saveFunction,
+ fieldName,
+ selectedDataType,
}: {
- form: UseFormReturn<T>;
- formFieldLabel?: string;
- name: Path<T>;
- fields: Field[];
- saveFunction: () => void;
-}) => (
- <FormField
- control={form.control}
- name={name}
- render={({ field }) => {
- const tooltips = field.value as Tooltip[] | undefined;
- return (
- <FormItem className="flex flex-row gap-2 items-center">
- {formFieldLabel && <FormLabel>{formFieldLabel}</FormLabel>}
+ fieldName: Path<T>;
+ selectedDataType: SelectableDataType;
+}) => {
+ const form = useFormContext<T>();
+ const availableAggregations =
+ selectedDataType === "string" ? STRING_AGGREGATION_FNS : AGGREGATION_FNS;
+
+ const renderSubtitle = (agg: AggregationFn) => {
+ return (
+ <span className="text-xs text-muted-foreground pr-10">
+ {AGGREGATION_TYPE_DESCRIPTIONS[agg]}
+ </span>
+ );
+ };
+
+ return (
+ <FormField
+ control={form.control}
+ name={fieldName}
+ render={({ field }) => (
+ <FormItem>
<FormControl>
- <Multiselect
- options={fields?.map((field) => field.name) ?? []}
- value={tooltips?.map((t) => t.field) ?? []}
- setValue={(values) => {
- const selectedValues =
- typeof values === "function" ? values([]) : values;
-
- const tooltipObjects = selectedValues.map((fieldName) => {
- const fieldType = fields?.find(
- (f) => f.name === fieldName,
- )?.type;
-
- return {
- field: fieldName,
- type: fieldType ?? "string",
- };
- });
-
- field.onChange(tooltipObjects);
- saveFunction();
- }}
- label={null}
- fullWidth={false}
- />
+ <Select
+ {...field}
+ value={field.value ?? NONE_AGGREGATION}
+ onValueChange={field.onChange}
+ >
+ <SelectTrigger variant="ghost">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectGroup>
+ <SelectLabel>Aggregation</SelectLabel>
+ {availableAggregations.map((agg) => {
+ const Icon = AGGREGATION_TYPE_ICON[agg];
+ return (
+ <SelectItem
+ key={agg}
+ value={agg}
+ className="flex flex-col items-start justify-center"
+ subtitle={renderSubtitle(agg)}
+ >
+ <div className="flex items-center">
+ <Icon className="w-3 h-3 mr-2" />
+ {capitalize(agg)}
+ </div>
+ </SelectItem>
+ );
+ })}
+ </SelectGroup>
+ </SelectContent>
+ </Select>
</FormControl>
</FormItem>
- );
- }}
- />
-);
+ )}
+ />
+ );
+};
+
+export const TooltipSelect = ({
+ fieldName,
+ saveFunction,
+}: {
+ fieldName: FieldName;
+ saveFunction: () => void;
+}) => {
+ const form = useFormContext();
+ const { fields } = useChartFormContext();
+
+ const createTooltip = (name: string, fields: Field[]) => {
+ const field = fields.find((f) => f.name === name);
+ return {
+ field: name,
+ type: field?.type ?? "string",
+ };
+ };
+
+ return (
+ <FormField
+ control={form.control}
+ name={fieldName}
+ render={({ field }) => {
+ const tooltips = field.value as Tooltip[] | undefined;
+ const values = tooltips?.map((t) => t.field) ?? [];
+
+ return (
+ <FormItem>
+ <FormControl>
+ <Multiselect
+ options={fields?.map((field) => field.name) ?? []}
+ value={values}
+ setValue={(values) => {
+ const selectedValues =
+ typeof values === "function" ? values([]) : values;
+
+ const tooltipObjects = selectedValues.map((fieldName) => {
+ return createTooltip(fieldName, fields);
+ });
+
+ field.onChange(tooltipObjects);
+ saveFunction();
+ }}
+ label={null}
+ fullWidth={false}
+ />
+ </FormControl>
+ </FormItem>
+ );
+ }}
+ />
+ );
+};
+
+export const SortField = ({
+ fieldName,
+ label,
+ defaultValue,
+}: {
+ fieldName: FieldName;
+ label: string;
+ defaultValue?: string;
+}) => {
+ return (
+ <SelectField
+ fieldName={fieldName}
+ label={label}
+ options={SORT_TYPES.map((type) => ({
+ display: (
+ <IconWithText
+ Icon={
+ type === "ascending"
+ ? ArrowUpWideNarrowIcon
+ : ArrowDownWideNarrowIcon
+ }
+ text={capitalize(type)}
+ />
+ ),
+ value: type,
+ }))}
+ defaultValue={defaultValue ?? "ascending"}
+ />
+ );
+};
+
+export const BinFields: React.FC<{
+ fieldName: "xAxis" | "yAxis" | "color";
+}> = ({ fieldName }) => {
+ const form = useFormContext<z.infer<typeof ChartSchema>>();
+ const formValues = useWatch({ control: form.control });
+ const isBinned = formValues[fieldName]?.bin?.binned;
+
+ const hasStep = formValues[fieldName]?.bin?.step !== DEFAULT_BIN_SIZE;
+
+ return (
+ <div className="flex flex-row justify-between">
+ <BooleanField fieldName={`${fieldName}.bin.binned`} label="Binned" />
+ {isBinned && (
+ <>
+ <NumberField
+ fieldName={`${fieldName}.bin.step`}
+ label="Step"
+ inputClassName="w-14"
+ placeholder="0.5" // TODO: This doesn't work yet, we still show 0
+ />
+ <NumberField
+ fieldName={`${fieldName}.bin.maxbins`}
+ label="Maxbins"
+ inputClassName="w-14"
+ isDisabled={hasStep}
+ placeholder="10"
+ />
+ </>
+ )}
+ </div>
+ );
+};
diff --git a/frontend/src/components/data-table/charts/components/layouts.tsx b/frontend/src/components/data-table/charts/components/layouts.tsx
new file mode 100644
index 0000000000..bf87cc31d0
--- /dev/null
+++ b/frontend/src/components/data-table/charts/components/layouts.tsx
@@ -0,0 +1,83 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import { AccordionItem, AccordionTrigger } from "@/components/ui/accordion";
+import { AccordionContent } from "@/components/ui/accordion";
+import { cn } from "@/utils/cn";
+import type { LucideProps } from "lucide-react";
+
+export const Title: React.FC<{ text: string }> = ({ text }) => {
+ return <h2 className="font-semibold my-0">{text}</h2>;
+};
+
+export const TabContainer: React.FC<{
+ className?: string;
+ children: React.ReactNode;
+}> = ({ children, className }) => {
+ return <div className={cn("flex flex-col gap-2", className)}>{children}</div>;
+};
+
+export const FormSectionHorizontalRule: React.FC<{
+ className?: string;
+}> = ({ className }) => {
+ return <hr className={cn("my-1", className)} />;
+};
+
+export const FieldSection: React.FC<{
+ children: React.ReactNode;
+ className?: string;
+}> = ({ children, className }) => {
+ return (
+ <section className={cn("flex flex-col gap-1.5", className)}>
+ {children}
+ </section>
+ );
+};
+
+export const IconWithText: React.FC<{
+ Icon: React.ForwardRefExoticComponent<
+ Omit<LucideProps, "ref"> & React.RefAttributes<SVGSVGElement>
+ >;
+ text: string;
+}> = ({ Icon, text }) => {
+ return (
+ <div className="flex items-center">
+ <Icon className="w-3 h-3 mr-2" />
+ <span>{text}</span>
+ </div>
+ );
+};
+
+export const AccordionFormTrigger: React.FC<{
+ children: React.ReactNode;
+ className?: string;
+}> = ({ children, className }) => {
+ return (
+ <AccordionTrigger className={cn("py-1", className)}>
+ {children}
+ </AccordionTrigger>
+ );
+};
+
+export const AccordionFormItem: React.FC<{
+ children: React.ReactNode;
+ value: string;
+}> = ({ children, value }) => {
+ return (
+ <AccordionItem value={value} className="border-none">
+ {children}
+ </AccordionItem>
+ );
+};
+
+export const AccordionFormContent: React.FC<{
+ children: React.ReactNode;
+ wrapperClassName?: string;
+}> = ({ children, wrapperClassName }) => {
+ return (
+ <AccordionContent
+ wrapperClassName={cn("pb-2 flex flex-col gap-2", wrapperClassName)}
+ >
+ {children}
+ </AccordionContent>
+ );
+};
diff --git a/frontend/src/components/data-table/chart-transforms/constants.ts b/frontend/src/components/data-table/charts/constants.ts
similarity index 88%
rename from frontend/src/components/data-table/chart-transforms/constants.ts
rename to frontend/src/components/data-table/charts/constants.ts
index 0deb8474d3..780626a257 100644
--- a/frontend/src/components/data-table/chart-transforms/constants.ts
+++ b/frontend/src/components/data-table/charts/constants.ts
@@ -14,6 +14,8 @@ import {
SquareFunctionIcon,
TableIcon,
AreaChartIcon,
+ ChartNoAxesColumn,
+ ChartColumn,
} from "lucide-react";
import type { ColorScheme } from "vega";
import type {
@@ -25,6 +27,10 @@ import type {
export const COUNT_FIELD = "__count__";
export const DEFAULT_COLOR_SCHEME = "default";
+export const DEFAULT_BIN_SIZE = 0;
+
+// Set a field to this to reflect that it is not set
+export const EMPTY_VALUE = "";
export const CHART_TYPE_ICON: Record<ChartType, React.ElementType> = {
line: LineChartIcon,
@@ -44,6 +50,11 @@ export const AGGREGATION_TYPE_ICON: Record<AggregationFn, React.ElementType> = {
min: ArrowDownToLineIcon,
max: ArrowUpToLineIcon,
distinct: HashIcon,
+ valid: HashIcon,
+ stdev: ChartNoAxesColumn,
+ stdevp: ChartNoAxesColumn,
+ variance: ChartColumn,
+ variancep: ChartColumn,
};
export const AGGREGATION_TYPE_DESCRIPTIONS: Record<AggregationFn, string> = {
@@ -54,7 +65,12 @@ export const AGGREGATION_TYPE_DESCRIPTIONS: Record<AggregationFn, string> = {
median: "Median of values",
min: "Minimum value",
max: "Maximum value",
- distinct: "Distinct values",
+ distinct: "Count of distinct records",
+ valid: "Count non-null records",
+ stdev: "Standard deviation",
+ stdevp: "Standard deviation of population",
+ variance: "Variance",
+ variancep: "Variance of population",
};
export const COLOR_SCHEMES: Array<ColorScheme | typeof DEFAULT_COLOR_SCHEME> = [
@@ -116,9 +132,6 @@ export const SCALE_TYPE_DESCRIPTIONS: Record<SelectableDataType, string> = {
temporal: "Continuous temporal scale",
};
-// Set a field to this to reflect that it is not set
-export const EMPTY_VALUE = "";
-
export const TIME_UNIT_DESCRIPTIONS: Record<
TimeUnit,
[title: string, description: string]
diff --git a/frontend/src/components/data-table/charts/context.ts b/frontend/src/components/data-table/charts/context.ts
new file mode 100644
index 0000000000..5d20906200
--- /dev/null
+++ b/frontend/src/components/data-table/charts/context.ts
@@ -0,0 +1,17 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import { createContext, useContext } from "react";
+import type { Field } from "./components/form-fields";
+import { Functions } from "@/utils/functions";
+
+export const ChartFormContext = createContext<{
+ fields: Field[];
+ saveForm: () => void;
+}>({
+ fields: [],
+ saveForm: Functions.NOOP,
+});
+
+export const useChartFormContext = () => {
+ return useContext(ChartFormContext);
+};
diff --git a/frontend/src/components/data-table/charts/forms/common-chart.tsx b/frontend/src/components/data-table/charts/forms/common-chart.tsx
new file mode 100644
index 0000000000..0e5b38cf36
--- /dev/null
+++ b/frontend/src/components/data-table/charts/forms/common-chart.tsx
@@ -0,0 +1,164 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import { XAxis, YAxis, ColorByAxis, Facet } from "../components/chart-items";
+import { useFormContext, useWatch } from "react-hook-form";
+import { isFieldSet } from "../chart-spec/spec";
+import type { ChartSchema } from "../schemas";
+import type { z } from "zod";
+import {
+ BooleanField,
+ InputField,
+ SliderField,
+ SelectField,
+ ColorArrayField,
+ TooltipSelect,
+} from "../components/form-fields";
+import { Accordion } from "@/components/ui/accordion";
+import { COLOR_SCHEMES, DEFAULT_COLOR_SCHEME } from "../constants";
+import { capitalize } from "lodash-es";
+import { InfoIcon } from "lucide-react";
+import {
+ AccordionFormItem,
+ AccordionFormTrigger,
+ AccordionFormContent,
+ Title,
+ FormSectionHorizontalRule,
+} from "../components/layouts";
+import { useChartFormContext } from "../context";
+
+export const CommonChartForm: React.FC = () => {
+ const form = useFormContext<z.infer<typeof ChartSchema>>();
+
+ const formValues = useWatch({ control: form.control });
+ const yColumn = formValues.general?.yColumn;
+ const groupByColumn = formValues.general?.colorByColumn;
+
+ const yColumnExists = isFieldSet(yColumn?.field);
+ const showStacking = isFieldSet(groupByColumn?.field);
+
+ return (
+ <>
+ <XAxis />
+ <YAxis />
+
+ {yColumnExists && (
+ <>
+ <ColorByAxis />
+ {showStacking && (
+ <div className="flex flex-row gap-2">
+ <BooleanField fieldName="general.stacking" label="Stacked" />
+ </div>
+ )}
+ </>
+ )}
+
+ <FormSectionHorizontalRule />
+ <OtherOptions />
+ </>
+ );
+};
+
+export const StyleForm: React.FC = () => {
+ return (
+ <Accordion type="multiple">
+ <AccordionFormItem value="general">
+ <AccordionFormTrigger className="pt-0">
+ <Title text="General" />
+ </AccordionFormTrigger>
+ <AccordionFormContent>
+ <InputField label="Plot title" fieldName="general.title" />
+ </AccordionFormContent>
+ </AccordionFormItem>
+
+ <AccordionFormItem value="xAxis">
+ <AccordionFormTrigger>
+ <Title text="X-Axis" />
+ </AccordionFormTrigger>
+ <AccordionFormContent>
+ <InputField label="Label" fieldName="xAxis.label" />
+ <SliderField
+ fieldName="xAxis.width"
+ label="Width"
+ value={400}
+ start={200}
+ stop={800}
+ />
+ </AccordionFormContent>
+ </AccordionFormItem>
+
+ <AccordionFormItem value="yAxis">
+ <AccordionFormTrigger>
+ <Title text="Y-Axis" />
+ </AccordionFormTrigger>
+ <AccordionFormContent>
+ <InputField label="Label" fieldName="yAxis.label" />
+ <SliderField
+ fieldName="yAxis.height"
+ label="Height"
+ value={300}
+ start={150}
+ stop={600}
+ />
+ </AccordionFormContent>
+ </AccordionFormItem>
+
+ <AccordionFormItem value="color">
+ <AccordionFormTrigger>
+ <Title text="Color" />
+ </AccordionFormTrigger>
+ <AccordionFormContent>
+ <SelectField
+ fieldName="color.scheme"
+ label="Color scheme"
+ defaultValue={DEFAULT_COLOR_SCHEME}
+ options={COLOR_SCHEMES.map((scheme) => ({
+ display: capitalize(scheme),
+ value: scheme,
+ }))}
+ />
+ <ColorArrayField fieldName="color.range" label="Color range" />
+ <p className="text-xs">
+ <InfoIcon className="w-2.5 h-2.5 inline mb-1 mr-1" />
+ If you are using color range, color scheme will be ignored.
+ </p>
+ </AccordionFormContent>
+ </AccordionFormItem>
+ </Accordion>
+ );
+};
+
+export const OtherOptions: React.FC = () => {
+ const { saveForm } = useChartFormContext();
+
+ const form = useFormContext<z.infer<typeof ChartSchema>>();
+ const formValues = useWatch({ control: form.control });
+ const autoTooltips = formValues.tooltips?.auto;
+
+ return (
+ <Accordion type="multiple">
+ <AccordionFormItem value="facet">
+ <AccordionFormTrigger className="pt-0">
+ <Title text="Faceting" />
+ </AccordionFormTrigger>
+ <AccordionFormContent>
+ <Facet />
+ </AccordionFormContent>
+ </AccordionFormItem>
+
+ <AccordionFormItem value="tooltips">
+ <AccordionFormTrigger>
+ <Title text="Tooltips" />
+ </AccordionFormTrigger>
+ <AccordionFormContent wrapperClassName="flex-row justify-between">
+ <BooleanField fieldName="tooltips.auto" label="Auto" />
+ {!autoTooltips && (
+ <TooltipSelect
+ fieldName="tooltips.fields"
+ saveFunction={saveForm}
+ />
+ )}
+ </AccordionFormContent>
+ </AccordionFormItem>
+ </Accordion>
+ );
+};
diff --git a/frontend/src/components/data-table/charts/forms/heatmap.tsx b/frontend/src/components/data-table/charts/forms/heatmap.tsx
new file mode 100644
index 0000000000..3de2b110cb
--- /dev/null
+++ b/frontend/src/components/data-table/charts/forms/heatmap.tsx
@@ -0,0 +1,45 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import { useFormContext, useWatch } from "react-hook-form";
+import { isFieldSet } from "../chart-spec/spec";
+import type { ChartSchema } from "../schemas";
+import type { z } from "zod";
+import { NumberField } from "../components/form-fields";
+import { ColorByAxis, XAxis, YAxis } from "../components/chart-items";
+import { OtherOptions } from "./common-chart";
+import { FormSectionHorizontalRule } from "../components/layouts";
+
+export const HeatmapForm: React.FC = () => {
+ const form = useFormContext<z.infer<typeof ChartSchema>>();
+
+ const formValues = useWatch({ control: form.control });
+ const xColumnExists = isFieldSet(formValues.general?.xColumn?.field);
+ const yColumnExists = isFieldSet(formValues.general?.yColumn?.field);
+
+ return (
+ <>
+ <XAxis />
+ {xColumnExists && (
+ <NumberField
+ fieldName="xAxis.bin.maxbins"
+ label="Number of boxes (max)"
+ className="justify-between"
+ />
+ )}
+ <YAxis />
+ {yColumnExists && (
+ <>
+ <NumberField
+ fieldName="yAxis.bin.maxbins"
+ label="Number of boxes (max)"
+ className="justify-between"
+ />
+ <ColorByAxis />
+ </>
+ )}
+
+ <FormSectionHorizontalRule />
+ <OtherOptions />
+ </>
+ );
+};
diff --git a/frontend/src/components/data-table/charts/forms/pie.tsx b/frontend/src/components/data-table/charts/forms/pie.tsx
new file mode 100644
index 0000000000..ed3abafc22
--- /dev/null
+++ b/frontend/src/components/data-table/charts/forms/pie.tsx
@@ -0,0 +1,70 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import { ColumnSelector } from "../components/form-fields";
+import { FormSectionHorizontalRule, Title } from "../components/layouts";
+import { useFormContext, useWatch } from "react-hook-form";
+import { isFieldSet } from "../chart-spec/spec";
+import type { ChartSchema } from "../schemas";
+import type { z } from "zod";
+import {
+ DataTypeSelect,
+ AggregationSelect,
+ NumberField,
+} from "../components/form-fields";
+import { useChartFormContext } from "../context";
+import { OtherOptions } from "./common-chart";
+import { convertDataTypeToSelectable } from "../chart-spec/types";
+import { EMPTY_VALUE } from "../constants";
+
+export const PieForm: React.FC = () => {
+ const form = useFormContext<z.infer<typeof ChartSchema>>();
+ const { fields } = useChartFormContext();
+
+ const formValues = useWatch({ control: form.control });
+ const colorByColumn = formValues.general?.colorByColumn;
+
+ let ySelectedDataType = formValues.general?.yColumn?.selectedDataType;
+ if (ySelectedDataType === EMPTY_VALUE || !ySelectedDataType) {
+ ySelectedDataType = "string";
+ }
+
+ const inferredColorByDataType = colorByColumn?.type
+ ? convertDataTypeToSelectable(colorByColumn.type)
+ : "string";
+
+ return (
+ <>
+ <Title text="Color by" />
+ <ColumnSelector
+ fieldName="general.colorByColumn.field"
+ columns={fields}
+ includeCountField={false}
+ />
+ {isFieldSet(colorByColumn?.field) && (
+ <DataTypeSelect
+ fieldName="general.colorByColumn.selectedDataType"
+ label="Data Type"
+ defaultValue={inferredColorByDataType}
+ />
+ )}
+
+ <Title text="Size by" />
+ <div className="flex flex-row justify-between">
+ <ColumnSelector fieldName="general.yColumn.field" columns={fields} />
+ <AggregationSelect
+ fieldName="general.yColumn.aggregate"
+ selectedDataType={ySelectedDataType}
+ />
+ </div>
+
+ <NumberField
+ fieldName="style.innerRadius"
+ label="Donut size"
+ className="w-32"
+ />
+
+ <FormSectionHorizontalRule />
+ <OtherOptions />
+ </>
+ );
+};
diff --git a/frontend/src/components/data-table/chart-transforms/lazy-chart.tsx b/frontend/src/components/data-table/charts/lazy-chart.tsx
similarity index 92%
rename from frontend/src/components/data-table/chart-transforms/lazy-chart.tsx
rename to frontend/src/components/data-table/charts/lazy-chart.tsx
index b5eb24a7ea..29e59321ef 100644
--- a/frontend/src/components/data-table/chart-transforms/lazy-chart.tsx
+++ b/frontend/src/components/data-table/charts/lazy-chart.tsx
@@ -5,11 +5,11 @@ import type { ChartType } from "./types";
import { useTheme } from "@/theme/useTheme";
import type { z } from "zod";
-import type { ChartSchema } from "./chart-schemas";
+import type { ChartSchema } from "./schemas";
import type { TopLevelSpec } from "vega-lite";
-import type { ErrorMessage } from "./chart-spec";
+import type { ErrorMessage } from "./chart-spec/spec";
import { ChartPieIcon } from "lucide-react";
-import { createVegaSpec } from "./chart-spec";
+import { createVegaSpec } from "./chart-spec/spec";
const LazyVega = React.lazy(() =>
import("react-vega").then((m) => ({ default: m.Vega })),
diff --git a/frontend/src/components/data-table/chart-transforms/chart-schemas.ts b/frontend/src/components/data-table/charts/schemas.ts
similarity index 55%
rename from frontend/src/components/data-table/chart-transforms/chart-schemas.ts
rename to frontend/src/components/data-table/charts/schemas.ts
index f0641c3419..813b948f56 100644
--- a/frontend/src/components/data-table/chart-transforms/chart-schemas.ts
+++ b/frontend/src/components/data-table/charts/schemas.ts
@@ -15,44 +15,49 @@ import {
} from "./types";
import { DEFAULT_COLOR_SCHEME, EMPTY_VALUE } from "./constants";
-export const DEFAULT_BIN_VALUE = 0;
-export const NONE_GROUP_BY = "None";
-
export const BinSchema = z.object({
binned: z.boolean().optional(),
step: z.number().optional(),
maxbins: z.number().optional(),
});
-export const AxisSchema = z
- .object({
- field: z.string().optional(),
- type: z.enum([...DATA_TYPES, EMPTY_VALUE]).optional(),
- selectedDataType: z
- .enum([...SELECTABLE_DATA_TYPES, EMPTY_VALUE])
- .optional(),
- aggregate: z.enum(AGGREGATION_FNS).default(NONE_AGGREGATION).optional(),
- sort: z.enum(SORT_TYPES).default("ascending").optional(),
- timeUnit: z.enum(TIME_UNITS).optional(),
- })
- .optional();
+const BaseColumnSchema = z.object({
+ field: z.string().optional(),
+ type: z.enum([...DATA_TYPES, EMPTY_VALUE]).optional(),
+ selectedDataType: z.enum([...SELECTABLE_DATA_TYPES, EMPTY_VALUE]).optional(),
+ sort: z.enum(SORT_TYPES).default("ascending").optional(),
+ timeUnit: z.enum(TIME_UNITS).optional(),
+});
+
+export const AxisSchema = BaseColumnSchema.extend({
+ aggregate: z.enum(AGGREGATION_FNS).default(NONE_AGGREGATION).optional(),
+});
+
+export const RowFacet = BaseColumnSchema.extend({
+ linkYAxis: z.boolean().default(true).optional(),
+ binned: z.boolean().default(true).optional(),
+ maxbins: z.number().optional(),
+});
+export const ColumnFacet = BaseColumnSchema.extend({
+ linkXAxis: z.boolean().default(true).optional(),
+ binned: z.boolean().default(true).optional(),
+ maxbins: z.number().optional(),
+});
export const ChartSchema = z.object({
general: z.object({
title: z.string().optional(),
- xColumn: AxisSchema,
- yColumn: AxisSchema,
- colorByColumn: AxisSchema,
+ xColumn: AxisSchema.optional(),
+ yColumn: AxisSchema.optional(),
+ colorByColumn: AxisSchema.optional(),
+ facet: z
+ .object({
+ row: RowFacet,
+ column: ColumnFacet,
+ })
+ .optional(),
horizontal: z.boolean().optional(),
stacking: z.boolean().optional(),
- tooltips: z
- .array(
- z.object({
- field: z.string(),
- type: z.enum(DATA_TYPES),
- }),
- )
- .optional(),
}),
xAxis: z
.object({
@@ -73,6 +78,7 @@ export const ChartSchema = z.object({
scheme: z.string().default(DEFAULT_COLOR_SCHEME).optional(),
range: z.array(z.string()).optional(),
domain: z.array(z.string()).optional(),
+ bin: BinSchema.optional(),
})
.optional(),
style: z
@@ -80,6 +86,18 @@ export const ChartSchema = z.object({
innerRadius: z.number().optional(),
})
.optional(),
+ tooltips: z
+ .object({
+ auto: z.boolean(),
+ fields: z.array(
+ z.object({
+ field: z.string(),
+ type: z.enum(DATA_TYPES),
+ }),
+ ),
+ })
+ .default({ auto: true, fields: [] })
+ .optional(),
});
export type ChartSchemaType = z.infer<typeof ChartSchema>;
diff --git a/frontend/src/components/data-table/chart-transforms/storage.ts b/frontend/src/components/data-table/charts/storage.ts
similarity index 78%
rename from frontend/src/components/data-table/chart-transforms/storage.ts
rename to frontend/src/components/data-table/charts/storage.ts
index 0822e0de97..f3fb56f0ac 100644
--- a/frontend/src/components/data-table/chart-transforms/storage.ts
+++ b/frontend/src/components/data-table/charts/storage.ts
@@ -4,11 +4,11 @@ import type { CellId } from "@/core/cells/ids";
import type { TypedString } from "@/utils/typed";
import { atomWithStorage } from "jotai/utils";
import { z } from "zod";
-import { atom } from "jotai";
-import { ChartSchema } from "./chart-schemas";
+import { ChartSchema } from "./schemas";
import { Logger } from "@/utils/Logger";
import type { ChartType } from "./types";
import { NotebookScopedLocalStorage } from "@/utils/localStorage";
+import { capitalize } from "lodash-es";
export type TabName = TypedString<"TabName">;
export const KEY = "marimo:charts:v2";
@@ -63,4 +63,14 @@ export const tabsStorageAtom = atomWithStorage<TabStorageMap>(
new Map(),
mapStorage,
);
-export const tabNumberAtom = atom(0);
+
+/**
+ * Convenience function to get the tab name for a given tab number and chart type
+ */
+export function getChartTabName(tabNum: number, chartType: ChartType) {
+ const capitalizedChartType = capitalize(chartType);
+ if (tabNum === 0) {
+ return `${capitalizedChartType} Chart` as TabName;
+ }
+ return `${capitalizedChartType} Chart ${tabNum + 1}` as TabName;
+}
diff --git a/frontend/src/components/data-table/chart-transforms/types.ts b/frontend/src/components/data-table/charts/types.ts
similarity index 91%
rename from frontend/src/components/data-table/chart-transforms/types.ts
rename to frontend/src/components/data-table/charts/types.ts
index 170d171460..be8009aaa5 100644
--- a/frontend/src/components/data-table/chart-transforms/types.ts
+++ b/frontend/src/components/data-table/charts/types.ts
@@ -64,9 +64,24 @@ export const AGGREGATION_FNS = [
"min",
"max",
"distinct",
+ "valid",
+ "stdev",
+ "stdevp",
+ "variance",
+ "variancep",
] as const;
export type AggregationFn = (typeof AGGREGATION_FNS)[number];
+/*
+ * Subset of AGGREGATION_FNS that are valid for string data types
+ */
+export const STRING_AGGREGATION_FNS: AggregationFn[] = [
+ "none",
+ "count",
+ "distinct",
+ "valid",
+];
+
/**
* Subset of VegaLite's MarkType, https://vega.github.io/vega-lite/docs/mark.html#types
*/
diff --git a/frontend/src/components/datasets/icons.tsx b/frontend/src/components/datasets/icons.tsx
index ff50ec74b0..be2804a644 100644
--- a/frontend/src/components/datasets/icons.tsx
+++ b/frontend/src/components/datasets/icons.tsx
@@ -11,7 +11,7 @@ import {
ClockIcon,
CurlyBracesIcon,
} from "lucide-react";
-import type { SelectableDataType } from "../data-table/chart-transforms/types";
+import type { SelectableDataType } from "../data-table/charts/types";
/**
* Maps a data type to an icon.
diff --git a/frontend/src/plugins/impl/DataTablePlugin.tsx b/frontend/src/plugins/impl/DataTablePlugin.tsx
index c96499f629..5c96179489 100644
--- a/frontend/src/plugins/impl/DataTablePlugin.tsx
+++ b/frontend/src/plugins/impl/DataTablePlugin.tsx
@@ -44,7 +44,7 @@ import type { CellSelectionState } from "@/components/data-table/cell-selection/
import type { CellStyleState } from "@/components/data-table/cell-styling/types";
import { Button } from "@/components/ui/button";
import { Table2Icon } from "lucide-react";
-import { TablePanel } from "@/components/data-table/chart-transforms/chart-transforms";
+import { TablePanel } from "@/components/data-table/charts/charts";
import { getFeatureFlag } from "@/core/config/feature-flag";
import {
filterToFilterCondition,