You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by mi...@apache.org on 2026/10/14 01:18:58 UTC
(superset) branch master updated: feat(semantic-layer): gate Table pagination on row offset support (#44452)
This is an automated email from the ASF dual-hosted git repository.
aminghadersohi pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/superset.git
The following commit(s) were added to refs/heads/master by this push:
new 114d32b12d1 feat(semantic-layer): gate Table pagination on row offset support (#44452)
114d32b12d1 is described below
commit 114d32b12d102f64af4b51594e66b99811342c12
Author: Mike Bridge <mi...@preset.io>
AuthorDate: Tue Oct 13 21:18:51 2026 -0400
feat(semantic-layer): gate Table pagination on row offset support (#44452)
Co-authored-by: Mike Bridge <mi...@ext.preset.io>
---
UPDATING.md | 10 +
.../extensions/contribution-types.md | 30 +-
.../src/superset_core/semantic_layers/view.py | 3 +
superset-core/tests/semantic_layers/test_view.py | 75 ++-
.../superset-ui-chart-controls/src/utils/index.ts | 1 +
.../src/utils/isServerPaginationUnsupported.ts | 70 +++
.../components/modals/EditDatasetModal.ts | 7 +-
.../src/controlPanel.tsx | 50 +-
.../test/buildQuery.test.ts | 23 +
.../test/controlPanel.test.tsx | 364 ++++++++++++++
.../plugin-chart-table/src/controlPanel.tsx | 50 +-
.../plugin-chart-table/test/buildQuery.test.ts | 53 ++
.../plugin-chart-table/test/controlPanel.test.tsx | 546 ++++++++++++++++++++-
.../src/explore/components/Control.test.tsx | 20 +-
.../src/explore/components/ControlHeader.test.tsx | 92 +++-
.../src/explore/components/ControlHeader.tsx | 37 +-
.../components/controls/CheckboxControl.test.tsx | 146 +++++-
.../components/controls/CheckboxControl.tsx | 73 ++-
.../CollectionControl/CollectionControl.test.tsx | 14 +-
superset/translations/messages.pot | 10 +
tests/unit_tests/semantic_layers/mapper_test.py | 54 +-
tests/unit_tests/semantic_layers/models_test.py | 16 +
22 files changed, 1681 insertions(+), 63 deletions(-)
diff --git a/UPDATING.md b/UPDATING.md
index 49dc6244484..ecce7e2f915 100644
--- a/UPDATING.md
+++ b/UPDATING.md
@@ -187,6 +187,16 @@ reattached to a reachable container by layout repair.
loader rejects semantic bundles;
use the chart, dashboard or assets importer instead.
+### Table and AG Grid server pagination for semantic views
+
+Table and AG Grid Table charts backed by semantic views require the optional `ROW_OFFSET`
+capability to enable Server pagination. Missing capability metadata disables
+the control with an explanation; SQL datasets are unchanged. Saved pagination
+settings are not rewritten. Users can explicitly turn off an unsupported
+saved setting; provider errors remain authoritative until that edit.
+Extension providers must use a compatible core version before declaring the
+new capability.
+
### Graph null category colors
Graph charts label SQL `NULL` categories as `<NULL>` and share their colors with
diff --git a/docs/developer_docs/extensions/contribution-types.md b/docs/developer_docs/extensions/contribution-types.md
index e317c248cf6..79b3c699f9b 100644
--- a/docs/developer_docs/extensions/contribution-types.md
+++ b/docs/developer_docs/extensions/contribution-types.md
@@ -323,7 +323,7 @@ key is deliberately **not** sent: because the `@semantic_layer` decorator
prefixes extension IDs, no stable bare key exists to publish, and behavior
keyed off provider identity would not survive that prefixing.
-Explore translates `semantic_view_features` exactly once, in the
+For column pickers, Explore translates `semantic_view_features` exactly once, in the
datasource-to-picker-capabilities adapter
(`superset-frontend/src/explore/components/controls/DndColumnSelectControl/utils/pickerCapabilities.ts`),
into a provider-neutral `ColumnPickerCapabilities` value. That adapter is the
@@ -338,6 +338,34 @@ Custom SQL modes are visible but disabled, so users cannot build an expression
the backend would reject. Unknown feature strings and payloads with no
`semantic_view_features` field are ignored, preserving existing behavior.
+#### Server pagination
+
+A view may declare `SemanticViewFeature.ROW_OFFSET` when it supports
+non-negative row offsets together with a positive finite limit. This does not
+promise offset-without-limit support, stable ordering without a sort, or snapshot
+consistency across pages. Providers remain responsible for validating query
+shapes and must honor offsets or return a clear error, never silently repeat
+the first page.
+
+The Table and AG Grid Table charts read this capability from
+`semantic_view_features`. For a semantic view with missing, empty, or
+unknown-only capabilities, **Server
+pagination** remains visible but disabled with an explanation. Ordinary SQL
+datasets keep their existing controls. Existing saved settings are preserved:
+an unsupported query continues to return the provider's actionable error until
+the author explicitly turns off server pagination and saves the chart. Opening
+a chart or switching datasources does not rewrite pagination settings. A saved
+enabled control offers a **Turn off server pagination** action beside the
+explanation once datasource metadata is available. During a datasource-type
+switch, controls follow the selected form-data datasource type rather than stale
+metadata; capabilities from a different datasource type do not enable pagination.
+
+This is an optional UI capability, not a new permission or a host-wide query
+validator. Direct API callers continue to use provider-local enforcement.
+Providers must deploy against a compatible core version before importing the
+new enum member. Older providers remain valid with an empty feature set; their
+Table pagination controls stay disabled until they explicitly opt in.
+
#### Semantic result containment caching
Superset containment caching is experimental and off by default. A provider must
diff --git a/superset-core/src/superset_core/semantic_layers/view.py b/superset-core/src/superset_core/semantic_layers/view.py
index 85d505e2b48..733acd3bfe7 100644
--- a/superset-core/src/superset_core/semantic_layers/view.py
+++ b/superset-core/src/superset_core/semantic_layers/view.py
@@ -39,6 +39,9 @@ class SemanticViewFeature(enum.Enum):
ADHOC_EXPRESSIONS_IN_ORDERBY = "ADHOC_EXPRESSIONS_IN_ORDERBY"
GROUP_LIMIT = "GROUP_LIMIT"
GROUP_OTHERS = "GROUP_OTHERS"
+ # Non-negative row offsets with a positive finite limit. Providers retain
+ # responsibility for ordering and rejecting unsupported query shapes.
+ ROW_OFFSET = "ROW_OFFSET"
class SemanticView(ABC):
diff --git a/superset-core/tests/semantic_layers/test_view.py b/superset-core/tests/semantic_layers/test_view.py
index abaf03015e2..e535f1a026c 100644
--- a/superset-core/tests/semantic_layers/test_view.py
+++ b/superset-core/tests/semantic_layers/test_view.py
@@ -15,7 +15,80 @@
# specific language governing permissions and limitations
# under the License.
-from superset_core.semantic_layers.view import SemanticView
+import pyarrow as pa
+from superset_core.semantic_layers.types import (
+ Dimension,
+ Filter,
+ Metric,
+ SemanticQuery,
+ SemanticResult,
+)
+from superset_core.semantic_layers.view import SemanticView, SemanticViewFeature
+
+
+class MinimalView(SemanticView):
+ """Implement the required provider interface without optional capabilities."""
+
+ name: str = "Minimal"
+
+ def uid(self) -> str:
+ """Return the provider identity."""
+ return "minimal"
+
+ def get_dimensions(self) -> set[Dimension]:
+ """Return no dimensions."""
+ return set()
+
+ def get_metrics(self) -> set[Metric]:
+ """Return no metrics."""
+ return set()
+
+ def get_values(
+ self, dimension: Dimension, filters: set[Filter] | None = None
+ ) -> SemanticResult:
+ """Return an empty result."""
+ return SemanticResult(requests=[], results=pa.table({}))
+
+ def get_table(self, query: SemanticQuery) -> SemanticResult:
+ """Return an empty result."""
+ return SemanticResult(requests=[], results=pa.table({}))
+
+ def get_row_count(self, query: SemanticQuery) -> SemanticResult:
+ """Return a zero count."""
+ return SemanticResult(requests=[], results=pa.table({"count": [0]}))
+
+ def get_compatible_metrics(
+ self, selected_metrics: set[Metric], selected_dimensions: set[Dimension]
+ ) -> set[Metric]:
+ """Return no compatible metrics."""
+ return set()
+
+ def get_compatible_dimensions(
+ self, selected_metrics: set[Metric], selected_dimensions: set[Dimension]
+ ) -> set[Dimension]:
+ """Return no compatible dimensions."""
+ return set()
+
+
+def test_row_offset_is_optional_for_minimal_provider() -> None:
+ """Adding row-offset support must not require unsupported provider stubs."""
+ view: MinimalView = MinimalView()
+
+ assert view.features == frozenset()
+ assert SemanticViewFeature.ROW_OFFSET not in view.features
+ assert view.uid() == "minimal"
+
+ class OffsetView(MinimalView):
+ """Advertise pagination without changing the required interface."""
+
+ features: frozenset[SemanticViewFeature] = frozenset(
+ {SemanticViewFeature.ROW_OFFSET}
+ )
+
+ offset_view: OffsetView = OffsetView()
+ assert SemanticViewFeature.ROW_OFFSET in offset_view.features
+ assert SemanticViewFeature.ROW_OFFSET.value == "ROW_OFFSET"
+ assert SemanticViewFeature.ROW_OFFSET not in view.features
def test_view_metadata_defaults_are_conservative() -> None:
diff --git a/superset-frontend/packages/superset-ui-chart-controls/src/utils/index.ts b/superset-frontend/packages/superset-ui-chart-controls/src/utils/index.ts
index 0a87a986383..248343d5b45 100644
--- a/superset-frontend/packages/superset-ui-chart-controls/src/utils/index.ts
+++ b/superset-frontend/packages/superset-ui-chart-controls/src/utils/index.ts
@@ -32,4 +32,5 @@ export * from './displayTimeRelatedControls';
export * from './colorControls';
export * from './metricColumnFilter';
export * from './buildSortMetricOrderby';
+export * from './isServerPaginationUnsupported';
export * from './headerGroups';
diff --git a/superset-frontend/packages/superset-ui-chart-controls/src/utils/isServerPaginationUnsupported.ts b/superset-frontend/packages/superset-ui-chart-controls/src/utils/isServerPaginationUnsupported.ts
new file mode 100644
index 00000000000..b5f2b56a4c0
--- /dev/null
+++ b/superset-frontend/packages/superset-ui-chart-controls/src/utils/isServerPaginationUnsupported.ts
@@ -0,0 +1,70 @@
+/**
+ * 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 { DatasourceType } from '@superset-ui/core';
+import type { ControlPanelState } from '../types';
+
+/** SemanticViewFeature value for providers that support row offsets. */
+export const ROW_OFFSET = 'ROW_OFFSET';
+
+/** Match Explore's host identity, or an opaque provider selection. */
+export function hasMatchingDatasourceMetadata({
+ datasource,
+ form_data,
+}: Pick<ControlPanelState, 'datasource' | 'form_data'>): boolean {
+ const selected = form_data.datasource?.match(
+ /^(\d+)__(table|semantic_view)$/,
+ );
+ if (selected) {
+ return (
+ datasource?.id === Number(selected[1]) && datasource.type === selected[2]
+ );
+ }
+ return Boolean(
+ datasource &&
+ 'uid' in datasource &&
+ datasource.uid === form_data.datasource,
+ );
+}
+
+/** Keep semantic pagination disabled until the view declares offset support. */
+export function isServerPaginationUnsupported({
+ datasource,
+ form_data,
+}: ControlPanelState): boolean {
+ const metadataMatchesSelection = hasMatchingDatasourceMetadata({
+ datasource,
+ form_data,
+ });
+ const selectedType = form_data.datasource?.split('__')[1];
+ const datasourceType =
+ metadataMatchesSelection ||
+ (selectedType !== DatasourceType.Table &&
+ selectedType !== DatasourceType.SemanticView)
+ ? datasource?.type
+ : selectedType;
+ const isSemanticView = datasourceType === DatasourceType.SemanticView;
+ const features =
+ datasource &&
+ metadataMatchesSelection &&
+ datasource.type === datasourceType &&
+ 'semantic_view_features' in datasource
+ ? datasource.semantic_view_features
+ : undefined;
+ return Boolean(isSemanticView && !features?.includes(ROW_OFFSET));
+}
diff --git a/superset-frontend/playwright/components/modals/EditDatasetModal.ts b/superset-frontend/playwright/components/modals/EditDatasetModal.ts
index 77e33f1850a..865c45e6698 100644
--- a/superset-frontend/playwright/components/modals/EditDatasetModal.ts
+++ b/superset-frontend/playwright/components/modals/EditDatasetModal.ts
@@ -128,19 +128,18 @@ export class EditDatasetModal extends Modal {
/**
* Gets the description Ace Editor component (Settings tab).
- * The Description button and ace-editor are in the same form item.
+ * The Description label and ace-editor are in the same form item.
*/
private get descriptionEditor(): AceEditor {
// Use tabpanel role with name "Settings" for more reliable lookup
const settingsPanel = this.element.getByRole('tabpanel', {
name: 'Settings',
});
- // Find the form item that contains the Description button
+ // Find the form item that contains the Description label
const descriptionFormItem = settingsPanel
.locator('.ant-form-item')
.filter({
- has: this.page.getByRole('button', {
- name: 'Description',
+ has: this.page.getByText('Description', {
exact: true,
}),
})
diff --git a/superset-frontend/plugins/plugin-chart-ag-grid-table/src/controlPanel.tsx b/superset-frontend/plugins/plugin-chart-ag-grid-table/src/controlPanel.tsx
index cb058717272..af919d8b03a 100644
--- a/superset-frontend/plugins/plugin-chart-ag-grid-table/src/controlPanel.tsx
+++ b/superset-frontend/plugins/plugin-chart-ag-grid-table/src/controlPanel.tsx
@@ -39,6 +39,8 @@ import {
shouldSkipMetricColumn,
isRegularMetric,
isPercentMetric,
+ isServerPaginationUnsupported,
+ hasMatchingDatasourceMetadata,
ConditionalFormattingConfig,
ObjectFormattingEnum,
ColorSchemeEnum,
@@ -387,6 +389,16 @@ const config: ControlPanelConfig = {
'Enable server side pagination of results (experimental feature)',
),
default: false,
+ shouldMapStateToProps: () => true,
+ mapStateToProps: state => ({
+ disabled: isServerPaginationUnsupported(state),
+ disabledReason: hasMatchingDatasourceMetadata(state)
+ ? t('This semantic view does not support server pagination.')
+ : undefined,
+ resetLabel: hasMatchingDatasourceMetadata(state)
+ ? t('Turn off server pagination')
+ : undefined,
+ }),
},
},
],
@@ -399,6 +411,10 @@ const config: ControlPanelConfig = {
label: t('Server Page Length'),
default: 10,
choices: SERVER_PAGE_SIZE_OPTIONS,
+ shouldMapStateToProps: () => true,
+ mapStateToProps: state => ({
+ disabled: isServerPaginationUnsupported(state),
+ }),
description: t('Rows per page, 0 means no pagination'),
visibility: ({ controls }: ControlPanelsContainerProps) =>
Boolean(controls?.server_pagination?.value),
@@ -414,7 +430,17 @@ const config: ControlPanelConfig = {
freeForm: true,
label: t('Row limit'),
clearable: false,
+ shouldMapStateToProps: () => true,
mapStateToProps: state => ({
+ paginationUnsupported: isServerPaginationUnsupported(state),
+ choices: formatSelectOptions(
+ ROW_LIMIT_OPTIONS_TABLE.filter(
+ value =>
+ !isServerPaginationUnsupported(state) ||
+ value <=
+ (state?.common?.conf?.SQL_MAX_ROW || DEFAULT_MAX_ROW),
+ ),
+ ),
maxValue: state?.common?.conf?.TABLE_VIZ_MAX_ROW_SERVER,
server_pagination: state?.form_data?.server_pagination,
maxValueWithoutServerPagination:
@@ -428,12 +454,24 @@ const config: ControlPanelConfig = {
state?.maxValue || DEFAULT_MAX_ROW_TABLE_SERVER,
),
(v, state) =>
- validateServerPagination(
- v,
- state?.server_pagination,
- state?.maxValueWithoutServerPagination || DEFAULT_MAX_ROW,
- state?.maxValue || DEFAULT_MAX_ROW_TABLE_SERVER,
- ),
+ state?.paginationUnsupported && !state?.server_pagination
+ ? validateMaxValue(
+ v,
+ state?.maxValueWithoutServerPagination ||
+ DEFAULT_MAX_ROW,
+ ) &&
+ t(
+ 'Lower the row limit to SQL_MAX_ROW (%s) or less.',
+ state?.maxValueWithoutServerPagination ||
+ DEFAULT_MAX_ROW,
+ )
+ : validateServerPagination(
+ v,
+ state?.server_pagination,
+ state?.maxValueWithoutServerPagination ||
+ DEFAULT_MAX_ROW,
+ state?.maxValue || DEFAULT_MAX_ROW_TABLE_SERVER,
+ ),
],
// Re run the validations when this control value
validationDependencies: ['server_pagination'],
diff --git a/superset-frontend/plugins/plugin-chart-ag-grid-table/test/buildQuery.test.ts b/superset-frontend/plugins/plugin-chart-ag-grid-table/test/buildQuery.test.ts
index 0d9fa62feaa..56f110df630 100644
--- a/superset-frontend/plugins/plugin-chart-ag-grid-table/test/buildQuery.test.ts
+++ b/superset-frontend/plugins/plugin-chart-ag-grid-table/test/buildQuery.test.ts
@@ -28,6 +28,29 @@ const basicFormData: TableChartFormData = {
metrics: ['count'],
};
+test('preserves saved semantic pagination offsets and ordering', () => {
+ const saved: TableChartFormData = Object.freeze({
+ ...basicFormData,
+ datasource: '1__semantic_view',
+ server_pagination: true,
+ server_page_length: 2,
+ });
+ const ownState = Object.freeze({
+ currentPage: 1,
+ pageSize: 2,
+ sortBy: [{ key: 'state', desc: false }],
+ });
+ const { queries } = buildQueryUncached(saved, { ownState });
+ expect(queries[0]).toMatchObject({
+ row_offset: 2,
+ row_limit: 2,
+ orderby: [['state', true]],
+ });
+ expect(queries[1]).toMatchObject({ is_rowcount: true, row_offset: 0 });
+ expect(saved.server_pagination).toBe(true);
+ expect(ownState.currentPage).toBe(1);
+});
+
const createAdhocColumn = (
sqlExpression: string,
label: string,
diff --git a/superset-frontend/plugins/plugin-chart-ag-grid-table/test/controlPanel.test.tsx b/superset-frontend/plugins/plugin-chart-ag-grid-table/test/controlPanel.test.tsx
index 55a3cc2f562..b153eb6b6b1 100644
--- a/superset-frontend/plugins/plugin-chart-ag-grid-table/test/controlPanel.test.tsx
+++ b/superset-frontend/plugins/plugin-chart-ag-grid-table/test/controlPanel.test.tsx
@@ -16,6 +16,9 @@
* specific language governing permissions and limitations
* under the License.
*/
+import { ComponentProps } from 'react';
+import { render, screen } from 'spec/helpers/testing-library';
+import CheckboxControl from 'src/explore/components/controls/CheckboxControl';
import { GenericDataType } from '@apache-superset/core/common';
import { QueryFormData } from '@superset-ui/core';
import {
@@ -43,6 +46,12 @@ const findNamedControl = (name: string): ControlConfig | null => {
return null;
};
+const getPaginationControl = (name: string): ControlConfig => {
+ const control = findNamedControl(name);
+ if (control) return control;
+ throw new Error(`Missing pagination control: ${name}`);
+};
+
const findConditionalFormattingControl = (): ControlConfig | null =>
findNamedControl('conditional_formatting');
@@ -327,3 +336,358 @@ test('metrics control includes non-filterable columns', () => {
]),
);
});
+
+test.each([
+ ['semantic_view', undefined, true],
+ ['semantic_view', [], true],
+ ['semantic_view', ['UNKNOWN'], true],
+ ['semantic_view', ['ROW_OFFSET'], false],
+ ['table', undefined, false],
+])(
+ 'AG Grid pagination gate: %s with %s disables=%s',
+ (type, features, disabled) => {
+ const panel = getPaginationControl('server_pagination');
+ const length = getPaginationControl('server_page_length');
+ const base = createMockExplore(undefined);
+ const state: ControlPanelState = {
+ ...base,
+ datasource: {
+ id: 1,
+ uid: 'provider-view',
+ type,
+ semantic_view_features: features,
+ } as Dataset,
+ form_data: {
+ ...base.form_data,
+ datasource: `1__${type}`,
+ server_pagination: true,
+ },
+ controls: {
+ ...base.controls,
+ server_pagination: { type: 'CheckboxControl', value: true },
+ },
+ };
+
+ expect(
+ panel.shouldMapStateToProps?.(
+ state,
+ state,
+ state.controls.server_pagination,
+ ),
+ ).toBe(true);
+ expect(
+ panel.mapStateToProps?.(state, state.controls.server_pagination),
+ ).toMatchObject({
+ disabled,
+ resetLabel: 'Turn off server pagination',
+ disabledReason: 'This semantic view does not support server pagination.',
+ });
+ expect(
+ length.mapStateToProps?.(state, state.controls.server_page_length),
+ ).toMatchObject({ disabled });
+ render(
+ <CheckboxControl
+ name="server_pagination"
+ value={Boolean(state.controls.server_pagination.value)}
+ {...(panel.mapStateToProps?.(
+ state,
+ state.controls.server_pagination,
+ ) as Partial<ComponentProps<typeof CheckboxControl>>)}
+ />,
+ );
+ expect(screen.getByRole('checkbox')).toBeChecked();
+ expect(screen.getByRole('checkbox').hasAttribute('disabled')).toBe(
+ disabled,
+ );
+ },
+);
+
+test('AG Grid fails closed while semantic datasource metadata loads', () => {
+ const panel = getPaginationControl('server_pagination');
+ const base = createMockExplore(undefined);
+ const state: ControlPanelState = {
+ ...base,
+ datasource: null,
+ form_data: { ...base.form_data, datasource: '1__semantic_view' },
+ };
+ expect(
+ panel.mapStateToProps?.(state, state.controls.server_pagination),
+ ).toMatchObject({
+ disabled: true,
+ resetLabel: undefined,
+ disabledReason: undefined,
+ });
+});
+
+test.each([
+ ['1__semantic_view', '2__semantic_view'],
+ ['cube__orders', 'cube__customers'],
+])(
+ 'withholds pagination advice for stale metadata %s -> %s',
+ (uid, selected) => {
+ const state = createMockExplore(undefined);
+ state.datasource = {
+ ...state.datasource,
+ id: 1,
+ uid,
+ type: 'semantic_view',
+ semantic_view_features: [],
+ } as Dataset;
+ state.form_data.datasource = selected;
+ const panel = getPaginationControl('server_pagination');
+ expect(
+ panel.mapStateToProps?.(state, state.controls.server_pagination),
+ ).toMatchObject({
+ disabled: true,
+ resetLabel: undefined,
+ disabledReason: undefined,
+ });
+ state.datasource = { ...state.datasource, id: 2, uid: selected } as Dataset;
+ expect(
+ panel.mapStateToProps?.(state, state.controls.server_pagination),
+ ).toMatchObject({
+ disabled: true,
+ resetLabel: 'Turn off server pagination',
+ disabledReason: 'This semantic view does not support server pagination.',
+ });
+ },
+);
+
+test.each([true, false])(
+ 'matches Explore id/type independently of provider uid: offset=%s',
+ supportsOffset => {
+ const state = createMockExplore(undefined);
+ state.datasource = {
+ ...state.datasource,
+ id: 42,
+ uid: 'provider-orders',
+ type: 'semantic_view',
+ semantic_view_features: supportsOffset ? ['ROW_OFFSET'] : [],
+ } as Dataset;
+ state.form_data.datasource = '42__semantic_view';
+ const panel = getPaginationControl('server_pagination');
+ expect(
+ panel.mapStateToProps?.(state, state.controls.server_pagination),
+ ).toMatchObject({
+ disabled: !supportsOffset,
+ resetLabel: 'Turn off server pagination',
+ disabledReason: 'This semantic view does not support server pagination.',
+ });
+ state.datasource = {
+ ...state.datasource,
+ id: 43,
+ uid: '42__semantic_view',
+ } as Dataset;
+ expect(
+ panel.mapStateToProps?.(state, state.controls.server_pagination),
+ ).toMatchObject({
+ disabled: true,
+ resetLabel: undefined,
+ disabledReason: undefined,
+ });
+ state.datasource = {
+ ...state.datasource,
+ id: 42,
+ type: 'table',
+ } as Dataset;
+ expect(
+ panel.mapStateToProps?.(state, state.controls.server_pagination),
+ ).toMatchObject({
+ disabled: true,
+ resetLabel: undefined,
+ disabledReason: undefined,
+ });
+ },
+);
+
+test.each([undefined, [], ['ROW_OFFSET']])(
+ 'AG Grid matches opaque provider uid before parsing datasource type: %s',
+ features => {
+ const base = createMockExplore(undefined);
+ const state: ControlPanelState = {
+ ...base,
+ datasource: {
+ ...base.datasource,
+ uid: 'cube__orders',
+ type: 'semantic_view',
+ semantic_view_features: features,
+ } as Dataset,
+ form_data: { ...base.form_data, datasource: 'cube__orders' },
+ };
+ const disabled = !features?.includes('ROW_OFFSET');
+ for (const name of ['server_pagination', 'server_page_length']) {
+ expect(
+ getPaginationControl(name).mapStateToProps?.(
+ state,
+ state.controls[name],
+ ),
+ ).toMatchObject({ disabled });
+ }
+ },
+);
+
+test('ignores stale offset capability when switching opaque semantic UIDs', () => {
+ const state = createMockExplore(undefined);
+ state.datasource = {
+ ...state.datasource,
+ uid: 'cube__orders',
+ type: 'semantic_view',
+ semantic_view_features: ['ROW_OFFSET'],
+ } as Dataset;
+ state.form_data.datasource = 'cube__customers';
+
+ for (const name of ['server_pagination', 'server_page_length']) {
+ expect(
+ getPaginationControl(name).mapStateToProps?.(state, state.controls[name]),
+ ).toMatchObject({ disabled: true });
+ }
+});
+
+test.each(['server_pagination', 'server_page_length'])(
+ 'AG Grid %s ignores stale offset capability from another semantic view',
+ name => {
+ const base = createMockExplore(undefined);
+ const state: ControlPanelState = {
+ ...base,
+ datasource: {
+ ...base.datasource,
+ uid: '1__semantic_view',
+ type: 'semantic_view',
+ semantic_view_features: ['ROW_OFFSET'],
+ } as Dataset,
+ form_data: {
+ ...base.form_data,
+ datasource: '2__semantic_view',
+ server_pagination: true,
+ },
+ };
+
+ expect(
+ getPaginationControl(name).mapStateToProps?.(state, state.controls[name]),
+ ).toMatchObject({ disabled: true });
+ expect(state.form_data.server_pagination).toBe(true);
+ },
+);
+
+test.each([
+ ['table', 'semantic_view', true],
+ ['semantic_view', 'table', false],
+])(
+ 'AG Grid trusts form datasource %s -> %s while metadata is stale',
+ (previous, next, disabled) => {
+ const panel = getPaginationControl('server_pagination');
+ const base = createMockExplore(undefined);
+ const state: ControlPanelState = {
+ ...base,
+ datasource: {
+ ...base.datasource,
+ type: previous,
+ semantic_view_features: [],
+ } as Dataset,
+ form_data: {
+ ...base.form_data,
+ datasource: `2__${next}`,
+ server_pagination: true,
+ },
+ };
+ expect(
+ panel.mapStateToProps?.(state, state.controls.server_pagination),
+ ).toMatchObject({ disabled });
+ },
+);
+
+test.each([
+ ['semantic_view', [], false, true],
+ ['semantic_view', [], true, true],
+ ['semantic_view', ['ROW_OFFSET'], false, false],
+ ['semantic_view', ['ROW_OFFSET'], true, false],
+ ['table', [], false, false],
+ ['table', [], true, false],
+])(
+ 'row-limit guidance for %s with %s and pagination %s',
+ (type, features, serverPagination, unsupported) => {
+ const rowLimit = getPaginationControl('row_limit');
+ const state: ControlPanelState = {
+ datasource: {
+ id: 1,
+ uid: 'provider-view',
+ type,
+ semantic_view_features: features,
+ } as Dataset,
+ form_data: {
+ datasource: `1__${type}`,
+ viz_type: 'table',
+ server_pagination: serverPagination,
+ },
+ controls: {},
+ slice: { slice_id: 1 },
+ common: {
+ conf: { SQL_MAX_ROW: 70000, TABLE_VIZ_MAX_ROW_SERVER: 500000 },
+ },
+ };
+ const mapped = rowLimit.mapStateToProps?.(state, {
+ ...rowLimit,
+ value: 200000,
+ });
+ const errors = rowLimit.validators?.map(validator =>
+ validator(200000, mapped as Parameters<typeof validator>[1]),
+ );
+ if (unsupported && !serverPagination) {
+ expect(errors).toContain(
+ 'Lower the row limit to SQL_MAX_ROW (70000) or less.',
+ );
+ expect(errors).not.toContain(
+ 'Server pagination needs to be enabled for values over 70000',
+ );
+ } else if (!serverPagination) {
+ expect(errors).toContain(
+ 'Server pagination needs to be enabled for values over 70000',
+ );
+ } else {
+ expect(errors?.filter(Boolean)).toEqual([]);
+ }
+ const choices = (mapped?.choices ?? rowLimit.choices) as [number, string][];
+ expect(choices.some(([value]) => value > 70000)).toBe(!unsupported);
+ expect(choices.some(([value]) => value === 50000)).toBe(true);
+ expect(
+ rowLimit.validators
+ ?.map(validator =>
+ validator(70000, mapped as Parameters<typeof validator>[1]),
+ )
+ .filter(Boolean),
+ ).toEqual([]);
+ },
+);
+
+test('row-limit guidance uses the default SQL_MAX_ROW when configuration is absent', () => {
+ const rowLimit = getPaginationControl('row_limit');
+ const state: ControlPanelState = {
+ datasource: {
+ ...(createMockExplore(undefined).datasource as Dataset),
+ id: 1,
+ uid: 'provider-view',
+ type: 'semantic_view',
+ semantic_view_features: [],
+ } as Dataset,
+ form_data: {
+ datasource: '1__semantic_view',
+ viz_type: 'table',
+ server_pagination: false,
+ },
+ controls: {},
+ slice: { slice_id: 1 },
+ common: {},
+ };
+ const mapped = rowLimit.mapStateToProps?.(state, {
+ ...rowLimit,
+ value: 200000,
+ });
+ expect(
+ rowLimit.validators?.map(validator =>
+ validator(200000, mapped as Parameters<typeof validator>[1]),
+ ),
+ ).toContain('Lower the row limit to SQL_MAX_ROW (100000) or less.');
+ const choices = (mapped?.choices ?? rowLimit.choices) as [number, string][];
+ expect(choices.every(([value]) => value <= 100000)).toBe(true);
+ expect(mapped).not.toHaveProperty('value');
+});
diff --git a/superset-frontend/plugins/plugin-chart-table/src/controlPanel.tsx b/superset-frontend/plugins/plugin-chart-table/src/controlPanel.tsx
index 5b71981b38d..390ecff1a0c 100644
--- a/superset-frontend/plugins/plugin-chart-table/src/controlPanel.tsx
+++ b/superset-frontend/plugins/plugin-chart-table/src/controlPanel.tsx
@@ -39,6 +39,8 @@ import {
shouldSkipMetricColumn,
isRegularMetric,
isPercentMetric,
+ isServerPaginationUnsupported,
+ hasMatchingDatasourceMetadata,
getHeaderGroupsControlProps,
getTimeComparisonColumnKeys,
ConditionalFormattingConfig,
@@ -438,6 +440,16 @@ const config: ControlPanelConfig = {
'Enable server side pagination of results (experimental feature)',
),
default: false,
+ shouldMapStateToProps: () => true,
+ mapStateToProps: state => ({
+ disabled: isServerPaginationUnsupported(state),
+ disabledReason: hasMatchingDatasourceMetadata(state)
+ ? t('This semantic view does not support server pagination.')
+ : undefined,
+ resetLabel: hasMatchingDatasourceMetadata(state)
+ ? t('Turn off server pagination')
+ : undefined,
+ }),
},
},
],
@@ -450,6 +462,10 @@ const config: ControlPanelConfig = {
label: t('Server Page Length'),
default: 10,
choices: SERVER_PAGE_SIZE_OPTIONS,
+ shouldMapStateToProps: () => true,
+ mapStateToProps: state => ({
+ disabled: isServerPaginationUnsupported(state),
+ }),
description: t('Rows per page, 0 means no pagination'),
visibility: ({ controls }: ControlPanelsContainerProps) =>
Boolean(controls?.server_pagination?.value),
@@ -465,7 +481,17 @@ const config: ControlPanelConfig = {
freeForm: true,
label: t('Row limit'),
clearable: false,
+ shouldMapStateToProps: () => true,
mapStateToProps: state => ({
+ paginationUnsupported: isServerPaginationUnsupported(state),
+ choices: formatSelectOptions(
+ ROW_LIMIT_OPTIONS_TABLE.filter(
+ value =>
+ !isServerPaginationUnsupported(state) ||
+ value <=
+ (state?.common?.conf?.SQL_MAX_ROW || DEFAULT_MAX_ROW),
+ ),
+ ),
maxValue: state?.common?.conf?.TABLE_VIZ_MAX_ROW_SERVER,
server_pagination: state?.form_data?.server_pagination,
maxValueWithoutServerPagination:
@@ -479,12 +505,24 @@ const config: ControlPanelConfig = {
state?.maxValue || DEFAULT_MAX_ROW_TABLE_SERVER,
),
(v, state) =>
- validateServerPagination(
- v,
- state?.server_pagination,
- state?.maxValueWithoutServerPagination || DEFAULT_MAX_ROW,
- state?.maxValue || DEFAULT_MAX_ROW_TABLE_SERVER,
- ),
+ state?.paginationUnsupported && !state?.server_pagination
+ ? validateMaxValue(
+ v,
+ state?.maxValueWithoutServerPagination ||
+ DEFAULT_MAX_ROW,
+ ) &&
+ t(
+ 'Lower the row limit to SQL_MAX_ROW (%s) or less.',
+ state?.maxValueWithoutServerPagination ||
+ DEFAULT_MAX_ROW,
+ )
+ : validateServerPagination(
+ v,
+ state?.server_pagination,
+ state?.maxValueWithoutServerPagination ||
+ DEFAULT_MAX_ROW,
+ state?.maxValue || DEFAULT_MAX_ROW_TABLE_SERVER,
+ ),
],
// Re run the validations when this control value
validationDependencies: ['server_pagination'],
diff --git a/superset-frontend/plugins/plugin-chart-table/test/buildQuery.test.ts b/superset-frontend/plugins/plugin-chart-table/test/buildQuery.test.ts
index c418a6c9efc..ecd14a6faa7 100644
--- a/superset-frontend/plugins/plugin-chart-table/test/buildQuery.test.ts
+++ b/superset-frontend/plugins/plugin-chart-table/test/buildQuery.test.ts
@@ -1088,3 +1088,56 @@ describe('plugin-chart-table', () => {
});
});
});
+
+test('preserves saved semantic pagination and ordering until an explicit edit', () => {
+ const saved: TableChartFormData = Object.freeze({
+ ...basicFormData,
+ datasource: '1__semantic_view',
+ query_mode: QueryMode.Aggregate,
+ metrics: ['count'],
+ groupby: ['category'],
+ server_pagination: true,
+ server_page_length: 2,
+ row_limit: 100,
+ });
+ const ownState = Object.freeze({
+ currentPage: 1,
+ pageSize: 2,
+ sortBy: [{ key: 'category', desc: false }],
+ });
+ const { queries } = buildQueryUncached(saved, { ownState });
+ expect(queries[0]).toMatchObject({
+ row_offset: 2,
+ row_limit: 2,
+ orderby: [['category', true]],
+ });
+ expect(queries[1]).toMatchObject({ is_rowcount: true, row_offset: 0 });
+ expect(saved.server_pagination).toBe(true);
+ expect(ownState.currentPage).toBe(1);
+
+ const edited = buildQueryUncached(
+ { ...saved, server_pagination: false },
+ { ownState },
+ );
+ expect(edited.queries[0].row_offset ?? 0).toBe(0);
+ expect(edited.queries).toHaveLength(1);
+ expect(saved.server_pagination).toBe(true);
+});
+
+test.each(['csv', 'xlsx'])(
+ 'retains semantic %s download offset behavior',
+ resultFormat => {
+ const { queries } = buildQueryUncached(
+ {
+ ...basicFormData,
+ datasource: '1__semantic_view',
+ server_pagination: true,
+ server_page_length: 2,
+ row_limit: 100,
+ result_format: resultFormat,
+ },
+ { ownState: { currentPage: 1, pageSize: 2 } },
+ );
+ expect(queries[0]).toMatchObject({ row_offset: 0, row_limit: 100 });
+ },
+);
diff --git a/superset-frontend/plugins/plugin-chart-table/test/controlPanel.test.tsx b/superset-frontend/plugins/plugin-chart-table/test/controlPanel.test.tsx
index 0344511dde5..30cee93b656 100644
--- a/superset-frontend/plugins/plugin-chart-table/test/controlPanel.test.tsx
+++ b/superset-frontend/plugins/plugin-chart-table/test/controlPanel.test.tsx
@@ -17,7 +17,11 @@
* under the License.
*/
import { GenericDataType } from '@apache-superset/core/common';
-import { QueryFormData } from '@superset-ui/core';
+import {
+ DatasourceType,
+ getChartControlPanelRegistry,
+ QueryFormData,
+} from '@superset-ui/core';
import {
ColumnMeta,
Dataset,
@@ -29,6 +33,13 @@ import {
ObjectFormattingEnum,
} from '@superset-ui/chart-controls';
import config from '../src/controlPanel';
+import { useState } from 'react';
+import { render, screen, userEvent } from 'spec/helpers/testing-library';
+import CheckboxControl from 'src/explore/components/controls/CheckboxControl';
+import {
+ ControlPanelsContainer,
+ ControlPanelsContainerProps,
+} from 'src/explore/components/ControlPanelsContainer';
const findNamedControl = (name: string): ControlConfig | null => {
for (const section of config.controlPanelSections) {
@@ -473,6 +484,410 @@ test('columnOptions defaults type_generic to String when missing from datasource
);
});
+function getControl(name: string): ControlConfig {
+ for (const section of config.controlPanelSections) {
+ if (!section) continue;
+ for (const row of section.controlSetRows) {
+ for (const control of row) {
+ if (isCustomControlItem(control) && control.name === name) {
+ return control.config;
+ }
+ }
+ }
+ }
+ throw new Error(`Missing control: ${name}`);
+}
+
+const pagination = getControl('server_pagination');
+const pageLength = getControl('server_page_length');
+
+function panelState(
+ features?: string[],
+ type = 'semantic_view',
+ value = false,
+): ControlPanelState {
+ return {
+ datasource: {
+ id: 1,
+ uid: 'provider-view',
+ type,
+ semantic_view_features: features,
+ } as Dataset,
+ form_data: {
+ datasource: `1__${type}`,
+ viz_type: 'table',
+ server_pagination: value,
+ },
+ controls: { server_pagination: { type: 'CheckboxControl', value } },
+ slice: { slice_id: 1 },
+ common: {},
+ };
+}
+
+test('recomputes pagination controls when datasource metadata changes', () => {
+ const registry = getChartControlPanelRegistry();
+ registry.registerValue('table', {
+ controlPanelSections: [
+ {
+ label: 'Options',
+ expanded: true,
+ controlSetRows: [
+ [{ name: 'server_pagination', config: pagination }],
+ [{ name: 'server_page_length', config: pageLength }],
+ ],
+ },
+ ],
+ });
+ const state = panelState(['ROW_OFFSET']);
+ const props = {
+ actions: { setControlValue: jest.fn() },
+ chart: { chartStatus: 'success', queriesResponse: null },
+ controls: {
+ ...state.controls,
+ server_page_length: { type: 'SelectControl', value: 10 },
+ },
+ datasource_type: DatasourceType.SemanticView,
+ exploreState: state,
+ form_data: state.form_data,
+ isDatasourceMetaLoading: false,
+ errorMessage: null,
+ onQuery: jest.fn(),
+ onStop: jest.fn(),
+ canStopQuery: false,
+ chartIsStale: false,
+ } as unknown as ControlPanelsContainerProps;
+
+ try {
+ const { rerender } = render(<ControlPanelsContainer {...props} />, {
+ useRedux: true,
+ });
+ expect(screen.getByRole('checkbox')).toBeEnabled();
+ rerender(
+ <ControlPanelsContainer
+ {...props}
+ exploreState={{
+ ...props.exploreState,
+ datasource: panelState([]).datasource as Dataset,
+ }}
+ />,
+ );
+ expect(screen.getByRole('checkbox')).toBeDisabled();
+ } finally {
+ registry.remove('table');
+ }
+});
+
+test.each([
+ ['server_pagination', pagination],
+ ['server_page_length', pageLength],
+])('%s remaps when datasource capabilities change', (name, control) => {
+ const before = panelState(['ROW_OFFSET']);
+ const after = panelState([]);
+ const controlState = after.controls[name];
+
+ expect(control.shouldMapStateToProps?.(before, after, controlState)).toBe(
+ true,
+ );
+ expect(control.mapStateToProps?.(after, controlState)).toMatchObject({
+ disabled: true,
+ });
+});
+
+function renderPagination(state: ControlPanelState, onChange = jest.fn()) {
+ return render(
+ <CheckboxControl
+ name="server_pagination"
+ label="Server pagination"
+ {...pagination.mapStateToProps?.(state, state.controls.server_pagination)}
+ value={Boolean(state.controls.server_pagination.value)}
+ onChange={onChange}
+ />,
+ );
+}
+
+test.each([undefined, [], ['UNKNOWN'], ['row_offset']])(
+ 'disables unsupported semantic pagination with explanation: %s',
+ async features => {
+ const onChange = jest.fn();
+ const state = panelState(features);
+ renderPagination(state, onChange);
+ const checkbox = screen.getByRole('checkbox');
+ expect(pagination.type).toBe('CheckboxControl');
+ expect(checkbox).toBeDisabled();
+ expect(checkbox).toHaveAccessibleDescription(
+ 'This semantic view does not support server pagination.',
+ );
+ await userEvent.click(screen.getByText('Server pagination'));
+ expect(onChange).not.toHaveBeenCalled();
+ },
+);
+
+test('fails closed while semantic datasource metadata is unavailable', () => {
+ const state = { ...panelState(), datasource: null };
+ renderPagination(state);
+ expect(screen.getByRole('checkbox')).toBeDisabled();
+});
+
+test.each([
+ ['1__semantic_view', '2__semantic_view'],
+ ['cube__orders', 'cube__customers'],
+])(
+ 'withholds pagination advice for stale metadata %s -> %s',
+ (uid, selected) => {
+ const state = panelState([], 'semantic_view', true);
+ state.datasource = {
+ ...state.datasource,
+ id: 1,
+ uid,
+ type: 'semantic_view',
+ semantic_view_features: [],
+ } as Dataset;
+ state.form_data.datasource = selected;
+ const panel = getControl('server_pagination');
+ expect(
+ panel.mapStateToProps?.(state, state.controls.server_pagination),
+ ).toMatchObject({
+ disabled: true,
+ resetLabel: undefined,
+ disabledReason: undefined,
+ });
+ state.datasource = { ...state.datasource, id: 2, uid: selected } as Dataset;
+ expect(
+ panel.mapStateToProps?.(state, state.controls.server_pagination),
+ ).toMatchObject({
+ disabled: true,
+ resetLabel: 'Turn off server pagination',
+ disabledReason: 'This semantic view does not support server pagination.',
+ });
+ },
+);
+
+test.each([true, false])(
+ 'matches Explore id/type independently of provider uid: offset=%s',
+ supportsOffset => {
+ const state = panelState([], 'semantic_view', true);
+ state.datasource = {
+ ...state.datasource,
+ id: 42,
+ uid: 'provider-orders',
+ type: 'semantic_view',
+ semantic_view_features: supportsOffset ? ['ROW_OFFSET'] : [],
+ } as Dataset;
+ state.form_data.datasource = '42__semantic_view';
+ const panel = getControl('server_pagination');
+ expect(
+ panel.mapStateToProps?.(state, state.controls.server_pagination),
+ ).toMatchObject({
+ disabled: !supportsOffset,
+ resetLabel: 'Turn off server pagination',
+ disabledReason: 'This semantic view does not support server pagination.',
+ });
+ state.datasource = {
+ ...state.datasource,
+ id: 43,
+ uid: '42__semantic_view',
+ } as Dataset;
+ expect(
+ panel.mapStateToProps?.(state, state.controls.server_pagination),
+ ).toMatchObject({
+ disabled: true,
+ resetLabel: undefined,
+ disabledReason: undefined,
+ });
+ state.datasource = {
+ ...state.datasource,
+ id: 42,
+ type: 'table',
+ } as Dataset;
+ expect(
+ panel.mapStateToProps?.(state, state.controls.server_pagination),
+ ).toMatchObject({
+ disabled: true,
+ resetLabel: undefined,
+ disabledReason: undefined,
+ });
+ },
+);
+
+test.each([undefined, [], ['ROW_OFFSET']])(
+ 'matches opaque provider uid before parsing datasource type: %s',
+ features => {
+ const state = panelState(features);
+ state.datasource = { ...state.datasource, uid: 'cube__orders' } as Dataset;
+ state.form_data.datasource = 'cube__orders';
+ renderPagination(state);
+ const disabled = !features?.includes('ROW_OFFSET');
+ expect(screen.getByRole('checkbox').hasAttribute('disabled')).toBe(
+ disabled,
+ );
+ expect(
+ pageLength.mapStateToProps?.(state, state.controls.server_page_length),
+ ).toMatchObject({ disabled });
+ },
+);
+
+test.each([
+ ['table', 'semantic_view', true],
+ ['semantic_view', 'table', false],
+])(
+ 'trusts form datasource %s -> %s while metadata is stale',
+ (previous, next, disabled) => {
+ const state = panelState([], previous, true);
+ state.form_data.datasource = `2__${next}`;
+ renderPagination(state);
+ expect(screen.getByRole('checkbox').hasAttribute('disabled')).toBe(
+ disabled,
+ );
+ expect(
+ pageLength.mapStateToProps?.(state, state.controls.server_pagination),
+ ).toMatchObject({ disabled });
+ expect(state.controls.server_pagination.value).toBe(true);
+ },
+);
+
+test('ignores stale offset capability when switching opaque semantic UIDs', () => {
+ const state = panelState(['ROW_OFFSET'], 'semantic_view', true);
+ state.datasource = {
+ ...state.datasource,
+ uid: 'cube__orders',
+ type: 'semantic_view',
+ semantic_view_features: ['ROW_OFFSET'],
+ } as Dataset;
+ state.form_data.datasource = 'cube__customers';
+
+ for (const name of ['server_pagination', 'server_page_length']) {
+ expect(
+ getControl(name).mapStateToProps?.(state, state.controls[name]),
+ ).toMatchObject({ disabled: true });
+ }
+});
+
+test.each(['server_pagination', 'server_page_length'])(
+ '%s ignores stale offset capability from another semantic view',
+ name => {
+ const state = panelState(['ROW_OFFSET'], 'semantic_view', true);
+ state.datasource = {
+ ...state.datasource,
+ uid: '1__semantic_view',
+ } as Dataset;
+ state.form_data.datasource = '2__semantic_view';
+
+ expect(
+ getControl(name).mapStateToProps?.(state, state.controls[name]),
+ ).toMatchObject({ disabled: true });
+ expect(state.controls.server_pagination.value).toBe(true);
+ },
+);
+
+test('does not offer a reset before datasource metadata arrives', () => {
+ const state = {
+ ...panelState(undefined, 'semantic_view', true),
+ datasource: null,
+ };
+ renderPagination(state);
+ expect(
+ getControl('server_pagination').mapStateToProps?.(
+ state,
+ state.controls.server_pagination,
+ ),
+ ).toMatchObject({ disabledReason: undefined, resetLabel: undefined });
+ expect(screen.getByRole('checkbox')).toBeDisabled();
+ expect(screen.getByRole('checkbox')).toBeChecked();
+ expect(
+ screen.queryByRole('button', { name: 'Turn off server pagination' }),
+ ).not.toBeInTheDocument();
+});
+
+test.each([
+ ['semantic_view', ['ROW_OFFSET']],
+ ['table', undefined],
+ ['table', []],
+])('keeps %s pagination editable with %s', async (type, features) => {
+ const onChange = jest.fn();
+ renderPagination(panelState(features, type), onChange);
+ expect(screen.getByRole('checkbox')).toBeEnabled();
+ await userEvent.click(screen.getByRole('checkbox'));
+ expect(onChange).toHaveBeenCalledWith(true);
+ expect(
+ screen.queryByText(/does not support server pagination/),
+ ).not.toBeInTheDocument();
+});
+
+test('disables dependent page length without hiding or resetting saved state', () => {
+ const state = panelState([], 'semantic_view', true);
+ expect(
+ pageLength.mapStateToProps?.(state, state.controls.server_pagination),
+ ).toMatchObject({ disabled: true });
+ expect(
+ pageLength.visibility?.(
+ { ...state, actions: { setDatasource: jest.fn() }, exportState: {} },
+ {},
+ ),
+ ).toBe(true);
+ expect(state.controls.server_pagination.value).toBe(true);
+});
+
+test.each(['semantic_view', 'table'])(
+ 'checked enabled %s pagination has no unsupported-control reset button',
+ type => {
+ renderPagination(panelState(['ROW_OFFSET'], type, true));
+ expect(screen.getByRole('checkbox')).toBeEnabled();
+ expect(screen.getByRole('checkbox')).toBeChecked();
+ expect(
+ screen.queryByRole('button', { name: 'Turn off server pagination' }),
+ ).not.toBeInTheDocument();
+ },
+);
+
+test('saved true survives datasource changes until an explicit keyboard edit', async () => {
+ const unsupportedState = panelState([], 'semantic_view', true);
+ expect(
+ pagination.mapStateToProps?.(
+ unsupportedState,
+ unsupportedState.controls.server_pagination,
+ ),
+ ).not.toHaveProperty('value');
+ const saved = Object.freeze({ server_pagination: true });
+ const onEdit = jest.fn();
+ function Editor({ features }: { features?: string[] }) {
+ const [value, setValue] = useState<boolean>(saved.server_pagination);
+ const state = panelState(features, 'semantic_view', value);
+ return (
+ <CheckboxControl
+ name="server_pagination"
+ label="Server pagination"
+ {...pagination.mapStateToProps?.(
+ state,
+ state.controls.server_pagination,
+ )}
+ value={value}
+ onChange={next => {
+ setValue(next);
+ onEdit(next);
+ }}
+ />
+ );
+ }
+ const { rerender } = render(<Editor features={['ROW_OFFSET']} />);
+ expect(screen.getByRole('checkbox')).toBeChecked();
+ rerender(<Editor features={[]} />);
+ expect(screen.getByRole('checkbox')).toBeChecked();
+ expect(screen.getByRole('checkbox')).toBeDisabled();
+ expect(onEdit).not.toHaveBeenCalled();
+ await userEvent.tab();
+ expect(
+ screen.getByRole('button', { name: 'Turn off server pagination' }),
+ ).toHaveFocus();
+ await userEvent.keyboard('{Enter}');
+ expect(screen.getByRole('checkbox')).not.toBeChecked();
+ expect(onEdit).toHaveBeenCalledTimes(1);
+ expect(onEdit).toHaveBeenCalledWith(false);
+ expect(saved.server_pagination).toBe(true);
+ expect(
+ screen.queryByRole('button', { name: 'Turn off server pagination' }),
+ ).not.toBeInTheDocument();
+});
+
test('column_config mapStateToProps expands comparison columns for metrics', () => {
const controlConfig = findNamedControl('column_config');
const explore = {
@@ -494,3 +909,132 @@ test('column_config mapStateToProps expands comparison columns for metrics', ()
expect(result.columnsPropsObject.childColumnMap['Main col1']).toBe(false);
expect(result.columnsPropsObject.childColumnMap['# col1']).toBe(true);
});
+
+test.each([false, true])(
+ 'numeric-leading provider uid retains pagination capability and reset advice: %s',
+ supportsOffset => {
+ const features = supportsOffset ? ['ROW_OFFSET'] : [];
+ const state = panelState(features, 'semantic_view', true);
+ state.datasource = {
+ ...state.datasource,
+ id: 7,
+ uid: '123__orders',
+ } as Dataset;
+ state.form_data.datasource = '123__orders';
+ renderPagination(state);
+ const disabled = !features.includes('ROW_OFFSET');
+ expect(screen.getByRole('checkbox').hasAttribute('disabled')).toBe(
+ disabled,
+ );
+ expect(
+ pageLength.mapStateToProps?.(state, state.controls.server_page_length),
+ ).toMatchObject({ disabled });
+ expect(
+ pagination.mapStateToProps?.(state, state.controls.server_pagination),
+ ).toMatchObject({
+ disabledReason: 'This semantic view does not support server pagination.',
+ resetLabel: 'Turn off server pagination',
+ });
+ if (disabled) {
+ expect(
+ screen.getByRole('button', { name: 'Turn off server pagination' }),
+ ).toBeInTheDocument();
+ }
+ },
+);
+
+test.each([
+ ['semantic_view', [], false, true],
+ ['semantic_view', [], true, true],
+ ['semantic_view', ['ROW_OFFSET'], false, false],
+ ['semantic_view', ['ROW_OFFSET'], true, false],
+ ['table', [], false, false],
+ ['table', [], true, false],
+])(
+ 'row-limit guidance for %s with %s and pagination %s',
+ (type, features, serverPagination, unsupported) => {
+ const rowLimit = getControl('row_limit');
+ const state: ControlPanelState = {
+ datasource: {
+ id: 1,
+ uid: 'provider-view',
+ type,
+ semantic_view_features: features,
+ } as Dataset,
+ form_data: {
+ datasource: `1__${type}`,
+ viz_type: 'table',
+ server_pagination: serverPagination,
+ },
+ controls: {},
+ slice: { slice_id: 1 },
+ common: {
+ conf: { SQL_MAX_ROW: 70000, TABLE_VIZ_MAX_ROW_SERVER: 500000 },
+ },
+ };
+ const mapped = rowLimit.mapStateToProps?.(state, {
+ ...rowLimit,
+ value: 200000,
+ });
+ const errors = rowLimit.validators?.map(validator =>
+ validator(200000, mapped as Parameters<typeof validator>[1]),
+ );
+ if (unsupported && !serverPagination) {
+ expect(errors).toContain(
+ 'Lower the row limit to SQL_MAX_ROW (70000) or less.',
+ );
+ expect(errors).not.toContain(
+ 'Server pagination needs to be enabled for values over 70000',
+ );
+ } else if (!serverPagination) {
+ expect(errors).toContain(
+ 'Server pagination needs to be enabled for values over 70000',
+ );
+ } else {
+ expect(errors?.filter(Boolean)).toEqual([]);
+ }
+ const choices = (mapped?.choices ?? rowLimit.choices) as [number, string][];
+ expect(choices.some(([value]) => value > 70000)).toBe(!unsupported);
+ expect(choices.some(([value]) => value === 50000)).toBe(true);
+ expect(
+ rowLimit.validators
+ ?.map(validator =>
+ validator(70000, mapped as Parameters<typeof validator>[1]),
+ )
+ .filter(Boolean),
+ ).toEqual([]);
+ },
+);
+
+test('row-limit guidance uses the default SQL_MAX_ROW when configuration is absent', () => {
+ const rowLimit = getControl('row_limit');
+ const state: ControlPanelState = {
+ datasource: {
+ ...(createMockExplore(undefined).datasource as Dataset),
+ id: 1,
+ uid: 'provider-view',
+ type: 'semantic_view',
+ semantic_view_features: [],
+ } as Dataset,
+ form_data: {
+ datasource: '1__semantic_view',
+ viz_type: 'table',
+ server_pagination: false,
+ },
+ controls: {},
+ slice: { slice_id: 1 },
+ common: {},
+ };
+ const mapped = rowLimit.mapStateToProps?.(state, {
+ ...rowLimit,
+ value: 200000,
+ });
+ expect(
+ rowLimit.validators?.map(validator =>
+ validator(200000, mapped as Parameters<typeof validator>[1]),
+ ),
+ ).toContain('Lower the row limit to SQL_MAX_ROW (100000) or less.');
+ const choices = (mapped?.choices ?? rowLimit.choices) as [number, string][];
+ expect(choices.every(([value]) => value <= 100000)).toBe(true);
+ expect(mapped).not.toHaveProperty('value');
+});
diff --git a/superset-frontend/src/explore/components/Control.test.tsx b/superset-frontend/src/explore/components/Control.test.tsx
index 3dd41ff4a2e..25282b5349b 100644
--- a/superset-frontend/src/explore/components/Control.test.tsx
+++ b/superset-frontend/src/explore/components/Control.test.tsx
@@ -104,7 +104,7 @@ test('marks hiding a control as a programmatic value reset', async () => {
);
});
-test('shows the description icon while the control is hovered', async () => {
+test('keeps description help available before and after hover', async () => {
render(
setup({
label: 'My checkbox',
@@ -113,8 +113,8 @@ test('shows the description icon while the control is hovered', async () => {
);
expect(
- screen.queryByRole('button', { name: 'Show info tooltip' }),
- ).not.toBeInTheDocument();
+ screen.getByRole('button', { name: 'Show info tooltip' }),
+ ).toBeInTheDocument();
await userEvent.hover(screen.getByTestId('checkbox'));
expect(
@@ -123,11 +123,11 @@ test('shows the description icon while the control is hovered', async () => {
await userEvent.unhover(screen.getByTestId('checkbox'));
expect(
- screen.queryByRole('button', { name: 'Show info tooltip' }),
- ).not.toBeInTheDocument();
+ screen.getByRole('button', { name: 'Show info tooltip' }),
+ ).toBeInTheDocument();
});
-test('shows the description icon while the control has keyboard focus', () => {
+test('keeps description help available across input and help focus', () => {
render(
setup({
label: 'My checkbox',
@@ -136,8 +136,8 @@ test('shows the description icon while the control has keyboard focus', () => {
);
expect(
- screen.queryByRole('button', { name: 'Show info tooltip' }),
- ).not.toBeInTheDocument();
+ screen.getByRole('button', { name: 'Show info tooltip' }),
+ ).toBeInTheDocument();
fireEvent.focus(screen.getByRole('checkbox'));
const infoIcon = screen.getByRole('button', { name: 'Show info tooltip' });
@@ -150,8 +150,8 @@ test('shows the description icon while the control has keyboard focus', () => {
fireEvent.blur(infoIcon, { relatedTarget: document.body });
expect(
- screen.queryByRole('button', { name: 'Show info tooltip' }),
- ).not.toBeInTheDocument();
+ screen.getByRole('button', { name: 'Show info tooltip' }),
+ ).toBeInTheDocument();
});
test('keeps the description icon visible when the pointer leaves a focused control', () => {
diff --git a/superset-frontend/src/explore/components/ControlHeader.test.tsx b/superset-frontend/src/explore/components/ControlHeader.test.tsx
index f014f609b90..a6a70f0db78 100644
--- a/superset-frontend/src/explore/components/ControlHeader.test.tsx
+++ b/superset-frontend/src/explore/components/ControlHeader.test.tsx
@@ -21,12 +21,60 @@ import {
screen,
userEvent,
fireEvent,
+ waitFor,
} from 'spec/helpers/testing-library';
import ControlHeader from './ControlHeader';
+import SelectControl from './controls/SelectControl';
const description = 'This control filters the whole chart.';
-test('does not render the description icon until the control is hovered', () => {
+test('instant-effect notice requires hover while description help remains available', () => {
+ const { rerender } = render(
+ <ControlHeader
+ name="my-control"
+ label="My control"
+ description={description}
+ renderTrigger
+ hovered={false}
+ />,
+ );
+ expect(screen.queryByTestId('info-tooltip-icon')).not.toBeInTheDocument();
+ expect(
+ screen.getByRole('button', { name: 'Show info tooltip' }),
+ ).toBeInTheDocument();
+ rerender(
+ <ControlHeader
+ name="my-control"
+ label="My control"
+ description={description}
+ renderTrigger
+ hovered
+ />,
+ );
+ expect(screen.getByTestId('info-tooltip-icon')).toBeInTheDocument();
+ expect(screen.getByTestId('my-control-description-icon')).toBeInTheDocument();
+});
+
+test('noninteractive labels do not add a dead keyboard stop', () => {
+ render(<ControlHeader name="time_range" label="Date Range" />);
+
+ const label = screen.getByText('Date Range');
+ expect(label).not.toHaveAttribute('role');
+ expect(label).not.toHaveAttribute('aria-disabled');
+ expect(label).not.toHaveAttribute('tabindex');
+});
+
+test('interactive labels remain keyboard-accessible buttons', () => {
+ const onClick = jest.fn();
+ render(<ControlHeader label="Toggle option" onClick={onClick} />);
+ const label = screen.getByRole('button', { name: 'Toggle option' });
+ expect(label).toHaveAttribute('tabindex', '0');
+ expect(label).not.toHaveAttribute('aria-disabled');
+ fireEvent.keyDown(label, { key: 'Enter' });
+ expect(onClick).toHaveBeenCalledTimes(1);
+});
+
+test('keeps the description icon available without hover', () => {
const { rerender } = render(
<ControlHeader
name="time_range"
@@ -36,8 +84,8 @@ test('does not render the description icon until the control is hovered', () =>
);
expect(
- screen.queryByRole('button', { name: 'Show info tooltip' }),
- ).not.toBeInTheDocument();
+ screen.getByRole('button', { name: 'Show info tooltip' }),
+ ).toBeInTheDocument();
rerender(
<ControlHeader
@@ -128,3 +176,41 @@ test('renders description icon outside label when hovered', async () => {
const formLabel = label.closest('label');
expect(formLabel).not.toContainElement(infoIcon);
});
+
+test('disabled selects keep their description reachable by keyboard without a header tab stop', async () => {
+ render(
+ <SelectControl
+ name="server_page_length"
+ label="Server Page Length"
+ description={description}
+ disabled
+ choices={[[10, '10']]}
+ value={10}
+ />,
+ );
+ expect(screen.getByText('Server Page Length')).not.toHaveAttribute(
+ 'tabindex',
+ );
+ await userEvent.tab();
+ expect(
+ screen.getByRole('button', { name: 'Show info tooltip' }),
+ ).toHaveFocus();
+ expect(await screen.findByRole('tooltip')).toHaveTextContent(description);
+});
+
+test('description help stays associated with its own control after focus moves', async () => {
+ render(
+ <>
+ <ControlHeader label="First control" description="First help" />
+ <ControlHeader label="Second control" description="Second help" />
+ </>,
+ );
+ const buttons = screen.getAllByRole('button', { name: 'Show info tooltip' });
+ await userEvent.tab();
+ expect(await screen.findByRole('tooltip')).toHaveTextContent('First help');
+ expect(buttons[0]).toHaveAccessibleDescription('First help');
+ await userEvent.tab();
+ await waitFor(() =>
+ expect(buttons[1]).toHaveAccessibleDescription('Second help'),
+ );
+});
diff --git a/superset-frontend/src/explore/components/ControlHeader.tsx b/superset-frontend/src/explore/components/ControlHeader.tsx
index 53f6cecae99..a753d4f8272 100644
--- a/superset-frontend/src/explore/components/ControlHeader.tsx
+++ b/superset-frontend/src/explore/components/ControlHeader.tsx
@@ -17,7 +17,7 @@
* under the License.
*/
import { handleKeyboardActivation } from '@superset-ui/core';
-import { FC, ReactNode } from 'react';
+import { FC, ReactNode, useId } from 'react';
import { t } from '@apache-superset/core/translation';
import { css, useTheme, SupersetTheme } from '@apache-superset/core/theme';
import { FormLabel, InfoTooltip, Tooltip } from '@superset-ui/core/components';
@@ -27,6 +27,7 @@ type ValidationError = string;
export type ControlHeaderProps = {
name?: string;
+ inputId?: string;
label?: ReactNode;
description?: ReactNode;
validationErrors?: ValidationError[];
@@ -61,6 +62,7 @@ const iconStyles = css`
const ControlHeader: FC<ControlHeaderProps> = ({
name,
+ inputId,
label,
description,
validationErrors = [],
@@ -75,13 +77,14 @@ const ControlHeader: FC<ControlHeaderProps> = ({
onDescriptionHoverChange,
}) => {
const theme = useTheme();
+ const descriptionId = useId();
if (!label) {
return null;
}
const renderOptionalIcons = () => {
- if (!hovered) {
+ if (!hovered && !description) {
return null;
}
@@ -99,7 +102,7 @@ const ControlHeader: FC<ControlHeaderProps> = ({
{description && (
<>
<Tooltip
- id="description-tooltip"
+ id={descriptionId}
title={description}
placement="top"
mouseLeaveDelay={0}
@@ -130,7 +133,7 @@ const ControlHeader: FC<ControlHeaderProps> = ({
</Tooltip>{' '}
</>
)}
- {renderTrigger && (
+ {hovered && renderTrigger && (
<span>
<InfoTooltip
label={t('bolt')}
@@ -162,23 +165,27 @@ const ControlHeader: FC<ControlHeaderProps> = ({
overflow: visible;
padding-bottom: 0.1em;
`}
- htmlFor={name}
+ htmlFor={inputId ?? name}
>
{leftNode && <span>{leftNode} </span>}
{/* This label text sits inside FormLabel's <label>, and HTML5
prohibits interactive content (including <button>) as a
descendant of <label>, so a real button tag isn't an option
here. */}
- <span
- // eslint-disable-next-line jsx-a11y/prefer-tag-over-role
- role="button"
- tabIndex={0}
- onClick={onClick}
- onKeyDown={onClick ? handleKeyboardActivation(onClick) : undefined}
- style={{ cursor: onClick ? 'pointer' : '' }}
- >
- {label}
- </span>{' '}
+ {onClick ? (
+ <span
+ // eslint-disable-next-line jsx-a11y/prefer-tag-over-role
+ role="button"
+ tabIndex={0}
+ onClick={onClick}
+ onKeyDown={handleKeyboardActivation(onClick)}
+ style={{ cursor: 'pointer' }}
+ >
+ {label}
+ </span>
+ ) : (
+ <span>{label}</span>
+ )}{' '}
{warning && (
<span>
<Tooltip id="error-tooltip" placement="top" title={warning}>
diff --git a/superset-frontend/src/explore/components/controls/CheckboxControl.test.tsx b/superset-frontend/src/explore/components/controls/CheckboxControl.test.tsx
index 5626fe21b9e..e9af5003476 100644
--- a/superset-frontend/src/explore/components/controls/CheckboxControl.test.tsx
+++ b/superset-frontend/src/explore/components/controls/CheckboxControl.test.tsx
@@ -16,7 +16,13 @@
* specific language governing permissions and limitations
* under the License.
*/
-import { render, screen, userEvent } from 'spec/helpers/testing-library';
+import {
+ fireEvent,
+ render,
+ screen,
+ userEvent,
+} from 'spec/helpers/testing-library';
+import { useState } from 'react';
import CheckboxControl from 'src/explore/components/controls/CheckboxControl';
const defaultProps = {
@@ -30,6 +36,27 @@ const setup = (overrides = {}) => (
<CheckboxControl {...defaultProps} {...overrides} />
);
+test.each([undefined, 'Unavailable'])(
+ 'resets a disabled saved value without a label, explanation=%s',
+ async disabledReason => {
+ const onChange = jest.fn();
+ render(
+ setup({
+ label: undefined,
+ disabled: true,
+ value: true,
+ disabledReason,
+ resetLabel: 'Turn off',
+ onChange,
+ }),
+ );
+ expect(screen.getByRole('checkbox')).toBeDisabled();
+ await userEvent.click(screen.getByRole('button', { name: 'Turn off' }));
+ expect(onChange).toHaveBeenCalledTimes(1);
+ expect(onChange).toHaveBeenCalledWith(false);
+ },
+);
+
// eslint-disable-next-line no-restricted-globals -- TODO: Migrate from describe blocks
describe('CheckboxControl', () => {
test('renders a Checkbox', () => {
@@ -41,12 +68,125 @@ describe('CheckboxControl', () => {
});
test('Checks the box when the label is clicked', async () => {
- render(setup());
+ const onChange = jest.fn();
+ render(setup({ onChange }));
const label = screen.getByRole('button', {
name: /checkbox label/i,
});
await userEvent.click(label);
- expect(defaultProps.onChange).toHaveBeenCalled();
+ expect(onChange).toHaveBeenCalledTimes(1);
+ });
+
+ test('keeps the checkbox checked after its label is clicked', () => {
+ function StatefulCheckbox() {
+ const [checked, setChecked] = useState(false);
+ return setup({ value: checked, onChange: setChecked });
+ }
+
+ render(<StatefulCheckbox />);
+ fireEvent.click(screen.getByText('checkbox label'));
+
+ expect(screen.getByRole('checkbox')).toBeChecked();
+ });
+
+ test('prevents duplicate native label activation from the label text', () => {
+ render(setup());
+ const click = new MouseEvent('click', { bubbles: true, cancelable: true });
+
+ screen.getByText('checkbox label').dispatchEvent(click);
+
+ expect(click.defaultPrevented).toBe(true);
});
+
+ test('focuses the checkbox when its label text is clicked', () => {
+ render(setup());
+
+ fireEvent.click(screen.getByText('checkbox label'));
+
+ expect(screen.getByRole('checkbox')).toHaveFocus();
+ });
+
+ test('explains a disabled checkbox without a label', () => {
+ render(
+ setup({
+ label: undefined,
+ disabled: true,
+ disabledReason: 'Unavailable',
+ }),
+ );
+
+ const checkbox = screen.getByRole('checkbox');
+ expect(checkbox).toHaveAccessibleDescription('Unavailable');
+ expect(screen.getByText('Unavailable')).toBeInTheDocument();
+ });
+
+ test('retains the control header and description when disabled', () => {
+ const { container } = render(
+ setup({
+ disabled: true,
+ description: 'Why this control is disabled',
+ hovered: true,
+ renderTrigger: true,
+ }),
+ );
+
+ expect(
+ container.querySelector('[data-test="show_legend-header"]'),
+ ).toBeInTheDocument();
+ expect(
+ container.querySelector('[data-test="show_legend-description-icon"]'),
+ ).toBeInTheDocument();
+ expect(screen.getByRole('checkbox')).toBeDisabled();
+ });
+
+ test('names the disabled checkbox from its visible label', () => {
+ render(setup({ disabled: true, disabledReason: 'Unavailable' }));
+
+ const checkbox = screen.getByRole('checkbox', { name: 'checkbox label' });
+ expect(checkbox).toHaveAttribute('id');
+ expect(checkbox).toHaveAccessibleDescription('Unavailable');
+ });
+
+ test('names a checkbox with a React label and no control name', () => {
+ render(setup({ name: undefined, label: <span>Custom label</span> }));
+
+ const checkbox = screen.getByRole('checkbox', { name: 'Custom label' });
+ expect(checkbox).toHaveAttribute('id');
+ });
+
+ test('ignores label clicks while disabled', async () => {
+ const onChange = jest.fn();
+ render(setup({ disabled: true, onChange }));
+
+ await userEvent.click(screen.getByText('checkbox label'));
+ expect(onChange).not.toHaveBeenCalled();
+ });
+});
+
+test('same-name instances keep their labels and focus on their own checkbox', () => {
+ const firstChange = jest.fn();
+ const secondChange = jest.fn();
+ render(
+ <>
+ <CheckboxControl
+ name="showCellBars"
+ label="First column bars"
+ onChange={firstChange}
+ />
+ <CheckboxControl
+ name="showCellBars"
+ label="Second column bars"
+ onChange={secondChange}
+ />
+ </>,
+ );
+ const first = screen.getByRole('checkbox', { name: 'First column bars' });
+ const second = screen.getByRole('checkbox', { name: 'Second column bars' });
+ expect(first.id).not.toBe(second.id);
+ fireEvent.click(screen.getByText('Second column bars'));
+ expect(second).toHaveFocus();
+ expect(secondChange).toHaveBeenCalledTimes(1);
+ expect(secondChange).toHaveBeenCalledWith(true);
+ expect(firstChange).not.toHaveBeenCalled();
});
diff --git a/superset-frontend/src/explore/components/controls/CheckboxControl.tsx b/superset-frontend/src/explore/components/controls/CheckboxControl.tsx
index b37829c57c2..f6d662ffb01 100644
--- a/superset-frontend/src/explore/components/controls/CheckboxControl.tsx
+++ b/superset-frontend/src/explore/components/controls/CheckboxControl.tsx
@@ -16,9 +16,14 @@
* specific language governing permissions and limitations
* under the License.
*/
-import { useCallback, type ReactNode } from 'react';
+import { useCallback, useId, type ReactNode } from 'react';
import { styled, css } from '@apache-superset/core/theme';
-import { Checkbox } from '@superset-ui/core/components';
+import {
+ Button,
+ Checkbox,
+ Space,
+ Typography,
+} from '@superset-ui/core/components';
import ControlHeader from '../ControlHeader';
interface CheckboxControlProps {
@@ -31,6 +36,9 @@ interface CheckboxControlProps {
validationErrors?: string[];
placeholder?: string;
debounceDelay?: number;
+ disabled?: boolean;
+ disabledReason?: string;
+ resetLabel?: string;
}
const CheckBoxControlWrapper = styled.div`
@@ -50,24 +58,77 @@ const CheckBoxControlWrapper = styled.div`
export default function CheckboxControl({
value = false,
label,
+ disabled = false,
+ disabledReason,
+ resetLabel,
onChange = () => {},
...restProps
}: CheckboxControlProps): JSX.Element {
+ const explanationId = useId();
+ const checkboxId = useId();
const handleChange = useCallback((): void => {
- onChange(!value);
- }, [onChange, value]);
+ if (!disabled) {
+ onChange(!value);
+ }
+ }, [disabled, onChange, value]);
- const checkbox = <Checkbox onChange={handleChange} checked={!!value} />;
+ const checkbox = (
+ <Checkbox
+ id={checkboxId}
+ onChange={handleChange}
+ checked={!!value}
+ disabled={disabled}
+ aria-describedby={disabled && disabledReason ? explanationId : undefined}
+ />
+ );
+ const explanation = disabled && disabledReason && (
+ <Typography.Text id={explanationId} type="secondary">
+ {disabledReason}
+ </Typography.Text>
+ );
+ const resetButton = disabled && value && resetLabel && (
+ <Button buttonSize="small" onClick={() => onChange(false)}>
+ {resetLabel}
+ </Button>
+ );
+ const feedback = (explanation || resetButton) && (
+ <Space direction="vertical" size="small">
+ {explanation}
+ {resetButton}
+ </Space>
+ );
if (label) {
return (
<CheckBoxControlWrapper>
<ControlHeader
{...restProps}
+ name={restProps.name || checkboxId}
+ inputId={checkboxId}
label={label}
leftNode={checkbox}
- onClick={handleChange}
+ onClick={
+ disabled
+ ? undefined
+ : (event?: { preventDefault: () => void }) => {
+ if (event) {
+ event.preventDefault();
+ // Preserve the label's focus behavior without a second toggle.
+ document.getElementById(checkboxId)?.focus();
+ }
+ handleChange();
+ }
+ }
/>
+ {feedback}
+ </CheckBoxControlWrapper>
+ );
+ }
+ if (feedback) {
+ return (
+ <CheckBoxControlWrapper>
+ {checkbox}
+ {feedback}
</CheckBoxControlWrapper>
);
}
diff --git a/superset-frontend/src/explore/components/controls/CollectionControl/CollectionControl.test.tsx b/superset-frontend/src/explore/components/controls/CollectionControl/CollectionControl.test.tsx
index b58e7f5ad83..7ceb3e04f26 100644
--- a/superset-frontend/src/explore/components/controls/CollectionControl/CollectionControl.test.tsx
+++ b/superset-frontend/src/explore/components/controls/CollectionControl/CollectionControl.test.tsx
@@ -89,15 +89,17 @@ test('Should render', async () => {
expect(await screen.findByTestId('CollectionControl')).toBeInTheDocument();
});
-test('Should show the button with the label', async () => {
+test('Should show the noninteractive label as plain text', async () => {
const props = createProps();
render(<CollectionControl {...props} />);
+ const label = await screen.findByText(props.label);
+ expect(label).toBeVisible();
+ expect(label).not.toHaveAttribute('role');
+ expect(label).not.toHaveAttribute('tabindex');
+ expect(label).not.toHaveAttribute('aria-disabled');
expect(
- await screen.findByRole('button', { name: props.label }),
- ).toBeInTheDocument();
- expect(screen.getByRole('button', { name: props.label })).toHaveTextContent(
- props.label,
- );
+ screen.queryByRole('button', { name: props.label }),
+ ).not.toBeInTheDocument();
});
test('Should have add button', async () => {
diff --git a/superset/translations/messages.pot b/superset/translations/messages.pot
index 5b360ffa344..799cb63d93b 100644
--- a/superset/translations/messages.pot
+++ b/superset/translations/messages.pot
@@ -8470,6 +8470,10 @@ msgstr ""
msgid "Lower bound of the color scale. When both start and end are set, the legend uses this fixed range instead of the automatic data range."
msgstr ""
+#, python-format
+msgid "Lower the row limit to SQL_MAX_ROW (%s) or less."
+msgstr ""
+
msgid "Lower threshold must be lower than upper threshold"
msgstr ""
@@ -14953,6 +14957,9 @@ msgstr ""
msgid "This semantic layer has no dependent semantic views."
msgstr ""
+msgid "This semantic view does not support server pagination."
+msgstr ""
+
msgid "This session has encountered an interruption, and some controls may not work as intended. If you are the developer of this app, please check that the guest token is being generated correctly."
msgstr ""
@@ -15403,6 +15410,9 @@ msgstr ""
msgid "Tukey"
msgstr ""
+msgid "Turn off server pagination"
+msgstr ""
+
msgid "Turn off the logarithmic axis before stacking bars"
msgstr ""
diff --git a/tests/unit_tests/semantic_layers/mapper_test.py b/tests/unit_tests/semantic_layers/mapper_test.py
index 828aaa316e6..7bdf44d108b 100644
--- a/tests/unit_tests/semantic_layers/mapper_test.py
+++ b/tests/unit_tests/semantic_layers/mapper_test.py
@@ -17,7 +17,7 @@
from datetime import date, datetime, time, timezone
from typing import Any
-from unittest.mock import MagicMock
+from unittest.mock import MagicMock, Mock
from zoneinfo import ZoneInfo
import freezegun
@@ -4298,6 +4298,58 @@ def test_abc_only_provider_validates_and_maps(mocker: MockerFixture) -> None:
assert {dim.name for dim in queries[0].dimensions} == {"category"}
+@pytest.mark.parametrize("offset", [None, -1, 0, 2])
+@pytest.mark.parametrize("limit", [None, 0, 2])
+def test_row_offset_mapping_without_advertised_capability(
+ mock_datasource: MagicMock, offset: int | None, limit: int | None
+) -> None:
+ """Keep direct callers provider-local even when UI support is absent."""
+ mock_datasource.implementation.features = frozenset()
+ query_object: ValidatedQueryObject = ValidatedQueryObject(
+ datasource=mock_datasource,
+ metrics=["total_sales"],
+ columns=["category"],
+ row_offset=offset,
+ row_limit=limit,
+ orderby=[("category", True)],
+ )
+
+ queries: list[SemanticQuery] = map_query_object(query_object)
+
+ assert len(queries) == 1
+ assert queries[0].offset == (offset or 0)
+ assert queries[0].limit == limit
+ assert queries[0].order is not None
+ assert queries[0].order[0][1] == OrderDirection.ASC
+ assert isinstance(queries[0].order[0][0], Dimension)
+ assert queries[0].order[0][0].name == "category"
+
+
+def test_unadvertised_offset_reaches_provider(
+ mock_datasource: MagicMock, mocker: MockerFixture
+) -> None:
+ """Do not add host-wide rejection for capable but unadvertised providers."""
+ mock_datasource.implementation.features = frozenset()
+ result: SemanticResult = SemanticResult(
+ requests=[], results=pa.table({"category": ["third"], "total_sales": [3.0]})
+ )
+ execute: Mock = mocker.Mock(return_value=result)
+ mock_datasource.implementation.get_table = execute
+ query_object: ValidatedQueryObject = ValidatedQueryObject(
+ datasource=mock_datasource,
+ metrics=["total_sales"],
+ columns=["category"],
+ row_offset=2,
+ row_limit=2,
+ )
+
+ get_results(query_object)
+
+ execute.assert_called_once()
+ assert execute.call_args.args[0].offset == 2
+ assert execute.call_args.args[0].limit == 2
+
+
def _offset_query_object(mock_datasource: MagicMock) -> ValidatedQueryObject:
return ValidatedQueryObject(
datasource=mock_datasource,
diff --git a/tests/unit_tests/semantic_layers/models_test.py b/tests/unit_tests/semantic_layers/models_test.py
index 47d7154fdde..db359dea372 100644
--- a/tests/unit_tests/semantic_layers/models_test.py
+++ b/tests/unit_tests/semantic_layers/models_test.py
@@ -2634,6 +2634,22 @@ def test_values_for_column_search_rejection_falls_back_unfiltered(
assert "category" in caplog.text
+def test_semantic_view_data_row_offset_capability(
+ mock_implementation: MagicMock,
+ semantic_view: SemanticView,
+) -> None:
+ """Expose the optional bounded-offset contract through existing metadata."""
+ declared: frozenset[SemanticViewFeature] = frozenset(
+ {SemanticViewFeature.ROW_OFFSET, SemanticViewFeature.GROUP_LIMIT}
+ )
+ mock_implementation.features = declared
+
+ data: ExplorableData = semantic_view.data
+
+ assert data["semantic_view_features"] == ["GROUP_LIMIT", "ROW_OFFSET"]
+ assert SemanticViewFeature.ROW_OFFSET.value == "ROW_OFFSET"
+
+
@pytest.mark.parametrize("reason", ["incomplete", "unverified"])
def test_values_fallback_translates_provider_completeness_error(
mock_implementation: MagicMock,