Compare commits
94 Commits
fix-explor
...
embedded-e
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
395c529a83 | ||
|
|
2fe1eb5ddc | ||
|
|
449aed9813 | ||
|
|
d30e9eb17d | ||
|
|
a4635f84bc | ||
|
|
01c84a3bf1 | ||
|
|
701eea222a | ||
|
|
3536adf340 | ||
|
|
98e89e6e5d | ||
|
|
2e3ae7a061 | ||
|
|
7c76fd3d81 | ||
|
|
0b419a07f5 | ||
|
|
0b51e9cd5e | ||
|
|
e7b9fb277e | ||
|
|
838ee870d0 | ||
|
|
84af6c9f29 | ||
|
|
05227e8a80 | ||
|
|
76a209663d | ||
|
|
61c45e3dd8 | ||
|
|
e11a50bedf | ||
|
|
f4a6ea0fde | ||
|
|
e542e9f840 | ||
|
|
e0dcb2908d | ||
|
|
eaccb2e471 | ||
|
|
c1a1f2e7e7 | ||
|
|
45d5501aa7 | ||
|
|
388596e4fe | ||
|
|
b11d4f3ef0 | ||
|
|
998b9e387b | ||
|
|
b3e88db87e | ||
|
|
8471e82342 | ||
|
|
c3a0f2749b | ||
|
|
c2d96e0dce | ||
|
|
44e77fdf2b | ||
|
|
18d6feb499 | ||
|
|
0d91f5e982 | ||
|
|
5661fc9128 | ||
|
|
a6156676c8 | ||
|
|
b2bd2329bc | ||
|
|
724f1484b9 | ||
|
|
84f7b4a973 | ||
|
|
ddcb9be9a7 | ||
|
|
8d9b5bd479 | ||
|
|
4b88fc57b4 | ||
|
|
b76080e291 | ||
|
|
411f769896 | ||
|
|
ffcc6e8b63 | ||
|
|
86575e129b | ||
|
|
3e25f02da9 | ||
|
|
002d8ad1e4 | ||
|
|
6287a07912 | ||
|
|
fa97d0357f | ||
|
|
f836c3eccd | ||
|
|
499e27ea54 | ||
|
|
c2a35e2eea | ||
|
|
5138aa2c11 | ||
|
|
66a9e2e16e | ||
|
|
0f417f0040 | ||
|
|
1462ac9282 | ||
|
|
da371217ef | ||
|
|
c971ea3ec6 | ||
|
|
de98fdc37b | ||
|
|
fa1f12a0b5 | ||
|
|
de40b58e10 | ||
|
|
eea3557f61 | ||
|
|
7a243d329e | ||
|
|
98146251c4 | ||
|
|
0aa8cace1b | ||
|
|
450701ecec | ||
|
|
e9911fbac4 | ||
|
|
69c8eef78e | ||
|
|
2ff50667e7 | ||
|
|
f1cf274751 | ||
|
|
b65396ccd4 | ||
|
|
1ad76e847e | ||
|
|
4583ef93a4 | ||
|
|
f632d2474b | ||
|
|
b1d69f5b39 | ||
|
|
aba7e6dae4 | ||
|
|
8bcc90c766 | ||
|
|
e39dd1afce | ||
|
|
680cef0ee0 | ||
|
|
e17cf3c808 | ||
|
|
f49310b8ff | ||
|
|
c7955a38ef | ||
|
|
68067d7f44 | ||
|
|
5815665cc6 | ||
|
|
6649f35a0d | ||
|
|
5263abdc60 | ||
|
|
c49641538d | ||
|
|
d915e4f3ff | ||
|
|
bad5a35fce | ||
|
|
1bde6f3bfd | ||
|
|
4e0890ee1f |
4
.github/dependabot.yml
vendored
@@ -4,6 +4,10 @@ updates:
|
||||
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
ignore:
|
||||
# Ignore temporarily as release schedule is too mentally taxing for dep-handling maintainers
|
||||
# Additionally, very few PRs are reviewed by this action.
|
||||
- dependency-name: anthropics/claude-code-action
|
||||
schedule:
|
||||
interval: "daily"
|
||||
|
||||
|
||||
9
.github/workflows/bashlib.sh
vendored
@@ -59,6 +59,15 @@ build-assets() {
|
||||
say "::endgroup::"
|
||||
}
|
||||
|
||||
build-embedded-sdk() {
|
||||
cd "$GITHUB_WORKSPACE/superset-embedded-sdk"
|
||||
|
||||
say "::group::Build embedded SDK bundle for E2E tests"
|
||||
npm ci
|
||||
npm run build
|
||||
say "::endgroup::"
|
||||
}
|
||||
|
||||
build-instrumented-assets() {
|
||||
cd "$GITHUB_WORKSPACE/superset-frontend"
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ jobs:
|
||||
- name: "Checkout ${{ github.ref }} ( ${{ github.sha }} )"
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
- name: Check and notify
|
||||
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8
|
||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
with:
|
||||
github-token: ${{ github.token }}
|
||||
script: |
|
||||
|
||||
4
.github/workflows/claude.yml
vendored
@@ -44,7 +44,7 @@ jobs:
|
||||
pull-requests: write
|
||||
steps:
|
||||
- name: Comment access denied
|
||||
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8
|
||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
with:
|
||||
script: |
|
||||
const message = `👋 Hi @${{ github.event.comment.user.login || github.event.review.user.login || github.event.issue.user.login }}!
|
||||
@@ -76,7 +76,7 @@ jobs:
|
||||
fetch-depth: 1
|
||||
|
||||
- name: Run Claude PR Action
|
||||
uses: anthropics/claude-code-action@6e2bd52842c65e914eba5c8badd17560bd26b5de # beta
|
||||
uses: anthropics/claude-code-action@5fb899572b81d2bb648d4d187173a2f423a9677c # beta
|
||||
with:
|
||||
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
timeout_minutes: "60"
|
||||
|
||||
2
.github/workflows/ephemeral-env-pr-close.yml
vendored
@@ -71,7 +71,7 @@ jobs:
|
||||
|
||||
- name: Comment (success)
|
||||
if: steps.describe-services.outputs.active == 'true'
|
||||
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8
|
||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
with:
|
||||
github-token: ${{github.token}}
|
||||
script: |
|
||||
|
||||
12
.github/workflows/ephemeral-env.yml
vendored
@@ -65,7 +65,7 @@ jobs:
|
||||
- name: Get event SHA
|
||||
id: get-sha
|
||||
if: steps.eval-label.outputs.result == 'up'
|
||||
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8
|
||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
with:
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
script: |
|
||||
@@ -96,7 +96,7 @@ jobs:
|
||||
core.setOutput("sha", prSha);
|
||||
|
||||
- name: Looking for feature flags in PR description
|
||||
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8
|
||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
id: eval-feature-flags
|
||||
if: steps.eval-label.outputs.result == 'up'
|
||||
with:
|
||||
@@ -118,7 +118,7 @@ jobs:
|
||||
return results;
|
||||
|
||||
- name: Reply with confirmation comment
|
||||
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8
|
||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
if: steps.eval-label.outputs.result == 'up'
|
||||
with:
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -250,7 +250,7 @@ jobs:
|
||||
|
||||
- name: Fail on missing container image
|
||||
if: steps.check-image.outcome == 'failure'
|
||||
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8
|
||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
with:
|
||||
github-token: ${{ github.token }}
|
||||
script: |
|
||||
@@ -324,7 +324,7 @@ jobs:
|
||||
echo "ip=$(aws ec2 describe-network-interfaces --network-interface-ids ${{ steps.get-eni.outputs.eni }} | jq -r '.NetworkInterfaces | first | .Association.PublicIp')" >> $GITHUB_OUTPUT
|
||||
- name: Comment (success)
|
||||
if: ${{ success() }}
|
||||
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8
|
||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
with:
|
||||
github-token: ${{github.token}}
|
||||
script: |
|
||||
@@ -337,7 +337,7 @@ jobs:
|
||||
});
|
||||
- name: Comment (failure)
|
||||
if: ${{ failure() }}
|
||||
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8
|
||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
with:
|
||||
github-token: ${{github.token}}
|
||||
script: |
|
||||
|
||||
2
.github/workflows/no-hold-label.yml
vendored
@@ -17,7 +17,7 @@ jobs:
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- name: Check for 'hold' label
|
||||
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8
|
||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
with:
|
||||
github-token: ${{secrets.GITHUB_TOKEN}}
|
||||
script: |
|
||||
|
||||
2
.github/workflows/pre-commit.yml
vendored
@@ -57,7 +57,7 @@ jobs:
|
||||
yarn install --immutable
|
||||
|
||||
- name: Cache pre-commit environments
|
||||
uses: actions/cache@668228422ae6a00e4ad889ee87cd7109ec5666a7 # v5
|
||||
uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5
|
||||
with:
|
||||
path: ~/.cache/pre-commit
|
||||
key: pre-commit-v2-${{ runner.os }}-py${{ matrix.python-version }}-${{ hashFiles('.pre-commit-config.yaml') }}
|
||||
|
||||
4
.github/workflows/release.yml
vendored
@@ -50,7 +50,7 @@ jobs:
|
||||
|
||||
- name: Cache npm
|
||||
if: env.HAS_TAGS
|
||||
uses: actions/cache@668228422ae6a00e4ad889ee87cd7109ec5666a7 # v5
|
||||
uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5
|
||||
with:
|
||||
path: ~/.npm # npm cache files are stored in `~/.npm` on Linux/macOS
|
||||
key: ${{ runner.OS }}-node-${{ hashFiles('**/package-lock.json') }}
|
||||
@@ -64,7 +64,7 @@ jobs:
|
||||
run: echo "dir=$(npm config get cache)" >> $GITHUB_OUTPUT
|
||||
- name: Cache npm
|
||||
if: env.HAS_TAGS
|
||||
uses: actions/cache@668228422ae6a00e4ad889ee87cd7109ec5666a7 # v5
|
||||
uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5
|
||||
id: npm-cache # use this to check for `cache-hit` (`steps.npm-cache.outputs.cache-hit != 'true'`)
|
||||
with:
|
||||
path: ${{ steps.npm-cache-dir-path.outputs.dir }}
|
||||
|
||||
2
.github/workflows/showtime-trigger.yml
vendored
@@ -37,7 +37,7 @@ jobs:
|
||||
steps:
|
||||
- name: Security Check - Authorize Maintainers Only
|
||||
id: auth
|
||||
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8
|
||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
|
||||
6
.github/workflows/superset-e2e.yml
vendored
@@ -169,6 +169,7 @@ jobs:
|
||||
PYTHONPATH: ${{ github.workspace }}
|
||||
REDIS_PORT: 16379
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
SUPERSET_FEATURE_EMBEDDED_SUPERSET: "true"
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:17-alpine
|
||||
@@ -239,6 +240,11 @@ jobs:
|
||||
uses: ./.github/actions/cached-dependencies
|
||||
with:
|
||||
run: build-instrumented-assets
|
||||
- name: Build embedded SDK
|
||||
if: steps.check.outputs.python || steps.check.outputs.frontend
|
||||
uses: ./.github/actions/cached-dependencies
|
||||
with:
|
||||
run: build-embedded-sdk
|
||||
- name: Install Playwright
|
||||
if: steps.check.outputs.python || steps.check.outputs.frontend
|
||||
uses: ./.github/actions/cached-dependencies
|
||||
|
||||
2
.github/workflows/superset-helm-release.yml
vendored
@@ -101,7 +101,7 @@ jobs:
|
||||
CR_RELEASE_NAME_TEMPLATE: "superset-helm-chart-{{ .Version }}"
|
||||
|
||||
- name: Open Pull Request
|
||||
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8
|
||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
with:
|
||||
script: |
|
||||
const branchName = '${{ env.branch_name }}';
|
||||
|
||||
6
.github/workflows/superset-playwright.yml
vendored
@@ -43,6 +43,7 @@ jobs:
|
||||
PYTHONPATH: ${{ github.workspace }}
|
||||
REDIS_PORT: 16379
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
SUPERSET_FEATURE_EMBEDDED_SUPERSET: "true"
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:17-alpine
|
||||
@@ -113,6 +114,11 @@ jobs:
|
||||
uses: ./.github/actions/cached-dependencies
|
||||
with:
|
||||
run: build-instrumented-assets
|
||||
- name: Build embedded SDK
|
||||
if: steps.check.outputs.python || steps.check.outputs.frontend
|
||||
uses: ./.github/actions/cached-dependencies
|
||||
with:
|
||||
run: build-embedded-sdk
|
||||
- name: Install Playwright
|
||||
if: steps.check.outputs.python || steps.check.outputs.frontend
|
||||
uses: ./.github/actions/cached-dependencies
|
||||
|
||||
2
.github/workflows/supersetbot.yml
vendored
@@ -26,7 +26,7 @@ jobs:
|
||||
steps:
|
||||
- name: Quickly add thumbs up!
|
||||
if: github.event_name == 'issue_comment' && contains(github.event.comment.body, '@supersetbot')
|
||||
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8
|
||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
with:
|
||||
script: |
|
||||
const [owner, repo] = process.env.GITHUB_REPOSITORY.split('/')
|
||||
|
||||
@@ -287,6 +287,11 @@ categories:
|
||||
url: https://www.gfk.com/home
|
||||
contributors: ["@mherr"]
|
||||
|
||||
- name: Hifadih Business & Technology
|
||||
url: https://hifadih.net/en
|
||||
logo: hifadih.png
|
||||
contributors: ["@saintLaurent00"]
|
||||
|
||||
# Logo approved by @anmol-hpe on behalf of HPE
|
||||
- name: HPE
|
||||
url: https://www.hpe.com/in/en/home.html
|
||||
|
||||
14
UPDATING.md
@@ -24,6 +24,20 @@ assists people when migrating to a new version.
|
||||
|
||||
## Next
|
||||
|
||||
### Granular Export Controls
|
||||
|
||||
A new feature flag `GRANULAR_EXPORT_CONTROLS` introduces three fine-grained permissions that replace the legacy `can_csv` permission:
|
||||
|
||||
| Permission | Controls |
|
||||
|---|---|
|
||||
| `can_export_data` | CSV, Excel, JSON exports |
|
||||
| `can_export_image` | Screenshot/PDF exports |
|
||||
| `can_copy_clipboard` | Copy-to-clipboard operations |
|
||||
|
||||
When the feature flag is enabled, these permissions are enforced on both the frontend (disabled buttons with tooltips) and backend (403 responses from API endpoints). When disabled, legacy `can_csv` behavior is preserved.
|
||||
|
||||
**Migration behavior:** All three new permissions are granted to every role that currently has `can_csv`, preserving existing access. Admins can then selectively revoke individual export permissions from specific roles as needed.
|
||||
|
||||
### Deck.gl MapBox viewport and opacity controls are functional
|
||||
|
||||
The Deck.gl MapBox chart's **Opacity**, **Default longitude**, **Default latitude**, and **Zoom** controls were previously non-functional — changing them had no effect on the rendered map. These controls are now wired up correctly.
|
||||
|
||||
@@ -412,7 +412,7 @@ curl -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
|
||||
|--------|----------|-------------|
|
||||
| `GET` | [Get security roles](/developer-docs/api/get-security-roles) | `/api/v1/security/roles/` |
|
||||
| `POST` | [Create security roles](/developer-docs/api/create-security-roles) | `/api/v1/security/roles/` |
|
||||
| `GET` | [Get security roles info](/developer-docs/api/get-security-roles-info) | `/api/v1/security/roles/_info` |
|
||||
| `GET` | [Get security roles info](/developer-docs/api/get-security-roles-info) | `/api/v1/security/roles/_info` |
|
||||
| `DELETE` | [Delete security roles by pk](/developer-docs/api/delete-security-roles-by-pk) | `/api/v1/security/roles/{pk}` |
|
||||
| `GET` | [Get security roles by pk](/developer-docs/api/get-security-roles-by-pk) | `/api/v1/security/roles/{pk}` |
|
||||
| `PUT` | [Update security roles by pk](/developer-docs/api/update-security-roles-by-pk) | `/api/v1/security/roles/{pk}` |
|
||||
@@ -430,7 +430,7 @@ curl -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
|
||||
|--------|----------|-------------|
|
||||
| `GET` | [Get security users](/developer-docs/api/get-security-users) | `/api/v1/security/users/` |
|
||||
| `POST` | [Create security users](/developer-docs/api/create-security-users) | `/api/v1/security/users/` |
|
||||
| `GET` | [Get security users info](/developer-docs/api/get-security-users-info) | `/api/v1/security/users/_info` |
|
||||
| `GET` | [Get security users info](/developer-docs/api/get-security-users-info) | `/api/v1/security/users/_info` |
|
||||
| `DELETE` | [Delete security users by pk](/developer-docs/api/delete-security-users-by-pk) | `/api/v1/security/users/{pk}` |
|
||||
| `GET` | [Get security users by pk](/developer-docs/api/get-security-users-by-pk) | `/api/v1/security/users/{pk}` |
|
||||
| `PUT` | [Update security users by pk](/developer-docs/api/update-security-users-by-pk) | `/api/v1/security/users/{pk}` |
|
||||
@@ -443,7 +443,7 @@ curl -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
|
||||
| Method | Endpoint | Description |
|
||||
|--------|----------|-------------|
|
||||
| `GET` | [Get security permissions](/developer-docs/api/get-security-permissions) | `/api/v1/security/permissions/` |
|
||||
| `GET` | [Get security permissions info](/developer-docs/api/get-security-permissions-info) | `/api/v1/security/permissions/_info` |
|
||||
| `GET` | [Get security permissions info](/developer-docs/api/get-security-permissions-info) | `/api/v1/security/permissions/_info` |
|
||||
| `GET` | [Get security permissions by pk](/developer-docs/api/get-security-permissions-by-pk) | `/api/v1/security/permissions/{pk}` |
|
||||
|
||||
</details>
|
||||
@@ -455,7 +455,7 @@ curl -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
|
||||
|--------|----------|-------------|
|
||||
| `GET` | [Get security resources](/developer-docs/api/get-security-resources) | `/api/v1/security/resources/` |
|
||||
| `POST` | [Create security resources](/developer-docs/api/create-security-resources) | `/api/v1/security/resources/` |
|
||||
| `GET` | [Get security resources info](/developer-docs/api/get-security-resources-info) | `/api/v1/security/resources/_info` |
|
||||
| `GET` | [Get security resources info](/developer-docs/api/get-security-resources-info) | `/api/v1/security/resources/_info` |
|
||||
| `DELETE` | [Delete security resources by pk](/developer-docs/api/delete-security-resources-by-pk) | `/api/v1/security/resources/{pk}` |
|
||||
| `GET` | [Get security resources by pk](/developer-docs/api/get-security-resources-by-pk) | `/api/v1/security/resources/{pk}` |
|
||||
| `PUT` | [Update security resources by pk](/developer-docs/api/update-security-resources-by-pk) | `/api/v1/security/resources/{pk}` |
|
||||
@@ -469,7 +469,7 @@ curl -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
|
||||
|--------|----------|-------------|
|
||||
| `GET` | [Get security permissions resources](/developer-docs/api/get-security-permissions-resources) | `/api/v1/security/permissions-resources/` |
|
||||
| `POST` | [Create security permissions resources](/developer-docs/api/create-security-permissions-resources) | `/api/v1/security/permissions-resources/` |
|
||||
| `GET` | [Get security permissions resources info](/developer-docs/api/get-security-permissions-resources-info) | `/api/v1/security/permissions-resources/_info` |
|
||||
| `GET` | [Get security permissions resources info](/developer-docs/api/get-security-permissions-resources-info) | `/api/v1/security/permissions-resources/_info` |
|
||||
| `DELETE` | [Delete security permissions resources by pk](/developer-docs/api/delete-security-permissions-resources-by-pk) | `/api/v1/security/permissions-resources/{pk}` |
|
||||
| `GET` | [Get security permissions resources by pk](/developer-docs/api/get-security-permissions-resources-by-pk) | `/api/v1/security/permissions-resources/{pk}` |
|
||||
| `PUT` | [Update security permissions resources by pk](/developer-docs/api/update-security-permissions-resources-by-pk) | `/api/v1/security/permissions-resources/{pk}` |
|
||||
@@ -578,7 +578,29 @@ curl -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
|
||||
|
||||
| Method | Endpoint | Description |
|
||||
|--------|----------|-------------|
|
||||
| `GET` | [Get api by version openapi](/developer-docs/api/get-api-by-version-openapi) | `/api/{version}/_openapi` |
|
||||
| `GET` | [Get api by version openapi](/developer-docs/api/get-api-by-version-openapi) | `/api/{version}/_openapi` |
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>Themes</strong> (14 endpoints) — Manage UI themes for customizing Superset's appearance.</summary>
|
||||
|
||||
| Method | Endpoint | Description |
|
||||
|--------|----------|-------------|
|
||||
| `DELETE` | [Bulk delete themes](/developer-docs/api/bulk-delete-themes) | `/api/v1/theme/` |
|
||||
| `GET` | [Get a list of themes](/developer-docs/api/get-a-list-of-themes) | `/api/v1/theme/` |
|
||||
| `POST` | [Create a theme](/developer-docs/api/create-a-theme) | `/api/v1/theme/` |
|
||||
| `GET` | [Get metadata information about this API resource (theme-info)](/developer-docs/api/get-metadata-information-about-this-api-resource-theme-info) | `/api/v1/theme/_info` |
|
||||
| `DELETE` | [Delete a theme](/developer-docs/api/delete-a-theme) | `/api/v1/theme/{pk}` |
|
||||
| `GET` | [Get a theme](/developer-docs/api/get-a-theme) | `/api/v1/theme/{pk}` |
|
||||
| `PUT` | [Update a theme](/developer-docs/api/update-a-theme) | `/api/v1/theme/{pk}` |
|
||||
| `PUT` | [Set a theme as the system dark theme](/developer-docs/api/set-a-theme-as-the-system-dark-theme) | `/api/v1/theme/{pk}/set_system_dark` |
|
||||
| `PUT` | [Set a theme as the system default theme](/developer-docs/api/set-a-theme-as-the-system-default-theme) | `/api/v1/theme/{pk}/set_system_default` |
|
||||
| `GET` | [Download multiple themes as YAML files](/developer-docs/api/download-multiple-themes-as-yaml-files) | `/api/v1/theme/export/` |
|
||||
| `POST` | [Import themes from a ZIP file](/developer-docs/api/import-themes-from-a-zip-file) | `/api/v1/theme/import/` |
|
||||
| `GET` | [Get related fields data (theme-related-column-name)](/developer-docs/api/get-related-fields-data-theme-related-column-name) | `/api/v1/theme/related/{column_name}` |
|
||||
| `DELETE` | [Clear the system dark theme](/developer-docs/api/clear-the-system-dark-theme) | `/api/v1/theme/unset_system_dark` |
|
||||
| `DELETE` | [Clear the system default theme](/developer-docs/api/clear-the-system-default-theme) | `/api/v1/theme/unset_system_default` |
|
||||
|
||||
</details>
|
||||
|
||||
|
||||
@@ -91,7 +91,7 @@ or a view.
|
||||
When working with tables, the solution would be to create a table that contains all the fields
|
||||
needed for your analysis, most likely through some scheduled batch process.
|
||||
|
||||
A view is a simple logical layer that abstracts an arbitrary SQL queries as a virtual table. This can
|
||||
A view is a simple logical layer that abstracts an arbitrary SQL query as a virtual table. This can
|
||||
allow you to join and union multiple tables and to apply some transformation using arbitrary SQL
|
||||
expressions. The limitation there is your database performance, as Superset effectively will run a
|
||||
query on top of your query (view). A good practice may be to limit yourself to joining your main
|
||||
|
||||
78
docs/docs/security/granular-export-controls.mdx
Normal file
@@ -0,0 +1,78 @@
|
||||
---
|
||||
title: Granular Export Controls
|
||||
sidebar_position: 4
|
||||
---
|
||||
|
||||
# Granular Export Controls
|
||||
|
||||
Superset provides granular, permission-based controls for data export, image export, and clipboard operations. These replace the legacy `can_csv` permission with three fine-grained permissions that can be assigned independently to roles.
|
||||
|
||||
## Feature Flag
|
||||
|
||||
Granular export controls are gated behind the `GRANULAR_EXPORT_CONTROLS` feature flag. When the flag is disabled, the legacy `can_csv` permission behavior is preserved.
|
||||
|
||||
```python
|
||||
FEATURE_FLAGS = {
|
||||
"GRANULAR_EXPORT_CONTROLS": True,
|
||||
}
|
||||
```
|
||||
|
||||
## Permissions
|
||||
|
||||
| Permission | Resource | Controls |
|
||||
| -------------------- | ---------- | ---------------------------------------------------------------------- |
|
||||
| `can_export_data` | `Superset` | CSV, Excel, and JSON data exports from charts, dashboards, and SQL Lab |
|
||||
| `can_export_image` | `Superset` | Screenshot (JPEG/PNG) and PDF exports from charts and dashboards |
|
||||
| `can_copy_clipboard` | `Superset` | Copy-to-clipboard operations in SQL Lab and the Explore data pane |
|
||||
|
||||
## Default Role Assignments
|
||||
|
||||
The migration grants all three new permissions (`can_export_data`, `can_export_image`, `can_copy_clipboard`) to every role that currently has `can_csv`. This preserves existing behavior — no role loses access during the upgrade.
|
||||
|
||||
After the migration, admins can selectively revoke individual export permissions from any role to restrict access. For example, to prevent Gamma users from exporting data or images while still allowing clipboard operations, revoke `can_export_data` and `can_export_image` from the Gamma role.
|
||||
|
||||
## Configuration Steps
|
||||
|
||||
1. **Enable the feature flag** in `superset_config.py`:
|
||||
|
||||
```python
|
||||
FEATURE_FLAGS = {
|
||||
"GRANULAR_EXPORT_CONTROLS": True,
|
||||
}
|
||||
```
|
||||
|
||||
2. **Run the database migration** to register the new permissions:
|
||||
|
||||
```bash
|
||||
superset db upgrade
|
||||
```
|
||||
|
||||
3. **Initialize permissions** so roles are populated:
|
||||
|
||||
```bash
|
||||
superset init
|
||||
```
|
||||
|
||||
4. **Verify role assignments** in **Settings > List Roles**. Confirm that each role has the expected permissions from the table above.
|
||||
|
||||
5. **Customize as needed**: Grant or revoke individual export permissions on any role through the role editor.
|
||||
|
||||
## User Experience
|
||||
|
||||
When a user lacks a required export permission:
|
||||
|
||||
- **Menu items** (CSV, Excel, JSON, screenshot) appear **disabled** with an info tooltip icon explaining the restriction
|
||||
- **Buttons** (SQL Lab download, clipboard copy) appear **disabled** with a tooltip on hover
|
||||
- **API endpoints** return **403 Forbidden** when the corresponding permission is missing
|
||||
|
||||
## API Enforcement
|
||||
|
||||
The following API endpoints enforce granular export permissions when the feature flag is enabled:
|
||||
|
||||
| Endpoint | Required Permission |
|
||||
| --------------------------------------------------------- | ------------------- |
|
||||
| `GET /api/v1/chart/{id}/data/` (CSV/Excel format) | `can_export_data` |
|
||||
| `GET /api/v1/chart/{id}/cache_screenshot/` | `can_export_image` |
|
||||
| `POST /api/v1/dashboard/{id}/cache_dashboard_screenshot/` | `can_export_image` |
|
||||
| `GET /api/v1/sqllab/export/{client_id}/` | `can_export_data` |
|
||||
| `POST /api/v1/sqllab/export_streaming/` | `can_export_data` |
|
||||
@@ -42,7 +42,7 @@
|
||||
"dependencies": {
|
||||
"@ant-design/icons": "^6.1.1",
|
||||
"@docusaurus/core": "3.9.2",
|
||||
"@docusaurus/faster": "^3.9.2",
|
||||
"@docusaurus/faster": "^3.10.0",
|
||||
"@docusaurus/plugin-client-redirects": "3.9.2",
|
||||
"@docusaurus/preset-classic": "3.9.2",
|
||||
"@docusaurus/theme-live-codeblock": "^3.9.2",
|
||||
@@ -69,8 +69,8 @@
|
||||
"@superset-ui/core": "^0.20.4",
|
||||
"@swc/core": "^1.15.21",
|
||||
"antd": "^6.3.5",
|
||||
"baseline-browser-mapping": "^2.10.13",
|
||||
"caniuse-lite": "^1.0.30001786",
|
||||
"baseline-browser-mapping": "^2.10.16",
|
||||
"caniuse-lite": "^1.0.30001788",
|
||||
"docusaurus-plugin-openapi-docs": "^4.6.0",
|
||||
"docusaurus-theme-openapi-docs": "^4.6.0",
|
||||
"js-yaml": "^4.1.1",
|
||||
@@ -86,14 +86,14 @@
|
||||
"remark-import-partial": "^0.0.2",
|
||||
"reselect": "^5.1.1",
|
||||
"storybook": "^8.6.18",
|
||||
"swagger-ui-react": "^5.32.1",
|
||||
"swagger-ui-react": "^5.32.4",
|
||||
"swc-loader": "^0.2.7",
|
||||
"tinycolor2": "^1.4.2",
|
||||
"unist-util-visit": "^5.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@docusaurus/module-type-aliases": "^3.9.1",
|
||||
"@docusaurus/tsconfig": "^3.9.2",
|
||||
"@docusaurus/module-type-aliases": "^3.10.0",
|
||||
"@docusaurus/tsconfig": "^3.10.0",
|
||||
"@eslint/js": "^9.39.2",
|
||||
"@types/js-yaml": "^4.0.9",
|
||||
"@types/react": "^19.1.8",
|
||||
|
||||
@@ -129,6 +129,30 @@ def add_missing_schemas(spec: dict[str, Any]) -> tuple[dict[str, Any], list[str]
|
||||
}
|
||||
fixed.append("DashboardColorsConfigUpdateSchema")
|
||||
|
||||
# DashboardChartCustomizationsConfigUpdateSchema (dashboards/schemas.py)
|
||||
if "DashboardChartCustomizationsConfigUpdateSchema" not in schemas:
|
||||
schemas["DashboardChartCustomizationsConfigUpdateSchema"] = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"deleted": {
|
||||
"type": "array",
|
||||
"items": {"type": "string"},
|
||||
"description": "List of deleted chart customization IDs.",
|
||||
},
|
||||
"modified": {
|
||||
"type": "array",
|
||||
"items": {"type": "object"},
|
||||
"description": "List of modified chart customizations.",
|
||||
},
|
||||
"reordered": {
|
||||
"type": "array",
|
||||
"items": {"type": "string"},
|
||||
"description": "List of chart customization IDs in new order.",
|
||||
},
|
||||
},
|
||||
}
|
||||
fixed.append("DashboardChartCustomizationsConfigUpdateSchema")
|
||||
|
||||
# FormatQueryPayloadSchema - based on superset/sqllab/schemas.py
|
||||
if "FormatQueryPayloadSchema" not in schemas:
|
||||
schemas["FormatQueryPayloadSchema"] = {
|
||||
@@ -295,6 +319,7 @@ TAG_DESCRIPTIONS = {
|
||||
"Security Roles": "Manage security roles and their permissions.",
|
||||
"Security Users": "Manage user accounts.",
|
||||
"Tags": "Organize assets with tags.",
|
||||
"Themes": "Manage UI themes for customizing Superset's appearance.",
|
||||
"User": "User profile and preferences.",
|
||||
}
|
||||
|
||||
|
||||
BIN
docs/static/img/logos/hifadih.png
vendored
Normal file
|
After Width: | Height: | Size: 18 KiB |
5791
docs/static/resources/openapi.json
vendored
@@ -35,7 +35,7 @@ or a view.
|
||||
When working with tables, the solution would be to create a table that contains all the fields
|
||||
needed for your analysis, most likely through some scheduled batch process.
|
||||
|
||||
A view is a simple logical layer that abstracts an arbitrary SQL queries as a virtual table. This can
|
||||
A view is a simple logical layer that abstracts an arbitrary SQL query as a virtual table. This can
|
||||
allow you to join and union multiple tables and to apply some transformation using arbitrary SQL
|
||||
expressions. The limitation there is your database performance, as Superset effectively will run a
|
||||
query on top of your query (view). A good practice may be to limit yourself to joining your main
|
||||
|
||||
792
docs/yarn.lock
@@ -48,7 +48,7 @@ dependencies = [
|
||||
"cryptography>=42.0.4, <47.0.0",
|
||||
"deprecation>=2.1.0, <2.2.0",
|
||||
"flask>=2.2.5, <4.0.0",
|
||||
"flask-appbuilder>=5.0.2,<6",
|
||||
"flask-appbuilder>=5.2.1, <6.0.0",
|
||||
"flask-caching>=2.1.0, <3",
|
||||
"flask-compress>=1.13, <2.0",
|
||||
"flask-talisman>=1.0.0, <2.0",
|
||||
@@ -372,6 +372,7 @@ unfixable = []
|
||||
dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$"
|
||||
|
||||
[tool.ruff.lint.per-file-ignores]
|
||||
"superset/mcp_service/app.py" = ["S608", "E501"] # LLM instruction text: SQL examples (S608) and long lines in multiline string (E501)
|
||||
"scripts/*" = ["TID251"]
|
||||
"setup.py" = ["TID251"]
|
||||
"superset/config.py" = ["TID251"]
|
||||
|
||||
@@ -120,7 +120,7 @@ flask==2.3.3
|
||||
# flask-session
|
||||
# flask-sqlalchemy
|
||||
# flask-wtf
|
||||
flask-appbuilder==5.2.0
|
||||
flask-appbuilder==5.2.1
|
||||
# via
|
||||
# apache-superset (pyproject.toml)
|
||||
# apache-superset-core
|
||||
|
||||
@@ -259,7 +259,7 @@ flask==2.3.3
|
||||
# flask-sqlalchemy
|
||||
# flask-testing
|
||||
# flask-wtf
|
||||
flask-appbuilder==5.2.0
|
||||
flask-appbuilder==5.2.1
|
||||
# via
|
||||
# -c requirements/base-constraint.txt
|
||||
# apache-superset
|
||||
|
||||
@@ -1,73 +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.
|
||||
*/
|
||||
import { selectResultsTab } from './sqllab.helper';
|
||||
|
||||
describe.skip('SqlLab datasource panel', () => {
|
||||
beforeEach(() => {
|
||||
cy.visit('/sqllab');
|
||||
});
|
||||
|
||||
// TODO the test below is flaky, and has been disabled for the time being
|
||||
// (notice the `it.skip`)
|
||||
it('creates a table preview when a database, schema, and table are selected', () => {
|
||||
cy.intercept('**/superset/table/**').as('tableMetadata');
|
||||
|
||||
// it should have dropdowns to select database, schema, and table
|
||||
cy.get('.sql-toolbar .Select').should('have.length', 3);
|
||||
|
||||
cy.get('.sql-toolbar .table-schema').should('not.exist');
|
||||
cy.get('[data-test="filterable-table-container"]').should('not.exist');
|
||||
|
||||
cy.get('.sql-toolbar .Select')
|
||||
.eq(0) // database select
|
||||
.within(() => {
|
||||
// note: we have to set force: true because the input is invisible / cypress throws
|
||||
cy.get('input').type('main{enter}', { force: true });
|
||||
});
|
||||
|
||||
cy.get('.sql-toolbar .Select')
|
||||
.eq(1) // schema select
|
||||
.within(() => {
|
||||
cy.get('input').type('main{enter}', { force: true });
|
||||
});
|
||||
|
||||
cy.get('.sql-toolbar .Select')
|
||||
.eq(2) // table select
|
||||
.within(() => {
|
||||
cy.get('input').type('birth_names{enter}', { force: true });
|
||||
});
|
||||
|
||||
cy.wait('@tableMetadata');
|
||||
|
||||
cy.get('.sql-toolbar .table-schema').should('have.length', 1);
|
||||
selectResultsTab().should('have.length', 1);
|
||||
|
||||
// add another table and check for added schema + preview
|
||||
cy.get('.sql-toolbar .Select')
|
||||
.eq(2)
|
||||
.within(() => {
|
||||
cy.get('input').type('logs{enter}', { force: true });
|
||||
});
|
||||
|
||||
cy.wait('@tableMetadata');
|
||||
|
||||
cy.get('.sql-toolbar .table-schema').should('have.length', 2);
|
||||
selectResultsTab().should('have.length', 2);
|
||||
});
|
||||
});
|
||||
@@ -1,192 +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.
|
||||
*/
|
||||
import { nanoid } from 'nanoid';
|
||||
import { selectResultsTab, assertSQLLabResultsAreEqual } from './sqllab.helper';
|
||||
|
||||
function parseClockStr(node: JQuery) {
|
||||
return Number.parseFloat(node.text().replace(/:/g, ''));
|
||||
}
|
||||
|
||||
describe('SqlLab query panel', () => {
|
||||
beforeEach(() => {
|
||||
cy.visit('/sqllab');
|
||||
});
|
||||
|
||||
it.skip('supports entering and running a query', () => {
|
||||
// row limit has to be < ~10 for us to be able to determine how many rows
|
||||
// are fetched below (because React _Virtualized_ does not render all rows)
|
||||
let clockTime = 0;
|
||||
|
||||
cy.intercept({
|
||||
method: 'POST',
|
||||
url: '**/api/v1/sqllab/execute/',
|
||||
}).as('mockSQLResponse');
|
||||
|
||||
cy.get('.TableSelector .Select:eq(0)').click();
|
||||
cy.get('.TableSelector .Select:eq(0) input[type=text]').focus();
|
||||
cy.focused().type('{enter}');
|
||||
|
||||
cy.get('#brace-editor textarea').focus();
|
||||
cy.focused().clear();
|
||||
cy.focused().type(`{selectall}{backspace}SELECT 1`);
|
||||
|
||||
cy.get('#js-sql-toolbar button:eq(0)').eq(0).click();
|
||||
|
||||
// wait for 300 milliseconds
|
||||
cy.wait(300);
|
||||
|
||||
// started timer
|
||||
cy.get('.sql-toolbar .label-success').then(node => {
|
||||
clockTime = parseClockStr(node);
|
||||
// should be longer than 0.2s
|
||||
expect(clockTime).greaterThan(0.2);
|
||||
});
|
||||
|
||||
cy.wait('@mockSQLResponse');
|
||||
|
||||
// timer is increasing
|
||||
cy.get('.sql-toolbar .label-success').then(node => {
|
||||
const newClockTime = parseClockStr(node);
|
||||
expect(newClockTime).greaterThan(0.9);
|
||||
clockTime = newClockTime;
|
||||
});
|
||||
|
||||
// rerun the query
|
||||
cy.get('#js-sql-toolbar button:eq(0)').eq(0).click();
|
||||
|
||||
// should restart the timer
|
||||
cy.get('.sql-toolbar .label-success').contains('00:00:00');
|
||||
cy.wait('@mockSQLResponse');
|
||||
cy.get('.sql-toolbar .label-success').then(node => {
|
||||
expect(parseClockStr(node)).greaterThan(0.9);
|
||||
});
|
||||
});
|
||||
|
||||
it.skip('successfully saves a query', () => {
|
||||
cy.intercept('**/api/v1/database/**/tables/**').as('getTables');
|
||||
|
||||
const query =
|
||||
'SELECT ds, gender, name, num FROM main.birth_names ORDER BY name LIMIT 3';
|
||||
const savedQueryTitle = `CYPRESS TEST QUERY ${nanoid()}`;
|
||||
|
||||
// we will assert that the results of the query we save, and the saved query are the same
|
||||
let initialResultsTable: HTMLElement | null = null;
|
||||
let savedQueryResultsTable = null;
|
||||
|
||||
cy.get('#brace-editor textarea').clear({ force: true });
|
||||
cy.get('#brace-editor textarea').type(`{selectall}{backspace}${query}`, {
|
||||
force: true,
|
||||
});
|
||||
cy.get('#brace-editor textarea').focus(); // focus => blur is required for updating the query that is to be saved
|
||||
cy.focused().blur();
|
||||
|
||||
// ctrl + r also runs query
|
||||
cy.get('#brace-editor textarea').type('{ctrl}r', { force: true });
|
||||
|
||||
cy.wait('@sqlLabQuery');
|
||||
|
||||
// Save results to check against below
|
||||
selectResultsTab().then(resultsA => {
|
||||
initialResultsTable = resultsA[0];
|
||||
});
|
||||
|
||||
cy.get('#js-sql-toolbar button')
|
||||
.eq(1) // save query
|
||||
.click();
|
||||
|
||||
// Enter name + save into modal
|
||||
cy.get('.modal-sm input').clear({ force: true });
|
||||
cy.get('.modal-sm input').type(`{selectall}{backspace}${savedQueryTitle}`, {
|
||||
force: true,
|
||||
});
|
||||
|
||||
cy.get('.modal-sm .modal-body button')
|
||||
.eq(0) // save
|
||||
.click();
|
||||
|
||||
// first row contains most recent link, follow back to SqlLab
|
||||
cy.get('table tr:first-child a[href*="savedQueryId"').click();
|
||||
|
||||
// will timeout without explicitly waiting here
|
||||
cy.wait(['@getSavedQuery', '@getTables']);
|
||||
|
||||
// run the saved query
|
||||
cy.get('#js-sql-toolbar button')
|
||||
.eq(0) // run query
|
||||
.click();
|
||||
|
||||
cy.wait('@sqlLabQuery');
|
||||
|
||||
// assert the results of the saved query match the initial results
|
||||
selectResultsTab().then(resultsB => {
|
||||
savedQueryResultsTable = resultsB[0];
|
||||
|
||||
assertSQLLabResultsAreEqual(initialResultsTable, savedQueryResultsTable);
|
||||
});
|
||||
});
|
||||
|
||||
it.skip('Create a chart from a query', () => {
|
||||
cy.intercept('**/api/v1/sqllab/execute/').as('queryFinished');
|
||||
cy.intercept('**/api/v1/explore/**').as('explore');
|
||||
cy.intercept('**/api/v1/chart/**').as('chart');
|
||||
cy.intercept('**/tabstateview/**').as('tabstateview');
|
||||
|
||||
// cypress doesn't handle opening a new tab, override window.open to open in the same tab
|
||||
cy.window().then(win => {
|
||||
cy.stub(win, 'open', url => {
|
||||
// eslint-disable-next-line no-param-reassign
|
||||
win.location.href = url;
|
||||
});
|
||||
});
|
||||
cy.wait('@tabstateview');
|
||||
|
||||
const query = 'SELECT gender, name FROM birth_names';
|
||||
|
||||
cy.get('.ace_text-input').focus();
|
||||
cy.focused().clear({ force: true });
|
||||
cy.focused().type(`{selectall}{backspace}${query}`, { force: true });
|
||||
cy.get('.sql-toolbar button').contains('Run').click();
|
||||
cy.wait('@queryFinished');
|
||||
|
||||
cy.get(
|
||||
'.SouthPane .ant-tabs-content > .ant-tabs-tabpane-active > div button:first',
|
||||
{ timeout: 10000 },
|
||||
).click();
|
||||
|
||||
cy.wait('@explore');
|
||||
cy.get('[data-test="datasource-control"] .title-select').contains(query);
|
||||
cy.get('.column-option-label').first().contains('gender');
|
||||
cy.get('.column-option-label').last().contains('name');
|
||||
|
||||
cy.get(
|
||||
'[data-test="all_columns"] [data-test="dnd-labels-container"] > div:first-child',
|
||||
).contains('gender');
|
||||
cy.get(
|
||||
'[data-test="all_columns"] [data-test="dnd-labels-container"] > div:nth-child(2)',
|
||||
).contains('name');
|
||||
|
||||
cy.wait('@chart');
|
||||
cy.get('[data-test="slice-container"] table > thead th')
|
||||
.first()
|
||||
.contains('gender');
|
||||
cy.get('[data-test="slice-container"] table > thead th')
|
||||
.last()
|
||||
.contains('name');
|
||||
});
|
||||
});
|
||||
@@ -1,41 +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 selectResultsTab = () =>
|
||||
cy.get('.SouthPane .ReactVirtualized__Table', { timeout: 10000 });
|
||||
|
||||
// this function asserts that the result set for two SQL lab table results are equal
|
||||
export const assertSQLLabResultsAreEqual = (resultsA, resultsB) => {
|
||||
const [headerA, bodyWrapperA] = resultsA.childNodes;
|
||||
const bodyA = bodyWrapperA.childNodes[0];
|
||||
|
||||
const [headerB, bodyWrapperB] = resultsB.childNodes;
|
||||
const bodyB = bodyWrapperB.childNodes[0];
|
||||
|
||||
expect(headerA.childNodes.length).to.equal(headerB.childNodes.length);
|
||||
expect(bodyA.childNodes.length).to.equal(bodyB.childNodes.length);
|
||||
|
||||
bodyA.childNodes.forEach((rowA, rowIndex) => {
|
||||
const rowB = bodyB.childNodes[rowIndex];
|
||||
|
||||
rowA.childNodes.forEach((cellA, columnIndex) => {
|
||||
const cellB = rowB.childNodes[columnIndex];
|
||||
expect(cellA.innerText).to.equal(cellB.innerText);
|
||||
});
|
||||
});
|
||||
};
|
||||
@@ -1,113 +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.
|
||||
*/
|
||||
describe('SqlLab query tabs', () => {
|
||||
beforeEach(() => {
|
||||
cy.visit('/sqllab');
|
||||
});
|
||||
|
||||
const tablistSelector = '[data-test="sql-editor-tabs"] > [role="tablist"]';
|
||||
const tabSelector = `${tablistSelector} [role="tab"]:not([type="button"])`;
|
||||
|
||||
it('allows you to create and close a tab', () => {
|
||||
cy.get(tabSelector).then(tabs => {
|
||||
const initialTabCount = tabs.length;
|
||||
const initialUntitledCount = Math.max(
|
||||
0,
|
||||
...tabs
|
||||
.map(
|
||||
(i, tabItem) =>
|
||||
Number(tabItem.textContent?.match(/Untitled Query (\d+)/)?.[1]) ||
|
||||
0,
|
||||
)
|
||||
.toArray(),
|
||||
);
|
||||
|
||||
// add two new tabs
|
||||
cy.get('[data-test="add-tab-icon"]:visible:last').click({ force: true });
|
||||
cy.contains('[role="tab"]', `Untitled Query ${initialUntitledCount + 1}`);
|
||||
cy.get(tabSelector).should('have.length', initialTabCount + 1);
|
||||
|
||||
cy.get('[data-test="add-tab-icon"]:visible:last').click({ force: true });
|
||||
cy.contains('[role="tab"]', `Untitled Query ${initialUntitledCount + 2}`);
|
||||
cy.get(tabSelector).should('have.length', initialTabCount + 2);
|
||||
|
||||
// close the tabs
|
||||
cy.get(`${tabSelector}:last [data-test="dropdown-trigger"]`).click({
|
||||
force: true,
|
||||
});
|
||||
cy.get('[data-test="close-tab-menu-option"]').click();
|
||||
cy.get(tabSelector).should('have.length', initialTabCount + 1);
|
||||
cy.contains('[role="tab"]', `Untitled Query ${initialUntitledCount + 1}`);
|
||||
|
||||
cy.get(`${tablistSelector} [aria-label="remove"]:last`).click();
|
||||
cy.get(tabSelector).should('have.length', initialTabCount);
|
||||
});
|
||||
});
|
||||
|
||||
it('opens a new tab by a button and a shortcut', () => {
|
||||
const editorContent = '.ace_editor .ace_content';
|
||||
const editorInput = '.ace_editor textarea';
|
||||
const queryLimitSelector = '#js-sql-toolbar .limitDropdown';
|
||||
cy.get(tabSelector).then(tabs => {
|
||||
const initialTabCount = tabs.length;
|
||||
const initialUntitledCount = Math.max(
|
||||
0,
|
||||
...tabs
|
||||
.map(
|
||||
(i, tabItem) =>
|
||||
Number(tabItem.textContent?.match(/Untitled Query (\d+)/)?.[1]) ||
|
||||
0,
|
||||
)
|
||||
.toArray(),
|
||||
);
|
||||
|
||||
// configure some editor settings
|
||||
cy.get(editorInput).type('some random query string', { force: true });
|
||||
cy.get(queryLimitSelector).parent().click({ force: true });
|
||||
cy.get('.ant-dropdown-menu')
|
||||
.last()
|
||||
.find('.ant-dropdown-menu-item')
|
||||
.first()
|
||||
.click({ force: true });
|
||||
|
||||
// open a new tab by a button
|
||||
cy.get('[data-test="add-tab-icon"]:visible:last').click({ force: true });
|
||||
cy.contains('[role="tab"]', `Untitled Query ${initialUntitledCount + 1}`);
|
||||
cy.get(tabSelector).should('have.length', initialTabCount + 1);
|
||||
cy.get(editorContent).contains('SELECT ...');
|
||||
cy.get(queryLimitSelector).contains('10');
|
||||
|
||||
// close the tab
|
||||
cy.get(`${tabSelector}:last [data-test="dropdown-trigger"]`).click({
|
||||
force: true,
|
||||
});
|
||||
cy.get(`${tablistSelector} [aria-label="remove"]:last`).click({
|
||||
force: true,
|
||||
});
|
||||
cy.get(tabSelector).should('have.length', initialTabCount);
|
||||
|
||||
// open a new tab by a shortcut
|
||||
cy.get('body').type('{ctrl}t');
|
||||
cy.get(tabSelector).should('have.length', initialTabCount + 1);
|
||||
cy.contains('[role="tab"]', `Untitled Query ${initialUntitledCount + 1}`);
|
||||
cy.get(editorContent).contains('SELECT ...');
|
||||
cy.get(queryLimitSelector).contains('10');
|
||||
});
|
||||
});
|
||||
});
|
||||
1049
superset-frontend/package-lock.json
generated
@@ -128,17 +128,17 @@
|
||||
"@superset-ui/legacy-plugin-chart-chord": "file:./plugins/legacy-plugin-chart-chord",
|
||||
"@superset-ui/legacy-plugin-chart-country-map": "file:./plugins/legacy-plugin-chart-country-map",
|
||||
"@superset-ui/legacy-plugin-chart-horizon": "file:./plugins/legacy-plugin-chart-horizon",
|
||||
"@superset-ui/legacy-plugin-chart-map-box": "file:./plugins/legacy-plugin-chart-map-box",
|
||||
"@superset-ui/legacy-plugin-chart-paired-t-test": "file:./plugins/legacy-plugin-chart-paired-t-test",
|
||||
"@superset-ui/legacy-plugin-chart-parallel-coordinates": "file:./plugins/legacy-plugin-chart-parallel-coordinates",
|
||||
"@superset-ui/legacy-plugin-chart-partition": "file:./plugins/legacy-plugin-chart-partition",
|
||||
"@superset-ui/legacy-plugin-chart-rose": "file:./plugins/legacy-plugin-chart-rose",
|
||||
"@superset-ui/legacy-plugin-chart-world-map": "file:./plugins/legacy-plugin-chart-world-map",
|
||||
"@superset-ui/legacy-preset-chart-deckgl": "file:./plugins/legacy-preset-chart-deckgl",
|
||||
"@superset-ui/preset-chart-deckgl": "file:./plugins/preset-chart-deckgl",
|
||||
"@superset-ui/legacy-preset-chart-nvd3": "file:./plugins/legacy-preset-chart-nvd3",
|
||||
"@superset-ui/plugin-chart-ag-grid-table": "file:./plugins/plugin-chart-ag-grid-table",
|
||||
"@superset-ui/plugin-chart-cartodiagram": "file:./plugins/plugin-chart-cartodiagram",
|
||||
"@superset-ui/plugin-chart-echarts": "file:./plugins/plugin-chart-echarts",
|
||||
"@superset-ui/plugin-chart-point-cluster-map": "file:./plugins/plugin-chart-point-cluster-map",
|
||||
"@superset-ui/plugin-chart-handlebars": "file:./plugins/plugin-chart-handlebars",
|
||||
"@superset-ui/plugin-chart-pivot-table": "file:./plugins/plugin-chart-pivot-table",
|
||||
"@superset-ui/plugin-chart-table": "file:./plugins/plugin-chart-table",
|
||||
@@ -168,7 +168,7 @@
|
||||
"echarts": "^5.6.0",
|
||||
"fast-glob": "^3.3.2",
|
||||
"fs-extra": "^11.3.4",
|
||||
"fuse.js": "^7.1.0",
|
||||
"fuse.js": "^7.3.0",
|
||||
"geolib": "^3.3.14",
|
||||
"geostyler": "^18.3.1",
|
||||
"geostyler-data": "^1.1.0",
|
||||
@@ -184,7 +184,7 @@
|
||||
"json-stringify-pretty-compact": "^2.0.0",
|
||||
"lodash": "^4.18.1",
|
||||
"mapbox-gl": "^3.20.0",
|
||||
"markdown-to-jsx": "^9.7.13",
|
||||
"markdown-to-jsx": "^9.7.15",
|
||||
"match-sorter": "^8.2.0",
|
||||
"memoize-one": "^5.2.1",
|
||||
"mousetrap": "^1.6.5",
|
||||
@@ -284,7 +284,7 @@
|
||||
"@types/js-levenshtein": "^1.1.3",
|
||||
"@types/json-bigint": "^1.0.4",
|
||||
"@types/mousetrap": "^1.6.15",
|
||||
"@types/node": "^25.5.0",
|
||||
"@types/node": "^25.6.0",
|
||||
"@types/react": "^17.0.83",
|
||||
"@types/react-dom": "^17.0.26",
|
||||
"@types/react-loadable": "^5.5.11",
|
||||
@@ -305,7 +305,7 @@
|
||||
"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.13",
|
||||
"baseline-browser-mapping": "^2.10.16",
|
||||
"cheerio": "1.2.0",
|
||||
"concurrently": "^9.2.1",
|
||||
"copy-webpack-plugin": "^14.0.0",
|
||||
@@ -347,7 +347,7 @@
|
||||
"open-cli": "^9.0.0",
|
||||
"oxlint": "^1.56.0",
|
||||
"po2json": "^0.4.5",
|
||||
"prettier": "3.8.1",
|
||||
"prettier": "3.8.2",
|
||||
"prettier-plugin-packagejson": "^3.0.2",
|
||||
"process": "^0.11.10",
|
||||
"react-refresh": "^0.18.0",
|
||||
@@ -367,8 +367,8 @@
|
||||
"typescript": "5.4.5",
|
||||
"unzipper": "^0.12.3",
|
||||
"vm-browserify": "^1.1.2",
|
||||
"wait-on": "^9.0.4",
|
||||
"webpack": "^5.105.4",
|
||||
"wait-on": "^9.0.5",
|
||||
"webpack": "^5.106.0",
|
||||
"webpack-bundle-analyzer": "^5.3.0",
|
||||
"webpack-cli": "^6.0.1",
|
||||
"webpack-dev-server": "^5.2.3",
|
||||
|
||||
@@ -76,7 +76,7 @@
|
||||
"@types/d3-time-format": "^4.0.3",
|
||||
"@types/jquery": "^3.5.33",
|
||||
"@types/lodash": "^4.17.24",
|
||||
"@types/node": "^25.5.0",
|
||||
"@types/node": "^25.6.0",
|
||||
"@types/prop-types": "^15.7.15",
|
||||
"@types/react-syntax-highlighter": "^15.5.13",
|
||||
"@types/react-table": "^7.7.20",
|
||||
|
||||
@@ -41,6 +41,7 @@ export enum VizType {
|
||||
LegacyBubble = 'bubble',
|
||||
Line = 'echarts_timeseries_line',
|
||||
MapBox = 'mapbox',
|
||||
PointClusterMap = 'point_cluster_map',
|
||||
MixedTimeseries = 'mixed_timeseries',
|
||||
PairedTTest = 'paired_ttest',
|
||||
ParallelCoordinates = 'para',
|
||||
|
||||
@@ -33,20 +33,22 @@ import type { PlaceholderProps } from './types';
|
||||
function DefaultPlaceholder({
|
||||
width,
|
||||
height,
|
||||
showLoadingForImport = false,
|
||||
showLoadingForImport = true,
|
||||
placeholderStyle: style,
|
||||
}: PlaceholderProps) {
|
||||
return (
|
||||
// since `width` defaults to 100%, we can display the placeholder once
|
||||
// height is specified.
|
||||
(height && (
|
||||
if (showLoadingForImport) {
|
||||
return (
|
||||
<div key="async-asm-placeholder" style={{ width, height, ...style }}>
|
||||
{showLoadingForImport && <Loading position="floating" />}
|
||||
<Loading position="floating" size="s" />
|
||||
</div>
|
||||
)) ||
|
||||
// `|| null` is for in case of height=0.
|
||||
null
|
||||
);
|
||||
);
|
||||
}
|
||||
if (height) {
|
||||
return (
|
||||
<div key="async-asm-placeholder" style={{ width, height, ...style }} />
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
import { render, screen } from '../../spec';
|
||||
import { render, screen, fireEvent } from '../../spec';
|
||||
import CodeSyntaxHighlighter from './index';
|
||||
|
||||
// Simple mock that just returns the content
|
||||
@@ -153,4 +153,44 @@ describe('CodeSyntaxHighlighter', () => {
|
||||
|
||||
expect(screen.getByText('SELECT * FROM users;')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('shows copy button by default', () => {
|
||||
render(
|
||||
<CodeSyntaxHighlighter language="sql">SELECT 1;</CodeSyntaxHighlighter>,
|
||||
);
|
||||
|
||||
expect(screen.getByTitle('Copy to clipboard')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('hides copy button when showCopyButton is false', () => {
|
||||
render(
|
||||
<CodeSyntaxHighlighter language="sql" showCopyButton={false}>
|
||||
SELECT 1;
|
||||
</CodeSyntaxHighlighter>,
|
||||
);
|
||||
|
||||
expect(screen.queryByTitle('Copy to clipboard')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('copy button does not throw when clipboard API is unavailable', () => {
|
||||
const originalClipboard = navigator.clipboard;
|
||||
Object.defineProperty(navigator, 'clipboard', {
|
||||
value: undefined,
|
||||
configurable: true,
|
||||
});
|
||||
document.execCommand = jest.fn().mockReturnValue(true);
|
||||
|
||||
render(
|
||||
<CodeSyntaxHighlighter language="sql">SELECT 1;</CodeSyntaxHighlighter>,
|
||||
);
|
||||
|
||||
expect(() =>
|
||||
fireEvent.click(screen.getByTitle('Copy to clipboard')),
|
||||
).not.toThrow();
|
||||
|
||||
Object.defineProperty(navigator, 'clipboard', {
|
||||
value: originalClipboard,
|
||||
configurable: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -16,11 +16,14 @@
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import SyntaxHighlighterBase from 'react-syntax-highlighter/dist/cjs/light';
|
||||
import github from 'react-syntax-highlighter/dist/cjs/styles/hljs/github';
|
||||
import tomorrow from 'react-syntax-highlighter/dist/cjs/styles/hljs/tomorrow-night';
|
||||
import { isThemeDark, useTheme } from '@apache-superset/core/theme';
|
||||
import { css, isThemeDark, useTheme } from '@apache-superset/core/theme';
|
||||
import { t } from '@apache-superset/core/translation';
|
||||
import copyTextToClipboard from '../../utils/copy';
|
||||
import { Icons } from '../Icons';
|
||||
|
||||
export type SupportedLanguage = 'sql' | 'htmlbars' | 'markdown' | 'json';
|
||||
|
||||
@@ -31,6 +34,7 @@ export interface CodeSyntaxHighlighterProps {
|
||||
showLineNumbers?: boolean;
|
||||
wrapLines?: boolean;
|
||||
style?: any; // Override theme style if needed
|
||||
showCopyButton?: boolean;
|
||||
}
|
||||
|
||||
// Track which languages have been registered to avoid duplicate registrations
|
||||
@@ -76,11 +80,14 @@ export const CodeSyntaxHighlighter: React.FC<CodeSyntaxHighlighterProps> = ({
|
||||
showLineNumbers = false,
|
||||
wrapLines = true,
|
||||
style: overrideStyle,
|
||||
showCopyButton = true,
|
||||
}) => {
|
||||
const theme = useTheme();
|
||||
const [isLanguageReady, setIsLanguageReady] = useState(
|
||||
registeredLanguages.has(language),
|
||||
);
|
||||
const [copied, setCopied] = useState(false);
|
||||
const copyTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const loadLanguage = async () => {
|
||||
@@ -93,6 +100,21 @@ export const CodeSyntaxHighlighter: React.FC<CodeSyntaxHighlighterProps> = ({
|
||||
loadLanguage();
|
||||
}, [language]);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (copyTimeoutRef.current) clearTimeout(copyTimeoutRef.current);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const handleCopy = useCallback(() => {
|
||||
copyTextToClipboard(() => Promise.resolve(children)).then(() => {
|
||||
if (copyTimeoutRef.current) clearTimeout(copyTimeoutRef.current);
|
||||
setCopied(true);
|
||||
copyTimeoutRef.current = setTimeout(() => setCopied(false), 1500);
|
||||
});
|
||||
}, [children]);
|
||||
|
||||
const isDark = isThemeDark(theme);
|
||||
const themeStyle = overrideStyle || (isDark ? tomorrow : github);
|
||||
|
||||
@@ -104,32 +126,79 @@ export const CodeSyntaxHighlighter: React.FC<CodeSyntaxHighlighterProps> = ({
|
||||
...customStyle,
|
||||
};
|
||||
|
||||
const copyButton = showCopyButton && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
handleCopy();
|
||||
}}
|
||||
title={copied ? t('Copied!') : t('Copy to clipboard')}
|
||||
css={css`
|
||||
position: absolute;
|
||||
top: ${theme.sizeUnit}px;
|
||||
right: ${theme.sizeUnit}px;
|
||||
background: none;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
padding: ${theme.sizeUnit}px;
|
||||
color: ${copied ? theme.colorSuccess : theme.colorTextSecondary};
|
||||
line-height: 1;
|
||||
border-radius: ${theme.borderRadius}px;
|
||||
&:hover {
|
||||
color: ${copied ? theme.colorSuccess : theme.colorText};
|
||||
background: ${theme.colorBgTextHover};
|
||||
}
|
||||
`}
|
||||
>
|
||||
{copied ? (
|
||||
<Icons.CheckOutlined style={{ fontSize: theme.fontSizeSM }} />
|
||||
) : (
|
||||
<Icons.CopyOutlined style={{ fontSize: theme.fontSizeSM }} />
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
|
||||
// Show a simple pre-formatted text while language is loading
|
||||
if (!isLanguageReady) {
|
||||
return (
|
||||
<pre
|
||||
style={{
|
||||
...defaultCustomStyle,
|
||||
fontFamily: 'monospace',
|
||||
whiteSpace: 'pre-wrap',
|
||||
margin: 0,
|
||||
}}
|
||||
<div
|
||||
css={css`
|
||||
position: relative;
|
||||
`}
|
||||
>
|
||||
{children}
|
||||
</pre>
|
||||
{copyButton}
|
||||
<pre
|
||||
style={{
|
||||
...defaultCustomStyle,
|
||||
fontFamily: 'monospace',
|
||||
whiteSpace: 'pre-wrap',
|
||||
margin: 0,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</pre>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<SyntaxHighlighterBase
|
||||
language={language}
|
||||
style={themeStyle}
|
||||
customStyle={defaultCustomStyle}
|
||||
showLineNumbers={showLineNumbers}
|
||||
wrapLines={wrapLines}
|
||||
<div
|
||||
css={css`
|
||||
position: relative;
|
||||
`}
|
||||
>
|
||||
{children}
|
||||
</SyntaxHighlighterBase>
|
||||
{copyButton}
|
||||
<SyntaxHighlighterBase
|
||||
language={language}
|
||||
style={themeStyle}
|
||||
customStyle={defaultCustomStyle}
|
||||
showLineNumbers={showLineNumbers}
|
||||
wrapLines={wrapLines}
|
||||
>
|
||||
{children}
|
||||
</SyntaxHighlighterBase>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -17,10 +17,10 @@ specific language governing permissions and limitations
|
||||
under the License.
|
||||
-->
|
||||
<svg viewBox="0 0 119 78" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<rect x="17" y="1" width="86" height="62" rx="3" stroke="currentColor" stroke-width="2"/>
|
||||
<rect x="21" y="5" width="78" height="14" rx="3" stroke="currentColor" stroke-width="2"/>
|
||||
<rect x="21" y="23" width="38" height="36" rx="3" stroke="currentColor" stroke-width="2"/>
|
||||
<rect x="63" y="37" width="36" height="22" rx="3" stroke="currentColor" stroke-width="2"/>
|
||||
<rect x="63" y="23" width="36" height="10" rx="3" stroke="currentColor" stroke-width="2"/>
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M16 55.2892C6.07439 57.7013 0 60.9397 0 64.5C0 71.9559 26.6391 78 59.5 78C92.3609 78 119 71.9559 119 64.5C119 61.0609 113.332 57.9221 104 55.5383V60C104 62.2092 102.209 64 100 64H20C17.7909 64 16 62.2092 16 60V55.2892Z" fill="currentColor" fill-opacity="0.25" stroke="currentColor"/>
|
||||
<path d="M99.3193 1H20.6639C19.0349 1 17.7143 2.32057 17.7143 3.94958V59.0084C17.7143 60.6374 19.0349 61.958 20.6639 61.958H99.3193C100.948 61.958 102.269 60.6374 102.269 59.0084V3.94958C102.269 2.32057 100.948 1 99.3193 1Z" stroke="currentColor" stroke-width="2"/>
|
||||
<path d="M95.3866 4.93277H24.5966C22.9676 4.93277 21.647 6.25335 21.647 7.88235V15.7479C21.647 17.3769 22.9676 18.6975 24.5966 18.6975H95.3866C97.0156 18.6975 98.3361 17.3769 98.3361 15.7479V7.88235C98.3361 6.25335 97.0156 4.93277 95.3866 4.93277Z" stroke="currentColor" stroke-width="2"/>
|
||||
<path d="M56.0588 22.6303H24.5966C22.9676 22.6303 21.647 23.9508 21.647 25.5798V55.0756C21.647 56.7046 22.9676 58.0252 24.5966 58.0252H56.0588C57.6878 58.0252 59.0084 56.7046 59.0084 55.0756V25.5798C59.0084 23.9508 57.6878 22.6303 56.0588 22.6303Z" stroke="currentColor" stroke-width="2"/>
|
||||
<path d="M95.3865 36.395H65.8907C64.2617 36.395 62.9412 37.7155 62.9412 39.3445V55.0756C62.9412 56.7046 64.2617 58.0252 65.8907 58.0252H95.3865C97.0155 58.0252 98.3361 56.7046 98.3361 55.0756V39.3445C98.3361 37.7155 97.0155 36.395 95.3865 36.395Z" stroke="currentColor" stroke-width="2"/>
|
||||
<path d="M95.3865 22.6303H65.8907C64.2617 22.6303 62.9412 23.9508 62.9412 25.5798V29.5126C62.9412 31.1416 64.2617 32.4622 65.8907 32.4622H95.3865C97.0155 32.4622 98.3361 31.1416 98.3361 29.5126V25.5798C98.3361 23.9508 97.0155 22.6303 95.3865 22.6303Z" stroke="currentColor" stroke-width="2"/>
|
||||
<path d="M17.2227 59.0086C17.2228 60.9091 18.7637 62.45 20.6641 62.45H99.3193C101.22 62.45 102.761 60.9091 102.761 59.0086V53.9891L103.374 54.1453C107.981 55.3221 111.718 56.6931 114.315 58.2137C116.877 59.7134 118.491 61.4572 118.491 63.4324C118.491 64.5056 118.01 65.513 117.177 66.4373C116.346 67.3587 115.143 68.2232 113.635 69.032C110.618 70.6501 106.286 72.0925 100.975 73.2977C90.343 75.7099 75.6797 77.1971 59.5 77.1971C43.3203 77.1971 28.657 75.7099 18.0254 73.2977C12.7137 72.0925 8.38162 70.6501 5.36523 69.032C3.85742 68.2232 2.65424 67.3587 1.82324 66.4373C0.989641 65.513 0.508789 64.5056 0.508789 63.4324C0.508977 61.389 2.23587 59.5926 4.96484 58.0535C7.73449 56.4916 11.717 55.0896 16.6152 53.8992L17.2227 53.7518V59.0086Z" fill="currentColor" fill-opacity="0.25" stroke="currentColor"/>
|
||||
</svg>
|
||||
|
||||
|
Before Width: | Height: | Size: 1.6 KiB After Width: | Height: | Size: 3.0 KiB |
@@ -17,6 +17,6 @@ specific language governing permissions and limitations
|
||||
under the License.
|
||||
-->
|
||||
<svg viewBox="0 0 119 76" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M83.1952 1.36598L103 24V62C103 64.2091 101.209 66 99 66H20C17.7909 66 16 64.2091 16 62V24L35.8048 1.36598C36.5643 0.497921 37.6616 0 38.8151 0H80.1849C81.3384 0 82.4357 0.497922 83.1952 1.36598ZM101 26V62C101 63.1046 100.105 64 99 64H20C18.8954 64 18 63.1046 18 62V26H35.25C37.8734 26 40 28.1266 40 30.75C40 34.4779 43.0221 37.5 46.75 37.5H72.25C75.9779 37.5 79 34.4779 79 30.75C79 28.1266 81.1266 26 83.75 26H101ZM100.342 24L81.6901 2.68299C81.3103 2.24896 80.7617 2 80.1849 2H38.8151C38.2383 2 37.6897 2.24896 37.3099 2.68299L18.6575 24H35.25C38.9779 24 42 27.0221 42 30.75C42 33.3734 44.1266 35.5 46.75 35.5H72.25C74.8734 35.5 77 33.3734 77 30.75C77 27.0221 80.0221 24 83.75 24H100.342Z" fill="currentColor"/>
|
||||
<path d="M16 53.2891C6.07439 55.7012 0 58.9396 0 62.4999C0 69.9557 26.6391 75.9999 59.5 75.9999C92.3609 75.9999 119 69.9557 119 62.4999C119 58.9396 112.926 55.7012 103 53.2891V61.9999C103 64.209 101.209 65.9999 99 65.9999H20C17.7909 65.9999 16 64.209 16 61.9999V53.2891Z" fill="currentColor" stroke="currentColor" fill-opacity="0.25" />
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M82.7969 1.34302L102.269 23.5966V60.958C102.269 63.13 100.508 64.8908 98.3361 64.8908H20.6639C18.4919 64.8908 16.7311 63.13 16.7311 60.958V23.5966L36.203 1.34302C36.9498 0.489553 38.0286 0 39.1627 0H79.8372C80.9713 0 82.0502 0.489554 82.7969 1.34302ZM100.303 25.563V60.958C100.303 62.044 99.4225 62.9244 98.3361 62.9244H20.6639C19.5778 62.9244 18.6975 62.044 18.6975 60.958V25.563H35.6575C38.2369 25.563 40.3277 27.6539 40.3277 30.2332C40.3277 33.8984 43.299 36.8698 46.9643 36.8698H72.0357C75.7009 36.8698 78.6723 33.8984 78.6723 30.2332C78.6723 27.6539 80.7631 25.563 83.3424 25.563H100.303ZM99.6556 23.5966L81.3171 2.6379C80.9437 2.21116 80.4043 1.96639 79.8372 1.96639H39.1627C38.5956 1.96639 38.0562 2.21116 37.6828 2.6379L19.3439 23.5966H35.6575C39.3228 23.5966 42.2941 26.568 42.2941 30.2332C42.2941 32.8125 44.385 34.9034 46.9643 34.9034H72.0357C74.615 34.9034 76.7059 32.8125 76.7059 30.2332C76.7059 26.568 79.6772 23.5966 83.3424 23.5966H99.6556Z" fill="currentColor"/>
|
||||
<path d="M102.385 51.9159C107.283 53.1063 111.266 54.5083 114.035 56.0702C116.764 57.6093 118.491 59.4058 118.491 61.4492C118.491 62.5223 118.01 63.5298 117.177 64.454C116.346 65.3754 115.143 66.2399 113.635 67.0488C110.618 68.6668 106.286 70.1092 100.975 71.3144C90.343 73.7266 75.6797 75.2138 59.5 75.2138C43.3203 75.2138 28.657 73.7266 18.0254 71.3144C12.7137 70.1092 8.38162 68.6668 5.36523 67.0488C3.85743 66.2399 2.65424 65.3754 1.82324 64.454C0.989642 63.5298 0.508789 62.5223 0.508789 61.4492C0.508976 59.4057 2.23587 57.6093 4.96484 56.0702C7.73449 54.5083 11.717 53.1063 16.6152 51.9159L17.2227 51.7685V60.9579C17.2227 62.8584 18.7636 64.3993 20.6641 64.3993H98.3359C100.236 64.3993 101.777 62.8584 101.777 60.9579V51.7685L102.385 51.9159Z" fill="currentColor" stroke="currentColor" fill-opacity="0.25" />
|
||||
</svg>
|
||||
|
||||
|
Before Width: | Height: | Size: 1.9 KiB After Width: | Height: | Size: 2.6 KiB |
@@ -17,6 +17,6 @@ specific language governing permissions and limitations
|
||||
under the License.
|
||||
-->
|
||||
<svg viewBox="0 0 119 78" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M59.2123 1.55857C59.4575 0.81382 60.5425 0.813801 60.7878 1.55857L67.5616 22.1322C67.9434 23.292 69.0328 24.0653 70.249 24.0653L92.1695 24.0653C92.9982 24.0653 93.2777 25.0719 92.6607 25.5143L74.9266 38.2295C73.9348 38.9406 73.5131 40.2085 73.8958 41.3707L80.6696 61.9444C80.8987 62.6402 80.076 63.3262 79.3906 62.8348L61.6566 50.1196C60.6679 49.4107 59.3321 49.4107 58.3434 50.1196L40.6094 62.8348C39.924 63.3262 39.1013 62.6402 39.3304 61.9444L46.1042 41.3707C46.4869 40.2085 46.0652 38.9406 45.0734 38.2295L27.3393 25.5143C26.7223 25.0719 27.0018 24.0653 27.8305 24.0653L49.751 24.0653C50.9672 24.0653 52.0566 23.292 52.4384 22.1322L59.2123 1.55857Z" stroke="currentColor" stroke-width="2"/>
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M41.6782 51.616C17.5239 53.3343 0 58.4528 0 64.5C0 71.9558 26.6391 78 59.5 78C92.3609 78 119 71.9558 119 64.5C119 58.5387 101.97 53.4798 78.3466 51.6913L81.6194 61.6317C82.1664 63.2928 80.2398 64.6741 78.808 63.6475L61.1757 51.0053C60.619 51.0018 60.0604 51 59.5 51C59.2765 51 59.0534 51.0003 58.8305 51.0008L41.192 63.6475C39.7602 64.6741 37.8337 63.2928 38.3806 61.6317L41.6782 51.616Z" fill="currentColor" fill-opacity="0.25" stroke="currentColor"/>
|
||||
<path d="M59.2172 1.54918C59.4582 0.816949 60.525 0.81693 60.7662 1.54918L67.4261 21.777C67.8015 22.9173 68.8726 23.6776 70.0684 23.6776H91.6205C92.4352 23.6776 92.71 24.6673 92.1034 25.1023L74.6673 37.6038C73.6922 38.3029 73.2776 39.5495 73.6539 40.6922L80.3138 60.9201C80.5391 61.6042 79.7302 62.2787 79.0563 61.7956L61.6204 49.2941C60.6483 48.5971 59.3349 48.5971 58.3629 49.2941L40.9269 61.7956C40.253 62.2787 39.4441 61.6042 39.6694 60.9201L46.3294 40.6922C46.7056 39.5495 46.291 38.3029 45.3159 37.6038L27.8798 25.1023C27.2732 24.6673 27.548 23.6776 28.3628 23.6776H49.9149C51.1106 23.6776 52.1817 22.9173 52.5571 21.777L59.2172 1.54918Z" stroke="currentColor" stroke-width="2"/>
|
||||
<path d="M59.5 49.6685C60.052 49.6685 60.6021 49.6699 61.1504 49.6733L61.3066 49.6743L61.4336 49.7651L78.7695 62.1948C79.8103 62.9411 81.1618 61.9247 80.7803 60.7661L77.5625 50.9927L77.333 50.2935L78.0674 50.3491C89.7005 51.2299 99.7327 52.9176 106.87 55.1284C110.435 56.2328 113.307 57.4759 115.298 58.8335C117.27 60.1787 118.491 61.7173 118.491 63.4331C118.491 64.5061 118.01 65.5129 117.177 66.437C116.346 67.3584 115.143 68.2239 113.635 69.0327C110.618 70.6507 106.286 72.0922 100.975 73.2974C90.343 75.7096 75.6797 77.1978 59.5 77.1978C43.3203 77.1978 28.657 75.7096 18.0254 73.2974C12.7139 72.0922 8.3816 70.6507 5.36523 69.0327C3.85739 68.2239 2.65424 67.3584 1.82324 66.437C0.989783 65.5129 0.508887 64.5061 0.508789 63.4331C0.508789 61.6928 1.7644 60.135 3.78906 58.7749C5.83338 57.4017 8.78191 56.1452 12.4404 55.0327C19.7642 52.8057 30.0482 51.1211 41.9424 50.2749L42.6738 50.2231L42.4443 50.9194L39.2021 60.7661C38.8207 61.9247 40.1722 62.9409 41.2129 62.1948L58.5557 49.7612L58.6836 49.6694L58.8408 49.6685C59.0602 49.668 59.2799 49.6685 59.5 49.6685Z" fill="currentColor" fill-opacity="0.25" stroke="currentColor"/>
|
||||
</svg>
|
||||
|
||||
|
Before Width: | Height: | Size: 2.0 KiB After Width: | Height: | Size: 2.6 KiB |
@@ -25,6 +25,7 @@ import {
|
||||
waitFor,
|
||||
within,
|
||||
} from '@superset-ui/core/spec';
|
||||
import { formatNumber } from '@superset-ui/core';
|
||||
import { Select } from '.';
|
||||
|
||||
type Option = {
|
||||
@@ -85,8 +86,10 @@ const getElementsByClassName = (className: string) =>
|
||||
const getSelect = () =>
|
||||
screen.getByRole('combobox', { name: new RegExp(ARIA_LABEL, 'i') });
|
||||
|
||||
const selectAllButtonText = (length: number) => `Select all (${length})`;
|
||||
const deselectAllButtonText = (length: number) => `Clear (${length})`;
|
||||
const selectAllButtonText = (length: number) =>
|
||||
`Select all (${formatNumber('SMART_NUMBER', length)})`;
|
||||
const deselectAllButtonText = (length: number) =>
|
||||
`Clear (${formatNumber('SMART_NUMBER', length)})`;
|
||||
|
||||
const findSelectOption = (text: string) =>
|
||||
waitFor(() =>
|
||||
@@ -811,6 +814,62 @@ test('Maintains stable maxTagCount to prevent click target disappearing in oneLi
|
||||
expect(withinSelector.getByText('+ 2 ...')).toBeVisible();
|
||||
});
|
||||
|
||||
test('dropdown width matches input width after tags collapse in oneLine mode', async () => {
|
||||
render(
|
||||
<div style={{ width: '300px' }}>
|
||||
<Select
|
||||
{...defaultProps}
|
||||
value={[OPTIONS[0], OPTIONS[1], OPTIONS[2]]}
|
||||
mode="multiple"
|
||||
oneLine
|
||||
/>
|
||||
</div>,
|
||||
);
|
||||
|
||||
await open();
|
||||
|
||||
// Wait for RAF to complete and tags to collapse
|
||||
await waitFor(() => {
|
||||
const withinSelector = within(
|
||||
getElementByClassName('.ant-select-selector'),
|
||||
);
|
||||
expect(
|
||||
withinSelector.queryByText(OPTIONS[0].label),
|
||||
).not.toBeInTheDocument();
|
||||
expect(withinSelector.getByText('+ 3 ...')).toBeVisible();
|
||||
});
|
||||
|
||||
const selectElement = document.querySelector('.ant-select') as HTMLElement;
|
||||
expect(selectElement).toBeInTheDocument();
|
||||
|
||||
// Mock the select element's width since JSDOM doesn't perform real layout
|
||||
jest.spyOn(selectElement, 'getBoundingClientRect').mockReturnValue({
|
||||
width: 300,
|
||||
height: 32,
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 300,
|
||||
bottom: 32,
|
||||
x: 0,
|
||||
y: 0,
|
||||
toJSON: () => ({}),
|
||||
} as DOMRect);
|
||||
|
||||
// Close and reopen to trigger width measurement with mocked value
|
||||
await type('{esc}');
|
||||
await open();
|
||||
|
||||
const dropdown = document.querySelector(
|
||||
'.ant-select-dropdown',
|
||||
) as HTMLElement;
|
||||
expect(dropdown).toBeInTheDocument();
|
||||
|
||||
// Verify the dropdown has inline width matching the mocked select width
|
||||
await waitFor(() => {
|
||||
expect(parseInt(dropdown.style.width, 10)).toBe(300);
|
||||
});
|
||||
});
|
||||
|
||||
test('does not render "Select all" when there are 0 or 1 options', async () => {
|
||||
const { rerender } = render(
|
||||
<Select {...defaultProps} options={[]} mode="multiple" allowNewOptions />,
|
||||
@@ -915,6 +974,17 @@ test('"Select all" does not affect disabled options', async () => {
|
||||
expect(await findSelectValue()).not.toHaveTextContent(options[1].label);
|
||||
});
|
||||
|
||||
test('abbreviates large numbers in bulk action buttons', async () => {
|
||||
const manyOptions = Array.from({ length: 1500 }, (_, i) => ({
|
||||
label: `Option ${i}`,
|
||||
value: i,
|
||||
}));
|
||||
render(<Select {...defaultProps} mode="multiple" options={manyOptions} />);
|
||||
await open();
|
||||
// SMART_NUMBER format uses lowercase 'k' for thousands (d3-format)
|
||||
expect(await screen.findByText('Select all (1.5k)')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('dropdown takes full width of the select input for multi select', async () => {
|
||||
render(
|
||||
<div style={{ width: '400px' }}>
|
||||
|
||||
@@ -31,7 +31,7 @@ import {
|
||||
} from 'react';
|
||||
|
||||
import { t } from '@apache-superset/core/translation';
|
||||
import { ensureIsArray, usePrevious } from '@superset-ui/core';
|
||||
import { ensureIsArray, formatNumber, usePrevious } from '@superset-ui/core';
|
||||
import { Constants } from '@superset-ui/core/components';
|
||||
import {
|
||||
LabeledValue as AntdLabeledValue,
|
||||
@@ -149,6 +149,8 @@ const Select = forwardRef(
|
||||
// Prevent maxTagCount change during click events to avoid click target disappearing
|
||||
const [stableMaxTagCount, setStableMaxTagCount] = useState(maxTagCount);
|
||||
const isOpeningRef = useRef(false);
|
||||
const selectContainerRef = useRef<HTMLDivElement>(null);
|
||||
const [dropdownWidth, setDropdownWidth] = useState<number | true>(true);
|
||||
|
||||
useEffect(() => {
|
||||
if (oneLine) {
|
||||
@@ -159,12 +161,23 @@ const Select = forwardRef(
|
||||
requestAnimationFrame(() => {
|
||||
setStableMaxTagCount(0);
|
||||
isOpeningRef.current = false;
|
||||
|
||||
// Measure collapsed width and update dropdown width
|
||||
const selectElement =
|
||||
selectContainerRef.current?.querySelector('.ant-select');
|
||||
if (selectElement) {
|
||||
const { width } = selectElement.getBoundingClientRect();
|
||||
if (width > 0) {
|
||||
setDropdownWidth(width);
|
||||
}
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (!isDropdownVisible) {
|
||||
// When closing, immediately show the first tag
|
||||
setStableMaxTagCount(1);
|
||||
setDropdownWidth(true); // Reset to default when closing
|
||||
isOpeningRef.current = false;
|
||||
}
|
||||
return;
|
||||
@@ -494,7 +507,7 @@ const Select = forwardRef(
|
||||
|
||||
const bulkSelectComponent = useMemo(
|
||||
() => (
|
||||
<StyledBulkActionsContainer justify="center">
|
||||
<StyledBulkActionsContainer justify="space-between">
|
||||
<Button
|
||||
type="link"
|
||||
buttonStyle="link"
|
||||
@@ -506,7 +519,7 @@ const Select = forwardRef(
|
||||
handleSelectAll();
|
||||
}}
|
||||
>
|
||||
{`${t('Select all')} (${bulkSelectCounts.selectable})`}
|
||||
{`${t('Select all')} (${formatNumber('SMART_NUMBER', bulkSelectCounts.selectable)})`}
|
||||
</Button>
|
||||
<Button
|
||||
type="link"
|
||||
@@ -523,7 +536,7 @@ const Select = forwardRef(
|
||||
handleDeselectAll();
|
||||
}}
|
||||
>
|
||||
{`${t('Clear')} (${bulkSelectCounts.deselectable})`}
|
||||
{`${t('Clear')} (${formatNumber('SMART_NUMBER', bulkSelectCounts.deselectable)})`}
|
||||
</Button>
|
||||
</StyledBulkActionsContainer>
|
||||
),
|
||||
@@ -717,7 +730,11 @@ const Select = forwardRef(
|
||||
};
|
||||
|
||||
return (
|
||||
<StyledContainer className={className} headerPosition={headerPosition}>
|
||||
<StyledContainer
|
||||
ref={selectContainerRef}
|
||||
className={className}
|
||||
headerPosition={headerPosition}
|
||||
>
|
||||
{header && (
|
||||
<StyledHeader headerPosition={headerPosition}>{header}</StyledHeader>
|
||||
)}
|
||||
@@ -777,7 +794,7 @@ const Select = forwardRef(
|
||||
options={visibleOptions}
|
||||
optionRender={option => <Space>{option.label || option.value}</Space>}
|
||||
oneLine={oneLine}
|
||||
popupMatchSelectWidth
|
||||
popupMatchSelectWidth={oneLine ? dropdownWidth : true}
|
||||
css={props.css}
|
||||
dropdownAlign={DROPDOWN_ALIGN_BOTTOM}
|
||||
{...props}
|
||||
|
||||
@@ -140,11 +140,17 @@ export const StyledErrorMessage = styled.div`
|
||||
|
||||
export const StyledBulkActionsContainer = styled(Flex)`
|
||||
${({ theme }) => `
|
||||
padding: ${theme.sizeUnit}px;
|
||||
padding: ${theme.sizeUnit}px 0;
|
||||
border-top: 1px solid ${theme.colorSplit};
|
||||
gap: ${theme.sizeUnit * 2}px;
|
||||
& .superset-button {
|
||||
font-family: inherit;
|
||||
margin-left: 0 !important;
|
||||
}
|
||||
& .superset-button:first-of-type {
|
||||
padding-right: 0 !important;
|
||||
}
|
||||
& .superset-button:last-of-type {
|
||||
padding-left: 0 !important;
|
||||
}
|
||||
`}
|
||||
`;
|
||||
|
||||
@@ -158,11 +158,13 @@ test('passes all props through to AgGridReact', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
// onGridReady and onFirstDataRendered are intercepted by the component to expose
|
||||
// the grid API on the container element; the wrapped function is passed instead.
|
||||
expect(AgGridReact).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
rowData: mockRowData,
|
||||
columnDefs: mockColumnDefs,
|
||||
onGridReady,
|
||||
onGridReady: expect.any(Function),
|
||||
onCellClicked,
|
||||
pagination: true,
|
||||
paginationPageSize: 10,
|
||||
@@ -171,6 +173,47 @@ test('passes all props through to AgGridReact', () => {
|
||||
);
|
||||
});
|
||||
|
||||
test('onGridReady wrapper calls user callback and exposes api on container', () => {
|
||||
const onGridReady = jest.fn();
|
||||
|
||||
render(
|
||||
<ThemedAgGridReact
|
||||
rowData={mockRowData}
|
||||
columnDefs={mockColumnDefs}
|
||||
onGridReady={onGridReady}
|
||||
/>,
|
||||
);
|
||||
|
||||
// Retrieve the wrapped handler that was passed to AgGridReact
|
||||
const lastCall = (AgGridReact as jest.Mock).mock.calls.at(-1)[0];
|
||||
const wrappedOnGridReady = lastCall.onGridReady as Function;
|
||||
|
||||
const mockApi = { setGridOption: jest.fn() };
|
||||
wrappedOnGridReady({ api: mockApi });
|
||||
|
||||
// The user-provided callback must be forwarded
|
||||
expect(onGridReady).toHaveBeenCalledWith({ api: mockApi });
|
||||
});
|
||||
|
||||
test('onFirstDataRendered wrapper calls user callback', () => {
|
||||
const onFirstDataRendered = jest.fn();
|
||||
|
||||
render(
|
||||
<ThemedAgGridReact
|
||||
rowData={mockRowData}
|
||||
columnDefs={mockColumnDefs}
|
||||
onFirstDataRendered={onFirstDataRendered}
|
||||
/>,
|
||||
);
|
||||
|
||||
const lastCall = (AgGridReact as jest.Mock).mock.calls.at(-1)[0];
|
||||
const wrappedOnFirstDataRendered = lastCall.onFirstDataRendered as Function;
|
||||
|
||||
wrappedOnFirstDataRendered({ firstRow: 0 });
|
||||
|
||||
expect(onFirstDataRendered).toHaveBeenCalledWith({ firstRow: 0 });
|
||||
});
|
||||
|
||||
test('applies custom theme colors from Superset theme', () => {
|
||||
const customTheme = {
|
||||
...supersetTheme,
|
||||
|
||||
@@ -16,19 +16,28 @@
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
import { useMemo, forwardRef } from 'react';
|
||||
import { useMemo, useRef, useCallback, forwardRef } from 'react';
|
||||
import { css } from '@emotion/react';
|
||||
import { AgGridReact, type AgGridReactProps } from 'ag-grid-react';
|
||||
import {
|
||||
themeQuartz,
|
||||
colorSchemeDark,
|
||||
colorSchemeLight,
|
||||
type GridApi,
|
||||
type GridReadyEvent,
|
||||
type FirstDataRenderedEvent,
|
||||
} from 'ag-grid-community';
|
||||
import { useTheme, useThemeMode } from '@apache-superset/core/theme';
|
||||
|
||||
// Note: With ag-grid v34's new theming API, CSS files are injected automatically
|
||||
// Do NOT import 'ag-grid-community/styles/ag-grid.css' or theme CSS files
|
||||
|
||||
// Extends HTMLDivElement with ag-grid state attached to the container for downloadAsImage.
|
||||
export interface AgGridContainerElement extends HTMLDivElement {
|
||||
_agGridApi?: GridApi;
|
||||
_agGridFirstDataRendered?: boolean;
|
||||
}
|
||||
|
||||
export interface ThemedAgGridReactProps extends AgGridReactProps {
|
||||
/**
|
||||
* Optional theme parameter overrides to customize specific ag-grid theme values.
|
||||
@@ -71,9 +80,13 @@ export interface ThemedAgGridReactProps extends AgGridReactProps {
|
||||
export const ThemedAgGridReact = forwardRef<
|
||||
AgGridReact,
|
||||
ThemedAgGridReactProps
|
||||
>(function ThemedAgGridReact({ themeOverrides, ...props }, ref) {
|
||||
>(function ThemedAgGridReact(
|
||||
{ themeOverrides, onGridReady, onFirstDataRendered, ...props },
|
||||
ref,
|
||||
) {
|
||||
const theme = useTheme();
|
||||
const isDarkMode = useThemeMode();
|
||||
const containerRef = useRef<AgGridContainerElement>(null);
|
||||
|
||||
// Get the appropriate ag-grid theme based on dark/light mode
|
||||
const agGridTheme = useMemo(() => {
|
||||
@@ -140,8 +153,32 @@ export const ThemedAgGridReact = forwardRef<
|
||||
return baseTheme.withParams(finalParams);
|
||||
}, [theme, isDarkMode, themeOverrides]);
|
||||
|
||||
// Expose gridApi and first-data-rendered flag on the container for downloadAsImage.
|
||||
const handleGridReady = useCallback(
|
||||
(event: GridReadyEvent) => {
|
||||
if (containerRef.current) {
|
||||
containerRef.current._agGridFirstDataRendered = false;
|
||||
containerRef.current._agGridApi = event.api;
|
||||
}
|
||||
onGridReady?.(event);
|
||||
},
|
||||
[onGridReady],
|
||||
);
|
||||
|
||||
// Mark the container once rows are painted so downloadAsImage can gate on readiness.
|
||||
const handleFirstDataRendered = useCallback(
|
||||
(event: FirstDataRenderedEvent) => {
|
||||
if (containerRef.current) {
|
||||
containerRef.current._agGridFirstDataRendered = true;
|
||||
}
|
||||
onFirstDataRendered?.(event);
|
||||
},
|
||||
[onFirstDataRendered],
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={containerRef}
|
||||
css={css`
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
@@ -151,7 +188,13 @@ export const ThemedAgGridReact = forwardRef<
|
||||
`}
|
||||
data-themed-ag-grid="true"
|
||||
>
|
||||
<AgGridReact ref={ref} theme={agGridTheme} {...props} />
|
||||
<AgGridReact
|
||||
ref={ref}
|
||||
theme={agGridTheme}
|
||||
onGridReady={handleGridReady}
|
||||
onFirstDataRendered={handleFirstDataRendered}
|
||||
{...props}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
@@ -171,6 +214,7 @@ export type {
|
||||
CellClassParams,
|
||||
IMenuActionParams,
|
||||
IHeaderParams,
|
||||
SelectionChangedEvent,
|
||||
SortModelItem,
|
||||
ValueFormatterParams,
|
||||
ValueGetterParams,
|
||||
|
||||
@@ -201,6 +201,7 @@ export * from './Result';
|
||||
export {
|
||||
ThemedAgGridReact,
|
||||
type ThemedAgGridReactProps,
|
||||
type AgGridContainerElement,
|
||||
setupAGGridModules,
|
||||
defaultModules,
|
||||
} from './ThemedAgGridReact';
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
|
||||
const isSafari = (): boolean => {
|
||||
const { userAgent } = navigator;
|
||||
return Boolean(userAgent && /^((?!chrome|android).)*safari/i.test(userAgent));
|
||||
};
|
||||
|
||||
// Use the new Clipboard API if the browser supports it
|
||||
const copyTextWithClipboardApi = async (getText: () => Promise<string>) => {
|
||||
// Safari (WebKit) does not support delayed generation of clipboard.
|
||||
// This means that writing to the clipboard, from the moment the user
|
||||
// interacts with the app, must be instantaneous.
|
||||
// However, neither writeText nor write accepts a Promise, so
|
||||
// we need to create a ClipboardItem that accepts said Promise to
|
||||
// delay the text generation, as needed.
|
||||
// Source: https://bugs.webkit.org/show_bug.cgi?id=222262P
|
||||
if (isSafari()) {
|
||||
try {
|
||||
const clipboardItem = new ClipboardItem({
|
||||
'text/plain': getText(),
|
||||
});
|
||||
await navigator.clipboard.write([clipboardItem]);
|
||||
} catch {
|
||||
// Fallback to default clipboard API implementation
|
||||
const text = await getText();
|
||||
await navigator.clipboard.writeText(text);
|
||||
}
|
||||
} else {
|
||||
// For Blink, the above method won't work, but we can use the
|
||||
// default (intended) API, since the delayed generation of the
|
||||
// clipboard is now supported.
|
||||
// Source: https://bugs.chromium.org/p/chromium/issues/detail?id=1014310
|
||||
const text = await getText();
|
||||
await navigator.clipboard.writeText(text);
|
||||
}
|
||||
};
|
||||
|
||||
const copyTextToClipboard = (getText: () => Promise<string>) =>
|
||||
copyTextWithClipboardApi(getText)
|
||||
// If the Clipboard API is not supported, fallback to the older method.
|
||||
.catch(() =>
|
||||
getText().then(
|
||||
text =>
|
||||
new Promise<void>((resolve, reject) => {
|
||||
const selection: Selection | null = document.getSelection();
|
||||
if (selection) {
|
||||
selection.removeAllRanges();
|
||||
const range = document.createRange();
|
||||
const span = document.createElement('span');
|
||||
span.textContent = text;
|
||||
span.style.position = 'fixed';
|
||||
span.style.top = '0';
|
||||
span.style.clip = 'rect(0, 0, 0, 0)';
|
||||
span.style.whiteSpace = 'pre';
|
||||
|
||||
document.body.appendChild(span);
|
||||
range.selectNode(span);
|
||||
selection.addRange(range);
|
||||
|
||||
try {
|
||||
if (!document.execCommand('copy')) {
|
||||
reject();
|
||||
}
|
||||
} catch (err) {
|
||||
reject();
|
||||
}
|
||||
|
||||
document.body.removeChild(span);
|
||||
if (selection.removeRange) {
|
||||
selection.removeRange(range);
|
||||
} else {
|
||||
selection.removeAllRanges();
|
||||
}
|
||||
}
|
||||
|
||||
resolve();
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
export default copyTextToClipboard;
|
||||
@@ -17,6 +17,7 @@
|
||||
* under the License.
|
||||
*/
|
||||
export { default as convertKeysToCamelCase } from './convertKeysToCamelCase';
|
||||
export { default as copyTextToClipboard } from './copy';
|
||||
export { default as ensureIsArray } from './ensureIsArray';
|
||||
export { default as ensureIsInt } from './ensureIsInt';
|
||||
export { default as isDefined } from './isDefined';
|
||||
|
||||
@@ -94,6 +94,8 @@ export default defineConfig({
|
||||
name: 'chromium',
|
||||
testIgnore: [
|
||||
'**/tests/auth/**/*.spec.ts',
|
||||
'**/tests/sqllab/**/*.spec.ts',
|
||||
'**/tests/embedded/**/*.spec.ts',
|
||||
...(process.env.INCLUDE_EXPERIMENTAL ? [] : ['**/experimental/**']),
|
||||
],
|
||||
use: {
|
||||
@@ -103,6 +105,22 @@ export default defineConfig({
|
||||
storageState: 'playwright/.auth/user.json',
|
||||
},
|
||||
},
|
||||
{
|
||||
// SQL Lab needs its own project because tab state is stored server-side
|
||||
// per user (/tabstateview/*). All workers share the same auth user, so
|
||||
// parallel workers mutating tabs would cause nondeterministic tab counts
|
||||
// and cross-worker tab deletions. Other test suites (dataset, dashboard,
|
||||
// chart) don't need this because they create/delete isolated resources
|
||||
// via API with unique names — no shared mutable state between tests.
|
||||
name: 'chromium-sqllab',
|
||||
testMatch: '**/tests/sqllab/**/*.spec.ts',
|
||||
fullyParallel: false,
|
||||
use: {
|
||||
browserName: 'chromium',
|
||||
testIdAttribute: 'data-test',
|
||||
storageState: 'playwright/.auth/user.json',
|
||||
},
|
||||
},
|
||||
{
|
||||
// Separate project for unauthenticated tests (login, signup, etc.)
|
||||
// These tests use beforeEach for per-test navigation - no global auth
|
||||
@@ -115,6 +133,18 @@ export default defineConfig({
|
||||
// No storageState = clean browser with no cached cookies
|
||||
},
|
||||
},
|
||||
{
|
||||
// Embedded dashboard tests - validates the full embedding flow:
|
||||
// external app -> SDK -> iframe -> guest token -> dashboard render
|
||||
name: 'chromium-embedded',
|
||||
testMatch: '**/tests/embedded/**/*.spec.ts',
|
||||
use: {
|
||||
browserName: 'chromium',
|
||||
testIdAttribute: 'data-test',
|
||||
// Uses admin auth for API calls to configure embedding and get guest tokens
|
||||
storageState: 'playwright/.auth/user.json',
|
||||
},
|
||||
},
|
||||
],
|
||||
|
||||
// Web server setup - disabled in CI (Flask started separately in workflow)
|
||||
|
||||
85
superset-frontend/playwright/components/core/AgGrid.ts
Normal file
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
import { Locator, Page } from '@playwright/test';
|
||||
|
||||
const AG_GRID_SELECTORS = {
|
||||
ROOT: '[role="grid"]',
|
||||
HEADER_ROW: '.ag-header-row',
|
||||
HEADER_CELL: '.ag-header-cell',
|
||||
BODY_ROW: '.ag-row',
|
||||
CELL: '.ag-cell',
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* AG Grid component wrapper for Playwright.
|
||||
* Used by FilterableTable/GridTable in SQL Lab results and elsewhere.
|
||||
*/
|
||||
export class AgGrid {
|
||||
readonly page: Page;
|
||||
private readonly locator: Locator;
|
||||
|
||||
constructor(page: Page, locator: Locator) {
|
||||
this.page = page;
|
||||
this.locator = locator;
|
||||
}
|
||||
|
||||
get element(): Locator {
|
||||
return this.locator;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait for the grid to render with data rows
|
||||
*/
|
||||
async waitForRows(options?: { timeout?: number }): Promise<void> {
|
||||
await this.locator
|
||||
.locator(AG_GRID_SELECTORS.BODY_ROW)
|
||||
.first()
|
||||
.waitFor({ state: 'visible', ...options });
|
||||
}
|
||||
|
||||
/**
|
||||
* Get header cell texts
|
||||
*/
|
||||
async getHeaderTexts(): Promise<string[]> {
|
||||
return this.locator
|
||||
.locator(AG_GRID_SELECTORS.HEADER_CELL)
|
||||
.allTextContents();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of visible data rows
|
||||
*/
|
||||
async getRowCount(): Promise<number> {
|
||||
return this.locator.locator(AG_GRID_SELECTORS.BODY_ROW).count();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get cell text at a specific row and column index (0-based)
|
||||
*/
|
||||
async getCellText(row: number, col: number): Promise<string> {
|
||||
const text = await this.locator
|
||||
.locator(AG_GRID_SELECTORS.BODY_ROW)
|
||||
.nth(row)
|
||||
.locator(AG_GRID_SELECTORS.CELL)
|
||||
.nth(col)
|
||||
.textContent();
|
||||
return text?.trim() ?? '';
|
||||
}
|
||||
}
|
||||
46
superset-frontend/playwright/components/core/EditableTabs.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
import { Tabs } from './Tabs';
|
||||
|
||||
/**
|
||||
* EditableTabs component for Ant Design editable-card tabs.
|
||||
*
|
||||
* Mirrors the Superset EditableTabs component (type="editable-card")
|
||||
* which adds add/remove tab functionality to the base Tabs component.
|
||||
*
|
||||
* The add button (.ant-tabs-nav-add) is only rendered when
|
||||
* type="editable-card". If the host component switches to type="card"
|
||||
* (e.g., SQL Lab empty state), use the host page object for that case.
|
||||
*/
|
||||
export class EditableTabs extends Tabs {
|
||||
/**
|
||||
* Clicks the add-tab button rendered by antd in editable-card mode.
|
||||
*/
|
||||
async addTab(): Promise<void> {
|
||||
await this.element.getByRole('button', { name: 'Add tab' }).click();
|
||||
}
|
||||
|
||||
/**
|
||||
* Clicks the remove button on the last tab.
|
||||
*/
|
||||
async removeLastTab(): Promise<void> {
|
||||
await this.nav.locator('.ant-tabs-tab-remove').last().click();
|
||||
}
|
||||
}
|
||||
@@ -68,7 +68,7 @@ export class Modal {
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a footer button by text content (private helper)
|
||||
* Gets a footer button by text content
|
||||
* @param buttonText - The text content of the button
|
||||
*/
|
||||
private getFooterButton(buttonText: string): Locator {
|
||||
@@ -80,7 +80,7 @@ export class Modal {
|
||||
* @param buttonText - The text content of the button to click
|
||||
* @param options - Optional click options
|
||||
*/
|
||||
protected async clickFooterButton(
|
||||
async clickFooterButton(
|
||||
buttonText: string,
|
||||
options?: { timeout?: number; force?: boolean; delay?: number },
|
||||
): Promise<void> {
|
||||
|
||||
53
superset-frontend/playwright/components/core/Popover.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
/**
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
import { Locator, Page } from '@playwright/test';
|
||||
import { Button } from './Button';
|
||||
|
||||
/**
|
||||
* Ant Design Popover component.
|
||||
*/
|
||||
export class Popover {
|
||||
readonly page: Page;
|
||||
private readonly locator: Locator;
|
||||
|
||||
constructor(page: Page, locator?: Locator) {
|
||||
this.page = page;
|
||||
this.locator = locator ?? page.locator('.ant-popover-content');
|
||||
}
|
||||
|
||||
get element(): Locator {
|
||||
return this.locator;
|
||||
}
|
||||
|
||||
async waitForVisible(options?: { timeout?: number }): Promise<void> {
|
||||
await this.locator.waitFor({ state: 'visible', ...options });
|
||||
}
|
||||
|
||||
async waitForHidden(options?: { timeout?: number }): Promise<void> {
|
||||
await this.locator.waitFor({ state: 'hidden', ...options });
|
||||
}
|
||||
|
||||
getButton(name: string): Button {
|
||||
return new Button(
|
||||
this.page,
|
||||
this.locator.getByRole('button', { name, exact: true }),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@
|
||||
*/
|
||||
|
||||
import { Locator, Page } from '@playwright/test';
|
||||
import { TIMEOUT } from '../../utils/constants';
|
||||
|
||||
/**
|
||||
* Ant Design Select component selectors
|
||||
@@ -87,7 +88,7 @@ export class Select {
|
||||
await this.page
|
||||
.locator(`${SELECT_SELECTORS.DROPDOWN}:not(.ant-select-dropdown-hidden)`)
|
||||
.last()
|
||||
.waitFor({ state: 'hidden', timeout: 5000 })
|
||||
.waitFor({ state: 'hidden', timeout: TIMEOUT.UI_TRANSITION })
|
||||
.catch(error => {
|
||||
// Only ignore TimeoutError (dropdown may already be closed); re-throw others
|
||||
if (!(error instanceof Error) || error.name !== 'TimeoutError') {
|
||||
|
||||
@@ -21,6 +21,10 @@ import { Locator, Page } from '@playwright/test';
|
||||
|
||||
/**
|
||||
* Tabs component for Ant Design tab navigation.
|
||||
*
|
||||
* Expects the locator to point to the `.ant-tabs` wrapper element
|
||||
* (not the inner tablist) so that `nav` can scope to the outer tab bar
|
||||
* and exclude nested/inner tabs (e.g. Results / Query history in SQL Lab).
|
||||
*/
|
||||
export class Tabs {
|
||||
readonly page: Page;
|
||||
@@ -28,23 +32,54 @@ export class Tabs {
|
||||
|
||||
constructor(page: Page, locator?: Locator) {
|
||||
this.page = page;
|
||||
// Default to the tablist role if no specific locator provided
|
||||
this.locator = locator ?? page.getByRole('tablist');
|
||||
this.locator = locator ?? page.locator('.ant-tabs').first();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the tablist element locator
|
||||
* The root element locator for this tabs component.
|
||||
*/
|
||||
get element(): Locator {
|
||||
return this.locator;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a tab by name, scoped to this tablist's container
|
||||
* The tab navigation bar for this component.
|
||||
* Scoped to the first `.ant-tabs-nav` descendant so that queries
|
||||
* only hit this component's tabs, never nested/inner tab bars.
|
||||
*/
|
||||
protected get nav(): Locator {
|
||||
return this.locator.locator('.ant-tabs-nav').first();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of tabs.
|
||||
* Counts `.ant-tabs-tab` wrappers in the nav bar — one per physical tab,
|
||||
* regardless of inner role="tab" elements (btn, remove button, etc.).
|
||||
*/
|
||||
async getTabCount(): Promise<number> {
|
||||
return this.nav.locator('.ant-tabs-tab').count();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the text content of all tabs.
|
||||
*/
|
||||
async getTabNames(): Promise<string[]> {
|
||||
return this.nav.locator('.ant-tabs-tab-btn').allTextContents();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a tab button by name, scoped to this component's nav bar.
|
||||
* Anchored at start (^) with negative lookahead (?!\d) to prevent
|
||||
* partial matches: "Query" won't match "Query 1", and "Query 1"
|
||||
* won't match "Query 10". Trailing icon text (e.g. " circle-solid")
|
||||
* is allowed since (?!\d) permits non-digit suffixes.
|
||||
* @param tabName - The name/label of the tab
|
||||
*/
|
||||
getTab(tabName: string): Locator {
|
||||
return this.locator.getByRole('tab', { name: tabName });
|
||||
const escaped = tabName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
return this.nav
|
||||
.locator('.ant-tabs-tab-btn')
|
||||
.filter({ hasText: new RegExp(`^${escaped}(?!\\d)`) });
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -63,6 +98,16 @@ export class Tabs {
|
||||
return this.page.getByRole('tabpanel', { name: tabName });
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the name of the currently active tab.
|
||||
*/
|
||||
async getActiveTabName(): Promise<string> {
|
||||
const text = await this.nav
|
||||
.locator('.ant-tabs-tab-active .ant-tabs-tab-btn')
|
||||
.textContent();
|
||||
return text?.trim() ?? '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a tab is selected
|
||||
* @param tabName - The name/label of the tab
|
||||
|
||||
@@ -19,12 +19,15 @@
|
||||
|
||||
// Core Playwright Components for Superset
|
||||
export { AceEditor } from './AceEditor';
|
||||
export { AgGrid } from './AgGrid';
|
||||
export { Button } from './Button';
|
||||
export { Checkbox } from './Checkbox';
|
||||
export { EditableTabs } from './EditableTabs';
|
||||
export { Form } from './Form';
|
||||
export { Input } from './Input';
|
||||
export { Menu } from './Menu';
|
||||
export { Modal } from './Modal';
|
||||
export { Popover } from './Popover';
|
||||
export { Select } from './Select';
|
||||
export { Table } from './Table';
|
||||
export { Tabs } from './Tabs';
|
||||
|
||||
@@ -40,8 +40,11 @@ export class EditDatasetModal extends Modal {
|
||||
// Use getByRole with specific name to target Edit Dataset dialog
|
||||
// The dialog has aria-labelledby that resolves to "edit Edit Dataset"
|
||||
this.specificLocator = page.getByRole('dialog', { name: /edit.*dataset/i });
|
||||
// Scope tabs to modal's tablist to avoid matching tablists elsewhere on page
|
||||
this.tabs = new Tabs(page, this.specificLocator.getByRole('tablist'));
|
||||
// Scope tabs to modal dialog so nav getter finds .ant-tabs-nav as descendant
|
||||
this.tabs = new Tabs(
|
||||
page,
|
||||
this.specificLocator.locator('.ant-tabs').first(),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -16,41 +16,28 @@
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
import getPointsFromPolygon from '../../src/utils/getPointsFromPolygon';
|
||||
|
||||
describe('getPointsFromPolygon', () => {
|
||||
test('handle original input', () => {
|
||||
expect(
|
||||
getPointsFromPolygon({
|
||||
polygon: [
|
||||
[1, 2],
|
||||
[3, 4],
|
||||
],
|
||||
}),
|
||||
).toEqual([
|
||||
[1, 2],
|
||||
[3, 4],
|
||||
]);
|
||||
});
|
||||
test('handle geojson features', () => {
|
||||
expect(
|
||||
getPointsFromPolygon({
|
||||
polygon: {
|
||||
type: 'Feature',
|
||||
geometry: {
|
||||
type: 'Polygon',
|
||||
coordinates: [
|
||||
[
|
||||
[1, 2],
|
||||
[3, 4],
|
||||
],
|
||||
],
|
||||
},
|
||||
},
|
||||
}),
|
||||
).toEqual([
|
||||
[1, 2],
|
||||
[3, 4],
|
||||
]);
|
||||
});
|
||||
});
|
||||
import { Page } from '@playwright/test';
|
||||
import { Input, Modal } from '../core';
|
||||
|
||||
/**
|
||||
* Save Dataset modal in SQL Lab.
|
||||
* Appears when clicking "Save dataset" after running a query.
|
||||
*/
|
||||
export class SaveDatasetModal extends Modal {
|
||||
constructor(page: Page) {
|
||||
super(page, '[data-test="Save or Overwrite Dataset-modal"] .ant-modal');
|
||||
}
|
||||
|
||||
private get nameInput(): Input {
|
||||
return new Input(
|
||||
this.page,
|
||||
this.body.locator('input[placeholder="Dataset name"]'),
|
||||
);
|
||||
}
|
||||
|
||||
async fillName(name: string): Promise<void> {
|
||||
await this.nameInput.clear();
|
||||
await this.nameInput.fill(name);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
import { Page } from '@playwright/test';
|
||||
import { Input, Modal } from '../core';
|
||||
|
||||
/**
|
||||
* Save Query modal in SQL Lab.
|
||||
* Appears when clicking the Save button in the SQL editor toolbar.
|
||||
*/
|
||||
export class SaveQueryModal extends Modal {
|
||||
constructor(page: Page) {
|
||||
super(page, '.save-query-modal');
|
||||
}
|
||||
|
||||
private get nameInput(): Input {
|
||||
return new Input(
|
||||
this.page,
|
||||
this.body.locator('input[type="text"]').first(),
|
||||
);
|
||||
}
|
||||
|
||||
async fillName(name: string): Promise<void> {
|
||||
await this.nameInput.clear();
|
||||
await this.nameInput.fill(name);
|
||||
}
|
||||
}
|
||||
@@ -24,3 +24,5 @@ export { DeleteConfirmationModal } from './DeleteConfirmationModal';
|
||||
export { DuplicateDatasetModal } from './DuplicateDatasetModal';
|
||||
export { EditDatasetModal } from './EditDatasetModal';
|
||||
export { ImportDatasetModal } from './ImportDatasetModal';
|
||||
export { SaveDatasetModal } from './SaveDatasetModal';
|
||||
export { SaveQueryModal } from './SaveQueryModal';
|
||||
|
||||
96
superset-frontend/playwright/embedded-app/index.html
Normal file
@@ -0,0 +1,96 @@
|
||||
<!--
|
||||
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.
|
||||
-->
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Embedded Dashboard Test App</title>
|
||||
<style>
|
||||
html, body { margin: 0; padding: 0; height: 100%; }
|
||||
#superset-container { width: 100%; height: 100vh; }
|
||||
#superset-container iframe { width: 100%; height: 100%; border: none; }
|
||||
#error { color: red; padding: 20px; display: none; }
|
||||
#status { padding: 10px; font-family: monospace; font-size: 12px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="status">Initializing embedded dashboard...</div>
|
||||
<div id="error"></div>
|
||||
<div id="superset-container" data-test="embedded-container"></div>
|
||||
|
||||
<script src="/sdk/index.js"></script>
|
||||
<script>
|
||||
(async function () {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const uuid = params.get('uuid');
|
||||
const supersetDomain = params.get('supersetDomain');
|
||||
|
||||
if (!uuid || !supersetDomain) {
|
||||
document.getElementById('error').style.display = 'block';
|
||||
document.getElementById('error').textContent =
|
||||
'Missing required query params: uuid, supersetDomain';
|
||||
return;
|
||||
}
|
||||
|
||||
const statusEl = document.getElementById('status');
|
||||
|
||||
// fetchGuestToken is injected by Playwright via page.exposeFunction()
|
||||
// Falls back to window.__guestToken for simple/static token injection
|
||||
async function fetchGuestToken() {
|
||||
if (typeof window.__fetchGuestToken === 'function') {
|
||||
statusEl.textContent = 'Fetching guest token...';
|
||||
const token = await window.__fetchGuestToken();
|
||||
statusEl.textContent = 'Guest token received, loading dashboard...';
|
||||
return token;
|
||||
}
|
||||
if (window.__guestToken) {
|
||||
return window.__guestToken;
|
||||
}
|
||||
throw new Error('No guest token source available');
|
||||
}
|
||||
|
||||
try {
|
||||
// Parse optional UI config from query params
|
||||
const uiConfig = {};
|
||||
if (params.get('hideTitle') === 'true') uiConfig.hideTitle = true;
|
||||
if (params.get('hideTab') === 'true') uiConfig.hideTab = true;
|
||||
if (params.get('hideChartControls') === 'true') uiConfig.hideChartControls = true;
|
||||
|
||||
const dashboard = await supersetEmbeddedSdk.embedDashboard({
|
||||
id: uuid,
|
||||
supersetDomain: supersetDomain,
|
||||
mountPoint: document.getElementById('superset-container'),
|
||||
fetchGuestToken: fetchGuestToken,
|
||||
dashboardUiConfig: Object.keys(uiConfig).length > 0 ? uiConfig : undefined,
|
||||
debug: params.get('debug') === 'true',
|
||||
});
|
||||
|
||||
statusEl.textContent = 'Dashboard embedded successfully';
|
||||
// Expose dashboard API on window for Playwright assertions
|
||||
window.__embeddedDashboard = dashboard;
|
||||
} catch (err) {
|
||||
document.getElementById('error').style.display = 'block';
|
||||
document.getElementById('error').textContent = 'Embed failed: ' + err.message;
|
||||
statusEl.textContent = 'Error';
|
||||
}
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -61,6 +61,22 @@ export function expectStatusOneOf<T extends ResponseLike>(
|
||||
return response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract the resource ID from a JSON response body.
|
||||
* Handles both `{ result: { id } }` and `{ id }` shapes.
|
||||
* @param response - Playwright Response or APIResponse object
|
||||
* @returns The extracted numeric ID
|
||||
*/
|
||||
export async function extractIdFromResponse(
|
||||
response: ResponseLike,
|
||||
): Promise<number> {
|
||||
const body = await response.json();
|
||||
const id: number = body.result?.id ?? body.id;
|
||||
expect(typeof id, 'Response body must contain a numeric id').toBe('number');
|
||||
expect(Number.isNaN(id), 'Response id must not be NaN').toBe(false);
|
||||
return id;
|
||||
}
|
||||
|
||||
interface ExportZipOptions {
|
||||
/** Directory name containing resource yaml files (e.g. 'charts', 'datasets') */
|
||||
resourceDir: string;
|
||||
|
||||
@@ -132,26 +132,14 @@ export interface DashboardResult {
|
||||
published?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a dashboard by its title
|
||||
* @param page - Playwright page instance (provides authentication context)
|
||||
* @param title - The dashboard_title to search for
|
||||
* @returns Dashboard object if found, null if not found
|
||||
*/
|
||||
export async function getDashboardByName(
|
||||
async function getDashboardByFilter(
|
||||
page: Page,
|
||||
title: string,
|
||||
col: 'dashboard_title' | 'slug',
|
||||
value: string,
|
||||
): Promise<DashboardResult | null> {
|
||||
const filter = {
|
||||
filters: [
|
||||
{
|
||||
col: 'dashboard_title',
|
||||
opr: 'eq',
|
||||
value: title,
|
||||
},
|
||||
],
|
||||
};
|
||||
const queryParam = rison.encode(filter);
|
||||
const queryParam = rison.encode({
|
||||
filters: [{ col, opr: 'eq', value }],
|
||||
});
|
||||
const response = await apiGet(
|
||||
page,
|
||||
`${ENDPOINTS.DASHBOARD}?q=${queryParam}`,
|
||||
@@ -169,3 +157,29 @@ export async function getDashboardByName(
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a dashboard by its title
|
||||
* @param page - Playwright page instance (provides authentication context)
|
||||
* @param title - The dashboard_title to search for
|
||||
* @returns Dashboard object if found, null if not found
|
||||
*/
|
||||
export async function getDashboardByName(
|
||||
page: Page,
|
||||
title: string,
|
||||
): Promise<DashboardResult | null> {
|
||||
return getDashboardByFilter(page, 'dashboard_title', title);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a dashboard by its slug
|
||||
* @param page - Playwright page instance (provides authentication context)
|
||||
* @param slug - The slug to search for
|
||||
* @returns Dashboard object if found, null if not found
|
||||
*/
|
||||
export async function getDashboardBySlug(
|
||||
page: Page,
|
||||
slug: string,
|
||||
): Promise<DashboardResult | null> {
|
||||
return getDashboardByFilter(page, 'slug', slug);
|
||||
}
|
||||
|
||||
113
superset-frontend/playwright/helpers/api/embedded.ts
Normal file
@@ -0,0 +1,113 @@
|
||||
/**
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
import { Page } from '@playwright/test';
|
||||
import { apiPost, apiPut } from './requests';
|
||||
import { ENDPOINTS as DASHBOARD_ENDPOINTS } from './dashboard';
|
||||
|
||||
export const ENDPOINTS = {
|
||||
SECURITY_LOGIN: 'api/v1/security/login',
|
||||
GUEST_TOKEN: 'api/v1/security/guest_token/',
|
||||
} as const;
|
||||
|
||||
export interface EmbeddedConfig {
|
||||
uuid: string;
|
||||
allowed_domains: string[];
|
||||
dashboard_id: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enable embedding on a dashboard and return the embedded UUID.
|
||||
* Uses PUT (upsert) to preserve UUID across repeated calls.
|
||||
* @param page - Playwright page instance (provides authentication context)
|
||||
* @param dashboardIdOrSlug - Numeric dashboard id or slug
|
||||
* @param allowedDomains - Domains allowed to embed; empty array allows all
|
||||
* @returns Embedded config with UUID, allowed_domains, and dashboard_id
|
||||
*/
|
||||
export async function apiEnableEmbedding(
|
||||
page: Page,
|
||||
dashboardIdOrSlug: number | string,
|
||||
allowedDomains: string[] = [],
|
||||
): Promise<EmbeddedConfig> {
|
||||
const response = await apiPut(
|
||||
page,
|
||||
`${DASHBOARD_ENDPOINTS.DASHBOARD}${dashboardIdOrSlug}/embedded`,
|
||||
{ allowed_domains: allowedDomains },
|
||||
);
|
||||
const body = await response.json();
|
||||
return body.result as EmbeddedConfig;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a guest token for an embedded dashboard.
|
||||
* Uses the admin login flow (login → access_token → guest_token).
|
||||
* @param page - Playwright page instance (used for request context)
|
||||
* @param dashboardId - Dashboard id to grant access to
|
||||
* @param options - Optional login credentials and RLS rules
|
||||
* @returns Signed guest token string
|
||||
*/
|
||||
export async function getGuestToken(
|
||||
page: Page,
|
||||
dashboardId: number | string,
|
||||
options?: {
|
||||
username?: string;
|
||||
password?: string;
|
||||
rls?: Array<{ dataset: number; clause: string }>;
|
||||
},
|
||||
): Promise<string> {
|
||||
const username = options?.username ?? 'admin';
|
||||
const password = options?.password ?? 'general';
|
||||
const rls = options?.rls ?? [];
|
||||
|
||||
// Step 1: Login to get access token
|
||||
const loginResponse = await apiPost(
|
||||
page,
|
||||
ENDPOINTS.SECURITY_LOGIN,
|
||||
{
|
||||
username,
|
||||
password,
|
||||
provider: 'db',
|
||||
refresh: true,
|
||||
},
|
||||
{ allowMissingCsrf: true },
|
||||
);
|
||||
const loginBody = await loginResponse.json();
|
||||
const accessToken = loginBody.access_token;
|
||||
|
||||
// Step 2: Fetch guest token using the access token.
|
||||
// Uses raw page.request.post() (not apiPost) because the guest token endpoint
|
||||
// requires a JWT Bearer token rather than session+CSRF auth.
|
||||
const guestResponse = await page.request.post(ENDPOINTS.GUEST_TOKEN, {
|
||||
data: {
|
||||
user: {
|
||||
username: 'embedded_test_user',
|
||||
first_name: 'Embedded',
|
||||
last_name: 'TestUser',
|
||||
},
|
||||
resources: [{ type: 'dashboard', id: String(dashboardId) }],
|
||||
rls,
|
||||
},
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
},
|
||||
});
|
||||
const guestBody = await guestResponse.json();
|
||||
return guestBody.token;
|
||||
}
|
||||
47
superset-frontend/playwright/helpers/api/savedQuery.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
import { Page, APIResponse } from '@playwright/test';
|
||||
import { apiGet, apiDelete, ApiRequestOptions } from './requests';
|
||||
|
||||
const ENDPOINTS = {
|
||||
SAVED_QUERY: 'api/v1/saved_query/',
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* GET request to fetch a saved query's details
|
||||
*/
|
||||
export async function apiGetSavedQuery(
|
||||
page: Page,
|
||||
savedQueryId: number,
|
||||
options?: ApiRequestOptions,
|
||||
): Promise<APIResponse> {
|
||||
return apiGet(page, `${ENDPOINTS.SAVED_QUERY}${savedQueryId}`, options);
|
||||
}
|
||||
|
||||
/**
|
||||
* DELETE request to remove a saved query
|
||||
*/
|
||||
export async function apiDeleteSavedQuery(
|
||||
page: Page,
|
||||
savedQueryId: number,
|
||||
options?: ApiRequestOptions,
|
||||
): Promise<APIResponse> {
|
||||
return apiDelete(page, `${ENDPOINTS.SAVED_QUERY}${savedQueryId}`, options);
|
||||
}
|
||||
@@ -23,6 +23,7 @@ import { apiDeleteDashboard } from '../api/dashboard';
|
||||
import { apiDeleteDataset } from '../api/dataset';
|
||||
import { apiDeleteTheme } from '../api/theme';
|
||||
import { apiDeleteDatabase } from '../api/database';
|
||||
import { apiDeleteSavedQuery } from '../api/savedQuery';
|
||||
|
||||
/**
|
||||
* Test asset tracker for automatic cleanup after each test.
|
||||
@@ -34,6 +35,7 @@ export interface TestAssets {
|
||||
trackDataset(id: number): void;
|
||||
trackTheme(id: number): void;
|
||||
trackDatabase(id: number): void;
|
||||
trackSavedQuery(id: number): void;
|
||||
}
|
||||
|
||||
const EXPECTED_CLEANUP_STATUSES = new Set([200, 202, 204, 404]);
|
||||
@@ -46,6 +48,7 @@ export const test = base.extend<{ testAssets: TestAssets }>({
|
||||
const datasetIds = new Set<number>();
|
||||
const themeIds = new Set<number>();
|
||||
const databaseIds = new Set<number>();
|
||||
const savedQueryIds = new Set<number>();
|
||||
|
||||
await use({
|
||||
trackDashboard: id => dashboardIds.add(id),
|
||||
@@ -53,9 +56,29 @@ export const test = base.extend<{ testAssets: TestAssets }>({
|
||||
trackDataset: id => datasetIds.add(id),
|
||||
trackTheme: id => themeIds.add(id),
|
||||
trackDatabase: id => databaseIds.add(id),
|
||||
trackSavedQuery: id => savedQueryIds.add(id),
|
||||
});
|
||||
|
||||
// Cleanup order: dashboards → charts → datasets → themes → databases (respects FK dependencies)
|
||||
// Cleanup order: saved queries → dashboards → charts → datasets → themes → databases (respects FK dependencies)
|
||||
// Saved queries have no FK dependents, so they can be cleaned up first
|
||||
await Promise.all(
|
||||
[...savedQueryIds].map(id =>
|
||||
apiDeleteSavedQuery(page, id, { failOnStatusCode: false })
|
||||
.then(response => {
|
||||
if (!EXPECTED_CLEANUP_STATUSES.has(response.status())) {
|
||||
console.warn(
|
||||
`[testAssets] Unexpected status ${response.status()} cleaning up saved query ${id}`,
|
||||
);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.warn(
|
||||
`[testAssets] Failed to cleanup saved query ${id}:`,
|
||||
error,
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
// Use failOnStatusCode: false to avoid throwing on 404 (resource already deleted by test)
|
||||
// Warn on unexpected status codes (401/403/500) that may indicate leaked state
|
||||
await Promise.all(
|
||||
|
||||
@@ -50,7 +50,9 @@ export class AuthPage {
|
||||
* Navigate to the login page
|
||||
*/
|
||||
async goto(): Promise<void> {
|
||||
await this.page.goto(URL.LOGIN);
|
||||
// Use domcontentloaded — the login form is server-rendered and ready before
|
||||
// all assets load. The default 'load' event may never fire with HMR WebSocket.
|
||||
await this.page.goto(URL.LOGIN, { waitUntil: 'domcontentloaded' });
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
140
superset-frontend/playwright/pages/EmbeddedPage.ts
Normal file
@@ -0,0 +1,140 @@
|
||||
/**
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
import { Page, FrameLocator } from '@playwright/test';
|
||||
import { EMBEDDED } from '../utils/constants';
|
||||
|
||||
/**
|
||||
* Page object for the embedded dashboard test app.
|
||||
*
|
||||
* The test app runs on a separate origin (localhost:9000) and uses the
|
||||
* @superset-ui/embedded-sdk to render a Superset dashboard in an iframe.
|
||||
* Playwright's page.exposeFunction() bridges the guest token from Node.js
|
||||
* into the browser page.
|
||||
*/
|
||||
export class EmbeddedPage {
|
||||
private readonly page: Page;
|
||||
|
||||
private static readonly SELECTORS = {
|
||||
CONTAINER: '[data-test="embedded-container"]',
|
||||
IFRAME: 'iframe[title="Embedded Dashboard"]',
|
||||
STATUS: '#status',
|
||||
ERROR: '#error',
|
||||
} as const;
|
||||
|
||||
constructor(page: Page) {
|
||||
this.page = page;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set up the guest token bridge before navigating.
|
||||
* Must be called BEFORE goto() since embedDashboard() calls fetchGuestToken
|
||||
* immediately on page load.
|
||||
*/
|
||||
async exposeTokenFetcher(tokenFn: () => Promise<string>): Promise<void> {
|
||||
await this.page.exposeFunction('__fetchGuestToken', tokenFn);
|
||||
}
|
||||
|
||||
/**
|
||||
* Navigate to the embedded test app with the given parameters.
|
||||
*/
|
||||
async goto(params: {
|
||||
uuid: string;
|
||||
supersetDomain: string;
|
||||
hideTitle?: boolean;
|
||||
hideTab?: boolean;
|
||||
hideChartControls?: boolean;
|
||||
debug?: boolean;
|
||||
}): Promise<void> {
|
||||
const searchParams = new URLSearchParams({
|
||||
uuid: params.uuid,
|
||||
supersetDomain: params.supersetDomain,
|
||||
});
|
||||
if (params.hideTitle) searchParams.set('hideTitle', 'true');
|
||||
if (params.hideTab) searchParams.set('hideTab', 'true');
|
||||
if (params.hideChartControls) searchParams.set('hideChartControls', 'true');
|
||||
if (params.debug) searchParams.set('debug', 'true');
|
||||
|
||||
await this.page.goto(`${EMBEDDED.APP_URL}/?${searchParams.toString()}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* FrameLocator for the embedded dashboard iframe.
|
||||
*/
|
||||
get iframe(): FrameLocator {
|
||||
return this.page.frameLocator(EmbeddedPage.SELECTORS.IFRAME);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait for the iframe to appear in the DOM.
|
||||
*/
|
||||
async waitForIframe(options?: { timeout?: number }): Promise<void> {
|
||||
await this.page.locator(EmbeddedPage.SELECTORS.IFRAME).waitFor({
|
||||
state: 'attached',
|
||||
timeout: options?.timeout ?? EMBEDDED.IFRAME_LOAD,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait for dashboard content to render inside the iframe.
|
||||
* Looks for the grid-container which indicates charts are loading/loaded.
|
||||
*/
|
||||
async waitForDashboardContent(options?: { timeout?: number }): Promise<void> {
|
||||
const frame = this.iframe;
|
||||
await frame
|
||||
.locator('.grid-container, [data-test="grid-container"]')
|
||||
.first()
|
||||
.waitFor({
|
||||
state: 'visible',
|
||||
timeout: options?.timeout ?? EMBEDDED.DASHBOARD_RENDER,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the status text from the test app.
|
||||
*/
|
||||
async getStatus(): Promise<string> {
|
||||
return (
|
||||
(await this.page.locator(EmbeddedPage.SELECTORS.STATUS).textContent()) ??
|
||||
''
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the error text, if any.
|
||||
*/
|
||||
async getError(): Promise<string> {
|
||||
const errorEl = this.page.locator(EmbeddedPage.SELECTORS.ERROR);
|
||||
const display = await errorEl.evaluate(el => getComputedStyle(el).display);
|
||||
if (display === 'none') return '';
|
||||
return (await errorEl.textContent()) ?? '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the dashboard title is visible inside the iframe.
|
||||
*/
|
||||
async isTitleVisible(): Promise<boolean> {
|
||||
const frame = this.iframe;
|
||||
return frame
|
||||
.locator(
|
||||
'[data-test="dashboard-header-container"] [data-test="editable-title-input"]',
|
||||
)
|
||||
.isVisible();
|
||||
}
|
||||
}
|
||||
371
superset-frontend/playwright/pages/SqlLabPage.ts
Normal file
@@ -0,0 +1,371 @@
|
||||
/**
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
import { Page, Locator, Response } from '@playwright/test';
|
||||
import { AceEditor } from '../components/core/AceEditor';
|
||||
import { AgGrid } from '../components/core/AgGrid';
|
||||
import { Button } from '../components/core/Button';
|
||||
import { EditableTabs } from '../components/core/EditableTabs';
|
||||
import { Popover } from '../components/core/Popover';
|
||||
import { Select } from '../components/core/Select';
|
||||
import { waitForPost } from '../helpers/api/intercepts';
|
||||
import { URL } from '../utils/urls';
|
||||
import { TIMEOUT } from '../utils/constants';
|
||||
|
||||
/**
|
||||
* Page object for SQL Lab.
|
||||
*
|
||||
* Selectors verified against source code — see plan for line references.
|
||||
*/
|
||||
export class SqlLabPage {
|
||||
private readonly page: Page;
|
||||
private readonly editorTabs: EditableTabs;
|
||||
|
||||
private static readonly SELECTORS = {
|
||||
SQL_EDITOR_TABS: '[data-test="sql-editor-tabs"]',
|
||||
ADD_TAB_ICON: '[data-test="add-tab-icon"]',
|
||||
RUN_QUERY_BUTTON: '[data-test="run-query-action"]',
|
||||
SOUTH_PANE: '[data-test="south-pane"]',
|
||||
EXPLORE_RESULTS_BUTTON: '[data-test="explore-results-button"]',
|
||||
SAVE_BUTTON: 'button[aria-label="Save"]',
|
||||
ACE_EDITOR: '.ace_editor',
|
||||
LEFT_BAR: '[data-test="sql-editor-left-bar"]',
|
||||
DATABASE_SELECTOR: '[data-test="DatabaseSelector"]',
|
||||
LIMIT_DROPDOWN: '.limitDropdown',
|
||||
SAVE_DATASET_BUTTON: 'button[aria-label="Save dataset"]',
|
||||
} as const;
|
||||
|
||||
constructor(page: Page) {
|
||||
this.page = page;
|
||||
this.editorTabs = new EditableTabs(
|
||||
page,
|
||||
page.locator(SqlLabPage.SELECTORS.SQL_EDITOR_TABS),
|
||||
);
|
||||
}
|
||||
|
||||
// ── Navigation ──
|
||||
|
||||
async goto(): Promise<void> {
|
||||
await this.page.goto(URL.SQLLAB, { waitUntil: 'domcontentloaded' });
|
||||
}
|
||||
|
||||
async waitForPageLoad(options?: { timeout?: number }): Promise<void> {
|
||||
// SQL Lab with dev server can be slow on first load (webpack HMR + React hydration)
|
||||
const timeout = options?.timeout ?? TIMEOUT.QUERY_EXECUTION;
|
||||
await this.editorTabs.element.waitFor({ state: 'visible', timeout });
|
||||
}
|
||||
|
||||
/**
|
||||
* Navigate to SQL Lab and wait until the editor is ready.
|
||||
* Convenience method combining goto + waitForPageLoad + ensureEditorReady.
|
||||
*/
|
||||
async gotoAndReady(): Promise<void> {
|
||||
await this.goto();
|
||||
await this.waitForPageLoad();
|
||||
await this.ensureEditorReady();
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures at least one query editor tab exists. Creates one if SQL Lab
|
||||
* is in the empty state ("Add a new tab to create SQL Query").
|
||||
* Waits for the ace editor to be ready before returning.
|
||||
*
|
||||
* Uses a two-stage check to handle three states correctly:
|
||||
* 1. Empty state (CI): type="card" with 0 queryEditors, no editor → create tab
|
||||
* 2. Loading after reload: real tabs exist, editor hasn't mounted yet → just wait
|
||||
* 3. Normal: tabs + editor present → ready immediately
|
||||
*
|
||||
* Stage 1 checks editor presence (catches empty + loading).
|
||||
* Stage 2 checks the Ant Design tabs type to distinguish real tabs
|
||||
* (type="editable-card") from the empty state (type="card"). The React
|
||||
* source (TabbedSqlEditors) sets type based on queryEditors.length,
|
||||
* so this directly reflects whether persisted tabs exist.
|
||||
*/
|
||||
async ensureEditorReady(): Promise<void> {
|
||||
// Page-global check: are there ANY editors in the DOM (any tab)?
|
||||
const anyEditor = this.page.locator(SqlLabPage.SELECTORS.ACE_EDITOR);
|
||||
let tabSyncPromise: Promise<Response> | null = null;
|
||||
|
||||
if ((await anyEditor.count()) === 0) {
|
||||
// No editor visible. Check if real query editors exist (editable-card)
|
||||
// or if this is the empty state (card type, 0 queryEditors).
|
||||
// type="editable-card" → queryEditors.length > 0 (even 1 real tab).
|
||||
// type="card" → queryEditors.length === 0 (true empty state).
|
||||
const isEditableCard = await this.editorTabs.element.evaluate(el =>
|
||||
el.classList.contains('ant-tabs-editable-card'),
|
||||
);
|
||||
if (!isEditableCard) {
|
||||
// Register before clicking — EditorAutoSync POSTs the new tab
|
||||
// within its 5 s interval, so capture it before any await.
|
||||
tabSyncPromise = waitForPost(this.page, /tabstateview\/?$/, {
|
||||
timeout: 10_000,
|
||||
});
|
||||
// True empty state — click add-tab icon (works in card mode)
|
||||
await this.editorTabs.element
|
||||
.locator(SqlLabPage.SELECTORS.ADD_TAB_ICON)
|
||||
.first()
|
||||
.click();
|
||||
}
|
||||
// If editable-card: real tabs exist, editor is still mounting — just wait
|
||||
}
|
||||
|
||||
// Wait for the editor in the ACTIVE panel, not page-global .first().
|
||||
// In persisted multi-tab sessions, .first() can resolve to a hidden
|
||||
// inactive editor. activePanel scopes to the visible tab panel.
|
||||
await this.activePanel
|
||||
.locator(SqlLabPage.SELECTORS.ACE_EDITOR)
|
||||
.waitFor({ state: 'visible' });
|
||||
await this.editor.waitForReady();
|
||||
|
||||
// If we created the initial tab, wait for its backend sync to complete.
|
||||
// This prevents later waitForPost calls from accidentally matching
|
||||
// this tab's creation POST instead of a subsequent tab's.
|
||||
if (tabSyncPromise) {
|
||||
await tabSyncPromise;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Active Tab Panel ──
|
||||
|
||||
/**
|
||||
* Gets the active tab panel. Ant Design keeps inactive tab panels mounted
|
||||
* but sets aria-hidden="true" on them. Using :not([aria-hidden="true"])
|
||||
* is more reliable than :visible during tab-switch animations where both
|
||||
* panels may briefly have non-zero dimensions.
|
||||
*/
|
||||
private get activePanel(): Locator {
|
||||
return this.page
|
||||
.locator('[role="tabpanel"]:not([aria-hidden="true"])')
|
||||
.filter({ has: this.page.locator(SqlLabPage.SELECTORS.ACE_EDITOR) });
|
||||
}
|
||||
|
||||
// ── Elements ──
|
||||
|
||||
get editor(): AceEditor {
|
||||
return new AceEditor(
|
||||
this.page,
|
||||
this.activePanel.locator(SqlLabPage.SELECTORS.ACE_EDITOR),
|
||||
);
|
||||
}
|
||||
|
||||
get resultsGrid(): AgGrid {
|
||||
return new AgGrid(
|
||||
this.page,
|
||||
this.activePanel
|
||||
.locator(SqlLabPage.SELECTORS.SOUTH_PANE)
|
||||
.locator('[role="grid"]'),
|
||||
);
|
||||
}
|
||||
|
||||
get resultsPane(): Locator {
|
||||
return this.activePanel.locator(SqlLabPage.SELECTORS.SOUTH_PANE);
|
||||
}
|
||||
|
||||
get errorAlert(): Locator {
|
||||
return this.resultsPane.locator('.ant-alert-error');
|
||||
}
|
||||
|
||||
get databaseSelector(): Button {
|
||||
return new Button(
|
||||
this.page,
|
||||
this.page.locator(
|
||||
`${SqlLabPage.SELECTORS.LEFT_BAR} ${SqlLabPage.SELECTORS.DATABASE_SELECTOR}`,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
get runQueryButton(): Button {
|
||||
return new Button(
|
||||
this.page,
|
||||
this.activePanel.locator(SqlLabPage.SELECTORS.RUN_QUERY_BUTTON),
|
||||
);
|
||||
}
|
||||
|
||||
get saveButton(): Button {
|
||||
return new Button(
|
||||
this.page,
|
||||
this.activePanel.locator(SqlLabPage.SELECTORS.SAVE_BUTTON),
|
||||
);
|
||||
}
|
||||
|
||||
get saveDatasetButton(): Button {
|
||||
return new Button(
|
||||
this.page,
|
||||
this.activePanel.locator(SqlLabPage.SELECTORS.SAVE_DATASET_BUTTON),
|
||||
);
|
||||
}
|
||||
|
||||
get createChartButton(): Button {
|
||||
return new Button(
|
||||
this.page,
|
||||
this.activePanel.locator(SqlLabPage.SELECTORS.EXPLORE_RESULTS_BUTTON),
|
||||
);
|
||||
}
|
||||
|
||||
// ── Editor Convenience ──
|
||||
|
||||
async setQuery(sql: string): Promise<void> {
|
||||
await this.editor.setText(sql);
|
||||
}
|
||||
|
||||
async getQuery(): Promise<string> {
|
||||
return this.editor.getText();
|
||||
}
|
||||
|
||||
// ── Tab Management ──
|
||||
|
||||
async getTabCount(): Promise<number> {
|
||||
return this.editorTabs.getTabCount();
|
||||
}
|
||||
|
||||
async getTabNames(): Promise<string[]> {
|
||||
return this.editorTabs.getTabNames();
|
||||
}
|
||||
|
||||
async getActiveTabName(): Promise<string> {
|
||||
return this.editorTabs.getActiveTabName();
|
||||
}
|
||||
|
||||
async addTab(): Promise<void> {
|
||||
await this.editorTabs.addTab();
|
||||
}
|
||||
|
||||
async addTabByShortcut(): Promise<void> {
|
||||
const modifier = process.platform === 'win32' ? 'Control+q' : 'Control+t';
|
||||
await this.page.keyboard.press(modifier);
|
||||
}
|
||||
|
||||
async closeLastTab(): Promise<void> {
|
||||
const countBefore = await this.getTabCount();
|
||||
await this.editorTabs.removeLastTab();
|
||||
// Wait for tab count to decrease
|
||||
await this.page.waitForFunction(
|
||||
([selector, expected]) => {
|
||||
const container = document.querySelector(selector);
|
||||
if (!container) return false;
|
||||
const nav = container.querySelector(':scope > .ant-tabs-nav');
|
||||
if (!nav) return false;
|
||||
return nav.querySelectorAll('.ant-tabs-tab').length === expected;
|
||||
},
|
||||
[SqlLabPage.SELECTORS.SQL_EDITOR_TABS, countBefore - 1] as const,
|
||||
{ timeout: TIMEOUT.UI_TRANSITION },
|
||||
);
|
||||
}
|
||||
|
||||
getTab(name: string): Locator {
|
||||
return this.editorTabs.getTab(name);
|
||||
}
|
||||
|
||||
// ── Database Selection (Left Sidebar) ──
|
||||
|
||||
async selectDatabase(dbName: string): Promise<void> {
|
||||
await this.databaseSelector.click();
|
||||
|
||||
const popover = new Popover(this.page);
|
||||
await popover.waitForVisible();
|
||||
|
||||
// Target the .ant-select wrapper (not the combobox input) because the
|
||||
// selection-item overlay intercepts pointer events on the input.
|
||||
const dbSelect = popover.element
|
||||
.locator(SqlLabPage.SELECTORS.DATABASE_SELECTOR)
|
||||
.locator('.ant-select')
|
||||
.first();
|
||||
const select = new Select(this.page, dbSelect);
|
||||
await select.selectOption(dbName);
|
||||
|
||||
await popover.getButton('Select').click();
|
||||
await popover
|
||||
.waitForHidden({ timeout: TIMEOUT.UI_TRANSITION })
|
||||
.catch(error => {
|
||||
if (!(error instanceof Error) || error.name !== 'TimeoutError') {
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ── Query Execution ──
|
||||
|
||||
/**
|
||||
* Sets SQL, runs the query, and waits for the API response.
|
||||
* Also observes the QueryStatusBar (.ant-steps) loading indicator to
|
||||
* confirm the UI entered the execution cycle — this unmounts the old
|
||||
* results grid, so waitForQueryResults() can trust that any grid it
|
||||
* finds afterward contains data from THIS execution.
|
||||
*/
|
||||
async executeQuery(sql: string): Promise<Response> {
|
||||
await this.setQuery(sql);
|
||||
const responsePromise = waitForPost(this.page, 'api/v1/sqllab/execute/', {
|
||||
timeout: TIMEOUT.QUERY_EXECUTION,
|
||||
});
|
||||
// Start observing the loading indicator BEFORE clicking Run so we
|
||||
// catch it even for fast queries. QueryStatusBar (.ant-steps) appears
|
||||
// when SQL Lab enters the running state and unmounts the results grid.
|
||||
const loadingStarted = this.resultsPane
|
||||
.locator('.ant-steps')
|
||||
.waitFor({ state: 'visible', timeout: TIMEOUT.QUERY_EXECUTION });
|
||||
await this.runQueryButton.click();
|
||||
const [, response] = await Promise.all([loadingStarted, responsePromise]);
|
||||
return response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait for fresh query results to render in the AG Grid.
|
||||
* Waits for the QueryStatusBar to disappear first, proving the execution
|
||||
* cycle completed and React rendered the post-query grid.
|
||||
* @param expectHeader - A column header that must be visible before returning.
|
||||
* @param options.timeout - How long to wait (default: TIMEOUT.QUERY_EXECUTION)
|
||||
*/
|
||||
async waitForQueryResults(
|
||||
expectHeader: string,
|
||||
options?: { timeout?: number },
|
||||
): Promise<void> {
|
||||
const timeout = options?.timeout ?? TIMEOUT.QUERY_EXECUTION;
|
||||
// Wait for QueryStatusBar to disappear — proves the loading → ready
|
||||
// transition completed. If already hidden (fast query finished before
|
||||
// this call), resolves immediately since executeQuery() already observed
|
||||
// the loading state appear.
|
||||
await this.resultsPane
|
||||
.locator('.ant-steps')
|
||||
.waitFor({ state: 'hidden', timeout });
|
||||
const grid = this.resultsGrid.element;
|
||||
await grid.waitFor({ state: 'visible', timeout });
|
||||
await grid
|
||||
.locator('.ag-header-cell', { hasText: expectHeader })
|
||||
.first()
|
||||
.waitFor({ state: 'visible', timeout });
|
||||
}
|
||||
|
||||
// ── Row Limit ──
|
||||
|
||||
async getRowLimit(): Promise<string> {
|
||||
const text = await this.activePanel
|
||||
.locator(SqlLabPage.SELECTORS.LIMIT_DROPDOWN)
|
||||
.textContent();
|
||||
return text?.trim() ?? '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the row limit via the Limit dropdown in the active panel.
|
||||
* @param limit - The menu item label to select (e.g., "10", "100")
|
||||
*/
|
||||
async setRowLimit(limit: string): Promise<void> {
|
||||
await this.activePanel.locator(SqlLabPage.SELECTORS.LIMIT_DROPDOWN).click();
|
||||
await this.page.getByRole('menuitem', { name: limit, exact: true }).click();
|
||||
}
|
||||
}
|
||||
@@ -44,25 +44,18 @@ test.beforeEach(async ({ page }) => {
|
||||
test('should redirect to login with incorrect username and password', async ({
|
||||
page,
|
||||
}) => {
|
||||
// Setup request interception before login attempt
|
||||
const loginRequestPromise = authPage.waitForLoginRequest();
|
||||
// The form submission is async (SupersetClient.postForm uses ensureAuth)
|
||||
// so listen for the page reload before triggering the login
|
||||
await Promise.all([
|
||||
page.waitForEvent('load', { timeout: TIMEOUT.PAGE_LOAD }),
|
||||
authPage.loginWithCredentials('wronguser', 'wrongpassword'),
|
||||
]);
|
||||
|
||||
// Attempt login with incorrect credentials (both username and password invalid)
|
||||
await authPage.loginWithCredentials('wronguser', 'wrongpassword');
|
||||
|
||||
// Wait for login request and verify response
|
||||
const loginResponse = await loginRequestPromise;
|
||||
// Failed login returns 401 Unauthorized or 302 redirect to login
|
||||
expect([401, 302]).toContain(loginResponse.status());
|
||||
|
||||
// Wait for redirect to complete before checking URL
|
||||
await page.waitForURL(url => url.pathname.endsWith(URL.LOGIN), {
|
||||
timeout: TIMEOUT.PAGE_LOAD,
|
||||
});
|
||||
// After the reload, wait for the React login form to render
|
||||
await authPage.waitForLoginForm();
|
||||
|
||||
// Verify we stay on login page
|
||||
const currentUrl = await authPage.getCurrentUrl();
|
||||
expect(currentUrl).toContain(URL.LOGIN);
|
||||
expect(page.url()).toContain(URL.LOGIN);
|
||||
|
||||
// Verify error message is shown
|
||||
const hasError = await authPage.hasLoginError();
|
||||
@@ -70,16 +63,12 @@ test('should redirect to login with incorrect username and password', async ({
|
||||
});
|
||||
|
||||
test('should login with correct username and password', async ({ page }) => {
|
||||
// Setup request interception before login attempt
|
||||
const loginRequestPromise = authPage.waitForLoginRequest();
|
||||
|
||||
// Login with correct credentials
|
||||
await authPage.loginWithCredentials(adminUsername, adminPassword);
|
||||
|
||||
// Wait for login request and verify response
|
||||
const loginResponse = await loginRequestPromise;
|
||||
// Successful login returns 302 redirect
|
||||
expect(loginResponse.status()).toBe(302);
|
||||
// Use waitForLoginSuccess (proven in global-setup) — guards against race
|
||||
// conditions with cookie check before falling back to response interception
|
||||
await authPage.waitForLoginSuccess({ timeout: TIMEOUT.PAGE_LOAD });
|
||||
|
||||
// Wait for successful redirect to welcome page
|
||||
await page.waitForURL(url => url.pathname.endsWith(URL.WELCOME), {
|
||||
|
||||
@@ -0,0 +1,288 @@
|
||||
/**
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
import { test, expect, Browser, BrowserContext, Page } from '@playwright/test';
|
||||
import { createServer, IncomingMessage, ServerResponse, Server } from 'http';
|
||||
import { readFileSync, existsSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
import { apiEnableEmbedding, getGuestToken } from '../../helpers/api/embedded';
|
||||
import { getDashboardBySlug } from '../../helpers/api/dashboard';
|
||||
import { EmbeddedPage } from '../../pages/EmbeddedPage';
|
||||
import { EMBEDDED } from '../../utils/constants';
|
||||
|
||||
/**
|
||||
* Superset domain (Flask server) — set by CI or defaults to local dev
|
||||
*/
|
||||
const SUPERSET_DOMAIN = (() => {
|
||||
const url = process.env.PLAYWRIGHT_BASE_URL || 'http://localhost:8088';
|
||||
return url.replace(/\/+$/, '');
|
||||
})();
|
||||
|
||||
const SUPERSET_BASE_URL = SUPERSET_DOMAIN.endsWith('/')
|
||||
? SUPERSET_DOMAIN
|
||||
: `${SUPERSET_DOMAIN}/`;
|
||||
|
||||
/**
|
||||
* Path to the SDK bundle built from superset-embedded-sdk/
|
||||
*/
|
||||
const SDK_BUNDLE_PATH = join(
|
||||
__dirname,
|
||||
'../../../../superset-embedded-sdk/bundle/index.js',
|
||||
);
|
||||
|
||||
/**
|
||||
* Path to the embedded test app static files
|
||||
*/
|
||||
const EMBED_APP_DIR = join(__dirname, '../../embedded-app');
|
||||
|
||||
/**
|
||||
* Create a minimal static file server for the embedded test app.
|
||||
* Serves only a fixed allowlist of routes — the test app references just
|
||||
* its index.html and the SDK bundle, so anything else is 404.
|
||||
*/
|
||||
const INDEX_HTML_PATH = join(EMBED_APP_DIR, 'index.html');
|
||||
|
||||
function createEmbedAppServer(): Server {
|
||||
return createServer((req: IncomingMessage, res: ServerResponse) => {
|
||||
const urlPath = req.url?.split('?')[0] || '/';
|
||||
|
||||
if (urlPath === '/sdk/index.js') {
|
||||
if (!existsSync(SDK_BUNDLE_PATH)) {
|
||||
res.writeHead(404);
|
||||
res.end(
|
||||
'SDK bundle not found. Run: cd superset-embedded-sdk && npm ci && npm run build',
|
||||
);
|
||||
return;
|
||||
}
|
||||
res.writeHead(200, { 'Content-Type': 'text/javascript' });
|
||||
res.end(readFileSync(SDK_BUNDLE_PATH));
|
||||
return;
|
||||
}
|
||||
|
||||
if (urlPath === '/' || urlPath === '/index.html') {
|
||||
res.writeHead(200, { 'Content-Type': 'text/html' });
|
||||
res.end(readFileSync(INDEX_HTML_PATH));
|
||||
return;
|
||||
}
|
||||
|
||||
res.writeHead(404);
|
||||
res.end('Not found');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a browser context authenticated as admin for API-only work
|
||||
* (enabling embedding, restoring config). Caller is responsible for closing.
|
||||
*/
|
||||
function createAdminContext(browser: Browser): Promise<BrowserContext> {
|
||||
return browser.newContext({
|
||||
storageState: 'playwright/.auth/user.json',
|
||||
baseURL: SUPERSET_BASE_URL,
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Test Suite ────────────────────────────────────────────────────────────
|
||||
|
||||
// Describe wrapper is needed for shared server state and serial execution:
|
||||
// all tests share a static file server on a fixed port and must not run in parallel.
|
||||
test.describe('Embedded Dashboard E2E', () => {
|
||||
test.describe.configure({ mode: 'serial' });
|
||||
|
||||
let server: Server;
|
||||
let embedUuid: string;
|
||||
let dashboardId: number;
|
||||
|
||||
/**
|
||||
* Set up a page to render the default embedded dashboard.
|
||||
* Tests that need a different UUID or UI config should not use this helper.
|
||||
*/
|
||||
async function setupEmbeddedPage(page: Page): Promise<EmbeddedPage> {
|
||||
const embeddedPage = new EmbeddedPage(page);
|
||||
await embeddedPage.exposeTokenFetcher(async () =>
|
||||
getGuestToken(page, dashboardId),
|
||||
);
|
||||
await embeddedPage.goto({
|
||||
uuid: embedUuid,
|
||||
supersetDomain: SUPERSET_DOMAIN,
|
||||
});
|
||||
await embeddedPage.waitForIframe();
|
||||
await embeddedPage.waitForDashboardContent();
|
||||
return embeddedPage;
|
||||
}
|
||||
|
||||
test.beforeAll(async ({ browser }) => {
|
||||
// Skip all tests if the SDK bundle hasn't been built
|
||||
test.skip(
|
||||
!existsSync(SDK_BUNDLE_PATH),
|
||||
'Embedded SDK bundle not found. Build it with: cd superset-embedded-sdk && npm ci && npm run build',
|
||||
);
|
||||
|
||||
// Start the embedded test app server
|
||||
server = createEmbedAppServer();
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.on('error', reject);
|
||||
server.listen(EMBEDDED.APP_PORT, () => resolve());
|
||||
});
|
||||
|
||||
// Use a fresh context with auth to set up test data via API
|
||||
const context = await createAdminContext(browser);
|
||||
const setupPage = await context.newPage();
|
||||
|
||||
try {
|
||||
// Find a well-known example dashboard
|
||||
const dashboard = await getDashboardBySlug(setupPage, 'world_health');
|
||||
if (!dashboard) {
|
||||
throw new Error(
|
||||
'Dashboard "world_health" not found. Ensure load_examples ran in CI setup.',
|
||||
);
|
||||
}
|
||||
dashboardId = dashboard.id;
|
||||
|
||||
// Enable embedding on the dashboard (empty allowed_domains = allow all)
|
||||
const embedded = await apiEnableEmbedding(setupPage, dashboardId);
|
||||
embedUuid = embedded.uuid;
|
||||
} finally {
|
||||
await context.close();
|
||||
}
|
||||
});
|
||||
|
||||
test.afterAll(async () => {
|
||||
if (server) {
|
||||
await new Promise<void>(resolve => server.close(() => resolve()));
|
||||
}
|
||||
});
|
||||
|
||||
test('dashboard renders in embedded iframe', async ({ page }) => {
|
||||
const embeddedPage = await setupEmbeddedPage(page);
|
||||
|
||||
// Verify the iframe src points to Superset's /embedded/ endpoint
|
||||
const iframeSrc = await page
|
||||
.locator('iframe[title="Embedded Dashboard"]')
|
||||
.getAttribute('src');
|
||||
expect(iframeSrc).toContain(`/embedded/${embedUuid}`);
|
||||
|
||||
// Verify no errors in the test app
|
||||
const error = await embeddedPage.getError();
|
||||
expect(error).toBe('');
|
||||
|
||||
// Baseline: title should be visible when hideTitle is not set
|
||||
const titleVisible = await embeddedPage.isTitleVisible();
|
||||
expect(titleVisible).toBe(true);
|
||||
});
|
||||
|
||||
test('UI config hideTitle hides dashboard title', async ({ page }) => {
|
||||
const embeddedPage = new EmbeddedPage(page);
|
||||
await embeddedPage.exposeTokenFetcher(async () =>
|
||||
getGuestToken(page, dashboardId),
|
||||
);
|
||||
await embeddedPage.goto({
|
||||
uuid: embedUuid,
|
||||
supersetDomain: SUPERSET_DOMAIN,
|
||||
hideTitle: true,
|
||||
});
|
||||
await embeddedPage.waitForIframe();
|
||||
await embeddedPage.waitForDashboardContent();
|
||||
|
||||
// The iframe URL should include uiConfig parameter
|
||||
const iframeSrc = await page
|
||||
.locator('iframe[title="Embedded Dashboard"]')
|
||||
.getAttribute('src');
|
||||
expect(iframeSrc).toContain('uiConfig=');
|
||||
|
||||
// Verify the title is actually hidden inside the iframe
|
||||
const titleVisible = await embeddedPage.isTitleVisible();
|
||||
expect(titleVisible).toBe(false);
|
||||
});
|
||||
|
||||
test('charts render inside embedded iframe', async ({ page }) => {
|
||||
const embeddedPage = await setupEmbeddedPage(page);
|
||||
|
||||
// Verify chart containers are present and visible in the iframe
|
||||
const charts = embeddedPage.iframe.locator(
|
||||
'.chart-container, [data-test="chart-container"]',
|
||||
);
|
||||
await expect(charts.first()).toBeVisible({
|
||||
timeout: EMBEDDED.DASHBOARD_RENDER,
|
||||
});
|
||||
});
|
||||
|
||||
test('allowed_domains blocks unauthorized referrer', async ({
|
||||
page,
|
||||
browser,
|
||||
}) => {
|
||||
const context = await createAdminContext(browser);
|
||||
const setupPage = await context.newPage();
|
||||
|
||||
try {
|
||||
// Restrict to a domain that is NOT localhost:9000
|
||||
const restrictedEmbed = await apiEnableEmbedding(setupPage, dashboardId, [
|
||||
'https://allowed.example.com',
|
||||
]);
|
||||
|
||||
const embeddedPage = new EmbeddedPage(page);
|
||||
await embeddedPage.exposeTokenFetcher(async () =>
|
||||
getGuestToken(page, dashboardId),
|
||||
);
|
||||
await embeddedPage.goto({
|
||||
uuid: restrictedEmbed.uuid,
|
||||
supersetDomain: SUPERSET_DOMAIN,
|
||||
});
|
||||
|
||||
// The iframe should load but get a 403 from Superset's referrer check
|
||||
await embeddedPage.waitForIframe();
|
||||
|
||||
// The dashboard content should NOT render (403 blocks the embedded page)
|
||||
const content = embeddedPage.iframe.locator(
|
||||
'.grid-container, [data-test="grid-container"]',
|
||||
);
|
||||
await expect(content).not.toBeVisible({ timeout: 5000 });
|
||||
} finally {
|
||||
// Restore the open embedding config for other tests
|
||||
await apiEnableEmbedding(setupPage, dashboardId, []);
|
||||
await context.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('guest token enables dashboard data access', async ({ page }) => {
|
||||
const embeddedPage = new EmbeddedPage(page);
|
||||
|
||||
let tokenCallCount = 0;
|
||||
await embeddedPage.exposeTokenFetcher(async () => {
|
||||
tokenCallCount += 1;
|
||||
return getGuestToken(page, dashboardId);
|
||||
});
|
||||
|
||||
await embeddedPage.goto({
|
||||
uuid: embedUuid,
|
||||
supersetDomain: SUPERSET_DOMAIN,
|
||||
});
|
||||
await embeddedPage.waitForIframe();
|
||||
await embeddedPage.waitForDashboardContent();
|
||||
|
||||
// The SDK should have called fetchGuestToken at least once
|
||||
expect(tokenCallCount).toBeGreaterThanOrEqual(1);
|
||||
|
||||
// Verify charts are actually rendering data (not just loading spinners)
|
||||
const charts = embeddedPage.iframe.locator(
|
||||
'.chart-container, [data-test="chart-container"]',
|
||||
);
|
||||
const chartCount = await charts.count();
|
||||
expect(chartCount).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
315
superset-frontend/playwright/tests/sqllab/sqllab.spec.ts
Normal file
@@ -0,0 +1,315 @@
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
|
||||
/**
|
||||
* SQL Lab E2E tests — sequential via chromium-sqllab project.
|
||||
*
|
||||
* Tab state is stored server-side per user (/tabstateview/*), and all workers
|
||||
* share the same authenticated user. Parallel workers adding/removing tabs
|
||||
* would cause nondeterministic tab counts and cross-worker deletions.
|
||||
* See playwright.config.ts chromium-sqllab project for details.
|
||||
*/
|
||||
|
||||
import { test, expect } from '../../helpers/fixtures/testAssets';
|
||||
import { SqlLabPage } from '../../pages/SqlLabPage';
|
||||
import { ExplorePage } from '../../pages/ExplorePage';
|
||||
import { Input } from '../../components/core';
|
||||
import { SaveQueryModal } from '../../components/modals/SaveQueryModal';
|
||||
import { SaveDatasetModal } from '../../components/modals/SaveDatasetModal';
|
||||
import { waitForPost } from '../../helpers/api/intercepts';
|
||||
import {
|
||||
expectStatus,
|
||||
extractIdFromResponse,
|
||||
} from '../../helpers/api/assertions';
|
||||
import { apiGetSavedQuery } from '../../helpers/api/savedQuery';
|
||||
import { TIMEOUT } from '../../utils/constants';
|
||||
import { URL } from '../../utils/urls';
|
||||
|
||||
let sqlLabPage: SqlLabPage;
|
||||
|
||||
test.beforeEach(async ({ page }) => {
|
||||
test.setTimeout(TIMEOUT.SLOW_TEST);
|
||||
sqlLabPage = new SqlLabPage(page);
|
||||
await sqlLabPage.gotoAndReady();
|
||||
});
|
||||
|
||||
// ── Query Execution ──
|
||||
|
||||
test('executes a simple SELECT query and displays results', async () => {
|
||||
await expect(sqlLabPage.databaseSelector.element).toBeVisible();
|
||||
|
||||
const response = await sqlLabPage.executeQuery('SELECT 1 AS test_col');
|
||||
expectStatus(response, 200);
|
||||
|
||||
await sqlLabPage.waitForQueryResults('test_col');
|
||||
const headers = await sqlLabPage.resultsGrid.getHeaderTexts();
|
||||
expect(headers.some(h => h.includes('test_col'))).toBe(true);
|
||||
});
|
||||
|
||||
test('shows error message for invalid SQL', async () => {
|
||||
const invalidTable = 'a_table_that_does_not_exist_xyz_pw';
|
||||
await sqlLabPage.executeQuery(`SELECT * FROM ${invalidTable}`);
|
||||
|
||||
const { errorAlert } = sqlLabPage;
|
||||
await expect(errorAlert).toBeVisible({ timeout: TIMEOUT.QUERY_EXECUTION });
|
||||
// Assert the error references the specific table name, proving this query
|
||||
// triggered the failure — not a stale error from a prior test or session.
|
||||
await expect(errorAlert).toContainText(invalidTable);
|
||||
});
|
||||
|
||||
test('re-runs a query and refreshes results', async () => {
|
||||
const firstResponse = await sqlLabPage.executeQuery('SELECT 1 AS first_col');
|
||||
expectStatus(firstResponse, 200);
|
||||
await sqlLabPage.waitForQueryResults('first_col');
|
||||
|
||||
const firstHeaders = await sqlLabPage.resultsGrid.getHeaderTexts();
|
||||
expect(firstHeaders.some(h => h.includes('first_col'))).toBe(true);
|
||||
|
||||
const secondResponse = await sqlLabPage.executeQuery(
|
||||
'SELECT 2 AS second_col',
|
||||
);
|
||||
expectStatus(secondResponse, 200);
|
||||
await sqlLabPage.waitForQueryResults('second_col');
|
||||
|
||||
const secondHeaders = await sqlLabPage.resultsGrid.getHeaderTexts();
|
||||
expect(secondHeaders.some(h => h.includes('second_col'))).toBe(true);
|
||||
expect(secondHeaders.some(h => h.includes('first_col'))).toBe(false);
|
||||
});
|
||||
|
||||
// ── Tabs ──
|
||||
|
||||
test('creates a new tab via button', async () => {
|
||||
const initialTabCount = await sqlLabPage.getTabCount();
|
||||
|
||||
await sqlLabPage.addTab();
|
||||
await sqlLabPage.editor.waitForReady();
|
||||
|
||||
expect(await sqlLabPage.getTabCount()).toBe(initialTabCount + 1);
|
||||
|
||||
const defaultContent = await sqlLabPage.getQuery();
|
||||
expect(defaultContent).toContain('SELECT');
|
||||
|
||||
await sqlLabPage.closeLastTab();
|
||||
expect(await sqlLabPage.getTabCount()).toBe(initialTabCount);
|
||||
});
|
||||
|
||||
test('closes a tab via close button', async () => {
|
||||
const initialTabCount = await sqlLabPage.getTabCount();
|
||||
|
||||
await sqlLabPage.addTab();
|
||||
await sqlLabPage.editor.waitForReady();
|
||||
expect(await sqlLabPage.getTabCount()).toBe(initialTabCount + 1);
|
||||
|
||||
await sqlLabPage.closeLastTab();
|
||||
expect(await sqlLabPage.getTabCount()).toBe(initialTabCount);
|
||||
});
|
||||
|
||||
test('preserves query state when switching tabs', async () => {
|
||||
const tabOneSql = `SELECT 'tab_one_${Date.now()}'`;
|
||||
const tabTwoSql = `SELECT 'tab_two_${Date.now()}'`;
|
||||
|
||||
const firstTabName = await sqlLabPage.getActiveTabName();
|
||||
|
||||
await sqlLabPage.setQuery(tabOneSql);
|
||||
|
||||
await sqlLabPage.addTab();
|
||||
await sqlLabPage.editor.waitForReady();
|
||||
const secondTabName = await sqlLabPage.getActiveTabName();
|
||||
await sqlLabPage.setQuery(tabTwoSql);
|
||||
|
||||
// Use positional selection — tab names can collide in CI (both tabs may be
|
||||
// named "Untitled Query 1" depending on server-side tab state from prior tests).
|
||||
// Content assertions use toPass() because the editor hydrates asynchronously
|
||||
// after the tab switch — the Ace editor mounts first, then Redux populates it.
|
||||
await sqlLabPage.getTab(firstTabName).first().click();
|
||||
await sqlLabPage.editor.waitForReady();
|
||||
await expect(async () => {
|
||||
expect(await sqlLabPage.getQuery()).toContain('tab_one_');
|
||||
}).toPass({ timeout: TIMEOUT.UI_TRANSITION });
|
||||
|
||||
await sqlLabPage.getTab(secondTabName).last().click();
|
||||
await sqlLabPage.editor.waitForReady();
|
||||
await expect(async () => {
|
||||
expect(await sqlLabPage.getQuery()).toContain('tab_two_');
|
||||
}).toPass({ timeout: TIMEOUT.UI_TRANSITION });
|
||||
|
||||
await sqlLabPage.closeLastTab();
|
||||
});
|
||||
|
||||
test('should open new tab by keyboard shortcut with correct defaults', async ({
|
||||
page,
|
||||
}) => {
|
||||
const initialTabCount = await sqlLabPage.getTabCount();
|
||||
|
||||
await sqlLabPage.setQuery('some random query string');
|
||||
|
||||
// Register before addTabByShortcut — EditorAutoSync POSTs the new tab
|
||||
// within its 5 s interval, so the POST can fire before any later line.
|
||||
const tabStatePromise = waitForPost(page, /tabstateview\/?$/);
|
||||
|
||||
await sqlLabPage.addTabByShortcut();
|
||||
await sqlLabPage.editor.waitForReady();
|
||||
expect(await sqlLabPage.getTabCount()).toBe(initialTabCount + 1);
|
||||
|
||||
// Verify new tab has default SQL (not carried over from previous tab)
|
||||
const defaultContent = await sqlLabPage.getQuery();
|
||||
expect(defaultContent).toContain('SELECT');
|
||||
|
||||
// Wait for the auto-sync POST that persists the new tab to the backend
|
||||
await tabStatePromise;
|
||||
|
||||
await page.reload();
|
||||
await sqlLabPage.waitForPageLoad();
|
||||
await sqlLabPage.ensureEditorReady();
|
||||
|
||||
expect(await sqlLabPage.getTabCount()).toBe(initialTabCount + 1);
|
||||
|
||||
await sqlLabPage.closeLastTab();
|
||||
expect(await sqlLabPage.getTabCount()).toBe(initialTabCount);
|
||||
});
|
||||
|
||||
// ── Save and Share ──
|
||||
|
||||
test('saves a query and loads it from saved queries', async ({
|
||||
page,
|
||||
testAssets,
|
||||
}) => {
|
||||
const queryText = 'SELECT 1 AS saved_test_col';
|
||||
const savedQueryTitle = `pw_test_saved_query_${Date.now()}`;
|
||||
|
||||
await expect(sqlLabPage.databaseSelector.element).toBeVisible();
|
||||
|
||||
const executeResponse = await sqlLabPage.executeQuery(queryText);
|
||||
expectStatus(executeResponse, 200);
|
||||
await sqlLabPage.waitForQueryResults('saved_test_col');
|
||||
|
||||
await sqlLabPage.saveButton.click();
|
||||
const saveModal = new SaveQueryModal(page);
|
||||
await saveModal.waitForReady();
|
||||
|
||||
await saveModal.fillName(savedQueryTitle);
|
||||
|
||||
const savePromise = waitForPost(page, 'api/v1/saved_query/', {
|
||||
timeout: TIMEOUT.API_RESPONSE,
|
||||
});
|
||||
await saveModal.clickFooterButton('Save');
|
||||
const saveResponse = await savePromise;
|
||||
expectStatus(saveResponse, 201);
|
||||
|
||||
const savedQueryId = await extractIdFromResponse(saveResponse);
|
||||
testAssets.trackSavedQuery(savedQueryId);
|
||||
|
||||
await saveModal.waitForHidden();
|
||||
|
||||
const getResponse = await apiGetSavedQuery(page, savedQueryId);
|
||||
const savedQuery = (await getResponse.json()).result;
|
||||
expect(savedQuery.sql).toContain('saved_test_col');
|
||||
expect(savedQuery.label).toBe(savedQueryTitle);
|
||||
|
||||
// Navigate through the Saved Queries list UI (not deep-link) to verify
|
||||
// the query appears in the list and can be loaded from there.
|
||||
await page.goto(URL.SAVED_QUERIES_LIST, { waitUntil: 'domcontentloaded' });
|
||||
await page.locator('.ant-table').waitFor({
|
||||
state: 'visible',
|
||||
timeout: TIMEOUT.PAGE_LOAD,
|
||||
});
|
||||
|
||||
// Search for the saved query by its unique name
|
||||
const searchInput = new Input(page, 'input[data-test="filters-search"]');
|
||||
await searchInput.fill(savedQueryTitle);
|
||||
|
||||
// Wait for the filtered row to appear in the table
|
||||
const queryLink = page.getByRole('link', { name: savedQueryTitle });
|
||||
await queryLink.waitFor({ state: 'visible', timeout: TIMEOUT.API_RESPONSE });
|
||||
|
||||
// Navigate to SQL Lab with the saved query ID. The list-view React Router
|
||||
// <Link> uses makeUrl() which double-prefixes with basename in CI, causing
|
||||
// the click to silently fail. Direct navigation tests the loading path
|
||||
// reliably — the list search above already proves the query appears in the UI.
|
||||
await page.goto(`${URL.SQLLAB}?savedQueryId=${savedQueryId}`);
|
||||
await sqlLabPage.waitForPageLoad();
|
||||
await sqlLabPage.ensureEditorReady();
|
||||
|
||||
const loadedSql = await sqlLabPage.getQuery();
|
||||
expect(loadedSql).toContain('saved_test_col');
|
||||
});
|
||||
|
||||
test('creates a dataset from query results', async ({ page, testAssets }) => {
|
||||
await sqlLabPage.selectDatabase('examples');
|
||||
|
||||
const executeResponse = await sqlLabPage.executeQuery(
|
||||
'SELECT 1 AS ds_test_col',
|
||||
);
|
||||
expectStatus(executeResponse, 200);
|
||||
await sqlLabPage.waitForQueryResults('ds_test_col');
|
||||
|
||||
await sqlLabPage.saveDatasetButton.click();
|
||||
|
||||
const saveDatasetModal = new SaveDatasetModal(page);
|
||||
await saveDatasetModal.waitForReady();
|
||||
|
||||
const datasetName = `pw_test_dataset_${Date.now()}`;
|
||||
await saveDatasetModal.fillName(datasetName);
|
||||
|
||||
const datasetCreatePromise = waitForPost(page, 'api/v1/dataset/', {
|
||||
timeout: TIMEOUT.API_RESPONSE,
|
||||
});
|
||||
const newPagePromise = page.context().waitForEvent('page', {
|
||||
timeout: TIMEOUT.API_RESPONSE,
|
||||
});
|
||||
|
||||
await saveDatasetModal.clickFooterButton('Save & Explore');
|
||||
|
||||
const createResponse = await datasetCreatePromise;
|
||||
const datasetId = await extractIdFromResponse(createResponse);
|
||||
testAssets.trackDataset(datasetId);
|
||||
|
||||
const newPage = await newPagePromise;
|
||||
|
||||
const explorePage = new ExplorePage(newPage);
|
||||
await explorePage.waitForPageLoad({ timeout: TIMEOUT.PAGE_LOAD });
|
||||
|
||||
const loadedDatasetName = await explorePage.getDatasetName();
|
||||
expect(loadedDatasetName).toContain(datasetName);
|
||||
|
||||
await newPage.close();
|
||||
});
|
||||
|
||||
// ── Create Chart ──
|
||||
|
||||
test('should navigate to Explore from SQL Lab query results', async ({
|
||||
page,
|
||||
}) => {
|
||||
await sqlLabPage.selectDatabase('examples');
|
||||
|
||||
const query = 'SELECT gender, name FROM birth_names';
|
||||
const executeResponse = await sqlLabPage.executeQuery(query);
|
||||
expectStatus(executeResponse, 200);
|
||||
|
||||
await sqlLabPage.waitForQueryResults('gender');
|
||||
|
||||
await expect(sqlLabPage.createChartButton.element).toBeEnabled();
|
||||
await sqlLabPage.createChartButton.click();
|
||||
|
||||
const explorePage = new ExplorePage(page);
|
||||
await explorePage.waitForPageLoad({ timeout: TIMEOUT.PAGE_LOAD });
|
||||
|
||||
const datasetName = await explorePage.getDatasetName();
|
||||
expect(datasetName).toContain(query);
|
||||
});
|
||||
@@ -58,4 +58,35 @@ export const TIMEOUT = {
|
||||
* File import/upload operations (upload + server processing)
|
||||
*/
|
||||
FILE_IMPORT: 30000, // 30s for file import operations
|
||||
|
||||
/**
|
||||
* UI transition timeout (tab close, popover dismiss, dropdown close)
|
||||
*/
|
||||
UI_TRANSITION: 5000, // 5s ceiling for Ant Design animations (~300-500ms actual)
|
||||
|
||||
/**
|
||||
* SQL query execution (query → backend processing → results)
|
||||
*/
|
||||
QUERY_EXECUTION: 15000, // 15s for SQL queries that may take longer than default expect timeout
|
||||
|
||||
/**
|
||||
* Extended test timeout for multi-step tests (page load + query execution + assertions).
|
||||
* Use with test.setTimeout() when the default 30s test timeout is insufficient.
|
||||
*/
|
||||
SLOW_TEST: 60000, // 60s for tests that chain multiple slow operations
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Embedded dashboard test app configuration.
|
||||
* The test app is served by a Node.js http server started in the test fixture.
|
||||
*/
|
||||
export const EMBEDDED = {
|
||||
/** Port for the embedded test app static server */
|
||||
APP_PORT: 9000,
|
||||
/** Full URL for the embedded test app */
|
||||
APP_URL: 'http://localhost:9000',
|
||||
/** Timeout for iframe to appear in the DOM */
|
||||
IFRAME_LOAD: 15000, // 15s
|
||||
/** Timeout for dashboard content to render inside the iframe */
|
||||
DASHBOARD_RENDER: 30000, // 30s
|
||||
} as const;
|
||||
|
||||
@@ -33,6 +33,7 @@ export const URL = {
|
||||
DASHBOARD_LIST: 'dashboard/list/',
|
||||
DATASET_LIST: 'tablemodelview/list',
|
||||
LOGIN: 'login/',
|
||||
SAVED_QUERIES_LIST: 'savedqueryview/list/',
|
||||
SQLLAB: 'sqllab',
|
||||
WELCOME: 'superset/welcome/',
|
||||
} as const;
|
||||
|
||||
@@ -1,55 +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.
|
||||
-->
|
||||
|
||||
# Change Log
|
||||
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
# [0.20.0](https://github.com/apache/superset/compare/v2021.41.0...v0.20.0) (2024-09-09)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
- **deckgl:** deckgl unable to load map ([#17851](https://github.com/apache/superset/issues/17851)) ([52f5dcb](https://github.com/apache/superset/commit/52f5dcb58eec7b188f4387b8781dcda4252a5680))
|
||||
- **explore:** Prevent shared controls from checking feature flags outside React render ([#21315](https://github.com/apache/superset/issues/21315)) ([2285ebe](https://github.com/apache/superset/commit/2285ebe72ec4edded6d195052740b7f9f13d1f1b))
|
||||
|
||||
### Features
|
||||
|
||||
- apply standardized form data to tier 2 charts ([#20530](https://github.com/apache/superset/issues/20530)) ([de524bc](https://github.com/apache/superset/commit/de524bc59f011fd361dcdb7d35c2cb51f7eba442))
|
||||
- **deckgl-map:** use an arbitraty Mabpox style URL ([#26027](https://github.com/apache/superset/issues/26027)) ([#26031](https://github.com/apache/superset/issues/26031)) ([af58784](https://github.com/apache/superset/commit/af587840403d83a7da7fb0f57bc10ad2335d4eeb))
|
||||
|
||||
# [0.19.0](https://github.com/apache/superset/compare/v2021.41.0...v0.19.0) (2024-09-07)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
- **deckgl:** deckgl unable to load map ([#17851](https://github.com/apache/superset/issues/17851)) ([52f5dcb](https://github.com/apache/superset/commit/52f5dcb58eec7b188f4387b8781dcda4252a5680))
|
||||
- **explore:** Prevent shared controls from checking feature flags outside React render ([#21315](https://github.com/apache/superset/issues/21315)) ([2285ebe](https://github.com/apache/superset/commit/2285ebe72ec4edded6d195052740b7f9f13d1f1b))
|
||||
|
||||
### Features
|
||||
|
||||
- apply standardized form data to tier 2 charts ([#20530](https://github.com/apache/superset/issues/20530)) ([de524bc](https://github.com/apache/superset/commit/de524bc59f011fd361dcdb7d35c2cb51f7eba442))
|
||||
- **deckgl-map:** use an arbitraty Mabpox style URL ([#26027](https://github.com/apache/superset/issues/26027)) ([#26031](https://github.com/apache/superset/issues/26031)) ([af58784](https://github.com/apache/superset/commit/af587840403d83a7da7fb0f57bc10ad2335d4eeb))
|
||||
|
||||
# [0.18.0](https://github.com/apache-superset/superset-ui/compare/v0.17.87...v0.18.0) (2021-08-30)
|
||||
|
||||
**Note:** Version bump only for package @superset-ui/legacy-plugin-chart-map-box
|
||||
|
||||
## [0.17.61](https://github.com/apache-superset/superset-ui/compare/v0.17.60...v0.17.61) (2021-07-02)
|
||||
|
||||
**Note:** Version bump only for package @superset-ui/legacy-plugin-chart-map-box
|
||||
@@ -1,52 +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.
|
||||
-->
|
||||
|
||||
## @superset-ui/legacy-plugin-chart-map-box
|
||||
|
||||
[](https://www.npmjs.com/package/@superset-ui/legacy-plugin-chart-map-box)
|
||||
[](https://libraries.io/npm/@superset-ui%2Flegacy-plugin-chart-map-box)
|
||||
|
||||
This plugin provides MapBox for Superset.
|
||||
|
||||
### Usage
|
||||
|
||||
Configure `key`, which can be any `string`, and register the plugin. This `key` will be used to
|
||||
lookup this chart throughout the app.
|
||||
|
||||
```js
|
||||
import MapBoxChartPlugin from '@superset-ui/legacy-plugin-chart-map-box';
|
||||
|
||||
new MapBoxChartPlugin().configure({ key: 'map-box' }).register();
|
||||
```
|
||||
|
||||
Then use it via `SuperChart`. See
|
||||
[storybook](https://apache-superset.github.io/superset-ui-plugins/?selectedKind=plugin-chart-map-box)
|
||||
for more details.
|
||||
|
||||
```js
|
||||
<SuperChart
|
||||
chartType="map-box"
|
||||
width={600}
|
||||
height={600}
|
||||
formData={...}
|
||||
queriesData={[{
|
||||
data: {...},
|
||||
}]}
|
||||
/>
|
||||
```
|
||||
@@ -1,243 +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.
|
||||
*/
|
||||
/* eslint-disable react/jsx-sort-default-props, react/sort-prop-types */
|
||||
/* eslint-disable react/forbid-prop-types, react/require-default-props */
|
||||
import { Component } from 'react';
|
||||
import MapGL from 'react-map-gl';
|
||||
import { WebMercatorViewport } from '@math.gl/web-mercator';
|
||||
import ScatterPlotGlowOverlay from './ScatterPlotGlowOverlay';
|
||||
import './MapBox.css';
|
||||
|
||||
const NOOP = () => {};
|
||||
export const DEFAULT_MAX_ZOOM = 16;
|
||||
export const DEFAULT_POINT_RADIUS = 60;
|
||||
|
||||
interface Viewport {
|
||||
longitude: number;
|
||||
latitude: number;
|
||||
zoom: number;
|
||||
isDragging?: boolean;
|
||||
}
|
||||
|
||||
interface Clusterer {
|
||||
getClusters(bbox: number[], zoom: number): GeoJSONLocation[];
|
||||
}
|
||||
|
||||
interface GeoJSONLocation {
|
||||
geometry: {
|
||||
coordinates: [number, number];
|
||||
};
|
||||
properties: Record<string, number | string | boolean | null | undefined>;
|
||||
}
|
||||
|
||||
interface MapBoxProps {
|
||||
width?: number;
|
||||
height?: number;
|
||||
aggregatorName?: string;
|
||||
clusterer: Clusterer; // Required - used for getClusters()
|
||||
globalOpacity?: number;
|
||||
hasCustomMetric?: boolean;
|
||||
mapStyle?: string;
|
||||
mapboxApiKey: string;
|
||||
onViewportChange?: (viewport: Viewport) => void;
|
||||
pointRadius?: number;
|
||||
pointRadiusUnit?: string;
|
||||
renderWhileDragging?: boolean;
|
||||
rgb?: (string | number)[];
|
||||
bounds?: [[number, number], [number, number]]; // May be undefined for empty datasets
|
||||
viewportLongitude?: number;
|
||||
viewportLatitude?: number;
|
||||
viewportZoom?: number;
|
||||
}
|
||||
|
||||
interface MapBoxState {
|
||||
viewport: Viewport;
|
||||
}
|
||||
|
||||
const defaultProps: Partial<MapBoxProps> = {
|
||||
width: 400,
|
||||
height: 400,
|
||||
globalOpacity: 1,
|
||||
onViewportChange: NOOP,
|
||||
pointRadius: DEFAULT_POINT_RADIUS,
|
||||
pointRadiusUnit: 'Pixels',
|
||||
};
|
||||
|
||||
class MapBox extends Component<MapBoxProps, MapBoxState> {
|
||||
static defaultProps = defaultProps;
|
||||
|
||||
constructor(props: MapBoxProps) {
|
||||
super(props);
|
||||
|
||||
const fitBounds = this.computeFitBoundsViewport();
|
||||
|
||||
this.state = {
|
||||
viewport: this.mergeViewportWithProps(fitBounds),
|
||||
};
|
||||
this.handleViewportChange = this.handleViewportChange.bind(this);
|
||||
}
|
||||
|
||||
handleViewportChange(viewport: Viewport) {
|
||||
this.setState({ viewport });
|
||||
const { onViewportChange } = this.props;
|
||||
onViewportChange!(viewport);
|
||||
}
|
||||
|
||||
mergeViewportWithProps(
|
||||
fitBounds: Viewport,
|
||||
viewport: Viewport = fitBounds,
|
||||
props: MapBoxProps = this.props,
|
||||
useFitBoundsForUnset = true,
|
||||
): Viewport {
|
||||
const { viewportLongitude, viewportLatitude, viewportZoom } = props;
|
||||
|
||||
return {
|
||||
...viewport,
|
||||
longitude:
|
||||
viewportLongitude ??
|
||||
(useFitBoundsForUnset ? fitBounds.longitude : viewport.longitude),
|
||||
latitude:
|
||||
viewportLatitude ??
|
||||
(useFitBoundsForUnset ? fitBounds.latitude : viewport.latitude),
|
||||
zoom:
|
||||
viewportZoom ?? (useFitBoundsForUnset ? fitBounds.zoom : viewport.zoom),
|
||||
};
|
||||
}
|
||||
|
||||
computeFitBoundsViewport(): Viewport {
|
||||
const { width = 400, height = 400, bounds } = this.props;
|
||||
if (bounds && bounds[0] && bounds[1]) {
|
||||
const mercator = new WebMercatorViewport({ width, height }).fitBounds(
|
||||
bounds,
|
||||
);
|
||||
return {
|
||||
latitude: mercator.latitude,
|
||||
longitude: mercator.longitude,
|
||||
zoom: mercator.zoom,
|
||||
};
|
||||
}
|
||||
return { latitude: 0, longitude: 0, zoom: 1 };
|
||||
}
|
||||
|
||||
componentDidUpdate(prevProps: MapBoxProps) {
|
||||
const { viewport } = this.state;
|
||||
const fitBoundsInputsChanged =
|
||||
prevProps.width !== this.props.width ||
|
||||
prevProps.height !== this.props.height ||
|
||||
prevProps.bounds !== this.props.bounds;
|
||||
const viewportPropsChanged =
|
||||
prevProps.viewportLongitude !== this.props.viewportLongitude ||
|
||||
prevProps.viewportLatitude !== this.props.viewportLatitude ||
|
||||
prevProps.viewportZoom !== this.props.viewportZoom;
|
||||
|
||||
if (!fitBoundsInputsChanged && !viewportPropsChanged) {
|
||||
return;
|
||||
}
|
||||
|
||||
const fitBounds = this.computeFitBoundsViewport();
|
||||
const nextViewport = this.mergeViewportWithProps(
|
||||
fitBounds,
|
||||
viewport,
|
||||
this.props,
|
||||
fitBoundsInputsChanged || viewportPropsChanged,
|
||||
);
|
||||
|
||||
const viewportChanged =
|
||||
nextViewport.longitude !== viewport.longitude ||
|
||||
nextViewport.latitude !== viewport.latitude ||
|
||||
nextViewport.zoom !== viewport.zoom;
|
||||
|
||||
if (viewportChanged) {
|
||||
this.setState({ viewport: nextViewport });
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
const {
|
||||
width,
|
||||
height,
|
||||
aggregatorName,
|
||||
clusterer,
|
||||
globalOpacity,
|
||||
mapStyle,
|
||||
mapboxApiKey,
|
||||
pointRadius,
|
||||
pointRadiusUnit,
|
||||
renderWhileDragging,
|
||||
rgb,
|
||||
hasCustomMetric,
|
||||
bounds,
|
||||
} = this.props;
|
||||
const { viewport } = this.state;
|
||||
const isDragging =
|
||||
viewport.isDragging === undefined ? false : viewport.isDragging;
|
||||
|
||||
// Compute the clusters based on the original bounds and current zoom level. Note when zoom/pan
|
||||
// to an area outside of the original bounds, no additional queries are made to the backend to
|
||||
// retrieve additional data.
|
||||
// add this variable to widen the visible area
|
||||
const offsetHorizontal = ((width ?? 400) * 0.5) / 100;
|
||||
const offsetVertical = ((height ?? 400) * 0.5) / 100;
|
||||
|
||||
// Guard against empty datasets where bounds may be undefined
|
||||
const bbox =
|
||||
bounds && bounds[0] && bounds[1]
|
||||
? [
|
||||
bounds[0][0] - offsetHorizontal,
|
||||
bounds[0][1] - offsetVertical,
|
||||
bounds[1][0] + offsetHorizontal,
|
||||
bounds[1][1] + offsetVertical,
|
||||
]
|
||||
: [-180, -90, 180, 90]; // Default to world bounds
|
||||
|
||||
const clusters = clusterer.getClusters(bbox, Math.round(viewport.zoom));
|
||||
|
||||
return (
|
||||
<MapGL
|
||||
{...viewport}
|
||||
mapStyle={mapStyle}
|
||||
width={width}
|
||||
height={height}
|
||||
mapboxApiAccessToken={mapboxApiKey}
|
||||
onViewportChange={this.handleViewportChange}
|
||||
preserveDrawingBuffer
|
||||
>
|
||||
<ScatterPlotGlowOverlay
|
||||
{...viewport}
|
||||
isDragging={isDragging}
|
||||
locations={clusters}
|
||||
dotRadius={pointRadius}
|
||||
pointRadiusUnit={pointRadiusUnit}
|
||||
rgb={rgb}
|
||||
globalOpacity={globalOpacity}
|
||||
compositeOperation="screen"
|
||||
renderWhileDragging={renderWhileDragging}
|
||||
aggregation={hasCustomMetric ? aggregatorName : undefined}
|
||||
lngLatAccessor={(location: GeoJSONLocation) => {
|
||||
const { coordinates } = location.geometry;
|
||||
|
||||
return [coordinates[0], coordinates[1]];
|
||||
}}
|
||||
/>
|
||||
</MapGL>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default MapBox;
|
||||
@@ -1,425 +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.
|
||||
*/
|
||||
/* eslint-disable react/require-default-props */
|
||||
import { PureComponent } from 'react';
|
||||
import { CanvasOverlay } from 'react-map-gl';
|
||||
import { kmToPixels, MILES_PER_KM } from './utils/geo';
|
||||
import roundDecimal from './utils/roundDecimal';
|
||||
import luminanceFromRGB from './utils/luminanceFromRGB';
|
||||
import 'mapbox-gl/dist/mapbox-gl.css';
|
||||
|
||||
// Shared radius bounds keep cluster and point sizing in sync.
|
||||
export const MIN_CLUSTER_RADIUS_RATIO = 1 / 6;
|
||||
export const MAX_POINT_RADIUS_RATIO = 1 / 3;
|
||||
|
||||
interface GeoJSONLocation {
|
||||
geometry: {
|
||||
coordinates: [number, number];
|
||||
};
|
||||
properties: Record<string, number | string | boolean | null | undefined>;
|
||||
}
|
||||
|
||||
interface RedrawParams {
|
||||
width: number;
|
||||
height: number;
|
||||
ctx: CanvasRenderingContext2D;
|
||||
isDragging: boolean;
|
||||
project: (lngLat: [number, number]) => [number, number];
|
||||
}
|
||||
|
||||
interface DrawTextOptions {
|
||||
fontHeight?: number;
|
||||
label?: string | number;
|
||||
radius?: number;
|
||||
rgb?: (string | number)[];
|
||||
shadow?: boolean;
|
||||
}
|
||||
|
||||
interface ScatterPlotGlowOverlayProps {
|
||||
aggregation?: string;
|
||||
compositeOperation?: string;
|
||||
dotRadius?: number;
|
||||
globalOpacity?: number;
|
||||
lngLatAccessor?: (location: GeoJSONLocation) => [number, number];
|
||||
locations: GeoJSONLocation[];
|
||||
pointRadiusUnit?: string;
|
||||
renderWhileDragging?: boolean;
|
||||
rgb?: (string | number)[];
|
||||
zoom?: number;
|
||||
isDragging?: boolean;
|
||||
}
|
||||
|
||||
const defaultProps: Partial<ScatterPlotGlowOverlayProps> = {
|
||||
// Same as browser default.
|
||||
compositeOperation: 'source-over',
|
||||
dotRadius: 4,
|
||||
lngLatAccessor: (location: GeoJSONLocation) => [
|
||||
location.geometry.coordinates[0],
|
||||
location.geometry.coordinates[1],
|
||||
],
|
||||
renderWhileDragging: true,
|
||||
};
|
||||
|
||||
const computeClusterLabel = (
|
||||
properties: Record<string, number | string | boolean | null | undefined>,
|
||||
aggregation: string | undefined,
|
||||
): number | string => {
|
||||
const count = properties.point_count as number;
|
||||
if (!aggregation) {
|
||||
return count;
|
||||
}
|
||||
if (aggregation === 'sum' || aggregation === 'min' || aggregation === 'max') {
|
||||
return properties[aggregation] as number;
|
||||
}
|
||||
const { sum } = properties as { sum: number };
|
||||
const mean = sum / count;
|
||||
if (aggregation === 'mean') {
|
||||
return Math.round(100 * mean) / 100;
|
||||
}
|
||||
const { squaredSum } = properties as { squaredSum: number };
|
||||
const variance = squaredSum / count - (sum / count) ** 2;
|
||||
if (aggregation === 'var') {
|
||||
return Math.round(100 * variance) / 100;
|
||||
}
|
||||
if (aggregation === 'stdev') {
|
||||
return Math.round(100 * Math.sqrt(variance)) / 100;
|
||||
}
|
||||
|
||||
// fallback to point_count, this really shouldn't happen
|
||||
return count;
|
||||
};
|
||||
|
||||
class ScatterPlotGlowOverlay extends PureComponent<ScatterPlotGlowOverlayProps> {
|
||||
static defaultProps = defaultProps;
|
||||
|
||||
constructor(props: ScatterPlotGlowOverlayProps) {
|
||||
super(props);
|
||||
this.redraw = this.redraw.bind(this);
|
||||
}
|
||||
|
||||
drawText(
|
||||
ctx: CanvasRenderingContext2D,
|
||||
pixel: [number, number],
|
||||
options: DrawTextOptions = {},
|
||||
) {
|
||||
const IS_DARK_THRESHOLD = 110;
|
||||
const {
|
||||
fontHeight = 0,
|
||||
label = '',
|
||||
radius = 0,
|
||||
rgb = [0, 0, 0],
|
||||
shadow = false,
|
||||
} = options;
|
||||
const maxWidth = radius * 1.8;
|
||||
const luminance = luminanceFromRGB(
|
||||
rgb[1] as number,
|
||||
rgb[2] as number,
|
||||
rgb[3] as number,
|
||||
);
|
||||
|
||||
ctx.globalCompositeOperation = 'source-over';
|
||||
ctx.fillStyle = luminance <= IS_DARK_THRESHOLD ? 'white' : 'black';
|
||||
ctx.font = `${fontHeight}px sans-serif`;
|
||||
ctx.textAlign = 'center';
|
||||
ctx.textBaseline = 'middle';
|
||||
if (shadow) {
|
||||
ctx.shadowBlur = 15;
|
||||
ctx.shadowColor = luminance <= IS_DARK_THRESHOLD ? 'black' : '';
|
||||
}
|
||||
|
||||
const textWidth = ctx.measureText(String(label)).width;
|
||||
if (textWidth > maxWidth) {
|
||||
const scale = fontHeight / textWidth;
|
||||
ctx.font = `${scale * maxWidth}px sans-serif`;
|
||||
}
|
||||
|
||||
const { compositeOperation } = this.props;
|
||||
|
||||
ctx.fillText(String(label), pixel[0], pixel[1]);
|
||||
ctx.globalCompositeOperation = (compositeOperation ??
|
||||
'source-over') as GlobalCompositeOperation;
|
||||
ctx.shadowBlur = 0;
|
||||
ctx.shadowColor = '';
|
||||
}
|
||||
|
||||
// Modified: https://github.com/uber/react-map-gl/blob/master/overlays/scatterplot.react.js
|
||||
redraw({ width, height, ctx, isDragging, project }: RedrawParams) {
|
||||
const {
|
||||
aggregation,
|
||||
compositeOperation,
|
||||
dotRadius,
|
||||
globalOpacity,
|
||||
lngLatAccessor,
|
||||
locations,
|
||||
pointRadiusUnit,
|
||||
renderWhileDragging,
|
||||
rgb,
|
||||
zoom,
|
||||
} = this.props;
|
||||
|
||||
const radius = dotRadius ?? 4;
|
||||
const clusterLabelMap: (number | string)[] = [];
|
||||
|
||||
locations.forEach((location, i) => {
|
||||
if (location.properties.cluster) {
|
||||
clusterLabelMap[i] = computeClusterLabel(
|
||||
location.properties,
|
||||
aggregation,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
const finiteClusterLabels = clusterLabelMap
|
||||
.map(value => Number(value))
|
||||
.filter(value => Number.isFinite(value));
|
||||
const safeMaxAbsLabel =
|
||||
finiteClusterLabels.length > 0
|
||||
? Math.max(
|
||||
Math.max(...finiteClusterLabels.map(value => Math.abs(value))),
|
||||
1,
|
||||
)
|
||||
: 1;
|
||||
|
||||
// Calculate min/max radius values for Pixels mode scaling
|
||||
let minRadiusValue = Infinity;
|
||||
let maxRadiusValue = -Infinity;
|
||||
if (pointRadiusUnit === 'Pixels') {
|
||||
locations.forEach(location => {
|
||||
// Accept both null and undefined as "no value" and coerce potential numeric strings
|
||||
if (
|
||||
!location.properties.cluster &&
|
||||
location.properties.radius != null
|
||||
) {
|
||||
const radiusValueRaw = location.properties.radius;
|
||||
const radiusValue =
|
||||
typeof radiusValueRaw === 'string' && radiusValueRaw.trim() === ''
|
||||
? null
|
||||
: Number(radiusValueRaw);
|
||||
if (radiusValue != null && Number.isFinite(radiusValue)) {
|
||||
minRadiusValue = Math.min(minRadiusValue, radiusValue);
|
||||
maxRadiusValue = Math.max(maxRadiusValue, radiusValue);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
ctx.clearRect(0, 0, width, height);
|
||||
ctx.globalCompositeOperation = (compositeOperation ??
|
||||
'source-over') as GlobalCompositeOperation;
|
||||
|
||||
if ((renderWhileDragging || !isDragging) && locations) {
|
||||
locations.forEach(function _forEach(
|
||||
this: ScatterPlotGlowOverlay,
|
||||
location: GeoJSONLocation,
|
||||
i: number,
|
||||
) {
|
||||
const pixel = project(lngLatAccessor!(location)) as [number, number];
|
||||
const pixelRounded: [number, number] = [
|
||||
roundDecimal(pixel[0], 1),
|
||||
roundDecimal(pixel[1], 1),
|
||||
];
|
||||
|
||||
if (
|
||||
pixelRounded[0] + radius >= 0 &&
|
||||
pixelRounded[0] - radius < width &&
|
||||
pixelRounded[1] + radius >= 0 &&
|
||||
pixelRounded[1] - radius < height
|
||||
) {
|
||||
ctx.beginPath();
|
||||
if (location.properties.cluster) {
|
||||
const clusterLabel = clusterLabelMap[i];
|
||||
// Validate clusterLabel is a finite number before using it for radius calculation
|
||||
const numericLabel = Number(clusterLabel);
|
||||
const safeNumericLabel = Number.isFinite(numericLabel)
|
||||
? numericLabel
|
||||
: 0;
|
||||
const minClusterRadius =
|
||||
pointRadiusUnit === 'Pixels'
|
||||
? radius * MAX_POINT_RADIUS_RATIO
|
||||
: radius * MIN_CLUSTER_RADIUS_RATIO;
|
||||
const ratio = Math.abs(safeNumericLabel) / safeMaxAbsLabel;
|
||||
const scaledRadius = roundDecimal(
|
||||
minClusterRadius + ratio ** 0.5 * (radius - minClusterRadius),
|
||||
1,
|
||||
);
|
||||
const fontHeight = roundDecimal(scaledRadius * 0.5, 1);
|
||||
const [x, y] = pixelRounded;
|
||||
const gradient = ctx.createRadialGradient(
|
||||
x,
|
||||
y,
|
||||
scaledRadius,
|
||||
x,
|
||||
y,
|
||||
0,
|
||||
);
|
||||
|
||||
gradient.addColorStop(
|
||||
1,
|
||||
`rgba(${rgb![1]}, ${rgb![2]}, ${rgb![3]}, ${0.8 * (globalOpacity ?? 1)})`,
|
||||
);
|
||||
gradient.addColorStop(
|
||||
0,
|
||||
`rgba(${rgb![1]}, ${rgb![2]}, ${rgb![3]}, 0)`,
|
||||
);
|
||||
ctx.arc(
|
||||
pixelRounded[0],
|
||||
pixelRounded[1],
|
||||
scaledRadius,
|
||||
0,
|
||||
Math.PI * 2,
|
||||
);
|
||||
ctx.fillStyle = gradient;
|
||||
ctx.fill();
|
||||
|
||||
if (Number.isFinite(safeNumericLabel)) {
|
||||
let label: string | number = clusterLabel;
|
||||
const absLabel = Math.abs(safeNumericLabel);
|
||||
const sign = safeNumericLabel < 0 ? '-' : '';
|
||||
if (absLabel >= 10000) {
|
||||
label = `${sign}${Math.round(absLabel / 1000)}k`;
|
||||
} else if (absLabel >= 1000) {
|
||||
label = `${sign}${Math.round(absLabel / 100) / 10}k`;
|
||||
}
|
||||
this.drawText(ctx, pixelRounded, {
|
||||
fontHeight,
|
||||
label,
|
||||
radius: scaledRadius,
|
||||
rgb,
|
||||
shadow: true,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
const defaultRadius = radius * MIN_CLUSTER_RADIUS_RATIO;
|
||||
const rawRadius = location.properties.radius;
|
||||
const numericRadiusProperty =
|
||||
rawRadius != null &&
|
||||
!(typeof rawRadius === 'string' && rawRadius.trim() === '')
|
||||
? Number(rawRadius)
|
||||
: null;
|
||||
const radiusProperty =
|
||||
numericRadiusProperty != null &&
|
||||
Number.isFinite(numericRadiusProperty)
|
||||
? numericRadiusProperty
|
||||
: null;
|
||||
const pointMetric = location.properties.metric ?? null;
|
||||
let pointRadius: number = radiusProperty ?? defaultRadius;
|
||||
let pointLabel: string | number | undefined;
|
||||
|
||||
if (radiusProperty != null) {
|
||||
const pointLatitude = lngLatAccessor!(location)[1];
|
||||
if (pointRadiusUnit === 'Kilometers') {
|
||||
pointLabel = `${roundDecimal(pointRadius, 2)}km`;
|
||||
pointRadius = kmToPixels(pointRadius, pointLatitude, zoom ?? 0);
|
||||
} else if (pointRadiusUnit === 'Miles') {
|
||||
pointLabel = `${roundDecimal(pointRadius, 2)}mi`;
|
||||
pointRadius = kmToPixels(
|
||||
pointRadius * MILES_PER_KM,
|
||||
pointLatitude,
|
||||
zoom ?? 0,
|
||||
);
|
||||
} else if (pointRadiusUnit === 'Pixels') {
|
||||
// Scale pixel values to a reasonable range (radius/6 to radius/3)
|
||||
// This ensures points are visible and proportional to their values
|
||||
const MIN_POINT_RADIUS = radius * MIN_CLUSTER_RADIUS_RATIO;
|
||||
const MAX_POINT_RADIUS = radius * MAX_POINT_RADIUS_RATIO;
|
||||
|
||||
if (
|
||||
Number.isFinite(minRadiusValue) &&
|
||||
Number.isFinite(maxRadiusValue) &&
|
||||
maxRadiusValue > minRadiusValue
|
||||
) {
|
||||
// Normalize the value to 0-1 range, then scale to pixel range
|
||||
const numericPointRadius = Number(pointRadius);
|
||||
if (!Number.isFinite(numericPointRadius)) {
|
||||
// fallback to minimum visible size when the value is not a finite number
|
||||
pointRadius = MIN_POINT_RADIUS;
|
||||
} else {
|
||||
const normalizedValueRaw =
|
||||
(numericPointRadius - minRadiusValue) /
|
||||
(maxRadiusValue - minRadiusValue);
|
||||
const normalizedValue = Math.max(
|
||||
0,
|
||||
Math.min(1, normalizedValueRaw),
|
||||
);
|
||||
pointRadius =
|
||||
MIN_POINT_RADIUS +
|
||||
normalizedValue * (MAX_POINT_RADIUS - MIN_POINT_RADIUS);
|
||||
}
|
||||
pointLabel = `${roundDecimal(radiusProperty, 2)}`;
|
||||
} else if (
|
||||
Number.isFinite(minRadiusValue) &&
|
||||
minRadiusValue === maxRadiusValue
|
||||
) {
|
||||
// All values are the same, use a fixed medium size
|
||||
pointRadius = (MIN_POINT_RADIUS + MAX_POINT_RADIUS) / 2;
|
||||
pointLabel = `${roundDecimal(radiusProperty, 2)}`;
|
||||
} else {
|
||||
// Use raw pixel values if they're already in a reasonable range
|
||||
pointRadius = Math.max(
|
||||
MIN_POINT_RADIUS,
|
||||
Math.min(pointRadius, MAX_POINT_RADIUS),
|
||||
);
|
||||
pointLabel = `${roundDecimal(radiusProperty, 2)}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (pointMetric !== null) {
|
||||
const numericMetric = parseFloat(String(pointMetric));
|
||||
pointLabel = Number.isFinite(numericMetric)
|
||||
? roundDecimal(numericMetric, 2)
|
||||
: String(pointMetric);
|
||||
}
|
||||
|
||||
// Fall back to default points if pointRadius wasn't a numerical column
|
||||
if (!pointRadius) {
|
||||
pointRadius = defaultRadius;
|
||||
}
|
||||
|
||||
ctx.arc(
|
||||
pixelRounded[0],
|
||||
pixelRounded[1],
|
||||
roundDecimal(pointRadius, 1),
|
||||
0,
|
||||
Math.PI * 2,
|
||||
);
|
||||
ctx.fillStyle = `rgba(${rgb![1]}, ${rgb![2]}, ${rgb![3]}, ${globalOpacity})`;
|
||||
ctx.fill();
|
||||
|
||||
if (pointLabel !== undefined) {
|
||||
this.drawText(ctx, pixelRounded, {
|
||||
fontHeight: roundDecimal(pointRadius, 1),
|
||||
label: pointLabel,
|
||||
radius: pointRadius,
|
||||
rgb,
|
||||
shadow: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}, this);
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
return <CanvasOverlay redraw={this.redraw} />;
|
||||
}
|
||||
}
|
||||
|
||||
export default ScatterPlotGlowOverlay;
|
||||
@@ -1,107 +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.
|
||||
*/
|
||||
|
||||
/* eslint-disable no-magic-numbers */
|
||||
import { SuperChart } from '@superset-ui/core';
|
||||
import { useTheme } from '@apache-superset/core/theme';
|
||||
import MapBoxChartPlugin from '@superset-ui/legacy-plugin-chart-map-box';
|
||||
import { withResizableChartDemo } from '@storybook-shared';
|
||||
import { generateData } from './data';
|
||||
|
||||
new MapBoxChartPlugin().configure({ key: 'map-box' }).register();
|
||||
|
||||
export default {
|
||||
title: 'Legacy Chart Plugins/legacy-plugin-chart-map-box',
|
||||
decorators: [withResizableChartDemo],
|
||||
args: {
|
||||
clusteringRadius: 60,
|
||||
globalOpacity: 1,
|
||||
pointRadius: 'Auto',
|
||||
renderWhileDragging: true,
|
||||
},
|
||||
argTypes: {
|
||||
clusteringRadius: {
|
||||
control: { type: 'range', min: 0, max: 200, step: 10 },
|
||||
description: 'Radius in pixels for clustering points',
|
||||
},
|
||||
globalOpacity: {
|
||||
control: { type: 'range', min: 0, max: 1, step: 0.1 },
|
||||
description: 'Opacity of map markers',
|
||||
},
|
||||
pointRadius: {
|
||||
control: 'select',
|
||||
options: ['Auto', 1, 2, 5, 10, 20, 50],
|
||||
description: 'Size of point markers',
|
||||
},
|
||||
renderWhileDragging: {
|
||||
control: 'boolean',
|
||||
description: 'Render markers while dragging the map',
|
||||
},
|
||||
},
|
||||
parameters: {
|
||||
docs: {
|
||||
description: {
|
||||
component:
|
||||
'Note: This chart requires a Mapbox API key to display. Without a valid key, the map background will not render.',
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export const MapBoxViz = ({
|
||||
clusteringRadius,
|
||||
globalOpacity,
|
||||
pointRadius,
|
||||
renderWhileDragging,
|
||||
width,
|
||||
height,
|
||||
}: {
|
||||
clusteringRadius: number;
|
||||
globalOpacity: number;
|
||||
pointRadius: string | number;
|
||||
renderWhileDragging: boolean;
|
||||
width: number;
|
||||
height: number;
|
||||
}) => {
|
||||
const theme = useTheme();
|
||||
return (
|
||||
<SuperChart
|
||||
chartType="map-box"
|
||||
width={width}
|
||||
height={height}
|
||||
queriesData={[{ data: generateData(theme) }]}
|
||||
formData={{
|
||||
all_columns_x: 'LON',
|
||||
all_columns_y: 'LAT',
|
||||
clustering_radius: String(clusteringRadius),
|
||||
global_opacity: globalOpacity,
|
||||
mapbox_color: 'rgb(244, 176, 42)',
|
||||
mapbox_label: [],
|
||||
mapbox_style: 'mapbox://styles/mapbox/light-v9',
|
||||
pandas_aggfunc: 'sum',
|
||||
point_radius: pointRadius,
|
||||
point_radius_unit: 'Pixels',
|
||||
render_while_dragging: renderWhileDragging,
|
||||
viewport_latitude: 37.78711146014447,
|
||||
viewport_longitude: -122.37633433151713,
|
||||
viewport_zoom: 10.026425338292782,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
};
|
||||
@@ -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.
|
||||
*/
|
||||
import Supercluster, {
|
||||
type Options as SuperclusterOptions,
|
||||
} from 'supercluster';
|
||||
import { ChartProps } from '@superset-ui/core';
|
||||
import { DEFAULT_POINT_RADIUS, DEFAULT_MAX_ZOOM } from './MapBox';
|
||||
|
||||
const NOOP = () => {};
|
||||
const MIN_LONGITUDE = -180;
|
||||
const MAX_LONGITUDE = 180;
|
||||
const MIN_LATITUDE = -90;
|
||||
const MAX_LATITUDE = 90;
|
||||
const MIN_ZOOM = 0;
|
||||
|
||||
function toFiniteNumber(
|
||||
value: string | number | null | undefined,
|
||||
): number | undefined {
|
||||
if (value === null || value === undefined) return undefined;
|
||||
const normalizedValue = typeof value === 'string' ? value.trim() : value;
|
||||
if (normalizedValue === '') return undefined;
|
||||
const num = Number(normalizedValue);
|
||||
return Number.isFinite(num) ? num : undefined;
|
||||
}
|
||||
|
||||
function clampNumber(
|
||||
value: number | undefined,
|
||||
min: number,
|
||||
max: number,
|
||||
): number | undefined {
|
||||
if (value === undefined) return undefined;
|
||||
return Math.min(max, Math.max(min, value));
|
||||
}
|
||||
|
||||
interface ClusterProperties {
|
||||
metric: number;
|
||||
sum: number;
|
||||
squaredSum: number;
|
||||
min: number;
|
||||
max: number;
|
||||
}
|
||||
|
||||
export default function transformProps(chartProps: ChartProps) {
|
||||
const { width, height, formData, hooks, queriesData } = chartProps;
|
||||
const { onError = NOOP, setControlValue = NOOP } = hooks;
|
||||
const { bounds, geoJSON, hasCustomMetric, mapboxApiKey } =
|
||||
queriesData[0].data;
|
||||
const {
|
||||
clusteringRadius,
|
||||
globalOpacity,
|
||||
mapboxColor,
|
||||
mapboxStyle,
|
||||
pandasAggfunc,
|
||||
pointRadiusUnit,
|
||||
renderWhileDragging,
|
||||
viewportLongitude,
|
||||
viewportLatitude,
|
||||
viewportZoom,
|
||||
} = formData;
|
||||
|
||||
// Validate mapbox color
|
||||
const rgb = /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/.exec(mapboxColor);
|
||||
if (rgb === null) {
|
||||
onError("Color field must be of form 'rgb(%d, %d, %d)'");
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
const opts: SuperclusterOptions<ClusterProperties, ClusterProperties> = {
|
||||
maxZoom: DEFAULT_MAX_ZOOM,
|
||||
radius: clusteringRadius,
|
||||
};
|
||||
if (hasCustomMetric) {
|
||||
opts.initial = () => ({
|
||||
metric: 0,
|
||||
sum: 0,
|
||||
squaredSum: 0,
|
||||
min: Infinity,
|
||||
max: -Infinity,
|
||||
});
|
||||
opts.map = (prop: ClusterProperties) => ({
|
||||
metric: prop.metric,
|
||||
sum: prop.metric,
|
||||
squaredSum: prop.metric ** 2,
|
||||
min: prop.metric,
|
||||
max: prop.metric,
|
||||
});
|
||||
opts.reduce = (accu: ClusterProperties, prop: ClusterProperties) => {
|
||||
// Temporarily disable param-reassignment linting to work with supercluster's api
|
||||
/* eslint-disable no-param-reassign */
|
||||
accu.sum += prop.sum;
|
||||
accu.squaredSum += prop.squaredSum;
|
||||
accu.min = Math.min(accu.min, prop.min);
|
||||
accu.max = Math.max(accu.max, prop.max);
|
||||
/* eslint-enable no-param-reassign */
|
||||
};
|
||||
}
|
||||
const clusterer = new Supercluster(opts);
|
||||
clusterer.load(geoJSON.features);
|
||||
|
||||
return {
|
||||
width,
|
||||
height,
|
||||
aggregatorName: pandasAggfunc,
|
||||
bounds,
|
||||
clusterer,
|
||||
hasCustomMetric,
|
||||
mapboxApiKey,
|
||||
mapStyle: mapboxStyle,
|
||||
onViewportChange({
|
||||
latitude,
|
||||
longitude,
|
||||
zoom,
|
||||
}: {
|
||||
latitude: number;
|
||||
longitude: number;
|
||||
zoom: number;
|
||||
}) {
|
||||
setControlValue('viewport_longitude', longitude);
|
||||
setControlValue('viewport_latitude', latitude);
|
||||
setControlValue('viewport_zoom', zoom);
|
||||
},
|
||||
// Always use DEFAULT_POINT_RADIUS as the base radius for cluster sizing
|
||||
// Individual point radii come from geoJSON properties.radius
|
||||
pointRadius: DEFAULT_POINT_RADIUS,
|
||||
pointRadiusUnit,
|
||||
renderWhileDragging,
|
||||
rgb,
|
||||
viewportLongitude: clampNumber(
|
||||
toFiniteNumber(viewportLongitude),
|
||||
MIN_LONGITUDE,
|
||||
MAX_LONGITUDE,
|
||||
),
|
||||
viewportLatitude: clampNumber(
|
||||
toFiniteNumber(viewportLatitude),
|
||||
MIN_LATITUDE,
|
||||
MAX_LATITUDE,
|
||||
),
|
||||
viewportZoom: clampNumber(
|
||||
toFiniteNumber(viewportZoom),
|
||||
MIN_ZOOM,
|
||||
DEFAULT_MAX_ZOOM,
|
||||
),
|
||||
globalOpacity: Math.min(1, Math.max(0, toFiniteNumber(globalOpacity) ?? 1)),
|
||||
};
|
||||
}
|
||||
@@ -1,381 +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.
|
||||
*/
|
||||
|
||||
import { type ReactNode } from 'react';
|
||||
import { render } from '@testing-library/react';
|
||||
import MapBox from '../src/MapBox';
|
||||
|
||||
// Capture the most recent viewport props passed to MapGL
|
||||
let lastMapGLProps: Record<string, unknown> = {};
|
||||
const mockFitBounds = jest.fn();
|
||||
|
||||
jest.mock('react-map-gl', () => {
|
||||
const MockMapGL = (props: Record<string, unknown>) => {
|
||||
lastMapGLProps = props;
|
||||
return <div data-test="map-gl">{props.children as ReactNode}</div>;
|
||||
};
|
||||
return { __esModule: true, default: MockMapGL };
|
||||
});
|
||||
|
||||
jest.mock('@math.gl/web-mercator', () => ({
|
||||
WebMercatorViewport: jest
|
||||
.fn()
|
||||
.mockImplementation(
|
||||
({ width, height }: { width: number; height: number }) => ({
|
||||
fitBounds: (bounds: [[number, number], [number, number]]) =>
|
||||
mockFitBounds(bounds, width, height),
|
||||
}),
|
||||
),
|
||||
}));
|
||||
|
||||
jest.mock('../src/ScatterPlotGlowOverlay', () => {
|
||||
const MockOverlay = (props: Record<string, unknown>) => (
|
||||
<div data-test="scatter-overlay" data-opacity={props.globalOpacity} />
|
||||
);
|
||||
return { __esModule: true, default: MockOverlay };
|
||||
});
|
||||
|
||||
const defaultProps = {
|
||||
width: 800,
|
||||
height: 600,
|
||||
clusterer: {
|
||||
getClusters: jest.fn().mockReturnValue([]),
|
||||
},
|
||||
globalOpacity: 1,
|
||||
mapboxApiKey: 'test-key',
|
||||
mapStyle: 'mapbox://styles/mapbox/light-v9',
|
||||
pointRadius: 60,
|
||||
pointRadiusUnit: 'Pixels',
|
||||
renderWhileDragging: true,
|
||||
rgb: ['', 255, 0, 0] as (string | number)[],
|
||||
hasCustomMetric: false,
|
||||
bounds: [
|
||||
[-74.0, 40.7],
|
||||
[-73.9, 40.8],
|
||||
] as [[number, number], [number, number]],
|
||||
onViewportChange: jest.fn(),
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
lastMapGLProps = {};
|
||||
jest.clearAllMocks();
|
||||
mockFitBounds.mockImplementation(
|
||||
(
|
||||
bounds: [[number, number], [number, number]],
|
||||
width: number,
|
||||
height: number,
|
||||
) => ({
|
||||
latitude: Number(((bounds[0][1] + bounds[1][1]) / 2).toFixed(2)),
|
||||
longitude: Number(((bounds[0][0] + bounds[1][0]) / 2).toFixed(2)),
|
||||
zoom: Number((10 + width / 1000 + height / 10000).toFixed(2)),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
test('initializes viewport from bounds', () => {
|
||||
render(<MapBox {...defaultProps} />);
|
||||
expect(lastMapGLProps.latitude).toBe(40.75);
|
||||
expect(lastMapGLProps.longitude).toBe(-73.95);
|
||||
expect(lastMapGLProps.zoom).toBe(10.86);
|
||||
});
|
||||
|
||||
test('updates viewport when viewport props change', () => {
|
||||
const { rerender } = render(
|
||||
<MapBox
|
||||
{...defaultProps}
|
||||
viewportLongitude={-73.95}
|
||||
viewportLatitude={40.75}
|
||||
viewportZoom={10}
|
||||
/>,
|
||||
);
|
||||
|
||||
rerender(
|
||||
<MapBox
|
||||
{...defaultProps}
|
||||
viewportLongitude={-122.4}
|
||||
viewportLatitude={37.8}
|
||||
viewportZoom={5}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(lastMapGLProps.longitude).toBe(-122.4);
|
||||
expect(lastMapGLProps.latitude).toBe(37.8);
|
||||
expect(lastMapGLProps.zoom).toBe(5);
|
||||
});
|
||||
|
||||
test('does not loop when viewport state matches new props', () => {
|
||||
const { rerender } = render(
|
||||
<MapBox
|
||||
{...defaultProps}
|
||||
viewportLongitude={-73.95}
|
||||
viewportLatitude={40.75}
|
||||
viewportZoom={10}
|
||||
/>,
|
||||
);
|
||||
|
||||
// Re-render with same props that match the initial viewport state
|
||||
rerender(
|
||||
<MapBox
|
||||
{...defaultProps}
|
||||
viewportLongitude={-73.95}
|
||||
viewportLatitude={40.75}
|
||||
viewportZoom={10}
|
||||
/>,
|
||||
);
|
||||
|
||||
// Viewport should still be the fitBounds-computed values since props didn't change
|
||||
expect(lastMapGLProps.longitude).toBe(-73.95);
|
||||
expect(lastMapGLProps.latitude).toBe(40.75);
|
||||
expect(lastMapGLProps.zoom).toBe(10);
|
||||
});
|
||||
|
||||
test('passes globalOpacity to ScatterPlotGlowOverlay', () => {
|
||||
const { getByTestId } = render(
|
||||
<MapBox {...defaultProps} globalOpacity={0.5} />,
|
||||
);
|
||||
const overlay = getByTestId('scatter-overlay');
|
||||
expect(overlay.dataset.opacity).toBe('0.5');
|
||||
});
|
||||
|
||||
test('initializes viewport from props when provided', () => {
|
||||
render(
|
||||
<MapBox
|
||||
{...defaultProps}
|
||||
viewportLongitude={-122.4}
|
||||
viewportLatitude={37.8}
|
||||
viewportZoom={5}
|
||||
/>,
|
||||
);
|
||||
expect(lastMapGLProps.longitude).toBe(-122.4);
|
||||
expect(lastMapGLProps.latitude).toBe(37.8);
|
||||
expect(lastMapGLProps.zoom).toBe(5);
|
||||
});
|
||||
|
||||
test('handles undefined bounds gracefully', () => {
|
||||
render(<MapBox {...defaultProps} bounds={undefined} />);
|
||||
expect(lastMapGLProps.longitude).toBe(0);
|
||||
expect(lastMapGLProps.latitude).toBe(0);
|
||||
expect(lastMapGLProps.zoom).toBe(1);
|
||||
});
|
||||
|
||||
test('applies partial viewport props on update', () => {
|
||||
const { rerender } = render(<MapBox {...defaultProps} />);
|
||||
|
||||
rerender(<MapBox {...defaultProps} viewportLongitude={-122.4} />);
|
||||
|
||||
expect(lastMapGLProps.longitude).toBe(-122.4);
|
||||
expect(lastMapGLProps.latitude).toBe(40.75);
|
||||
expect(lastMapGLProps.zoom).toBe(10.86);
|
||||
});
|
||||
|
||||
test('restores fitBounds when viewport props are cleared', () => {
|
||||
const { rerender } = render(
|
||||
<MapBox
|
||||
{...defaultProps}
|
||||
viewportLongitude={-122.4}
|
||||
viewportLatitude={37.8}
|
||||
viewportZoom={5}
|
||||
/>,
|
||||
);
|
||||
|
||||
// Clear all viewport props (simulates user clearing the controls)
|
||||
rerender(<MapBox {...defaultProps} />);
|
||||
|
||||
// Should revert to fitBounds values
|
||||
expect(lastMapGLProps.longitude).toBe(-73.95);
|
||||
expect(lastMapGLProps.latitude).toBe(40.75);
|
||||
expect(lastMapGLProps.zoom).toBe(10.86);
|
||||
});
|
||||
|
||||
test('restores only cleared viewport props, keeps the rest', () => {
|
||||
const { rerender } = render(
|
||||
<MapBox
|
||||
{...defaultProps}
|
||||
viewportLongitude={-122.4}
|
||||
viewportLatitude={37.8}
|
||||
viewportZoom={5}
|
||||
/>,
|
||||
);
|
||||
|
||||
// Clear only longitude, keep lat/zoom
|
||||
rerender(
|
||||
<MapBox {...defaultProps} viewportLatitude={37.8} viewportZoom={5} />,
|
||||
);
|
||||
|
||||
// Longitude reverts to fitBounds, lat/zoom stay
|
||||
expect(lastMapGLProps.longitude).toBe(-73.95);
|
||||
expect(lastMapGLProps.latitude).toBe(37.8);
|
||||
expect(lastMapGLProps.zoom).toBe(5);
|
||||
});
|
||||
|
||||
test('applies changed viewport props even when another is cleared simultaneously', () => {
|
||||
const { rerender } = render(
|
||||
<MapBox
|
||||
{...defaultProps}
|
||||
viewportLongitude={-122.4}
|
||||
viewportLatitude={37.8}
|
||||
viewportZoom={5}
|
||||
/>,
|
||||
);
|
||||
|
||||
// Clear longitude, change latitude simultaneously
|
||||
rerender(
|
||||
<MapBox {...defaultProps} viewportLatitude={40.0} viewportZoom={5} />,
|
||||
);
|
||||
|
||||
// Longitude reverts to fitBounds, latitude should be the NEW value
|
||||
expect(lastMapGLProps.longitude).toBe(-73.95);
|
||||
expect(lastMapGLProps.latitude).toBe(40.0);
|
||||
expect(lastMapGLProps.zoom).toBe(5);
|
||||
});
|
||||
|
||||
test('falls back to default viewport when cleared with undefined bounds', () => {
|
||||
const { rerender } = render(
|
||||
<MapBox
|
||||
{...defaultProps}
|
||||
bounds={undefined}
|
||||
viewportLongitude={-122.4}
|
||||
viewportLatitude={37.8}
|
||||
viewportZoom={5}
|
||||
/>,
|
||||
);
|
||||
|
||||
// Clear viewport props — no bounds to fitBounds to
|
||||
rerender(<MapBox {...defaultProps} bounds={undefined} />);
|
||||
|
||||
// Should fall back to {0, 0, 1}
|
||||
expect(lastMapGLProps.longitude).toBe(0);
|
||||
expect(lastMapGLProps.latitude).toBe(0);
|
||||
expect(lastMapGLProps.zoom).toBe(1);
|
||||
});
|
||||
|
||||
test('recomputes fitBounds when bounds change and no explicit viewport is set', () => {
|
||||
const { rerender } = render(<MapBox {...defaultProps} />);
|
||||
|
||||
rerender(
|
||||
<MapBox
|
||||
{...defaultProps}
|
||||
bounds={[
|
||||
[-123.2, 36.5],
|
||||
[-121.8, 38.1],
|
||||
]}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(lastMapGLProps.longitude).toBe(-122.5);
|
||||
expect(lastMapGLProps.latitude).toBe(37.3);
|
||||
expect(lastMapGLProps.zoom).toBe(10.86);
|
||||
});
|
||||
|
||||
test('recomputes fitBounds when chart size changes and no explicit viewport is set', () => {
|
||||
const { rerender } = render(<MapBox {...defaultProps} />);
|
||||
|
||||
rerender(<MapBox {...defaultProps} width={1200} height={900} />);
|
||||
|
||||
expect(lastMapGLProps.longitude).toBe(-73.95);
|
||||
expect(lastMapGLProps.latitude).toBe(40.75);
|
||||
expect(lastMapGLProps.zoom).toBe(11.29);
|
||||
});
|
||||
|
||||
test('recomputes only implicit viewport fields when bounds change', () => {
|
||||
const { rerender } = render(
|
||||
<MapBox {...defaultProps} viewportLongitude={-122.4} />,
|
||||
);
|
||||
|
||||
rerender(
|
||||
<MapBox
|
||||
{...defaultProps}
|
||||
viewportLongitude={-122.4}
|
||||
bounds={[
|
||||
[-123.2, 36.5],
|
||||
[-121.8, 38.1],
|
||||
]}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(lastMapGLProps.longitude).toBe(-122.4);
|
||||
expect(lastMapGLProps.latitude).toBe(37.3);
|
||||
expect(lastMapGLProps.zoom).toBe(10.86);
|
||||
});
|
||||
|
||||
test('recomputes only implicit viewport fields when chart size changes', () => {
|
||||
const { rerender } = render(
|
||||
<MapBox {...defaultProps} viewportLatitude={37.8} />,
|
||||
);
|
||||
|
||||
rerender(
|
||||
<MapBox
|
||||
{...defaultProps}
|
||||
viewportLatitude={37.8}
|
||||
width={1200}
|
||||
height={900}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(lastMapGLProps.longitude).toBe(-73.95);
|
||||
expect(lastMapGLProps.latitude).toBe(37.8);
|
||||
expect(lastMapGLProps.zoom).toBe(11.29);
|
||||
});
|
||||
|
||||
test('recomputes implicit position when zoom stays explicit across bounds changes', () => {
|
||||
const { rerender } = render(<MapBox {...defaultProps} viewportZoom={5} />);
|
||||
|
||||
rerender(
|
||||
<MapBox
|
||||
{...defaultProps}
|
||||
viewportZoom={5}
|
||||
bounds={[
|
||||
[-123.2, 36.5],
|
||||
[-121.8, 38.1],
|
||||
]}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(lastMapGLProps.longitude).toBe(-122.5);
|
||||
expect(lastMapGLProps.latitude).toBe(37.3);
|
||||
expect(lastMapGLProps.zoom).toBe(5);
|
||||
});
|
||||
|
||||
test('does not recompute fitBounds on bounds change when an explicit viewport is set', () => {
|
||||
const { rerender } = render(
|
||||
<MapBox
|
||||
{...defaultProps}
|
||||
viewportLongitude={-122.4}
|
||||
viewportLatitude={37.8}
|
||||
viewportZoom={5}
|
||||
/>,
|
||||
);
|
||||
|
||||
rerender(
|
||||
<MapBox
|
||||
{...defaultProps}
|
||||
viewportLongitude={-122.4}
|
||||
viewportLatitude={37.8}
|
||||
viewportZoom={5}
|
||||
bounds={[
|
||||
[-123.2, 36.5],
|
||||
[-121.8, 38.1],
|
||||
]}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(lastMapGLProps.longitude).toBe(-122.4);
|
||||
expect(lastMapGLProps.latitude).toBe(37.8);
|
||||
expect(lastMapGLProps.zoom).toBe(5);
|
||||
});
|
||||
@@ -1,9 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"composite": false,
|
||||
"emitDeclarationOnly": false,
|
||||
"rootDir": "."
|
||||
},
|
||||
"extends": "../../../tsconfig.json",
|
||||
"include": ["**/*", "../types/**/*", "../../../types/**/*"]
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
{
|
||||
"extends": "../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
// Path Resolution: Override baseUrl to maintain correct path mappings from parent config
|
||||
// (e.g., "@apache-superset/core" -> "./packages/superset-core/src")
|
||||
"baseUrl": "../..",
|
||||
|
||||
// Directory Overrides: Parent config paths are relative to frontend root,
|
||||
// but packages need paths relative to their own directory
|
||||
"outDir": "lib",
|
||||
"rootDir": "src",
|
||||
"declarationDir": "lib"
|
||||
},
|
||||
"include": ["src/**/*.ts", "src/**/*.tsx", "types/**/*"],
|
||||
"exclude": [
|
||||
"src/**/*.js",
|
||||
"src/**/*.jsx",
|
||||
"src/**/*.test.*",
|
||||
"src/**/*.stories.*"],
|
||||
"references": [
|
||||
{ "path": "../../packages/superset-core" },
|
||||
{ "path": "../../packages/superset-ui-core" },
|
||||
{ "path": "../../packages/superset-ui-chart-controls" }
|
||||
]
|
||||
}
|
||||
@@ -1,101 +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.
|
||||
*/
|
||||
|
||||
declare module '*.png' {
|
||||
const value: string;
|
||||
export default value;
|
||||
}
|
||||
|
||||
declare module '*.jpg' {
|
||||
const value: string;
|
||||
export default value;
|
||||
}
|
||||
|
||||
declare module 'supercluster' {
|
||||
interface Options<P = Record<string, unknown>, C = Record<string, unknown>> {
|
||||
minZoom?: number;
|
||||
maxZoom?: number;
|
||||
minPoints?: number;
|
||||
radius?: number;
|
||||
extent?: number;
|
||||
nodeSize?: number;
|
||||
log?: boolean;
|
||||
initial?: () => C;
|
||||
map?: (props: P) => C;
|
||||
reduce?: (accumulated: C, props: C) => void;
|
||||
}
|
||||
|
||||
interface GeoJSONFeature {
|
||||
type: string;
|
||||
geometry: {
|
||||
type: string;
|
||||
coordinates: [number, number];
|
||||
};
|
||||
properties: Record<string, unknown>;
|
||||
}
|
||||
|
||||
class Supercluster<P = Record<string, unknown>, C = Record<string, unknown>> {
|
||||
constructor(options?: Options<P, C>);
|
||||
load(points: GeoJSONFeature[]): Supercluster<P, C>;
|
||||
getClusters(bbox: number[], zoom: number): GeoJSONFeature[];
|
||||
getTile(z: number, x: number, y: number): GeoJSONFeature[] | null;
|
||||
getChildren(clusterId: number): GeoJSONFeature[];
|
||||
getLeaves(
|
||||
clusterId: number,
|
||||
limit?: number,
|
||||
offset?: number,
|
||||
): GeoJSONFeature[];
|
||||
getClusterExpansionZoom(clusterId: number): number;
|
||||
}
|
||||
|
||||
export default Supercluster;
|
||||
export { Options, GeoJSONFeature };
|
||||
}
|
||||
|
||||
declare module 'react-map-gl' {
|
||||
import { Component, ReactNode } from 'react';
|
||||
|
||||
interface MapGLProps {
|
||||
width?: number;
|
||||
height?: number;
|
||||
latitude?: number;
|
||||
longitude?: number;
|
||||
zoom?: number;
|
||||
mapStyle?: string;
|
||||
mapboxApiAccessToken?: string;
|
||||
onViewportChange?: Function;
|
||||
preserveDrawingBuffer?: boolean;
|
||||
children?: ReactNode;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export default class MapGL extends Component<MapGLProps> {}
|
||||
|
||||
interface CanvasOverlayProps {
|
||||
redraw: (params: {
|
||||
width: number;
|
||||
height: number;
|
||||
ctx: CanvasRenderingContext2D;
|
||||
isDragging: boolean;
|
||||
project: (lngLat: [number, number]) => [number, number];
|
||||
}) => void;
|
||||
}
|
||||
|
||||
export class CanvasOverlay extends Component<CanvasOverlayProps> {}
|
||||
}
|
||||
@@ -1,89 +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.
|
||||
-->
|
||||
|
||||
# Change Log
|
||||
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
## [0.20.4](https://github.com/apache/superset/compare/v0.20.3...v0.20.4) (2024-12-10)
|
||||
|
||||
**Note:** Version bump only for package @superset-ui/legacy-preset-chart-deckgl
|
||||
|
||||
# [0.20.0](https://github.com/apache/superset/compare/v2021.41.0...v0.20.0) (2024-09-09)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
- **Dashboard:** Color inconsistency on refreshes and conflicts ([#27439](https://github.com/apache/superset/issues/27439)) ([313ee59](https://github.com/apache/superset/commit/313ee596f5435894f857d72be7269d5070c8c964))
|
||||
- deck.gl Geojson path not visible ([#24428](https://github.com/apache/superset/issues/24428)) ([6bb930e](https://github.com/apache/superset/commit/6bb930ef4ed26ea381e7f8e889851aa7867ba0eb))
|
||||
- deck.gl GeoJsonLayer Autozoom & fill/stroke options ([#19778](https://github.com/apache/superset/issues/19778)) ([d65b77e](https://github.com/apache/superset/commit/d65b77ec7dac4c2368fcaa1fe6e98db102966198))
|
||||
- **deck.gl Multiple Layer Chart:** Add Contour and Heatmap Layer as options ([#25923](https://github.com/apache/superset/issues/25923)) ([64ba579](https://github.com/apache/superset/commit/64ba5797df92d0f8067ccd2b30ba6ff58e0bd791))
|
||||
- deck.gl Scatterplot min/max radius ([#24363](https://github.com/apache/superset/issues/24363)) ([c728cdf](https://github.com/apache/superset/commit/c728cdf501ec292beb14a0982265052bf2274bec))
|
||||
- **deck.gl:** multiple layers map size is shrunk ([#18939](https://github.com/apache/superset/issues/18939)) ([2cb3635](https://github.com/apache/superset/commit/2cb3635256ee8e91f0bac2f3091684673c04ff2b))
|
||||
- **deck.gl:** update view state on property changes ([#17720](https://github.com/apache/superset/issues/17720)) ([#17826](https://github.com/apache/superset/issues/17826)) ([97d918b](https://github.com/apache/superset/commit/97d918b6927f572dca3b33c61b89c8b3ebdc4376))
|
||||
- DeckGL legend layout ([#30140](https://github.com/apache/superset/issues/30140)) ([af066a4](https://github.com/apache/superset/commit/af066a46306f2f476aa2944b14df3de1faf1e96d))
|
||||
- **deckgl:** deckgl unable to load map ([#17851](https://github.com/apache/superset/issues/17851)) ([52f5dcb](https://github.com/apache/superset/commit/52f5dcb58eec7b188f4387b8781dcda4252a5680))
|
||||
- **explore:** Fix chart standalone URL for report/thumbnail generation ([#20673](https://github.com/apache/superset/issues/20673)) ([84d4302](https://github.com/apache/superset/commit/84d4302628d18aa19c13cc5322e68abbc690ea4d))
|
||||
- **explore:** Prevent shared controls from checking feature flags outside React render ([#21315](https://github.com/apache/superset/issues/21315)) ([2285ebe](https://github.com/apache/superset/commit/2285ebe72ec4edded6d195052740b7f9f13d1f1b))
|
||||
- weight tooltip issue ([#19397](https://github.com/apache/superset/issues/19397)) ([f6d550b](https://github.com/apache/superset/commit/f6d550b7fc3643350483850064e65dbd3d026dc4))
|
||||
|
||||
### Features
|
||||
|
||||
- Add Deck.gl Contour Layer ([#24154](https://github.com/apache/superset/issues/24154)) ([512fb9a](https://github.com/apache/superset/commit/512fb9a0bdd428b94b0c121158b8b15b7631e0fb))
|
||||
- Add deck.gl Heatmap Visualization ([#23551](https://github.com/apache/superset/issues/23551)) ([fc8c537](https://github.com/apache/superset/commit/fc8c537118ce6c7b3a4624f88a31e2e7fb287327))
|
||||
- Add line width unit control in deckgl Polygon and Path ([#24755](https://github.com/apache/superset/issues/24755)) ([d26ea98](https://github.com/apache/superset/commit/d26ea980acc7d2a20757efc360d810afe83d5c65))
|
||||
- apply standardized form data to deckgl ([#20579](https://github.com/apache/superset/issues/20579)) ([290b89c](https://github.com/apache/superset/commit/290b89c7b4ae702c55f611bfac9cedb245ea8bd8))
|
||||
- **deck.gl:** add color range for deck.gl 3D ([#19520](https://github.com/apache/superset/issues/19520)) ([c0a00fd](https://github.com/apache/superset/commit/c0a00fd302ec66fbe0ca766cf73978c99ba00d82))
|
||||
- **deckgl-map:** use an arbitraty Mabpox style URL ([#26027](https://github.com/apache/superset/issues/26027)) ([#26031](https://github.com/apache/superset/issues/26031)) ([af58784](https://github.com/apache/superset/commit/af587840403d83a7da7fb0f57bc10ad2335d4eeb))
|
||||
- **explore:** Frontend implementation of dataset creation from infobox ([#19855](https://github.com/apache/superset/issues/19855)) ([ba0c37d](https://github.com/apache/superset/commit/ba0c37d3df85b1af39404af1d578daeb0ff2d278))
|
||||
- improve color consistency (save all labels) ([#19038](https://github.com/apache/superset/issues/19038)) ([dc57508](https://github.com/apache/superset/commit/dc575080d7e43d40b1734bb8f44fdc291cb95b11))
|
||||
- **legacy-preset-chart-deckgl:** Add ,.1f and ,.2f value formats to deckgl charts ([#18945](https://github.com/apache/superset/issues/18945)) ([c56dc8e](https://github.com/apache/superset/commit/c56dc8eace6a71b45240d1bb6768d75661052a2e))
|
||||
- make data tables support html ([#24368](https://github.com/apache/superset/issues/24368)) ([d2b0b8e](https://github.com/apache/superset/commit/d2b0b8eac52ad8b68639c6581a1ed174a593f564))
|
||||
- **viz picker:** Remove some tags, refactor Recommended section ([#27708](https://github.com/apache/superset/issues/27708)) ([c314999](https://github.com/apache/superset/commit/c3149994ac0d4392e0462421b62cd0c034142082))
|
||||
|
||||
# [0.19.0](https://github.com/apache/superset/compare/v2021.41.0...v0.19.0) (2024-09-07)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
- **Dashboard:** Color inconsistency on refreshes and conflicts ([#27439](https://github.com/apache/superset/issues/27439)) ([313ee59](https://github.com/apache/superset/commit/313ee596f5435894f857d72be7269d5070c8c964))
|
||||
- deck.gl Geojson path not visible ([#24428](https://github.com/apache/superset/issues/24428)) ([6bb930e](https://github.com/apache/superset/commit/6bb930ef4ed26ea381e7f8e889851aa7867ba0eb))
|
||||
- deck.gl GeoJsonLayer Autozoom & fill/stroke options ([#19778](https://github.com/apache/superset/issues/19778)) ([d65b77e](https://github.com/apache/superset/commit/d65b77ec7dac4c2368fcaa1fe6e98db102966198))
|
||||
- **deck.gl Multiple Layer Chart:** Add Contour and Heatmap Layer as options ([#25923](https://github.com/apache/superset/issues/25923)) ([64ba579](https://github.com/apache/superset/commit/64ba5797df92d0f8067ccd2b30ba6ff58e0bd791))
|
||||
- deck.gl Scatterplot min/max radius ([#24363](https://github.com/apache/superset/issues/24363)) ([c728cdf](https://github.com/apache/superset/commit/c728cdf501ec292beb14a0982265052bf2274bec))
|
||||
- **deck.gl:** multiple layers map size is shrunk ([#18939](https://github.com/apache/superset/issues/18939)) ([2cb3635](https://github.com/apache/superset/commit/2cb3635256ee8e91f0bac2f3091684673c04ff2b))
|
||||
- **deck.gl:** update view state on property changes ([#17720](https://github.com/apache/superset/issues/17720)) ([#17826](https://github.com/apache/superset/issues/17826)) ([97d918b](https://github.com/apache/superset/commit/97d918b6927f572dca3b33c61b89c8b3ebdc4376))
|
||||
- DeckGL legend layout ([#30140](https://github.com/apache/superset/issues/30140)) ([af066a4](https://github.com/apache/superset/commit/af066a46306f2f476aa2944b14df3de1faf1e96d))
|
||||
- **deckgl:** deckgl unable to load map ([#17851](https://github.com/apache/superset/issues/17851)) ([52f5dcb](https://github.com/apache/superset/commit/52f5dcb58eec7b188f4387b8781dcda4252a5680))
|
||||
- **explore:** Fix chart standalone URL for report/thumbnail generation ([#20673](https://github.com/apache/superset/issues/20673)) ([84d4302](https://github.com/apache/superset/commit/84d4302628d18aa19c13cc5322e68abbc690ea4d))
|
||||
- **explore:** Prevent shared controls from checking feature flags outside React render ([#21315](https://github.com/apache/superset/issues/21315)) ([2285ebe](https://github.com/apache/superset/commit/2285ebe72ec4edded6d195052740b7f9f13d1f1b))
|
||||
- weight tooltip issue ([#19397](https://github.com/apache/superset/issues/19397)) ([f6d550b](https://github.com/apache/superset/commit/f6d550b7fc3643350483850064e65dbd3d026dc4))
|
||||
|
||||
### Features
|
||||
|
||||
- Add Deck.gl Contour Layer ([#24154](https://github.com/apache/superset/issues/24154)) ([512fb9a](https://github.com/apache/superset/commit/512fb9a0bdd428b94b0c121158b8b15b7631e0fb))
|
||||
- Add deck.gl Heatmap Visualization ([#23551](https://github.com/apache/superset/issues/23551)) ([fc8c537](https://github.com/apache/superset/commit/fc8c537118ce6c7b3a4624f88a31e2e7fb287327))
|
||||
- Add line width unit control in deckgl Polygon and Path ([#24755](https://github.com/apache/superset/issues/24755)) ([d26ea98](https://github.com/apache/superset/commit/d26ea980acc7d2a20757efc360d810afe83d5c65))
|
||||
- apply standardized form data to deckgl ([#20579](https://github.com/apache/superset/issues/20579)) ([290b89c](https://github.com/apache/superset/commit/290b89c7b4ae702c55f611bfac9cedb245ea8bd8))
|
||||
- **deck.gl:** add color range for deck.gl 3D ([#19520](https://github.com/apache/superset/issues/19520)) ([c0a00fd](https://github.com/apache/superset/commit/c0a00fd302ec66fbe0ca766cf73978c99ba00d82))
|
||||
- **deckgl-map:** use an arbitraty Mabpox style URL ([#26027](https://github.com/apache/superset/issues/26027)) ([#26031](https://github.com/apache/superset/issues/26031)) ([af58784](https://github.com/apache/superset/commit/af587840403d83a7da7fb0f57bc10ad2335d4eeb))
|
||||
- **explore:** Frontend implementation of dataset creation from infobox ([#19855](https://github.com/apache/superset/issues/19855)) ([ba0c37d](https://github.com/apache/superset/commit/ba0c37d3df85b1af39404af1d578daeb0ff2d278))
|
||||
- improve color consistency (save all labels) ([#19038](https://github.com/apache/superset/issues/19038)) ([dc57508](https://github.com/apache/superset/commit/dc575080d7e43d40b1734bb8f44fdc291cb95b11))
|
||||
- **legacy-preset-chart-deckgl:** Add ,.1f and ,.2f value formats to deckgl charts ([#18945](https://github.com/apache/superset/issues/18945)) ([c56dc8e](https://github.com/apache/superset/commit/c56dc8eace6a71b45240d1bb6768d75661052a2e))
|
||||
- make data tables support html ([#24368](https://github.com/apache/superset/issues/24368)) ([d2b0b8e](https://github.com/apache/superset/commit/d2b0b8eac52ad8b68639c6581a1ed174a593f564))
|
||||
- **viz picker:** Remove some tags, refactor Recommended section ([#27708](https://github.com/apache/superset/issues/27708)) ([c314999](https://github.com/apache/superset/commit/c3149994ac0d4392e0462421b62cd0c034142082))
|
||||
@@ -1,57 +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.
|
||||
-->
|
||||
|
||||
## @superset-ui/legacy-preset-chart-deckgl
|
||||
|
||||
[](https://img.shields.io/npm/v/@superset-ui/legacy-preset-chart-deckgl.svg?style=flat-square)
|
||||
[](https://libraries.io/npm/@superset-ui%2Flegacy-preset-chart-deckgl)
|
||||
|
||||
This plugin provides `deck.gl` for Superset.
|
||||
|
||||
### Usage
|
||||
|
||||
Import the preset and register. This will register all the chart plugins under `deck.gl`.
|
||||
|
||||
```js
|
||||
import { DeckGLChartPreset } from '@superset-ui/legacy-preset-chart-deckgl';
|
||||
|
||||
new DeckGLChartPreset().register();
|
||||
```
|
||||
|
||||
or register charts one by one. Configure `key`, which can be any `string`, and register the plugin. This `key` will be used to lookup this chart throughout the app.
|
||||
|
||||
```js
|
||||
import { ArcChartPlugin } from '@superset-ui/legacy-preset-chart-deckgl';
|
||||
|
||||
new ArcChartPlugin().configure({ key: 'deck_arc' }).register();
|
||||
```
|
||||
|
||||
Then use it via `SuperChart`. See [storybook](https://apache-superset.github.io/superset-ui-plugins-deckgl) for more details.
|
||||
|
||||
```js
|
||||
<SuperChart
|
||||
chartType="deck_arc"
|
||||
width={600}
|
||||
height={600}
|
||||
formData={...}
|
||||
queriesData={[{
|
||||
data: {...},
|
||||
}]}
|
||||
/>
|
||||
```
|
||||
@@ -1,71 +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.
|
||||
*/
|
||||
|
||||
declare module 'deck.gl' {
|
||||
import { Layer, LayerProps } from '@deck.gl/core';
|
||||
|
||||
interface HeatmapLayerProps<T extends object = any> extends LayerProps<T> {
|
||||
id?: string;
|
||||
data?: T[];
|
||||
getPosition?: (d: T) => number[] | null | undefined;
|
||||
getWeight?: (d: T) => number | null | undefined;
|
||||
radiusPixels?: number;
|
||||
colorRange?: number[][];
|
||||
threshold?: number;
|
||||
intensity?: number;
|
||||
aggregation?: string;
|
||||
}
|
||||
|
||||
interface ContourLayerProps<T extends object = any> extends LayerProps<T> {
|
||||
id?: string;
|
||||
data?: T[];
|
||||
getPosition?: (d: T) => number[] | null | undefined;
|
||||
getWeight?: (d: T) => number | null | undefined;
|
||||
contours: {
|
||||
color?: ColorType | undefined;
|
||||
lowerThreshold?: any | undefined;
|
||||
upperThreshold?: any | undefined;
|
||||
strokeWidth?: any | undefined;
|
||||
zIndex?: any | undefined;
|
||||
};
|
||||
cellSize: number;
|
||||
colorRange?: number[][];
|
||||
intensity?: number;
|
||||
aggregation?: string;
|
||||
}
|
||||
|
||||
export class HeatmapLayer<T extends object = any> extends Layer<
|
||||
T,
|
||||
HeatmapLayerProps<T>
|
||||
> {
|
||||
constructor(props: HeatmapLayerProps<T>);
|
||||
}
|
||||
|
||||
export class ContourLayer<T extends object = any> extends Layer<
|
||||
T,
|
||||
ContourLayerProps<T>
|
||||
> {
|
||||
constructor(props: ContourLayerProps<T>);
|
||||
}
|
||||
}
|
||||
|
||||
declare module '*.png' {
|
||||
const value: any;
|
||||
export default value;
|
||||
}
|
||||
@@ -40,7 +40,7 @@ import {
|
||||
GridReadyEvent,
|
||||
GridState,
|
||||
CellClickedEvent,
|
||||
IMenuActionParams,
|
||||
SelectionChangedEvent,
|
||||
} from '@superset-ui/core/components/ThemedAgGridReact';
|
||||
import { t } from '@apache-superset/core/translation';
|
||||
import {
|
||||
@@ -56,6 +56,7 @@ import SearchSelectDropdown from './components/SearchSelectDropdown';
|
||||
import { SearchOption, SortByItem } from '../types';
|
||||
import getInitialSortState, { shouldSort } from '../utils/getInitialSortState';
|
||||
import getInitialFilterModel from '../utils/getInitialFilterModel';
|
||||
import reconcileColumnState from '../utils/reconcileColumnState';
|
||||
import { PAGE_SIZE_OPTIONS } from '../consts';
|
||||
import { getCompleteFilterState } from '../utils/filterStateManager';
|
||||
|
||||
@@ -95,8 +96,9 @@ export interface AgGridTableProps {
|
||||
percentMetrics: string[];
|
||||
serverPageLength: number;
|
||||
hasServerPageLengthChanged: boolean;
|
||||
handleCrossFilter: (event: CellClickedEvent | IMenuActionParams) => void;
|
||||
isActiveFilterValue: (key: string, val: DataRecordValue) => boolean;
|
||||
handleCellClicked: (event: CellClickedEvent) => void;
|
||||
handleSelectionChanged: (event: SelectionChangedEvent) => void;
|
||||
filters?: Record<string, DataRecordValue[]> | null;
|
||||
renderTimeComparisonDropdown: () => JSX.Element | null;
|
||||
cleanedTotals: DataRecord;
|
||||
showTotals: boolean;
|
||||
@@ -134,8 +136,9 @@ const AgGridDataTable: FunctionComponent<AgGridTableProps> = memo(
|
||||
percentMetrics,
|
||||
serverPageLength,
|
||||
hasServerPageLengthChanged,
|
||||
handleCrossFilter,
|
||||
isActiveFilterValue,
|
||||
handleCellClicked,
|
||||
handleSelectionChanged,
|
||||
filters,
|
||||
renderTimeComparisonDropdown,
|
||||
cleanedTotals,
|
||||
showTotals,
|
||||
@@ -421,6 +424,15 @@ const AgGridDataTable: FunctionComponent<AgGridTableProps> = memo(
|
||||
}
|
||||
}, [width]);
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
(!filters || Object.keys(filters).length === 0) &&
|
||||
gridRef.current?.api?.getSelectedRows().length
|
||||
) {
|
||||
gridRef.current.api.deselectAll();
|
||||
}
|
||||
}, [filters]);
|
||||
|
||||
const onGridReady = (params: GridReadyEvent) => {
|
||||
// This will make columns fill the grid width
|
||||
params.api.sizeColumnsToFit();
|
||||
@@ -429,10 +441,17 @@ const AgGridDataTable: FunctionComponent<AgGridTableProps> = memo(
|
||||
// Note: filterModel is now handled via gridInitialState for better performance
|
||||
if (chartState?.columnState && params.api) {
|
||||
try {
|
||||
params.api.applyColumnState?.({
|
||||
state: chartState.columnState as ColumnState[],
|
||||
applyOrder: true,
|
||||
});
|
||||
const reconciledColumnState = reconcileColumnState(
|
||||
chartState.columnState as ColumnState[],
|
||||
colDefsFromProps as ColDef[],
|
||||
);
|
||||
|
||||
if (reconciledColumnState) {
|
||||
params.api.applyColumnState?.({
|
||||
state: reconciledColumnState.columnState,
|
||||
applyOrder: reconciledColumnState.applyOrder,
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
// Silently fail if state restoration fails
|
||||
}
|
||||
@@ -492,7 +511,8 @@ const AgGridDataTable: FunctionComponent<AgGridTableProps> = memo(
|
||||
onColumnGroupOpened={params => params.api.sizeColumnsToFit()}
|
||||
rowSelection="multiple"
|
||||
animateRows
|
||||
onCellClicked={handleCrossFilter}
|
||||
onCellClicked={handleCellClicked}
|
||||
onSelectionChanged={handleSelectionChanged}
|
||||
onFilterChanged={handleFilterChanged}
|
||||
onStateUpdated={handleGridStateChange}
|
||||
initialState={gridInitialState}
|
||||
@@ -584,7 +604,6 @@ const AgGridDataTable: FunctionComponent<AgGridTableProps> = memo(
|
||||
initialSortState: getInitialSortState(
|
||||
serverPaginationData?.sortBy || [],
|
||||
),
|
||||
isActiveFilterValue,
|
||||
lastFilteredColumn: serverPaginationData?.lastFilteredColumn,
|
||||
lastFilteredInputPosition:
|
||||
serverPaginationData?.lastFilteredInputPosition,
|
||||
|
||||
@@ -23,12 +23,12 @@ import {
|
||||
getTimeFormatterForGranularity,
|
||||
} from '@superset-ui/core';
|
||||
import { GenericDataType } from '@apache-superset/core/common';
|
||||
import { useCallback, useEffect, useState, useMemo } from 'react';
|
||||
import { useCallback, useEffect, useRef, useState, useMemo } from 'react';
|
||||
import { isEqual } from 'lodash';
|
||||
|
||||
import {
|
||||
CellClickedEvent,
|
||||
IMenuActionParams,
|
||||
SelectionChangedEvent,
|
||||
} from '@superset-ui/core/components/ThemedAgGridReact';
|
||||
import {
|
||||
AgGridTableChartTransformedProps,
|
||||
@@ -40,7 +40,7 @@ import AgGridDataTable from './AgGridTable';
|
||||
import { updateTableOwnState } from './utils/externalAPIs';
|
||||
import TimeComparisonVisibility from './AgGridTable/components/TimeComparisonVisibility';
|
||||
import { useColDefs } from './utils/useColDefs';
|
||||
import { getCrossFilterDataMask } from './utils/getCrossFilterDataMask';
|
||||
import { buildSelectionCrossFilterDataMask } from './utils/getCrossFilterDataMask';
|
||||
import { StyledChartContainer } from './styles';
|
||||
import type { FilterState } from './utils/filterStateManager';
|
||||
|
||||
@@ -248,7 +248,14 @@ export default function TableChart<D extends DataRecord = DataRecord>(
|
||||
|
||||
const isActiveFilterValue = useCallback(
|
||||
function isActiveFilterValue(key: string, val: DataRecordValue) {
|
||||
return !!filters && filters[key]?.includes(val);
|
||||
if (!filters || !filters[key]) return false;
|
||||
return filters[key].some(filterVal => {
|
||||
if (filterVal === val) return true;
|
||||
if (filterVal instanceof Date && val instanceof Date) {
|
||||
return filterVal.getTime() === val.getTime();
|
||||
}
|
||||
return false;
|
||||
});
|
||||
},
|
||||
[filters],
|
||||
);
|
||||
@@ -263,37 +270,68 @@ export default function TableChart<D extends DataRecord = DataRecord>(
|
||||
[timeGrain, isRawRecords],
|
||||
);
|
||||
|
||||
const toggleFilter = useCallback(
|
||||
(event: CellClickedEvent | IMenuActionParams) => {
|
||||
const activeColumnRef = useRef<string | null>(null);
|
||||
|
||||
const handleCellClicked = useCallback(
|
||||
(event: CellClickedEvent) => {
|
||||
if (!emitCrossFilters || !event.column) return;
|
||||
const colDef = event.column.getColDef();
|
||||
if (colDef.context?.isMetric || colDef.context?.isPercentMetric) return;
|
||||
|
||||
const key = event.column.getColId();
|
||||
activeColumnRef.current = key;
|
||||
|
||||
// Re-click on already-filtered single selection → untoggle
|
||||
// AG Grid doesn't change selection when re-clicking the same row,
|
||||
// so onSelectionChanged won't fire — handle clear directly here
|
||||
const selectedNodes = event.api.getSelectedNodes();
|
||||
if (
|
||||
emitCrossFilters &&
|
||||
event.column &&
|
||||
!(
|
||||
event.column.getColDef().context?.isMetric ||
|
||||
event.column.getColDef().context?.isPercentMetric
|
||||
)
|
||||
selectedNodes.length === 1 &&
|
||||
selectedNodes[0] === event.node &&
|
||||
isActiveFilterValue(key, event.value)
|
||||
) {
|
||||
const crossFilterProps = {
|
||||
key: event.column.getColId(),
|
||||
value: event.value,
|
||||
filters,
|
||||
timeGrain,
|
||||
isActiveFilterValue,
|
||||
timestampFormatter,
|
||||
};
|
||||
setDataMask(getCrossFilterDataMask(crossFilterProps).dataMask);
|
||||
event.node.setSelected(false);
|
||||
setDataMask(
|
||||
buildSelectionCrossFilterDataMask({
|
||||
key,
|
||||
values: [],
|
||||
timeGrain,
|
||||
timestampFormatter,
|
||||
}).dataMask,
|
||||
);
|
||||
}
|
||||
},
|
||||
[
|
||||
emitCrossFilters,
|
||||
setDataMask,
|
||||
filters,
|
||||
timeGrain,
|
||||
isActiveFilterValue,
|
||||
setDataMask,
|
||||
timeGrain,
|
||||
timestampFormatter,
|
||||
],
|
||||
);
|
||||
|
||||
const handleSelectionChanged = useCallback(
|
||||
(event: SelectionChangedEvent) => {
|
||||
if (!emitCrossFilters || !activeColumnRef.current) return;
|
||||
|
||||
const key = activeColumnRef.current;
|
||||
const selectedRows = event.api.getSelectedRows();
|
||||
const values = selectedRows
|
||||
.map(row => row[key] as DataRecordValue)
|
||||
.filter(v => v != null);
|
||||
|
||||
setDataMask(
|
||||
buildSelectionCrossFilterDataMask({
|
||||
key,
|
||||
values,
|
||||
timeGrain,
|
||||
timestampFormatter,
|
||||
}).dataMask,
|
||||
);
|
||||
},
|
||||
[emitCrossFilters, setDataMask, timeGrain, timestampFormatter],
|
||||
);
|
||||
|
||||
const handleServerPaginationChange = useCallback(
|
||||
(pageNumber: number, pageSize: number) => {
|
||||
const modifiedOwnState = {
|
||||
@@ -395,11 +433,12 @@ export default function TableChart<D extends DataRecord = DataRecord>(
|
||||
onFilterChanged={handleFilterChanged}
|
||||
metricColumns={metricColumns}
|
||||
id={slice_id}
|
||||
handleCrossFilter={toggleFilter}
|
||||
handleCellClicked={handleCellClicked}
|
||||
handleSelectionChanged={handleSelectionChanged}
|
||||
filters={filters}
|
||||
percentMetrics={percentMetrics}
|
||||
serverPageLength={serverPageLength}
|
||||
hasServerPageLengthChanged={hasServerPageLengthChanged}
|
||||
isActiveFilterValue={isActiveFilterValue}
|
||||
renderTimeComparisonDropdown={
|
||||
isUsingTimeComparison ? renderTimeComparisonVisibility : () => null
|
||||
}
|
||||
|
||||
@@ -238,12 +238,11 @@ const buildQuery: BuildQuery<TableChartFormData> = (
|
||||
});
|
||||
|
||||
if (matchingColumn) {
|
||||
if (
|
||||
typeof matchingColumn === 'object' &&
|
||||
'sqlExpression' in matchingColumn
|
||||
) {
|
||||
return matchingColumn.sqlExpression;
|
||||
}
|
||||
// Return the label, not the raw sqlExpression. The backend
|
||||
// (helpers.py get_sqla_query) resolves orderby strings by
|
||||
// matching adhoc column labels, then uses adhoc_column_to_sqla
|
||||
// to emit the actual SQL expression into ORDER BY — so this
|
||||
// is dialect-safe across all database engines.
|
||||
return getColumnLabel(matchingColumn);
|
||||
}
|
||||
|
||||
|
||||
@@ -27,15 +27,11 @@ type GetCellClassParams = CellClassParams & {
|
||||
|
||||
const getCellClass = (params: GetCellClassParams) => {
|
||||
const { col, emitCrossFilters } = params;
|
||||
const isActiveFilterValue = params?.context?.isActiveFilterValue;
|
||||
let className = '';
|
||||
if (emitCrossFilters) {
|
||||
if (!col?.isMetric) {
|
||||
className += ' dt-is-filter';
|
||||
}
|
||||
if (isActiveFilterValue?.(col?.key, params?.value)) {
|
||||
className += ' dt-is-active-filter';
|
||||
}
|
||||
if (col?.config?.truncateLongCells) {
|
||||
className += ' dt-truncate-cell';
|
||||
}
|
||||
|
||||
@@ -34,6 +34,55 @@ type GetCrossFilterDataMaskProps = {
|
||||
timestampFormatter: (value: DataRecordValue) => string;
|
||||
};
|
||||
|
||||
type BuildSelectionCrossFilterProps = {
|
||||
key: string;
|
||||
values: DataRecordValue[];
|
||||
timeGrain?: TimeGranularity;
|
||||
timestampFormatter: (value: DataRecordValue) => string;
|
||||
};
|
||||
|
||||
export const buildSelectionCrossFilterDataMask = ({
|
||||
key,
|
||||
values,
|
||||
timeGrain,
|
||||
timestampFormatter,
|
||||
}: BuildSelectionCrossFilterProps) => {
|
||||
if (values.length === 0) {
|
||||
return {
|
||||
dataMask: {
|
||||
extraFormData: { filters: [] },
|
||||
filterState: { label: null, value: null, filters: null },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const updatedFilters: DataRecordFilters = { [key]: values };
|
||||
const isTimestamp = key === DTTM_ALIAS;
|
||||
const label = values
|
||||
.map(v => (isTimestamp ? timestampFormatter(v) : v))
|
||||
.join(', ');
|
||||
|
||||
return {
|
||||
dataMask: {
|
||||
extraFormData: {
|
||||
filters: [
|
||||
{
|
||||
col: key,
|
||||
op: 'IN' as const,
|
||||
val: values.map(el => (el instanceof Date ? el.getTime() : el!)),
|
||||
grain: isTimestamp ? timeGrain : undefined,
|
||||
},
|
||||
],
|
||||
},
|
||||
filterState: {
|
||||
label,
|
||||
value: [values],
|
||||
filters: updatedFilters,
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export const getCrossFilterDataMask = ({
|
||||
key,
|
||||
value,
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
/**
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
import {
|
||||
type ColDef,
|
||||
type ColumnState,
|
||||
} from '@superset-ui/core/components/ThemedAgGridReact';
|
||||
import reconcileColumnState, { getLeafColumnIds } from './reconcileColumnState';
|
||||
|
||||
test('getLeafColumnIds flattens grouped column defs in visual order', () => {
|
||||
const colDefs: ColDef[] = [
|
||||
{ field: 'Manufacture_Date' },
|
||||
{
|
||||
headerName: 'Metrics',
|
||||
children: [
|
||||
{ field: 'SUM(Sales_Amount)' },
|
||||
{ field: 'SUM(Discount_Applied)' },
|
||||
],
|
||||
} as ColDef,
|
||||
{ field: 'SUM(Quantity_Sold)' },
|
||||
];
|
||||
|
||||
expect(getLeafColumnIds(colDefs)).toEqual([
|
||||
'Manufacture_Date',
|
||||
'SUM(Sales_Amount)',
|
||||
'SUM(Discount_Applied)',
|
||||
'SUM(Quantity_Sold)',
|
||||
]);
|
||||
});
|
||||
|
||||
test('preserves saved order when the current column set is unchanged', () => {
|
||||
const colDefs: ColDef[] = [
|
||||
{ field: 'Transaction_Timestamp' },
|
||||
{ field: 'SUM(Sales_Amount)' },
|
||||
{ field: 'SUM(Discount_Applied)' },
|
||||
];
|
||||
const savedColumnState: ColumnState[] = [
|
||||
{ colId: 'SUM(Sales_Amount)' },
|
||||
{ colId: 'Transaction_Timestamp' },
|
||||
{ colId: 'SUM(Discount_Applied)' },
|
||||
];
|
||||
|
||||
expect(reconcileColumnState(savedColumnState, colDefs)).toEqual({
|
||||
applyOrder: true,
|
||||
columnState: savedColumnState,
|
||||
});
|
||||
});
|
||||
|
||||
test('drops stale order when a dynamic group by swaps the dimension column', () => {
|
||||
const currentColDefs: ColDef[] = [
|
||||
{ field: 'Manufacture_Date' },
|
||||
{ field: 'SUM(Sales_Amount)' },
|
||||
{ field: 'SUM(Discount_Applied)' },
|
||||
{ field: 'SUM(Quantity_Sold)' },
|
||||
];
|
||||
const savedColumnState: ColumnState[] = [
|
||||
{ colId: 'Transaction_Timestamp' },
|
||||
{ colId: 'SUM(Sales_Amount)' },
|
||||
{ colId: 'SUM(Discount_Applied)' },
|
||||
{ colId: 'SUM(Quantity_Sold)' },
|
||||
];
|
||||
|
||||
expect(reconcileColumnState(savedColumnState, currentColDefs)).toEqual({
|
||||
applyOrder: false,
|
||||
columnState: [
|
||||
{ colId: 'SUM(Sales_Amount)' },
|
||||
{ colId: 'SUM(Discount_Applied)' },
|
||||
{ colId: 'SUM(Quantity_Sold)' },
|
||||
],
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
/**
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
import {
|
||||
type ColDef,
|
||||
type ColumnState,
|
||||
} from '@superset-ui/core/components/ThemedAgGridReact';
|
||||
|
||||
type ColumnGroupDef = ColDef & {
|
||||
children?: ColumnDefLike[];
|
||||
};
|
||||
|
||||
type ColumnDefLike = ColDef | ColumnGroupDef;
|
||||
|
||||
function hasChildren(colDef: ColumnDefLike): colDef is ColumnGroupDef {
|
||||
return 'children' in colDef;
|
||||
}
|
||||
|
||||
export interface ReconciledColumnState {
|
||||
applyOrder: boolean;
|
||||
columnState: ColumnState[];
|
||||
}
|
||||
|
||||
export function getLeafColumnIds(colDefs: ColumnDefLike[]): string[] {
|
||||
return colDefs.flatMap(colDef => {
|
||||
if (
|
||||
hasChildren(colDef) &&
|
||||
Array.isArray(colDef.children) &&
|
||||
colDef.children.length > 0
|
||||
) {
|
||||
return getLeafColumnIds(colDef.children);
|
||||
}
|
||||
|
||||
return typeof colDef.field === 'string' ? [colDef.field] : [];
|
||||
});
|
||||
}
|
||||
|
||||
export default function reconcileColumnState(
|
||||
savedColumnState: ColumnState[] | undefined,
|
||||
colDefs: ColumnDefLike[],
|
||||
): ReconciledColumnState | null {
|
||||
if (!Array.isArray(savedColumnState) || savedColumnState.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const currentColumnIds = getLeafColumnIds(colDefs);
|
||||
const currentColumnIdSet = new Set(currentColumnIds);
|
||||
const filteredColumnState = savedColumnState.filter(
|
||||
column =>
|
||||
typeof column.colId === 'string' && currentColumnIdSet.has(column.colId),
|
||||
);
|
||||
|
||||
if (filteredColumnState.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const savedColumnIdSet = new Set(
|
||||
filteredColumnState.map(column => column.colId),
|
||||
);
|
||||
const hasSameColumnSet =
|
||||
currentColumnIds.length === savedColumnIdSet.size &&
|
||||
currentColumnIds.every(columnId => savedColumnIdSet.has(columnId));
|
||||
|
||||
return {
|
||||
columnState: filteredColumnState,
|
||||
applyOrder: hasSameColumnSet,
|
||||
};
|
||||
}
|
||||
@@ -90,7 +90,7 @@ describe('plugin-chart-ag-grid-table', () => {
|
||||
},
|
||||
).queries[0];
|
||||
|
||||
expect(query.orderby).toEqual([['degree_type', true]]);
|
||||
expect(query.orderby).toEqual([['Highest Degree', true]]);
|
||||
});
|
||||
|
||||
test('should map string metric colId to backend identifier', () => {
|
||||
@@ -267,6 +267,25 @@ describe('plugin-chart-ag-grid-table', () => {
|
||||
]);
|
||||
});
|
||||
|
||||
test('should use label (not sqlExpression) for adhoc column in CSV export sortModel', () => {
|
||||
const adhocColumn = createAdhocColumn('sales / 100', 'Margin');
|
||||
|
||||
const query = buildQuery(
|
||||
{
|
||||
...basicFormData,
|
||||
groupby: [adhocColumn],
|
||||
result_format: 'csv',
|
||||
},
|
||||
{
|
||||
ownState: {
|
||||
sortModel: [{ colId: 'Margin', sort: 'desc' }],
|
||||
},
|
||||
},
|
||||
).queries[0];
|
||||
|
||||
expect(query.orderby?.[0]).toEqual(['Margin', false]);
|
||||
});
|
||||
|
||||
test('should not add tie-breaker for non-download queries with server pagination', () => {
|
||||
const query = buildQuery(
|
||||
{
|
||||
|
||||
@@ -273,18 +273,28 @@ function Echart(
|
||||
);
|
||||
|
||||
const notMerge = !isDashboardRefreshing;
|
||||
if (!notMerge) {
|
||||
chartRef.current?.dispatchAction({ type: 'hideTip' });
|
||||
}
|
||||
chartRef.current?.dispatchAction({ type: 'hideTip' });
|
||||
chartRef.current?.setOption(themedEchartOptions, {
|
||||
notMerge,
|
||||
replaceMerge: notMerge ? undefined : ['series'],
|
||||
lazyUpdate: isDashboardRefreshing,
|
||||
// lazyUpdate defers render, causing tooltip crashes on stale shapes (#39247)
|
||||
lazyUpdate: false,
|
||||
});
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps -- isDashboardRefreshing intentionally excluded to prevent extra setOption calls
|
||||
}, [didMount, echartOptions, eventHandlers, zrEventHandlers, theme, vizType]);
|
||||
|
||||
// Clear tooltip on refresh start to avoid stale content (#39247)
|
||||
useEffect(() => {
|
||||
if (didMount && isDashboardRefreshing && chartRef.current) {
|
||||
chartRef.current.dispatchAction({ type: 'hideTip' });
|
||||
chartRef.current.dispatchAction({
|
||||
type: 'updateAxisPointer',
|
||||
currTrigger: 'leave',
|
||||
});
|
||||
}
|
||||
}, [didMount, isDashboardRefreshing]);
|
||||
|
||||
useEffect(() => () => chartRef.current?.dispose(), []);
|
||||
|
||||
// highlighting
|
||||
|
||||
@@ -29,7 +29,8 @@ import { Refs } from '../types';
|
||||
|
||||
export function getDefaultTooltip(refs: Refs) {
|
||||
return {
|
||||
appendToBody: true,
|
||||
appendToBody:
|
||||
typeof document !== 'undefined' ? !document.fullscreenElement : true,
|
||||
borderColor: 'transparent',
|
||||
// CSS hack applied on this class to resolve https://github.com/apache/superset/issues/30058
|
||||
className: 'echarts-tooltip',
|
||||
|
||||
@@ -16,67 +16,66 @@
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
import { QueryFormData } from '@superset-ui/core';
|
||||
import { isPostProcessingRank, QueryFormData } from '@superset-ui/core';
|
||||
import buildQuery from '../../src/Heatmap/buildQuery';
|
||||
|
||||
describe('Heatmap buildQuery - Rank Operation for Normalized Field', () => {
|
||||
const baseFormData = {
|
||||
datasource: '5__table',
|
||||
granularity_sqla: 'ds',
|
||||
metric: 'count',
|
||||
x_axis: 'category',
|
||||
groupby: ['region'],
|
||||
viz_type: 'heatmap',
|
||||
} as QueryFormData;
|
||||
const baseFormData = {
|
||||
datasource: '5__table',
|
||||
granularity_sqla: 'ds',
|
||||
metric: 'count',
|
||||
x_axis: 'category',
|
||||
groupby: ['region'],
|
||||
viz_type: 'heatmap',
|
||||
} as QueryFormData;
|
||||
|
||||
test('should ALWAYS include rank operation when normalized=true', () => {
|
||||
const formData = {
|
||||
...baseFormData,
|
||||
normalized: true,
|
||||
};
|
||||
const getQuery = (formData: QueryFormData) => buildQuery(formData).queries[0];
|
||||
const getRankOperation = (formData: QueryFormData) =>
|
||||
getQuery(formData).post_processing?.find(isPostProcessingRank);
|
||||
|
||||
const queryContext = buildQuery(formData);
|
||||
const [query] = queryContext.queries;
|
||||
|
||||
const rankOperation = query.post_processing?.find(
|
||||
op => op?.operation === 'rank',
|
||||
);
|
||||
|
||||
expect(rankOperation).toBeDefined();
|
||||
expect(rankOperation?.operation).toBe('rank');
|
||||
test('adds X axis orderby when sorting alphabetically ascending', () => {
|
||||
const query = getQuery({
|
||||
...baseFormData,
|
||||
sort_x_axis: 'alpha_asc',
|
||||
});
|
||||
|
||||
test('should ALWAYS include rank operation when normalized=false', () => {
|
||||
const formData = {
|
||||
...baseFormData,
|
||||
normalized: false,
|
||||
};
|
||||
|
||||
const queryContext = buildQuery(formData);
|
||||
const [query] = queryContext.queries;
|
||||
|
||||
const rankOperation = query.post_processing?.find(
|
||||
op => op?.operation === 'rank',
|
||||
);
|
||||
|
||||
expect(rankOperation).toBeDefined();
|
||||
expect(rankOperation?.operation).toBe('rank');
|
||||
});
|
||||
|
||||
test('should ALWAYS include rank operation when normalized is undefined', () => {
|
||||
const formData = {
|
||||
...baseFormData,
|
||||
// normalized not set
|
||||
};
|
||||
|
||||
const queryContext = buildQuery(formData);
|
||||
const [query] = queryContext.queries;
|
||||
|
||||
const rankOperation = query.post_processing?.find(
|
||||
op => op?.operation === 'rank',
|
||||
);
|
||||
|
||||
expect(rankOperation).toBeDefined();
|
||||
expect(rankOperation?.operation).toBe('rank');
|
||||
});
|
||||
expect(query.orderby).toEqual([['category', true]]);
|
||||
});
|
||||
|
||||
test('adds Y axis orderby when sorting alphabetically descending', () => {
|
||||
const query = getQuery({
|
||||
...baseFormData,
|
||||
sort_y_axis: 'alpha_desc',
|
||||
});
|
||||
|
||||
expect(query.orderby).toEqual([['region', false]]);
|
||||
});
|
||||
|
||||
test('should ALWAYS include rank operation when normalized=true', () => {
|
||||
const rankOperation = getRankOperation({
|
||||
...baseFormData,
|
||||
normalized: true,
|
||||
});
|
||||
|
||||
expect(rankOperation).toBeDefined();
|
||||
expect(rankOperation?.operation).toBe('rank');
|
||||
});
|
||||
|
||||
test('should ALWAYS include rank operation when normalized=false', () => {
|
||||
const rankOperation = getRankOperation({
|
||||
...baseFormData,
|
||||
normalized: false,
|
||||
});
|
||||
|
||||
expect(rankOperation).toBeDefined();
|
||||
expect(rankOperation?.operation).toBe('rank');
|
||||
});
|
||||
|
||||
test('should ALWAYS include rank operation when normalized is undefined', () => {
|
||||
const rankOperation = getRankOperation({
|
||||
...baseFormData,
|
||||
// normalized not set
|
||||
});
|
||||
|
||||
expect(rankOperation).toBeDefined();
|
||||
expect(rankOperation?.operation).toBe('rank');
|
||||
});
|
||||
|
||||