You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by en...@apache.org on 2026/08/27 13:12:56 UTC
(superset) 05/46: feat(dashboard-v2): add column-reference widget controls
This is an automated email from the ASF dual-hosted git repository.
EnxDev pushed a commit to branch enxdev/poc/dashboard-v2-editing-ui-flow
in repository https://gitbox.apache.org/repos/asf/superset.git
commit a2a7bf4f76b65056118920c8b93c8570d207a6f2
Author: Enzo Martellucci <en...@gmail.com>
AuthorDate: Thu Aug 20 15:42:52 2026 +0200
feat(dashboard-v2): add column-reference widget controls
Render x-control: "column" and "column-multi" schema fields as a
dataset-aware column picker / reorderable multi-select instead of
plain text inputs, using Task 2's useDatasetMetadata hook. Introduces
ReferenceOption/ReferenceSelect/ReferenceMultiList primitives in
schemaControlRenderers.tsx, reused by the metric controls landing in
Task 4.
---
.../DashboardBuilderV2/SchemaControlPanel.test.tsx | 89 +++++++-
.../DashboardBuilderV2/SchemaControlPanel.tsx | 5 +
.../schemaControlRenderers.test.tsx | 50 +++++
.../DashboardBuilderV2/schemaControlRenderers.tsx | 244 ++++++++++++++++++++-
4 files changed, 379 insertions(+), 9 deletions(-)
diff --git a/superset-frontend/src/pages/DashboardBuilderV2/SchemaControlPanel.test.tsx b/superset-frontend/src/pages/DashboardBuilderV2/SchemaControlPanel.test.tsx
index 3ed90e70914..671fd937523 100644
--- a/superset-frontend/src/pages/DashboardBuilderV2/SchemaControlPanel.test.tsx
+++ b/superset-frontend/src/pages/DashboardBuilderV2/SchemaControlPanel.test.tsx
@@ -17,10 +17,16 @@
* under the License.
*/
import { SupersetClient } from '@superset-ui/core';
-import { render, screen, waitFor } from 'spec/helpers/testing-library';
+import {
+ render,
+ screen,
+ selectOption,
+ waitFor,
+} from 'spec/helpers/testing-library';
import DashboardProvider from 'src/core/dashboard/DashboardProvider';
import 'src/core/dashboard';
import { fetchQueryData } from 'src/core/dashboard/chartData';
+import { resetDatasetMetadataCacheForTests } from 'src/core/dashboard/datasetMetadata';
import SchemaControlPanel from './SchemaControlPanel';
jest.mock('src/core/dashboard/chartData', () => ({
@@ -42,13 +48,19 @@ const SCHEMA = {
};
const postSpy = jest.spyOn(SupersetClient, 'post');
+const getSpy = jest.spyOn(SupersetClient, 'get');
beforeEach(() => {
provider.reset();
postSpy.mockReset();
postSpy.mockResolvedValue({ json: { result: SCHEMA } } as never);
+ getSpy.mockReset();
fetchQueryDataMock.mockReset();
fetchQueryDataMock.mockResolvedValue({ columns: [], rows: [] });
+ // `useDatasetMetadata` caches by dataset id for the lifetime of the page,
+ // which would otherwise leak one test's mocked columns/metrics into the
+ // next test that binds the same `datasetId`.
+ resetDatasetMetadataCacheForTests();
});
const mount = (type: string, props?: Record<string, unknown>) => {
@@ -144,3 +156,78 @@ test('discovers series from an explicit colorDimension when set', async () => {
),
);
});
+
+test('renders a column picker for an x-control: "column" field and writes the pick back into props', async () => {
+ postSpy.mockResolvedValue({
+ json: {
+ result: {
+ type: 'object',
+ properties: {
+ colorDimension: {
+ type: 'string',
+ title: 'Color dimension',
+ 'x-control': 'column',
+ },
+ },
+ },
+ },
+ } as never);
+ getSpy.mockResolvedValue({
+ json: {
+ result: {
+ columns: [{ column_name: 'gender', type_generic: 1 }],
+ metrics: [],
+ },
+ },
+ } as never);
+
+ const id = mount('balloons', {
+ dataBinding: { datasetId: 1, metrics: ['count'] },
+ });
+
+ await screen.findByText('Color dimension');
+ await selectOption('gender');
+
+ await waitFor(() =>
+ expect(provider.getNode(id)?.props?.colorDimension).toBe('gender'),
+ );
+});
+
+test('renders an ordered column-multi list for an x-control: "column-multi" field, and picking one writes the array back', async () => {
+ postSpy.mockResolvedValue({
+ json: {
+ result: {
+ type: 'object',
+ properties: {
+ dimensions: {
+ type: 'array',
+ title: 'Dimensions',
+ 'x-control': 'column-multi',
+ },
+ },
+ },
+ },
+ } as never);
+ getSpy.mockResolvedValue({
+ json: {
+ result: {
+ columns: [
+ { column_name: 'name', type_generic: 1 },
+ { column_name: 'gender', type_generic: 1 },
+ ],
+ metrics: [],
+ },
+ },
+ } as never);
+
+ const id = mount('balloons', {
+ dataBinding: { datasetId: 1, metrics: ['count'] },
+ });
+
+ await screen.findByText('Dimensions');
+ await selectOption('name');
+
+ await waitFor(() =>
+ expect(provider.getNode(id)?.props?.dimensions).toEqual(['name']),
+ );
+});
diff --git a/superset-frontend/src/pages/DashboardBuilderV2/SchemaControlPanel.tsx b/superset-frontend/src/pages/DashboardBuilderV2/SchemaControlPanel.tsx
index 4282b8de440..a7d4dd30d12 100644
--- a/superset-frontend/src/pages/DashboardBuilderV2/SchemaControlPanel.tsx
+++ b/superset-frontend/src/pages/DashboardBuilderV2/SchemaControlPanel.tsx
@@ -240,6 +240,11 @@ export default function SchemaControlPanel({ nodeId }: { nodeId: string }) {
renderers={schemaControlRenderers}
cells={cellRegistryEntries}
validationMode="ValidateAndHide"
+ // Column/metric-reference controls need the widget's
+ // `dataBinding.datasetId`, which lives outside their own field —
+ // `config.formData` is how a JsonForms control reaches sibling
+ // data (mirrors `SemanticLayerModal`'s `config={{ formData }}`).
+ config={{ formData: props }}
onChange={({ data }) => {
if (JSON.stringify(data) !== propsKey) {
// Our own edit — don't let the resync effect remount the form
diff --git a/superset-frontend/src/pages/DashboardBuilderV2/schemaControlRenderers.test.tsx b/superset-frontend/src/pages/DashboardBuilderV2/schemaControlRenderers.test.tsx
new file mode 100644
index 00000000000..934e0db0bbf
--- /dev/null
+++ b/superset-frontend/src/pages/DashboardBuilderV2/schemaControlRenderers.test.tsx
@@ -0,0 +1,50 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { columnOptions } from './schemaControlRenderers';
+
+test('columnOptions filters by x-column-types when given', () => {
+ const metadata = {
+ columns: [
+ { name: 'region', type: 1 },
+ { name: 'sales', type: 0 },
+ ],
+ metrics: [],
+ };
+ expect(columnOptions(metadata, ['numeric']).map(o => o.value)).toEqual([
+ 'sales',
+ ]);
+});
+
+test('columnOptions returns every column when no x-column-types hint is given', () => {
+ const metadata = {
+ columns: [
+ { name: 'region', type: 1 },
+ { name: 'sales', type: 0 },
+ ],
+ metrics: [],
+ };
+ expect(columnOptions(metadata, undefined).map(o => o.value)).toEqual([
+ 'region',
+ 'sales',
+ ]);
+});
+
+test('columnOptions returns an empty list when metadata has not loaded yet', () => {
+ expect(columnOptions(null, undefined)).toEqual([]);
+});
diff --git a/superset-frontend/src/pages/DashboardBuilderV2/schemaControlRenderers.tsx b/superset-frontend/src/pages/DashboardBuilderV2/schemaControlRenderers.tsx
index 9cc97d8e0b4..5f59ccc52ee 100644
--- a/superset-frontend/src/pages/DashboardBuilderV2/schemaControlRenderers.tsx
+++ b/superset-frontend/src/pages/DashboardBuilderV2/schemaControlRenderers.tsx
@@ -20,20 +20,35 @@
/**
* Extra JSONForms renderers for schema-driven widget controls, on top
* of the Semantic Layer's shared `renderers`:
- * - `x-control: code` → a raw JSON editor (e.g. AG Grid column definitions).
- * - `x-control: color` → a native color swatch (e.g. per-series balloon color).
+ * - `x-control: code` → a raw JSON editor (e.g. AG Grid column definitions).
+ * - `x-control: color` → a native color swatch (e.g. per-series balloon color).
+ * - `x-control: column` → a single column-reference picker.
+ * - `x-control: column-multi` → an ordered, reorderable list of column references.
*
- * Both fall back to the field's schema `default`, since JsonForms does not
- * write defaults into the data until a field is touched.
+ * `code` and `color` fall back to the field's schema `default`, since
+ * JsonForms does not write defaults into the data until a field is touched.
*/
-import { useState } from 'react';
-import type { ChangeEvent } from 'react';
+import { useRef, useState } from 'react';
+import type { ChangeEvent, ReactElement, ReactNode } from 'react';
import { withJsonFormsControlProps } from '@jsonforms/react';
import type { ControlProps, JsonSchema } from '@jsonforms/core';
import { rankWith, schemaMatches } from '@jsonforms/core';
-import { Flex, Typography } from '@superset-ui/core/components';
+import { t } from '@apache-superset/core/translation';
+import {
+ Button,
+ Flex,
+ Form,
+ Select,
+ Typography,
+} from '@superset-ui/core/components';
+import { Icons } from '@superset-ui/core/components/Icons';
+import { ColumnTypeLabel } from '@superset-ui/chart-controls';
import { useTheme } from '@apache-superset/core/theme';
import { renderers as baseRenderers } from 'src/features/semanticLayers/jsonFormsHelpers';
+import {
+ useDatasetMetadata,
+ type DatasetMetadata,
+} from 'src/core/dashboard/datasetMetadata';
const xControlIs = (value: string) =>
schemaMatches(
@@ -110,7 +125,212 @@ function ColorControl({
);
}
-/** Base Semantic-Layer renderers plus the widget-control code/color ones. */
+/**
+ * The dataset id a column/metric-reference control resolves options
+ * against. A JsonForms control only sees its own field's data by default —
+ * the whole node's props reach it through `config.formData`, which
+ * `SchemaControlPanel` populates for exactly this reason (mirroring
+ * `SemanticLayerModal`'s own `config={{ formData }}`).
+ */
+function useBoundDatasetId(props: ControlProps): number | undefined {
+ const formData = (
+ props.config as { formData?: Record<string, unknown> } | undefined
+ )?.formData;
+ const dataBinding = formData?.dataBinding as
+ { datasetId?: number } | undefined;
+ return dataBinding?.datasetId;
+}
+
+interface ReferenceOption {
+ value: string;
+ label: ReactNode;
+}
+
+const COLUMN_TYPE_BY_HINT: Record<string, number> = {
+ numeric: 0,
+ string: 1,
+ temporal: 2,
+ boolean: 3,
+};
+
+/**
+ * Column options for a `column`/`column-multi` control, filtered by the
+ * field's `x-column-types` hint (omitted means any column type).
+ */
+export function columnOptions(
+ metadata: DatasetMetadata | null,
+ allowedTypes: string[] | undefined,
+): ReferenceOption[] {
+ const allowed = allowedTypes?.map(hint => COLUMN_TYPE_BY_HINT[hint]);
+ return (metadata?.columns ?? [])
+ .filter(
+ column =>
+ !allowed || (column.type !== null && allowed.includes(column.type)),
+ )
+ .map(column => ({
+ value: column.name,
+ label: (
+ <Flex align="center" gap="small">
+ <ColumnTypeLabel type={column.type ?? undefined} />
+ {column.name}
+ </Flex>
+ ),
+ }));
+}
+
+/** A single reference value (column or metric), rendered as a Select. */
+function ReferenceSelect({
+ label,
+ value,
+ options,
+ loading,
+ disabled,
+ onChange,
+}: {
+ label: string;
+ value: string | undefined;
+ options: ReferenceOption[];
+ loading: boolean;
+ disabled: boolean;
+ onChange: (next: string | undefined) => void;
+}): ReactElement {
+ return (
+ <Form.Item label={label}>
+ <Select
+ value={value}
+ onChange={next => onChange((next as string | undefined) ?? undefined)}
+ options={options}
+ loading={loading}
+ disabled={disabled}
+ allowClear
+ css={{ width: '100%' }}
+ />
+ </Form.Item>
+ );
+}
+
+/**
+ * An ordered list of reference values (columns or metrics): each entry can
+ * be removed or dragged to reorder, and a trailing Select adds one more from
+ * whatever isn't already picked.
+ */
+function ReferenceMultiList({
+ label,
+ values,
+ options,
+ loading,
+ disabled,
+ onChange,
+}: {
+ label: string;
+ values: string[];
+ options: ReferenceOption[];
+ loading: boolean;
+ disabled: boolean;
+ onChange: (next: string[]) => void;
+}): ReactElement {
+ const dragIndexRef = useRef<number | null>(null);
+ const available = options.filter(option => !values.includes(option.value));
+
+ const move = (from: number, to: number) => {
+ const next = [...values];
+ const [moved] = next.splice(from, 1);
+ next.splice(to, 0, moved);
+ onChange(next);
+ };
+
+ return (
+ <Flex vertical gap="small">
+ <Typography.Text strong>{label}</Typography.Text>
+ {values.map((value, index) => {
+ const option = options.find(candidate => candidate.value === value);
+ return (
+ <Flex
+ key={value}
+ align="center"
+ gap="small"
+ draggable
+ onDragStart={() => {
+ dragIndexRef.current = index;
+ }}
+ onDragOver={event => event.preventDefault()}
+ onDrop={() => {
+ if (
+ dragIndexRef.current !== null &&
+ dragIndexRef.current !== index
+ ) {
+ move(dragIndexRef.current, index);
+ }
+ dragIndexRef.current = null;
+ }}
+ >
+ <Icons.HolderOutlined iconSize="s" />
+ <div style={{ flex: 1 }}>{option?.label ?? value}</div>
+ <Button
+ buttonSize="xsmall"
+ buttonStyle="link"
+ aria-label={t('Remove')}
+ icon={<Icons.CloseOutlined iconSize="s" />}
+ onClick={() => onChange(values.filter((_, i) => i !== index))}
+ />
+ </Flex>
+ );
+ })}
+ {available.length > 0 && (
+ <Select
+ value={undefined}
+ placeholder={t('Add field')}
+ options={available}
+ loading={loading}
+ disabled={disabled}
+ onChange={next => onChange([...values, next as string])}
+ css={{ width: '100%' }}
+ />
+ )}
+ </Flex>
+ );
+}
+
+/** `x-control: "column"` — a single column reference. */
+function ColumnControl(props: ControlProps): ReactElement {
+ const datasetId = useBoundDatasetId(props);
+ const { metadata, loading } = useDatasetMetadata(datasetId);
+ const allowedTypes = (props.schema as Record<string, unknown>)[
+ 'x-column-types'
+ ] as string[] | undefined;
+ return (
+ <ReferenceSelect
+ label={props.label}
+ value={props.data as string | undefined}
+ options={columnOptions(metadata, allowedTypes)}
+ loading={loading}
+ disabled={!props.enabled}
+ onChange={value => props.handleChange(props.path, value)}
+ />
+ );
+}
+
+/** `x-control: "column-multi"` — an ordered list of column references. */
+function ColumnMultiControl(props: ControlProps): ReactElement {
+ const datasetId = useBoundDatasetId(props);
+ const { metadata, loading } = useDatasetMetadata(datasetId);
+ const allowedTypes = (props.schema as Record<string, unknown>)[
+ 'x-column-types'
+ ] as string[] | undefined;
+ const values = Array.isArray(props.data) ? (props.data as string[]) : [];
+ return (
+ <ReferenceMultiList
+ label={props.label}
+ values={values}
+ options={columnOptions(metadata, allowedTypes)}
+ loading={loading}
+ disabled={!props.enabled}
+ onChange={next => props.handleChange(props.path, next)}
+ />
+ );
+}
+
+/** Base Semantic-Layer renderers plus the widget-control ones above. */
export const schemaControlRenderers = [
...baseRenderers,
{
@@ -121,4 +341,12 @@ export const schemaControlRenderers = [
tester: rankWith(1000, xControlIs('color')),
renderer: withJsonFormsControlProps(ColorControl),
},
+ {
+ tester: rankWith(1000, xControlIs('column')),
+ renderer: withJsonFormsControlProps(ColumnControl),
+ },
+ {
+ tester: rankWith(1000, xControlIs('column-multi')),
+ renderer: withJsonFormsControlProps(ColumnMultiControl),
+ },
];