Compare commits

..

6 Commits

Author SHA1 Message Date
Evan Rusackas
0a9e3a751d feat(docs): tier 2 — dashboard view and save-modal tutorial screenshots (#39466)
Co-authored-by: Claude <claude@anthropic.com>
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
Co-authored-by: Superset Dev <dev@superset.apache.org>
2026-04-21 17:29:05 -07:00
Claude
ab658ac4b5 fix(docs): address Copilot review feedback on screenshot generator
- Use stable data-test="run-query-action" selector for SQL Lab Run button
- Update docstring port 9000 -> 8088 to match Superset default
- Include 'community' in screenshot-manifest type values comment

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-20 08:59:44 -07:00
Claude
b34b799d2c fix(docs): add ASF license header to screenshot manifest
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-20 08:53:53 -07:00
Claude
406358ca3b fix(docs): screenshot quality improvements and chart type picker dataset selection
- Add settle() helper (1s wait) before every screenshot to let ECharts
  animations and lazy-loaded images finish before capture
- Datasets list: switch from table-element screenshot to viewport screenshot
  so the SubMenu (Datasets nav, Bulk Select, + Dataset buttons) is visible
- Chart type picker: select birth_names dataset and Pivot Table chart type
  before screenshotting, showing both wizard steps in a useful state
- Fix strict-mode violations in chart type picker test (step title vs
  placeholder both match "Choose a dataset"; dataset select uses hidden ARIA
  listbox with ID-based option names rather than display labels)
- Regenerate all screenshots with updated tests

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-17 10:26:23 -07:00
Claude
12403b98c0 fix(docs): update screenshot generator tests and regenerate screenshots
- Remove deprecated schema/table selector steps in SQL Lab test (UI changed to tree view)
- Fix datasets table row check to skip hidden ant-table-measure-row
- Fix strict-mode violation in Run button selector (scoped to button role)
- Add baseURL explicitly to generator playwright config project use block
- Regenerate all 6 doc screenshots with latest UI

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-17 09:37:52 -07:00
Claude
df61792f59 feat(docs): add screenshot manifest and expand docs:screenshots generator
Introduces screenshot-manifest.yaml as a living inventory of all images
in the Superset docs, tracking output path, selector, and app_path for
each entry. Entries are removed from the manifest as Playwright tests
are written for them.

Adds two new tutorial screenshot tests to docs-screenshots.spec.ts:
- Datasets list (tutorial_08_sources_tables.png)
- Chart type picker (create_pivot.png)

Also updates DOCS_STATIC/TUTORIAL_DIR path constants and run instructions
to reflect the PLAYWRIGHT_BASE_URL env var override for local Docker use.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-17 09:12:14 -07:00
379 changed files with 7466 additions and 16580 deletions

5
.github/CODEOWNERS vendored
View File

@@ -22,11 +22,6 @@
/.github/ @villebro @geido @eschutho @rusackas @betodealmeida @nytai @mistercrunch @craig-rueda @kgabryje @dpgaspar @sadpandajoe @hainenber
# Notify PMC members of changes to CI-executed scripts (supply-chain risk:
# scripts/ files run directly in CI workflows and can execute arbitrary code)
/scripts/ @villebro @geido @eschutho @rusackas @betodealmeida @nytai @mistercrunch @craig-rueda @kgabryje @dpgaspar @sadpandajoe @hainenber
# Notify PMC members of changes to required GitHub Actions
/.asf.yaml @villebro @geido @eschutho @rusackas @betodealmeida @nytai @mistercrunch @craig-rueda @kgabryje @dpgaspar @Antonio-RiveroMartnez

5
.github/labeler.yml vendored
View File

@@ -17,11 +17,6 @@
- any-glob-to-any-file:
- 'superset/migrations/**'
"risk:ci-script":
- changed-files:
- any-glob-to-any-file:
- 'scripts/**'
############################################
# Dependencies
############################################

View File

@@ -31,7 +31,7 @@ jobs:
working-directory: superset-embedded-sdk
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
- uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6
- uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6
with:
node-version-file: './superset-embedded-sdk/.nvmrc'
registry-url: 'https://registry.npmjs.org'

View File

@@ -19,7 +19,7 @@ jobs:
working-directory: superset-embedded-sdk
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
- uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6
- uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6
with:
node-version-file: './superset-embedded-sdk/.nvmrc'
registry-url: 'https://registry.npmjs.org'

View File

@@ -58,7 +58,7 @@ jobs:
- name: Login to Amazon ECR
if: steps.describe-services.outputs.active == 'true'
id: login-ecr
uses: aws-actions/amazon-ecr-login@19d944daaa35f0fa1d3f7f8af1d3f2e5de25c5b7 # v2
uses: aws-actions/amazon-ecr-login@f2e9fc6c2b355c1890b65e6f6f0e2ac3e6e22f78 # v2
- name: Delete ECR image tag
if: steps.describe-services.outputs.active == 'true'

View File

@@ -199,7 +199,7 @@ jobs:
- name: Login to Amazon ECR
id: login-ecr
uses: aws-actions/amazon-ecr-login@19d944daaa35f0fa1d3f7f8af1d3f2e5de25c5b7 # v2
uses: aws-actions/amazon-ecr-login@f2e9fc6c2b355c1890b65e6f6f0e2ac3e6e22f78 # v2
- name: Load, tag and push image to ECR
id: push-image
@@ -235,7 +235,7 @@ jobs:
- name: Login to Amazon ECR
id: login-ecr
uses: aws-actions/amazon-ecr-login@19d944daaa35f0fa1d3f7f8af1d3f2e5de25c5b7 # v2
uses: aws-actions/amazon-ecr-login@f2e9fc6c2b355c1890b65e6f6f0e2ac3e6e22f78 # v2
- name: Check target image exists in ECR
id: check-image

View File

@@ -17,7 +17,7 @@ jobs:
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
- name: Set up Node.js
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6
uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6
with:
node-version: '20'

View File

@@ -42,7 +42,7 @@ jobs:
echo "HOMEBREW_REPOSITORY=$HOMEBREW_REPOSITORY" >>"${GITHUB_ENV}"
brew install norwoodj/tap/helm-docs
- name: Setup Node.js
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6
uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6
with:
node-version: '20'

View File

@@ -44,7 +44,7 @@ jobs:
- name: Install Node.js
if: env.HAS_TAGS
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6
uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6
with:
node-version-file: './superset-frontend/.nvmrc'

View File

@@ -46,7 +46,7 @@ jobs:
persist-credentials: false
submodules: recursive
- name: Set up Node.js
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6
uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6
with:
node-version-file: './docs/.nvmrc'
- name: Setup Python

View File

@@ -72,7 +72,7 @@ jobs:
persist-credentials: false
submodules: recursive
- name: Set up Node.js
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6
uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6
with:
node-version-file: './docs/.nvmrc'
- name: yarn install
@@ -104,7 +104,7 @@ jobs:
persist-credentials: false
submodules: recursive
- name: Set up Node.js
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6
uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6
with:
node-version-file: './docs/.nvmrc'
- name: yarn install

View File

@@ -109,7 +109,7 @@ jobs:
run: testdata
- name: Setup Node.js
if: steps.check.outputs.python || steps.check.outputs.frontend
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6
uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6
with:
node-version-file: './superset-frontend/.nvmrc'
- name: Install npm dependencies
@@ -146,7 +146,7 @@ jobs:
SAFE_APP_ROOT=${APP_ROOT//\//_}
echo "safe_app_root=$SAFE_APP_ROOT" >> $GITHUB_OUTPUT
- name: Upload Artifacts
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7
if: failure()
with:
path: ${{ github.workspace }}/superset-frontend/cypress-base/cypress/screenshots
@@ -226,7 +226,7 @@ jobs:
run: playwright_testdata
- name: Setup Node.js
if: steps.check.outputs.python || steps.check.outputs.frontend
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6
uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6
with:
node-version-file: './superset-frontend/.nvmrc'
- name: Install npm dependencies
@@ -259,7 +259,7 @@ jobs:
SAFE_APP_ROOT=${APP_ROOT//\//_}
echo "safe_app_root=$SAFE_APP_ROOT" >> $GITHUB_OUTPUT
- name: Upload Playwright Artifacts
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7
if: failure()
with:
path: |

View File

@@ -58,7 +58,7 @@ jobs:
- name: Upload HTML coverage report
if: steps.check.outputs.superset-extensions-cli
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7
with:
name: superset-extensions-cli-coverage-html
path: htmlcov/

View File

@@ -58,7 +58,7 @@ jobs:
- name: Upload Docker Image Artifact
if: steps.check.outputs.frontend
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7
with:
name: docker-image
path: docker-image.tar.zst
@@ -91,7 +91,7 @@ jobs:
"npm run test -- --coverage --shard=${{ matrix.shard }}/8 --coverageReporters=json"
- name: Upload Coverage Artifact
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7
with:
name: coverage-artifacts-${{ matrix.shard }}
path: superset-frontend/coverage

View File

@@ -100,7 +100,7 @@ jobs:
run: playwright_testdata
- name: Setup Node.js
if: steps.check.outputs.python || steps.check.outputs.frontend
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6
uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6
with:
node-version-file: './superset-frontend/.nvmrc'
- name: Install npm dependencies
@@ -133,7 +133,7 @@ jobs:
SAFE_APP_ROOT=${APP_ROOT//\//_}
echo "safe_app_root=$SAFE_APP_ROOT" >> $GITHUB_OUTPUT
- name: Upload Playwright Artifacts
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7
if: failure()
with:
path: |

View File

@@ -101,7 +101,7 @@ jobs:
"
- name: Upload database diagnostics artifact
if: steps.check.outputs.python
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7
with:
name: database-diagnostics
path: databases-diagnostics.json

View File

@@ -31,7 +31,7 @@ jobs:
- name: Setup Node.js
if: steps.check.outputs.frontend
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6
uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6
with:
node-version-file: './superset-frontend/.nvmrc'
- name: Install dependencies

View File

@@ -62,7 +62,7 @@ jobs:
build: "true"
- name: Use Node.js 20
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6
uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6
with:
node-version: 20
@@ -117,7 +117,7 @@ jobs:
fetch-depth: 0
- name: Use Node.js 20
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6
uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6
with:
node-version: 20

View File

@@ -35,7 +35,7 @@ jobs:
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
- name: Set up Node.js
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6
uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6
with:
node-version-file: './superset-frontend/.nvmrc'

1
.gitignore vendored
View File

@@ -62,7 +62,6 @@ rat-results.txt
superset/app/
superset-websocket/config.json
.direnv
*.log
# Node.js, webpack artifacts, storybook
*.entry.js

View File

@@ -458,7 +458,7 @@ cd ../
sed -i '' "s/version_string = .*/version_string = \"$SUPERSET_VERSION\"/" setup.py
# build the python distribution
python -m build
python setup.py sdist
```
Publish to PyPI

View File

@@ -1,162 +0,0 @@
{/*
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.
*/}
---
title: AWS IAM Authentication
sidebar_label: AWS IAM Authentication
sidebar_position: 15
---
# AWS IAM Authentication for AWS Databases
Superset supports IAM-based authentication for **Amazon Aurora** (PostgreSQL and MySQL) and **Amazon Redshift**. IAM auth eliminates the need for database passwords — Superset generates a short-lived auth token using temporary AWS credentials instead.
Cross-account IAM role assumption via STS `AssumeRole` is supported, allowing a Superset deployment in one AWS account to connect to databases in a different account.
## Prerequisites
- Enable the `AWS_DATABASE_IAM_AUTH` feature flag in `superset_config.py`. IAM authentication is gated behind this flag; if it is disabled, connections using `aws_iam` fail with *"AWS IAM database authentication is not enabled."*
```python
FEATURE_FLAGS = {
"AWS_DATABASE_IAM_AUTH": True,
}
```
- `boto3` must be installed in your Superset environment:
```bash
pip install boto3
```
- The Superset server's IAM role (or static credentials) must have permission to call `sts:AssumeRole` (for cross-account) or the same-account permissions for the target service:
- **Aurora (RDS)**: `rds-db:connect`
- **Redshift provisioned**: `redshift:GetClusterCredentials`
- **Redshift Serverless**: `redshift-serverless:GetCredentials` and `redshift-serverless:GetWorkgroup`
- SSL must be enabled on the Aurora / Redshift endpoint (required for IAM token auth).
## Configuration
IAM authentication is configured via the **encrypted_extra** field of the database connection. Access this field in the **Advanced** → **Security** section of the database connection form, under **Secure Extra**.
### Aurora PostgreSQL or Aurora MySQL
```json
{
"aws_iam": {
"enabled": true,
"role_arn": "arn:aws:iam::222222222222:role/SupersetDatabaseAccess",
"external_id": "superset-prod-12345",
"region": "us-east-1",
"db_username": "superset_iam_user",
"session_duration": 3600
}
}
```
| Field | Required | Description |
|-------|----------|-------------|
| `enabled` | Yes | Set to `true` to activate IAM auth |
| `role_arn` | No | ARN of the cross-account IAM role to assume via STS. Omit for same-account auth |
| `external_id` | No | External ID for the STS `AssumeRole` call, if required by the target role's trust policy |
| `region` | Yes | AWS region of the database cluster |
| `db_username` | Yes | The database username associated with the IAM identity |
| `session_duration` | No | STS session duration in seconds (default: `3600`) |
### Redshift (Serverless)
```json
{
"aws_iam": {
"enabled": true,
"role_arn": "arn:aws:iam::222222222222:role/SupersetRedshiftAccess",
"region": "us-east-1",
"workgroup_name": "my-workgroup",
"db_name": "dev"
}
}
```
### Redshift (Provisioned Cluster)
```json
{
"aws_iam": {
"enabled": true,
"role_arn": "arn:aws:iam::222222222222:role/SupersetRedshiftAccess",
"region": "us-east-1",
"cluster_identifier": "my-cluster",
"db_username": "superset_iam_user",
"db_name": "dev"
}
}
```
## Cross-Account IAM Setup
To connect to a database in Account B from a Superset deployment in Account A:
**1. In Account B — create a database-access role:**
```json
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["rds-db:connect"],
"Resource": "arn:aws:rds-db:us-east-1:222222222222:dbuser/db-XXXXXXXXXXXX/superset_iam_user"
}
]
}
```
**Trust policy** (allows Account A's Superset role to assume it):
```json
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::111111111111:role/SupersetInstanceRole"
},
"Action": "sts:AssumeRole",
"Condition": {
"StringEquals": {
"sts:ExternalId": "superset-prod-12345"
}
}
}
]
}
```
**2. In Account A — grant Superset's role permission to assume the Account B role:**
```json
{
"Effect": "Allow",
"Action": "sts:AssumeRole",
"Resource": "arn:aws:iam::222222222222:role/SupersetDatabaseAccess"
}
```
**3. Configure the database connection in Superset** using the `role_arn` and `external_id` from the trust policy (as shown in the configuration example above).
## Credential Caching
STS credentials are cached in memory keyed by `(role_arn, region, external_id)` with a 10-minute TTL. This reduces the number of STS API calls when multiple queries are executed with the same connection. Tokens are refreshed automatically before expiry.

View File

@@ -109,14 +109,6 @@ SECRET_KEY = 'YOUR_OWN_RANDOM_GENERATED_SECRET_KEY'
You can generate a strong secure key with `openssl rand -base64 42`.
Alternatively, you can set the secret key using `SUPERSET_SECRET_KEY` environment variable:
On a Unix-based system, such as Linux or macOS, you can do so by running the following command in your terminal:
```bash
export SUPERSET_SECRET_KEY=$(openssl rand -base64 42)
```
:::caution Use a strong secret key
This key will be used for securely signing session cookies and encrypting sensitive information stored in Superset's application metadata database.
Your deployment must use a complex, unique key.

View File

@@ -10,10 +10,6 @@ version: 1
The superset cli allows you to import and export datasources from and to YAML. Datasources include
databases. The data is expected to be organized in the following hierarchy:
:::info
Superset's ZIP-based import/export also covers **dashboards**, **charts**, and **saved queries**, exercised through the UI and REST API. The [Dashboard Import Overwrite Behavior](#dashboard-import-overwrite-behavior) and [UUIDs in API Responses](#uuids-in-api-responses) sections below document the behavior shared across all asset types.
:::
```text
├──databases
| ├──database_1
@@ -79,29 +75,6 @@ The optional username flag **-u** sets the user used for the datasource import.
superset import_datasources -p <path / filename> -u 'admin'
```
## Dashboard Import Overwrite Behavior
When importing a dashboard ZIP with the **overwrite** option enabled, any existing charts that are part of the dashboard are **replaced** rather than duplicated. This applies to:
- Charts whose UUID matches a chart already present in the target instance
- The full chart configuration (query, visualization type, columns, metrics) is replaced by the imported version
If you import without the overwrite flag, existing charts with conflicting UUIDs are left unchanged and the import skips those objects. Use overwrite when you want to push a fully updated dashboard (including chart definitions) from a development or staging environment to production.
## UUIDs in API Responses
The REST API POST endpoints for **datasets**, **charts**, and **dashboards** include the auto-generated `uuid` field in the response body:
```json
{
"id": 42,
"uuid": "b8a8d5c3-1234-4abc-8def-0123456789ab",
...
}
```
UUIDs remain stable across import/export cycles and can be used for cross-environment workflows — for example, recording a UUID when creating a chart in development and using it to identify the matching chart after importing into production.
## Legacy Importing Datasources
### From older versions of Superset to current version

View File

@@ -501,7 +501,6 @@ All MCP settings go in `superset_config.py`. Defaults are defined in `superset/m
| `MCP_SERVICE_URL` | `None` | Public base URL for MCP-generated links (set this when behind a reverse proxy) |
| `MCP_DEBUG` | `False` | Enable debug logging |
| `MCP_DEV_USERNAME` | -- | Superset username for development mode (no auth) |
| `MCP_PARSE_REQUEST_ENABLED` | `True` | Pre-parse MCP tool inputs from JSON strings into objects. Set to `False` for clients (Claude Desktop, LangChain) that do not double-serialize arguments — this produces cleaner tool schemas for those clients |
### Authentication
@@ -665,32 +664,6 @@ MCP_CSRF_CONFIG = {
---
## Audit Events
All MCP tool calls are logged to Superset's event logger, the same system used by the web UI (viewable at **Settings → Action Log**). Each event captures:
- **Action**: `mcp.<tool_name>.<phase>` (e.g., `mcp.list_databases.query`)
- **User**: the resolved Superset username from the JWT or dev config
- **Timestamp**: when the operation ran
This means MCP activity is auditable alongside normal user activity. No additional configuration is required — logging is on by default whenever the event logger is enabled in your Superset deployment.
## Tool Pagination
MCP list tools (`list_datasets`, `list_charts`, `list_dashboards`, `list_databases`) use **offset pagination** via `page` (1-based) and `page_size` parameters. Responses include `page`, `page_size`, `total_count`, `total_pages`, `has_previous`, and `has_next`. To iterate through all results:
```python
# Example: fetch all charts across pages
all_charts = []
page = 1
while True:
result = mcp.list_charts(page=page, page_size=50)
all_charts.extend(result["charts"])
if not result.get("has_next"):
break
page += 1
```
## Security Best Practices
- **Use TLS** for all production MCP endpoints -- place the server behind a reverse proxy with HTTPS

View File

@@ -63,12 +63,6 @@ by clicking the **Connect** button in the bottom right corner of the modal windo
Congratulations, you've just added a new data source in Superset!
### Sharing a Database Connection
When adding a new database, you can share the connection with other Superset users. Shared connections appear in other users' database lists, making it easier to collaborate on the same data without requiring each user to configure the same connection separately.
To share a connection, enable the **Share connection with other users** option in the **Advanced** tab of the database connection modal before saving. You can change sharing settings later by editing the database connection.
### Registering a new table
Now that youve configured a data source, you can select specific tables (called **Datasets** in Superset)
@@ -86,22 +80,6 @@ we register the **cleaned_sales_data** table from the **examples** database.
To finish, click the **Add** button in the bottom right corner. You should now see your dataset in the list of datasets.
### Organizing Datasets into Folders
The Datasets list view supports **folders** for organizing datasets into groups. To create and manage folders:
1. In the **Datasets** list, click the **Folders** panel on the left sidebar.
2. Click **+ New Folder** to create a top-level folder, or drag an existing folder to nest it.
3. Drag dataset rows onto a folder to move them in, or right-click a dataset and select **Move to folder**.
Folders are per-user organizational aids — they do not affect dataset access permissions or how other users see the datasets.
### Uploading Files via the OS File Manager (PWA)
When Superset is installed as a **Progressive Web App (PWA)** from your browser, your operating system will offer Superset as an option when opening CSV, Excel (`.xls`/`.xlsx`), and Parquet files. Double-clicking or right-clicking a supported file and selecting "Open with Superset" navigates directly to the upload workflow for that file.
To install Superset as a PWA, look for the install icon in your browser's address bar (Chrome, Edge) when visiting your Superset instance over HTTPS. PWA installation requires HTTPS and a valid manifest — your admin needs to confirm the app manifest is served correctly.
### Customizing column properties
Now that you've registered your dataset, you can configure column properties
@@ -256,64 +234,6 @@ For example, when running the local development build, the following will disabl
Top Nav and remove the Filter Bar:
`http://localhost:8088/superset/dashboard/my-dashboard/?standalone=1&show_filters=0`
### AG Grid Interactive Table
The **AG Grid Interactive Table** chart type is Superset's fully-featured data grid, suitable for large paginated datasets where the standard Table chart is not enough.
#### Server-Side Column Filters
AG Grid supports server-side column filters that query the full dataset — not just the loaded page. Filters are applied before data is sent to the browser, so results are correct even across millions of rows.
**Available filter types:**
| Column type | Filter options |
|---|---|
| Text | Contains, equals, starts with, ends with |
| Number | Equals, not equal, less than, greater than, between |
| Date | Before, after, between, blank |
| Set | Select from a list of distinct values |
**AND / OR logic:** Each column supports combining multiple conditions with AND or OR. Filters from different columns are always combined with AND.
**Interaction with pagination:** Server-side filters run as WHERE clauses in the underlying SQL query, so pagination always operates over the already-filtered result set.
#### Time Shift (Time Comparison)
AG Grid Interactive Table supports **Time Shift** (time comparison), matching the behavior of the standard Table chart. In the **Advanced Analytics** → **Time Comparison** section of the chart configuration, enter a shift expression (e.g., `1 year ago`, `minus 7 days`) to add comparison columns showing values from the offset period. Dashboard-level time range overrides apply to both the base and comparison periods.
### Dynamic Currency Formatting
Chart metric values can display currencies dynamically rather than using a fixed currency code. To enable:
1. Open the dataset editor for your dataset (**Datasets → Edit**).
2. In the **Advanced** tab, set **Currency Code Column** to the name of a column in your dataset that contains ISO 4217 currency codes (e.g., `USD`, `EUR`, `GBP`).
3. In the Explore chart configuration, open the metric's **Number format** section and select **Auto-detect** for currency.
When Auto-detect is active, each row uses the currency code from the designated column, so a single chart can display values in multiple currencies — each formatted correctly for its currency.
### ECharts Option Editor
For ECharts-based chart types (line, bar, area, scatter, pie, and others), Explore includes an advanced **ECharts Option Editor** that accepts raw JSON overrides for the underlying ECharts configuration.
Access it via the **Customize** tab → **ECharts Options** section at the bottom of the panel. The JSON you enter is deep-merged on top of Superset's generated ECharts config, so you can override specific options without rewriting the entire config.
**Example:** override the legend position and add a custom title:
```json
{
"legend": { "orient": "vertical", "right": "5%", "top": "middle" },
"title": { "text": "My Custom Title", "left": "center" }
}
```
:::caution
ECharts option overrides bypass Superset's validation layer. Invalid option keys are silently ignored by ECharts. Overrides that conflict with Superset-generated options (e.g., `series`) may produce unexpected results.
:::
### Table Chart: Exporting Filtered Data
When the **Search Box** is visible in a Table chart, the **Download** action exports only the rows currently visible after the search filter is applied — not the full underlying dataset. This matches the visual output and is intentional. To export the full dataset regardless of search state, use the **Download as CSV** option from the chart's three-dot menu in the dashboard or from the Explore chart toolbar before applying a search filter.
:::resources
- [Dashboard Customization](https://docs.preset.io/docs/dashboard-customization) - Advanced dashboard styling and layout options
- [Blog: BI Dashboard Best Practices](https://preset.io/blog/bi-dashboard-best-practices/)

View File

@@ -1,130 +0,0 @@
{/*
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.
*/}
---
title: Embedding Superset
sidebar_position: 6
---
# Embedding Superset
Superset dashboards can be embedded directly in host applications using the `@superset-ui/embedded-sdk` package.
:::info Prerequisites
- The `EMBEDDED_SUPERSET` feature flag must be enabled.
- The embedding domain and allowed origins must be configured by an admin.
:::
## Quick Start
Install the SDK:
```bash
npm install @superset-ui/embedded-sdk
```
Embed a dashboard:
```javascript
import { embedDashboard } from '@superset-ui/embedded-sdk';
embedDashboard({
id: 'dashboard-uuid-here', // from Dashboard → Embed
supersetDomain: 'https://superset.example.com',
mountPoint: document.getElementById('superset-container'),
fetchGuestToken: () => fetchTokenFromYourBackend(),
dashboardUiConfig: {
hideTitle: true,
filters: { expanded: false },
},
});
```
`fetchGuestToken` must return a **guest token** obtained from your server by calling Superset's `/api/v1/security/guest_token/` endpoint with a service account. Do not call this endpoint from client-side code.
---
## Callbacks
### `resolvePermalinkUrl`
When a user copies a permalink from an embedded dashboard, Superset generates a URL on its own domain. In an embedded context this URL is usually not meaningful to the host application's users — the dashboard is rendered inside the host app, not at the Superset URL.
The `resolvePermalinkUrl` callback lets the host app intercept permalink generation and return a URL on the host domain instead:
```javascript
embedDashboard({
id: 'my-dashboard-uuid',
supersetDomain: 'https://superset.example.com',
mountPoint: document.getElementById('superset-container'),
fetchGuestToken: () => fetchGuestToken(),
/**
* Called when Superset generates a permalink.
* @param {Object} args - { key: string } — the permalink key
* @returns {string | null} - your host URL, or null to use Superset's default
*/
resolvePermalinkUrl: ({ key }) => {
return `https://myapp.example.com/dashboard?permalink=${key}`;
},
});
```
If the callback returns `null` or is not provided, Superset uses its own permalink URL as a fallback.
---
## Feature Flags for Embedded Mode
### `DISABLE_EMBEDDED_SUPERSET_LOGOUT`
Hides the logout button when Superset is embedded in a host application. This is useful when the host application manages the session lifecycle and you do not want users to accidentally log out of the embedded Superset session:
```python
# superset_config.py
FEATURE_FLAGS = {
"EMBEDDED_SUPERSET": True,
"DISABLE_EMBEDDED_SUPERSET_LOGOUT": True,
}
```
When enabled, the **Logout** menu item is removed from the user avatar dropdown in the embedded view. The session can still be invalidated server-side by revoking the guest token.
### `EMBEDDED_SUPERSET`
Must be `True` to enable the embedded SDK and the guest token endpoint. Without this flag, `embedDashboard` will fail to load.
---
## URL Parameters
The following URL parameters can be passed through the `urlParams` option in `dashboardUiConfig` or appended to the embedded iframe URL:
| Parameter | Values | Effect |
|-----------|--------|--------|
| `standalone` | `0`, `1`, `2`, `3` | `0`: normal; `1`: hide nav; `2`: hide nav + title; `3`: hide nav + title + tabs |
| `show_filters` | `0`, `1` | Show or hide the native filter bar |
| `expand_filters` | `0`, `1` | Start with filter bar expanded or collapsed |
---
## Security Notes
- **Guest tokens expire** — their lifetime is controlled by the `GUEST_TOKEN_JWT_EXP_SECONDS` config (default: 5 minutes). Refresh tokens before they expire using a token refresh mechanism in your host app.
- **Row-level security** — pass `rls` rules in the guest token request to restrict which rows are visible to the embedded user.
- **Allowed domains** — restrict which host origins can embed a dashboard by setting **Allowed Domains** per-dashboard in the *Embed* settings modal. Superset checks the request's `Referer` header against this list before serving the embedded view; an empty list allows any origin, so configure this explicitly for production.

View File

@@ -329,27 +329,6 @@ various options in this section, refer to the
Lastly, save your chart as Tutorial Resample and add it to the Tutorial Dashboard. Go to the
tutorial dashboard to see the four charts side by side and compare the different outputs.
### SQL Lab Tips
**Schema and table browser**: The left-side table browser uses a collapsible treeview — click a schema to expand its tables, and click a table to see its columns and sample data inline. This makes navigating large schemas much faster than the previous flat list.
**Find in editor**: Press **Ctrl+F** (or **Cmd+F** on Mac) to open the Monaco find/replace widget inside the SQL editor without leaving the editor.
**Resizable panels**: The dividers between the SQL editor, schema browser, and results pane are draggable. Adjust them to match your workflow and screen size.
**Dialect-aware Format SQL**: The **Format SQL** button applies the SQL dialect of the currently selected database — Trino, Presto, MySQL, PostgreSQL, etc. — rather than a generic formatter. Switch to a different database in the toolbar and re-format to get dialect-specific output. Jinja template syntax (`{{ }}`, `{% %}`) is preserved during formatting and will not cause format errors.
### Time Range Natural Language Expressions
The **Custom** time range picker accepts natural language expressions alongside specific dates:
- **Relative**: `Last 7 days`, `Last month`, `Last quarter`, `Last year`
- **Anchored**: `previous calendar week`, `previous calendar month`
- **"First of" expressions**: `first day of this week`, `first day of this month`, `first day of this quarter`, `first day of this year`, `first week of this year`
- **Offsets**: `30 days ago`, `1 year ago`, `next week`
These expressions are evaluated at query time, so saved charts always display data relative to the current date.
:::resources
- [Chart Walkthroughs](https://docs.preset.io/docs/chart-walkthroughs) - Detailed guides for most chart types
- [Blog: Why Apache ECharts is the Future of Apache Superset](https://preset.io/blog/2021-4-1-why-echarts/)

View File

@@ -56,8 +56,8 @@ Ask your AI assistant to browse what's available in your Superset instance:
Describe the visualization you want and AI creates it for you:
- **Create charts from natural language** -- describe what you want to see and AI picks the right chart type, metrics, and dimensions
- **Preview before saving** -- `generate_chart` defaults to `save_chart=False`, showing the chart in Explore before it's committed. Ask AI to save once you're satisfied.
- **Modify existing charts** -- `update_chart` also supports preview mode so you can review changes before saving
- **Preview before saving** -- AI generates a preview so you can review before committing
- **Modify existing charts** -- update filters, change chart types, add metrics
- **Get Explore links** -- open any chart in Superset's Explore view for further refinement
**Example prompts:**
@@ -195,59 +195,27 @@ Ask your admin for the MCP server URL and any authentication tokens you need.
## Available Tools Reference
### Exploration & Discovery
| Tool | Description |
|------|-------------|
| `health_check` | Verify the MCP server is running and connected |
| `get_instance_info` | Get instance statistics (dataset, chart, dashboard counts) |
| `get_schema` | Discover available charts, datasets, and dashboards with schema info |
### Datasets
| Tool | Description |
|------|-------------|
| `list_datasets` | List datasets with filtering and search |
| `get_dataset_info` | Get dataset metadata (columns, metrics, filters) |
| `create_virtual_dataset` | Create a virtual dataset from a SQL query |
### Charts
| Tool | Description |
|------|-------------|
| `list_charts` | List charts with filtering and search |
| `get_chart_info` | Get chart metadata and configuration |
| `get_chart_data` | Retrieve chart data (JSON, CSV, or Excel) |
| `get_chart_preview` | Generate a chart preview (URL, ASCII, table, or Vega-Lite) |
| `get_chart_type_schema` | Get the configuration schema for a chart type |
| `generate_chart` | Create a new chart from a specification (defaults to preview mode — review before saving) |
| `update_chart` | Modify an existing chart's configuration (pass `generate_preview=False` to persist immediately instead of returning a preview URL) |
| `generate_chart` | Create a new chart from a specification |
| `update_chart` | Modify an existing chart's configuration |
| `update_chart_preview` | Update a cached chart preview without saving |
| `generate_explore_link` | Generate an Explore URL for interactive visualization |
### Dashboards
| Tool | Description |
|------|-------------|
| `list_dashboards` | List dashboards with filtering and search |
| `get_dashboard_info` | Get dashboard metadata and layout |
| `generate_dashboard` | Create a new dashboard with specified charts |
| `add_chart_to_existing_dashboard` | Add a chart to an existing dashboard |
### SQL
| Tool | Description |
|------|-------------|
| `execute_sql` | Run a SQL query with RBAC enforcement |
| `save_sql_query` | Persist a SQL query to SQL Lab's saved queries |
| `open_sql_lab_with_context` | Open SQL Lab with a pre-populated query |
### Databases
| Tool | Description |
|------|-------------|
| `list_databases` | List configured database connections |
| `get_database_info` | Get details about a specific database connection |
| `generate_explore_link` | Generate an Explore URL for interactive visualization |
---

View File

@@ -41,12 +41,12 @@
},
"dependencies": {
"@ant-design/icons": "^6.1.1",
"@docusaurus/core": "^3.10.0",
"@docusaurus/core": "3.9.2",
"@docusaurus/faster": "^3.10.0",
"@docusaurus/plugin-client-redirects": "^3.10.0",
"@docusaurus/preset-classic": "3.10.0",
"@docusaurus/theme-live-codeblock": "^3.10.0",
"@docusaurus/theme-mermaid": "^3.10.0",
"@docusaurus/plugin-client-redirects": "3.9.2",
"@docusaurus/preset-classic": "3.9.2",
"@docusaurus/theme-live-codeblock": "^3.9.2",
"@docusaurus/theme-mermaid": "^3.9.2",
"@emotion/core": "^11.0.0",
"@emotion/react": "^11.13.3",
"@emotion/styled": "^11.14.1",
@@ -67,12 +67,12 @@
"@storybook/preview-api": "^8.6.18",
"@storybook/theming": "^8.6.15",
"@superset-ui/core": "^0.20.4",
"@swc/core": "^1.15.30",
"antd": "^6.3.6",
"baseline-browser-mapping": "^2.10.21",
"caniuse-lite": "^1.0.30001790",
"docusaurus-plugin-openapi-docs": "^5.0.1",
"docusaurus-theme-openapi-docs": "^5.0.1",
"@swc/core": "^1.15.24",
"antd": "^6.3.5",
"baseline-browser-mapping": "^2.10.19",
"caniuse-lite": "^1.0.30001788",
"docusaurus-plugin-openapi-docs": "^4.6.0",
"docusaurus-theme-openapi-docs": "^4.6.0",
"js-yaml": "^4.1.1",
"js-yaml-loader": "^1.2.2",
"json-bigint": "^1.0.0",
@@ -98,16 +98,16 @@
"@types/js-yaml": "^4.0.9",
"@types/react": "^19.1.8",
"@typescript-eslint/eslint-plugin": "^8.52.0",
"@typescript-eslint/parser": "^8.59.0",
"@typescript-eslint/parser": "^8.56.1",
"eslint": "^9.39.2",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-prettier": "^5.5.5",
"eslint-plugin-react": "^7.37.5",
"globals": "^17.5.0",
"prettier": "^3.8.3",
"typescript": "~6.0.3",
"typescript-eslint": "^8.59.0",
"webpack": "^5.106.2"
"globals": "^17.4.0",
"prettier": "^3.8.1",
"typescript": "~5.9.3",
"typescript-eslint": "^8.58.0",
"webpack": "^5.105.4"
},
"browserslist": {
"production": [
@@ -124,8 +124,7 @@
"resolutions": {
"react-redux": "^9.2.0",
"@reduxjs/toolkit": "^2.5.0",
"baseline-browser-mapping": "^2.9.19",
"webpackbar": "^7.0.0"
"baseline-browser-mapping": "^2.9.19"
},
"packageManager": "yarn@1.22.22+sha1.ac34549e6aa8e7ead463a7407e1c7390f61a6610"
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 134 KiB

After

Width:  |  Height:  |  Size: 132 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 104 KiB

After

Width:  |  Height:  |  Size: 116 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 118 KiB

After

Width:  |  Height:  |  Size: 118 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 99 KiB

After

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 79 KiB

After

Width:  |  Height:  |  Size: 240 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 84 KiB

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 51 KiB

After

Width:  |  Height:  |  Size: 131 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 85 KiB

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 97 KiB

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 141 KiB

After

Width:  |  Height:  |  Size: 21 KiB

View File

@@ -3,7 +3,6 @@
"extends": "@docusaurus/tsconfig",
"compilerOptions": {
"baseUrl": ".",
"ignoreDeprecations": "6.0",
"skipLibCheck": true,
"noImplicitAny": false,
"strict": false,

View File

@@ -109,14 +109,6 @@ SECRET_KEY = 'YOUR_OWN_RANDOM_GENERATED_SECRET_KEY'
You can generate a strong secure key with `openssl rand -base64 42`.
Alternatively, you can set the secret key using `SUPERSET_SECRET_KEY` environment variable:
On a Unix-based system, such as Linux or macOS, you can do so by running the following command in your terminal:
```bash
export SUPERSET_SECRET_KEY=$(openssl rand -base64 42)
```
:::caution Use a strong secret key
This key will be used for securely signing session cookies and encrypting sensitive information stored in Superset's application metadata database.
Your deployment must use a complex, unique key.

File diff suppressed because it is too large Load Diff

View File

@@ -89,11 +89,10 @@ dependencies = [
"python-dateutil",
"python-dotenv", # optional dependencies for Flask but required for Superset, see https://flask.palletsprojects.com/en/stable/installation/#optional-dependencies
"pygeohash",
"pyarrow>=16.1.0, <21", # before upgrading pyarrow, check that all db dependencies support this, see e.g. https://github.com/apache/superset/pull/34693
"pyarrow>=16.1.0, <19", # before upgrading pyarrow, check that all db dependencies support this, see e.g. https://github.com/apache/superset/pull/34693
"pyyaml>=6.0.0, <7.0.0",
"PyJWT>=2.4.0, <3.0",
"redis>=5.0.0, <6.0",
"rison>=2.0.0, <3.0",
"selenium>=4.14.0, <5.0",
"shillelagh[gsheetsapi]>=1.4.3, <2.0",
"sshtunnel>=0.4.0, <0.5",
@@ -184,7 +183,6 @@ risingwave = ["sqlalchemy-risingwave"]
shillelagh = ["shillelagh[all]>=1.4.3, <2"]
singlestore = ["sqlalchemy-singlestoredb>=1.1.1, <2"]
snowflake = ["snowflake-sqlalchemy>=1.2.4, <2"]
sqlite = ["syntaqlite>=0.1.0"]
spark = [
"pyhive[hive]>=0.6.5;python_version<'3.11'",
"pyhive[hive_pure_sasl]>=0.7",
@@ -228,7 +226,6 @@ development = [
"ruff",
"sqloxide",
"statsd",
"syntaqlite>=0.1.0",
]
[project.urls]
@@ -241,7 +238,7 @@ combine_as_imports = true
include_trailing_comma = true
line_length = 88
known_first_party = "superset, apache-superset-core, apache-superset-extensions-cli"
known_third_party = "alembic, apispec, backoff, celery, click, colorama, cron_descriptor, croniter, cryptography, dateutil, deprecation, flask, flask_appbuilder, flask_babel, flask_caching, flask_compress, flask_jwt_extended, flask_login, flask_migrate, flask_sqlalchemy, flask_talisman, flask_testing, flask_wtf, freezegun, geohash, geopy, holidays, humanize, isodate, jinja2, jwt, markdown, markupsafe, marshmallow, marshmallow-union, msgpack, nh3, numpy, pandas, parameterized, parsedatetime, pgsanity, polyline, rison, progress, pyarrow, sqlalchemy_bigquery, pyhive, pyparsing, pytest, pytest_mock, pytz, redis, requests, selenium, setuptools, shillelagh, simplejson, slack, sqlalchemy, sqlalchemy_utils, syntaqlite, typing_extensions, urllib3, werkzeug, wtforms, wtforms_json, yaml"
known_third_party = "alembic, apispec, backoff, celery, click, colorama, cron_descriptor, croniter, cryptography, dateutil, deprecation, flask, flask_appbuilder, flask_babel, flask_caching, flask_compress, flask_jwt_extended, flask_login, flask_migrate, flask_sqlalchemy, flask_talisman, flask_testing, flask_wtf, freezegun, geohash, geopy, holidays, humanize, isodate, jinja2, jwt, markdown, markupsafe, marshmallow, marshmallow-union, msgpack, nh3, numpy, pandas, parameterized, parsedatetime, pgsanity, polyline, prison, progress, pyarrow, sqlalchemy_bigquery, pyhive, pyparsing, pytest, pytest_mock, pytz, redis, requests, selenium, setuptools, shillelagh, simplejson, slack, sqlalchemy, sqlalchemy_utils, typing_extensions, urllib3, werkzeug, wtforms, wtforms_json, yaml"
multi_line_output = 3
order_by_type = false

View File

@@ -25,16 +25,6 @@ filelock>=3.20.3,<4.0.0
# Security: decompression bomb fix (required by aiohttp 3.13.3)
brotli>=1.2.0,<2.0.0
numexpr>=2.9.0
# Security: CVE-2026-34073 (MEDIUM) - Improper Certificate Validation
cryptography>=46.0.7,<47.0.0
# Security: Snyk - XSS vulnerability in Mako templates
mako>=1.3.11,<2.0.0
# Security: CVE-2024-52338 (CRITICAL) - Deserialization of untrusted data in IPC/Parquet readers
pyarrow>=20.0.0,<21.0.0
# Security: CVE-2026-27459 - pyopenssl certificate validation
pyopenssl>=26.0.0,<27.0.0
# Security: CVE-2026-25645 (MEDIUM) - Insecure Temporary File
requests>=2.33.0,<3.0.0
# 5.0.0 has a sensitive deprecation used in other libs
# -> https://github.com/aio-libs/async-timeout/blob/master/CHANGES.rst#500-2024-10-31

View File

@@ -86,9 +86,8 @@ cron-descriptor==1.4.5
# via apache-superset (pyproject.toml)
croniter==6.0.0
# via apache-superset (pyproject.toml)
cryptography==46.0.7
cryptography==46.0.6
# via
# -r requirements/base.in
# apache-superset (pyproject.toml)
# paramiko
# pyopenssl
@@ -206,9 +205,8 @@ kombu==5.5.3
# via celery
limits==5.1.0
# via flask-limiter
mako==1.3.11
mako==1.3.10
# via
# -r requirements/base.in
# apache-superset (pyproject.toml)
# alembic
markdown==3.8.1
@@ -249,6 +247,7 @@ numpy==1.26.4
# bottleneck
# numexpr
# pandas
# pyarrow
odfpy==1.4.1
# via pandas
openapi-schema-validator==0.6.3
@@ -280,7 +279,7 @@ parsedatetime==2.6
# via apache-superset (pyproject.toml)
pgsanity==0.2.9
# via apache-superset (pyproject.toml)
pillow==12.2.0
pillow==12.1.1
# via apache-superset (pyproject.toml)
platformdirs==4.3.8
# via requests-cache
@@ -292,10 +291,8 @@ prison==0.2.1
# via flask-appbuilder
prompt-toolkit==3.0.51
# via click-repl
pyarrow==20.0.0
# via
# -r requirements/base.in
# apache-superset (pyproject.toml)
pyarrow==16.1.0
# via apache-superset (pyproject.toml)
pyasn1==0.6.3
# via
# pyasn1-modules
@@ -322,10 +319,8 @@ pyjwt==2.12.0
# redis
pynacl==1.6.2
# via paramiko
pyopenssl==26.0.0
# via
# -r requirements/base.in
# shillelagh
pyopenssl==25.3.0
# via shillelagh
pyparsing==3.2.3
# via apache-superset (pyproject.toml)
pysocks==1.7.1
@@ -358,9 +353,8 @@ referencing==0.36.2
# via
# jsonschema
# jsonschema-specifications
requests==2.33.0
requests==2.32.4
# via
# -r requirements/base.in
# requests-cache
# shillelagh
requests-cache==1.2.1
@@ -369,8 +363,6 @@ rfc3339-validator==0.1.4
# via openapi-schema-validator
rich==13.9.4
# via flask-limiter
rison==2.0.0
# via apache-superset (pyproject.toml)
rpds-py==0.25.0
# via
# jsonschema

View File

@@ -178,7 +178,7 @@ croniter==6.0.0
# via
# -c requirements/base-constraint.txt
# apache-superset
cryptography==46.0.7
cryptography==46.0.6
# via
# -c requirements/base-constraint.txt
# apache-superset
@@ -503,7 +503,7 @@ limits==5.1.0
# via
# -c requirements/base-constraint.txt
# flask-limiter
mako==1.3.11
mako==1.3.10
# via
# -c requirements/base-constraint.txt
# alembic
@@ -580,6 +580,7 @@ numpy==1.26.4
# pandas
# pandas-gbq
# prophet
# pyarrow
oauthlib==3.2.2
# via requests-oauthlib
odfpy==1.4.1
@@ -654,7 +655,7 @@ pgsanity==0.2.9
# via
# -c requirements/base-constraint.txt
# apache-superset
pillow==12.2.0
pillow==12.1.1
# via
# -c requirements/base-constraint.txt
# apache-superset
@@ -709,7 +710,7 @@ psycopg2-binary==2.9.9
# via apache-superset
py-key-value-aio==0.4.4
# via fastmcp
pyarrow==20.0.0
pyarrow==16.1.0
# via
# -c requirements/base-constraint.txt
# apache-superset
@@ -777,7 +778,7 @@ pynacl==1.6.2
# via
# -c requirements/base-constraint.txt
# paramiko
pyopenssl==26.0.0
pyopenssl==25.3.0
# via
# -c requirements/base-constraint.txt
# shillelagh
@@ -864,7 +865,7 @@ referencing==0.36.2
# jsonschema
# jsonschema-path
# jsonschema-specifications
requests==2.33.0
requests==2.32.4
# via
# -c requirements/base-constraint.txt
# docker
@@ -896,10 +897,6 @@ rich==13.9.4
# rich-rst
rich-rst==1.3.1
# via cyclopts
rison==2.0.0
# via
# -c requirements/base-constraint.txt
# apache-superset
rpds-py==0.25.0
# via
# -c requirements/base-constraint.txt
@@ -995,8 +992,6 @@ starlette==0.49.1
# via mcp
statsd==4.0.1
# via apache-superset
syntaqlite==0.1.0
# via apache-superset
tabulate==0.9.0
# via
# -c requirements/base-constraint.txt

View File

@@ -33,33 +33,6 @@
// - No FontAwesome icons (use Icons component)
// - No template variables in i18n (use parameterized messages)
// === Rules carried over from ESLint that oxlint does NOT implement ===
// oxlint 1.58+ errors on unknown builtin rules, so these can no longer
// be listed in this config. They were silently dropped in earlier
// oxlint versions (not actually enforced). Documented here for future
// maintainers — if/when oxlint adds them, re-enable in the relevant
// plugin section above.
// import: newline-after-import, no-extraneous-dependencies,
// no-import-module-exports, no-relative-packages,
// no-unresolved, no-useless-path-segments
// react: default-props-match-prop-types, destructuring-assignment,
// forbid-component-props, forbid-foreign-prop-types,
// forbid-prop-types, function-component-definition,
// jsx-no-bind, jsx-uses-vars, no-access-state-in-setstate,
// no-deprecated, no-did-update-set-state, no-typos,
// no-unstable-nested-components,
// no-unused-class-component-methods, no-unused-prop-types,
// no-unused-state, prefer-stateless-function, prop-types,
// require-default-props, sort-comp, static-property-placement
// (prefer-stateless-function / function-component-definition
// are represented by react/prefer-function-component below)
// jsx-a11y: interactive-supports-focus,
// no-interactive-element-to-noninteractive-role,
// no-noninteractive-element-interactions,
// no-noninteractive-element-to-interactive-role
// typescript: naming-convention
// unicorn: prevent-abbreviations
// === Core ESLint rules ===
// Error prevention
"no-console": "warn",
@@ -116,6 +89,7 @@
"no-object-constructor": "error",
// === Import plugin rules ===
"import/no-unresolved": "error",
// TODO: Fix incorrect named imports in Storybook and other files
"import/named": "warn",
// TODO: Fix duplicate exports in shared-controls and other modules
@@ -131,24 +105,56 @@
"import/first": "error",
// TODO: Consolidate duplicate imports in DatasetList and other files
"import/no-duplicates": "warn",
"import/newline-after-import": "error",
"import/no-absolute-path": "error",
"import/no-dynamic-require": "error",
"import/no-webpack-loader-syntax": "error",
"import/no-self-import": "error",
"import/no-cycle": "off",
"import/no-useless-path-segments": ["error", { "commonjs": true }],
"import/prefer-default-export": "off",
"import/no-relative-packages": "off",
"import/no-import-module-exports": "off",
"import/no-extraneous-dependencies": [
"error",
{
"devDependencies": [
"test/**",
"tests/**",
"spec/**",
"**/__tests__/**",
"**/__mocks__/**",
"*.test.{js,jsx,ts,tsx}",
"*.spec.{js,jsx,ts,tsx}",
"**/*.test.{js,jsx,ts,tsx}",
"**/*.spec.{js,jsx,ts,tsx}",
"**/jest.config.js",
"**/jest.setup.js",
"**/webpack.config.js",
"**/webpack.config.*.js",
"**/.eslintrc.js"
],
"optionalDependencies": false
}
],
// === React plugin rules ===
"react/prop-types": "off",
"react/require-default-props": "off",
"react/forbid-prop-types": "off",
"react/forbid-component-props": "warn",
"react/jsx-filename-extension": [
"warn",
{ "extensions": [".jsx", ".tsx"] }
],
"react/jsx-fragments": "error",
"react/jsx-no-bind": "off",
"react/jsx-props-no-spreading": "off",
"react/jsx-boolean-value": ["error", "never", { "always": [] }],
"react/jsx-no-duplicate-props": "error",
"react/jsx-no-undef": "error",
"react/jsx-pascal-case": ["error", { "allowAllCaps": true, "ignore": [] }],
"react/jsx-uses-vars": "error",
"react/jsx-no-target-blank": ["error", { "enforceDynamicLinks": "always" }],
"react/jsx-no-comment-textnodes": "error",
"react/jsx-no-useless-fragment": "off",
@@ -159,27 +165,40 @@
"react/no-array-index-key": "off",
"react/no-children-prop": "error",
"react/no-danger": "error",
"react/forbid-foreign-prop-types": "error",
"react/no-danger-with-children": "error",
"react/no-deprecated": "error",
"react/no-did-update-set-state": "error",
"react/no-find-dom-node": "error",
"react/no-is-mounted": "error",
"react/no-render-return-value": "error",
"react/no-string-refs": "off",
"react/no-unescaped-entities": "off",
"react/no-unknown-property": "off",
"react/no-unused-prop-types": "off",
"react/no-unused-state": "error",
"react/no-will-update-set-state": "error",
"react/prefer-es6-class": ["error", "always"],
"react/prefer-stateless-function": [
"error",
{ "ignorePureComponents": true }
],
"react/require-render-return": "error",
"react/self-closing-comp": "error",
"react/void-dom-elements-no-children": "error",
"react/no-access-state-in-setstate": "error",
"react/no-redundant-should-component-update": "error",
"react/no-this-in-sfc": "error",
"react/no-typos": "error",
"react/no-unstable-nested-components": "off",
"react/no-unused-class-component-methods": "off",
"react/destructuring-assignment": "off",
"react/sort-comp": "off",
"react/state-in-constructor": "off",
"react/static-property-placement": "off",
"react/react-in-jsx-scope": "off",
// Successor to the ESLint-era `react/prefer-stateless-function` and
// `react/function-component-definition` rules. Disabled because the
// codebase still contains legacy class components; flip to "error"
// once the class-to-function migration completes.
"react/prefer-function-component": "off",
"react/function-component-definition": "off",
"react/default-props-match-prop-types": "off",
"react/button-has-type": [
"error",
{ "button": true, "submit": true, "reset": false }
@@ -204,6 +223,7 @@
"jsx-a11y/html-has-lang": "error",
"jsx-a11y/iframe-has-title": "error",
"jsx-a11y/img-redundant-alt": "error",
"jsx-a11y/interactive-supports-focus": "error",
"jsx-a11y/label-has-associated-control": "error",
"jsx-a11y/lang": "error",
"jsx-a11y/media-has-caption": "error",
@@ -211,6 +231,9 @@
"jsx-a11y/no-access-key": "error",
"jsx-a11y/no-autofocus": ["error", { "ignoreNonDOM": true }],
"jsx-a11y/no-distracting-elements": "error",
"jsx-a11y/no-interactive-element-to-noninteractive-role": "error",
"jsx-a11y/no-noninteractive-element-interactions": "error",
"jsx-a11y/no-noninteractive-element-to-interactive-role": "error",
"jsx-a11y/no-noninteractive-tabindex": "error",
"jsx-a11y/no-redundant-roles": "error",
"jsx-a11y/no-static-element-interactions": "off",
@@ -230,6 +253,17 @@
"@typescript-eslint/explicit-module-boundary-types": "off",
"@typescript-eslint/no-unused-vars": "warn",
"@typescript-eslint/prefer-optional-chain": "error",
"@typescript-eslint/naming-convention": [
"error",
{
"selector": "enum",
"format": ["PascalCase"]
},
{
"selector": "enumMember",
"format": ["PascalCase"]
}
],
// === Unicorn rules (bonus coverage) ===
"unicorn/no-new-array": "error",
@@ -245,6 +279,7 @@
"unicorn/prefer-negative-index": "error",
"unicorn/prefer-math-trunc": "error",
"unicorn/filename-case": "off",
"unicorn/prevent-abbreviations": "off",
"unicorn/no-null": "off",
"unicorn/no-array-reduce": "off",
"unicorn/no-array-for-each": "off",

File diff suppressed because it is too large Load Diff

View File

@@ -154,12 +154,12 @@
"@visx/scale": "^3.5.0",
"@visx/tooltip": "^3.0.0",
"@visx/xychart": "^3.5.1",
"ag-grid-community": "35.2.1",
"ag-grid-react": "35.2.1",
"ag-grid-community": "35.0.1",
"ag-grid-react": "35.0.1",
"antd": "^5.26.0",
"chrono-node": "^2.9.0",
"classnames": "^2.2.5",
"content-disposition": "^1.1.0",
"content-disposition": "^1.0.1",
"d3-color": "^3.1.0",
"d3-scale": "^4.0.2",
"dayjs": "^1.11.20",
@@ -170,9 +170,9 @@
"fs-extra": "^11.3.4",
"fuse.js": "^7.3.0",
"geolib": "^3.3.14",
"geostyler": "^18.5.0",
"geostyler": "^18.3.1",
"geostyler-data": "^1.1.0",
"geostyler-openlayers-parser": "^5.7.0",
"geostyler-openlayers-parser": "^5.4.1",
"geostyler-style": "11.0.2",
"geostyler-wfs-parser": "^3.0.1",
"google-auth-library": "^10.6.2",
@@ -183,21 +183,21 @@
"json-bigint": "^1.0.0",
"json-stringify-pretty-compact": "^2.0.0",
"lodash": "^4.18.1",
"mapbox-gl": "^3.22.0",
"markdown-to-jsx": "^9.7.16",
"match-sorter": "^8.3.0",
"mapbox-gl": "^3.20.0",
"markdown-to-jsx": "^9.7.15",
"match-sorter": "^8.2.0",
"memoize-one": "^5.2.1",
"mousetrap": "^1.6.5",
"mustache": "^4.2.0",
"nanoid": "^5.1.9",
"ol": "^10.9.0",
"nanoid": "^5.1.7",
"ol": "^10.8.0",
"pretty-ms": "^9.3.0",
"query-string": "9.3.1",
"re-resizable": "^6.11.2",
"react": "^17.0.2",
"react-arborist": "^3.5.0",
"react-checkbox-tree": "^2.0.1",
"react-diff-viewer-continued": "^4.2.2",
"react-arborist": "^3.4.3",
"react-checkbox-tree": "^1.8.0",
"react-diff-viewer-continued": "^4.2.0",
"react-dnd": "^11.1.3",
"react-dnd-html5-backend": "^11.1.3",
"react-dom": "^17.0.2",
@@ -230,7 +230,7 @@
"use-event-callback": "^0.1.0",
"use-immer": "^0.11.0",
"use-query-params": "^2.2.2",
"uuid": "^14.0.0",
"uuid": "^13.0.0",
"xlsx": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz",
"yargs": "^17.7.2"
},
@@ -258,19 +258,19 @@
"@mihkeleidast/storybook-addon-source": "^1.0.1",
"@playwright/test": "^1.59.1",
"@pmmmwh/react-refresh-webpack-plugin": "^0.6.2",
"@storybook/addon-actions": "^8.6.18",
"@storybook/addon-controls": "^8.6.18",
"@storybook/addon-essentials": "^8.6.18",
"@storybook/addon-links": "^8.6.18",
"@storybook/addon-mdx-gfm": "^8.6.18",
"@storybook/components": "^8.6.18",
"@storybook/preview-api": "^8.6.18",
"@storybook/react": "^8.6.18",
"@storybook/react-webpack5": "^8.6.18",
"@storybook/test": "^8.6.18",
"@storybook/addon-actions": "^8.6.17",
"@storybook/addon-controls": "^8.6.17",
"@storybook/addon-essentials": "^8.6.17",
"@storybook/addon-links": "^8.6.17",
"@storybook/addon-mdx-gfm": "^8.6.17",
"@storybook/components": "^8.6.17",
"@storybook/preview-api": "^8.6.17",
"@storybook/react": "^8.6.17",
"@storybook/react-webpack5": "^8.6.17",
"@storybook/test": "^8.6.15",
"@storybook/test-runner": "^0.17.0",
"@svgr/webpack": "^8.1.0",
"@swc/core": "^1.15.30",
"@swc/core": "^1.15.24",
"@swc/plugin-emotion": "^14.8.0",
"@swc/plugin-transform-imports": "^12.5.0",
"@testing-library/dom": "^8.20.1",
@@ -281,7 +281,6 @@
"@types/content-disposition": "^0.5.9",
"@types/dom-to-image": "^2.6.7",
"@types/jest": "^30.0.0",
"@types/jquery": "^4.0.0",
"@types/js-levenshtein": "^1.1.3",
"@types/json-bigint": "^1.0.4",
"@types/mousetrap": "^1.6.15",
@@ -299,14 +298,14 @@
"@types/rison": "0.1.0",
"@types/tinycolor2": "^1.4.3",
"@types/unzipper": "^0.10.11",
"@typescript-eslint/eslint-plugin": "^8.59.0",
"@typescript-eslint/parser": "^8.58.2",
"@typescript-eslint/eslint-plugin": "^7.18.0",
"@typescript-eslint/parser": "^7.18.0",
"babel-jest": "^30.0.2",
"babel-loader": "^10.1.1",
"babel-plugin-dynamic-import-node": "^2.3.3",
"babel-plugin-jsx-remove-data-test-id": "^3.0.0",
"babel-plugin-lodash": "^3.3.4",
"baseline-browser-mapping": "^2.10.21",
"baseline-browser-mapping": "^2.10.16",
"cheerio": "1.2.0",
"concurrently": "^9.2.1",
"copy-webpack-plugin": "^14.0.0",
@@ -326,14 +325,14 @@
"eslint-plugin-no-only-tests": "^3.3.0",
"eslint-plugin-prettier": "^5.5.5",
"eslint-plugin-react-prefer-function-component": "^5.0.0",
"eslint-plugin-react-you-might-not-need-an-effect": "^0.9.3",
"eslint-plugin-react-you-might-not-need-an-effect": "^0.9.2",
"eslint-plugin-storybook": "^0.8.0",
"eslint-plugin-testing-library": "^7.16.2",
"eslint-plugin-theme-colors": "file:eslint-rules/eslint-plugin-theme-colors",
"fetch-mock": "^12.6.0",
"fork-ts-checker-webpack-plugin": "^9.1.0",
"history": "^5.3.0",
"html-webpack-plugin": "^5.6.7",
"html-webpack-plugin": "^5.6.6",
"http-server": "^14.1.1",
"imports-loader": "^5.0.0",
"jest": "^30.3.0",
@@ -346,9 +345,9 @@
"lightningcss": "^1.32.0",
"mini-css-extract-plugin": "^2.10.2",
"open-cli": "^9.0.0",
"oxlint": "^1.61.0",
"oxlint": "^1.56.0",
"po2json": "^0.4.5",
"prettier": "3.8.3",
"prettier": "3.8.2",
"prettier-plugin-packagejson": "^3.0.2",
"process": "^0.11.10",
"react-refresh": "^0.18.0",
@@ -357,10 +356,10 @@
"source-map": "^0.7.6",
"source-map-support": "^0.5.21",
"speed-measure-webpack-plugin": "^1.6.0",
"storybook": "8.6.18",
"storybook": "8.6.17",
"style-loader": "^4.0.0",
"swc-loader": "^0.2.7",
"terser-webpack-plugin": "^5.5.0",
"terser-webpack-plugin": "^5.4.0",
"thread-loader": "^4.0.4",
"ts-jest": "^29.4.9",
"tscw-config": "^1.1.2",
@@ -369,12 +368,12 @@
"unzipper": "^0.12.3",
"vm-browserify": "^1.1.2",
"wait-on": "^9.0.5",
"webpack": "^5.106.2",
"webpack": "^5.106.0",
"webpack-bundle-analyzer": "^5.3.0",
"webpack-cli": "^6.0.1",
"webpack-dev-server": "^5.2.3",
"webpack-manifest-plugin": "^5.0.1",
"webpack-sources": "^3.4.0",
"webpack-sources": "^3.3.4",
"webpack-visualizer-plugin2": "^2.0.0"
},
"peerDependencies": {

View File

@@ -23,7 +23,7 @@ import { ControlPanelSectionConfig } from '../types';
import { formatSelectOptions } from '../utils';
export const TITLE_MARGIN_OPTIONS: number[] = [
0, 15, 30, 40, 50, 75, 100, 125, 150, 200,
0, 15, 30, 50, 75, 100, 125, 150, 200,
];
export const TITLE_POSITION_OPTIONS: [string, string][] = [
['Left', t('Left')],
@@ -56,7 +56,7 @@ export const titleControls: ControlPanelSectionConfig = {
clearable: true,
label: t('X Axis Title Margin'),
renderTrigger: true,
default: TITLE_MARGIN_OPTIONS[3],
default: TITLE_MARGIN_OPTIONS[0],
choices: formatSelectOptions(TITLE_MARGIN_OPTIONS),
},
},
@@ -82,7 +82,7 @@ export const titleControls: ControlPanelSectionConfig = {
clearable: true,
label: t('Y Axis Title Margin'),
renderTrigger: true,
default: TITLE_MARGIN_OPTIONS[4],
default: TITLE_MARGIN_OPTIONS[0],
choices: formatSelectOptions(TITLE_MARGIN_OPTIONS),
},
},

View File

@@ -30,8 +30,8 @@
"@types/json-bigint": "^1.0.4",
"@visx/responsive": "^3.12.0",
"ace-builds": "^1.43.6",
"ag-grid-community": "35.2.1",
"ag-grid-react": "35.2.1",
"ag-grid-community": "35.0.1",
"ag-grid-react": "35.0.1",
"brace": "^0.11.1",
"classnames": "^2.5.1",
"core-js": "^3.49.0",
@@ -42,7 +42,7 @@
"d3-time": "^3.1.0",
"d3-time-format": "^4.1.0",
"dayjs": "^1.11.20",
"dompurify": "^3.4.1",
"dompurify": "^3.3.3",
"fetch-retry": "^6.0.0",
"handlebars": "^4.7.9",
"jed": "^1.1.1",
@@ -56,7 +56,7 @@
"react-js-cron": "^5.2.0",
"react-markdown": "^8.0.7",
"react-resize-detector": "^7.1.2",
"react-syntax-highlighter": "^16.1.1",
"react-syntax-highlighter": "^16.1.0",
"react-ultimate-pagination": "^1.3.2",
"regenerator-runtime": "^0.14.1",
"rehype-raw": "^7.0.0",
@@ -74,7 +74,7 @@
"@types/d3-scale": "^2.1.1",
"@types/d3-time": "^3.0.4",
"@types/d3-time-format": "^4.0.3",
"@types/jquery": "^4.0.0",
"@types/jquery": "^3.5.33",
"@types/lodash": "^4.17.24",
"@types/node": "^25.6.0",
"@types/prop-types": "^15.7.15",
@@ -85,7 +85,7 @@
"fetch-mock": "^12.6.0",
"jest-mock-console": "^2.0.0",
"resize-observer-polyfill": "1.5.1",
"timezone-mock": "^1.4.2"
"timezone-mock": "1.4.0"
},
"peerDependencies": {
"@emotion/cache": "^11.4.0",

View File

@@ -17,7 +17,7 @@
* under the License.
*/
import { memo, ReactNode } from 'react';
import { PureComponent, ReactNode } from 'react';
import { isDefined } from '../utils';
@@ -29,7 +29,7 @@ type Props = {
contentWidth?: number;
contentHeight?: number;
height: number;
renderContent?: ({
renderContent: ({
height,
width,
}: {
@@ -39,35 +39,36 @@ type Props = {
width: number;
};
function ChartFrame({
contentWidth,
contentHeight,
width,
height,
renderContent = () => null,
}: Props) {
const overflowX = checkNumber(contentWidth) && contentWidth > width;
const overflowY = checkNumber(contentHeight) && contentHeight > height;
export default class ChartFrame extends PureComponent<Props, {}> {
static defaultProps = {
renderContent() {},
};
if (overflowX || overflowY) {
return (
<div
style={{
height,
overflowX: overflowX ? 'auto' : 'hidden',
overflowY: overflowY ? 'auto' : 'hidden',
width,
}}
>
{renderContent({
height: Math.max(contentHeight ?? 0, height),
width: Math.max(contentWidth ?? 0, width),
})}
</div>
);
render() {
const { contentWidth, contentHeight, width, height, renderContent } =
this.props;
const overflowX = checkNumber(contentWidth) && contentWidth > width;
const overflowY = checkNumber(contentHeight) && contentHeight > height;
if (overflowX || overflowY) {
return (
<div
style={{
height,
overflowX: overflowX ? 'auto' : 'hidden',
overflowY: overflowY ? 'auto' : 'hidden',
width,
}}
>
{renderContent({
height: Math.max(contentHeight ?? 0, height),
width: Math.max(contentWidth ?? 0, width),
})}
</div>
);
}
return renderContent({ height, width });
}
return <>{renderContent({ height, width })}</>;
}
export default memo(ChartFrame);

View File

@@ -17,19 +17,26 @@
* under the License.
*/
import { CSSProperties, ReactNode, memo, useMemo } from 'react';
import { CSSProperties, ReactNode, PureComponent } from 'react';
import { ParentSize } from '@visx/responsive';
const defaultProps = {
className: '',
height: 'auto' as number | string,
position: 'top',
width: 'auto' as number | string,
};
type Props = {
className?: string;
className: string;
debounceTime?: number;
width?: number | string;
height?: number | string;
width: number | string;
height: number | string;
legendJustifyContent?: 'center' | 'flex-start' | 'flex-end';
position?: 'top' | 'left' | 'bottom' | 'right';
position: 'top' | 'left' | 'bottom' | 'right';
renderChart: (dim: { width: number; height: number }) => ReactNode;
renderLegend?: (params: { direction: string }) => ReactNode;
};
} & Readonly<typeof defaultProps>;
const LEGEND_STYLE_BASE: CSSProperties = {
display: 'flex',
@@ -45,101 +52,95 @@ const CHART_STYLE_BASE: CSSProperties = {
position: 'relative',
};
function getContainerDirection(
position: Props['position'],
): CSSProperties['flexDirection'] {
if (position === 'left') {
return 'row';
}
if (position === 'right') {
return 'row-reverse';
}
if (position === 'bottom') {
return 'column-reverse';
class WithLegend extends PureComponent<Props, {}> {
static defaultProps = defaultProps;
getContainerDirection(): CSSProperties['flexDirection'] {
const { position } = this.props;
if (position === 'left') {
return 'row';
}
if (position === 'right') {
return 'row-reverse';
}
if (position === 'bottom') {
return 'column-reverse';
}
return 'column';
}
return 'column';
}
getLegendJustifyContent() {
const { legendJustifyContent, position } = this.props;
if (legendJustifyContent) {
return legendJustifyContent;
}
function getLegendJustifyContent(
legendJustifyContent: Props['legendJustifyContent'],
position: Props['position'],
) {
if (legendJustifyContent) {
return legendJustifyContent;
if (position === 'left' || position === 'right') {
return 'flex-start';
}
return 'flex-end';
}
if (position === 'left' || position === 'right') {
return 'flex-start';
}
render() {
const {
className,
debounceTime,
width,
height,
position,
renderChart,
renderLegend,
} = this.props;
return 'flex-end';
}
const isHorizontal = position === 'left' || position === 'right';
function WithLegend({
className = '',
debounceTime,
width = 'auto',
height = 'auto',
legendJustifyContent,
position = 'top',
renderChart,
renderLegend,
}: Props) {
const isHorizontal = position === 'left' || position === 'right';
const style: CSSProperties = useMemo(
() => ({
const style: CSSProperties = {
display: 'flex',
flexDirection: getContainerDirection(position),
flexDirection: this.getContainerDirection(),
height,
width,
}),
[position, height, width],
);
};
const chartStyle: CSSProperties = useMemo(() => {
const baseStyle = { ...CHART_STYLE_BASE };
const chartStyle: CSSProperties = { ...CHART_STYLE_BASE };
if (isHorizontal) {
baseStyle.width = 0;
chartStyle.width = 0;
} else {
baseStyle.height = 0;
chartStyle.height = 0;
}
return baseStyle;
}, [isHorizontal]);
const legendDirection = isHorizontal ? 'column' : 'row';
const legendStyle: CSSProperties = useMemo(
() => ({
const legendDirection = isHorizontal ? 'column' : 'row';
const legendStyle: CSSProperties = {
...LEGEND_STYLE_BASE,
flexDirection: legendDirection,
justifyContent: getLegendJustifyContent(legendJustifyContent, position),
}),
[legendDirection, legendJustifyContent, position],
);
justifyContent: this.getLegendJustifyContent(),
};
return (
<div className={`with-legend ${className}`} style={style}>
{renderLegend && (
<div className="legend-container" style={legendStyle}>
{renderLegend({
// Pass flexDirection for @vx/legend to arrange legend items
direction: legendDirection,
})}
return (
<div className={`with-legend ${className}`} style={style}>
{renderLegend && (
<div className="legend-container" style={legendStyle}>
{renderLegend({
// Pass flexDirection for @vx/legend to arrange legend items
direction: legendDirection,
})}
</div>
)}
<div className="main-container" style={chartStyle}>
<ParentSize debounceTime={debounceTime}>
{(parent: { width: number; height: number }) =>
parent.width > 0 && parent.height > 0
? // Only render when necessary
renderChart(parent)
: null
}
</ParentSize>
</div>
)}
<div className="main-container" style={chartStyle}>
<ParentSize debounceTime={debounceTime}>
{(parent: { width: number; height: number }) =>
parent.width > 0 && parent.height > 0
? // Only render when necessary
renderChart(parent)
: null
}
</ParentSize>
</div>
</div>
);
);
}
}
export default memo(WithLegend);
export default WithLegend;

View File

@@ -17,21 +17,31 @@
* under the License.
*/
import { memo, ReactNode } from 'react';
import { PureComponent, ReactNode } from 'react';
const defaultProps = {
className: '',
};
type Props = {
className?: string;
children: ReactNode;
};
} & Readonly<typeof defaultProps>;
const CONTAINER_STYLE = { padding: 8 };
function TooltipFrame({ className = '', children }: Props) {
return (
<div className={className} style={CONTAINER_STYLE}>
{children}
</div>
);
class TooltipFrame extends PureComponent<Props, {}> {
static defaultProps = defaultProps;
render() {
const { className, children } = this.props;
return (
<div className={className} style={CONTAINER_STYLE}>
{children}
</div>
);
}
}
export default memo(TooltipFrame);
export default TooltipFrame;

View File

@@ -90,7 +90,6 @@ import {
InfoCircleFilled,
InsertRowAboveOutlined,
InsertRowBelowOutlined,
LeftOutlined,
LineChartOutlined,
LineOutlined,
LinkOutlined,
@@ -247,7 +246,6 @@ const AntdIcons = {
InfoCircleFilled,
InsertRowAboveOutlined,
InsertRowBelowOutlined,
LeftOutlined,
LineChartOutlined,
LineOutlined,
LinkOutlined,

View File

@@ -95,13 +95,10 @@ const TitleLink = styled.span`
const TitleRight = styled.span`
${({ theme }) => css`
position: absolute;
right: -1px;
font-weight: 400;
bottom: ${theme.sizeUnit * 3}px;
right: ${theme.sizeUnit * 2}px;
max-width: 120px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
`}
`;
const CoverFooter = styled.div`
@@ -247,11 +244,7 @@ function ListViewCard({
{title}
</TitleLink>
</Tooltip>
{titleRight && (
<Tooltip title={titleRight}>
<TitleRight>{titleRight}</TitleRight>
</Tooltip>
)}
{titleRight && <TitleRight>{titleRight}</TitleRight>}
<div className="card-actions" data-test="card-actions">
{actions}
</div>

View File

@@ -227,15 +227,8 @@ const CustomModal = ({
draggableConfig,
destroyOnHidden,
openerRef,
bodyStyle,
styles: stylesProp,
...rest
}: ModalProps) => {
// Convert deprecated bodyStyle to styles.body
const styles = useMemo(
() => (bodyStyle ? { ...stylesProp, body: bodyStyle } : stylesProp),
[bodyStyle, stylesProp],
);
const draggableRef = useRef<HTMLDivElement>(null);
const [bounds, setBounds] = useState<DraggableBounds>();
const [dragDisabled, setDragDisabled] = useState<boolean>(true);
@@ -368,7 +361,6 @@ const CustomModal = ({
draggable={draggable}
resizable={resizable}
destroyOnHidden={destroyOnHidden}
styles={styles}
{...rest}
>
{children}

View File

@@ -51,9 +51,7 @@ export interface ModalProps {
destroyOnHidden?: boolean;
maskClosable?: boolean;
zIndex?: number;
/** @deprecated Use styles.body instead */
bodyStyle?: CSSProperties;
styles?: { body?: CSSProperties; [key: string]: CSSProperties | undefined };
openerRef?: React.RefObject<HTMLElement>;
}

View File

@@ -155,21 +155,19 @@ export const PageHeaderWithActions = ({
popupRender={() => additionalActionsMenu}
{...menuDropdownProps}
>
<span>
<Button
css={menuTriggerStyles}
buttonStyle="tertiary"
aria-label={t('Menu actions trigger')}
tooltip={tooltipProps?.text}
placement={tooltipProps?.placement}
data-test="actions-trigger"
>
<Icons.EllipsisOutlined
iconColor={theme.colorPrimary}
iconSize="l"
/>
</Button>
</span>
<Button
css={menuTriggerStyles}
buttonStyle="tertiary"
aria-label={t('Menu actions trigger')}
tooltip={tooltipProps?.text}
placement={tooltipProps?.placement}
data-test="actions-trigger"
>
<Icons.EllipsisOutlined
iconColor={theme.colorPrimary}
iconSize="l"
/>
</Button>
</Dropdown>
)}
</div>

View File

@@ -81,7 +81,6 @@ export type Filter = {
granularity?: string;
time_grain_sqla?: string;
time_range?: string;
time_grains?: string[];
requiredFirst?: boolean;
tabsInScope?: string[];
chartsInScope?: number[];

View File

@@ -109,10 +109,10 @@ test('should handle custom range with relative dates (now)', () => {
timeRangeFilter,
shifts,
startDate,
['4 days ago'],
['5 days ago'],
);
runTimezoneTest(NOW_IN_UTC, 'UTC', timeRangeFilter, shifts, startDate, [
'4 days ago',
'5 days ago',
]);
runTimezoneTest(
NOW_UTC_IN_PACIFIC,
@@ -218,10 +218,10 @@ test('should handle null timeRangeFilter', () => {
timeRangeFilter,
shifts,
startDate,
['2 days ago'],
['3 days ago'],
);
runTimezoneTest(NOW_IN_UTC, 'UTC', timeRangeFilter, shifts, startDate, [
'2 days ago',
'3 days ago',
]);
runTimezoneTest(
NOW_UTC_IN_PACIFIC,
@@ -304,10 +304,10 @@ test('should handle custom range with DATEADD function and relative start date',
timeRangeFilter,
shifts,
startDate,
['2 days ago'],
['3 days ago'],
);
runTimezoneTest(NOW_IN_UTC, 'UTC', timeRangeFilter, shifts, startDate, [
'2 days ago',
'3 days ago',
]);
runTimezoneTest(
NOW_UTC_IN_PACIFIC,
@@ -362,10 +362,10 @@ test('should handle custom range with specific date and relative end date', () =
timeRangeFilter,
shifts,
startDate,
['9 days ago'],
['8 days ago'],
);
runTimezoneTest(NOW_IN_UTC, 'UTC', timeRangeFilter, shifts, startDate, [
'9 days ago',
'8 days ago',
]);
runTimezoneTest(
NOW_UTC_IN_PACIFIC,
@@ -390,10 +390,10 @@ test('should handle custom range with specific date and specific end date', () =
timeRangeFilter,
shifts,
startDate,
['2 days ago'],
['1 days ago'],
);
runTimezoneTest(NOW_IN_UTC, 'UTC', timeRangeFilter, shifts, startDate, [
'2 days ago',
'1 days ago',
]);
runTimezoneTest(
NOW_UTC_IN_PACIFIC,
@@ -474,7 +474,7 @@ test('should handle custom range with previous calendar week', () => {
timeRangeFilter,
shifts,
startDate,
['1 days ago'],
['3 days ago'],
);
runTimezoneTest(
'2024-06-05T00:06:00Z',
@@ -482,7 +482,7 @@ test('should handle custom range with previous calendar week', () => {
timeRangeFilter,
shifts,
startDate,
['1 days ago'],
['3 days ago'],
);
runTimezoneTest(
'2024-06-04T16:06:00-08:00',
@@ -507,7 +507,7 @@ test('should handle custom range with previous calendar month', () => {
timeRangeFilter,
shifts,
startDate,
['5 days ago'],
['7 days ago'],
);
runTimezoneTest(
'2024-06-05T00:06:00Z',
@@ -515,7 +515,7 @@ test('should handle custom range with previous calendar month', () => {
timeRangeFilter,
shifts,
startDate,
['5 days ago'],
['7 days ago'],
);
runTimezoneTest(
'2024-06-04T16:06:00-08:00',
@@ -541,7 +541,7 @@ test('should handle custom range with previous calendar year', () => {
timeRangeFilter,
shifts,
startDate,
['6 days ago'],
['8 days ago'],
);
runTimezoneTest(
'2024-06-05T00:06:00Z',
@@ -549,7 +549,7 @@ test('should handle custom range with previous calendar year', () => {
timeRangeFilter,
shifts,
startDate,
['6 days ago'],
['8 days ago'],
);
runTimezoneTest(
'2024-06-04T16:06:00-08:00',
@@ -760,10 +760,10 @@ test('should handle future custom shift with different format', () => {
timeRangeFilter,
shifts,
startDate,
['4 days after'],
['3 days after'],
);
runTimezoneTest(NOW_IN_UTC, 'UTC', timeRangeFilter, shifts, startDate, [
'4 days after',
'3 days after',
]);
runTimezoneTest(
NOW_UTC_IN_PACIFIC,
@@ -771,7 +771,7 @@ test('should handle future custom shift with different format', () => {
timeRangeFilter,
shifts,
startDate,
['5 days after'],
['4 days after'],
);
});
@@ -850,10 +850,10 @@ test('should handle custom range with relative dates (hour)', () => {
timeRangeFilter,
shifts,
startDate,
['4 days ago'],
['2 days ago'],
);
runTimezoneTest(NOW_IN_UTC, 'UTC', timeRangeFilter, shifts, startDate, [
'4 days ago',
'2 days ago',
]);
runTimezoneTest(
NOW_UTC_IN_PACIFIC,

View File

@@ -20,7 +20,7 @@
import { parseDttmToDate } from '@superset-ui/core';
import timezoneMock from 'timezone-mock';
// NOW will be set at midnight 2024-06-03 and transformed from local timezone to UTC
// NOW will be set at midnight 2024-06-03 and transforme dfrom local timezone to UTC
const NOW_IN_UTC = '2024-06-03T00:00:00Z';
const NOW_UTC_IN_EUROPE = '2024-06-02T22:00:00Z'; // Same as 2024-06-03T00:00:00+02:00
const NOW_UTC_IN_PACIFIC = '2024-06-03T08:00:00Z'; // Same as 2024-06-03T00:00:00-08:00
@@ -69,9 +69,9 @@ test('should return the current date for "today"', () => {
'today',
NOW_UTC_IN_EUROPE,
'Etc/GMT-2',
new Date('2024-06-02T22:00:00Z'),
new Date('2024-06-01T22:00:00Z'),
);
runTimezoneTest('today', NOW_IN_UTC, 'UTC', new Date('2024-06-03T00:00:00Z'));
runTimezoneTest('today', NOW_IN_UTC, 'UTC', new Date('2024-06-02T00:00:00Z'));
runTimezoneTest(
'today',
NOW_UTC_IN_PACIFIC,
@@ -125,13 +125,13 @@ test('should return yesterday date for "Last day"', () => {
'Last day',
NOW_UTC_IN_EUROPE,
'Etc/GMT-2',
new Date('2024-06-01T22:00:00Z'),
new Date('2024-05-31T22:00:00Z'),
);
runTimezoneTest(
'Last day',
NOW_IN_UTC,
'UTC',
new Date('2024-06-02T00:00:00Z'),
new Date('2024-06-01T00:00:00Z'),
);
runTimezoneTest(
'Last day',
@@ -147,13 +147,13 @@ test('should return the date one week ago for "Last week"', () => {
'Last week',
NOW_UTC_IN_EUROPE,
'Etc/GMT-2',
new Date('2024-05-26T22:00:00Z'),
new Date('2024-05-25T22:00:00Z'),
);
runTimezoneTest(
'Last week',
NOW_IN_UTC,
'UTC',
new Date('2024-05-27T00:00:00Z'),
new Date('2024-05-26T00:00:00Z'),
);
runTimezoneTest(
'Last week',
@@ -169,13 +169,13 @@ test('should return the date one month ago for "Last month"', () => {
'Last month',
NOW_UTC_IN_EUROPE,
'Etc/GMT-2',
new Date('2024-05-02T22:00:00Z'),
new Date('2024-05-01T22:00:00Z'),
);
runTimezoneTest(
'Last month',
NOW_IN_UTC,
'UTC',
new Date('2024-05-03T00:00:00Z'),
new Date('2024-05-02T00:00:00Z'),
);
runTimezoneTest(
'Last month',
@@ -191,13 +191,13 @@ test('should return the date three months ago for "Last quarter"', () => {
'Last quarter',
NOW_UTC_IN_EUROPE,
'Etc/GMT-2',
new Date('2024-03-02T22:00:00Z'),
new Date('2024-03-01T22:00:00Z'),
);
runTimezoneTest(
'Last quarter',
NOW_IN_UTC,
'UTC',
new Date('2024-03-03T00:00:00Z'),
new Date('2024-03-02T00:00:00Z'),
);
runTimezoneTest(
'Last quarter',
@@ -213,13 +213,13 @@ test('should return the date one year ago for "Last year"', () => {
'Last year',
NOW_UTC_IN_EUROPE,
'Etc/GMT-2',
new Date('2023-06-02T22:00:00Z'),
new Date('2023-06-01T22:00:00Z'),
);
runTimezoneTest(
'Last year',
NOW_IN_UTC,
'UTC',
new Date('2023-06-03T00:00:00Z'),
new Date('2023-06-02T00:00:00Z'),
);
runTimezoneTest(
'Last year',
@@ -235,19 +235,19 @@ test('should return the date for "previous calendar week"', () => {
'previous calendar week',
'2024-06-04T22:00:00Z',
'Etc/GMT-2',
new Date('2024-05-26T22:00:00Z'),
new Date('2024-05-27T16:00:00Z'),
);
runTimezoneTest(
'previous calendar week',
'2024-06-05T00:00:00Z',
'UTC',
new Date('2024-05-27T00:00:00Z'),
new Date('2024-05-27T20:00:00Z'),
);
runTimezoneTest(
'previous calendar week',
'2024-06-05T08:00:00Z',
'Etc/GMT+8',
new Date('2024-05-27T08:00:00Z'),
new Date('2024-05-27T12:00:00Z'),
);
});
@@ -257,19 +257,19 @@ test('should return the date for "previous calendar month"', () => {
'previous calendar month',
NOW_UTC_IN_EUROPE,
'Etc/GMT-2',
new Date('2024-04-30T22:00:00Z'),
new Date('2024-05-01T10:00:00Z'),
);
runTimezoneTest(
'previous calendar month',
NOW_IN_UTC,
'UTC',
new Date('2024-05-01T00:00:00Z'),
new Date('2024-05-01T16:00:00Z'),
);
runTimezoneTest(
'previous calendar month',
NOW_UTC_IN_PACIFIC,
'Etc/GMT+8',
new Date('2024-05-01T08:00:00Z'),
new Date('2024-05-01T16:00:00Z'),
);
});
@@ -279,19 +279,19 @@ test('should return the date for "previous calendar year"', () => {
'previous calendar year',
NOW_UTC_IN_EUROPE,
'Etc/GMT-2',
new Date('2022-12-31T22:00:00Z'),
new Date('2023-01-01T16:00:00Z'),
);
runTimezoneTest(
'previous calendar year',
NOW_IN_UTC,
'UTC',
new Date('2023-01-01T00:00:00Z'),
new Date('2023-01-01T20:00:00Z'),
);
runTimezoneTest(
'previous calendar year',
NOW_UTC_IN_PACIFIC,
'Etc/GMT+8',
new Date('2023-01-01T08:00:00Z'),
new Date('2023-01-01T12:00:00Z'),
);
});
@@ -301,13 +301,13 @@ test('should return the date for "1 day ago"', () => {
'1 day ago',
NOW_UTC_IN_EUROPE,
'Etc/GMT-2',
new Date('2024-06-01T22:00:00Z'),
new Date('2024-05-31T22:00:00Z'),
);
runTimezoneTest(
'1 day ago',
NOW_IN_UTC,
'UTC',
new Date('2024-06-02T00:00:00Z'),
new Date('2024-06-01T00:00:00Z'),
);
runTimezoneTest(
'1 day ago',
@@ -323,13 +323,13 @@ test('should return the date for "1 week ago"', () => {
'1 week ago',
NOW_UTC_IN_EUROPE,
'Etc/GMT-2',
new Date('2024-05-26T22:00:00Z'),
new Date('2024-05-25T22:00:00Z'),
);
runTimezoneTest(
'1 week ago',
NOW_IN_UTC,
'UTC',
new Date('2024-05-27T00:00:00Z'),
new Date('2024-05-26T00:00:00Z'),
);
runTimezoneTest(
'1 week ago',
@@ -345,13 +345,13 @@ test('should return the date for "1 month ago"', () => {
'1 month ago',
NOW_UTC_IN_EUROPE,
'Etc/GMT-2',
new Date('2024-05-02T22:00:00Z'),
new Date('2024-05-01T22:00:00Z'),
);
runTimezoneTest(
'1 month ago',
NOW_IN_UTC,
'UTC',
new Date('2024-05-03T00:00:00Z'),
new Date('2024-05-02T00:00:00Z'),
);
runTimezoneTest(
'1 month ago',
@@ -367,13 +367,13 @@ test('should return the date for "1 year ago"', () => {
'1 year ago',
NOW_UTC_IN_EUROPE,
'Etc/GMT-2',
new Date('2023-06-02T22:00:00Z'),
new Date('2023-06-01T22:00:00Z'),
);
runTimezoneTest(
'1 year ago',
NOW_IN_UTC,
'UTC',
new Date('2023-06-03T00:00:00Z'),
new Date('2023-06-02T00:00:00Z'),
);
runTimezoneTest(
'1 year ago',
@@ -389,13 +389,13 @@ test('should return the date for "2024-03-09"', () => {
'2024-03-09',
NOW_UTC_IN_EUROPE,
'Etc/GMT-2',
new Date('2024-03-08T22:00:00.000Z'),
new Date('2024-03-07T22:00:00.000Z'),
);
runTimezoneTest(
'2024-03-09',
NOW_IN_UTC,
'UTC',
new Date('2024-03-09T00:00:00.000Z'),
new Date('2024-03-08T00:00:00.000Z'),
);
runTimezoneTest(
'2024-03-09',
@@ -411,14 +411,14 @@ test('should return the current date for "Last day" with isEndDate true', () =>
'Last day',
NOW_UTC_IN_EUROPE,
'Etc/GMT-2',
new Date('2024-06-02T22:00:00Z'),
new Date('2024-06-01T22:00:00Z'),
true,
);
runTimezoneTest(
'Last day',
NOW_IN_UTC,
'UTC',
new Date('2024-06-03T00:00:00Z'),
new Date('2024-06-02T00:00:00Z'),
true,
);
runTimezoneTest(
@@ -436,14 +436,14 @@ test('should return the current date for "Last week" with isEndDate true', () =>
'Last week',
NOW_UTC_IN_EUROPE,
'Etc/GMT-2',
new Date('2024-06-02T22:00:00Z'),
new Date('2024-06-01T22:00:00Z'),
true,
);
runTimezoneTest(
'Last week',
NOW_IN_UTC,
'UTC',
new Date('2024-06-03T00:00:00Z'),
new Date('2024-06-02T00:00:00Z'),
true,
);
runTimezoneTest(
@@ -461,14 +461,14 @@ test('should return the current date for "Last quarter" with isEndDate true', ()
'Last quarter',
NOW_UTC_IN_EUROPE,
'Etc/GMT-2',
new Date('2024-06-02T22:00:00Z'),
new Date('2024-06-01T22:00:00Z'),
true,
);
runTimezoneTest(
'Last quarter',
NOW_IN_UTC,
'UTC',
new Date('2024-06-03T00:00:00Z'),
new Date('2024-06-02T00:00:00Z'),
true,
);
runTimezoneTest(
@@ -486,14 +486,14 @@ test('should return the current date for "Last year" with isEndDate true', () =>
'Last year',
NOW_UTC_IN_EUROPE,
'Etc/GMT-2',
new Date('2024-06-02T22:00:00Z'),
new Date('2024-06-01T22:00:00Z'),
true,
);
runTimezoneTest(
'Last year',
NOW_IN_UTC,
'UTC',
new Date('2024-06-03T00:00:00Z'),
new Date('2024-06-02T00:00:00Z'),
true,
);
runTimezoneTest(
@@ -511,21 +511,21 @@ test('should return the date for "previous calendar week" with isEndDate true',
'previous calendar week',
NOW_UTC_IN_EUROPE,
'Etc/GMT-2',
new Date('2024-06-02T22:00:00Z'),
new Date('2024-06-03T16:00:00Z'),
true,
);
runTimezoneTest(
'previous calendar week',
NOW_IN_UTC,
'UTC',
new Date('2024-06-03T00:00:00Z'),
new Date('2024-06-03T20:00:00Z'),
true,
);
runTimezoneTest(
'previous calendar week',
NOW_UTC_IN_PACIFIC,
'Etc/GMT+8',
new Date('2024-06-03T08:00:00Z'),
new Date('2024-06-03T12:00:00Z'),
true,
);
});
@@ -536,21 +536,21 @@ test('should return the date for "previous calendar month" with isEndDate true',
'previous calendar month',
NOW_UTC_IN_EUROPE,
'Etc/GMT-2',
new Date('2024-05-31T22:00:00Z'),
new Date('2024-06-01T16:00:00Z'),
true,
);
runTimezoneTest(
'previous calendar month',
NOW_IN_UTC,
'UTC',
new Date('2024-06-01T00:00:00Z'),
new Date('2024-06-01T20:00:00Z'),
true,
);
runTimezoneTest(
'previous calendar month',
NOW_UTC_IN_PACIFIC,
'Etc/GMT+8',
new Date('2024-06-01T08:00:00Z'),
new Date('2024-06-01T12:00:00Z'),
true,
);
});
@@ -561,21 +561,21 @@ test('should return the date for "previous calendar year" with isEndDate true',
'previous calendar year',
NOW_UTC_IN_EUROPE,
'Etc/GMT-2',
new Date('2023-12-31T22:00:00Z'),
new Date('2024-01-01T16:00:00Z'),
true,
);
runTimezoneTest(
'previous calendar year',
NOW_IN_UTC,
'UTC',
new Date('2024-01-01T00:00:00Z'),
new Date('2024-01-01T20:00:00Z'),
true,
);
runTimezoneTest(
'previous calendar year',
NOW_UTC_IN_PACIFIC,
'Etc/GMT+8',
new Date('2024-01-01T08:00:00Z'),
new Date('2024-01-01T12:00:00Z'),
true,
);
});
@@ -586,9 +586,9 @@ test('should return the date for "2024" with parts.length === 1', () => {
'2024',
NOW_UTC_IN_EUROPE,
'Etc/GMT-2',
new Date('2023-12-31T22:00:00.000Z'),
new Date('2023-12-30T22:00:00.000Z'),
);
runTimezoneTest('2024', NOW_IN_UTC, 'UTC', new Date('2024-01-01T00:00:00Z'));
runTimezoneTest('2024', NOW_IN_UTC, 'UTC', new Date('2023-12-31T00:00:00Z'));
runTimezoneTest(
'2024',
NOW_UTC_IN_PACIFIC,
@@ -603,13 +603,13 @@ test('should return the date for "2024-03" with parts.length === 2', () => {
'2024-03',
NOW_UTC_IN_EUROPE,
'Etc/GMT-2',
new Date('2024-02-29T22:00:00.000Z'),
new Date('2024-02-28T22:00:00.000Z'),
);
runTimezoneTest(
'2024-03',
NOW_IN_UTC,
'UTC',
new Date('2024-03-01T00:00:00Z'),
new Date('2024-02-29T00:00:00Z'),
);
runTimezoneTest(
'2024-03',
@@ -625,13 +625,13 @@ test('should return the date for "2024-03-06" with parts.length === 3', () => {
'2024-03-06',
NOW_UTC_IN_EUROPE,
'Etc/GMT-2',
new Date('2024-03-05T22:00:00.000Z'),
new Date('2024-03-04T22:00:00.000Z'),
);
runTimezoneTest(
'2024-03-06',
NOW_IN_UTC,
'UTC',
new Date('2024-03-06T00:00:00.000Z'),
new Date('2024-03-05T00:00:00.000Z'),
);
runTimezoneTest(
'2024-03-06',
@@ -643,7 +643,7 @@ test('should return the date for "2024-03-06" with parts.length === 3', () => {
test('should return the date for "2024-03-06" with computingShifts true', () => {
jest.useFakeTimers();
const expectedDate = new Date('2024-03-06T22:00:00Z');
const expectedDate = new Date('2024-03-05T22:00:00Z');
expectedDate.setHours(-expectedDate.getTimezoneOffset() / 60, 0, 0, 0);
runTimezoneTest(
'2024-03-06',
@@ -657,7 +657,7 @@ test('should return the date for "2024-03-06" with computingShifts true', () =>
test('should return the date for "2024-03-06" with computingShifts true and isEndDate true', () => {
jest.useFakeTimers();
const expectedDate = new Date('2024-03-06T22:00:00Z');
const expectedDate = new Date('2024-03-05T22:00:00Z');
expectedDate.setHours(-expectedDate.getTimezoneOffset() / 60, 0, 0, 0);
runTimezoneTest(
'2024-03-06',

View File

@@ -25,9 +25,7 @@ const CHROME_UA =
const makeGetText = (text: string) => () => Promise.resolve(text);
const globalWithClipboardItem = global as unknown as {
ClipboardItem?: unknown;
};
const globalWithClipboardItem = global as unknown as { ClipboardItem?: unknown };
afterEach(() => {
jest.restoreAllMocks();
@@ -96,7 +94,9 @@ function mockExecCommand(impl: (cmd: string) => boolean) {
});
}
function setupFallbackMocks(options: { selection: Partial<Selection> | null }) {
function setupFallbackMocks(options: {
selection: Partial<Selection> | null;
}) {
Object.defineProperty(navigator, 'userAgent', {
value: CHROME_UA,
configurable: true,
@@ -117,9 +117,7 @@ function setupFallbackMocks(options: { selection: Partial<Selection> | null }) {
jest
.spyOn(document, 'getSelection')
.mockReturnValue(options.selection as Selection | null);
jest
.spyOn(document, 'createRange')
.mockReturnValue(mockRange as unknown as Range);
jest.spyOn(document, 'createRange').mockReturnValue(mockRange as unknown as Range);
jest.spyOn(document, 'createElement').mockReturnValue(mockSpan);
jest.spyOn(document.body, 'appendChild').mockImplementation(() => mockSpan);
jest.spyOn(document.body, 'removeChild').mockImplementation(() => mockSpan);
@@ -170,9 +168,7 @@ test('rejects when execCommand returns false', async () => {
});
mockExecCommand(() => false);
await expect(
copyTextToClipboard(makeGetText('fail')),
).rejects.toBeUndefined();
await expect(copyTextToClipboard(makeGetText('fail'))).rejects.toBeUndefined();
});
test('rejects when execCommand throws', async () => {
@@ -191,9 +187,7 @@ test('rejects when execCommand throws', async () => {
writable: true,
});
await expect(
copyTextToClipboard(makeGetText('throw')),
).rejects.toBeUndefined();
await expect(copyTextToClipboard(makeGetText('throw'))).rejects.toBeUndefined();
});
test('resolves without copying when getSelection returns null', async () => {

View File

@@ -25,22 +25,108 @@
*
* Run locally:
* cd superset-frontend
* npm run docs:screenshots
* PLAYWRIGHT_BASE_URL=http://localhost:8088 PLAYWRIGHT_ADMIN_PASSWORD=admin npm run docs:screenshots
*
* Or directly:
* npx playwright test --config=playwright/generators/playwright.config.ts docs/
*
* Screenshots are saved to docs/static/img/screenshots/.
* Screenshots are saved under docs/static/img/.
* As new screenshots are scripted, entries are removed from screenshot-manifest.yaml
* and the output path moves from that manifest into the test below.
*/
import path from 'path';
import { Page } from '@playwright/test';
import { test, expect } from '@playwright/test';
import { URL } from '../../utils/urls';
import { apiDelete, apiGet } from '../../helpers/api/requests';
const SCREENSHOTS_DIR = path.resolve(
__dirname,
'../../../../docs/static/img/screenshots',
);
const DOCS_STATIC = path.resolve(__dirname, '../../../../docs/static/img');
const SCREENSHOTS_DIR = path.join(DOCS_STATIC, 'screenshots');
const TUTORIAL_DIR = path.join(DOCS_STATIC, 'tutorial');
/**
* Waits for animations and async renders to settle before taking a screenshot.
* ECharts entry animations, image lazy-loading, and other async UI updates
* require a short pause that can't be expressed as a deterministic wait condition.
*/
async function settle(page: Page, ms = 1000): Promise<void> {
await page.waitForTimeout(ms);
}
/**
* Navigates to the Sales Dashboard (from example data) and waits for charts
* to finish rendering. Used by several tutorial screenshots that show the
* dashboard in view or edit mode.
*/
async function openSalesDashboard(page: Page): Promise<void> {
await page.goto(URL.DASHBOARD_LIST);
const searchInput = page.getByPlaceholder('Type a value');
await expect(searchInput).toBeVisible({ timeout: 15000 });
await searchInput.fill('Sales Dashboard');
await searchInput.press('Enter');
const dashboardLink = page.getByRole('link', { name: /sales dashboard/i });
await expect(dashboardLink).toBeVisible({ timeout: 10000 });
await dashboardLink.click();
const dashboardWrapper = page.locator(
'[data-test="dashboard-content-wrapper"]',
);
await expect(dashboardWrapper).toBeVisible({ timeout: 30000 });
await expect(
page.locator('.dashboard-component-chart-holder').first(),
).toBeVisible({ timeout: 15000 });
await expect(
dashboardWrapper.locator('[data-test="loading-indicator"]'),
).toHaveCount(0, { timeout: 30000 });
await expect(
page.locator('.dashboard-component-chart-holder canvas').first(),
).toBeVisible({ timeout: 15000 });
}
/**
* Delete all dashboards matching the given exact title, along with the
* charts attached to them. Used by the save-flow test to clean up after
* itself and to recover from prior failed runs (idempotent pre-cleanup).
*
* Only safe because the title is unique to the test ("Superset Duper
* Sales Dashboard"); don't reuse this against titles that could match
* example-data dashboards.
*/
async function deleteDashboardByTitle(
page: Page,
title: string,
): Promise<void> {
const filter = `(filters:!((col:dashboard_title,opr:eq,value:'${title}')))`;
const resp = await apiGet(page, 'api/v1/dashboard/', {
params: { q: filter },
failOnStatusCode: false,
});
if (!resp.ok()) return;
const body = await resp.json();
const dashboards: { id: number }[] = body.result || [];
for (const dash of dashboards) {
const chartsResp = await apiGet(
page,
`api/v1/dashboard/${dash.id}/charts`,
{ failOnStatusCode: false },
);
const chartIds: number[] = chartsResp.ok()
? ((await chartsResp.json()).result || [])
.map((c: { id?: number }) => c.id)
.filter((id: unknown): id is number => typeof id === 'number')
: [];
await apiDelete(page, `api/v1/dashboard/${dash.id}`, {
failOnStatusCode: false,
});
for (const id of chartIds) {
await apiDelete(page, `api/v1/chart/${id}`, { failOnStatusCode: false });
}
}
}
test('chart gallery screenshot', async ({ page }) => {
await page.goto(URL.CHART_ADD);
@@ -58,6 +144,7 @@ test('chart gallery screenshot', async ({ page }) => {
vizGallery.locator('[data-test="viztype-selector-container"]').first(),
).toBeVisible();
await settle(page);
await vizGallery.screenshot({
path: path.join(SCREENSHOTS_DIR, 'gallery.jpg'),
type: 'jpeg',
@@ -65,36 +152,7 @@ test('chart gallery screenshot', async ({ page }) => {
});
test('dashboard screenshot', async ({ page }) => {
// Navigate to Sales Dashboard via the dashboard list (slug is null)
await page.goto(URL.DASHBOARD_LIST);
const searchInput = page.getByPlaceholder('Type a value');
await expect(searchInput).toBeVisible({ timeout: 15000 });
await searchInput.fill('Sales Dashboard');
await searchInput.press('Enter');
// Click the Sales Dashboard link
const dashboardLink = page.getByRole('link', { name: /sales dashboard/i });
await expect(dashboardLink).toBeVisible({ timeout: 10000 });
await dashboardLink.click();
// Wait for dashboard to fully render
const dashboardWrapper = page.locator(
'[data-test="dashboard-content-wrapper"]',
);
await expect(dashboardWrapper).toBeVisible({ timeout: 30000 });
// Wait for chart holders to appear, then wait for all loading spinners to clear
await expect(
page.locator('.dashboard-component-chart-holder').first(),
).toBeVisible({ timeout: 15000 });
await expect(
dashboardWrapper.locator('[data-test="loading-indicator"]'),
).toHaveCount(0, { timeout: 30000 });
// Wait for at least one chart to finish rendering (ECharts renders to canvas)
await expect(
page.locator('.dashboard-component-chart-holder canvas').first(),
).toBeVisible({ timeout: 15000 });
await openSalesDashboard(page);
// Open the filter bar (collapsed by default)
const expandButton = page.locator('[data-test="filter-bar__expand-button"]');
@@ -109,6 +167,8 @@ test('dashboard screenshot', async ({ page }) => {
).toBeVisible({ timeout: 5000 });
}
// Allow ECharts entry animations to finish before capturing
await settle(page);
await page.screenshot({
path: path.join(SCREENSHOTS_DIR, 'dashboard.jpg'),
type: 'jpeg',
@@ -143,6 +203,7 @@ test('chart editor screenshot', async ({ page }) => {
timeout: 15000,
});
await settle(page);
await page.screenshot({
path: path.join(SCREENSHOTS_DIR, 'explore.jpg'),
type: 'jpeg',
@@ -151,7 +212,7 @@ test('chart editor screenshot', async ({ page }) => {
});
test('SQL Lab screenshot', async ({ page }) => {
// SQL Lab has many interactive steps (schema, table, query, results) — allow extra time
// SQL Lab has many interactive steps — allow extra time
test.setTimeout(90000);
await page.goto(URL.SQLLAB);
@@ -168,34 +229,7 @@ test('SQL Lab screenshot', async ({ page }) => {
}
await expect(aceEditor).toBeVisible({ timeout: 15000 });
// Select the "public" schema so we can pick a table from the left panel
const schemaSelect = page.locator('#select-schema');
await expect(schemaSelect).toBeEnabled({ timeout: 10000 });
await schemaSelect.click({ force: true });
await schemaSelect.fill('public');
await page.getByRole('option', { name: 'public' }).click();
// Wait for table list to load after schema change, then select birth_names
const tableSelectWrapper = page
.locator('.ant-select')
.filter({ has: page.locator('#select-table') });
await expect(tableSelectWrapper).toBeVisible({ timeout: 10000 });
await tableSelectWrapper.click();
await page.keyboard.type('birth_names');
// Wait for the filtered option to appear in the DOM, then select it
const tableOption = page
.locator('.ant-select-dropdown [role="option"]')
.filter({ hasText: 'birth_names' });
await expect(tableOption).toBeAttached({ timeout: 10000 });
await page.keyboard.press('Enter');
// Wait for table schema to load and show columns in the left panel
await expect(page.locator('[data-test="col-name"]').first()).toBeVisible({
timeout: 15000,
});
// Close the table dropdown by clicking elsewhere, then switch to the query tab
await page.locator('[data-test="sql-editor-tabs"]').first().click();
// Click the active query tab to ensure focus is on the editor pane
await page.getByText('Untitled Query').first().click();
// Write a multi-line SELECT with explicit columns to fill the editor
@@ -205,8 +239,8 @@ test('SQL Lab screenshot', async ({ page }) => {
'SELECT\n ds,\n name,\n gender,\n state,\n num\nFROM birth_names\nLIMIT 100',
);
// Run the query
const runButton = page.getByText('Run', { exact: true });
// Run the query — use the stable data-test attribute on the action button
const runButton = page.locator('[data-test="run-query-action"]');
await expect(runButton).toBeVisible();
await runButton.click();
@@ -222,9 +256,352 @@ test('SQL Lab screenshot', async ({ page }) => {
await page.mouse.move(0, 0);
await expect(page.getByRole('tooltip')).toHaveCount(0, { timeout: 2000 });
await settle(page);
await page.screenshot({
path: path.join(SCREENSHOTS_DIR, 'sql_lab.jpg'),
type: 'jpeg',
fullPage: true,
});
});
// ---------------------------------------------------------------------------
// Tutorial screenshots
// ---------------------------------------------------------------------------
test('datasets list screenshot', async ({ page }) => {
await page.goto(URL.DATASET_LIST);
const table = page.locator('[data-test="listview-table"]');
await expect(table).toBeVisible({ timeout: 15000 });
// Wait for at least one visible data row (skip ant-table-measure-row which is always hidden)
await expect(
table.locator('tbody tr:not(.ant-table-measure-row)').first(),
).toBeVisible({ timeout: 10000 });
// Viewport screenshot (not fullPage) captures the SubMenu — showing the
// "Datasets" nav item, Bulk Select button, and + Dataset button — plus the
// top of the table. This is more informative than screenshotting the table alone.
await settle(page);
await page.screenshot({
path: path.join(TUTORIAL_DIR, 'tutorial_08_sources_tables.png'),
type: 'png',
});
});
test('chart type picker screenshot', async ({ page }) => {
await page.goto(URL.CHART_ADD);
// Wait for the dataset step to appear (step title is first match; placeholder is second)
await expect(page.getByText('Choose a dataset').first()).toBeVisible({
timeout: 15000,
});
// Open the dataset selector and choose birth_names
await page.getByTestId('Dataset').click();
await page.keyboard.type('birth_names');
// The dataset select uses a hidden ARIA listbox — the visible popup is a portal.
// Wait for the first option to appear in the DOM, then select it via keyboard.
await expect(
page.locator('[role="listbox"] [role="option"]').first(),
).toBeAttached({ timeout: 10000 });
await page.keyboard.press('ArrowDown');
await page.keyboard.press('Enter');
// Open the chart gallery and wait for thumbnails to render
await expect(page.getByText('Choose chart type')).toBeVisible({
timeout: 10000,
});
await page.getByRole('tab', { name: 'All charts' }).click();
const vizGallery = page.locator('.viz-gallery');
await expect(vizGallery).toBeVisible();
await expect(
vizGallery.locator('[data-test="viztype-selector-container"]').first(),
).toBeVisible();
// Select the Pivot Table chart type
await vizGallery
.locator('[data-test="viztype-selector-container"]')
.filter({ hasText: 'Pivot Table' })
.first()
.click();
// Allow thumbnails to finish loading and selection state to render
await settle(page);
// Viewport screenshot shows the dataset step (birth_names selected) and
// the chart type gallery (Pivot Table highlighted)
await page.screenshot({
path: path.join(TUTORIAL_DIR, 'create_pivot.png'),
type: 'png',
});
});
test('publish button dashboard screenshot', async ({ page }) => {
// Toggle Sales Dashboard to Draft, hover the label so the tooltip renders,
// then capture the header area plus enough room below for the tooltip.
// Always restores the dashboard to Published at the end.
await openSalesDashboard(page);
const publishedLabel = page.getByText('Published', { exact: true }).first();
await expect(publishedLabel).toBeVisible({ timeout: 10000 });
await publishedLabel.click();
const draftLabel = page.getByText('Draft', { exact: true }).first();
await expect(draftLabel).toBeVisible({ timeout: 10000 });
try {
await draftLabel.hover();
await expect(page.getByRole('tooltip')).toBeVisible({ timeout: 5000 });
await settle(page, 500);
const headerBox = await page
.locator('[data-test="dashboard-header-container"]')
.boundingBox();
if (!headerBox) {
throw new Error('Could not locate dashboard header container');
}
await page.screenshot({
path: path.join(TUTORIAL_DIR, 'publish_button_dashboard.png'),
type: 'png',
clip: {
x: headerBox.x,
y: headerBox.y,
width: headerBox.width,
height: headerBox.height + 140,
},
});
} finally {
// Restore: click Draft to re-publish so other runs start from a clean state
await page.mouse.move(0, 0);
await draftLabel.click();
await expect(
page.getByText('Published', { exact: true }).first(),
).toBeVisible({ timeout: 10000 });
}
});
test('edit button screenshot', async ({ page }) => {
// Capture the right-side action buttons (Edit dashboard + "..." menu)
// rather than the edit button in isolation.
await openSalesDashboard(page);
await settle(page);
const rightPanel = page.locator('.right-button-panel');
await expect(rightPanel).toBeVisible({ timeout: 5000 });
await rightPanel.screenshot({
path: path.join(TUTORIAL_DIR, 'tutorial_edit_button.png'),
type: 'png',
});
});
test('chart resize screenshot', async ({ page }) => {
// Enter edit mode, start a resize drag on the right-edge handle, then
// screenshot the chart mid-drag. While `DashboardGrid` is in the resizing
// state it renders vertical `grid-column-guide` overlays across the grid
// and the chart gets a blue `--resizing` outline — that's the state the
// original tutorial screenshot was capturing.
await openSalesDashboard(page);
const editButton = page.locator('[data-test="edit-dashboard-button"]');
await expect(editButton).toBeVisible();
await editButton.click();
await expect(
page.locator('[data-test="dashboard-builder-sidepane"]'),
).toBeVisible({ timeout: 10000 });
const chart = page.locator('.dashboard-component-chart-holder').first();
await expect(chart).toBeVisible();
const chartBox = await chart.boundingBox();
if (!chartBox) {
throw new Error('Could not locate chart bounding box');
}
// Hover over the chart so the on-hover action buttons (drag/trash/settings)
// and resize handles become visible.
await page.mouse.move(
chartBox.x + chartBox.width / 2,
chartBox.y + chartBox.height / 2,
);
await settle(page, 200);
// The right-edge handle is a `<span>` added by re-resizable with our
// custom class. Locating it by class is more reliable than computing
// coordinates from the chart-holder (which isn't the full resizable box).
const rightHandle = page
.locator('.resizable-container-handle--right')
.first();
await expect(rightHandle).toBeVisible();
const handleBox = await rightHandle.boundingBox();
if (!handleBox) {
throw new Error('Could not locate right-edge resize handle');
}
const handleX = handleBox.x + handleBox.width / 2;
const handleY = handleBox.y + handleBox.height / 2;
await page.mouse.move(handleX, handleY);
await page.mouse.down();
// Move far enough to snap at least one grid column, which puts
// DashboardGrid into isResizing=true so the column guides render.
await page.mouse.move(handleX + 80, handleY, { steps: 10 });
await settle(page, 500);
// Clip to the chart area plus a left gutter for the hover action rail
// and right padding that reaches past the dragged handle position.
const leftGutter = 32;
const rightPadding = 100;
const topPadding = 16;
const bottomPadding = 24;
await page.screenshot({
path: path.join(TUTORIAL_DIR, 'tutorial_chart_resize.png'),
type: 'png',
clip: {
x: Math.max(0, chartBox.x - leftGutter),
y: Math.max(0, chartBox.y - topPadding),
width: chartBox.width + leftGutter + rightPadding,
height: chartBox.height + topPadding + bottomPadding,
},
});
// Release back at the start to avoid persisting a size change. Edit-mode
// changes aren't saved (we never click the dashboard Save button).
await page.mouse.move(handleX, handleY, { steps: 6 });
await page.mouse.up();
});
test('save flow and first dashboard screenshots', async ({ page }) => {
// Captures two linked tutorial screenshots in a single flow so the second
// faithfully shows the dashboard the user just created:
// 1. tutorial_save_slice.png — Save modal with the "Add to dashboard"
// dropdown surfacing a creatable option for a new dashboard.
// 2. tutorial_first_dashboard.png — the freshly-created dashboard with
// the single saved chart (matches the tutorial narrative).
//
// Creates and then deletes a "Superset Duper Sales Dashboard" dashboard
// plus the duplicate chart it owns. Pre-cleans in case a prior run failed.
const NEW_DASHBOARD_NAME = 'Superset Duper Sales Dashboard';
await deleteDashboardByTitle(page, NEW_DASHBOARD_NAME);
// 1100px is wide enough to show the full "Superset Duper Sales Dashboard"
// title alongside the header actions without truncation.
await page.setViewportSize({ width: 1100, height: 800 });
await page.goto(URL.CHART_LIST);
const searchInput = page.getByPlaceholder('Type a value');
await expect(searchInput).toBeVisible({ timeout: 15000 });
await searchInput.fill('Scatter Plot');
await searchInput.press('Enter');
const chartLink = page.getByRole('link', { name: /scatter plot/i });
await expect(chartLink).toBeVisible({ timeout: 10000 });
await chartLink.click();
await page.waitForURL('**/explore/**', { timeout: 15000 });
const sliceContainer = page.locator('[data-test="slice-container"]');
await expect(sliceContainer).toBeVisible({ timeout: 15000 });
await expect(
sliceContainer.locator('[data-test="loading-indicator"]'),
).toHaveCount(0, { timeout: 15000 });
const saveButton = page.locator('[data-test="query-save-button"]');
await expect(saveButton).toBeVisible({ timeout: 10000 });
await saveButton.click();
const modal = page.locator('.ant-modal-content').filter({
has: page.locator('[data-test="save-modal-body"]'),
});
await expect(modal).toBeVisible({ timeout: 10000 });
// Open the "Add to dashboard" select and type a new dashboard name so
// the dropdown surfaces the creatable option.
const dashboardSelect = page.getByRole('combobox', {
name: /select a dashboard/i,
});
await dashboardSelect.click();
await page.keyboard.type(NEW_DASHBOARD_NAME);
// Ant Design portals the visible dropdown with the class
// `.ant-select-item-option` on each option (distinct from the hidden
// ARIA listbox options rendered inside the combobox itself).
const createOption = page
.locator('.ant-select-item-option')
.filter({ hasText: NEW_DASHBOARD_NAME });
await expect(createOption).toBeVisible({ timeout: 10000 });
await settle(page);
try {
// Screenshot 1: save modal + portaled dropdown.
const modalBox = await modal.boundingBox();
const optionBox = await createOption.boundingBox();
if (!modalBox || !optionBox) {
throw new Error('Could not locate save modal or create-option');
}
const padding = 16;
const top = Math.max(0, modalBox.y - padding);
const bottom = optionBox.y + optionBox.height + padding;
await page.screenshot({
path: path.join(TUTORIAL_DIR, 'tutorial_save_slice.png'),
type: 'png',
clip: {
x: Math.max(0, modalBox.x - padding),
y: top,
width: modalBox.width + padding * 2,
height: bottom - top,
},
});
// Pick the creatable option, then click "Save & go to dashboard" so the
// backend creates the dashboard + slice and redirects us to the new one.
await createOption.click();
const saveAndGotoBtn = page.locator('#btn_modal_save_goto_dash');
await expect(saveAndGotoBtn).toBeEnabled({ timeout: 5000 });
await saveAndGotoBtn.click();
await page.waitForURL(/\/dashboard\/[^/]+\/?/, { timeout: 30000 });
await expect(
page.locator('[data-test="dashboard-content-wrapper"]'),
).toBeVisible({ timeout: 30000 });
await expect(
page.locator('.dashboard-component-chart-holder').first(),
).toBeVisible({ timeout: 30000 });
await expect(
page.locator('.dashboard-component-chart-holder canvas').first(),
).toBeVisible({ timeout: 15000 });
// Dismiss the "Chart [X] has been saved" toast so it doesn't appear in
// the screenshot. The close button is inside the toast container.
const toast = page.locator('[data-test="toast-container"]').first();
if (await toast.isVisible().catch(() => false)) {
await toast.locator('.toast__close').click();
await expect(toast).toBeHidden({ timeout: 5000 });
}
await settle(page);
// Screenshot 2: the newly-created single-chart dashboard (title + chart).
const headerBox = await page
.locator('[data-test="dashboard-header-wrapper"]')
.boundingBox();
const chartBox = await page
.locator('.dashboard-component-chart-holder')
.first()
.boundingBox();
if (!headerBox || !chartBox) {
throw new Error('Could not locate dashboard header or chart');
}
// Trim right edge to just past the chart so the screenshot isn't padded
// with empty grid space.
const rightPadding = 16;
await page.screenshot({
path: path.join(TUTORIAL_DIR, 'tutorial_first_dashboard.png'),
type: 'png',
clip: {
x: 0,
y: headerBox.y,
width: Math.min(1100, chartBox.x + chartBox.width + rightPadding),
height: chartBox.y + chartBox.height - headerBox.y + 16,
},
});
} finally {
await deleteDashboardByTitle(page, NEW_DASHBOARD_NAME);
}
});

File diff suppressed because it is too large Load Diff

View File

@@ -64,6 +64,7 @@ export default defineConfig({
name: 'docs-generators',
use: {
browserName: 'chromium',
baseURL, // explicit here so globalSetup can read it from config.projects[0].use.baseURL
testIdAttribute: 'data-test',
storageState: path.resolve(__dirname, '../.auth/user.json'),
},

View File

@@ -31,7 +31,7 @@
"dependencies": {
"d3": "^3.5.17",
"prop-types": "^15.8.1",
"react": "^19.2.5"
"react": "^19.2.1"
},
"peerDependencies": {
"@superset-ui/chart-controls": "*",

View File

@@ -34,7 +34,7 @@
"fast-safe-stringify": "^2.1.1",
"lodash": "^4.18.1",
"nvd3-fork": "^2.0.5",
"dompurify": "^3.4.1",
"dompurify": "^3.3.3",
"prop-types": "^15.8.1",
"urijs": "^1.19.11"
},

View File

@@ -431,11 +431,6 @@ const processColumns = memoizeOne(function processColumns(
formatter,
config,
};
})
.sort((a, b) => {
const aIsMetric = a.isMetric || a.isPercentMetric ? 1 : 0;
const bIsMetric = b.isMetric || b.isPercentMetric ? 1 : 0;
return aIsMetric - bIsMetric;
});
return [metrics, percentMetrics, columns] as [
typeof metrics,

View File

@@ -29,7 +29,6 @@ import {
} from '@superset-ui/core';
import { GenericDataType } from '@apache-superset/core/common';
import { BigNumberTotalChartProps, BigNumberVizProps } from '../types';
import { PROPORTION } from '../constants';
import { getDateFormatter, getOriginalLabel, parseMetricValue } from '../utils';
import { Refs } from '../../types';
@@ -77,8 +76,8 @@ export default function transformProps(
const showMetricName = chartProps.rawFormData?.show_metric_name ?? false;
const formattedSubtitle = subtitle?.trim() ? subtitle : subheader || '';
const formattedSubtitleFontSize = subtitle?.trim()
? (subtitleFontSize ?? PROPORTION.SUBHEADER)
: (subheaderFontSize ?? subtitleFontSize ?? PROPORTION.SUBHEADER);
? (subtitleFontSize ?? 1)
: (subheaderFontSize ?? 1);
const bigNumber =
data.length === 0 ? null : parseMetricValue(data[0][metricName]);

View File

@@ -30,11 +30,20 @@ import {
import { styled, useTheme } from '@apache-superset/core/theme';
import Echart from '../components/Echart';
import { BigNumberVizProps } from './types';
import { PROPORTION } from './constants';
import { EventHandlers } from '../types';
const defaultNumberFormatter = getNumberFormatter();
const PROPORTION = {
// text size: proportion of the chart container sans trendline
METRIC_NAME: 0.125,
KICKER: 0.1,
HEADER: 0.3,
SUBHEADER: 0.125,
// trendline size: proportion of the whole chart container
TRENDLINE: 0.3,
};
function BigNumberVis({
className = '',
headerFormatter = defaultNumberFormatter,

View File

@@ -1,26 +0,0 @@
/**
* 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.
*/
export const PROPORTION = {
METRIC_NAME: 0.125,
KICKER: 0.1,
HEADER: 0.3,
SUBHEADER: 0.125,
TRENDLINE: 0.3,
};

View File

@@ -25,8 +25,8 @@ export const DEFAULT_FORM_DATA: Partial<EchartsBubbleFormData> = {
emitFilter: false,
logXAis: false,
logYAxis: false,
xAxisTitleMargin: 40,
yAxisTitleMargin: 50,
xAxisTitleMargin: 30,
yAxisTitleMargin: 30,
truncateXAxis: false,
truncateYAxis: false,
xAxisBounds: [null, null],

View File

@@ -144,7 +144,7 @@ const config: ControlPanelConfig = {
clearable: true,
label: t('X axis title margin'),
renderTrigger: true,
default: sections.TITLE_MARGIN_OPTIONS[3],
default: sections.TITLE_MARGIN_OPTIONS[1],
choices: formatSelectOptions(sections.TITLE_MARGIN_OPTIONS),
},
},
@@ -216,7 +216,7 @@ const config: ControlPanelConfig = {
clearable: true,
label: t('Y axis title margin'),
renderTrigger: true,
default: sections.TITLE_MARGIN_OPTIONS[4],
default: sections.TITLE_MARGIN_OPTIONS[1],
choices: formatSelectOptions(sections.TITLE_MARGIN_OPTIONS),
},
},

View File

@@ -156,9 +156,9 @@ const defaultFormData: EchartsTimeseriesFormData & {
showLegend: false,
legendSort: null,
xAxisTitle: '',
xAxisTitleMargin: 40,
xAxisTitleMargin: 0,
yAxisTitle: '',
yAxisTitleMargin: 50,
yAxisTitleMargin: 15,
yAxisTitlePosition: '',
time_range: 'No filter',
granularity: undefined,

View File

@@ -92,7 +92,7 @@ function createAxisTitleControl(axis: 'x' | 'y'): ControlSetRow[] {
clearable: true,
label: t('Axis title margin'),
renderTrigger: true,
default: sections.TITLE_MARGIN_OPTIONS[3],
default: sections.TITLE_MARGIN_OPTIONS[0],
choices: formatSelectOptions(sections.TITLE_MARGIN_OPTIONS),
visibility: ({ controls }: ControlPanelsContainerProps) =>
isXAxis ? isVertical(controls) : isHorizontal(controls),
@@ -125,7 +125,7 @@ function createAxisTitleControl(axis: 'x' | 'y'): ControlSetRow[] {
clearable: true,
label: t('Axis title margin'),
renderTrigger: true,
default: sections.TITLE_MARGIN_OPTIONS[4],
default: sections.TITLE_MARGIN_OPTIONS[1],
choices: formatSelectOptions(sections.TITLE_MARGIN_OPTIONS),
visibility: ({ controls }: ControlPanelsContainerProps) =>
isXAxis ? isHorizontal(controls) : isVertical(controls),

View File

@@ -44,9 +44,9 @@ export const DEFAULT_FORM_DATA: EchartsTimeseriesFormData = {
// ...DEFAULT_TITLE_FORM_DATA, // TODO: figure out why these break things for stories (e.g. Bubble Chart)
// here are the contents of DEFAULT_TITLE_FORM_DATA:
xAxisTitle: '',
xAxisTitleMargin: 40,
xAxisTitleMargin: 0,
yAxisTitle: '',
yAxisTitleMargin: 50,
yAxisTitleMargin: 15,
yAxisTitlePosition: 'Top',
// Now that the weird bug workaround is over, here's the rest...
...DEFAULT_SORT_SERIES_DATA,

View File

@@ -179,13 +179,7 @@ function Echart(
}
if (!divRef.current) return;
if (!chartRef.current) {
// Pass width and height to init to avoid "Can't get DOM width or height" warning
// since the DOM element may not have its dimensions yet when init is called
chartRef.current = init(divRef.current, null, {
locale,
width,
height,
});
chartRef.current = init(divRef.current, null, { locale });
}
// did mount
handleSizeChange({ width, height });

View File

@@ -107,9 +107,9 @@ export const DEFAULT_LEGEND_FORM_DATA: LegendFormData = {
export const DEFAULT_TITLE_FORM_DATA: TitleFormData = {
xAxisTitle: '',
xAxisTitleMargin: 40,
xAxisTitleMargin: 0,
yAxisTitle: '',
yAxisTitleMargin: 50,
yAxisTitleMargin: 15,
yAxisTitlePosition: 'Top',
};

View File

@@ -110,11 +110,11 @@ const formData: EchartsMixedTimeseriesFormData = {
truncateYAxisSecondary: false,
xAxisLabelRotation: 0,
xAxisTitle: '',
xAxisTitleMargin: 40,
xAxisTitleMargin: 0,
yAxisBounds: [undefined, undefined],
yAxisBoundsSecondary: [undefined, undefined],
yAxisTitle: '',
yAxisTitleMargin: 50,
yAxisTitleMargin: 15,
yAxisTitlePosition: '',
yAxisTitleSecondary: '',
zoomable: false,

View File

@@ -917,7 +917,7 @@ export class TableRenderer extends Component<
allowRenderHtml,
)}
<span
role="button"
role="columnheader"
tabIndex={0}
// Prevents event bubbling to avoid conflict with column header click handlers
// Ensures sort operation executes without triggering cross-filtration

View File

@@ -27,9 +27,9 @@
],
"dependencies": {
"@math.gl/web-mercator": "^4.1.0",
"mapbox-gl": "^3.22.0",
"maplibre-gl": "^5.24.0",
"react-map-gl": "^8.1.1",
"mapbox-gl": "^3.0.0",
"maplibre-gl": "^5.0.0",
"react-map-gl": "^8.0.0",
"supercluster": "^8.0.1"
},
"peerDependencies": {

View File

@@ -829,7 +829,7 @@ export default function TableChart<D extends DataRecord = DataRecord>(
th {
border-right: 1px solid ${theme.colorSplit};
}
th:first-of-type {
th:first-child {
border-left: none;
}
th:last-child {

View File

@@ -21,8 +21,7 @@ import { buildQueryContext, QueryFormOrderBy } from '@superset-ui/core';
import { WordCloudFormData } from '../types';
export default function buildQuery(formData: WordCloudFormData) {
const { metric, sort_by_metric, sort_by_series, series, row_limit } =
formData;
const { metric, sort_by_metric, series, row_limit } = formData;
const orderby: QueryFormOrderBy[] = [];
const shouldApplyOrderBy =
row_limit !== undefined && row_limit !== null && row_limit !== 0;
@@ -30,7 +29,7 @@ export default function buildQuery(formData: WordCloudFormData) {
if (sort_by_metric && metric) {
orderby.push([metric, false]);
}
if (sort_by_series !== false && series) {
if (series) {
orderby.push([series, true]);
}

View File

@@ -35,22 +35,6 @@ const config: ControlPanelConfig = {
['adhoc_filters'],
['row_limit'],
['sort_by_metric'],
[
{
name: 'sort_by_series',
config: {
type: 'CheckboxControl',
label: t('Sort by series'),
default: true,
description: t(
'Sort results by series name in ascending order. ' +
'When combined with "Sort by metric", this acts as a tiebreaker ' +
'for equal metric values. Adding this sort may reduce query ' +
'performance on some databases.',
),
},
},
],
],
},
{

View File

@@ -21,81 +21,17 @@ import { VizType } from '@superset-ui/core';
import { WordCloudFormData } from '../src';
import buildQuery from '../src/plugin/buildQuery';
const basicFormData: WordCloudFormData = {
datasource: '5__table',
granularity_sqla: 'ds',
series: 'foo',
viz_type: VizType.WordCloud,
};
describe('WordCloud buildQuery', () => {
const formData: WordCloudFormData = {
datasource: '5__table',
granularity_sqla: 'ds',
series: 'foo',
viz_type: VizType.WordCloud,
};
describe('plugin-chart-word-cloud', () => {
describe('buildQuery', () => {
test('should build columns from series in form data', () => {
const queryContext = buildQuery(basicFormData);
const [query] = queryContext.queries;
expect(query.columns).toEqual(['foo']);
});
test('should not include orderby when neither sort option is enabled', () => {
const queryContext = buildQuery({
...basicFormData,
metric: 'count',
sort_by_metric: false,
sort_by_series: false,
row_limit: 100,
});
const [query] = queryContext.queries;
expect(query.orderby).toBeUndefined();
});
test('should order by metric DESC only when sort_by_metric is true', () => {
const queryContext = buildQuery({
...basicFormData,
metric: 'count',
sort_by_metric: true,
sort_by_series: false,
row_limit: 100,
});
const [query] = queryContext.queries;
expect(query.orderby).toEqual([['count', false]]);
});
test('should order by series ASC only when sort_by_series is true', () => {
const queryContext = buildQuery({
...basicFormData,
metric: 'count',
sort_by_metric: false,
sort_by_series: true,
row_limit: 100,
});
const [query] = queryContext.queries;
expect(query.orderby).toEqual([['foo', true]]);
});
test('should order by metric DESC then series ASC when both are true', () => {
const queryContext = buildQuery({
...basicFormData,
metric: 'count',
sort_by_metric: true,
sort_by_series: true,
row_limit: 100,
});
const [query] = queryContext.queries;
expect(query.orderby).toEqual([
['count', false],
['foo', true],
]);
});
test('should order by series ASC when sort_by_series is undefined (legacy chart)', () => {
const queryContext = buildQuery({
...basicFormData,
metric: 'count',
sort_by_metric: false,
row_limit: 100,
});
const [query] = queryContext.queries;
expect(query.orderby).toEqual([['foo', true]]);
});
test('should build columns from series in form data', () => {
const queryContext = buildQuery(formData);
const [query] = queryContext.queries;
expect(query.columns).toEqual(['foo']);
});
});

View File

@@ -16,7 +16,6 @@
* specific language governing permissions and limitations
* under the License.
*/
import { isCustomControlItem } from '@superset-ui/chart-controls';
import controlPanel from '../src/plugin/controlPanel';
import React, { ReactElement } from 'react';
@@ -46,24 +45,3 @@ test('control panel has rotation and color_scheme controls', () => {
);
expect(colorSchemeRow).toBeDefined();
});
test('sort_by_series defaults to true to preserve legacy ordering', () => {
const querySection = controlPanel.controlPanelSections.find(
(section): section is NonNullable<typeof section> =>
Boolean(section && section.label === 'Query'),
);
expect(querySection).toBeDefined();
if (!querySection) {
throw new Error('Query section missing');
}
const sortBySeriesEntry = querySection.controlSetRows
.flat()
.find(item => isCustomControlItem(item) && item.name === 'sort_by_series');
expect(isCustomControlItem(sortBySeriesEntry)).toBe(true);
if (!isCustomControlItem(sortBySeriesEntry)) {
throw new Error('sort_by_series control missing');
}
expect(sortBySeriesEntry.config.default).toBe(true);
});

View File

@@ -29,7 +29,7 @@
"@deck.gl/extensions": "~9.2.9",
"@deck.gl/geo-layers": "~9.2.5",
"@deck.gl/layers": "~9.2.5",
"@deck.gl/mapbox": "~9.3.1",
"@deck.gl/mapbox": "~9.2.5",
"@deck.gl/mesh-layers": "~9.2.5",
"@luma.gl/constants": "~9.2.5",
"@luma.gl/core": "~9.2.5",
@@ -46,11 +46,11 @@
"d3-scale": "^4.0.2",
"handlebars": "^4.7.9",
"lodash": "^4.18.1",
"maplibre-gl": "^5.24.0",
"maplibre-gl": "^5.0.0",
"mousetrap": "^1.6.5",
"ngeohash": "^0.6.3",
"prop-types": "^15.8.1",
"react-map-gl": "^8.1.1",
"react-map-gl": "^8.0.0",
"underscore": "^1.13.7",
"urijs": "^1.19.11",
"xss": "^1.0.15"

View File

@@ -124,25 +124,6 @@ describe('ShareSqlLabQuery', () => {
).toEqual(expected);
});
test('does not show duplicate "Copy to clipboard" tooltip on hover', async () => {
await act(async () => {
render(<ShareSqlLabQuery {...defaultProps} />, {
useRedux: true,
store,
});
});
const button = screen.getByRole('button');
userEvent.hover(button);
expect(
await screen.findByText('Copy query link to your clipboard'),
).toBeInTheDocument();
await waitFor(() => {
// CopyToClipboard default tooltip must NOT appear —
// only the Button-level "Copy query link to your clipboard" should show.
expect(screen.queryByText('Copy to clipboard')).not.toBeInTheDocument();
});
});
test('calls storeQuery() with unsaved changes', async () => {
await act(async () => {
render(<ShareSqlLabQuery {...defaultProps} />, {

View File

@@ -89,7 +89,6 @@ const ShareSqlLabQuery = ({
getText={getCopyUrl}
wrapped={false}
copyNode={buildButton()}
hideTooltip
/>
);
};

View File

@@ -22,7 +22,7 @@ import { connect } from 'react-redux';
import type { QueryEditor, SqlLabRootState } from 'src/SqlLab/types';
import { t } from '@apache-superset/core/translation';
import { FeatureFlag, isFeatureEnabled } from '@superset-ui/core';
import { styled } from '@apache-superset/core/theme';
import { styled, css } from '@apache-superset/core/theme';
import { Logger } from 'src/logger/LogUtils';
import { EmptyState, Tooltip } from '@superset-ui/core/components';
import { detectOS } from 'src/utils/common';
@@ -89,11 +89,6 @@ const TabTitle = styled.span`
text-transform: none;
`;
const AddTabIconWrapper = styled.span`
display: inline-flex;
vertical-align: middle;
`;
// Get the user's OS
const userOS = detectOS();
@@ -199,9 +194,13 @@ class TabbedSqlEditors extends PureComponent<TabbedSqlEditorsProps> {
: t('New tab (Ctrl + t)')
}
>
<AddTabIconWrapper>
<Icons.PlusCircleOutlined iconSize="s" data-test="add-tab-icon" />
</AddTabIconWrapper>
<Icons.PlusCircleOutlined
iconSize="s"
css={css`
vertical-align: middle;
`}
data-test="add-tab-icon"
/>
</Tooltip>
</StyledTab>
);
@@ -242,9 +241,13 @@ class TabbedSqlEditors extends PureComponent<TabbedSqlEditorsProps> {
: t('New tab (Ctrl + t)')
}
>
<AddTabIconWrapper>
<Icons.PlusOutlined iconSize="l" data-test="add-tab-icon" />
</AddTabIconWrapper>
<Icons.PlusOutlined
iconSize="l"
css={css`
vertical-align: middle;
`}
data-test="add-tab-icon"
/>
</Tooltip>
}
items={tabItems}

View File

@@ -79,7 +79,6 @@ export interface TreeNodeRendererProps extends NodeRendererProps<TreeNodeData> {
searchTerm: string;
catalog: string | null | undefined;
pinnedTableKeys: Set<string>;
pinnedSchemas: Set<string>;
selectStarMap: Record<string, string>;
handleRefreshTables: (params: {
dbId: number;
@@ -92,11 +91,6 @@ export interface TreeNodeRendererProps extends NodeRendererProps<TreeNodeData> {
catalogName: string | null,
) => void;
handleUnpinTable: (tableName: string, schemaName: string) => void;
handlePinSchema: (schemaName: string) => void;
handleUnpinSchema: (schemaName: string) => void;
refreshTableSchema: (id: string) => void;
sortedTables: Record<string, boolean>;
toggleSortColumns: (tableId: string) => void;
}
const TreeNodeRenderer: React.FC<TreeNodeRendererProps> = ({
@@ -107,23 +101,19 @@ const TreeNodeRenderer: React.FC<TreeNodeRendererProps> = ({
searchTerm,
catalog,
pinnedTableKeys,
pinnedSchemas,
selectStarMap,
handleRefreshTables,
handlePinTable,
handleUnpinTable,
handlePinSchema,
handleUnpinSchema,
refreshTableSchema,
sortedTables,
toggleSortColumns,
}) => {
const theme = useTheme();
const { data } = node;
const parts = data.id.split(':');
const [identifier, _dbId, schema, tableName] = parts;
const isManuallyOpen = node.isOpen && !node.data.disableCheckbox;
// Use manually tracked open state for icon display
// This prevents search auto-expansion from affecting the icon
const isManuallyOpen = manuallyOpenedNodes[data.id] ?? false;
const isLoading = loadingNodes[data.id] ?? false;
const renderIcon = () => {
@@ -145,7 +135,12 @@ const TreeNodeRenderer: React.FC<TreeNodeRendererProps> = ({
? Icons.FunctionOutlined
: Icons.TableOutlined;
if (isLoading) {
return <Icons.LoadingOutlined iconSize="l" />;
return (
<>
<Icons.LoadingOutlined iconSize="l" />
<TableTypeIcon iconSize="l" />
</>
);
}
return <TableTypeIcon iconSize="l" />;
}
@@ -238,27 +233,7 @@ const TreeNodeRenderer: React.FC<TreeNodeRendererProps> = ({
{highlightText(data.name, searchTerm)}
</Typography.Text>
{identifier === 'schema' && (
<div
className="side-action-container"
role="menu"
onClick={e => e.stopPropagation()}
>
{pinnedSchemas.has(schema) && (
<div className="action-static">
<ActionButton
label={`pinned-schema-${schema}`}
icon={
<Icons.PushpinFilled
iconSize="m"
css={css`
color: ${theme.colorTextDescription};
`}
/>
}
onClick={() => handleUnpinSchema(schema)}
/>
</div>
)}
<div className="side-action-container" role="menu">
<div className="action-hover">
<RefreshLabel
onClick={e => {
@@ -271,30 +246,6 @@ const TreeNodeRenderer: React.FC<TreeNodeRendererProps> = ({
}}
tooltipContent={t('Force refresh table list')}
/>
<ActionButton
label={
pinnedSchemas.has(schema)
? `unpin-schema-${schema}`
: `pin-schema-${schema}`
}
tooltip={
pinnedSchemas.has(schema)
? t('Unpin from top')
: t('Pin to top')
}
icon={
pinnedSchemas.has(schema) ? (
<Icons.PushpinFilled iconSize="m" />
) : (
<Icons.PushpinOutlined iconSize="m" />
)
}
onClick={() =>
pinnedSchemas.has(schema)
? handleUnpinSchema(schema)
: handlePinSchema(schema)
}
/>
</div>
</div>
)}
@@ -337,31 +288,6 @@ const TreeNodeRenderer: React.FC<TreeNodeRendererProps> = ({
}
/>
)}
<ActionButton
label={`sort-cols-${schema}-${tableName}`}
tooltip={
sortedTables[data.id]
? t('Sort by original table order')
: t('Sort columns alphabetically')
}
icon={
<Icons.SortAscendingOutlined
iconSize="m"
css={css`
color: ${sortedTables[data.id]
? theme.colorPrimary
: 'inherit'};
`}
/>
}
onClick={() => toggleSortColumns(data.id)}
/>
<ActionButton
label={`refresh-schema-${schema}-${tableName}`}
tooltip={t('Refresh table schema')}
icon={<Icons.SyncOutlined iconSize="m" />}
onClick={() => refreshTableSchema(data.id)}
/>
<ActionButton
label={
isPinned
@@ -386,19 +312,18 @@ const TreeNodeRenderer: React.FC<TreeNodeRendererProps> = ({
: handlePinTable(tableName, schema, catalog ?? null)
}
/>
<ActionButton
label={`toggle-${schema}-${tableName}`}
tooltip={isManuallyOpen ? t('Collapse') : t('Expand')}
icon={
isManuallyOpen ? (
<Icons.UpOutlined iconSize="m" />
) : (
<Icons.DownOutlined iconSize="m" />
)
}
onClick={() => node.toggle()}
/>
</div>
<ActionButton
label={`toggle-${schema}-${tableName}`}
icon={
isManuallyOpen ? (
<Icons.UpOutlined iconSize="m" />
) : (
<Icons.DownOutlined iconSize="m" />
)
}
onClick={() => node.toggle()}
/>
</div>
);
})()}

View File

@@ -24,7 +24,6 @@ import {
type ChangeEvent,
useMemo,
} from 'react';
import { useDebounceValue } from 'src/hooks/useDebounceValue';
import { useSelector, useDispatch, shallowEqual } from 'react-redux';
import { styled, css, useTheme } from '@apache-superset/core/theme';
import { t } from '@apache-superset/core/translation';
@@ -42,11 +41,6 @@ import {
import type { SqlLabRootState } from 'src/SqlLab/types';
import useQueryEditor from 'src/SqlLab/hooks/useQueryEditor';
import { addTable, removeTables } from 'src/SqlLab/actions/sqlLab';
import {
getItem,
setItem,
LocalStorageKeys,
} from 'src/utils/localStorageHelpers';
import PanelToolbar from 'src/components/PanelToolbar';
import { ViewLocations } from 'src/SqlLab/contributions';
import TreeNodeRenderer from './TreeNodeRenderer';
@@ -132,36 +126,6 @@ const StyledTreeContainer = styled.div`
const ROW_HEIGHT = 28;
const getPinnedSchemasStorageKey = (
dbId: number | undefined,
catalog: string | null | undefined,
): string => `${dbId ?? ''}:${catalog ?? ''}`;
const getPinnedSchemasFromStorage = (
dbId: number | undefined,
catalog: string | null | undefined,
): Set<string> => {
if (!dbId) return new Set();
const stored = getItem(LocalStorageKeys.SqllabPinnedSchemas, {});
const key = getPinnedSchemasStorageKey(dbId, catalog);
const schemas = stored[key];
return Array.isArray(schemas) ? new Set<string>(schemas) : new Set();
};
const savePinnedSchemasToStorage = (
dbId: number | undefined,
catalog: string | null | undefined,
schemas: Set<string>,
) => {
if (!dbId) return;
const stored = getItem(LocalStorageKeys.SqllabPinnedSchemas, {});
const key = getPinnedSchemasStorageKey(dbId, catalog);
setItem(LocalStorageKeys.SqllabPinnedSchemas, {
...stored,
[key]: [...schemas],
});
};
const TableExploreTree: React.FC<Props> = ({ queryEditorId }) => {
const dispatch = useDispatch();
const theme = useTheme();
@@ -197,7 +161,6 @@ const TableExploreTree: React.FC<Props> = ({ queryEditorId }) => {
selectStarMap,
handleToggle,
handleRefreshTables,
refreshTableSchema,
errorPayload,
} = useTreeData({
dbId,
@@ -236,85 +199,7 @@ const TableExploreTree: React.FC<Props> = ({ queryEditorId }) => {
},
[dispatch, tables, editorId, dbId],
);
const [pinnedSchemas, setPinnedSchemas] = useState<Set<string>>(() =>
getPinnedSchemasFromStorage(dbId, catalog),
);
const previousDbIdRef = useRef<number | undefined>(dbId);
const previousCatalogRef = useRef<string | null | undefined>(catalog);
// Single effect handles both loading and persisting pinned schemas.
// Using refs to detect source changes avoids the race condition where the
// persist branch would run with stale pinnedSchemas right after a dbId/catalog
// change, corrupting the new source's stored pins.
useEffect(() => {
const dbChanged = previousDbIdRef.current !== dbId;
const catalogChanged = previousCatalogRef.current !== catalog;
if (dbChanged || catalogChanged) {
previousDbIdRef.current = dbId;
previousCatalogRef.current = catalog;
setPinnedSchemas(getPinnedSchemasFromStorage(dbId, catalog));
return;
}
savePinnedSchemasToStorage(dbId, catalog, pinnedSchemas);
}, [dbId, catalog, pinnedSchemas]);
const handlePinSchema = useCallback((schemaName: string) => {
setPinnedSchemas(prev => new Set([...prev, schemaName]));
}, []);
const handleUnpinSchema = useCallback((schemaName: string) => {
setPinnedSchemas(prev => {
const next = new Set(prev);
next.delete(schemaName);
return next;
});
}, []);
const sortedTreeData = useMemo(() => {
if (pinnedSchemas.size === 0) return treeData;
const pinned = treeData.filter(node => pinnedSchemas.has(node.name));
const rest = treeData.filter(node => !pinnedSchemas.has(node.name));
return [...pinned, ...rest];
}, [treeData, pinnedSchemas]);
const [sortedTables, setSortedTables] = useState<Record<string, boolean>>({});
useEffect(() => {
setSortedTables({});
}, [dbId, catalog]);
const toggleSortColumns = useCallback((tableId: string) => {
setSortedTables(prev => ({ ...prev, [tableId]: !prev[tableId] }));
}, []);
const displayTreeData = useMemo(() => {
const activeSorted = Object.keys(sortedTables).filter(
id => sortedTables[id],
);
if (activeSorted.length === 0) return sortedTreeData;
const sortedSet = new Set(activeSorted);
return sortedTreeData.map(schemaNode => ({
...schemaNode,
children: schemaNode.children?.map(tableNode => {
if (tableNode.type !== 'table' || !sortedSet.has(tableNode.id)) {
return tableNode;
}
const { children } = tableNode;
if (!children || children.length <= 1) return tableNode;
return {
...tableNode,
children: [...children].sort((a, b) => a.name.localeCompare(b.name)),
};
}),
}));
}, [sortedTreeData, sortedTables]);
const [searchTerm, setSearchTerm] = useState('');
const debouncedSearchTerm = useDebounceValue(searchTerm);
const handleSearchChange = useCallback(
({ target }: ChangeEvent<HTMLInputElement>) => setSearchTerm(target.value),
[],
@@ -372,9 +257,9 @@ const TableExploreTree: React.FC<Props> = ({ queryEditorId }) => {
// Check if any nodes match the search term
const hasMatchingNodes = useMemo(() => {
if (!debouncedSearchTerm) return true;
if (!searchTerm) return true;
const lowerTerm = debouncedSearchTerm.toLowerCase();
const lowerTerm = searchTerm.toLowerCase();
const checkNode = (node: TreeNodeData): boolean => {
if (node.type === 'empty') return false;
@@ -385,8 +270,8 @@ const TableExploreTree: React.FC<Props> = ({ queryEditorId }) => {
return false;
};
return displayTreeData.some(node => checkNode(node));
}, [debouncedSearchTerm, displayTreeData]);
return treeData.some(node => checkNode(node));
}, [searchTerm, treeData]);
// Node renderer for react-arborist
const renderNode = useCallback(
@@ -395,37 +280,25 @@ const TableExploreTree: React.FC<Props> = ({ queryEditorId }) => {
{...props}
manuallyOpenedNodes={manuallyOpenedNodes}
loadingNodes={loadingNodes}
searchTerm={debouncedSearchTerm}
searchTerm={searchTerm}
catalog={catalog}
pinnedTableKeys={pinnedTableKeys}
pinnedSchemas={pinnedSchemas}
selectStarMap={selectStarMap}
handleRefreshTables={handleRefreshTables}
handlePinTable={handlePinTable}
handleUnpinTable={handleUnpinTable}
handlePinSchema={handlePinSchema}
handleUnpinSchema={handleUnpinSchema}
refreshTableSchema={refreshTableSchema}
sortedTables={sortedTables}
toggleSortColumns={toggleSortColumns}
/>
),
[
catalog,
pinnedTableKeys,
pinnedSchemas,
selectStarMap,
handleRefreshTables,
handlePinTable,
handleUnpinTable,
handlePinSchema,
handleUnpinSchema,
refreshTableSchema,
sortedTables,
toggleSortColumns,
loadingNodes,
manuallyOpenedNodes,
debouncedSearchTerm,
searchTerm,
],
);
@@ -484,7 +357,7 @@ const TableExploreTree: React.FC<Props> = ({ queryEditorId }) => {
return <Skeleton active />;
}
if (debouncedSearchTerm && !hasMatchingNodes) {
if (searchTerm && !hasMatchingNodes) {
return (
<Empty
description={t('No matching results found')}
@@ -496,12 +369,12 @@ const TableExploreTree: React.FC<Props> = ({ queryEditorId }) => {
return (
<Tree<TreeNodeData>
ref={treeRef}
data={displayTreeData}
data={treeData}
width="100%"
height={height || 500}
rowHeight={ROW_HEIGHT}
indent={16}
searchTerm={debouncedSearchTerm}
searchTerm={searchTerm}
searchMatch={searchMatch}
disableDrag
disableDrop
@@ -527,7 +400,7 @@ const TableExploreTree: React.FC<Props> = ({ queryEditorId }) => {
// react-arborist marks all schemas as open (isOpen=true) even before any
// user interaction. Using treeRef in that case would treat every first
// click as a close action, so fall back to manuallyOpenedNodes instead.
const wasOpen = debouncedSearchTerm
const wasOpen = searchTerm
? (treeRef.current?.get(id)?.isOpen ??
manuallyOpenedNodes[id] ??
false)

View File

@@ -17,7 +17,6 @@
* under the License.
*/
import { useMemo, useReducer, useCallback } from 'react';
import { useDispatch } from 'react-redux';
import { t } from '@apache-superset/core/translation';
import {
Table,
@@ -27,7 +26,6 @@ import {
useLazyTableMetadataQuery,
useLazyTableExtendedMetadataQuery,
} from 'src/hooks/apiResources';
import { addDangerToast } from 'src/SqlLab/actions/sqlLab';
import type { TreeNodeData } from './types';
import { SupersetError } from '@superset-ui/core';
@@ -44,7 +42,6 @@ interface TreeDataState {
type TreeDataAction =
| { type: 'SET_TABLE_DATA'; key: string; data: { options: Table[] } }
| { type: 'SET_TABLE_SCHEMA_DATA'; key: string; data: TableMetaData }
| { type: 'CLEAR_TABLE_SCHEMA_DATA'; key: string }
| { type: 'SET_LOADING_NODE'; nodeId: string; loading: boolean }
| { type: 'SET_ERROR'; errorPayload: SupersetError | null };
@@ -74,10 +71,6 @@ function treeDataReducer(
[action.key]: action.data,
},
};
case 'CLEAR_TABLE_SCHEMA_DATA': {
const { [action.key]: _, ...rest } = state.tableSchemaData;
return { ...state, tableSchemaData: rest };
}
case 'SET_LOADING_NODE':
return {
...state,
@@ -115,7 +108,6 @@ interface UseTreeDataResult {
catalog: string | null | undefined;
schema: string;
}) => void;
refreshTableSchema: (id: string) => void;
errorPayload: SupersetError | null;
}
@@ -130,7 +122,6 @@ const useTreeData = ({
catalog,
pinnedTables,
}: UseTreeDataParams): UseTreeDataResult => {
const reduxDispatch = useDispatch();
// Schema data from API
const {
currentData: schemaData,
@@ -146,64 +137,6 @@ const useTreeData = ({
const [state, dispatch] = useReducer(treeDataReducer, initialState);
const { tableData, tableSchemaData, loadingNodes, errorPayload } = state;
// Shared helper: fetch table metadata + extended metadata and store in state.
// preferCacheValue=true on initial open (use cached data if available),
// preferCacheValue=false on explicit refresh (bypass cache).
const fetchAndStoreTableSchema = useCallback(
(id: string, preferCacheValue: boolean) => {
if (loadingNodes[id]) return;
const parts = id.split(':');
const [, databaseId, schema, table] = parts;
const parsedDbId = Number(databaseId);
const tableKey = `${parsedDbId}:${schema}:${table}`;
dispatch({ type: 'SET_LOADING_NODE', nodeId: id, loading: true });
// .unwrap() causes RTK Query to reject on error so .catch() fires.
// Without it RTK Query resolves with { error } instead of rejecting.
Promise.all([
fetchTableMetadata(
{ dbId: parsedDbId, catalog, schema, table },
preferCacheValue,
).unwrap(),
fetchTableExtendedMetadata(
{ dbId: parsedDbId, catalog, schema, table },
preferCacheValue,
).unwrap(),
])
.then(([tableMetadata, tableExtendedMetadata]) => {
if (tableMetadata) {
dispatch({
type: 'SET_TABLE_SCHEMA_DATA',
key: tableKey,
data: { ...tableMetadata, ...tableExtendedMetadata },
});
}
})
.catch(() => {
reduxDispatch(
addDangerToast(
t(
'An error occurred while fetching table metadata for %s',
table,
),
),
);
})
.finally(() => {
dispatch({ type: 'SET_LOADING_NODE', nodeId: id, loading: false });
});
},
[
catalog,
fetchTableExtendedMetadata,
fetchTableMetadata,
loadingNodes,
reduxDispatch,
],
);
// Handle async loading when node is toggled open
const handleToggle = useCallback(
async (id: string, isOpen: boolean) => {
@@ -217,14 +150,20 @@ const useTreeData = ({
if (identifier === 'schema') {
const schemaKey = `${parsedDbId}:${schema}`;
if (!tableData?.[schemaKey]) {
// Set loading state
dispatch({ type: 'SET_LOADING_NODE', nodeId: id, loading: true });
// Fetch tables asynchronously
fetchLazyTables(
{ dbId: parsedDbId, catalog, schema, forceRefresh: false },
{
dbId: parsedDbId,
catalog,
schema,
forceRefresh: false,
},
true,
)
.unwrap()
.then(data => {
.then(({ data }) => {
if (data) {
dispatch({ type: 'SET_TABLE_DATA', key: schemaKey, data });
}
@@ -252,14 +191,59 @@ const useTreeData = ({
if (pinnedTables[tableKey]) return;
if (!tableSchemaData[tableKey]) {
fetchAndStoreTableSchema(id, true);
// Set loading state
dispatch({ type: 'SET_LOADING_NODE', nodeId: id, loading: true });
// Fetch metadata asynchronously
Promise.all([
fetchTableMetadata(
{
dbId: parsedDbId,
catalog,
schema,
table,
},
true,
),
fetchTableExtendedMetadata(
{
dbId: parsedDbId,
catalog,
schema,
table,
},
true,
),
])
.then(
([{ data: tableMetadata }, { data: tableExtendedMetadata }]) => {
if (tableMetadata) {
dispatch({
type: 'SET_TABLE_SCHEMA_DATA',
key: tableKey,
data: {
...tableMetadata,
...tableExtendedMetadata,
},
});
}
},
)
.finally(() => {
dispatch({
type: 'SET_LOADING_NODE',
nodeId: id,
loading: false,
});
});
}
}
},
[
catalog,
fetchAndStoreTableSchema,
fetchLazyTables,
fetchTableExtendedMetadata,
fetchTableMetadata,
pinnedTables,
tableData,
tableSchemaData,
@@ -305,13 +289,6 @@ const useTreeData = ({
[fetchLazyTables],
);
const refreshTableSchema = useCallback(
(id: string) => {
fetchAndStoreTableSchema(id, false);
},
[fetchAndStoreTableSchema],
);
// Build tree data
const treeData = useMemo((): TreeNodeData[] => {
const data = schemaData?.map(schema => {
@@ -401,7 +378,6 @@ const useTreeData = ({
selectStarMap,
handleToggle,
handleRefreshTables,
refreshTableSchema,
errorPayload,
};
};

View File

@@ -34,7 +34,6 @@ const apiData = {
lastName: 'last name',
permissions: {},
roles: {},
groups: [],
},
};
const apiDataWithTabState = {

View File

@@ -32,7 +32,6 @@ jest.mock('@superset-ui/core', () => ({
const mockSupersetClientGet = SupersetClient.get as jest.Mock;
const defaultProps: PluginDeckglLayerVisibilityProps = {
data: [],
formData: {
viz_type: 'deckgl_layer_visibility',
defaultToAllLayersVisible: true,
@@ -41,13 +40,7 @@ const defaultProps: PluginDeckglLayerVisibilityProps = {
height: 400,
width: 600,
filterState: {},
inputRef: { current: null },
setDataMask: jest.fn(),
setFocusedFilter: jest.fn(),
unsetFocusedFilter: jest.fn(),
setHoveredFilter: jest.fn(),
unsetHoveredFilter: jest.fn(),
setFilterActive: jest.fn(),
};
const mockCharts = {
@@ -92,13 +85,10 @@ test('displays loading state initially', () => {
},
});
expect(
screen.getByTestId('deckgl-layer-visibility-select'),
).toBeInTheDocument();
expect(screen.getByRole('combobox')).toBeDisabled();
expect(screen.getByText('Loading deck.gl layers...')).toBeInTheDocument();
});
test('displays disabled select when no deck.gl multi layer charts are found', async () => {
test('displays message when no deck.gl multi layer charts are found', async () => {
mockSupersetClientGet.mockResolvedValue({ json: { result: [] } });
render(<DeckglLayerVisibilityCustomizationPlugin {...defaultProps} />, {
@@ -117,7 +107,11 @@ test('displays disabled select when no deck.gl multi layer charts are found', as
});
await waitFor(() => {
expect(screen.getByRole('combobox')).toBeDisabled();
expect(
screen.getByText(
'No deck.gl multi layer charts found in this dashboard.',
),
).toBeInTheDocument();
});
});
@@ -132,10 +126,10 @@ test('renders layer selection control with layers from API', async () => {
});
await waitFor(() => {
expect(
screen.getByTestId('deckgl-layer-visibility-select'),
).toBeInTheDocument();
expect(screen.getByText('Exclude layers (deck.gl)')).toBeInTheDocument();
});
expect(screen.getByRole('combobox')).toBeInTheDocument();
});
test('collects unique layer IDs from multiple deck_multi charts', async () => {
@@ -174,9 +168,7 @@ test('handles layer selection and calls setDataMask', async () => {
);
await waitFor(() => {
expect(
screen.getByTestId('deckgl-layer-visibility-select'),
).toBeInTheDocument();
expect(screen.getByText('Exclude layers (deck.gl)')).toBeInTheDocument();
});
const select = screen.getByRole('combobox');
@@ -219,9 +211,7 @@ test('initializes with filterState value when provided', async () => {
);
await waitFor(() => {
expect(
screen.getByTestId('deckgl-layer-visibility-select'),
).toBeInTheDocument();
expect(screen.getByText('Exclude layers (deck.gl)')).toBeInTheDocument();
});
const select = screen.getByRole('combobox');
@@ -290,9 +280,7 @@ test('does not auto-initialize when defaultToAllLayersVisible is false', async (
);
await waitFor(() => {
expect(
screen.getByTestId('deckgl-layer-visibility-select'),
).toBeInTheDocument();
expect(screen.getByText('Exclude layers (deck.gl)')).toBeInTheDocument();
});
expect(setDataMaskMock).not.toHaveBeenCalled();
@@ -316,9 +304,7 @@ test('handles multiple layer selection', async () => {
);
await waitFor(() => {
expect(
screen.getByTestId('deckgl-layer-visibility-select'),
).toBeInTheDocument();
expect(screen.getByText('Exclude layers (deck.gl)')).toBeInTheDocument();
});
const select = screen.getByRole('combobox');
@@ -345,36 +331,29 @@ test('handles multiple layer selection', async () => {
});
});
test('displays tooltip on hover when select is disabled', async () => {
mockSupersetClientGet.mockResolvedValue({ json: { result: [] } });
test('displays tooltip info icon', async () => {
mockSupersetClientGet.mockResolvedValue(mockApiResponse);
render(<DeckglLayerVisibilityCustomizationPlugin {...defaultProps} />, {
useRedux: true,
initialState: {
sliceEntities: {
slices: {
chart1: {
form_data: {
viz_type: 'line',
},
},
},
},
sliceEntities: { slices: mockCharts },
},
});
await waitFor(() => {
expect(
screen.getByTestId('deckgl-layer-visibility-select'),
).toBeInTheDocument();
expect(screen.getByText('Exclude layers (deck.gl)')).toBeInTheDocument();
});
await userEvent.hover(screen.getByTestId('deckgl-layer-visibility-select'));
const tooltipIcon = screen.getByRole('img', { name: /info-circle/i });
expect(tooltipIcon).toBeInTheDocument();
await userEvent.hover(tooltipIcon);
await waitFor(() => {
expect(
screen.getByText(
'No multilayer deck.gl charts are currently added to this dashboard.',
'Choose layers to hide from all deck.gl Multiple Layer charts in this dashboard.',
),
).toBeInTheDocument();
});
@@ -399,7 +378,11 @@ test('handles charts with undefined deck_slices', async () => {
});
await waitFor(() => {
expect(screen.getByRole('combobox')).toBeDisabled();
expect(
screen.getByText(
'No deck.gl multi layer charts found in this dashboard.',
),
).toBeInTheDocument();
});
});
@@ -423,7 +406,11 @@ test('handles charts with non-array deck_slices', async () => {
});
await waitFor(() => {
expect(screen.getByRole('combobox')).toBeDisabled();
expect(
screen.getByText(
'No deck.gl multi layer charts found in this dashboard.',
),
).toBeInTheDocument();
});
});
@@ -460,30 +447,6 @@ test('deduplicates layer IDs from multiple charts', async () => {
expect(callArgs.endpoint).toContain('/api/v1/chart/?q=');
});
test('renders validate message when filterState has validateMessage', async () => {
mockSupersetClientGet.mockResolvedValue(mockApiResponse);
render(
<DeckglLayerVisibilityCustomizationPlugin
{...defaultProps}
filterState={{
validateMessage: 'This field is required',
validateStatus: 'error',
}}
/>,
{
useRedux: true,
initialState: {
sliceEntities: { slices: mockCharts },
},
},
);
await waitFor(() => {
expect(screen.getByText('This field is required')).toBeInTheDocument();
});
});
test('respects existing visible_deckgl_layers from Redux state', async () => {
mockSupersetClientGet.mockResolvedValue(mockApiResponse);
const setDataMaskMock = jest.fn();
@@ -514,9 +477,7 @@ test('respects existing visible_deckgl_layers from Redux state', async () => {
);
await waitFor(() => {
expect(
screen.getByTestId('deckgl-layer-visibility-select'),
).toBeInTheDocument();
expect(screen.getByText('Exclude layers (deck.gl)')).toBeInTheDocument();
});
expect(setDataMaskMock).not.toHaveBeenCalled();

View File

@@ -19,17 +19,19 @@
import { useEffect, useState, useMemo, useRef, useCallback } from 'react';
import { t } from '@apache-superset/core/translation';
import { DataMask, ExtraFormData } from '@superset-ui/core';
import { useTheme } from '@apache-superset/core/theme';
import {
Select,
FormItem,
Tooltip,
type FormItemProps,
Icons,
Flex,
} from '@superset-ui/core/components';
import { useSelector } from 'react-redux';
import { createSelector } from '@reduxjs/toolkit';
import { PluginDeckglLayerVisibilityProps } from './types';
import { useDeckLayerMetadata } from './useDeckLayerMetadata';
import { FilterPluginStyle, StatusMessage } from '../common';
import { FilterPluginStyle } from '../common';
import { Slice } from 'src/dashboard/types';
type SliceEntitiesState = {
@@ -70,6 +72,7 @@ export default function DeckglLayerVisibilityCustomizationPlugin(
props: PluginDeckglLayerVisibilityProps,
) {
const { formData, filterState, setDataMask, width, height } = props;
const theme = useTheme();
const [hiddenLayers, setHiddenLayers] = useState<number[]>(
filterState?.value || [],
);
@@ -125,19 +128,6 @@ export default function DeckglLayerVisibilityCustomizationPlugin(
setDataMask,
]);
const formItemData: FormItemProps = useMemo(() => {
if (filterState.validateMessage) {
return {
extra: (
<StatusMessage status={filterState.validateStatus}>
{filterState.validateMessage}
</StatusMessage>
),
};
}
return EMPTY_OBJECT as FormItemProps;
}, [filterState.validateMessage, filterState.validateStatus]);
const handleLayerChange = useCallback(
(selectedHiddenLayers: number[]) => {
setHiddenLayers(selectedHiddenLayers);
@@ -167,34 +157,48 @@ export default function DeckglLayerVisibilityCustomizationPlugin(
[apiLayers],
);
if (isLoadingMetadata && apiLayers.length === 0) {
return (
<FilterPluginStyle height={height} width={width}>
<div>{t('Loading deck.gl layers...')}</div>
</FilterPluginStyle>
);
}
return (
<FilterPluginStyle height={height} width={width}>
<FormItem validateStatus={filterState.validateStatus} {...formItemData}>
<Tooltip
title={
!isLoadingMetadata && apiLayers.length === 0
? t(
'No multilayer deck.gl charts are currently added to this dashboard.',
)
: null
{apiLayers.length === 0 ? (
<div>{t('No deck.gl multi layer charts found in this dashboard.')}</div>
) : (
<FormItem
label={
<Flex gap={theme.sizeUnit}>
<span>{t('Exclude layers (deck.gl)')}</span>
<Tooltip
title={t(
'Choose layers to hide from all deck.gl Multiple Layer charts in this dashboard.',
)}
>
<span className="tooltip-icon">
<Icons.InfoCircleOutlined
iconSize="m"
iconColor={theme.colorIcon}
/>
</span>
</Tooltip>
</Flex>
}
>
<div>
<Select
data-test="deckgl-layer-visibility-select"
mode="multiple"
oneLine
value={hiddenLayers}
onChange={handleLayerChange}
options={selectOptions}
placeholder={t('Select layers to hide')}
allowClear
disabled={apiLayers.length === 0}
loading={isLoadingMetadata && apiLayers.length === 0}
/>
</div>
</Tooltip>
</FormItem>
<Select
mode="multiple"
value={hiddenLayers}
onChange={handleLayerChange}
options={selectOptions}
placeholder={t('Select layers to hide')}
allowClear
/>
</FormItem>
)}
</FilterPluginStyle>
);
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.5 KiB

Some files were not shown because too many files have changed in this diff Show More