You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by ru...@apache.org on 2026/05/19 06:10:33 UTC
(superset) branch feat/glyph-single-file updated: test(glyph-core): add Tier 1 unit test suite (162 tests)
This is an automated email from the ASF dual-hosted git repository.
rusackas pushed a commit to branch feat/glyph-single-file
in repository https://gitbox.apache.org/repos/asf/superset.git
The following commit(s) were added to refs/heads/feat/glyph-single-file by this push:
new 86f2f056d26 test(glyph-core): add Tier 1 unit test suite (162 tests)
86f2f056d26 is described below
commit 86f2f056d263eb19abdb231a7f38345452c17edb
Author: Evan Rusackas <ev...@rusackas.com>
AuthorDate: Tue May 19 01:10:23 2026 -0500
test(glyph-core): add Tier 1 unit test suite (162 tests)
Comprehensive unit coverage of @superset-ui/glyph-core's public API:
arguments.test.ts (53 tests)
Every Argument class (Metric, Dimension, Temporal, Select, Text,
Checkbox, Int, Color, NumberFormat, Currency, TimeFormat,
ConditionalFormatting, Slider, Bounds, ColorPicker, RadioButton)
plus all type guards. Verifies static defaults, .with() override
semantics, and that the base class isn't mutated by subclasses.
defineChart.test.tsx (34 tests)
Factory wiring end-to-end: metadata pass-throughs (label,
canBeAnnotationTypes, useLegacyApi, supportedAnnotationTypes,
behaviors default, exampleGallery, thumbnailDark, credits),
arguments → auto Query / Chart Options sections, suppress flag,
prepend/middle/additional sections ordering, chartOptionsTabOverride,
controlOverrides + additionalControlOverrides merge, formDataOverrides,
onInit, _glyphArgs attachment, custom buildQuery + transform via the
plugin's loaders, and visibleWhen preservation through object-form
ArgDef. Plus resolveArgClass, getArgVisibleWhen, evaluateGlyphCondition.
presets.test.ts (27 tests)
Every reusable preset (HeaderFontSize, SubheaderFontSize, Subtitle,
ShowLegend, ShowLabels, ShowValue, ShowMetricName, MetricNameFontSize,
LegendType, LegendOrientation, LegendSort, LabelType, SortByMetric,
LabelPosition, SimpleLabelType, ValueLabelType, ShowTotal,
LabelThreshold, CircleShape, DataZoom, ForceTimestampFormatting) and
the shared option arrays (FONT_SIZE_OPTIONS_*, LEGEND_*_OPTIONS,
LABEL_TYPE_OPTIONS, SORT_OPTIONS). Verifies extensibility via .with().
crossFilter.test.ts (19 tests)
createSelectedValuesMap (empty / single / multi / unknown name),
isDataPointFiltered (empty filter / matching / mismatched),
createLabelMap (empty / multi / collision / column subset),
extractCrossFilterProps (all fields, missing setDataMask default,
coltypeMapping passthrough, empty filterState).
generators.test.ts (29 tests)
getControlConfig for Select/Checkbox/Int/Color/Text (with paramName
fallback when label is null), generateControlPanel section structure
(Query / Chart Options auto-population, metric/groupby/x_axis/
time_grain_sqla rows, adhoc_filters always present, GlyphArgConfig
visibility wiring, controlOverrides/formDataOverrides/extra rows),
generateTransformProps value extraction with all defaulting rules,
Color RGBA↔hex round-trip, Metric/Dimension/Temporal skipping,
passthrough option, custom transform option. Plus createGlyphPlugin
bundling.
All 162 tests green. Runs as: npx jest packages/superset-ui-glyph-core/test
Co-Authored-By: Claude Sonnet 4.6 <no...@anthropic.com>
---
.../superset-ui-glyph-core/test/arguments.test.ts | 475 +++++++++++++++++
.../test/crossFilter.test.ts | 212 ++++++++
.../test/defineChart.test.tsx | 563 +++++++++++++++++++++
.../superset-ui-glyph-core/test/generators.test.ts | 401 +++++++++++++++
.../superset-ui-glyph-core/test/presets.test.ts | 203 ++++++++
5 files changed, 1854 insertions(+)
diff --git a/superset-frontend/packages/superset-ui-glyph-core/test/arguments.test.ts b/superset-frontend/packages/superset-ui-glyph-core/test/arguments.test.ts
new file mode 100644
index 00000000000..539863f8235
--- /dev/null
+++ b/superset-frontend/packages/superset-ui-glyph-core/test/arguments.test.ts
@@ -0,0 +1,475 @@
+/**
+ * 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 {
+ Argument,
+ Bounds,
+ Checkbox,
+ Color,
+ ColorPicker,
+ ConditionalFormatting,
+ Currency,
+ Dimension,
+ Int,
+ isBoundsArg,
+ isCheckboxArg,
+ isColorArg,
+ isColorPickerArg,
+ isConditionalFormattingArg,
+ isCurrencyArg,
+ isDimensionArg,
+ isIntArg,
+ isMetricArg,
+ isNumberFormatArg,
+ isRadioButtonArg,
+ isSelectArg,
+ isSliderArg,
+ isTemporalArg,
+ isTextArg,
+ isTimeFormatArg,
+ Metric,
+ NumberFormat,
+ RadioButton,
+ Select,
+ Slider,
+ Temporal,
+ Text,
+ TimeFormat,
+} from '@superset-ui/glyph-core';
+import { ColumnType } from '@superset-ui/glyph-core/types';
+
+describe('Argument base class', () => {
+ test('stores its constructor value', () => {
+ const a = new Argument(42);
+ expect(a.value).toBe(42);
+ });
+
+ test('has expected static defaults', () => {
+ expect(Argument.label).toBeNull();
+ expect(Argument.description).toBeNull();
+ expect(Argument.columnType).toBe(ColumnType.Argument);
+ expect(Argument.controlType).toBe('TextControl');
+ });
+});
+
+describe('Metric', () => {
+ test('has expected static metadata', () => {
+ expect(Metric.label).toBe('Metric');
+ expect(Metric.columnType).toBe(ColumnType.Metric);
+ expect(Metric.controlType).toBe('MetricsControl');
+ expect(Metric.multi).toBe(false);
+ });
+
+ test('.with() overrides label, description, multi', () => {
+ const M = Metric.with({
+ label: 'Sales',
+ description: 'Total sales',
+ multi: true,
+ });
+ expect(M.label).toBe('Sales');
+ expect(M.description).toBe('Total sales');
+ expect(M.multi).toBe(true);
+ // unaltered ancestor metadata still present
+ expect(M.columnType).toBe(ColumnType.Metric);
+ expect(M.controlType).toBe('MetricsControl');
+ });
+
+ test('.with() falls back to parent defaults when option omitted', () => {
+ const M = Metric.with({ label: 'X' });
+ expect(M.label).toBe('X');
+ expect(M.multi).toBe(Metric.multi);
+ expect(M.description).toBe(Metric.description);
+ });
+
+ test('isMetricArg type guard', () => {
+ expect(isMetricArg(Metric)).toBe(true);
+ expect(isMetricArg(Metric.with({ label: 'X' }))).toBe(true);
+ expect(isMetricArg(Dimension)).toBe(false);
+ expect(isMetricArg(Select)).toBe(false);
+ });
+});
+
+describe('Dimension', () => {
+ test('has expected static metadata', () => {
+ expect(Dimension.label).toBe('Dimension');
+ expect(Dimension.columnType).toBe(ColumnType.Dimension);
+ expect(Dimension.controlType).toBe('GroupByControl');
+ expect(Dimension.multi).toBe(true);
+ });
+
+ test('.with() overrides label, description, multi', () => {
+ const D = Dimension.with({
+ label: 'Region',
+ multi: false,
+ });
+ expect(D.label).toBe('Region');
+ expect(D.multi).toBe(false);
+ });
+
+ test('isDimensionArg type guard', () => {
+ expect(isDimensionArg(Dimension)).toBe(true);
+ expect(isDimensionArg(Dimension.with({ label: 'X' }))).toBe(true);
+ expect(isDimensionArg(Metric)).toBe(false);
+ });
+});
+
+describe('Temporal', () => {
+ test('has expected static metadata', () => {
+ expect(Temporal.label).toBe('Time Column');
+ expect(Temporal.columnType).toBe(ColumnType.Temporal);
+ expect(Temporal.controlType).toBe('TemporalControl');
+ });
+
+ test('.with() overrides label and description', () => {
+ const T = Temporal.with({ label: 'Order Date' });
+ expect(T.label).toBe('Order Date');
+ });
+
+ test('isTemporalArg type guard', () => {
+ expect(isTemporalArg(Temporal)).toBe(true);
+ expect(isTemporalArg(Metric)).toBe(false);
+ });
+});
+
+describe('Select', () => {
+ const OPTIONS = [
+ { label: 'A', value: 'a' },
+ { label: 'B', value: 'b' },
+ ];
+
+ test('has expected static defaults', () => {
+ expect(Select.label).toBe('Select');
+ expect(Select.controlType).toBe('SelectControl');
+ expect(Select.options).toEqual([]);
+ expect(Select.default).toBe('');
+ });
+
+ test('.with() applies label, default, options', () => {
+ const S = Select.with({
+ label: 'Choice',
+ default: 'a',
+ options: OPTIONS,
+ });
+ expect(S.label).toBe('Choice');
+ expect(S.default).toBe('a');
+ expect(S.options).toEqual(OPTIONS);
+ });
+
+ test('isSelectArg type guard', () => {
+ expect(isSelectArg(Select.with({ options: OPTIONS }))).toBe(true);
+ expect(isSelectArg(Checkbox)).toBe(false);
+ expect(isSelectArg(Metric)).toBe(false);
+ });
+});
+
+describe('Text', () => {
+ test('has expected static defaults', () => {
+ expect(Text.controlType).toBe('TextControl');
+ expect(Text.default).toBe('');
+ expect(Text.placeholder).toBe('');
+ });
+
+ test('.with() applies label, default, placeholder', () => {
+ const T = Text.with({
+ label: 'Title',
+ default: 'Untitled',
+ placeholder: 'Enter title',
+ });
+ expect(T.label).toBe('Title');
+ expect(T.default).toBe('Untitled');
+ expect(T.placeholder).toBe('Enter title');
+ });
+
+ test('isTextArg type guard accepts Text but not Select/Checkbox', () => {
+ expect(isTextArg(Text)).toBe(true);
+ expect(isTextArg(Text.with({ label: 'X' }))).toBe(true);
+ expect(isTextArg(Checkbox)).toBe(false);
+ });
+});
+
+describe('Checkbox', () => {
+ test('has expected static defaults', () => {
+ expect(Checkbox.controlType).toBe('CheckboxControl');
+ expect(Checkbox.default).toBe(false);
+ });
+
+ test('.with() applies label, description, default', () => {
+ const C = Checkbox.with({
+ label: 'Show legend',
+ default: true,
+ });
+ expect(C.label).toBe('Show legend');
+ expect(C.default).toBe(true);
+ });
+
+ test('isCheckboxArg type guard', () => {
+ expect(isCheckboxArg(Checkbox)).toBe(true);
+ expect(isCheckboxArg(Checkbox.with({ default: true }))).toBe(true);
+ expect(isCheckboxArg(Text)).toBe(false);
+ });
+});
+
+describe('Int', () => {
+ test('has expected static defaults', () => {
+ expect(Int.controlType).toBe('SliderControl');
+ expect(Int.default).toBe(0);
+ expect(Int.min).toBe(0);
+ expect(Int.max).toBe(100);
+ expect(Int.step).toBe(1);
+ });
+
+ test('.with() applies label, default, min, max, step', () => {
+ const I = Int.with({
+ label: 'Limit',
+ default: 50,
+ min: 10,
+ max: 1000,
+ step: 5,
+ });
+ expect(I.label).toBe('Limit');
+ expect(I.default).toBe(50);
+ expect(I.min).toBe(10);
+ expect(I.max).toBe(1000);
+ expect(I.step).toBe(5);
+ });
+
+ test('isIntArg type guard', () => {
+ expect(isIntArg(Int)).toBe(true);
+ expect(isIntArg(Slider)).toBe(true); // Slider also has min/max
+ expect(isIntArg(Checkbox)).toBe(false);
+ });
+});
+
+describe('Color', () => {
+ test('has expected static defaults', () => {
+ expect(Color.controlType).toBe('ColorPickerControl');
+ expect(Color.default).toBe('#000000');
+ });
+
+ test('.with() applies label, default', () => {
+ const C = Color.with({ label: 'Fill', default: '#ff0000' });
+ expect(C.label).toBe('Fill');
+ expect(C.default).toBe('#ff0000');
+ });
+
+ test('isColorArg type guard', () => {
+ expect(isColorArg(Color)).toBe(true);
+ expect(isColorArg(Color.with({ default: '#ff0000' }))).toBe(true);
+ expect(isColorArg(Metric)).toBe(false);
+ });
+});
+
+describe('NumberFormat', () => {
+ test('has expected static defaults', () => {
+ expect(NumberFormat.controlType).toBe('NumberFormatControl');
+ expect(NumberFormat.default).toBe('SMART_NUMBER');
+ expect(NumberFormat.FORMAT_OPTIONS.length).toBeGreaterThan(10);
+ expect(
+ NumberFormat.FORMAT_OPTIONS.some(o => o.value === 'SMART_NUMBER'),
+ ).toBe(true);
+ });
+
+ test('.with() applies label, default', () => {
+ const N = NumberFormat.with({ label: 'Amount', default: '.2f' });
+ expect(N.label).toBe('Amount');
+ expect(N.default).toBe('.2f');
+ });
+
+ test('isNumberFormatArg type guard', () => {
+ expect(isNumberFormatArg(NumberFormat)).toBe(true);
+ expect(isNumberFormatArg(TimeFormat)).toBe(false);
+ });
+});
+
+describe('Currency', () => {
+ test('has expected static defaults', () => {
+ expect(Currency.controlType).toBe('CurrencyControl');
+ expect(Currency.default).toEqual({});
+ });
+
+ test('.with() applies label, default', () => {
+ const C = Currency.with({
+ label: 'Money',
+ default: { symbol: 'USD', symbolPosition: 'prefix' },
+ });
+ expect(C.label).toBe('Money');
+ expect(C.default).toEqual({ symbol: 'USD', symbolPosition: 'prefix' });
+ });
+
+ test('isCurrencyArg type guard', () => {
+ expect(isCurrencyArg(Currency)).toBe(true);
+ expect(isCurrencyArg(NumberFormat)).toBe(false);
+ });
+});
+
+describe('TimeFormat', () => {
+ test('has expected static defaults', () => {
+ expect(TimeFormat.controlType).toBe('TimeFormatControl');
+ expect(TimeFormat.default).toBe('smart_date');
+ expect(
+ TimeFormat.FORMAT_OPTIONS.some(o => o.value === 'smart_date'),
+ ).toBe(true);
+ });
+
+ test('.with() applies label, default', () => {
+ const T = TimeFormat.with({ label: 'When', default: '%Y-%m-%d' });
+ expect(T.label).toBe('When');
+ expect(T.default).toBe('%Y-%m-%d');
+ });
+
+ test('isTimeFormatArg type guard', () => {
+ expect(isTimeFormatArg(TimeFormat)).toBe(true);
+ expect(isTimeFormatArg(NumberFormat)).toBe(false);
+ });
+});
+
+describe('ConditionalFormatting', () => {
+ test('has expected static defaults', () => {
+ expect(ConditionalFormatting.controlType).toBe(
+ 'ConditionalFormattingControl',
+ );
+ expect(ConditionalFormatting.default).toEqual([]);
+ });
+
+ test('.with() applies label and description (not default)', () => {
+ const CF = ConditionalFormatting.with({ label: 'Format' });
+ expect(CF.label).toBe('Format');
+ });
+
+ test('isConditionalFormattingArg type guard', () => {
+ expect(isConditionalFormattingArg(ConditionalFormatting)).toBe(true);
+ expect(isConditionalFormattingArg(Select)).toBe(false);
+ });
+});
+
+describe('Slider', () => {
+ test('has expected float-friendly defaults', () => {
+ expect(Slider.controlType).toBe('SliderControl');
+ expect(Slider.default).toBe(0);
+ expect(Slider.min).toBe(0);
+ expect(Slider.max).toBe(1);
+ expect(Slider.step).toBe(0.1);
+ });
+
+ test('.with() applies all numeric fields', () => {
+ const S = Slider.with({
+ label: 'Opacity',
+ default: 0.8,
+ min: 0,
+ max: 1,
+ step: 0.05,
+ });
+ expect(S.label).toBe('Opacity');
+ expect(S.default).toBe(0.8);
+ expect(S.step).toBe(0.05);
+ });
+
+ test('isSliderArg type guard requires float step', () => {
+ expect(isSliderArg(Slider)).toBe(true);
+ // Int is also SliderControl + has step but step is integer-valued — still
+ // numeric so the guard recognizes it (current behavior); document it.
+ expect(isSliderArg(Int)).toBe(true);
+ expect(isSliderArg(Checkbox)).toBe(false);
+ });
+});
+
+describe('Bounds', () => {
+ test('has expected static defaults', () => {
+ expect(Bounds.controlType).toBe('BoundsControl');
+ expect(Bounds.default).toEqual([null, null]);
+ });
+
+ test('.with() applies default', () => {
+ const B = Bounds.with({ label: 'Range', default: [0, 100] });
+ expect(B.label).toBe('Range');
+ expect(B.default).toEqual([0, 100]);
+ });
+
+ test('isBoundsArg type guard', () => {
+ expect(isBoundsArg(Bounds)).toBe(true);
+ expect(isBoundsArg(Int)).toBe(false);
+ });
+});
+
+describe('ColorPicker', () => {
+ test('has expected static defaults', () => {
+ expect(ColorPicker.controlType).toBe('ColorPickerControl');
+ expect(ColorPicker.default).toEqual({ r: 0, g: 0, b: 0, a: 1 });
+ });
+
+ test('.with() applies default', () => {
+ const CP = ColorPicker.with({
+ label: 'Pick',
+ default: { r: 255, g: 0, b: 0, a: 0.5 },
+ });
+ expect(CP.label).toBe('Pick');
+ expect(CP.default).toEqual({ r: 255, g: 0, b: 0, a: 0.5 });
+ });
+
+ test('isColorPickerArg distinguishes from Color (string)', () => {
+ expect(isColorPickerArg(ColorPicker)).toBe(true);
+ expect(isColorPickerArg(Color)).toBe(false);
+ });
+});
+
+describe('RadioButton', () => {
+ const RADIO_OPTIONS = [
+ { label: 'Yes', value: true },
+ { label: 'No', value: false },
+ ];
+
+ test('has expected static defaults', () => {
+ expect(RadioButton.controlType).toBe('RadioButtonControl');
+ expect(RadioButton.default).toBe('');
+ expect(RadioButton.options).toEqual([]);
+ });
+
+ test('.with() applies all fields', () => {
+ const RB = RadioButton.with({
+ label: 'Toggle',
+ default: true,
+ options: RADIO_OPTIONS,
+ });
+ expect(RB.label).toBe('Toggle');
+ expect(RB.default).toBe(true);
+ expect(RB.options).toEqual(RADIO_OPTIONS);
+ });
+
+ test('isRadioButtonArg type guard', () => {
+ expect(isRadioButtonArg(RadioButton)).toBe(true);
+ expect(isRadioButtonArg(Select)).toBe(false);
+ });
+});
+
+describe('Argument inheritance via .with()', () => {
+ test('chained .with() calls compose overrides', () => {
+ const Base = Select.with({
+ label: 'Pick one',
+ options: [{ label: 'A', value: 'a' }],
+ });
+ const Tighter = Base.with({ label: 'Pick exactly one' });
+ expect(Tighter.label).toBe('Pick exactly one');
+ expect(Tighter.options).toEqual([{ label: 'A', value: 'a' }]);
+ });
+
+ test('original class is unmodified after .with()', () => {
+ const before = Metric.multi;
+ Metric.with({ multi: !before });
+ expect(Metric.multi).toBe(before);
+ });
+});
diff --git a/superset-frontend/packages/superset-ui-glyph-core/test/crossFilter.test.ts b/superset-frontend/packages/superset-ui-glyph-core/test/crossFilter.test.ts
new file mode 100644
index 00000000000..833d8f0ae36
--- /dev/null
+++ b/superset-frontend/packages/superset-ui-glyph-core/test/crossFilter.test.ts
@@ -0,0 +1,212 @@
+/**
+ * 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 type { ChartProps, FilterState } from '@superset-ui/core';
+import {
+ createLabelMap,
+ createSelectedValuesMap,
+ extractCrossFilterProps,
+ isDataPointFiltered,
+} from '@superset-ui/glyph-core';
+
+describe('createSelectedValuesMap', () => {
+ test('returns empty object when filterState is undefined', () => {
+ expect(createSelectedValuesMap(undefined, ['a', 'b'])).toEqual({});
+ });
+
+ test('returns empty object when selectedValues is undefined', () => {
+ expect(
+ createSelectedValuesMap({} as FilterState, ['a', 'b']),
+ ).toEqual({});
+ });
+
+ test('returns empty object when selectedValues is empty', () => {
+ expect(
+ createSelectedValuesMap(
+ { selectedValues: [] } as unknown as FilterState,
+ ['a', 'b'],
+ ),
+ ).toEqual({});
+ });
+
+ test('maps selected value to its index in seriesNames', () => {
+ const result = createSelectedValuesMap(
+ { selectedValues: ['b'] } as unknown as FilterState,
+ ['a', 'b', 'c'],
+ );
+ expect(result).toEqual({ 1: 'b' });
+ });
+
+ test('maps multiple selected values to their indices', () => {
+ const result = createSelectedValuesMap(
+ { selectedValues: ['a', 'c'] } as unknown as FilterState,
+ ['a', 'b', 'c'],
+ );
+ expect(result).toEqual({ 0: 'a', 2: 'c' });
+ });
+
+ test('ignores selected values not in seriesNames', () => {
+ const result = createSelectedValuesMap(
+ { selectedValues: ['x', 'a'] } as unknown as FilterState,
+ ['a', 'b', 'c'],
+ );
+ expect(result).toEqual({ 0: 'a' });
+ });
+});
+
+describe('isDataPointFiltered', () => {
+ test('returns false when no filterState', () => {
+ expect(isDataPointFiltered(undefined, 'a')).toBe(false);
+ });
+
+ test('returns false when selectedValues is empty', () => {
+ expect(
+ isDataPointFiltered(
+ { selectedValues: [] } as unknown as FilterState,
+ 'a',
+ ),
+ ).toBe(false);
+ });
+
+ test('returns false when name is in selectedValues', () => {
+ expect(
+ isDataPointFiltered(
+ { selectedValues: ['a', 'b'] } as unknown as FilterState,
+ 'a',
+ ),
+ ).toBe(false);
+ });
+
+ test('returns true when name is NOT in non-empty selectedValues', () => {
+ expect(
+ isDataPointFiltered(
+ { selectedValues: ['a', 'b'] } as unknown as FilterState,
+ 'c',
+ ),
+ ).toBe(true);
+ });
+});
+
+describe('createLabelMap', () => {
+ test('returns empty object for empty data', () => {
+ expect(createLabelMap([], ['col1'], () => 'label')).toEqual({});
+ });
+
+ test('maps each record to its label and groupby column values', () => {
+ const data = [
+ { country: 'USA', region: 'North' },
+ { country: 'Brazil', region: 'South' },
+ ];
+ const result = createLabelMap(
+ data,
+ ['country', 'region'],
+ d => d.country as string,
+ );
+ expect(result).toEqual({
+ USA: ['USA', 'North'],
+ Brazil: ['Brazil', 'South'],
+ });
+ });
+
+ test('last record wins when extractLabel collides', () => {
+ const data = [
+ { name: 'X', value: 1 },
+ { name: 'X', value: 2 },
+ ];
+ const result = createLabelMap(data, ['value'], d => d.name as string);
+ // collision: later entry overwrites
+ expect(result).toEqual({ X: [2] });
+ });
+
+ test('groupbyLabels controls the columns extracted, not the label', () => {
+ const data = [{ a: 1, b: 2, c: 3 }];
+ const result = createLabelMap(data, ['c'], () => 'only-key');
+ expect(result).toEqual({ 'only-key': [3] });
+ });
+});
+
+describe('extractCrossFilterProps', () => {
+ const baseChartProps = {
+ hooks: { setDataMask: jest.fn(), onContextMenu: jest.fn() },
+ filterState: {
+ selectedValues: ['USA'],
+ } as unknown as FilterState,
+ emitCrossFilters: true,
+ formData: { viz_type: 'test' },
+ } as unknown as ChartProps;
+
+ test('returns all expected fields', () => {
+ const result = extractCrossFilterProps(
+ baseChartProps,
+ ['country'],
+ { USA: ['USA'] },
+ ['USA', 'Brazil'],
+ );
+ expect(result.groupby).toEqual(['country']);
+ expect(result.labelMap).toEqual({ USA: ['USA'] });
+ expect(result.selectedValues).toEqual({ 0: 'USA' });
+ expect(result.emitCrossFilters).toBe(true);
+ expect(result.setDataMask).toBe(baseChartProps.hooks!.setDataMask);
+ expect(result.onContextMenu).toBe(baseChartProps.hooks!.onContextMenu);
+ });
+
+ test('coltypeMapping pass-through when provided', () => {
+ const result = extractCrossFilterProps(
+ baseChartProps,
+ ['country'],
+ {},
+ [],
+ { country: 1 },
+ );
+ expect(result.coltypeMapping).toEqual({ country: 1 });
+ });
+
+ test('defaults setDataMask to a no-op when hooks omits it', () => {
+ const chartProps = {
+ ...baseChartProps,
+ hooks: {},
+ } as unknown as ChartProps;
+ const result = extractCrossFilterProps(chartProps, [], {}, []);
+ expect(typeof result.setDataMask).toBe('function');
+ // No throw when invoked
+ expect(() =>
+ result.setDataMask({ filterState: {} } as unknown as Parameters<
+ typeof result.setDataMask
+ >[0]),
+ ).not.toThrow();
+ });
+
+ test('formData is included in the returned shape (for context menu formatting)', () => {
+ const result = extractCrossFilterProps(
+ baseChartProps,
+ ['country'],
+ {},
+ [],
+ ) as ReturnType<typeof extractCrossFilterProps> & { formData: unknown };
+ expect(result.formData).toEqual({ viz_type: 'test' });
+ });
+
+ test('selectedValues is empty when filterState has none', () => {
+ const chartProps = {
+ ...baseChartProps,
+ filterState: {} as FilterState,
+ } as unknown as ChartProps;
+ const result = extractCrossFilterProps(chartProps, [], {}, ['x']);
+ expect(result.selectedValues).toEqual({});
+ });
+});
diff --git a/superset-frontend/packages/superset-ui-glyph-core/test/defineChart.test.tsx b/superset-frontend/packages/superset-ui-glyph-core/test/defineChart.test.tsx
new file mode 100644
index 00000000000..57e0ff7e169
--- /dev/null
+++ b/superset-frontend/packages/superset-ui-glyph-core/test/defineChart.test.tsx
@@ -0,0 +1,563 @@
+/**
+ * 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 {
+ Behavior,
+ ChartLabel,
+ ChartMetadata,
+ ChartPlugin,
+} from '@superset-ui/core';
+import {
+ Checkbox,
+ defineChart,
+ Dimension,
+ evaluateGlyphCondition,
+ getArgVisibleWhen,
+ Metric,
+ resolveArgClass,
+ Select,
+ Text,
+} from '@superset-ui/glyph-core';
+
+// Helper: instantiate a plugin and reach its controlPanel config.
+function instantiate(PluginClass: ReturnType<typeof defineChart>) {
+ const plugin = new PluginClass();
+ // ChartPlugin internals expose the panel under .controlPanel
+ // (set via super({ controlPanel }) in defineChart's GlyphChartPlugin).
+ return {
+ plugin,
+ controlPanel: (plugin as unknown as { controlPanel: Record<string, unknown> })
+ .controlPanel,
+ metadata: (plugin as unknown as { metadata: ChartMetadata }).metadata,
+ };
+}
+
+const MIN_THUMBNAIL = 'thumb.png';
+
+describe('resolveArgClass', () => {
+ test('returns the bare class form unchanged', () => {
+ expect(resolveArgClass(Metric)).toBe(Metric);
+ });
+
+ test('unwraps the { arg, visibleWhen } object form', () => {
+ const M = Metric.with({ label: 'Sales' });
+ const argDef = { arg: M, visibleWhen: { show: true } };
+ expect(resolveArgClass(argDef)).toBe(M);
+ });
+});
+
+describe('getArgVisibleWhen', () => {
+ test('returns undefined for bare class form', () => {
+ expect(getArgVisibleWhen(Metric)).toBeUndefined();
+ });
+
+ test('returns the condition for object form', () => {
+ const argDef = { arg: Metric, visibleWhen: { show: true } };
+ expect(getArgVisibleWhen(argDef)).toEqual({ show: true });
+ });
+
+ test('returns undefined when object form has no visibleWhen', () => {
+ expect(getArgVisibleWhen({ arg: Metric })).toBeUndefined();
+ });
+});
+
+describe('evaluateGlyphCondition', () => {
+ test('returns true for empty condition', () => {
+ expect(evaluateGlyphCondition({}, { foo: 1 })).toBe(true);
+ });
+
+ test('returns true when equality check matches', () => {
+ expect(evaluateGlyphCondition({ show: true }, { show: true })).toBe(true);
+ });
+
+ test('returns false when equality check fails', () => {
+ expect(evaluateGlyphCondition({ show: true }, { show: false })).toBe(false);
+ });
+
+ test('handles missing formData keys as undefined', () => {
+ expect(evaluateGlyphCondition({ show: true }, {})).toBe(false);
+ });
+
+ test('supports function-valued conditions', () => {
+ const cond = { subtitle: (val: unknown) => !!val };
+ expect(evaluateGlyphCondition(cond, { subtitle: 'hi' })).toBe(true);
+ expect(evaluateGlyphCondition(cond, { subtitle: '' })).toBe(false);
+ });
+
+ test('requires all keys in the condition to pass (AND semantics)', () => {
+ const cond = { a: true, b: 'x' };
+ expect(evaluateGlyphCondition(cond, { a: true, b: 'x' })).toBe(true);
+ expect(evaluateGlyphCondition(cond, { a: true, b: 'y' })).toBe(false);
+ expect(evaluateGlyphCondition(cond, { a: false, b: 'x' })).toBe(false);
+ });
+});
+
+describe('defineChart - basic plugin construction', () => {
+ test('returns a ChartPlugin subclass', () => {
+ const Plugin = defineChart({
+ metadata: { name: 'Test', thumbnail: MIN_THUMBNAIL },
+ arguments: {},
+ transform: () => ({}),
+ render: () => null as unknown as React.ReactElement,
+ });
+
+ const p = new Plugin();
+ expect(p).toBeInstanceOf(ChartPlugin);
+ });
+
+ test('plugin metadata is a ChartMetadata instance with required fields', () => {
+ const Plugin = defineChart({
+ metadata: {
+ name: 'Test',
+ description: 'A test chart',
+ category: 'Charts',
+ tags: ['test'],
+ thumbnail: MIN_THUMBNAIL,
+ },
+ arguments: {},
+ transform: () => ({}),
+ render: () => null as unknown as React.ReactElement,
+ });
+
+ const { metadata } = instantiate(Plugin);
+ expect(metadata).toBeInstanceOf(ChartMetadata);
+ expect(metadata.name).toBe('Test');
+ expect(metadata.description).toBe('A test chart');
+ expect(metadata.category).toBe('Charts');
+ expect(metadata.tags).toEqual(['test']);
+ expect(metadata.thumbnail).toBe(MIN_THUMBNAIL);
+ });
+
+ test('metadata defaults Behavior.InteractiveChart when omitted', () => {
+ const Plugin = defineChart({
+ metadata: { name: 'Test', thumbnail: MIN_THUMBNAIL },
+ arguments: {},
+ transform: () => ({}),
+ render: () => null as unknown as React.ReactElement,
+ });
+ const { metadata } = instantiate(Plugin);
+ expect(metadata.behaviors).toContain(Behavior.InteractiveChart);
+ });
+
+ test('metadata behaviors override the default when provided', () => {
+ const Plugin = defineChart({
+ metadata: {
+ name: 'Test',
+ thumbnail: MIN_THUMBNAIL,
+ behaviors: [Behavior.InteractiveChart, Behavior.DrillToDetail],
+ },
+ arguments: {},
+ transform: () => ({}),
+ render: () => null as unknown as React.ReactElement,
+ });
+ const { metadata } = instantiate(Plugin);
+ expect(metadata.behaviors).toEqual([
+ Behavior.InteractiveChart,
+ Behavior.DrillToDetail,
+ ]);
+ });
+
+ test('passes label, canBeAnnotationTypes, useLegacyApi, supportedAnnotationTypes through', () => {
+ const Plugin = defineChart({
+ metadata: {
+ name: 'Test',
+ thumbnail: MIN_THUMBNAIL,
+ label: ChartLabel.Deprecated,
+ canBeAnnotationTypes: ['EVENT', 'INTERVAL'],
+ useLegacyApi: true,
+ supportedAnnotationTypes: ['FORMULA'],
+ credits: ['https://example.com'],
+ },
+ arguments: {},
+ transform: () => ({}),
+ render: () => null as unknown as React.ReactElement,
+ });
+ const { metadata } = instantiate(Plugin);
+ expect(metadata.label).toBe(ChartLabel.Deprecated);
+ expect(metadata.canBeAnnotationTypes).toEqual(['EVENT', 'INTERVAL']);
+ expect(metadata.useLegacyApi).toBe(true);
+ expect(metadata.supportedAnnotationTypes).toEqual(['FORMULA']);
+ expect(metadata.credits).toEqual(['https://example.com']);
+ });
+
+ test('exampleGallery + thumbnailDark are preserved', () => {
+ const Plugin = defineChart({
+ metadata: {
+ name: 'Test',
+ thumbnail: MIN_THUMBNAIL,
+ thumbnailDark: 'thumb-dark.png',
+ exampleGallery: [{ url: 'a.png', urlDark: 'a-dark.png' }],
+ },
+ arguments: {},
+ transform: () => ({}),
+ render: () => null as unknown as React.ReactElement,
+ });
+ const { metadata } = instantiate(Plugin);
+ expect(metadata.thumbnailDark).toBe('thumb-dark.png');
+ expect(metadata.exampleGallery).toEqual([
+ { url: 'a.png', urlDark: 'a-dark.png' },
+ ]);
+ });
+});
+
+describe('defineChart - controlPanel generation from arguments', () => {
+ test('Query section is auto-generated from Metric/Dimension arguments', () => {
+ const Plugin = defineChart({
+ metadata: { name: 'Test', thumbnail: MIN_THUMBNAIL },
+ arguments: {
+ metric: Metric,
+ groupby: Dimension,
+ },
+ transform: () => ({}),
+ render: () => null as unknown as React.ReactElement,
+ });
+ const { controlPanel } = instantiate(Plugin);
+ const sections = controlPanel.controlPanelSections as Array<{
+ label?: string;
+ }>;
+ // Query section should be auto-generated
+ expect(sections.some(s => s?.label === 'Query')).toBe(true);
+ });
+
+ test('suppressQuerySection: true skips the auto Query section', () => {
+ const Plugin = defineChart({
+ metadata: { name: 'Test', thumbnail: MIN_THUMBNAIL },
+ arguments: {
+ metric: Metric,
+ },
+ suppressQuerySection: true,
+ transform: () => ({}),
+ render: () => null as unknown as React.ReactElement,
+ });
+ const { controlPanel } = instantiate(Plugin);
+ const sections = controlPanel.controlPanelSections as Array<{
+ label?: string;
+ }>;
+ // The auto-generated Query section is suppressed.
+ // (Charts using suppressQuerySection typically provide their own via
+ // prependSections — see legacy nvd3 / deckgl consolidations.)
+ const autoQuery = sections.find(s => s?.label === 'Query');
+ expect(autoQuery).toBeUndefined();
+ });
+
+ test('Chart Options section is generated when there are non-data args', () => {
+ const Plugin = defineChart({
+ metadata: { name: 'Test', thumbnail: MIN_THUMBNAIL },
+ arguments: {
+ metric: Metric,
+ showLegend: Checkbox.with({ label: 'Show legend', default: true }),
+ },
+ transform: () => ({}),
+ render: () => null as unknown as React.ReactElement,
+ });
+ const { controlPanel } = instantiate(Plugin);
+ const sections = controlPanel.controlPanelSections as Array<{
+ label?: string;
+ }>;
+ expect(sections.some(s => s?.label === 'Chart Options')).toBe(true);
+ });
+
+ test('Chart Options section is hidden when there are no customize args', () => {
+ const Plugin = defineChart({
+ metadata: { name: 'Test', thumbnail: MIN_THUMBNAIL },
+ arguments: {
+ metric: Metric,
+ groupby: Dimension,
+ },
+ transform: () => ({}),
+ render: () => null as unknown as React.ReactElement,
+ });
+ const { controlPanel } = instantiate(Plugin);
+ const sections = controlPanel.controlPanelSections as Array<{
+ label?: string;
+ }>;
+ // No Customize-tab content → Chart Options auto-hides.
+ expect(sections.some(s => s?.label === 'Chart Options')).toBe(false);
+ });
+});
+
+describe('defineChart - prependSections / middleSections / additionalSections', () => {
+ test('prependSections appears before the auto Query section', () => {
+ const TIME_SECTION = {
+ label: 'Time',
+ controlSetRows: [],
+ };
+ const Plugin = defineChart({
+ metadata: { name: 'Test', thumbnail: MIN_THUMBNAIL },
+ arguments: { metric: Metric },
+ prependSections: [TIME_SECTION],
+ transform: () => ({}),
+ render: () => null as unknown as React.ReactElement,
+ });
+ const { controlPanel } = instantiate(Plugin);
+ const sections = controlPanel.controlPanelSections as Array<{
+ label?: string;
+ }>;
+ const timeIdx = sections.findIndex(s => s?.label === 'Time');
+ const queryIdx = sections.findIndex(s => s?.label === 'Query');
+ expect(timeIdx).toBeGreaterThanOrEqual(0);
+ expect(queryIdx).toBeGreaterThan(timeIdx);
+ });
+
+ test('additionalSections appears after Chart Options', () => {
+ const TIME_COMP = {
+ label: 'Time Comparison',
+ controlSetRows: [],
+ };
+ const Plugin = defineChart({
+ metadata: { name: 'Test', thumbnail: MIN_THUMBNAIL },
+ arguments: {
+ metric: Metric,
+ showLegend: Checkbox.with({ label: 'Show', default: true }),
+ },
+ additionalSections: [TIME_COMP],
+ transform: () => ({}),
+ render: () => null as unknown as React.ReactElement,
+ });
+ const { controlPanel } = instantiate(Plugin);
+ const sections = controlPanel.controlPanelSections as Array<{
+ label?: string;
+ }>;
+ const chartOptsIdx = sections.findIndex(s => s?.label === 'Chart Options');
+ const timeCompIdx = sections.findIndex(s => s?.label === 'Time Comparison');
+ expect(chartOptsIdx).toBeGreaterThanOrEqual(0);
+ expect(timeCompIdx).toBeGreaterThan(chartOptsIdx);
+ });
+
+ test('middleSections appears between Query and Chart Options', () => {
+ const MIDDLE = {
+ label: 'Middle',
+ controlSetRows: [],
+ };
+ const Plugin = defineChart({
+ metadata: { name: 'Test', thumbnail: MIN_THUMBNAIL },
+ arguments: {
+ metric: Metric,
+ showLegend: Checkbox.with({ label: 'Show', default: true }),
+ },
+ middleSections: [MIDDLE],
+ transform: () => ({}),
+ render: () => null as unknown as React.ReactElement,
+ });
+ const { controlPanel } = instantiate(Plugin);
+ const sections = controlPanel.controlPanelSections as Array<{
+ label?: string;
+ }>;
+ const queryIdx = sections.findIndex(s => s?.label === 'Query');
+ const middleIdx = sections.findIndex(s => s?.label === 'Middle');
+ const chartOptsIdx = sections.findIndex(s => s?.label === 'Chart Options');
+ expect(queryIdx).toBeLessThan(middleIdx);
+ expect(middleIdx).toBeLessThan(chartOptsIdx);
+ });
+
+ test('chartOptionsTabOverride sets tabOverride on the generated section', () => {
+ const Plugin = defineChart({
+ metadata: { name: 'Test', thumbnail: MIN_THUMBNAIL },
+ arguments: {
+ showLegend: Checkbox.with({ label: 'Show', default: true }),
+ },
+ chartOptionsTabOverride: 'data',
+ transform: () => ({}),
+ render: () => null as unknown as React.ReactElement,
+ });
+ const { controlPanel } = instantiate(Plugin);
+ const sections = controlPanel.controlPanelSections as Array<{
+ label?: string;
+ tabOverride?: string;
+ }>;
+ const chartOpts = sections.find(s => s?.label === 'Chart Options');
+ expect(chartOpts?.tabOverride).toBe('data');
+ });
+});
+
+describe('defineChart - overrides + formDataOverrides + onInit', () => {
+ test('additionalControlOverrides land on controlPanel.controlOverrides', () => {
+ const Plugin = defineChart({
+ metadata: { name: 'Test', thumbnail: MIN_THUMBNAIL },
+ arguments: { metric: Metric },
+ additionalControlOverrides: {
+ size: { label: 'Custom Size Label' },
+ },
+ transform: () => ({}),
+ render: () => null as unknown as React.ReactElement,
+ });
+ const { controlPanel } = instantiate(Plugin);
+ expect(
+ (controlPanel.controlOverrides as Record<string, unknown>)?.size,
+ ).toEqual({ label: 'Custom Size Label' });
+ });
+
+ test('controlOverrides + additionalControlOverrides merge', () => {
+ const Plugin = defineChart({
+ metadata: { name: 'Test', thumbnail: MIN_THUMBNAIL },
+ arguments: { metric: Metric },
+ controlOverrides: {
+ a: { label: 'A' },
+ },
+ additionalControlOverrides: {
+ b: { label: 'B' },
+ },
+ transform: () => ({}),
+ render: () => null as unknown as React.ReactElement,
+ });
+ const { controlPanel } = instantiate(Plugin);
+ const merged = controlPanel.controlOverrides as Record<string, unknown>;
+ expect(merged.a).toEqual({ label: 'A' });
+ expect(merged.b).toEqual({ label: 'B' });
+ });
+
+ test('formDataOverrides is preserved on controlPanel', () => {
+ const fdo = (formData: Record<string, unknown>) => ({
+ ...formData,
+ custom: 'extra',
+ });
+ const Plugin = defineChart({
+ metadata: { name: 'Test', thumbnail: MIN_THUMBNAIL },
+ arguments: {},
+ formDataOverrides: fdo,
+ transform: () => ({}),
+ render: () => null as unknown as React.ReactElement,
+ });
+ const { controlPanel } = instantiate(Plugin);
+ expect(controlPanel.formDataOverrides).toBe(fdo);
+ });
+
+ test('onInit is preserved on controlPanel', () => {
+ const onInit = (state: unknown) => state;
+ const Plugin = defineChart({
+ metadata: { name: 'Test', thumbnail: MIN_THUMBNAIL },
+ arguments: {},
+ onInit,
+ transform: () => ({}),
+ render: () => null as unknown as React.ReactElement,
+ });
+ const { controlPanel } = instantiate(Plugin);
+ expect(controlPanel.onInit).toBe(onInit);
+ });
+
+ test('_glyphArgs is attached to the controlPanel for native rendering', () => {
+ const args = {
+ metric: Metric,
+ showLegend: Checkbox.with({ label: 'Show', default: true }),
+ };
+ const Plugin = defineChart({
+ metadata: { name: 'Test', thumbnail: MIN_THUMBNAIL },
+ arguments: args,
+ transform: () => ({}),
+ render: () => null as unknown as React.ReactElement,
+ });
+ const { controlPanel } = instantiate(Plugin);
+ expect(controlPanel._glyphArgs).toEqual(args);
+ });
+});
+
+describe('defineChart - custom buildQuery / transform', () => {
+ test('custom buildQuery is invoked via the plugin loader', async () => {
+ const customBuildQuery = jest.fn(() => ({ queries: [{ marker: 1 }] }));
+ const Plugin = defineChart({
+ metadata: { name: 'Test', thumbnail: MIN_THUMBNAIL },
+ arguments: {},
+ buildQuery: customBuildQuery as unknown as never,
+ transform: () => ({}),
+ render: () => null as unknown as React.ReactElement,
+ });
+ const p = new Plugin();
+ // ChartPlugin stores it as a sanitized loader
+ const loader = (p as unknown as { loadBuildQuery?: () => Promise<Function> })
+ .loadBuildQuery;
+ expect(loader).toBeDefined();
+ const fn = await (loader as () => Promise<Function>)();
+ fn({ viz_type: 'test', datasource: '1__table' });
+ expect(customBuildQuery).toHaveBeenCalledTimes(1);
+ });
+
+ test('transform receives chartProps and argValues', async () => {
+ const captured: unknown[] = [];
+ const Plugin = defineChart({
+ metadata: { name: 'Test', thumbnail: MIN_THUMBNAIL },
+ arguments: { metric: Metric },
+ transform: (chartProps, argValues) => {
+ captured.push({ chartProps, argValues });
+ return { transformed: true };
+ },
+ render: () => null as unknown as React.ReactElement,
+ });
+ const p = new Plugin();
+ const loader = (
+ p as unknown as { loadTransformProps: () => Promise<Function> }
+ ).loadTransformProps;
+ const transformProps = await loader();
+ transformProps({
+ width: 100,
+ height: 100,
+ formData: { metric: 'count' },
+ queriesData: [{ data: [] }],
+ });
+ expect(captured).toHaveLength(1);
+ expect((captured[0] as { chartProps: unknown }).chartProps).toBeDefined();
+ expect((captured[0] as { argValues: unknown }).argValues).toBeDefined();
+ });
+});
+
+describe('defineChart - Text-only argument behavior', () => {
+ test('a Text-only chart still wires up a working plugin', () => {
+ const Plugin = defineChart({
+ metadata: { name: 'TextOnly', thumbnail: MIN_THUMBNAIL },
+ arguments: {
+ title: Text.with({ label: 'Title', default: 'Hi' }),
+ },
+ transform: () => ({}),
+ render: () => null as unknown as React.ReactElement,
+ });
+ const { controlPanel, metadata } = instantiate(Plugin);
+ expect(metadata.name).toBe('TextOnly');
+ // Customize args present → Chart Options shows up
+ const sections = controlPanel.controlPanelSections as Array<{
+ label?: string;
+ }>;
+ expect(sections.some(s => s?.label === 'Chart Options')).toBe(true);
+ });
+});
+
+describe('defineChart - visibleWhen with object-form ArgDef', () => {
+ test('attaches a visibility derivation to the underlying control', () => {
+ // Build a plugin where one arg is visibleWhen another is true.
+ const Plugin = defineChart({
+ metadata: { name: 'V', thumbnail: MIN_THUMBNAIL },
+ arguments: {
+ showLegend: Checkbox.with({ label: 'Show legend', default: true }),
+ legendPosition: {
+ arg: Select.with({
+ label: 'Position',
+ default: 'right',
+ options: [{ label: 'R', value: 'right' }],
+ }),
+ visibleWhen: { showLegend: true },
+ },
+ },
+ transform: () => ({}),
+ render: () => null as unknown as React.ReactElement,
+ });
+ const { controlPanel } = instantiate(Plugin);
+ expect(controlPanel._glyphArgs).toBeDefined();
+ const glyphArgs = controlPanel._glyphArgs as Record<string, unknown>;
+ // The visibleWhen is preserved on the glyph args
+ const lp = glyphArgs.legendPosition as { visibleWhen?: unknown };
+ expect(lp.visibleWhen).toEqual({ showLegend: true });
+ });
+});
diff --git a/superset-frontend/packages/superset-ui-glyph-core/test/generators.test.ts b/superset-frontend/packages/superset-ui-glyph-core/test/generators.test.ts
new file mode 100644
index 00000000000..a22458c3cf4
--- /dev/null
+++ b/superset-frontend/packages/superset-ui-glyph-core/test/generators.test.ts
@@ -0,0 +1,401 @@
+/**
+ * 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 type { ChartProps } from '@superset-ui/core';
+import {
+ Checkbox,
+ Color,
+ createGlyphPlugin,
+ Dimension,
+ generateControlPanel,
+ generateTransformProps,
+ getControlConfig,
+ Int,
+ Metric,
+ Select,
+ Temporal,
+ Text,
+} from '@superset-ui/glyph-core';
+import type { GlyphArguments } from '@superset-ui/glyph-core/generators';
+
+describe('getControlConfig - per argument type', () => {
+ test('Select → SelectControl with options and clearable=false', () => {
+ const S = Select.with({
+ label: 'Choose',
+ default: 'a',
+ options: [{ label: 'A', value: 'a' }],
+ });
+ const cfg = getControlConfig(S, 'myParam');
+ expect(cfg.type).toBe('SelectControl');
+ expect(cfg.label).toBe('Choose');
+ expect(cfg.default).toBe('a');
+ expect(cfg.options).toEqual([{ label: 'A', value: 'a' }]);
+ expect(cfg.clearable).toBe(false);
+ expect(cfg.renderTrigger).toBe(true);
+ });
+
+ test('Checkbox → CheckboxControl with default', () => {
+ const C = Checkbox.with({ label: 'Show', default: true });
+ const cfg = getControlConfig(C, 'show');
+ expect(cfg.type).toBe('CheckboxControl');
+ expect(cfg.label).toBe('Show');
+ expect(cfg.default).toBe(true);
+ expect(cfg.renderTrigger).toBe(true);
+ });
+
+ test('Int → SliderControl with min/max/step', () => {
+ const I = Int.with({ label: 'Limit', default: 50, min: 0, max: 1000, step: 5 });
+ const cfg = getControlConfig(I, 'limit');
+ expect(cfg.type).toBe('SliderControl');
+ expect(cfg.label).toBe('Limit');
+ expect(cfg.default).toBe(50);
+ expect(cfg.min).toBe(0);
+ expect(cfg.max).toBe(1000);
+ expect(cfg.step).toBe(5);
+ });
+
+ test('Color (hex) → ColorPickerControl with RGBA default', () => {
+ const C = Color.with({ label: 'Fill', default: '#ff0000' });
+ const cfg = getControlConfig(C, 'fill');
+ expect(cfg.type).toBe('ColorPickerControl');
+ expect(cfg.label).toBe('Fill');
+ expect(cfg.default).toEqual({ r: 255, g: 0, b: 0, a: 1 });
+ });
+
+ test('Text → TextControl with placeholder', () => {
+ const T = Text.with({
+ label: 'Title',
+ default: 'Untitled',
+ placeholder: 'Enter…',
+ });
+ const cfg = getControlConfig(T, 'title');
+ expect(cfg.type).toBe('TextControl');
+ expect(cfg.label).toBe('Title');
+ expect(cfg.default).toBe('Untitled');
+ expect(cfg.placeholder).toBe('Enter…');
+ });
+
+ test('falls back to paramName when label is unset', () => {
+ // Use the raw Text class (label: null on Argument)
+ class Bare extends Text {
+ static override label = null;
+ }
+ const cfg = getControlConfig(Bare, 'fallback_name');
+ expect(cfg.label).toBe('fallback_name');
+ });
+});
+
+describe('generateControlPanel', () => {
+ test('produces Query and Chart Options sections', () => {
+ const args: GlyphArguments = new Map([
+ ['metric', Metric],
+ ['showLegend', Checkbox.with({ label: 'Legend', default: true })],
+ ]);
+ const cp = generateControlPanel(args);
+ const labels = cp.controlPanelSections.map(s =>
+ s && 'label' in s ? s.label : undefined,
+ );
+ expect(labels).toContain('Query');
+ expect(labels).toContain('Chart Options');
+ });
+
+ test('Metric args produce a [metric] row in Query', () => {
+ const args: GlyphArguments = new Map([['m', Metric]]);
+ const cp = generateControlPanel(args);
+ const querySection = cp.controlPanelSections.find(
+ s => s && 'label' in s && s.label === 'Query',
+ );
+ expect(querySection).toBeDefined();
+ const rows = (querySection as { controlSetRows: unknown[][] }).controlSetRows;
+ expect(rows).toContainEqual(['metric']);
+ });
+
+ test('Dimension args produce a [groupby] row in Query', () => {
+ const args: GlyphArguments = new Map([['d', Dimension]]);
+ const cp = generateControlPanel(args);
+ const querySection = cp.controlPanelSections.find(
+ s => s && 'label' in s && s.label === 'Query',
+ );
+ const rows = (querySection as { controlSetRows: unknown[][] }).controlSetRows;
+ expect(rows).toContainEqual(['groupby']);
+ });
+
+ test('Temporal args produce [x_axis] and [time_grain_sqla] rows in Query', () => {
+ const args: GlyphArguments = new Map([['t', Temporal]]);
+ const cp = generateControlPanel(args);
+ const querySection = cp.controlPanelSections.find(
+ s => s && 'label' in s && s.label === 'Query',
+ );
+ const rows = (querySection as { controlSetRows: unknown[][] }).controlSetRows;
+ expect(rows).toContainEqual(['x_axis']);
+ expect(rows).toContainEqual(['time_grain_sqla']);
+ });
+
+ test('adhoc_filters is always added to Query', () => {
+ const args: GlyphArguments = new Map();
+ const cp = generateControlPanel(args);
+ const querySection = cp.controlPanelSections.find(
+ s => s && 'label' in s && s.label === 'Query',
+ );
+ const rows = (querySection as { controlSetRows: unknown[][] }).controlSetRows;
+ expect(rows).toContainEqual(['adhoc_filters']);
+ });
+
+ test('Non-data args become controls in Chart Options', () => {
+ const args: GlyphArguments = new Map([
+ ['showLegend', Checkbox.with({ label: 'Legend', default: true })],
+ ]);
+ const cp = generateControlPanel(args);
+ const chartOpts = cp.controlPanelSections.find(
+ s => s && 'label' in s && s.label === 'Chart Options',
+ );
+ const rows = (chartOpts as { controlSetRows: unknown[][] }).controlSetRows;
+ expect(rows).toHaveLength(1);
+ expect(rows[0]).toEqual([
+ {
+ name: 'showLegend',
+ config: expect.objectContaining({ type: 'CheckboxControl' }),
+ },
+ ]);
+ });
+
+ test('GlyphArgConfig with visibility wires onto control', () => {
+ const visibility = jest.fn(() => true);
+ const args: GlyphArguments = new Map([
+ [
+ 'subtitleSize',
+ {
+ arg: Select.with({
+ label: 'Size',
+ default: 'm',
+ options: [{ label: 'M', value: 'm' }],
+ }),
+ visibility,
+ resetOnHide: true,
+ },
+ ],
+ ]);
+ const cp = generateControlPanel(args);
+ const chartOpts = cp.controlPanelSections.find(
+ s => s && 'label' in s && s.label === 'Chart Options',
+ );
+ const row = (chartOpts as { controlSetRows: unknown[][] }).controlSetRows[0];
+ const item = (row as Array<{ config: Record<string, unknown> }>)[0];
+ expect(item.config.visibility).toBe(visibility);
+ expect(item.config.resetOnHide).toBe(true);
+ });
+
+ test('controlOverrides and formDataOverrides options pass through', () => {
+ const fdo = (fd: Record<string, unknown>) => ({ ...fd, x: 1 });
+ const cp = generateControlPanel(new Map(), {
+ controlOverrides: { metric: { label: 'M' } },
+ formDataOverrides: fdo,
+ });
+ expect(cp.controlOverrides).toEqual({ metric: { label: 'M' } });
+ expect(cp.formDataOverrides).toBe(fdo);
+ });
+
+ test('extra queryControls and chartOptionsControls are appended', () => {
+ const args: GlyphArguments = new Map();
+ const cp = generateControlPanel(args, {
+ queryControls: [['custom_filter']] as never,
+ chartOptionsControls: [['custom_chart_opt']] as never,
+ });
+ const querySection = cp.controlPanelSections.find(
+ s => s && 'label' in s && s.label === 'Query',
+ );
+ const queryRows = (querySection as { controlSetRows: unknown[][] })
+ .controlSetRows;
+ expect(queryRows).toContainEqual(['custom_filter']);
+
+ const chartOpts = cp.controlPanelSections.find(
+ s => s && 'label' in s && s.label === 'Chart Options',
+ );
+ const optRows = (chartOpts as { controlSetRows: unknown[][] }).controlSetRows;
+ expect(optRows).toContainEqual(['custom_chart_opt']);
+ });
+});
+
+describe('generateTransformProps', () => {
+ function makeChartProps(formData: Record<string, unknown>): ChartProps {
+ return {
+ width: 400,
+ height: 300,
+ queriesData: [{ data: [] }],
+ formData,
+ } as unknown as ChartProps;
+ }
+
+ test('returns width/height/queriesData passthrough', () => {
+ const transform = generateTransformProps(new Map());
+ const out = transform(makeChartProps({}));
+ expect(out).toMatchObject({ width: 400, height: 300 });
+ });
+
+ test('extracts Select value from formData', () => {
+ const args: GlyphArguments = new Map([
+ [
+ 'size',
+ Select.with({
+ label: 'Size',
+ default: 'm',
+ options: [
+ { label: 'S', value: 's' },
+ { label: 'M', value: 'm' },
+ ],
+ }),
+ ],
+ ]);
+ const transform = generateTransformProps(args);
+ const out = transform(makeChartProps({ size: 's' }));
+ expect((out as { size: unknown }).size).toBe('s');
+ });
+
+ test('Select falls back to default when value missing', () => {
+ const args: GlyphArguments = new Map([
+ ['size', Select.with({ label: 'Size', default: 'm', options: [] })],
+ ]);
+ const transform = generateTransformProps(args);
+ const out = transform(makeChartProps({}));
+ expect((out as { size: unknown }).size).toBe('m');
+ });
+
+ test('Checkbox uses formData value when present', () => {
+ const args: GlyphArguments = new Map([
+ ['flag', Checkbox.with({ label: 'F', default: false })],
+ ]);
+ const transform = generateTransformProps(args);
+ const out = transform(makeChartProps({ flag: true }));
+ expect((out as { flag: unknown }).flag).toBe(true);
+ });
+
+ test('Checkbox falls back to default when value missing', () => {
+ const args: GlyphArguments = new Map([
+ ['flag', Checkbox.with({ label: 'F', default: true })],
+ ]);
+ const transform = generateTransformProps(args);
+ const out = transform(makeChartProps({}));
+ expect((out as { flag: unknown }).flag).toBe(true);
+ });
+
+ test('Color: RGBA in formData → hex string', () => {
+ const args: GlyphArguments = new Map([
+ ['fill', Color.with({ label: 'Fill', default: '#000000' })],
+ ]);
+ const transform = generateTransformProps(args);
+ const out = transform(
+ makeChartProps({ fill: { r: 255, g: 0, b: 0, a: 1 } }),
+ );
+ expect((out as { fill: unknown }).fill).toBe('#ff0000');
+ });
+
+ test('Color: string value in formData passes through', () => {
+ const args: GlyphArguments = new Map([
+ ['fill', Color.with({ label: 'Fill', default: '#000000' })],
+ ]);
+ const transform = generateTransformProps(args);
+ const out = transform(makeChartProps({ fill: '#abcdef' }));
+ expect((out as { fill: unknown }).fill).toBe('#abcdef');
+ });
+
+ test('Color: falls back to class default when value missing', () => {
+ const args: GlyphArguments = new Map([
+ ['fill', Color.with({ label: 'Fill', default: '#112233' })],
+ ]);
+ const transform = generateTransformProps(args);
+ const out = transform(makeChartProps({}));
+ // default is hex string; transform converts the RGBA-formatted default back to hex
+ expect((out as { fill: unknown }).fill).toBe('#112233');
+ });
+
+ test('Int uses default when value missing', () => {
+ const args: GlyphArguments = new Map([
+ ['n', Int.with({ label: 'N', default: 7, min: 0, max: 100 })],
+ ]);
+ const transform = generateTransformProps(args);
+ const out = transform(makeChartProps({}));
+ expect((out as { n: unknown }).n).toBe(7);
+ });
+
+ test('Text uses default when value missing', () => {
+ const args: GlyphArguments = new Map([
+ ['s', Text.with({ label: 'S', default: 'hi' })],
+ ]);
+ const transform = generateTransformProps(args);
+ const out = transform(makeChartProps({}));
+ expect((out as { s: unknown }).s).toBe('hi');
+ });
+
+ test('Metric/Dimension/Temporal args are NOT extracted (handled elsewhere)', () => {
+ const args: GlyphArguments = new Map([
+ ['metric', Metric],
+ ['groupby', Dimension],
+ ['t', Temporal],
+ ]);
+ const transform = generateTransformProps(args);
+ const out = transform(
+ makeChartProps({ metric: 'count', groupby: 'a', t: 'date' }),
+ );
+ expect((out as Record<string, unknown>).metric).toBeUndefined();
+ expect((out as Record<string, unknown>).groupby).toBeUndefined();
+ expect((out as Record<string, unknown>).t).toBeUndefined();
+ });
+
+ test('passthrough option copies named ChartProps fields onto the result', () => {
+ const args: GlyphArguments = new Map();
+ const transform = generateTransformProps(args, {
+ passthrough: ['formData'],
+ });
+ const out = transform(makeChartProps({ marker: 1 })) as Record<
+ string,
+ unknown
+ >;
+ expect(out.formData).toEqual({ marker: 1 });
+ });
+
+ test('custom transform option receives extracted values and chartProps', () => {
+ const args: GlyphArguments = new Map([
+ ['flag', Checkbox.with({ label: 'F', default: false })],
+ ]);
+ const transform = generateTransformProps(args, {
+ transform: (values, chartProps) => ({
+ values,
+ gotChartProps: !!chartProps,
+ }),
+ });
+ const out = transform(makeChartProps({ flag: true })) as {
+ values: { flag: boolean };
+ gotChartProps: boolean;
+ };
+ expect(out.values.flag).toBe(true);
+ expect(out.gotChartProps).toBe(true);
+ });
+});
+
+describe('createGlyphPlugin', () => {
+ test('returns both controlPanel and transformProps', () => {
+ const args: GlyphArguments = new Map([
+ ['metric', Metric],
+ ['show', Checkbox.with({ label: 'S', default: true })],
+ ]);
+ const plugin = createGlyphPlugin(args);
+ expect(plugin.controlPanel).toBeDefined();
+ expect(plugin.controlPanel.controlPanelSections.length).toBe(2);
+ expect(typeof plugin.transformProps).toBe('function');
+ });
+});
diff --git a/superset-frontend/packages/superset-ui-glyph-core/test/presets.test.ts b/superset-frontend/packages/superset-ui-glyph-core/test/presets.test.ts
new file mode 100644
index 00000000000..8c1a3ad897b
--- /dev/null
+++ b/superset-frontend/packages/superset-ui-glyph-core/test/presets.test.ts
@@ -0,0 +1,203 @@
+/**
+ * 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 {
+ Checkbox,
+ CircleShape,
+ DataZoom,
+ ForceTimestampFormatting,
+ HeaderFontSize,
+ isCheckboxArg,
+ isSelectArg,
+ isTextArg,
+ LabelPosition,
+ LabelType,
+ LabelThreshold,
+ LegendOrientation,
+ LegendSort,
+ LegendType,
+ MetricNameFontSize,
+ Select,
+ ShowLabels,
+ ShowLegend,
+ ShowMetricName,
+ ShowTotal,
+ ShowValue,
+ SimpleLabelType,
+ SortByMetric,
+ Subtitle,
+ SubheaderFontSize,
+ Text,
+ ValueLabelType,
+} from '@superset-ui/glyph-core';
+import {
+ FONT_SIZE_OPTIONS_LARGE,
+ FONT_SIZE_OPTIONS_SMALL,
+ LABEL_TYPE_OPTIONS,
+ LEGEND_ORIENTATION_OPTIONS,
+ LEGEND_SORT_OPTIONS,
+ LEGEND_TYPE_OPTIONS,
+ SORT_OPTIONS,
+} from '@superset-ui/glyph-core/presets';
+
+describe('Font-size presets', () => {
+ test('HeaderFontSize is a Select with large font options', () => {
+ expect(isSelectArg(HeaderFontSize)).toBe(true);
+ expect((HeaderFontSize as unknown as typeof Select).options).toBe(
+ FONT_SIZE_OPTIONS_LARGE,
+ );
+ });
+
+ test('SubheaderFontSize is a Select with small font options', () => {
+ expect(isSelectArg(SubheaderFontSize)).toBe(true);
+ expect((SubheaderFontSize as unknown as typeof Select).options).toBe(
+ FONT_SIZE_OPTIONS_SMALL,
+ );
+ });
+
+ test('FONT_SIZE_OPTIONS_LARGE and _SMALL are non-empty option arrays', () => {
+ expect(FONT_SIZE_OPTIONS_LARGE.length).toBeGreaterThan(0);
+ expect(FONT_SIZE_OPTIONS_SMALL.length).toBeGreaterThan(0);
+ expect(FONT_SIZE_OPTIONS_LARGE[0]).toHaveProperty('label');
+ expect(FONT_SIZE_OPTIONS_LARGE[0]).toHaveProperty('value');
+ });
+
+ test('MetricNameFontSize is a Select preset', () => {
+ expect(isSelectArg(MetricNameFontSize)).toBe(true);
+ });
+});
+
+describe('Text presets', () => {
+ test('Subtitle is a Text preset', () => {
+ expect(isTextArg(Subtitle)).toBe(true);
+ expect(Subtitle.prototype).toBeInstanceOf(Text);
+ });
+
+ test('LabelThreshold is a Text preset', () => {
+ expect(isTextArg(LabelThreshold)).toBe(true);
+ });
+});
+
+describe('Checkbox presets', () => {
+ test.each([
+ ['ShowLegend', ShowLegend],
+ ['ShowLabels', ShowLabels],
+ ['ShowValue', ShowValue],
+ ['ShowMetricName', ShowMetricName],
+ ['ShowTotal', ShowTotal],
+ ['SortByMetric', SortByMetric],
+ ['CircleShape', CircleShape],
+ ['DataZoom', DataZoom],
+ ['ForceTimestampFormatting', ForceTimestampFormatting],
+ ])('%s is a Checkbox preset', (_name, preset) => {
+ expect(isCheckboxArg(preset)).toBe(true);
+ expect(preset.prototype).toBeInstanceOf(Checkbox);
+ });
+
+ test('Checkbox presets have a label and a description', () => {
+ [ShowLegend, ShowLabels, ShowValue, ShowMetricName, ShowTotal].forEach(
+ preset => {
+ expect(preset.label).toBeTruthy();
+ expect(preset.description).toBeTruthy();
+ },
+ );
+ });
+});
+
+describe('Legend Select presets', () => {
+ test('LegendType uses LEGEND_TYPE_OPTIONS', () => {
+ expect(isSelectArg(LegendType)).toBe(true);
+ expect((LegendType as unknown as typeof Select).options).toBe(
+ LEGEND_TYPE_OPTIONS,
+ );
+ });
+
+ test('LegendOrientation uses LEGEND_ORIENTATION_OPTIONS', () => {
+ expect(isSelectArg(LegendOrientation)).toBe(true);
+ expect((LegendOrientation as unknown as typeof Select).options).toBe(
+ LEGEND_ORIENTATION_OPTIONS,
+ );
+ });
+
+ test('LegendSort uses LEGEND_SORT_OPTIONS', () => {
+ expect(isSelectArg(LegendSort)).toBe(true);
+ expect((LegendSort as unknown as typeof Select).options).toBe(
+ LEGEND_SORT_OPTIONS,
+ );
+ });
+
+ test('legend option sets are non-empty', () => {
+ expect(LEGEND_TYPE_OPTIONS.length).toBeGreaterThan(0);
+ expect(LEGEND_ORIENTATION_OPTIONS.length).toBeGreaterThan(0);
+ expect(LEGEND_SORT_OPTIONS.length).toBeGreaterThan(0);
+ });
+});
+
+describe('Label / value-label Select presets', () => {
+ test('LabelType is a Select with LABEL_TYPE_OPTIONS', () => {
+ expect(isSelectArg(LabelType)).toBe(true);
+ expect((LabelType as unknown as typeof Select).options).toBe(
+ LABEL_TYPE_OPTIONS,
+ );
+ });
+
+ test('SimpleLabelType is a Select preset', () => {
+ expect(isSelectArg(SimpleLabelType)).toBe(true);
+ });
+
+ test('ValueLabelType is a Select preset', () => {
+ expect(isSelectArg(ValueLabelType)).toBe(true);
+ });
+
+ test('LabelPosition is a Select preset', () => {
+ expect(isSelectArg(LabelPosition)).toBe(true);
+ });
+});
+
+describe('Sort options', () => {
+ test('SORT_OPTIONS is non-empty', () => {
+ expect(SORT_OPTIONS.length).toBeGreaterThan(0);
+ expect(SORT_OPTIONS[0]).toHaveProperty('label');
+ expect(SORT_OPTIONS[0]).toHaveProperty('value');
+ });
+});
+
+describe('Preset extensibility', () => {
+ test('ShowLegend.with() overrides label while keeping the Checkbox shape', () => {
+ const Custom = ShowLegend.with({
+ label: 'Display legend',
+ default: false,
+ });
+ expect(isCheckboxArg(Custom)).toBe(true);
+ expect(Custom.label).toBe('Display legend');
+ expect(Custom.default).toBe(false);
+ });
+
+ test('HeaderFontSize.with() overrides label, default keeps options', () => {
+ const Custom = HeaderFontSize.with({
+ label: 'Title size',
+ default: 0.4,
+ });
+ expect(isSelectArg(Custom)).toBe(true);
+ expect(Custom.label).toBe('Title size');
+ expect(Custom.default).toBe(0.4);
+ expect((Custom as unknown as typeof Select).options).toBe(
+ FONT_SIZE_OPTIONS_LARGE,
+ );
+ });
+});