Compare commits

..

16 Commits

Author SHA1 Message Date
Elizabeth Thompson
7186f92d38 test: add comprehensive unhappy path tests for export
Add tests for error scenarios including:
- Network errors and logging
- 404 errors when resource not found
- Empty response handling
- Download failure with proper cleanup
- Malformed Content-Disposition header
- Missing headers fallback
- Empty IDs array edge case

These tests ensure proper error handling and cleanup in all failure modes.
2025-10-17 11:47:04 -07:00
Elizabeth Thompson
513fc30bb5 style: fix prettier formatting and add eslint-disable comment
- Auto-format ChartTable.test.tsx with prettier
- Add eslint-disable comment for jest-dom/prefer-to-have-style in export.test.ts
  since toHaveStyle is not available without React Testing Library
2025-10-09 17:41:38 -07:00
Elizabeth Thompson
4a94a4c387 test: use direct style property check in export test
Replace toHaveStyle() with direct style.display check since this test
doesn't use React Testing Library and toHaveStyle is not available.
2025-10-09 17:27:50 -07:00
Elizabeth Thompson
8a6461816a style: fix prettier formatting in ChartTable test 2025-10-09 17:26:46 -07:00
Elizabeth Thompson
0b251d80fa test: move jest.mock to module level in ChartTable test
Move the export mock from inside the test body to module level to match
the correct pattern used in DashboardTable.test.tsx. This ensures the
mock is properly hoisted and consistently applied.

Also add verification that export is called with correct chart ID.

Addresses code review feedback from @joe in PR #35584.
2025-10-09 17:26:24 -07:00
Elizabeth Thompson
efe10ecebe style: fix linting errors in test files
- Fix import order in DashboardTable.test.tsx
- Remove unnecessary block statement in ChartTable.test.tsx
- Use toHaveStyle matcher in export.test.ts
2025-10-09 17:11:14 -07:00
Elizabeth Thompson
6c11c49524 test: fix DashboardTable export test with proper mock
- Mock export function at module level instead of inside test
- Add delay to mock implementation to ensure spinner appears
- Use waitFor to check for spinner appearance asynchronously
- Verify export is called with correct dashboard ID
2025-10-09 16:51:47 -07:00
Elizabeth Thompson
9afd7609a5 test: fix export test assertions
- Replace toHaveStyle() with direct style.display check in export.test.ts
- Add can_export permission to ChartTable test mock to enable Export menu option
2025-10-09 15:46:11 -07:00
Elizabeth Thompson
18a325a4eb test: fix revokeObjectURL mock in export tests
Add conditional creation of window.URL.revokeObjectURL in test setup
since it doesn't exist in Jest's JSDOM environment. This prevents
'Property revokeObjectURL does not exist' errors during test execution.
2025-10-09 15:28:27 -07:00
Elizabeth Thompson
c1f9541640 style: fix prettier and jest-dom linting errors in export test
- Fix line breaks in spyOn calls to match prettier formatting
- Replace direct style assertion with toHaveStyle matcher
- Improves test readability and follows jest-dom best practices

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-09 13:39:05 -07:00
Elizabeth Thompson
22afa0448f test: add comprehensive export tests for ChartTable and DashboardTable
Add integration tests that verify:
- Export button triggers the export flow
- Loading spinner appears during export operation
- Spinner disappears after export completes
- Export functionality works end-to-end in table views

These tests fill a testing gap by ensuring the export button
interaction and loading states work correctly in the home page tables.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-09 13:37:21 -07:00
Elizabeth Thompson
da61031603 fix: remove jest.requireMock to resolve eslint error
Replace dynamic require with static import of logging from @superset-ui/core
to fix global-require and @typescript-eslint/no-var-requires linting errors.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-09 11:58:17 -07:00
Elizabeth Thompson
252f306a30 refactor(export): address korbit-ai code review suggestions
Implement improvements suggested by korbit-ai code review:

1. Extract download logic into separate `downloadBlob()` utility function
   - Improves code reusability and testability
   - Better separation of concerns

2. Add memory safety check for large exports
   - Warn when Content-Length exceeds 100MB limit
   - Helps prevent browser memory issues with large files
   - Note: We cannot fallback to window.location.href as suggested,
     since that would reintroduce the CSP violation this PR fixes

3. Optimize DOM manipulation to prevent layout thrashing
   - Use display: 'none' on anchor element
   - Avoids triggering unnecessary layout calculations

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-09 11:11:05 -07:00
Elizabeth Thompson
c9003b6697 style: fix eslint and prettier violations in export tests
Fix linting errors in export test file and DashboardList:
- Remove 'describe' block (use test() instead per conventions)
- Fix prettier formatting issues
- Replace require() with import statements
- Remove await-in-loop by testing sequentially
- Fix multi-line function parameter formatting

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-09 10:59:42 -07:00
Elizabeth Thompson
4d5c78953c test(export): add comprehensive tests for blob-based export functionality
Add unit tests for the new fetch-based export utility to ensure:
- Correct API endpoint construction and headers
- Proper blob download and DOM manipulation
- Content-Disposition header parsing with fallbacks
- Error handling for API and blob conversion failures
- Cleanup of blob URLs and DOM elements
- Support for multiple resource types and IDs

Tests cover success paths, error cases, and edge cases like
malformed headers and missing Content-Disposition.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-09 10:38:13 -07:00
Elizabeth Thompson
001cccac54 fix(export): replace iframe with fetch to avoid CSP frame-src violations
Replace iframe-based resource export with fetch API and blob downloads
to prevent Content Security Policy frame-src violations.

Changes:
- Update handleResourceExport() to use SupersetClient.get() with blob response
- Parse Content-Disposition headers for proper filenames
- Implement programmatic download using blob URLs
- Add proper async/await error handling in all export handlers
- Add user-friendly error messages on export failures

This approach:
- Eliminates CSP frame-src violations
- Provides better error handling and user feedback
- Follows the same pattern as dashboard screenshot downloads
- Works with strict Content Security Policies

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-09 10:35:58 -07:00
125 changed files with 2773 additions and 10159 deletions

View File

@@ -41,7 +41,7 @@ jobs:
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v4
uses: github/codeql-action/init@v3
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
@@ -53,6 +53,6 @@ jobs:
- name: Perform CodeQL Analysis
if: steps.check.outputs.python || steps.check.outputs.frontend
uses: github/codeql-action/analyze@v4
uses: github/codeql-action/analyze@v3
with:
category: "/language:${{matrix.language}}"

View File

@@ -49,7 +49,6 @@ are compatible with Superset.
| [Apache Pinot](/docs/configuration/databases#apache-pinot) | `pip install pinotdb` | `pinot://BROKER:5436/query?server=http://CONTROLLER:5983/` |
| [Apache Solr](/docs/configuration/databases#apache-solr) | `pip install sqlalchemy-solr` | `solr://{username}:{password}@{hostname}:{port}/{server_path}/{collection}` |
| [Apache Spark SQL](/docs/configuration/databases#apache-spark-sql) | `pip install pyhive` | `hive://hive@{hostname}:{port}/{database}` |
| [Arc (Basekick Labs)](/docs/configuration/databases#arc) | `pip install arc-superset-dialect` | `arc://{api_key}@{hostname}:{port}/{database}` |
| [Ascend.io](/docs/configuration/databases#ascendio) | `pip install impyla` | `ascend://{username}:{password}@{hostname}:{port}/{database}?auth_mechanism=PLAIN;use_ssl=true` |
| [Azure MS SQL](/docs/configuration/databases#sql-server) | `pip install pymssql` | `mssql+pymssql://UserName@presetSQL:TestPassword@presetSQL.database.windows.net:1433/TestSchema` |
| [ClickHouse](/docs/configuration/databases#clickhouse) | `pip install clickhouse-connect` | `clickhousedb://{username}:{password}@{hostname}:{port}/{database}` |
@@ -1257,20 +1256,6 @@ The expected connection string is formatted as follows:
hive://hive@{hostname}:{port}/{database}
```
#### Arc
The recommended connector library is [arc-superset-dialect](https://pypi.org/project/arc-superset-dialect/). Install with `pip install arc-superset-dialect`.
The connection string looks like:
```
arc://{api_key}@{hostname}:{port}/{database}
```
##### Multi-Database Support
Arc supports multiple databases (schemas) within a single instance. In Superset, each Arc database appears as a schema in the SQL Lab, and cross-database queries are supported using `database.table` syntax.
#### SQL Server
The recommended connector library for SQL Server is [pymssql](https://github.com/pymssql/pymssql).

View File

@@ -1,174 +0,0 @@
---
title: Securing Your Superset Installation for Production
sidebar_position: 3
---
> *This guide applies to Apache Superset version 4.0 and later and is an evolving set of best practices that administrators should adapt to their specific deployment architecture.*
The default Apache Superset configuration is optimized for ease of use and development, not for security. For any production deployment, it is **critical** that you review and apply the following security configurations to harden your instance, protect user data, and prevent unauthorized access.
This guide provides a comprehensive checklist of essential security configurations and best practices.
### **Critical Prerequisites: HTTPS/TLS Configuration**
Running Superset without HTTPS (TLS) is not secure. Without it, all network traffic—including user credentials, session tokens, and sensitive data—is sent in cleartext and can be easily intercepted.
* **Use a Reverse Proxy:** Your Superset instance should always be deployed behind a reverse proxy (e.g., Nginx, Traefik) or a load balancer (e.g., AWS ALB, Google Cloud Load Balancer) that is configured to handle HTTPS termination.
* **Enforce Modern TLS:** Configure your proxy to enforce TLS 1.2 or higher with strong, industry-standard cipher suites.
* **Implement HSTS:** Use the HTTP Strict Transport Security (HSTS) header to ensure browsers only connect to your Superset instance over HTTPS. This can be configured in your reverse proxy or within Superset's Talisman settings.
### **`SUPERSET_SECRET_KEY` Management (CRITICAL)**
This is the most critical security setting for your Superset instance. It is used to sign all session cookies and encrypt sensitive information in the metadata database, such as database connection credentials.
* **Generate a Unique, Strong Key:** A unique key must be generated for every Superset instance. Use a cryptographically secure method to create it.
```bash
# Example using openssl to generate a strong key
openssl rand -base64 42
```
* **Store the Key Securely:** The key must be kept confidential. The recommended approach is to store it as an environment variable or in a secrets management system (e.g., AWS Secrets Manager, HashiCorp Vault). **Do not hardcode the key in `superset_config.py` or commit it to version control.**
```python
# In superset_config.py
import os
SECRET_KEY = os.environ.get('SUPERSET_SECRET_KEY')
```
> #### ⚠️ Warning: Your `SUPERSET_SECRET_KEY` Must Be Unique
>
> **NEVER** reuse the same `SUPERSET_SECRET_KEY` across different environments (e.g., development, staging, production) or different Superset instances. Reusing a key allows cryptographically signed session cookies to be used across those instances, which can lead to a full authentication bypass if a cookie is compromised. Treat this key like a master password.
### **Session Management Security (CRITICAL)**
Properly configuring user sessions is essential to prevent session hijacking and ensure that sessions are terminated correctly.
#### **Use a Server-Side Session Backend (Strongly Recommended for Production)**
The default stateless cookie-based session handling presents challenges for immediate session invalidation upon logout. For all production deployments, we strongly recommend configuring an optional server-side session backend like Redis, Memcached, or a database. This ensures that session data is stored securely on the server and can be instantly destroyed upon logout, rendering any copied session cookies immediately useless.
**Example `superset_config.py` for Redis:**
```python
# superset_config.py
from redis import Redis
import os
# 1. Enable server-side sessions
SESSION_SERVER_SIDE = True
# 2. Choose your backend (e.g., 'redis', 'memcached', 'filesystem', 'sqlalchemy')
SESSION_TYPE = 'redis'
# 3. Configure your Redis connection
# Use environment variables for sensitive details
SESSION_REDIS = Redis(
host=os.environ.get('REDIS_HOST', 'localhost'),
port=int(os.environ.get('REDIS_PORT', 6379)),
password=os.environ.get('REDIS_PASSWORD'),
db=int(os.environ.get('REDIS_DB', 0)),
ssl=os.environ.get('REDIS_SSL_ENABLED', 'True').lower() == 'true',
ssl_cert_reqs='required' # Or another appropriate SSL setting
)
# 4. Ensure the session cookie is signed for integrity
SESSION_USE_SIGNER = True
```
#### **Configure Session Lifetime and Cookie Security Flags**
This is mandatory for *all* deployments, whether stateless or server-side.
```python
# superset_config.py
from datetime import timedelta
# Set a short absolute session timeout
# The default is 31 days, which is NOT recommended for production.
PERMANENT_SESSION_LIFETIME = timedelta(hours=8)
# Enforce secure cookie flags to prevent browser-based attacks
SESSION_COOKIE_SECURE = True # Transmit cookie only over HTTPS
SESSION_COOKIE_HTTPONLY = True # Prevent client-side JS from accessing the cookie
SESSION_COOKIE_SAMESITE = 'Lax' # Provide protection against CSRF attacks
```
> ##### Note on iFrame Embedding and `SESSION_COOKIE_SAMESITE`
>The recommended default setting `'Lax'` provides good CSRF protection for most use cases. However, if you need to embed Superset dashboards into other applications using an iFrame, you will need to change this setting to `'None'`.
SESSION_COOKIE_SAMESITE = 'None'
Setting SameSite to 'None' requires that SESSION_COOKIE_SECURE is also set to True. Be aware that this configuration disables some of the browser's built-in CSRF protections to allow for cross-domain functionality, so it should only be used when iFrame embedding is necessary.
### **Authentication and Authorization**
While Superset's built-in database authentication is convenient, for production it's highly recommended to integrate with an enterprise-grade identity provider (IdP).
* **Use an Enterprise IdP:** Configure authentication via OAuth or LDAP to leverage your organization's existing identity management system. This provides benefits like Single Sign-On (SSO), Multi-Factor Authentication (MFA), and centralized user provisioning/deprovisioning.
* **Principle of Least Privilege:** Assign users to the most restrictive roles necessary for their jobs. Avoid over-provisioning users with Admin or Alpha roles, and ensure row-level security is applied where appropriate.
* **Admin Accounts:** Delete or disable the default admin user after a new administrative account has been configured.
### **Content Security Policy (CSP) and Other Headers**
Superset can use Flask-Talisman to set security headers. However, it must be explicitly enabled.
> #### ⚠️ Important: Talisman is Disabled by Default
>
> In Superset 4.0 and later, Talisman is disabled by default (`TALISMAN_ENABLED = False`). You **must** explicitly enable it in your `superset_config.py` for the security headers defined in `TALISMAN_CONFIG` to take effect.
Here's the documentation section how how to set up Talisman: https://superset.apache.org/docs/security/#content-security-policy-csp
### **Database Security**
> #### ❗ Superset is Not a Database Firewall
>
> It is essential to understand that **Apache Superset is a data visualization and exploration platform, not a database firewall or a comprehensive security solution for your data warehouse.** While Superset provides features to help manage data access, the ultimate responsibility for securing your underlying databases lies with your database administrators (DBAs) and security teams. This includes managing network access, user privileges, and fine-grained permissions directly within the database. The configurations below are an important secondary layer of security but should not be your only line of defense.
* **Use a Dedicated Database User:** The database connection configured in Superset should use a dedicated, limited-privilege database user. This user should only have the minimum required permissions (e.g., `SELECT` on specific schemas) for the data sources it needs to query. It should **not** have `INSERT`, `UPDATE`, `DELETE`, or administrative privileges.
* **Restrict Dangerous SQL Functions:** To mitigate potential SQL injection risks, configure the `DISALLOWED_SQL_FUNCTIONS` list in your `superset_config.py`. Be aware that this is a defense-in-depth measure, not a substitute for proper database permissions.
### **Additional Security Layers**
* **Web Application Firewall (WAF):** Deploying Superset behind a WAF (e.g., Cloudflare, AWS WAF) is strongly recommended. A WAF with a standard ruleset (like the OWASP Core Rule Set) provides a critical layer of defense against common attacks like SQL Injection, XSS, and remote code execution.
### **Monitoring and Logging**
* **Configure Structured Logging:** Set up a robust logging configuration to capture important security events.
* **Centralize Logs:** Ship logs from all Superset components (frontend, worker, etc.) to a centralized SIEM (Security Information and Event Management) system for analysis and alerting.
* **Monitor Key Events:** Create alerts for suspicious activities, including:
* Multiple failed login attempts for a single user or from a single IP address.
* Changes to user roles or permissions.
* Creation or deletion of high-privilege users.
* Attempts to use disallowed SQL functions.
-----
### **Appendix A: Production Deployment Checklist**
#### **Initial Setup:**
- [ ] HTTPS/TLS is configured and enforced via a reverse proxy.
- [ ] A unique, strong `SUPERSET_SECRET_KEY` is generated and secured in an environment variable or secrets vault.
- [ ] Server-side session management is configured (e.g., Redis).
- [ ] `PERMANENT_SESSION_LIFETIME` is set to a short duration (e.g., 8 hours).
- [ ] All session cookie security flags (`Secure`, `HttpOnly`, `SameSite`) are enabled.
- [ ] `DEBUG` mode is set to `False`.
- [ ] Talisman is explicitly enabled and configured with a strict Content Security Policy.
- [ ] Database connections use dedicated, limited-privilege accounts.
- [ ] Authentication is integrated with an enterprise identity provider (OAuth/LDAP).
- [ ] A Web Application Firewall (WAF) is deployed in front of Superset.
- [ ] Logging is configured and logs are shipped to a central monitoring system.
#### **Ongoing Maintenance:**
- [ ] Regularly update to the latest major or minor versions of Superset. Those versions receive up-to-date security patches.
- [ ] Rotate the `SUPERSET_SECRET_KEY` periodically (e.g., quarterly) and after any potential security incident.
- [ ] Conduct quarterly access reviews for all users.
- [ ] Assuming logging and monitoring is in place, review security monitoring alerts weekly.
### **Appendix B: `SECRET_KEY` Rotation and Compromise Response**
**Why and When to Rotate the `SECRET_KEY`**
Rotating the `SUPERSET_SECRET_KEY` is a critical security procedure. It is mandatory after a known or suspected compromise and is a best practice when an employee with access to the key departs. While periodic rotation can limit the window of exposure for an unknown leak, it is a high-impact operation that will invalidate all user sessions and requires careful execution to avoid breaking your instance. The principles behind managing this key align with general best practices for cryptographic storage, which are further detailed in the OWASP Cryptographic Storage Cheat Sheet here: https://cheatsheetseries.owasp.org/cheatsheets/Cryptographic_Storage_Cheat_Sheet.html
**Procedure for Rotating the Key**
The procedure for safely rotating the SECRET_KEY must be followed precisely to avoid locking yourself out of your instance. The official Apache Superset documentation maintains the correct, up-to-date procedure. Please follow the official guide here:
https://superset.apache.org/docs/configuration/configuring-superset/#rotating-to-a-newer-secret_key

View File

@@ -50,7 +50,7 @@
"@storybook/theming": "^8.6.11",
"@superset-ui/core": "^0.20.4",
"antd": "^5.27.4",
"caniuse-lite": "^1.0.30001750",
"caniuse-lite": "^1.0.30001749",
"docusaurus-plugin-less": "^2.0.2",
"json-bigint": "^1.0.0",
"less": "^4.4.2",
@@ -63,7 +63,7 @@
"remark-import-partial": "^0.0.2",
"reselect": "^5.1.1",
"storybook": "^8.6.11",
"swagger-ui-react": "^5.29.4",
"swagger-ui-react": "^5.29.3",
"tinycolor2": "^1.4.2",
"ts-loader": "^9.5.4"
},
@@ -81,7 +81,7 @@
"globals": "^16.4.0",
"prettier": "^3.6.2",
"typescript": "~5.9.3",
"typescript-eslint": "^8.46.1",
"typescript-eslint": "^8.46.0",
"webpack": "^5.102.1"
},
"browserslist": {

View File

@@ -4336,79 +4336,79 @@
dependencies:
"@types/yargs-parser" "*"
"@typescript-eslint/eslint-plugin@8.46.1", "@typescript-eslint/eslint-plugin@^8.37.0":
version "8.46.1"
resolved "https://registry.yarnpkg.com/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.46.1.tgz#20876354024140aabc8b400bc95735fdcade17d5"
integrity sha512-rUsLh8PXmBjdiPY+Emjz9NX2yHvhS11v0SR6xNJkm5GM1MO9ea/1GoDKlHHZGrOJclL/cZ2i/vRUYVtjRhrHVQ==
"@typescript-eslint/eslint-plugin@8.46.0", "@typescript-eslint/eslint-plugin@^8.37.0":
version "8.46.0"
resolved "https://registry.yarnpkg.com/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.46.0.tgz#fc90b35d8025b5eaa66b2f6c3859cd5381a1e751"
integrity sha512-hA8gxBq4ukonVXPy0OKhiaUh/68D0E88GSmtC1iAEnGaieuDi38LhS7jdCHRLi6ErJBNDGCzvh5EnzdPwUc0DA==
dependencies:
"@eslint-community/regexpp" "^4.10.0"
"@typescript-eslint/scope-manager" "8.46.1"
"@typescript-eslint/type-utils" "8.46.1"
"@typescript-eslint/utils" "8.46.1"
"@typescript-eslint/visitor-keys" "8.46.1"
"@typescript-eslint/scope-manager" "8.46.0"
"@typescript-eslint/type-utils" "8.46.0"
"@typescript-eslint/utils" "8.46.0"
"@typescript-eslint/visitor-keys" "8.46.0"
graphemer "^1.4.0"
ignore "^7.0.0"
natural-compare "^1.4.0"
ts-api-utils "^2.1.0"
"@typescript-eslint/parser@8.46.1", "@typescript-eslint/parser@^8.46.0":
version "8.46.1"
resolved "https://registry.yarnpkg.com/@typescript-eslint/parser/-/parser-8.46.1.tgz#81751f46800fc6b01ce1a72760cd17f06e7f395b"
integrity sha512-6JSSaBZmsKvEkbRUkf7Zj7dru/8ZCrJxAqArcLaVMee5907JdtEbKGsZ7zNiIm/UAkpGUkaSMZEXShnN2D1HZA==
"@typescript-eslint/parser@8.46.0", "@typescript-eslint/parser@^8.46.0":
version "8.46.0"
resolved "https://registry.yarnpkg.com/@typescript-eslint/parser/-/parser-8.46.0.tgz#9186f28c59f6e477ab8919312d2654f4f27d45c1"
integrity sha512-n1H6IcDhmmUEG7TNVSspGmiHHutt7iVKtZwRppD7e04wha5MrkV1h3pti9xQLcCMt6YWsncpoT0HMjkH1FNwWQ==
dependencies:
"@typescript-eslint/scope-manager" "8.46.1"
"@typescript-eslint/types" "8.46.1"
"@typescript-eslint/typescript-estree" "8.46.1"
"@typescript-eslint/visitor-keys" "8.46.1"
"@typescript-eslint/scope-manager" "8.46.0"
"@typescript-eslint/types" "8.46.0"
"@typescript-eslint/typescript-estree" "8.46.0"
"@typescript-eslint/visitor-keys" "8.46.0"
debug "^4.3.4"
"@typescript-eslint/project-service@8.46.1":
version "8.46.1"
resolved "https://registry.yarnpkg.com/@typescript-eslint/project-service/-/project-service-8.46.1.tgz#07be0e6f27fa90a17d8e5f6996ee02329c9a8c2e"
integrity sha512-FOIaFVMHzRskXr5J4Jp8lFVV0gz5ngv3RHmn+E4HYxSJ3DgDzU7fVI1/M7Ijh1zf6S7HIoaIOtln1H5y8V+9Zg==
"@typescript-eslint/project-service@8.46.0":
version "8.46.0"
resolved "https://registry.yarnpkg.com/@typescript-eslint/project-service/-/project-service-8.46.0.tgz#1190dcc0d3494d46a85773e0c3a2838cbb2b45a7"
integrity sha512-OEhec0mH+U5Je2NZOeK1AbVCdm0ChyapAyTeXVIYTPXDJ3F07+cu87PPXcGoYqZ7M9YJVvFnfpGg1UmCIqM+QQ==
dependencies:
"@typescript-eslint/tsconfig-utils" "^8.46.1"
"@typescript-eslint/types" "^8.46.1"
"@typescript-eslint/tsconfig-utils" "^8.46.0"
"@typescript-eslint/types" "^8.46.0"
debug "^4.3.4"
"@typescript-eslint/scope-manager@8.46.1":
version "8.46.1"
resolved "https://registry.yarnpkg.com/@typescript-eslint/scope-manager/-/scope-manager-8.46.1.tgz#590dd2e65e95af646bdaf50adeae9af39e25e8c1"
integrity sha512-weL9Gg3/5F0pVQKiF8eOXFZp8emqWzZsOJuWRUNtHT+UNV2xSJegmpCNQHy37aEQIbToTq7RHKhWvOsmbM680A==
"@typescript-eslint/scope-manager@8.46.0":
version "8.46.0"
resolved "https://registry.yarnpkg.com/@typescript-eslint/scope-manager/-/scope-manager-8.46.0.tgz#a41833fe387044075cb2d4cfab490a7f1dd19b61"
integrity sha512-lWETPa9XGcBes4jqAMYD9fW0j4n6hrPtTJwWDmtqgFO/4HF4jmdH/Q6wggTw5qIT5TXjKzbt7GsZUBnWoO3dqw==
dependencies:
"@typescript-eslint/types" "8.46.1"
"@typescript-eslint/visitor-keys" "8.46.1"
"@typescript-eslint/types" "8.46.0"
"@typescript-eslint/visitor-keys" "8.46.0"
"@typescript-eslint/tsconfig-utils@8.46.1", "@typescript-eslint/tsconfig-utils@^8.46.1":
version "8.46.1"
resolved "https://registry.yarnpkg.com/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.46.1.tgz#24405888560175c6c209c39df11ac06a2efef9d7"
integrity sha512-X88+J/CwFvlJB+mK09VFqx5FE4H5cXD+H/Bdza2aEWkSb8hnWIQorNcscRl4IEo1Cz9VI/+/r/jnGWkbWPx54g==
"@typescript-eslint/tsconfig-utils@8.46.0", "@typescript-eslint/tsconfig-utils@^8.46.0":
version "8.46.0"
resolved "https://registry.yarnpkg.com/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.46.0.tgz#3e33019e0b94838d37d7cc61341fbcc5bf791007"
integrity sha512-WrYXKGAHY836/N7zoK/kzi6p8tXFhasHh8ocFL9VZSAkvH956gfeRfcnhs3xzRy8qQ/dq3q44v1jvQieMFg2cw==
"@typescript-eslint/type-utils@8.46.1":
version "8.46.1"
resolved "https://registry.yarnpkg.com/@typescript-eslint/type-utils/-/type-utils-8.46.1.tgz#14d4307dd6045f6b48a888cde1513d6ec305537f"
integrity sha512-+BlmiHIiqufBxkVnOtFwjah/vrkF4MtKKvpXrKSPLCkCtAp8H01/VV43sfqA98Od7nJpDcFnkwgyfQbOG0AMvw==
"@typescript-eslint/type-utils@8.46.0":
version "8.46.0"
resolved "https://registry.yarnpkg.com/@typescript-eslint/type-utils/-/type-utils-8.46.0.tgz#815efeb11b9533da68fd825628cecf283ac79829"
integrity sha512-hy+lvYV1lZpVs2jRaEYvgCblZxUoJiPyCemwbQZ+NGulWkQRy0HRPYAoef/CNSzaLt+MLvMptZsHXHlkEilaeg==
dependencies:
"@typescript-eslint/types" "8.46.1"
"@typescript-eslint/typescript-estree" "8.46.1"
"@typescript-eslint/utils" "8.46.1"
"@typescript-eslint/types" "8.46.0"
"@typescript-eslint/typescript-estree" "8.46.0"
"@typescript-eslint/utils" "8.46.0"
debug "^4.3.4"
ts-api-utils "^2.1.0"
"@typescript-eslint/types@8.46.1", "@typescript-eslint/types@^8.46.1":
version "8.46.1"
resolved "https://registry.yarnpkg.com/@typescript-eslint/types/-/types-8.46.1.tgz#4c5479538ec10b5508b8e982e172911c987446d8"
integrity sha512-C+soprGBHwWBdkDpbaRC4paGBrkIXxVlNohadL5o0kfhsXqOC6GYH2S/Obmig+I0HTDl8wMaRySwrfrXVP8/pQ==
"@typescript-eslint/types@8.46.0", "@typescript-eslint/types@^8.46.0":
version "8.46.0"
resolved "https://registry.yarnpkg.com/@typescript-eslint/types/-/types-8.46.0.tgz#20af6b332f9cd55a15fcd862fdb07d47a6131bf4"
integrity sha512-bHGGJyVjSE4dJJIO5yyEWt/cHyNwga/zXGJbJJ8TiO01aVREK6gCTu3L+5wrkb1FbDkQ+TKjMNe9R/QQQP9+rA==
"@typescript-eslint/typescript-estree@8.46.1":
version "8.46.1"
resolved "https://registry.yarnpkg.com/@typescript-eslint/typescript-estree/-/typescript-estree-8.46.1.tgz#1c146573b942ebe609c156c217ceafdc7a88e6ed"
integrity sha512-uIifjT4s8cQKFQ8ZBXXyoUODtRoAd7F7+G8MKmtzj17+1UbdzFl52AzRyZRyKqPHhgzvXunnSckVu36flGy8cg==
"@typescript-eslint/typescript-estree@8.46.0":
version "8.46.0"
resolved "https://registry.yarnpkg.com/@typescript-eslint/typescript-estree/-/typescript-estree-8.46.0.tgz#f45a0d5f5e99b26f0280e8cff3ed3380658fd720"
integrity sha512-ekDCUfVpAKWJbRfm8T1YRrCot1KFxZn21oV76v5Fj4tr7ELyk84OS+ouvYdcDAwZL89WpEkEj2DKQ+qg//+ucg==
dependencies:
"@typescript-eslint/project-service" "8.46.1"
"@typescript-eslint/tsconfig-utils" "8.46.1"
"@typescript-eslint/types" "8.46.1"
"@typescript-eslint/visitor-keys" "8.46.1"
"@typescript-eslint/project-service" "8.46.0"
"@typescript-eslint/tsconfig-utils" "8.46.0"
"@typescript-eslint/types" "8.46.0"
"@typescript-eslint/visitor-keys" "8.46.0"
debug "^4.3.4"
fast-glob "^3.3.2"
is-glob "^4.0.3"
@@ -4416,22 +4416,22 @@
semver "^7.6.0"
ts-api-utils "^2.1.0"
"@typescript-eslint/utils@8.46.1":
version "8.46.1"
resolved "https://registry.yarnpkg.com/@typescript-eslint/utils/-/utils-8.46.1.tgz#c572184d9227d66b10a954b90249a20c48b22452"
integrity sha512-vkYUy6LdZS7q1v/Gxb2Zs7zziuXN0wxqsetJdeZdRe/f5dwJFglmuvZBfTUivCtjH725C1jWCDfpadadD95EDQ==
"@typescript-eslint/utils@8.46.0":
version "8.46.0"
resolved "https://registry.yarnpkg.com/@typescript-eslint/utils/-/utils-8.46.0.tgz#27025c5ed7cbc928440d6a30edd6ba34cc5b927a"
integrity sha512-nD6yGWPj1xiOm4Gk0k6hLSZz2XkNXhuYmyIrOWcHoPuAhjT9i5bAG+xbWPgFeNR8HPHHtpNKdYUXJl/D3x7f5g==
dependencies:
"@eslint-community/eslint-utils" "^4.7.0"
"@typescript-eslint/scope-manager" "8.46.1"
"@typescript-eslint/types" "8.46.1"
"@typescript-eslint/typescript-estree" "8.46.1"
"@typescript-eslint/scope-manager" "8.46.0"
"@typescript-eslint/types" "8.46.0"
"@typescript-eslint/typescript-estree" "8.46.0"
"@typescript-eslint/visitor-keys@8.46.1":
version "8.46.1"
resolved "https://registry.yarnpkg.com/@typescript-eslint/visitor-keys/-/visitor-keys-8.46.1.tgz#da35f1d58ec407419d68847cfd358b32746ac315"
integrity sha512-ptkmIf2iDkNUjdeu2bQqhFPV1m6qTnFFjg7PPDjxKWaMaP0Z6I9l30Jr3g5QqbZGdw8YdYvLp+XnqnWWZOg/NA==
"@typescript-eslint/visitor-keys@8.46.0":
version "8.46.0"
resolved "https://registry.yarnpkg.com/@typescript-eslint/visitor-keys/-/visitor-keys-8.46.0.tgz#23936809054c511f703713c56ddd2f46dc197845"
integrity sha512-FrvMpAK+hTbFy7vH5j1+tMYHMSKLE6RzluFJlkFNKD0p9YsUT75JlBSmr5so3QRzvMwU5/bIEdeNrxm8du8l3Q==
dependencies:
"@typescript-eslint/types" "8.46.1"
"@typescript-eslint/types" "8.46.0"
eslint-visitor-keys "^4.2.1"
"@ungap/structured-clone@^1.0.0":
@@ -5305,10 +5305,10 @@ caniuse-api@^3.0.0:
lodash.memoize "^4.1.2"
lodash.uniq "^4.5.0"
caniuse-lite@^1.0.0, caniuse-lite@^1.0.30001702, caniuse-lite@^1.0.30001746, caniuse-lite@^1.0.30001750:
version "1.0.30001750"
resolved "https://registry.yarnpkg.com/caniuse-lite/-/caniuse-lite-1.0.30001750.tgz#c229f82930033abd1502c6f73035356cf528bfbc"
integrity sha512-cuom0g5sdX6rw00qOoLNSFCJ9/mYIsuSOA+yzpDw8eopiFqcVwQvZHqov0vmEighRxX++cfC0Vg1G+1Iy/mSpQ==
caniuse-lite@^1.0.0, caniuse-lite@^1.0.30001702, caniuse-lite@^1.0.30001746, caniuse-lite@^1.0.30001749:
version "1.0.30001749"
resolved "https://registry.yarnpkg.com/caniuse-lite/-/caniuse-lite-1.0.30001749.tgz#21a43b923577932097fe32bcaabb6da7f4677632"
integrity sha512-0rw2fJOmLfnzCRbkm8EyHL8SvI2Apu5UbnQuTsJ0ClgrH8hcwFooJ1s5R0EP8o8aVrFu8++ae29Kt9/gZAZp/Q==
ccount@^2.0.0:
version "2.0.1"
@@ -13259,10 +13259,10 @@ swagger-client@^3.35.7:
ramda "^0.30.1"
ramda-adjunct "^5.1.0"
swagger-ui-react@^5.29.4:
version "5.29.4"
resolved "https://registry.yarnpkg.com/swagger-ui-react/-/swagger-ui-react-5.29.4.tgz#ff061f301b46849a93c53b2490f7cebbea401832"
integrity sha512-lBBRq75dHWnuN1uuxGOvJkoYr8F+AuZpOSUdHez9st7GlHKTPiBz5bOFONXPzbLKDWrwsPTQ/zArBSDjfqtVow==
swagger-ui-react@^5.29.3:
version "5.29.3"
resolved "https://registry.yarnpkg.com/swagger-ui-react/-/swagger-ui-react-5.29.3.tgz#a132c3c3c4553c2acd0aca1f02c8484ca4c78183"
integrity sha512-cx47SmqrxXCP86+6NHEzXUBEG/MGbNK/H8BQphzUVomxGpG9lZCUo6hIGFNe1i7fP5eaMxpLV/qoqaWVo3TSvw==
dependencies:
"@babel/runtime-corejs3" "^7.27.1"
"@scarf/scarf" "=1.4.0"
@@ -13590,15 +13590,15 @@ types-ramda@^0.30.1:
dependencies:
ts-toolbelt "^9.6.0"
typescript-eslint@^8.46.1:
version "8.46.1"
resolved "https://registry.yarnpkg.com/typescript-eslint/-/typescript-eslint-8.46.1.tgz#baeb322ee83ca566a8cf1f6403847694a3acd44a"
integrity sha512-VHgijW803JafdSsDO8I761r3SHrgk4T00IdyQ+/UsthtgPRsBWQLqoSxOolxTpxRKi1kGXK0bSz4CoAc9ObqJA==
typescript-eslint@^8.46.0:
version "8.46.0"
resolved "https://registry.yarnpkg.com/typescript-eslint/-/typescript-eslint-8.46.0.tgz#fb1c37a90fadf42fe1c8f8b192b974b6d9c439cc"
integrity sha512-6+ZrB6y2bT2DX3K+Qd9vn7OFOJR+xSLDj+Aw/N3zBwUt27uTw2sw2TE2+UcY1RiyBZkaGbTkVg9SSdPNUG6aUw==
dependencies:
"@typescript-eslint/eslint-plugin" "8.46.1"
"@typescript-eslint/parser" "8.46.1"
"@typescript-eslint/typescript-estree" "8.46.1"
"@typescript-eslint/utils" "8.46.1"
"@typescript-eslint/eslint-plugin" "8.46.0"
"@typescript-eslint/parser" "8.46.0"
"@typescript-eslint/typescript-estree" "8.46.0"
"@typescript-eslint/utils" "8.46.0"
typescript@~5.9.3:
version "5.9.3"

View File

@@ -441,42 +441,24 @@ def init() -> None:
(target_dir / "extension.json").write_text(extension_json)
click.secho("✅ Created extension.json", fg="green")
# Initialize frontend files
# Copy frontend template
if include_frontend:
frontend_dir = target_dir / "frontend"
frontend_dir.mkdir()
frontend_src_dir = frontend_dir / "src"
frontend_src_dir.mkdir()
# frontend files
# package.json
package_json = env.get_template("frontend/package.json.j2").render(ctx)
(frontend_dir / "package.json").write_text(package_json)
webpack_config = env.get_template("frontend/webpack.config.js.j2").render(ctx)
(frontend_dir / "webpack.config.js").write_text(webpack_config)
tsconfig_json = env.get_template("frontend/tsconfig.json.j2").render(ctx)
(frontend_dir / "tsconfig.json").write_text(tsconfig_json)
index_tsx = env.get_template("frontend/src/index.tsx.j2").render(ctx)
(frontend_src_dir / "index.tsx").write_text(index_tsx)
click.secho("✅ Created frontend folder structure", fg="green")
# Initialize backend files
# Copy backend template
if include_backend:
backend_dir = target_dir / "backend"
backend_dir.mkdir()
backend_src_dir = backend_dir / "src"
backend_src_dir.mkdir()
backend_src_package_dir = backend_src_dir / id_
backend_src_package_dir.mkdir()
# backend files
# pyproject.toml
pyproject_toml = env.get_template("backend/pyproject.toml.j2").render(ctx)
(backend_dir / "pyproject.toml").write_text(pyproject_toml)
init_py = env.get_template("backend/src/package/__init__.py.j2").render(ctx)
(backend_src_package_dir / "__init__.py").write_text(init_py)
entrypoint_py = env.get_template("backend/src/package/entrypoint.py.j2").render(
ctx
)
(backend_src_package_dir / "entrypoint.py").write_text(entrypoint_py)
click.secho("✅ Created backend folder structure", fg="green")

View File

@@ -1 +0,0 @@
print("{{ name }} extension registered")

View File

@@ -14,7 +14,7 @@
"license": "{{ license }}",
"description": "",
"peerDependencies": {
"@apache-superset/core": "*",
"@apache-superset/core": "file:../../../superset-frontend/packages/superset-core",
"react": "^17.0.2",
"react-dom": "^17.0.2"
},

View File

@@ -1,13 +0,0 @@
import React from "react";
import { core } from "@apache-superset/core";
export const activate = (context: core.ExtensionContext) => {
context.disposables.push(
core.registerViewProvider("{{ id }}.example", () => <p>{{ name }}</p>)
);
console.log("{{ name }} extension activated");
};
export const deactivate = () => {
console.log("{{ name }} extension deactivated");
};

View File

@@ -1,13 +0,0 @@
{
"compilerOptions": {
"target": "es5",
"module": "esnext",
"moduleResolution": "node10",
"jsx": "react",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src"]
}

View File

@@ -1,67 +0,0 @@
const path = require("path");
const { ModuleFederationPlugin } = require("webpack").container;
const packageConfig = require("./package");
module.exports = (env, argv) => {
const isProd = argv.mode === "production";
return {
entry: isProd ? {} : "./src/index.tsx",
mode: isProd ? "production" : "development",
devServer: {
port: 3000,
headers: {
"Access-Control-Allow-Origin": "*",
},
},
output: {
clean: true,
filename: isProd ? undefined : "[name].[contenthash].js",
chunkFilename: "[name].[contenthash].js",
path: path.resolve(__dirname, "dist"),
publicPath: `/api/v1/extensions/${packageConfig.name}/`,
},
resolve: {
extensions: [".ts", ".tsx", ".js", ".jsx"],
},
externalsType: "window",
externals: {
"@apache-superset/core": "superset",
},
module: {
rules: [
{
test: /\.tsx?$/,
use: "ts-loader",
exclude: /node_modules/,
},
],
},
plugins: [
new ModuleFederationPlugin({
name: "{{ id }}",
filename: "remoteEntry.[contenthash].js",
exposes: {
"./index": "./src/index.tsx",
},
shared: {
react: {
singleton: true,
requiredVersion: packageConfig.peerDependencies.react,
import: false,
},
"react-dom": {
singleton: true,
requiredVersion: packageConfig.peerDependencies["react-dom"],
import: false,
},
antd: {
singleton: true,
requiredVersion: packageConfig.peerDependencies["antd"],
import: false,
},
},
}),
],
};
};

View File

@@ -87,7 +87,6 @@ export function prepareDashboardFilters(
if (dashboardId) {
const jsonMetadata = {
native_filter_configuration: allFilters,
chart_customization_config: [],
timed_refresh_immune_slices: [],
expanded_slices: {},
refresh_frequency: 0,

File diff suppressed because it is too large Load Diff

View File

@@ -220,7 +220,7 @@
"@babel/plugin-syntax-dynamic-import": "^7.8.3",
"@babel/plugin-transform-export-namespace-from": "^7.27.1",
"@babel/plugin-transform-modules-commonjs": "^7.26.3",
"@babel/plugin-transform-runtime": "^7.28.3",
"@babel/plugin-transform-runtime": "^7.27.1",
"@babel/preset-env": "^7.27.2",
"@babel/preset-react": "^7.27.1",
"@babel/preset-typescript": "^7.26.0",

View File

@@ -34,7 +34,7 @@
"yosay": "^3.0.0"
},
"devDependencies": {
"cross-env": "^10.1.0",
"cross-env": "^10.0.0",
"fs-extra": "^11.3.2",
"jest": "^30.0.5",
"yeoman-test": "^10.1.1"

View File

@@ -49,7 +49,7 @@
"jed": "^1.1.1",
"lodash": "^4.17.21",
"math-expression-evaluator": "^2.0.6",
"pretty-ms": "^9.3.0",
"pretty-ms": "^9.2.0",
"re-resizable": "^6.11.2",
"react-ace": "^14.0.1",
"react-js-cron": "^5.2.0",

View File

@@ -1,129 +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 { render, screen, userEvent } from '@superset-ui/core/spec';
import { ThemeProvider, supersetTheme } from '@superset-ui/core';
import { ConfirmModal } from '.';
const defaultProps = {
show: true,
onHide: jest.fn(),
onConfirm: jest.fn(),
title: 'Confirm Action',
body: 'Are you sure you want to proceed?',
};
const renderWithTheme = (component: React.ReactElement) =>
render(<ThemeProvider theme={supersetTheme}>{component}</ThemeProvider>);
test('renders modal with title and body', () => {
renderWithTheme(<ConfirmModal {...defaultProps} />);
expect(screen.getByText('Confirm Action')).toBeInTheDocument();
expect(
screen.getByText('Are you sure you want to proceed?'),
).toBeInTheDocument();
});
test('renders default confirm and cancel buttons', () => {
renderWithTheme(<ConfirmModal {...defaultProps} />);
expect(screen.getByRole('button', { name: 'Confirm' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Cancel' })).toBeInTheDocument();
});
test('renders custom button text', () => {
renderWithTheme(
<ConfirmModal {...defaultProps} confirmText="Delete" cancelText="Keep" />,
);
expect(screen.getByRole('button', { name: 'Delete' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Keep' })).toBeInTheDocument();
});
test('calls onConfirm when confirm button is clicked', () => {
const onConfirm = jest.fn();
renderWithTheme(<ConfirmModal {...defaultProps} onConfirm={onConfirm} />);
userEvent.click(screen.getByRole('button', { name: 'Confirm' }));
expect(onConfirm).toHaveBeenCalledTimes(1);
});
test('calls onHide when cancel button is clicked', () => {
const onHide = jest.fn();
renderWithTheme(<ConfirmModal {...defaultProps} onHide={onHide} />);
userEvent.click(screen.getByRole('button', { name: 'Cancel' }));
expect(onHide).toHaveBeenCalledTimes(1);
});
test('renders danger button style', () => {
renderWithTheme(
<ConfirmModal {...defaultProps} confirmButtonStyle="danger" />,
);
const confirmButton = screen.getByRole('button', { name: 'Confirm' });
expect(confirmButton).toBeInTheDocument();
});
test('shows loading state on confirm button', () => {
renderWithTheme(<ConfirmModal {...defaultProps} loading />);
const confirmButton = screen.getByRole('button', { name: /Confirm/ });
expect(confirmButton).toBeInTheDocument();
expect(confirmButton).toHaveClass('ant-btn-loading');
});
test('disables buttons when loading', () => {
renderWithTheme(<ConfirmModal {...defaultProps} loading />);
const cancelButton = screen.getByRole('button', { name: 'Cancel' });
expect(cancelButton).toBeDisabled();
});
test('renders custom icon', () => {
const CustomIcon = () => <span data-test="custom-icon">!</span>;
renderWithTheme(<ConfirmModal {...defaultProps} icon={<CustomIcon />} />);
expect(screen.getByTestId('custom-icon')).toBeInTheDocument();
});
test('renders ReactNode as body', () => {
renderWithTheme(
<ConfirmModal
{...defaultProps}
body={
<div>
<p>Line 1</p>
<p>Line 2</p>
</div>
}
/>,
);
expect(screen.getByText('Line 1')).toBeInTheDocument();
expect(screen.getByText('Line 2')).toBeInTheDocument();
});
test('does not render when show is false', () => {
renderWithTheme(<ConfirmModal {...defaultProps} show={false} />);
expect(screen.queryByText('Confirm Action')).not.toBeInTheDocument();
});

View File

@@ -1,87 +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 { t, styled } from '@superset-ui/core';
import { Icons, Modal, Typography, Button } from '@superset-ui/core/components';
import type { FC, ReactElement, ReactNode } from 'react';
const IconWrapper = styled.span`
margin-right: ${({ theme }) => theme.sizeUnit * 2}px;
`;
const DEFAULT_ICON = <Icons.QuestionCircleOutlined iconSize="m" />;
export type ConfirmModalProps = {
show: boolean;
onHide: () => void;
onConfirm: () => void;
title: string;
body: string | ReactNode;
confirmText?: string;
cancelText?: string;
confirmButtonStyle?: 'primary' | 'danger' | 'dashed';
icon?: ReactNode;
loading?: boolean;
};
export const ConfirmModal: FC<ConfirmModalProps> = ({
show,
onHide,
onConfirm,
title,
body,
confirmText = t('Confirm'),
cancelText = t('Cancel'),
confirmButtonStyle = 'primary',
icon = DEFAULT_ICON,
loading = false,
}: ConfirmModalProps): ReactElement => (
<Modal
centered
responsive
onHide={onHide}
show={show}
width="600px"
title={
<>
<IconWrapper>{icon}</IconWrapper>
{title}
</>
}
footer={
<>
<Button buttonStyle="secondary" onClick={onHide} disabled={loading}>
{cancelText}
</Button>
<Button
buttonStyle={confirmButtonStyle}
onClick={onConfirm}
loading={loading}
>
{confirmText}
</Button>
</>
}
>
{typeof body === 'string' ? (
<Typography.Text>{body}</Typography.Text>
) : (
body
)}
</Modal>
);

View File

@@ -144,7 +144,6 @@ import {
GoogleOutlined,
DesktopOutlined,
FormatPainterOutlined,
GroupOutlined,
ExportOutlined,
CompressOutlined,
HistoryOutlined,
@@ -222,7 +221,6 @@ const AntdIcons = {
FunctionOutlined,
GithubOutlined,
GoogleOutlined,
GroupOutlined,
HighlightOutlined,
InfoCircleOutlined,
InfoCircleFilled,

View File

@@ -167,33 +167,6 @@ const StyledTable = styled(AntTable as FC<AntTableProps>)<{ height?: number }>(
.ant-table-body {
overflow: auto;
height: ${height ? `${height}px` : undefined};
/* Chrome/Safari/Edge webkit scrollbar styling */
&::-webkit-scrollbar {
width: 8px;
height: 8px;
}
&::-webkit-scrollbar-track {
background: ${theme.colorFillQuaternary};
}
&::-webkit-scrollbar-thumb {
background: ${theme.colorFillSecondary};
border-radius: ${theme.borderRadiusSM}px;
&:hover {
background: ${theme.colorFillTertiary};
}
}
&::-webkit-scrollbar-corner {
background: ${theme.colorFillQuaternary};
}
/* Firefox scrollbar styling */
scrollbar-width: thin;
scrollbar-color: ${theme.colorFillSecondary} ${theme.colorFillQuaternary};
}
.ant-spin-nested-loading .ant-spin .ant-spin-dot {

View File

@@ -66,7 +66,6 @@ export {
type CheckboxProps,
type CheckboxChangeEvent,
} from './Checkbox';
export { ConfirmModal, type ConfirmModalProps } from './ConfirmModal';
export {
ColorPicker,
type ColorPickerProps,

View File

@@ -34,7 +34,7 @@
"@luma.gl/engine": "^9.1.9",
"@luma.gl/shadertools": "^9.1.9",
"@luma.gl/webgl": "^9.1.9",
"@mapbox/tiny-sdf": "^2.0.7",
"@mapbox/tiny-sdf": "^2.0.6",
"@mapbox/geojson-extent": "^1.0.1",
"@math.gl/web-mercator": "^4.1.0",
"@types/d3-array": "^2.0.0",

View File

@@ -156,27 +156,13 @@ const CategoricalDeckGLContainer = (props: CategoricalDeckGLContainerProps) => {
switch (selectedColorScheme) {
case COLOR_SCHEME_TYPES.fixed_color: {
color = fd.color_picker || { r: 0, g: 0, b: 0, a: 100 };
const colorArray = [color.r, color.g, color.b, color.a * 255];
return data.map(d => ({ ...d, color: colorArray }));
return data.map(d => ({
...d,
color: [color.r, color.g, color.b, color.a * 255],
}));
}
case COLOR_SCHEME_TYPES.categorical_palette: {
if (!fd.dimension) {
const fallbackColor = fd.color_picker || {
r: 0,
g: 0,
b: 0,
a: 100,
};
const colorArray = [
fallbackColor.r,
fallbackColor.g,
fallbackColor.b,
fallbackColor.a * 255,
];
return data.map(d => ({ ...d, color: colorArray }));
}
return data.map(d => ({
...d,
color: hexToRGB(colorFn(d.cat_color, fd.slice_id)),
@@ -204,17 +190,17 @@ const CategoricalDeckGLContainer = (props: CategoricalDeckGLContainerProps) => {
d.metric <= breakpoint.maxValue,
);
if (breakpointForPoint) {
const pointColor = [
breakpointForPoint.color.r,
breakpointForPoint.color.g,
breakpointForPoint.color.b,
breakpointForPoint.color.a * 255,
];
return { ...d, color: pointColor };
}
return { ...d, color: defaultBreakpointColor };
return {
...d,
color: breakpointForPoint
? [
breakpointForPoint?.color.r,
breakpointForPoint?.color.g,
breakpointForPoint?.color.b,
breakpointForPoint?.color.a * 255,
]
: defaultBreakpointColor,
};
});
}
default: {

View File

@@ -46,14 +46,14 @@ export interface DeckScatterFormData
min_radius?: number;
max_radius?: number;
color_picker?: { r: number; g: number; b: number; a: number };
dimension?: string;
category_name?: string;
}
export default function buildQuery(formData: DeckScatterFormData) {
const {
spatial,
point_radius_fixed,
dimension,
category_name,
js_columns,
tooltip_contents,
} = formData;
@@ -67,8 +67,8 @@ export default function buildQuery(formData: DeckScatterFormData) {
const spatialColumns = getSpatialColumns(spatial);
let columns = [...(baseQueryObject.columns || []), ...spatialColumns];
if (dimension) {
columns.push(dimension);
if (category_name) {
columns.push(category_name);
}
const columnStrings = columns.map(col =>

View File

@@ -37,6 +37,7 @@ import {
tooltipContents,
tooltipTemplate,
} from '../../utilities/Shared_DeckGL';
import { COLOR_SCHEME_TYPES } from '../../utilities/utils';
const config: ControlPanelConfig = {
onInit: controlState => ({
@@ -133,7 +134,9 @@ const config: ControlPanelConfig = {
controlSetRows: [
[legendPosition],
[legendFormat],
...generateDeckGLColorSchemeControls({}),
...generateDeckGLColorSchemeControls({
defaultSchemeType: COLOR_SCHEME_TYPES.fixed_color,
}),
],
},
{

View File

@@ -95,7 +95,7 @@ function processScatterData(
export default function transformProps(chartProps: ChartProps) {
const { rawFormData: formData } = chartProps;
const { spatial, point_radius_fixed, dimension, js_columns } =
const { spatial, point_radius_fixed, category_name, js_columns } =
formData as DeckScatterFormData;
const radiusMetricLabel = getMetricLabelFromFormData(point_radius_fixed);
@@ -104,7 +104,7 @@ export default function transformProps(chartProps: ChartProps) {
records,
spatial,
radiusMetricLabel,
dimension,
category_name,
js_columns,
);

View File

@@ -33,7 +33,7 @@
"d3-tip": "^0.9.1",
"fast-safe-stringify": "^2.1.1",
"lodash": "^4.17.21",
"dayjs": "^1.11.18",
"dayjs": "^1.11.13",
"nvd3-fork": "^2.0.5",
"dompurify": "^3.2.7",
"prop-types": "^15.8.1",

View File

@@ -37,8 +37,8 @@
"react-dom": "^17.0.2"
},
"devDependencies": {
"@babel/types": "^7.28.4",
"@babel/types": "^7.28.0",
"@types/jest": "^29.5.12",
"jest": "^30.2.0"
"jest": "^30.0.5"
}
}

View File

@@ -55,38 +55,9 @@ const Styles = styled.div<PivotTableStylesProps>`
`;
const PivotTableWrapper = styled.div`
${({ theme }) => `
height: 100%;
max-width: inherit;
overflow: auto;
/* Chrome/Safari/Edge webkit scrollbar styling */
&::-webkit-scrollbar {
width: 8px;
height: 8px;
}
&::-webkit-scrollbar-track {
background: ${theme.colorFillQuaternary};
}
&::-webkit-scrollbar-thumb {
background: ${theme.colorFillSecondary};
border-radius: ${theme.borderRadiusSM}px;
&:hover {
background: ${theme.colorFillTertiary};
}
}
&::-webkit-scrollbar-corner {
background: ${theme.colorFillQuaternary};
}
/* Firefox scrollbar styling */
scrollbar-width: thin;
scrollbar-color: ${theme.colorFillSecondary} ${theme.colorFillQuaternary};
`}
height: 100%;
max-width: inherit;
overflow: auto;
`;
const METRIC_KEY = t('Metric');

View File

@@ -27,7 +27,7 @@ import {
DragEvent,
useEffect,
} from 'react';
import { typedMemo, usePrevious } from '@superset-ui/core';
import { styled, typedMemo, usePrevious } from '@superset-ui/core';
import {
useTable,
usePagination,
@@ -42,7 +42,7 @@ import {
} from 'react-table';
import { matchSorter, rankings } from 'match-sorter';
import { isEqual } from 'lodash';
import { Flex, Space } from '@superset-ui/core/components';
import { Space } from '@superset-ui/core/components';
import GlobalFilter, { GlobalFilterProps } from './components/GlobalFilter';
import SelectPageSize, {
SelectPageSizeProps,
@@ -77,7 +77,7 @@ export interface DataTableProps<D extends object> extends TableOptions<D> {
sticky?: boolean;
rowCount: number;
wrapperRef?: MutableRefObject<HTMLDivElement>;
onColumnOrderChange?: () => void;
onColumnOrderChange: () => void;
renderGroupingHeaders?: () => JSX.Element;
renderTimeComparisonDropdown?: () => JSX.Element;
handleSortByChange: (sortBy: SortByItem[]) => void;
@@ -98,6 +98,24 @@ const sortTypes = {
alphanumeric: sortAlphanumericCaseInsensitive,
};
const StyledSpace = styled(Space)`
display: flex;
justify-content: flex-end;
.search-select-container {
display: flex;
}
.search-by-label {
align-self: center;
margin-right: 4px;
}
`;
const StyledRow = styled.div`
display: flex;
`;
// Be sure to pass our updateMyData and the skipReset option
export default typedMemo(function DataTable<D extends object>({
tableClassName,
@@ -318,7 +336,8 @@ export default typedMemo(function DataTable<D extends object>({
const colToBeMoved = currentCols.splice(columnBeingDragged, 1);
currentCols.splice(newPosition, 0, colToBeMoved[0]);
setColumnOrder(currentCols);
onColumnOrderChange?.();
// toggle value in TableChart to trigger column width recalc
onColumnOrderChange();
}
e.preventDefault();
};
@@ -431,36 +450,30 @@ export default typedMemo(function DataTable<D extends object>({
>
{hasGlobalControl ? (
<div ref={globalControlRef} className="form-inline dt-controls">
<Flex
wrap
className="row"
align="center"
justify="space-between"
gap="middle"
>
{hasPagination ? (
<SelectPageSize
total={resultsSize}
current={resultCurrentPageSize}
options={pageSizeOptions}
selectRenderer={
typeof selectPageSize === 'boolean'
? undefined
: selectPageSize
}
onChange={setPageSize}
/>
) : null}
<Flex wrap align="center" gap="middle">
<StyledRow className="row">
<StyledSpace size="middle">
{hasPagination ? (
<SelectPageSize
total={resultsSize}
current={resultCurrentPageSize}
options={pageSizeOptions}
selectRenderer={
typeof selectPageSize === 'boolean'
? undefined
: selectPageSize
}
onChange={setPageSize}
/>
) : null}
{serverPagination && (
<Space size="small" className="search-select-container">
<span className="search-by-label">Search by:</span>
<div className="search-select-container">
<span className="search-by-label">Search by: </span>
<SearchSelectDropdown
searchOptions={searchOptions}
value={serverPaginationData?.searchColumn || ''}
onChange={onSearchColChange}
/>
</Space>
</div>
)}
{searchInput && (
<GlobalFilter<D>
@@ -480,8 +493,8 @@ export default typedMemo(function DataTable<D extends object>({
{renderTimeComparisonDropdown
? renderTimeComparisonDropdown()
: null}
</Flex>
</Flex>
</StyledSpace>
</StyledRow>
</div>
) : null}
{wrapStickyTable ? wrapStickyTable(renderTable) : renderTable()}

View File

@@ -30,7 +30,6 @@ import {
UIEventHandler,
} from 'react';
import { TableInstance, Hooks } from 'react-table';
import { useTheme, css } from '@superset-ui/core';
import getScrollBarSize from '../utils/getScrollBarSize';
import needScrollBar from '../utils/needScrollBar';
import useMountedMemo from '../utils/useMountedMemo';
@@ -126,8 +125,6 @@ function StickyWrap({
children: Table;
sticky?: StickyState; // current sticky element sizes
}) {
const theme = useTheme();
if (!table || table.type !== 'table') {
throw new Error('<StickyWrap> must have only one <table> element as child');
}
@@ -224,26 +221,6 @@ function StickyWrap({
let footerTable: ReactElement | undefined;
let bodyTable: ReactElement | undefined;
const scrollBarStyles = css`
&::-webkit-scrollbar {
width: 8px;
height: 8px;
}
&::-webkit-scrollbar-track {
background: ${theme.colorFillQuaternary};
}
&::-webkit-scrollbar-thumb {
background: ${theme.colorFillSecondary};
border-radius: ${theme.borderRadiusSM}px;
&:hover {
background: ${theme.colorFillTertiary};
}
}
&::-webkit-scrollbar-corner {
background: ${theme.colorFillQuaternary};
}
`;
if (needSizer) {
const theadWithRef = cloneElement(thead, { ref: theadRef });
const tfootWithRef = tfoot && cloneElement(tfoot, { ref: tfootRef });
@@ -256,7 +233,6 @@ function StickyWrap({
visibility: 'hidden',
scrollbarGutter: 'stable',
}}
css={scrollBarStyles}
role="presentation"
>
{cloneElement(
@@ -340,7 +316,6 @@ function StickyWrap({
overflow: 'auto',
scrollbarGutter: 'stable',
}}
css={scrollBarStyles}
onScroll={sticky.hasHorizontalScroll ? onScroll : undefined}
role="presentation"
>

View File

@@ -195,21 +195,6 @@ function SortIcon<D extends object>({ column }: { column: ColumnInstance<D> }) {
return sortIcon;
}
/**
* Label that is visually hidden but accessible
*/
const VisuallyHidden = styled.label`
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border: 0;
`;
function SearchInput({
count,
value,
@@ -240,10 +225,10 @@ function SelectPageSize({
const { Option } = Select;
return (
<span className="dt-select-page-size">
<VisuallyHidden htmlFor="pageSizeSelect">
<>
<label htmlFor="pageSizeSelect" className="sr-only">
{t('Select page size')}
</VisuallyHidden>
</label>
{t('Show')}{' '}
<Select<number>
id="pageSizeSelect"
@@ -267,7 +252,7 @@ function SelectPageSize({
})}
</Select>{' '}
{t('entries per page')}
</span>
</>
);
}
@@ -311,17 +296,12 @@ export default function TableChart<D extends DataRecord = DataRecord>(
serverPageLength,
slice_id,
} = props;
const comparisonColumns = useMemo(
() => [
{ key: 'all', label: t('Display all') },
{ key: '#', label: '#' },
{ key: '△', label: '△' },
{ key: '%', label: '%' },
],
[],
);
const comparisonColumns = [
{ key: 'all', label: t('Display all') },
{ key: '#', label: '#' },
{ key: '', label: '△' },
{ key: '%', label: '%' },
];
const timestampFormatter = useCallback(
value => getTimeFormatterForGranularity(timeGrain)(value),
[timeGrain],
@@ -373,74 +353,71 @@ export default function TableChart<D extends DataRecord = DataRecord>(
[filters],
);
const getCrossFilterDataMask = useCallback(
(key: string, value: DataRecordValue) => {
let updatedFilters = { ...(filters || {}) };
if (filters && isActiveFilterValue(key, value)) {
updatedFilters = {};
} else {
updatedFilters = {
[key]: [value],
};
}
if (
Array.isArray(updatedFilters[key]) &&
updatedFilters[key].length === 0
) {
delete updatedFilters[key];
}
const getCrossFilterDataMask = (key: string, value: DataRecordValue) => {
let updatedFilters = { ...(filters || {}) };
if (filters && isActiveFilterValue(key, value)) {
updatedFilters = {};
} else {
updatedFilters = {
[key]: [value],
};
}
if (
Array.isArray(updatedFilters[key]) &&
updatedFilters[key].length === 0
) {
delete updatedFilters[key];
}
const groupBy = Object.keys(updatedFilters);
const groupByValues = Object.values(updatedFilters);
const labelElements: string[] = [];
groupBy.forEach(col => {
const isTimestamp = col === DTTM_ALIAS;
const filterValues = ensureIsArray(updatedFilters?.[col]);
if (filterValues.length) {
const valueLabels = filterValues.map(value =>
isTimestamp ? timestampFormatter(value) : value,
);
labelElements.push(`${valueLabels.join(', ')}`);
}
});
const groupBy = Object.keys(updatedFilters);
const groupByValues = Object.values(updatedFilters);
const labelElements: string[] = [];
groupBy.forEach(col => {
const isTimestamp = col === DTTM_ALIAS;
const filterValues = ensureIsArray(updatedFilters?.[col]);
if (filterValues.length) {
const valueLabels = filterValues.map(value =>
isTimestamp ? timestampFormatter(value) : value,
);
labelElements.push(`${valueLabels.join(', ')}`);
}
});
return {
dataMask: {
extraFormData: {
filters:
groupBy.length === 0
? []
: groupBy.map(col => {
const val = ensureIsArray(updatedFilters?.[col]);
if (!val.length)
return {
col,
op: 'IS NULL' as const,
};
return {
dataMask: {
extraFormData: {
filters:
groupBy.length === 0
? []
: groupBy.map(col => {
const val = ensureIsArray(updatedFilters?.[col]);
if (!val.length)
return {
col,
op: 'IN' as const,
val: val.map(el =>
el instanceof Date ? el.getTime() : el!,
),
grain: col === DTTM_ALIAS ? timeGrain : undefined,
op: 'IS NULL' as const,
};
}),
},
filterState: {
label: labelElements.join(', '),
value: groupByValues.length ? groupByValues : null,
filters:
updatedFilters && Object.keys(updatedFilters).length
? updatedFilters
: null,
},
return {
col,
op: 'IN' as const,
val: val.map(el =>
el instanceof Date ? el.getTime() : el!,
),
grain: col === DTTM_ALIAS ? timeGrain : undefined,
};
}),
},
isCurrentValueSelected: isActiveFilterValue(key, value),
};
},
[filters, isActiveFilterValue, timestampFormatter, timeGrain],
);
filterState: {
label: labelElements.join(', '),
value: groupByValues.length ? groupByValues : null,
filters:
updatedFilters && Object.keys(updatedFilters).length
? updatedFilters
: null,
},
},
isCurrentValueSelected: isActiveFilterValue(key, value),
};
};
const toggleFilter = useCallback(
function toggleFilter(key: string, val: DataRecordValue) {
@@ -452,21 +429,17 @@ export default function TableChart<D extends DataRecord = DataRecord>(
[emitCrossFilters, getCrossFilterDataMask, setDataMask],
);
const getSharedStyle = useCallback(
(column: DataColumnMeta): CSSProperties => {
const { isNumeric, config = {} } = column;
const textAlign =
config.horizontalAlign ||
(isNumeric && !isUsingTimeComparison ? 'right' : 'left');
return {
textAlign,
};
},
[isUsingTimeComparison],
);
const comparisonLabels = useMemo(() => [t('Main'), '#', '△', '%'], []);
const getSharedStyle = (column: DataColumnMeta): CSSProperties => {
const { isNumeric, config = {} } = column;
const textAlign =
config.horizontalAlign ||
(isNumeric && !isUsingTimeComparison ? 'right' : 'left');
return {
textAlign,
};
};
const comparisonLabels = [t('Main'), '#', '△', '%'];
const filteredColumnsMeta = useMemo(() => {
if (!isUsingTimeComparison) {
return columnsMeta;
@@ -498,86 +471,79 @@ export default function TableChart<D extends DataRecord = DataRecord>(
selectedComparisonColumns,
]);
const handleContextMenu = useMemo(() => {
if (onContextMenu && !isRawRecords) {
return (
value: D,
cellPoint: {
key: string;
value: DataRecordValue;
isMetric?: boolean;
},
clientX: number,
clientY: number,
) => {
const drillToDetailFilters: BinaryQueryObjectFilterClause[] = [];
filteredColumnsMeta.forEach(col => {
if (!col.isMetric) {
const dataRecordValue = value[col.key];
drillToDetailFilters.push({
col: col.key,
op: '==',
val: dataRecordValue as string | number | boolean,
formattedVal: formatColumnValue(col, dataRecordValue)[1],
});
}
});
onContextMenu(clientX, clientY, {
drillToDetail: drillToDetailFilters,
crossFilter: cellPoint.isMetric
? undefined
: getCrossFilterDataMask(cellPoint.key, cellPoint.value),
drillBy: cellPoint.isMetric
? undefined
: {
filters: [
{
col: cellPoint.key,
op: '==',
val: cellPoint.value as string | number | boolean,
},
],
groupbyFieldName: 'groupby',
},
});
};
}
return undefined;
}, [
onContextMenu,
isRawRecords,
filteredColumnsMeta,
getCrossFilterDataMask,
]);
const getHeaderColumns = useCallback(
(columnsMeta: DataColumnMeta[], enableTimeComparison?: boolean) => {
const resultMap: Record<string, number[]> = {};
if (!enableTimeComparison) {
return resultMap;
}
columnsMeta.forEach((element, index) => {
// Check if element's label is one of the comparison labels
if (comparisonLabels.includes(element.label)) {
// Extract the key portion after the space, assuming the format is always "label key"
const keyPortion = element.key.substring(element.label.length);
// If the key portion is not in the map, initialize it with the current index
if (!resultMap[keyPortion]) {
resultMap[keyPortion] = [index];
} else {
// Add the index to the existing array
resultMap[keyPortion].push(index);
}
const handleContextMenu =
onContextMenu && !isRawRecords
? (
value: D,
cellPoint: {
key: string;
value: DataRecordValue;
isMetric?: boolean;
},
clientX: number,
clientY: number,
) => {
const drillToDetailFilters: BinaryQueryObjectFilterClause[] = [];
filteredColumnsMeta.forEach(col => {
if (!col.isMetric) {
const dataRecordValue = value[col.key];
drillToDetailFilters.push({
col: col.key,
op: '==',
val: dataRecordValue as string | number | boolean,
formattedVal: formatColumnValue(col, dataRecordValue)[1],
});
}
});
onContextMenu(clientX, clientY, {
drillToDetail: drillToDetailFilters,
crossFilter: cellPoint.isMetric
? undefined
: getCrossFilterDataMask(cellPoint.key, cellPoint.value),
drillBy: cellPoint.isMetric
? undefined
: {
filters: [
{
col: cellPoint.key,
op: '==',
val: cellPoint.value as string | number | boolean,
},
],
groupbyFieldName: 'groupby',
},
});
}
});
: undefined;
const getHeaderColumns = (
columnsMeta: DataColumnMeta[],
enableTimeComparison?: boolean,
) => {
const resultMap: Record<string, number[]> = {};
if (!enableTimeComparison) {
return resultMap;
},
[comparisonLabels],
);
}
columnsMeta.forEach((element, index) => {
// Check if element's label is one of the comparison labels
if (comparisonLabels.includes(element.label)) {
// Extract the key portion after the space, assuming the format is always "label key"
const keyPortion = element.key.substring(element.label.length);
// If the key portion is not in the map, initialize it with the current index
if (!resultMap[keyPortion]) {
resultMap[keyPortion] = [index];
} else {
// Add the index to the existing array
resultMap[keyPortion].push(index);
}
}
});
return resultMap;
};
const renderTimeComparisonDropdown = (): JSX.Element => {
const allKey = comparisonColumns[0].key;
@@ -672,11 +638,6 @@ export default function TableChart<D extends DataRecord = DataRecord>(
);
};
const groupHeaderColumns = useMemo(
() => getHeaderColumns(filteredColumnsMeta, isUsingTimeComparison),
[filteredColumnsMeta, getHeaderColumns, isUsingTimeComparison],
);
const renderGroupingHeaders = (): JSX.Element => {
// TODO: Make use of ColumnGroup to render the aditional headers
const headers: any = [];
@@ -758,6 +719,11 @@ export default function TableChart<D extends DataRecord = DataRecord>(
);
};
const groupHeaderColumns = useMemo(
() => getHeaderColumns(filteredColumnsMeta, isUsingTimeComparison),
[filteredColumnsMeta, isUsingTimeComparison],
);
const getColumnConfigs = useCallback(
(
column: DataColumnMeta,
@@ -1120,27 +1086,19 @@ export default function TableChart<D extends DataRecord = DataRecord>(
};
},
[
getSharedStyle,
defaultAlignPN,
defaultColorPN,
columnColorFormatters,
isUsingTimeComparison,
basicColorFormatters,
showCellBars,
isRawRecords,
getValueRange,
emitCrossFilters,
comparisonLabels,
totals,
theme,
sortDesc,
groupHeaderColumns,
allowRenderHtml,
basicColorColumnFormatters,
getValueRange,
isActiveFilterValue,
isRawRecords,
showCellBars,
sortDesc,
toggleFilter,
handleContextMenu,
allowRearrangeColumns,
totals,
columnColorFormatters,
columnOrderToggle,
theme,
],
);
@@ -1173,7 +1131,7 @@ export default function TableChart<D extends DataRecord = DataRecord>(
if (!isEqual(options, searchOptions)) {
setSearchOptions(options || []);
}
}, [columns, searchOptions]);
}, [columns]);
const handleServerPaginationChange = useCallback(
(pageNumber: number, pageSize: number) => {
@@ -1184,7 +1142,7 @@ export default function TableChart<D extends DataRecord = DataRecord>(
};
updateTableOwnState(setDataMask, modifiedOwnState);
},
[serverPaginationData, setDataMask],
[setDataMask],
);
useEffect(() => {
@@ -1196,12 +1154,7 @@ export default function TableChart<D extends DataRecord = DataRecord>(
};
updateTableOwnState(setDataMask, modifiedOwnState);
}
}, [
hasServerPageLengthChanged,
serverPageLength,
serverPaginationData,
setDataMask,
]);
}, []);
const handleSizeChange = useCallback(
({ width, height }: { width: number; height: number }) => {
@@ -1247,7 +1200,7 @@ export default function TableChart<D extends DataRecord = DataRecord>(
};
updateTableOwnState(setDataMask, modifiedOwnState);
},
[serverPagination, serverPaginationData, setDataMask],
[setDataMask, serverPagination],
);
const handleSearch = (searchText: string) => {

View File

@@ -16,8 +16,6 @@
* specific language governing permissions and limitations
* under the License.
*/
import { DatasourceType } from '@superset-ui/core';
export const id = 7;
export const datasourceId = `${id}__table`;
@@ -42,135 +40,125 @@ export default {
},
metrics: [
{
id: 1,
uuid: 'metric-1-uuid',
expression: 'SUM(birth_names.num)',
warning_text: null,
verbose_name: 'sum__num',
metric_name: 'sum__num',
metric_type: 'sum',
certified_by: 'someone',
certification_details: 'foo',
warning_markdown: 'bar',
description: null,
extra:
'{"certification":{"details":"foo", "certified_by":"someone"},"warning_markdown":"bar"}',
},
{
id: 2,
uuid: 'metric-2-uuid',
expression: 'AVG(birth_names.num)',
warning_text: null,
verbose_name: 'avg__num',
metric_name: 'avg__num',
metric_type: 'avg',
description: null,
},
{
id: 3,
uuid: 'metric-3-uuid',
expression: 'SUM(birth_names.num_boys)',
warning_text: null,
verbose_name: 'sum__num_boys',
metric_name: 'sum__num_boys',
metric_type: 'sum',
description: null,
},
{
id: 4,
uuid: 'metric-4-uuid',
expression: 'AVG(birth_names.num_boys)',
warning_text: null,
verbose_name: 'avg__num_boys',
metric_name: 'avg__num_boys',
metric_type: 'avg',
description: null,
},
{
id: 5,
uuid: 'metric-5-uuid',
expression: 'SUM(birth_names.num_girls)',
warning_text: null,
verbose_name: 'sum__num_girls',
metric_name: 'sum__num_girls',
metric_type: 'sum',
description: null,
},
{
id: 6,
uuid: 'metric-6-uuid',
expression: 'AVG(birth_names.num_girls)',
warning_text: null,
verbose_name: 'avg__num_girls',
metric_name: 'avg__num_girls',
metric_type: 'avg',
description: null,
},
{
id: 7,
uuid: 'metric-7-uuid',
expression: 'COUNT(*)',
warning_text: null,
verbose_name: 'COUNT(*)',
metric_name: 'count',
metric_type: 'count',
description: null,
},
],
column_formats: {},
columns: [
{
id: 1,
type: 'DATETIME',
description: null,
filterable: false,
verbose_name: null,
is_dttm: true,
is_active: true,
expression: '',
groupby: false,
column_name: 'ds',
},
{
id: 2,
type: 'VARCHAR(16)',
description: null,
filterable: true,
verbose_name: null,
is_dttm: false,
is_active: true,
expression: '',
groupby: true,
column_name: 'gender',
},
{
id: 3,
type: 'VARCHAR(255)',
description: null,
filterable: true,
verbose_name: null,
is_dttm: false,
is_active: true,
expression: '',
groupby: true,
column_name: 'name',
},
{
id: 4,
type: 'BIGINT',
description: null,
filterable: false,
verbose_name: null,
is_dttm: false,
is_active: true,
expression: '',
groupby: false,
column_name: 'num',
},
{
id: 5,
type: 'VARCHAR(10)',
description: null,
filterable: true,
verbose_name: null,
is_dttm: false,
is_active: true,
expression: '',
groupby: true,
column_name: 'state',
},
{
id: 6,
type: 'BIGINT',
description: null,
filterable: false,
verbose_name: null,
is_dttm: false,
is_active: true,
expression: '',
groupby: false,
column_name: 'num_boys',
},
{
id: 7,
type: 'BIGINT',
description: null,
filterable: false,
verbose_name: null,
is_dttm: false,
is_active: true,
expression: '',
groupby: false,
column_name: 'num_girls',
@@ -181,9 +169,7 @@ export default {
granularity_sqla: [['ds', 'ds']],
main_dttm_col: 'ds',
name: 'birth_names',
owners: [
{ first_name: 'joe', last_name: 'man', id: 1, username: 'joeman' },
],
owners: [{ first_name: 'joe', last_name: 'man', id: 1 }],
database: {
name: 'main',
backend: 'sqlite',
@@ -212,11 +198,6 @@ export default {
['["num_girls", true]', 'num_girls [asc]'],
['["num_girls", false]', 'num_girls [desc]'],
],
type: DatasourceType.Table,
description: null,
is_managed_externally: false,
normalize_columns: false,
always_filter_main_dttm: false,
datasource_name: null,
type: 'table',
},
};

View File

@@ -35,6 +35,7 @@ import {
ButtonGroup,
Tooltip,
Card,
Modal,
Input,
Label,
Loading,
@@ -86,7 +87,6 @@ import {
} from 'src/logger/LogUtils';
import { Icons } from '@superset-ui/core/components/Icons';
import { findPermission } from 'src/utils/findPermission';
import { useConfirmModal } from 'src/hooks/useConfirmModal';
import ExploreCtasResultsButton from '../ExploreCtasResultsButton';
import ExploreResultsButton from '../ExploreResultsButton';
import HighlightedSql from '../HighlightedSql';
@@ -156,14 +156,12 @@ const ResultSetButtons = styled.div`
padding-right: ${({ theme }) => 2 * theme.sizeUnit}px;
`;
const CopyStyledButton = styled(Button)`
const copyButtonStyles = css`
&:hover {
color: ${({ theme }) => theme.colorPrimary};
text-decoration: unset;
}
span > :first-of-type {
margin: 0;
margin: 0px;
}
`;
@@ -228,7 +226,6 @@ const ResultSet = ({
const history = useHistory();
const dispatch = useDispatch();
const logAction = useLogAction({ queryId, sqlEditorId: query.sqlEditorId });
const { showConfirm, ConfirmModal } = useConfirmModal();
const reRunQueryIfSessionTimeoutErrorOnMount = useCallback(() => {
if (
@@ -305,7 +302,7 @@ const ResultSet = ({
const renderControls = () => {
if (search || visualize || csv) {
const { limitingFactor, queryLimit, results, rows } = query;
const { results, queryLimit, limitingFactor, rows } = query;
const limit = queryLimit || results.query.limit;
const rowsCount = Math.min(rows || 0, results?.data?.length || 0);
let { data } = query.results;
@@ -313,6 +310,7 @@ const ResultSet = ({
data = cachedData;
}
const { columns } = query.results;
// Added compute logic to stop user from being able to Save & Explore
const datasource: ISaveableDatasource = {
columns: query.results.columns as ISimpleColumn[],
@@ -329,27 +327,6 @@ const ResultSet = ({
user?.roles,
);
const handleDownloadCsv = (event: React.MouseEvent<HTMLElement>) => {
logAction(LOG_ACTIONS_SQLLAB_DOWNLOAD_CSV, {});
if (limitingFactor === LimitingFactor.Dropdown && limit === rowsCount) {
event.preventDefault();
showConfirm({
title: t('Download is on the way'),
body: t(
'Downloading %(rows)s rows based on the LIMIT configuration. If you want the entire result set, you need to adjust the LIMIT.',
{ rows: rowsCount.toLocaleString() },
),
onConfirm: () => {
window.location.href = getExportCsvUrl(query.id);
},
confirmText: t('OK'),
cancelText: t('Close'),
});
}
};
return (
<ResultSetControls>
<SaveDatasetModal
@@ -370,28 +347,45 @@ const ResultSet = ({
/>
)}
{csv && canExportData && (
<CopyStyledButton
<Button
css={copyButtonStyles}
buttonSize="small"
buttonStyle="secondary"
href={getExportCsvUrl(query.id)}
data-test="export-csv-button"
onClick={handleDownloadCsv}
onClick={() => {
logAction(LOG_ACTIONS_SQLLAB_DOWNLOAD_CSV, {});
if (
limitingFactor === LimitingFactor.Dropdown &&
limit === rowsCount
) {
Modal.warning({
title: t('Download is on the way'),
content: t(
'Downloading %(rows)s rows based on the LIMIT configuration. If you want the entire result set, you need to adjust the LIMIT.',
{ rows: rowsCount.toLocaleString() },
),
});
}
}}
>
<Icons.DownloadOutlined iconSize="m" /> {t('Download to CSV')}
</CopyStyledButton>
</Button>
)}
{canExportData && (
<CopyToClipboard
text={prepareCopyToClipboardTabularData(data, columns)}
wrapped={false}
copyNode={
<CopyStyledButton
<Button
css={copyButtonStyles}
buttonSize="small"
buttonStyle="secondary"
data-test="copy-to-clipboard-button"
>
<Icons.CopyOutlined iconSize="s" /> {t('Copy to Clipboard')}
</CopyStyledButton>
</Button>
}
hideTooltip
onCopyEnd={() =>
@@ -659,71 +653,68 @@ const ResultSet = ({
true,
);
return (
<>
<ResultContainer>
{renderControls()}
{showSql && showSqlInline ? (
<>
<div
css={css`
display: flex;
justify-content: space-between;
align-items: center;
gap: ${GAP}px;
`}
<ResultContainer>
{renderControls()}
{showSql && showSqlInline ? (
<>
<div
css={css`
display: flex;
justify-content: space-between;
align-items: center;
gap: ${GAP}px;
`}
>
<Card
css={[
css`
height: 28px;
width: calc(100% - ${ROWS_CHIP_WIDTH + GAP}px);
code {
width: 100%;
overflow: hidden;
white-space: nowrap !important;
text-overflow: ellipsis;
display: block;
}
`,
]}
>
<Card
css={[
css`
height: 28px;
width: calc(100% - ${ROWS_CHIP_WIDTH + GAP}px);
code {
width: 100%;
overflow: hidden;
white-space: nowrap !important;
text-overflow: ellipsis;
display: block;
}
`,
]}
>
{sql}
</Card>
{renderRowsReturned(false)}
</div>
{renderRowsReturned(true)}
</>
) : (
<>
{sql}
</Card>
{renderRowsReturned(false)}
{renderRowsReturned(true)}
{sql}
</>
)}
<div
css={css`
flex: 1 1 auto;
`}
>
<AutoSizer disableWidth>
{({ height }) => (
<ResultTable
data={data}
queryId={query.id}
orderedColumnKeys={results.columns.map(
col => col.column_name,
)}
height={height}
filterText={searchText}
expandedColumns={expandedColumns}
allowHTML={allowHTML}
/>
)}
</AutoSizer>
</div>
</ResultContainer>
{ConfirmModal}
</>
</div>
{renderRowsReturned(true)}
</>
) : (
<>
{renderRowsReturned(false)}
{renderRowsReturned(true)}
{sql}
</>
)}
<div
css={css`
flex: 1 1 auto;
`}
>
<AutoSizer disableWidth>
{({ height }) => (
<ResultTable
data={data}
queryId={query.id}
orderedColumnKeys={results.columns.map(
col => col.column_name,
)}
height={height}
filterText={searchText}
expandedColumns={expandedColumns}
allowHTML={allowHTML}
/>
)}
</AutoSizer>
</div>
</ResultContainer>
);
}
if (data && data.length === 0) {

View File

@@ -25,8 +25,7 @@ import {
cleanup,
} from 'spec/helpers/testing-library';
import mockDatasource from 'spec/fixtures/mockDatasource';
import { DatasourceType, isFeatureEnabled } from '@superset-ui/core';
import type { DatasetObject } from 'src/features/datasets/types';
import { isFeatureEnabled } from '@superset-ui/core';
import DatasourceEditor from '..';
/* eslint-disable jest/no-export */
@@ -35,17 +34,8 @@ jest.mock('@superset-ui/core', () => ({
isFeatureEnabled: jest.fn(),
}));
interface DatasourceEditorProps {
datasource: DatasetObject;
addSuccessToast: () => void;
addDangerToast: () => void;
onChange: jest.Mock;
columnLabels?: Record<string, string>;
columnLabelTooltips?: Record<string, string>;
}
// Common setup for tests
export const props: DatasourceEditorProps = {
export const props = {
datasource: mockDatasource['7__table'],
addSuccessToast: () => {},
addDangerToast: () => {},
@@ -57,19 +47,16 @@ export const props: DatasourceEditorProps = {
state: 'This is a tooltip for state',
},
};
export const DATASOURCE_ENDPOINT =
'glob:*/datasource/external_metadata_by_name/*';
const routeProps = {
history: {},
location: {},
match: {},
};
export const asyncRender = (renderProps: DatasourceEditorProps) =>
export const asyncRender = props =>
waitFor(() =>
render(<DatasourceEditor {...renderProps} {...routeProps} />, {
render(<DatasourceEditor {...props} {...routeProps} />, {
useRedux: true,
initialState: { common: { currencies: ['USD', 'GBP', 'EUR'] } },
useRouter: true,
@@ -100,16 +87,16 @@ describe('DatasourceEditor', () => {
test('can sync columns from source', async () => {
const columnsTab = screen.getByTestId('collection-tab-Columns');
await userEvent.click(columnsTab);
userEvent.click(columnsTab);
const syncButton = screen.getByText(/sync columns from source/i);
expect(syncButton).toBeInTheDocument();
// Use a Promise to track when fetchMock is called
const fetchPromise = new Promise<string>(resolve => {
const fetchPromise = new Promise(resolve => {
fetchMock.get(
DATASOURCE_ENDPOINT,
(url: string) => {
url => {
resolve(url);
return [];
},
@@ -117,7 +104,7 @@ describe('DatasourceEditor', () => {
);
});
await userEvent.click(syncButton);
userEvent.click(syncButton);
// Wait for the fetch to be called
const url = await fetchPromise;
@@ -127,12 +114,12 @@ describe('DatasourceEditor', () => {
// to add, remove and modify columns accordingly
test('can modify columns', async () => {
const columnsTab = screen.getByTestId('collection-tab-Columns');
await userEvent.click(columnsTab);
userEvent.click(columnsTab);
const getToggles = screen.getAllByRole('button', {
name: /expand row/i,
});
await userEvent.click(getToggles[0]);
userEvent.click(getToggles[0]);
const getTextboxes = await screen.findAllByRole('textbox');
expect(getTextboxes.length).toBeGreaterThanOrEqual(5);
@@ -145,39 +132,22 @@ describe('DatasourceEditor', () => {
'Certification details',
);
// Clear onChange mock to track user action callbacks
props.onChange.mockClear();
await userEvent.type(inputLabel, 'test_label');
await userEvent.type(inputDescription, 'test');
await userEvent.type(inputDtmFormat, 'test');
await userEvent.type(inputCertifiedBy, 'test');
await userEvent.type(inputCertDetails, 'test');
// Verify the inputs were updated with the typed values
await waitFor(() => {
expect(inputLabel).toHaveValue('test_label');
expect(inputDescription).toHaveValue('test');
expect(inputDtmFormat).toHaveValue('test');
expect(inputCertifiedBy).toHaveValue('test');
expect(inputCertDetails).toHaveValue('test');
});
// Verify that onChange was triggered by user actions
await waitFor(() => {
expect(props.onChange).toHaveBeenCalled();
});
userEvent.type(inputLabel, 'test_label');
userEvent.type(inputDescription, 'test');
userEvent.type(inputDtmFormat, 'test');
userEvent.type(inputCertifiedBy, 'test');
userEvent.type(inputCertDetails, 'test');
}, 40000);
test('can delete columns', async () => {
const columnsTab = screen.getByTestId('collection-tab-Columns');
await userEvent.click(columnsTab);
userEvent.click(columnsTab);
const getToggles = screen.getAllByRole('button', {
name: /expand row/i,
});
await userEvent.click(getToggles[0]);
userEvent.click(getToggles[0]);
const deleteButtons = await screen.findAllByRole('button', {
name: /delete item/i,
@@ -185,7 +155,7 @@ describe('DatasourceEditor', () => {
const initialCount = deleteButtons.length;
expect(initialCount).toBeGreaterThan(0);
await userEvent.click(deleteButtons[0]);
userEvent.click(deleteButtons[0]);
await waitFor(() => {
const countRows = screen.getAllByRole('button', { name: /delete item/i });
@@ -195,14 +165,14 @@ describe('DatasourceEditor', () => {
test('can add new columns', async () => {
const calcColsTab = screen.getByTestId('collection-tab-Calculated columns');
await userEvent.click(calcColsTab);
userEvent.click(calcColsTab);
const addBtn = screen.getByRole('button', {
name: /add item/i,
});
expect(addBtn).toBeInTheDocument();
await userEvent.click(addBtn);
userEvent.click(addBtn);
// newColumn (Column name) is the first textbox in the tab
await waitFor(() => {
@@ -215,7 +185,7 @@ describe('DatasourceEditor', () => {
const columnsTab = screen.getByRole('tab', {
name: /settings/i,
});
await userEvent.click(columnsTab);
userEvent.click(columnsTab);
const extraField = screen.getAllByText(/extra/i);
expect(extraField.length).toBeGreaterThan(0);
@@ -229,7 +199,7 @@ describe('DatasourceEditor', () => {
// eslint-disable-next-line no-restricted-globals -- TODO: Migrate from describe blocks
describe('DatasourceEditor Source Tab', () => {
beforeAll(() => {
(isFeatureEnabled as jest.Mock).mockImplementation(() => false);
isFeatureEnabled.mockImplementation(() => false);
});
beforeEach(async () => {
@@ -245,12 +215,12 @@ describe('DatasourceEditor Source Tab', () => {
});
afterAll(() => {
(isFeatureEnabled as jest.Mock).mockRestore();
isFeatureEnabled.mockRestore();
});
test('Source Tab: edit mode', async () => {
const getLockBtn = screen.getByRole('img', { name: /lock/i });
await userEvent.click(getLockBtn);
userEvent.click(getLockBtn);
const physicalRadioBtn = screen.getByRole('radio', {
name: /physical \(table or view\)/i,
@@ -289,7 +259,7 @@ describe('DatasourceEditor Source Tab', () => {
datasource: {
...props.datasource,
table_name: 'Vehicle Sales +',
type: DatasourceType.Query,
datasourceType: 'virtual',
sql: 'SELECT * FROM users',
},
});

View File

@@ -19,16 +19,13 @@
import fetchMock from 'fetch-mock';
import { render, screen, waitFor } from 'spec/helpers/testing-library';
import userEvent from '@testing-library/user-event';
import type { DatasetObject } from 'src/features/datasets/types';
import DatasourceEditor from '..';
import { props, DATASOURCE_ENDPOINT } from './DatasourceEditor.test';
type MetricType = DatasetObject['metrics'][number];
// Optimized render function that doesn't use waitFor initially
// This helps prevent one source of the timeout
const fastRender = (renderProps: typeof props) =>
render(<DatasourceEditor {...renderProps} />, {
const fastRender = props =>
render(<DatasourceEditor {...props} />, {
useRedux: true,
initialState: { common: { currencies: ['USD', 'GBP', 'EUR'] } },
});
@@ -69,15 +66,13 @@ describe('DatasourceEditor Currency Tests', () => {
const metricButton = screen.getByTestId('collection-tab-Metrics');
await userEvent.click(metricButton);
// Find and expand the metric row with currency
// Metrics are sorted by ID descending, so metric with id=1 (which has currency)
// is at position 6 (last). Expand that one.
// Find and expand the first metric row
const expandToggles = await screen.findAllByLabelText(
/expand row/i,
{},
{ timeout: 5000 },
);
await userEvent.click(expandToggles[6]);
await userEvent.click(expandToggles[0]);
// Check for currency section header
const currencyHeader = await screen.findByText(
@@ -96,7 +91,7 @@ describe('DatasourceEditor Currency Tests', () => {
expect(positionSelector).toBeInTheDocument();
// Open the dropdown
await userEvent.click(positionSelector);
userEvent.click(positionSelector);
// Wait for dropdown to open and find the suffix option
const suffixOption = await waitFor(
@@ -104,7 +99,7 @@ describe('DatasourceEditor Currency Tests', () => {
// Look for 'suffix' option in the dropdown
const options = document.querySelectorAll('.ant-select-item-option');
const suffixOpt = Array.from(options).find(opt =>
opt.textContent?.toLowerCase().includes('suffix'),
opt.textContent.toLowerCase().includes('suffix'),
);
if (!suffixOpt) throw new Error('Suffix option not found');
@@ -117,7 +112,7 @@ describe('DatasourceEditor Currency Tests', () => {
propsWithCurrency.onChange.mockClear();
// Click the suffix option
await userEvent.click(suffixOption);
userEvent.click(suffixOption);
// Check if onChange was called with the expected parameters
await waitFor(
@@ -128,12 +123,11 @@ describe('DatasourceEditor Currency Tests', () => {
// More robust check for the metrics array
const metrics = callArg.metrics || [];
const updatedMetric = metrics.find(
(m: MetricType) =>
m.currency && m.currency.symbolPosition === 'suffix',
m => m.currency && m.currency.symbolPosition === 'suffix',
);
expect(updatedMetric).toBeDefined();
expect(updatedMetric?.currency?.symbol).toBe('USD');
expect(updatedMetric.currency.symbol).toBe('USD');
},
{ timeout: 5000 },
);
@@ -148,7 +142,7 @@ describe('DatasourceEditor Currency Tests', () => {
);
// Open the currency dropdown
await userEvent.click(currencySymbol);
userEvent.click(currencySymbol);
// Wait for dropdown to open and find the GBP option
const gbpOption = await waitFor(
@@ -156,7 +150,7 @@ describe('DatasourceEditor Currency Tests', () => {
// Look for 'GBP' option in the dropdown
const options = document.querySelectorAll('.ant-select-item-option');
const gbpOpt = Array.from(options).find(opt =>
opt.textContent?.includes('GBP'),
opt.textContent.includes('GBP'),
);
if (!gbpOpt) throw new Error('GBP option not found');
@@ -169,7 +163,7 @@ describe('DatasourceEditor Currency Tests', () => {
propsWithCurrency.onChange.mockClear();
// Click the GBP option
await userEvent.click(gbpOption);
userEvent.click(gbpOption);
// Verify the onChange with GBP was called
await waitFor(
@@ -180,11 +174,11 @@ describe('DatasourceEditor Currency Tests', () => {
// More robust check
const metrics = callArg.metrics || [];
const updatedMetric = metrics.find(
(m: MetricType) => m.currency && m.currency.symbol === 'GBP',
m => m.currency && m.currency.symbol === 'GBP',
);
expect(updatedMetric).toBeDefined();
expect(updatedMetric?.currency?.symbolPosition).toBe('suffix');
expect(updatedMetric.currency.symbolPosition).toBe('suffix');
},
{ timeout: 5000 },
);

View File

@@ -42,18 +42,15 @@ describe('DatasourceEditor RTL Metrics Tests', () => {
await userEvent.click(metricButton);
const expandToggle = await screen.findAllByLabelText(/expand row/i);
// Metrics are sorted by ID descending, so metric with id=1 (which has certification)
// is at position 6 (last). Expand that one.
await userEvent.click(expandToggle[6]);
await userEvent.click(expandToggle[0]);
// Wait for fields to appear
const certificationDetails = await screen.findByPlaceholderText(
/certification details/i,
);
const certifiedBy = await screen.findByPlaceholderText(/certified by/i);
expect(certificationDetails.value).toEqual('foo');
expect(certificationDetails).toHaveValue('foo');
expect(certifiedBy).toHaveValue('someone');
const warningMarkdown = await screen.findByPlaceholderText(/certified by/i);
expect(warningMarkdown.value).toEqual('someone');
});
test('properly updates the metric information', async () => {
@@ -74,14 +71,14 @@ describe('DatasourceEditor RTL Metrics Tests', () => {
/certification details/i,
);
await waitFor(() => {
expect(certifiedBy).toHaveValue('I am typing a new name');
expect(certifiedBy.value).toEqual('I am typing a new name');
});
await userEvent.clear(certificationDetails);
await userEvent.type(certificationDetails, 'I am typing something new');
await waitFor(() => {
expect(certificationDetails).toHaveValue('I am typing something new');
expect(certificationDetails.value).toEqual('I am typing something new');
});
});
});

View File

@@ -0,0 +1,271 @@
/**
* 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 { render, screen, within, waitFor } from 'spec/helpers/testing-library';
import userEvent from '@testing-library/user-event';
import { QueryParamProvider } from 'use-query-params';
import thunk from 'redux-thunk';
import configureStore from 'redux-mock-store';
import fetchMock from 'fetch-mock';
// Only import components that are directly referenced in tests
import { ListView } from './ListView';
const middlewares = [thunk];
const mockStore = configureStore(middlewares);
function makeMockLocation(query) {
const queryStr = encodeURIComponent(query);
return {
protocol: 'http:',
host: 'localhost',
pathname: '/',
search: queryStr.length ? `?${queryStr}` : '',
};
}
const fetchSelectsMock = jest.fn(() => []);
const mockedProps = {
title: 'Data Table',
columns: [
{
accessor: 'id',
Header: 'ID',
sortable: true,
id: 'id',
},
{
accessor: 'age',
Header: 'Age',
id: 'age',
},
{
accessor: 'name',
Header: 'Name',
id: 'name',
},
{
accessor: 'time',
Header: 'Time',
id: 'time',
},
],
filters: [
{
Header: 'ID',
id: 'id',
input: 'select',
selects: [{ label: 'foo', value: 'bar' }],
operator: 'eq',
},
{
Header: 'Name',
id: 'name',
input: 'search',
operator: 'ct',
},
{
Header: 'Age',
id: 'age',
input: 'select',
fetchSelects: fetchSelectsMock,
paginate: true,
operator: 'eq',
},
{
Header: 'Time',
id: 'time',
input: 'datetime_range',
operator: 'between',
},
],
data: [
{ id: 1, name: 'data 1', age: 10, time: '2020-11-18T07:53:45.354Z' },
{ id: 2, name: 'data 2', age: 1, time: '2020-11-18T07:53:45.354Z' },
],
count: 2,
pageSize: 1,
fetchData: jest.fn(() => []),
loading: false,
bulkSelectEnabled: true,
disableBulkSelect: jest.fn(),
bulkActions: [
{
key: 'something',
name: 'do something',
style: 'danger',
onSelect: jest.fn(),
},
],
cardSortSelectOptions: [
{
desc: false,
id: 'something',
label: 'Alphabetical',
value: 'alphabetical',
},
],
};
const factory = (props = mockedProps) =>
render(
<QueryParamProvider location={makeMockLocation()}>
<ListView {...props} />
</QueryParamProvider>,
{ store: mockStore() },
);
// eslint-disable-next-line no-restricted-globals -- TODO: Migrate from describe blocks
describe('ListView', () => {
beforeEach(() => {
fetchMock.reset();
jest.clearAllMocks();
factory();
});
afterEach(() => {
fetchMock.reset();
mockedProps.fetchData.mockClear();
mockedProps.bulkActions.forEach(ba => {
ba.onSelect.mockClear();
});
});
// Example of converted test:
test('calls fetchData on mount', () => {
expect(mockedProps.fetchData).toHaveBeenCalledWith({
filters: [],
pageIndex: 0,
pageSize: 1,
sortBy: [],
});
});
test('calls fetchData on sort', async () => {
const sortHeader = screen.getAllByTestId('sort-header')[1];
await userEvent.click(sortHeader);
expect(mockedProps.fetchData).toHaveBeenCalledWith({
filters: [],
pageIndex: 0,
pageSize: 1,
sortBy: [
{
desc: false,
id: 'id',
},
],
});
});
// Update pagination control tests for Ant Design pagination
test('renders pagination controls', () => {
const paginationList = screen.getByRole('list');
expect(paginationList).toBeInTheDocument();
const pageOneItem = screen.getByRole('listitem', { name: '1' });
expect(pageOneItem).toBeInTheDocument();
});
test('calls fetchData on page change', async () => {
const pageTwoItem = screen.getByRole('listitem', { name: '2' });
await userEvent.click(pageTwoItem);
await waitFor(() => {
const { calls } = mockedProps.fetchData.mock;
const pageChangeCall = calls.find(
call =>
call[0].pageIndex === 1 &&
call[0].filters.length === 0 &&
call[0].pageSize === 1,
);
expect(pageChangeCall).toBeDefined();
});
});
test('handles bulk actions on 1 row', async () => {
const checkboxes = screen.getAllByRole('checkbox');
await userEvent.click(checkboxes[1]); // Index 1 is the first row checkbox
const bulkActionButton = within(
screen.getByTestId('bulk-select-controls'),
).getByTestId('bulk-select-action');
await userEvent.click(bulkActionButton);
expect(mockedProps.bulkActions[0].onSelect).toHaveBeenCalledWith([
{
age: 10,
id: 1,
name: 'data 1',
time: '2020-11-18T07:53:45.354Z',
},
]);
});
// Update UI filters test to use more specific selector
test('renders UI filters', () => {
const filterControls = screen.getAllByRole('combobox');
expect(filterControls).toHaveLength(2);
});
test('calls fetchData on filter', async () => {
// Handle select filter
const selectFilter = screen.getAllByRole('combobox')[0];
await userEvent.click(selectFilter);
const option = screen.getByText('foo');
await userEvent.click(option);
// Handle search filter
const searchFilter = screen.getByPlaceholderText('Type a value');
await userEvent.type(searchFilter, 'something');
await userEvent.tab();
expect(mockedProps.fetchData).toHaveBeenCalledWith(
expect.objectContaining({
filters: [
{
id: 'id',
operator: 'eq',
value: { label: 'foo', value: 'bar' },
},
{
id: 'name',
operator: 'ct',
value: 'something',
},
],
}),
);
});
test('calls fetchData on card view sort', async () => {
factory({
...mockedProps,
renderCard: jest.fn(),
initialSort: [{ id: 'something' }],
});
const sortSelect = screen.getByTestId('card-sort-select');
await userEvent.click(sortSelect);
const sortOption = screen.getByText('Alphabetical');
await userEvent.click(sortOption);
expect(mockedProps.fetchData).toHaveBeenCalled();
});
});

View File

@@ -16,146 +16,11 @@
* specific language governing permissions and limitations
* under the License.
*/
import { render, screen, within, waitFor } from 'spec/helpers/testing-library';
import userEvent from '@testing-library/user-event';
import { QueryParamProvider } from 'use-query-params';
import thunk from 'redux-thunk';
import configureStore from 'redux-mock-store';
import fetchMock from 'fetch-mock';
import { ReactNode } from 'react';
import { ListView, type ListViewProps } from './ListView';
import { ListViewFilterOperator, type ListViewFetchDataConfig } from './types';
import { render, waitFor } from 'spec/helpers/testing-library';
import { ListView } from './ListView';
// Test-specific type that properly represents mocked props
type MockedListViewProps = Omit<
ListViewProps,
| 'fetchData'
| 'refreshData'
| 'addSuccessToast'
| 'addDangerToast'
| 'disableBulkSelect'
| 'bulkActions'
> & {
fetchData: jest.Mock<unknown[], [ListViewFetchDataConfig]>;
refreshData: jest.Mock;
addSuccessToast: jest.Mock;
addDangerToast: jest.Mock;
disableBulkSelect: jest.Mock;
bulkActions: Array<{
key: string;
name: ReactNode;
onSelect: jest.Mock;
type?: 'primary' | 'secondary' | 'danger';
}>;
};
const middlewares = [thunk];
const mockStore = configureStore(middlewares);
function makeMockLocation(query?: string) {
const queryStr = query ? encodeURIComponent(query) : '';
return {
protocol: 'http:',
host: 'localhost',
pathname: '/',
search: queryStr.length ? `?${queryStr}` : '',
} as Location;
}
const fetchSelectsMock = jest.fn(() =>
Promise.resolve({ data: [], totalCount: 0 }),
);
// Create a properly typed mock with all required fields and Jest mock types
const mockedPropsComprehensive: MockedListViewProps = {
columns: [
{
accessor: 'id',
Header: 'ID',
sortable: true,
id: 'id',
},
{
accessor: 'age',
Header: 'Age',
id: 'age',
},
{
accessor: 'name',
Header: 'Name',
id: 'name',
},
{
accessor: 'time',
Header: 'Time',
id: 'time',
},
],
filters: [
{
key: 'id',
Header: 'ID',
id: 'id',
input: 'select',
selects: [{ label: 'foo', value: 'bar' }],
operator: ListViewFilterOperator.Equals,
},
{
key: 'name',
Header: 'Name',
id: 'name',
input: 'search',
operator: ListViewFilterOperator.Contains,
},
{
key: 'age',
Header: 'Age',
id: 'age',
input: 'select',
fetchSelects: fetchSelectsMock,
paginate: true,
operator: ListViewFilterOperator.Equals,
},
{
key: 'time',
Header: 'Time',
id: 'time',
input: 'datetime_range',
operator: ListViewFilterOperator.Between,
},
],
data: [
{ id: 1, name: 'data 1', age: 10, time: '2020-11-18T07:53:45.354Z' },
{ id: 2, name: 'data 2', age: 1, time: '2020-11-18T07:53:45.354Z' },
],
count: 2,
pageSize: 1,
fetchData: jest.fn<unknown[], [ListViewFetchDataConfig]>(() => []),
loading: false,
refreshData: jest.fn(),
addSuccessToast: jest.fn(),
addDangerToast: jest.fn(),
bulkSelectEnabled: true,
disableBulkSelect: jest.fn(),
bulkActions: [
{
key: 'something',
name: 'do something',
type: 'danger',
onSelect: jest.fn(),
},
],
cardSortSelectOptions: [
{
desc: false,
id: 'something',
label: 'Alphabetical',
value: 'alphabetical',
},
],
};
const mockedPropsSimple = {
const mockedProps = {
title: 'Data Table',
columns: [
{
accessor: 'id',
@@ -194,7 +59,7 @@ const mockedPropsSimple = {
test('redirects to first page when page index is invalid', async () => {
const fetchData = jest.fn();
window.history.pushState({}, '', '/?pageIndex=9');
render(<ListView {...mockedPropsSimple} fetchData={fetchData} />, {
render(<ListView {...mockedProps} fetchData={fetchData} />, {
useRouter: true,
useQueryParams: true,
});
@@ -210,152 +75,3 @@ test('redirects to first page when page index is invalid', async () => {
});
fetchData.mockClear();
});
// Comprehensive test suite from original JSX file
const factory = (overrides?: Partial<ListViewProps>) => {
const props = { ...mockedPropsComprehensive, ...overrides };
return render(
<QueryParamProvider location={makeMockLocation()}>
<ListView {...props} />
</QueryParamProvider>,
{ store: mockStore() },
);
};
// eslint-disable-next-line no-restricted-globals -- TODO: Migrate from describe blocks
describe('ListView', () => {
beforeEach(() => {
fetchMock.reset();
jest.clearAllMocks();
factory();
});
afterEach(() => {
fetchMock.reset();
mockedPropsComprehensive.fetchData.mockClear();
mockedPropsComprehensive.bulkActions.forEach(ba => {
ba.onSelect.mockClear();
});
});
test('calls fetchData on mount', () => {
expect(mockedPropsComprehensive.fetchData).toHaveBeenCalledWith({
filters: [],
pageIndex: 0,
pageSize: 1,
sortBy: [],
});
});
test('calls fetchData on sort', async () => {
const sortHeader = screen.getAllByTestId('sort-header')[1];
await userEvent.click(sortHeader);
expect(mockedPropsComprehensive.fetchData).toHaveBeenCalledWith({
filters: [],
pageIndex: 0,
pageSize: 1,
sortBy: [
{
desc: false,
id: 'id',
},
],
});
});
test('renders pagination controls', () => {
const paginationList = screen.getByRole('list');
expect(paginationList).toBeInTheDocument();
const pageOneItem = screen.getByRole('listitem', { name: '1' });
expect(pageOneItem).toBeInTheDocument();
});
test('calls fetchData on page change', async () => {
const pageTwoItem = screen.getByRole('listitem', { name: '2' });
await userEvent.click(pageTwoItem);
await waitFor(() => {
const { calls } = mockedPropsComprehensive.fetchData.mock;
const pageChangeCall = calls.find(
(call: [ListViewFetchDataConfig]) =>
call?.[0]?.pageIndex === 1 &&
call?.[0]?.filters?.length === 0 &&
call?.[0]?.pageSize === 1,
);
expect(pageChangeCall).toBeDefined();
});
});
test('handles bulk actions on 1 row', async () => {
const checkboxes = screen.getAllByRole('checkbox');
await userEvent.click(checkboxes[1]); // Index 1 is the first row checkbox
const bulkActionButton = within(
screen.getByTestId('bulk-select-controls'),
).getByTestId('bulk-select-action');
await userEvent.click(bulkActionButton);
expect(
mockedPropsComprehensive.bulkActions[0].onSelect,
).toHaveBeenCalledWith([
{
age: 10,
id: 1,
name: 'data 1',
time: '2020-11-18T07:53:45.354Z',
},
]);
});
test('renders UI filters', () => {
const filterControls = screen.getAllByRole('combobox');
expect(filterControls).toHaveLength(2);
});
test('calls fetchData on filter', async () => {
// Handle select filter
const selectFilter = screen.getAllByRole('combobox')[0];
await userEvent.click(selectFilter);
const option = screen.getByText('foo');
await userEvent.click(option);
// Handle search filter
const searchFilter = screen.getByPlaceholderText('Type a value');
await userEvent.type(searchFilter, 'something');
await userEvent.tab();
expect(mockedPropsComprehensive.fetchData).toHaveBeenCalledWith(
expect.objectContaining({
filters: [
{
id: 'id',
operator: 'eq',
value: { label: 'foo', value: 'bar' },
},
{
id: 'name',
operator: 'ct',
value: 'something',
},
],
}),
);
});
test('calls fetchData on card view sort', async () => {
factory({
renderCard: jest.fn(),
initialSort: [{ id: 'something' }],
});
const sortSelect = screen.getByTestId('card-sort-select');
await userEvent.click(sortSelect);
const sortOption = screen.getByText('Alphabetical');
await userEvent.click(sortOption);
expect(mockedPropsComprehensive.fetchData).toHaveBeenCalled();
});
});

View File

@@ -1,390 +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 { AnyAction } from 'redux';
import { ThunkAction, ThunkDispatch } from 'redux-thunk';
import { makeApi, t, getClientErrorObject, DataMask } from '@superset-ui/core';
import { addDangerToast } from 'src/components/MessageToasts/actions';
import { DashboardInfo, RootState } from 'src/dashboard/types';
import {
ChartCustomizationItem,
FilterOption,
ColumnOption,
} from 'src/dashboard/components/nativeFilters/ChartCustomization/types';
import { triggerQuery } from 'src/components/Chart/chartAction';
import { removeDataMask, updateDataMask } from 'src/dataMask/actions';
import { onSave } from './dashboardState';
const createUpdateDashboardApi = (id: number) =>
makeApi<
Partial<DashboardInfo>,
{ result: Partial<DashboardInfo>; last_modified_time: number }
>({
method: 'PUT',
endpoint: `/api/v1/dashboard/${id}`,
});
export interface ChartCustomizationSavePayload {
id: string;
title?: string;
description?: string;
removed?: boolean;
chartId?: number;
customization: {
name: string;
dataset:
| string
| number
| {
value: string | number;
label?: string;
table_name?: string;
schema?: string;
}
| null;
datasetInfo?: {
label: string;
value: number;
table_name: string;
};
column: string | string[] | null;
description?: string;
sortFilter?: boolean;
sortAscending?: boolean;
sortMetric?: string;
hasDefaultValue?: boolean;
defaultValue?: string;
isRequired?: boolean;
selectFirst?: boolean;
defaultDataMask?: DataMask;
defaultValueQueriesData?: ColumnOption[] | null;
aggregation?: string;
canSelectMultiple?: boolean;
};
}
export const SAVE_CHART_CUSTOMIZATION_COMPLETE =
'SAVE_CHART_CUSTOMIZATION_COMPLETE';
export function setChartCustomization(
chartCustomization: ChartCustomizationItem[],
) {
return { type: SAVE_CHART_CUSTOMIZATION_COMPLETE, chartCustomization };
}
export function saveChartCustomization(
chartCustomizationItems: ChartCustomizationSavePayload[],
): ThunkAction<
Promise<{ result: Partial<DashboardInfo>; last_modified_time: number }>,
RootState,
null,
AnyAction
> {
return async function (
dispatch: ThunkDispatch<RootState, null, AnyAction>,
getState: () => RootState,
) {
const { id, metadata, json_metadata } = getState().dashboardInfo;
const currentState = getState();
const currentChartCustomizationItems =
currentState.dashboardInfo.metadata?.chart_customization_config || [];
const existingItemsMap = new Map(
currentChartCustomizationItems.map(item => [item.id, item]),
);
const updatedItemsMap = new Map(existingItemsMap);
chartCustomizationItems.forEach(newItem => {
if (newItem.removed) {
updatedItemsMap.delete(newItem.id);
} else {
const chartCustomizationItem: ChartCustomizationItem = {
id: newItem.id,
title: newItem.title,
removed: newItem.removed,
chartId: newItem.chartId,
customization: newItem.customization,
};
updatedItemsMap.set(newItem.id, chartCustomizationItem);
}
});
const simpleItems = Array.from(updatedItemsMap.values());
dispatch(setChartCustomization(simpleItems));
const removedItems = currentChartCustomizationItems.filter(
existingItem => !updatedItemsMap.has(existingItem.id),
);
removedItems.forEach(removedItem => {
const customizationFilterId = `chart_customization_${removedItem.id}`;
dispatch(removeDataMask(customizationFilterId));
});
simpleItems.forEach(item => {
const customizationFilterId = `chart_customization_${item.id}`;
if (item.customization?.column) {
const existingDataMask = getState().dataMask[customizationFilterId];
const existingFilterState = existingDataMask?.filterState;
dispatch(removeDataMask(customizationFilterId));
const dataMask = {
extraFormData: {},
filterState: {
value:
existingFilterState?.value ||
item.customization?.defaultDataMask?.filterState?.value ||
[],
},
ownState: {
column: item.customization.column,
},
};
dispatch(updateDataMask(customizationFilterId, dataMask));
} else {
dispatch(removeDataMask(customizationFilterId));
}
});
const updateDashboard = createUpdateDashboardApi(id);
try {
let parsedMetadata: any = {};
try {
parsedMetadata = json_metadata ? JSON.parse(json_metadata) : metadata;
} catch (e) {
console.error('Error parsing json_metadata:', e);
parsedMetadata = metadata || {};
}
const updatedMetadata = {
...parsedMetadata,
native_filter_configuration: (
parsedMetadata.native_filter_configuration || []
).filter(
(item: any) =>
!(
item.type === 'CHART_CUSTOMIZATION' &&
item.id === 'chart_customization_groupby'
),
),
chart_customization_config: simpleItems,
};
const response = await updateDashboard({
json_metadata: JSON.stringify(updatedMetadata),
});
const lastModifiedTime = response.last_modified_time;
if (lastModifiedTime) {
dispatch(onSave(lastModifiedTime));
}
const { dashboardState } = getState();
const chartIds = dashboardState.sliceIds || [];
if (chartIds.length > 0) {
chartIds.forEach(chartId => {
dispatch(triggerQuery(true, chartId));
});
}
return response;
} catch (errorObject) {
const { error } = await getClientErrorObject(errorObject);
dispatch(
addDangerToast(error || t('Failed to save chart customization')),
);
throw errorObject;
}
};
}
export const INITIALIZE_CHART_CUSTOMIZATION = 'INITIALIZE_CHART_CUSTOMIZATION';
export interface InitializeChartCustomization {
type: typeof INITIALIZE_CHART_CUSTOMIZATION;
chartCustomizationItems: ChartCustomizationItem[];
}
export function initializeChartCustomization(
chartCustomizationItems: ChartCustomizationItem[],
): ThunkAction<void, RootState, null, AnyAction> {
return (dispatch: ThunkDispatch<RootState, null, AnyAction>) => {
dispatch({
type: INITIALIZE_CHART_CUSTOMIZATION,
chartCustomizationItems,
});
chartCustomizationItems.forEach(item => {
const customizationFilterId = `chart_customization_${item.id}`;
if (item.customization?.column) {
dispatch(removeDataMask(customizationFilterId));
const dataMask = {
extraFormData: {},
filterState: {
value:
item.customization?.defaultDataMask?.filterState?.value || [],
},
ownState: {
column: item.customization.column,
},
};
dispatch(updateDataMask(customizationFilterId, dataMask));
} else {
dispatch(removeDataMask(customizationFilterId));
}
});
};
}
export const SET_CHART_CUSTOMIZATION_DATA_LOADING =
'SET_CHART_CUSTOMIZATION_DATA_LOADING';
export interface SetChartCustomizationDataLoading {
type: typeof SET_CHART_CUSTOMIZATION_DATA_LOADING;
itemId: string;
isLoading: boolean;
}
export function setChartCustomizationDataLoading(
itemId: string,
isLoading: boolean,
): SetChartCustomizationDataLoading {
return {
type: SET_CHART_CUSTOMIZATION_DATA_LOADING,
itemId,
isLoading,
};
}
export const SET_CHART_CUSTOMIZATION_DATA = 'SET_CHART_CUSTOMIZATION_DATA';
export interface SetChartCustomizationData {
type: typeof SET_CHART_CUSTOMIZATION_DATA;
itemId: string;
data: FilterOption[];
}
export function setChartCustomizationData(
itemId: string,
data: FilterOption[],
): SetChartCustomizationData {
return {
type: SET_CHART_CUSTOMIZATION_DATA,
itemId,
data,
};
}
export function loadChartCustomizationData(
itemId: string,
datasetId: string,
columnName: string | string[],
): ThunkAction<Promise<void>, RootState, null, AnyAction> {
return async (dispatch: ThunkDispatch<RootState, null, AnyAction>) => {
if (!datasetId || !columnName) {
return;
}
const actualColumnName = Array.isArray(columnName)
? columnName[0]
: columnName;
if (!actualColumnName) {
return;
}
dispatch(setChartCustomizationDataLoading(itemId, false));
};
}
export const SET_PENDING_CHART_CUSTOMIZATION =
'SET_PENDING_CHART_CUSTOMIZATION';
export interface SetPendingChartCustomization {
type: typeof SET_PENDING_CHART_CUSTOMIZATION;
pendingCustomization: ChartCustomizationSavePayload;
}
export function setPendingChartCustomization(
pendingCustomization: ChartCustomizationSavePayload,
): SetPendingChartCustomization {
return {
type: SET_PENDING_CHART_CUSTOMIZATION,
pendingCustomization,
};
}
export const CLEAR_PENDING_CHART_CUSTOMIZATION =
'CLEAR_PENDING_CHART_CUSTOMIZATION';
export interface ClearPendingChartCustomization {
type: typeof CLEAR_PENDING_CHART_CUSTOMIZATION;
itemId: string;
}
export function clearPendingChartCustomization(
itemId: string,
): ClearPendingChartCustomization {
return {
type: CLEAR_PENDING_CHART_CUSTOMIZATION,
itemId,
};
}
export const CLEAR_ALL_PENDING_CHART_CUSTOMIZATIONS =
'CLEAR_ALL_PENDING_CHART_CUSTOMIZATIONS';
export interface ClearAllPendingChartCustomizations {
type: typeof CLEAR_ALL_PENDING_CHART_CUSTOMIZATIONS;
}
export function clearAllPendingChartCustomizations(): ClearAllPendingChartCustomizations {
return {
type: CLEAR_ALL_PENDING_CHART_CUSTOMIZATIONS,
};
}
export const CLEAR_ALL_CHART_CUSTOMIZATIONS = 'CLEAR_ALL_CHART_CUSTOMIZATIONS';
export interface ClearAllChartCustomizations {
type: typeof CLEAR_ALL_CHART_CUSTOMIZATIONS;
}
export function clearAllChartCustomizations(): ClearAllChartCustomizations {
return {
type: CLEAR_ALL_CHART_CUSTOMIZATIONS,
};
}
export function clearAllChartCustomizationsFromMetadata() {
return clearAllChartCustomizations();
}
export type AnyChartCustomizationAction =
| ReturnType<typeof setChartCustomization>
| InitializeChartCustomization
| SetChartCustomizationDataLoading
| SetChartCustomizationData
| SetPendingChartCustomization
| ClearPendingChartCustomization
| ClearAllPendingChartCustomizations
| ClearAllChartCustomizations;

View File

@@ -17,7 +17,7 @@
* under the License.
*/
import { Dispatch } from 'redux';
import { makeApi, t, getClientErrorObject } from '@superset-ui/core';
import { makeApi, t, getErrorText } from '@superset-ui/core';
import { addDangerToast } from 'src/components/MessageToasts/actions';
import {
ChartConfiguration,
@@ -28,15 +28,6 @@ import {
} from 'src/dashboard/types';
import { onSave } from './dashboardState';
const createUpdateDashboardApi = (id: number) =>
makeApi<
Partial<DashboardInfo>,
{ result: Partial<DashboardInfo>; last_modified_time: number }
>({
method: 'PUT',
endpoint: `/api/v1/dashboard/${id}`,
});
export const DASHBOARD_INFO_UPDATED = 'DASHBOARD_INFO_UPDATED';
export const DASHBOARD_INFO_FILTERS_CHANGED = 'DASHBOARD_INFO_FILTERS_CHANGED';
@@ -69,7 +60,14 @@ export const saveChartConfiguration =
});
const { id, metadata } = getState().dashboardInfo;
const updateDashboard = createUpdateDashboardApi(id);
// TODO extract this out when makeApi supports url parameters
const updateDashboard = makeApi<
Partial<DashboardInfo>,
{ result: DashboardInfo }
>({
method: 'PUT',
endpoint: `/api/v1/dashboard/${id}`,
});
try {
const response = await updateDashboard({
@@ -83,7 +81,7 @@ export const saveChartConfiguration =
});
dispatch(
dashboardInfoChanged({
metadata: JSON.parse(response.result.json_metadata || '{}'),
metadata: JSON.parse(response.result.json_metadata),
}),
);
dispatch({
@@ -118,7 +116,13 @@ export function setCrossFiltersEnabled(crossFiltersEnabled: boolean) {
export function saveFilterBarOrientation(orientation: FilterBarOrientation) {
return async (dispatch: Dispatch, getState: () => RootState) => {
const { id, metadata } = getState().dashboardInfo;
const updateDashboard = createUpdateDashboardApi(id);
const updateDashboard = makeApi<
Partial<DashboardInfo>,
{ result: Partial<DashboardInfo>; last_modified_time: number }
>({
method: 'PUT',
endpoint: `/api/v1/dashboard/${id}`,
});
try {
const response = await updateDashboard({
json_metadata: JSON.stringify({
@@ -138,33 +142,23 @@ export function saveFilterBarOrientation(orientation: FilterBarOrientation) {
dispatch(onSave(lastModifiedTime));
}
} catch (errorObject) {
const { error } = await getClientErrorObject(errorObject);
dispatch(
addDangerToast(
t(
'Sorry, there was an error saving this dashboard: %s',
error || 'Bad Request',
),
),
);
const errorText = await getErrorText(errorObject, 'dashboard');
dispatch(addDangerToast(errorText));
throw errorObject;
}
};
}
export function saveCrossFiltersSetting(crossFiltersEnabled: boolean) {
return async function saveCrossFiltersSettingThunk(
dispatch: Dispatch,
getState: () => RootState,
) {
return async (dispatch: Dispatch, getState: () => RootState) => {
const { id, metadata } = getState().dashboardInfo;
const previousCrossFiltersEnabled =
getState().dashboardInfo.crossFiltersEnabled;
dispatch(setCrossFiltersEnabled(crossFiltersEnabled));
const updateDashboard = createUpdateDashboardApi(id);
const updateDashboard = makeApi<
Partial<DashboardInfo>,
{ result: Partial<DashboardInfo>; last_modified_time: number }
>({
method: 'PUT',
endpoint: `/api/v1/dashboard/${id}`,
});
try {
const response = await updateDashboard({
json_metadata: JSON.stringify({
@@ -172,29 +166,19 @@ export function saveCrossFiltersSetting(crossFiltersEnabled: boolean) {
cross_filters_enabled: crossFiltersEnabled,
}),
});
const updatedDashboard = response.result;
const lastModifiedTime = response.last_modified_time;
if (updatedDashboard.json_metadata) {
const metadata = JSON.parse(updatedDashboard.json_metadata);
dispatch(setCrossFiltersEnabled(metadata.cross_filters_enabled));
}
if (lastModifiedTime) {
dispatch(onSave(lastModifiedTime));
}
dispatch(
dashboardInfoChanged({
metadata: JSON.parse(response.result.json_metadata || '{}'),
}),
);
return response;
} catch (err) {
dispatch(setCrossFiltersEnabled(previousCrossFiltersEnabled));
dispatch(addDangerToast(t('Failed to save cross-filters setting')));
throw err;
} catch (errorObject) {
const errorText = await getErrorText(errorObject, 'dashboard');
dispatch(addDangerToast(errorText));
throw errorObject;
}
};
}

View File

@@ -159,7 +159,7 @@ export function resizeComponent({ id, width, height }) {
};
}
// Drag and Drop --------------------------------------------------------------
// Drag and drop --------------------------------------------------------------
export const MOVE_COMPONENT = 'MOVE_COMPONENT';
const moveComponent = setUnsavedChangesAfterAction(dropResult => ({
type: MOVE_COMPONENT,

View File

@@ -244,8 +244,6 @@ export const hydrateDashboard =
metadata.cross_filters_enabled,
);
const chartCustomizationItems = metadata?.chart_customization_config || [];
return dispatch({
type: HYDRATE_DASHBOARD,
data: {
@@ -310,7 +308,6 @@ export const hydrateDashboard =
activeTabs: activeTabs || dashboardState?.activeTabs || [],
datasetsStatus:
dashboardState?.datasetsStatus || ResourceStatus.Loading,
chartCustomizationItems,
},
dashboardLayout,
},

View File

@@ -196,32 +196,6 @@ export function unsetHoveredNativeFilter(): UnsetHoveredNativeFilter {
};
}
export const SET_HOVERED_CHART_CUSTOMIZATION =
'SET_HOVERED_CHART_CUSTOMIZATION';
export interface SetHoveredChartCustomization {
type: typeof SET_HOVERED_CHART_CUSTOMIZATION;
id: string;
}
export const UNSET_HOVERED_CHART_CUSTOMIZATION =
'UNSET_HOVERED_CHART_CUSTOMIZATION';
export interface UnsetHoveredChartCustomization {
type: typeof UNSET_HOVERED_CHART_CUSTOMIZATION;
}
export function setHoveredChartCustomization(
id: string,
): SetHoveredChartCustomization {
return {
type: SET_HOVERED_CHART_CUSTOMIZATION,
id,
};
}
export function unsetHoveredChartCustomization(): UnsetHoveredChartCustomization {
return {
type: UNSET_HOVERED_CHART_CUSTOMIZATION,
};
}
export const UPDATE_CASCADE_PARENT_IDS = 'UPDATE_CASCADE_PARENT_IDS';
export interface UpdateCascadeParentIds {
type: typeof UPDATE_CASCADE_PARENT_IDS;
@@ -249,6 +223,4 @@ export type AnyFilterAction =
| UnsetFocusedNativeFilter
| SetHoveredNativeFilter
| UnsetHoveredNativeFilter
| SetHoveredChartCustomization
| UnsetHoveredChartCustomization
| UpdateCascadeParentIds;

View File

@@ -152,10 +152,7 @@ const DashboardContainer: FC<DashboardContainerProps> = ({ topLevelTabs }) => {
return;
}
const scopes = nativeFilterScopes.map(filterScope => {
if (
filterScope.id.startsWith(NATIVE_FILTER_DIVIDER_PREFIX) ||
filterScope.id.startsWith('chart_customization_')
) {
if (filterScope.id.startsWith(NATIVE_FILTER_DIVIDER_PREFIX)) {
return {
filterId: filterScope.id,
tabsInScope: [],
@@ -167,14 +164,6 @@ const DashboardContainer: FC<DashboardContainerProps> = ({ topLevelTabs }) => {
item => item?.type === CHART_TYPE,
);
if (!filterScope.scope || !Array.isArray(filterScope.scope.excluded)) {
return {
filterId: filterScope.id,
tabsInScope: [],
chartsInScope: [],
};
}
const chartsInScope: number[] = getChartIdsInFilterScope(
filterScope.scope,
chartIds,

View File

@@ -16,10 +16,11 @@
* specific language governing permissions and limitations
* under the License.
*/
import {
render,
screen,
userEvent,
fireEvent,
waitFor,
} from 'spec/helpers/testing-library';
import {
@@ -27,8 +28,9 @@ import {
getExtensionsRegistry,
makeApi,
} from '@superset-ui/core';
import { Modal } from '@superset-ui/core/components';
import setupCodeOverrides from 'src/setup/setupCodeOverrides';
import DashboardEmbedModal from '.';
import DashboardEmbedModal from './index';
const defaultResponse = {
result: { uuid: 'uuid', dashboard_id: '1', allowed_domains: ['example.com'] },
@@ -56,16 +58,16 @@ const setMockApiNotFound = () => {
};
const setup = () => {
resetMockApi();
render(<DashboardEmbedModal {...defaultProps} />, { useRedux: true });
};
beforeEach(() => {
jest.clearAllMocks();
resetMockApi();
getExtensionsRegistry().set('embedded.modal', undefined);
});
test('renders the embed modal', async () => {
test('renders', async () => {
setup();
expect(await screen.findByText('Embed')).toBeInTheDocument();
});
@@ -77,15 +79,15 @@ test('renders loading state', async () => {
});
});
test('renders modal content with settings', async () => {
setup();
test('renders the modal default content', async () => {
render(<DashboardEmbedModal {...defaultProps} />, { useRedux: true });
expect(await screen.findByText('Settings')).toBeInTheDocument();
expect(
screen.getByText(new RegExp(/Allowed Domains/, 'i')),
).toBeInTheDocument();
});
test('shows Deactivate and Save changes buttons when ready to embed', async () => {
test('renders the correct actions when dashboard is ready to embed', async () => {
setup();
expect(
await screen.findByRole('button', { name: 'Deactivate' }),
@@ -95,7 +97,7 @@ test('shows Deactivate and Save changes buttons when ready to embed', async () =
).toBeInTheDocument();
});
test('shows Enable embedding button when not ready to embed', async () => {
test('renders the correct actions when dashboard is not ready to embed', async () => {
setMockApiNotFound();
render(<DashboardEmbedModal {...defaultProps} />, { useRedux: true });
expect(
@@ -103,7 +105,7 @@ test('shows Enable embedding button when not ready to embed', async () => {
).toBeInTheDocument();
});
test('enables embedding when Enable embedding button is clicked', async () => {
test('enables embedding', async () => {
setMockApiNotFound();
render(<DashboardEmbedModal {...defaultProps} />, { useRedux: true });
@@ -113,33 +115,33 @@ test('enables embedding when Enable embedding button is clicked', async () => {
expect(enableEmbed).toBeInTheDocument();
resetMockApi();
await userEvent.click(enableEmbed);
fireEvent.click(enableEmbed);
expect(
await screen.findByRole('button', { name: 'Deactivate' }),
).toBeInTheDocument();
});
test('shows and hides confirmation alert when deactivating', async () => {
test('shows and hides the confirmation modal on deactivation', async () => {
setup();
const deactivate = await screen.findByRole('button', { name: 'Deactivate' });
await userEvent.click(deactivate);
fireEvent.click(deactivate);
expect(await screen.findByText('Disable embedding?')).toBeInTheDocument();
expect(
screen.getByText('This will remove your current embed configuration.'),
).toBeInTheDocument();
const confirmBtn = screen.getByRole('button', { name: 'Deactivate' });
await userEvent.click(confirmBtn);
const okBtn = screen.getByRole('button', { name: 'OK' });
fireEvent.click(okBtn);
await waitFor(() => {
expect(screen.queryByText('Disable embedding?')).not.toBeInTheDocument();
});
});
test('enables Save Changes button when allowed domains are modified', async () => {
test('enables the "Save Changes" button', async () => {
setup();
const allowedDomainsInput = await screen.findByRole('textbox', {
@@ -151,12 +153,11 @@ test('enables Save Changes button when allowed domains are modified', async () =
expect(saveChangesBtn).toBeDisabled();
expect(allowedDomainsInput).toBeInTheDocument();
await userEvent.clear(allowedDomainsInput);
await userEvent.type(allowedDomainsInput, 'test.com');
fireEvent.change(allowedDomainsInput, { target: { value: 'test.com' } });
expect(saveChangesBtn).toBeEnabled();
});
test('renders extension component when registered', async () => {
test('adds extension to DashboardEmbedModal', async () => {
const extensionsRegistry = getExtensionsRegistry();
extensionsRegistry.set('embedded.modal', () => (
@@ -164,7 +165,7 @@ test('renders extension component when registered', async () => {
));
setupCodeOverrides();
setup();
render(<DashboardEmbedModal {...defaultProps} />, { useRedux: true });
expect(
await screen.findByText('dashboard.embed.modal.extension component'),
@@ -172,3 +173,86 @@ test('renders extension component when registered', async () => {
extensionsRegistry.set('embedded.modal', undefined);
});
// eslint-disable-next-line no-restricted-globals -- TODO: Migrate from describe blocks
describe('Modal.useModal integration', () => {
beforeEach(() => {
jest.clearAllMocks();
});
test('uses Modal.useModal hook for confirmation dialogs', () => {
const useModalSpy = jest.spyOn(Modal, 'useModal');
setup();
// Verify that useModal is called when the component mounts
expect(useModalSpy).toHaveBeenCalled();
useModalSpy.mockRestore();
});
test('renders contextHolder for proper theming', async () => {
const { container } = render(<DashboardEmbedModal {...defaultProps} />, {
useRedux: true,
});
// Wait for component to be rendered
await screen.findByText('Embed');
// The contextHolder is rendered in the component tree
// Check that modal root elements exist for theming
const modalRootElements = container.querySelectorAll('.ant-modal-root');
expect(modalRootElements).toBeDefined();
});
test('confirmation modal inherits theme context', async () => {
setup();
// Click deactivate to trigger the confirmation modal
const deactivate = await screen.findByRole('button', {
name: 'Deactivate',
});
fireEvent.click(deactivate);
// Wait for the modal to appear
const modalTitle = await screen.findByText('Disable embedding?');
expect(modalTitle).toBeInTheDocument();
// Check that the modal is rendered within the component tree (not on body directly)
const modal = modalTitle.closest('.ant-modal-wrap');
expect(modal).toBeInTheDocument();
});
test('does not use Modal.confirm directly', () => {
// Spy on the static Modal.confirm method
const confirmSpy = jest.spyOn(Modal, 'confirm');
setup();
// The component should not call Modal.confirm directly
expect(confirmSpy).not.toHaveBeenCalled();
confirmSpy.mockRestore();
});
test('modal actions work correctly with useModal', async () => {
setup();
// Click deactivate
const deactivate = await screen.findByRole('button', {
name: 'Deactivate',
});
fireEvent.click(deactivate);
// Modal should appear
expect(await screen.findByText('Disable embedding?')).toBeInTheDocument();
// Click Cancel to close modal
const cancelBtn = screen.getByRole('button', { name: 'Cancel' });
fireEvent.click(cancelBtn);
// Modal should close
await waitFor(() => {
expect(screen.queryByText('Disable embedding?')).not.toBeInTheDocument();
});
});
});

View File

@@ -33,8 +33,6 @@ import {
Modal,
Loading,
Form,
Alert,
Space,
} from '@superset-ui/core/components';
import { useToasts } from 'src/components/MessageToasts/withToasts';
import { EmbeddedDashboard } from 'src/dashboard/types';
@@ -66,7 +64,9 @@ export const DashboardEmbedControls = ({ dashboardId, onHide }: Props) => {
const [loading, setLoading] = useState(false); // whether we are currently doing an async thing
const [embedded, setEmbedded] = useState<EmbeddedDashboard | null>(null); // the embedded dashboard config
const [allowedDomains, setAllowedDomains] = useState<string>('');
const [showDeactivateConfirm, setShowDeactivateConfirm] = useState(false);
// Use Modal.useModal hook to ensure proper theming
const [modal, contextHolder] = Modal.useModal();
const endpoint = `/api/v1/dashboard/${dashboardId}/embedded`;
// whether saveable changes have been made to the config
@@ -103,33 +103,35 @@ export const DashboardEmbedControls = ({ dashboardId, onHide }: Props) => {
}, [endpoint, allowedDomains]);
const disableEmbedded = useCallback(() => {
setShowDeactivateConfirm(true);
}, []);
const confirmDeactivate = useCallback(() => {
setLoading(true);
makeApi<{}>({ method: 'DELETE', endpoint })({})
.then(
() => {
setEmbedded(null);
setAllowedDomains('');
setShowDeactivateConfirm(false);
addInfoToast(t('Embedding deactivated.'));
onHide();
},
err => {
console.error(err);
addDangerToast(
t(
'Sorry, something went wrong. Embedding could not be deactivated.',
),
);
},
)
.finally(() => {
setLoading(false);
});
}, [endpoint, addInfoToast, addDangerToast, onHide]);
modal.confirm({
title: t('Disable embedding?'),
content: t('This will remove your current embed configuration.'),
okType: 'danger',
onOk: () => {
setLoading(true);
makeApi<{}>({ method: 'DELETE', endpoint })({})
.then(
() => {
setEmbedded(null);
setAllowedDomains('');
addInfoToast(t('Embedding deactivated.'));
onHide();
},
err => {
console.error(err);
addDangerToast(
t(
'Sorry, something went wrong. Embedding could not be deactivated.',
),
);
},
)
.finally(() => {
setLoading(false);
});
},
});
}, [endpoint, modal]);
useEffect(() => {
setReady(false);
@@ -168,6 +170,7 @@ export const DashboardEmbedControls = ({ dashboardId, onHide }: Props) => {
return (
<>
{contextHolder}
{embedded ? (
DocsConfigDetails ? (
<DocsConfigDetails embeddedId={embedded.uuid} />
@@ -219,71 +222,39 @@ export const DashboardEmbedControls = ({ dashboardId, onHide }: Props) => {
/>
</FormItem>
</Form>
{showDeactivateConfirm ? (
<Alert
closable={false}
type="warning"
message={t('Disable embedding?')}
description={t('This will remove your current embed configuration.')}
css={{
textAlign: 'left',
marginTop: '16px',
}}
action={
<Space>
<Button
key="cancel"
buttonStyle="secondary"
onClick={() => setShowDeactivateConfirm(false)}
>
{t('Cancel')}
</Button>
<Button
key="deactivate"
buttonStyle="danger"
onClick={confirmDeactivate}
loading={loading}
>
{t('Deactivate')}
</Button>
</Space>
}
/>
) : (
<ButtonRow
css={theme => css`
margin-top: ${theme.margin}px;
`}
>
{embedded ? (
<>
<Button
onClick={disableEmbedded}
buttonStyle="secondary"
loading={loading}
>
{t('Deactivate')}
</Button>
<Button
onClick={enableEmbedded}
buttonStyle="primary"
disabled={!isDirty}
loading={loading}
>
{t('Save changes')}
</Button>
</>
) : (
<ButtonRow
css={theme => css`
margin-top: ${theme.margin}px;
`}
>
{embedded ? (
<>
<Button
onClick={disableEmbedded}
buttonStyle="secondary"
loading={loading}
>
{t('Deactivate')}
</Button>
<Button
onClick={enableEmbedded}
buttonStyle="primary"
disabled={!isDirty}
loading={loading}
>
{t('Enable embedding')}
{t('Save changes')}
</Button>
)}
</ButtonRow>
)}
</>
) : (
<Button
onClick={enableEmbedded}
buttonStyle="primary"
loading={loading}
>
{t('Enable embedding')}
</Button>
)}
</ButtonRow>
</>
);
};

View File

@@ -1,350 +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 { memo, useMemo, useState, useRef } from 'react';
import { useSelector } from 'react-redux';
import { styled, t, useTheme } from '@superset-ui/core';
import { Icons, Badge, Tooltip, Tag } from '@superset-ui/core/components';
import { getFilterValueForDisplay } from '../nativeFilters/utils';
import { ChartCustomizationItem } from '../nativeFilters/ChartCustomization/types';
import { RootState } from '../../types';
import { isChartWithoutGroupBy } from '../../util/charts/chartTypeLimitations';
export interface GroupByBadgeProps {
chartId: number;
}
const StyledTag = styled(Tag)`
${({ theme }) => `
display: flex;
align-items: center;
cursor: pointer;
margin-left: ${theme.sizeUnit * 2}px;
margin-right: ${theme.sizeUnit}px;
padding: ${theme.sizeUnit * 0.5}px ${theme.sizeUnit}px;
background: ${theme.colorBgContainer};
border: 1px solid ${theme.colorBorder};
border-radius: ${theme.borderRadius}px;
height: auto;
min-height: 20px;
.anticon {
vertical-align: middle;
color: ${theme.colorTextSecondary};
margin-right: ${theme.sizeUnit * 0.5}px;
font-size: 12px;
&:hover {
color: ${theme.colorText};
}
}
&:hover {
background: ${theme.colorBgTextHover};
}
&:focus-visible {
outline: 2px solid ${theme.colorPrimary};
}
`}
`;
const StyledBadge = styled(Badge)`
${({ theme }) => `
margin-left: ${theme.sizeUnit * 0.5}px;
&>sup.ant-badge-count {
padding: 0 ${theme.sizeUnit * 0.5}px;
min-width: ${theme.sizeUnit * 3}px;
height: ${theme.sizeUnit * 3}px;
line-height: 1.2;
font-weight: ${theme.fontWeightStrong};
font-size: ${theme.fontSizeSM - 2}px;
box-shadow: none;
}
`}
`;
const TooltipContent = styled.div`
${({ theme }) => `
min-width: 200px;
max-width: 300px;
overflow-x: hidden;
color: ${theme.colorText};
font-size: ${theme.fontSizeSM}px;
`}
`;
const SectionName = styled.span`
${({ theme }) => `
font-weight: ${theme.fontWeightStrong};
font-size: ${theme.fontSizeSM}px;
`}
`;
const GroupByInfo = styled.div`
${({ theme }) => `
margin-top: ${theme.sizeUnit}px;
&:not(:last-child) {
padding-bottom: ${theme.sizeUnit * 3}px;
}
`}
`;
const GroupByItem = styled.div`
${({ theme }) => `
font-size: ${theme.fontSizeSM}px;
margin-bottom: ${theme.sizeUnit}px;
&:last-child {
margin-bottom: 0;
}
`}
`;
const GroupByName = styled.span`
${({ theme }) => `
padding-right: ${theme.sizeUnit}px;
font-style: italic;
`}
`;
const GroupByValue = styled.span`
max-width: 100%;
flex-grow: 1;
overflow: auto;
`;
export const GroupByBadge = ({ chartId }: GroupByBadgeProps) => {
const [tooltipVisible, setTooltipVisible] = useState(false);
const triggerRef = useRef<HTMLDivElement>(null);
const theme = useTheme();
const chartCustomizationItems = useSelector<
RootState,
ChartCustomizationItem[]
>(
({ dashboardInfo }) =>
dashboardInfo.metadata?.chart_customization_config || [],
);
const chartDataset = useSelector<RootState, string | null>(state => {
const chart = state.charts[chartId];
if (!chart?.latestQueryFormData?.datasource) {
return null;
}
const chartDatasetParts = String(
chart.latestQueryFormData.datasource,
).split('__');
return chartDatasetParts[0];
});
const applicableGroupBys = useMemo(() => {
if (!chartDataset) {
return [];
}
return chartCustomizationItems.filter(item => {
if (item.removed) return false;
const targetDataset = item.customization?.dataset;
if (!targetDataset) return false;
const targetDatasetId = String(targetDataset);
const matchesDataset = chartDataset === targetDatasetId;
const hasColumn = item.customization?.column;
return matchesDataset && hasColumn;
});
}, [chartCustomizationItems, chartDataset]);
const chart = useSelector<RootState, any>(state => state.charts[chartId]);
const chartType = chart?.latestQueryFormData?.viz_type;
const effectiveGroupBys = useMemo(() => {
if (!chartType || applicableGroupBys.length === 0) {
return [];
}
if (isChartWithoutGroupBy(chartType)) {
return [];
}
const chartFormData = chart?.latestQueryFormData;
if (!chartFormData) {
return applicableGroupBys;
}
const existingColumns = new Set<string>();
const extractColumnNames = (columns: unknown[]): void => {
if (Array.isArray(columns)) {
columns.forEach((col: unknown) => {
if (typeof col === 'string') {
existingColumns.add(col);
} else if (col && typeof col === 'object' && 'column_name' in col) {
existingColumns.add((col as { column_name: string }).column_name);
}
});
}
};
const existingGroupBy = Array.isArray(chartFormData.groupby)
? chartFormData.groupby
: chartFormData.groupby
? [chartFormData.groupby]
: [];
existingGroupBy.forEach((col: string) => existingColumns.add(col));
if (chartFormData.x_axis) {
existingColumns.add(chartFormData.x_axis);
}
const metrics = chartFormData.metrics || [];
metrics.forEach((metric: any) => {
if (typeof metric === 'string') {
existingColumns.add(metric);
} else if (metric && typeof metric === 'object' && 'column' in metric) {
const metricColumn = metric.column;
if (typeof metricColumn === 'string') {
existingColumns.add(metricColumn);
} else if (
metricColumn &&
typeof metricColumn === 'object' &&
'column_name' in metricColumn
) {
existingColumns.add(metricColumn.column_name);
}
}
});
if (chartFormData.series) {
existingColumns.add(chartFormData.series);
}
if (chartFormData.entity) {
existingColumns.add(chartFormData.entity);
}
if (chartFormData.source) {
existingColumns.add(chartFormData.source);
}
if (chartFormData.target) {
existingColumns.add(chartFormData.target);
}
if (chartType === 'pivot_table_v2') {
extractColumnNames(chartFormData.groupbyColumns || []);
}
if (chartType === 'box_plot') {
extractColumnNames(chartFormData.columns || []);
}
return applicableGroupBys.filter(item => {
if (!item.customization?.column) return false;
let columnNames: string[] = [];
if (typeof item.customization.column === 'string') {
columnNames = [item.customization.column];
} else if (Array.isArray(item.customization.column)) {
columnNames = item.customization.column.filter(
col => typeof col === 'string' && col.trim() !== '',
);
} else if (
typeof item.customization.column === 'object' &&
item.customization.column !== null
) {
const columnObj = item.customization.column as any;
const columnName =
columnObj.column_name || columnObj.name || String(columnObj);
if (columnName && columnName.trim() !== '') {
columnNames = [columnName];
}
}
return columnNames.length > 0;
});
}, [applicableGroupBys, chartType, chart]);
const groupByCount = effectiveGroupBys.length;
if (groupByCount === 0) {
return null;
}
const tooltipContent = (
<TooltipContent>
<div>
<SectionName>
{t('Chart Customization (%d)', applicableGroupBys.length)}
</SectionName>
<GroupByInfo>
{effectiveGroupBys.map(groupBy => (
<GroupByItem key={groupBy.id}>
<div>
{groupBy.customization?.name &&
groupBy.customization?.column ? (
<>
<GroupByName>{groupBy.customization.name}: </GroupByName>
<GroupByValue>
{getFilterValueForDisplay(groupBy.customization.column)}
</GroupByValue>
</>
) : (
groupBy.customization?.name || t('None')
)}
</div>
</GroupByItem>
))}
</GroupByInfo>
</div>
</TooltipContent>
);
return (
<Tooltip
title={tooltipContent}
visible={tooltipVisible}
onVisibleChange={setTooltipVisible}
placement="bottom"
overlayStyle={{
color: theme.colorText,
backgroundColor: theme.colorBgContainer,
border: `1px solid ${theme.colorBorder}`,
boxShadow: theme.boxShadow,
}}
overlayInnerStyle={{
color: theme.colorText,
backgroundColor: theme.colorBgContainer,
}}
>
<StyledTag
ref={triggerRef}
aria-label={t('Group by settings (%s)', groupByCount)}
role="button"
tabIndex={0}
>
<Icons.GroupOutlined iconSize="m" />
<StyledBadge
data-test="applied-groupby-count"
count={groupByCount}
showZero={false}
/>
</StyledTag>
</Tooltip>
);
};
export default memo(GroupByBadge);

View File

@@ -21,6 +21,7 @@ import { omit } from 'lodash';
import jsonStringify from 'json-stringify-pretty-compact';
import {
Form,
Modal,
Collapse,
CollapseLabelInModal,
JsonEditor,
@@ -150,7 +151,11 @@ const PropertiesModal = ({
}
}
addDangerToast(errorText);
Modal.error({
title: t('Error'),
content: errorText,
okButtonProps: { danger: true, className: 'btn-danger' },
});
};
const handleDashboardData = useCallback(
@@ -262,7 +267,11 @@ const PropertiesModal = ({
// only fire if the color_scheme is present and invalid
if (colorScheme && !colorChoices.includes(colorScheme)) {
addDangerToast(t('A valid color scheme is required'));
Modal.error({
title: t('Error'),
content: t('A valid color scheme is required'),
okButtonProps: { danger: true, className: 'btn-danger' },
});
onHide();
throw new Error('A valid color scheme is required');
}

View File

@@ -40,7 +40,6 @@ import { useSelector } from 'react-redux';
import SliceHeaderControls from 'src/dashboard/components/SliceHeaderControls';
import { SliceHeaderControlsProps } from 'src/dashboard/components/SliceHeaderControls/types';
import FiltersBadge from 'src/dashboard/components/FiltersBadge';
import GroupByBadge from 'src/dashboard/components/GroupByBadge';
import { RootState } from 'src/dashboard/types';
import { getSliceHeaderTooltip } from 'src/dashboard/util/getSliceHeaderTooltip';
import { DashboardPageIdContext } from 'src/dashboard/containers/DashboardPage';
@@ -300,9 +299,6 @@ const SliceHeader = forwardRef<HTMLDivElement, SliceHeaderProps>(
<CrossFilterIcon iconSize="m" />
</Tooltip>
)}
{!uiConfig.hideChartControls && (
<GroupByBadge chartId={slice.slice_id} />
)}
{!uiConfig.hideChartControls && (
<FiltersBadge chartId={slice.slice_id} />

View File

@@ -267,9 +267,6 @@ const Chart = props => {
const chartConfiguration = useSelector(
state => state.dashboardInfo.metadata?.chart_configuration,
);
const chartCustomizationItems = useSelector(
state => state.dashboardInfo.metadata?.chart_customization_config || [],
);
const colorScheme = useSelector(state => state.dashboardState.colorScheme);
const colorNamespace = useSelector(
state => state.dashboardState.colorNamespace,
@@ -297,7 +294,6 @@ const Chart = props => {
getFormDataWithExtraFilters({
chart,
chartConfiguration,
chartCustomizationItems,
filters: getAppliedFilterValues(props.id),
colorScheme,
colorNamespace,
@@ -314,7 +310,6 @@ const Chart = props => {
[
chart,
chartConfiguration,
chartCustomizationItems,
props.id,
props.extraControls,
colorScheme,

View File

@@ -1,699 +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 { useState, useEffect, useMemo, useCallback, memo } from 'react';
import { t, useTheme } from '@superset-ui/core';
import { useSelector } from 'react-redux';
import { isEmpty, isEqual, sortBy, debounce } from 'lodash';
import { Form } from '@superset-ui/core/components';
import type {
DatasourcesState,
ChartsState,
RootState,
} from 'src/dashboard/types';
import { DatasetSelectLabel } from 'src/features/datasets/DatasetSelectLabel';
import { mostUsedDataset } from '../FiltersConfigModal/FiltersConfigForm/utils';
import ChartCustomizationTitlePane from './ChartCustomizationTitlePane';
import ChartCustomizationForm from './ChartCustomizationForm';
import { createDefaultChartCustomizationItem } from './utils';
import { ChartCustomizationItem } from './types';
import RemovedFilter from '../FiltersConfigModal/FiltersConfigForm/RemovedFilter';
import { selectChartCustomizationItems } from './selectors';
import { BaseConfigModal } from '../ConfigModal/BaseConfigModal';
export interface ChartCustomizationModalProps {
isOpen: boolean;
dashboardId: number;
chartId?: number;
initialItemId?: string;
onCancel: () => void;
onSave: (dashboardId: number, items: ChartCustomizationItem[]) => void;
}
const ChartCustomizationModal = ({
isOpen,
dashboardId,
chartId,
initialItemId,
onCancel,
onSave,
}: ChartCustomizationModalProps) => {
const theme = useTheme();
const [expanded, setExpanded] = useState(false);
const [form] = Form.useForm();
const [items, setItems] = useState<ChartCustomizationItem[]>([]);
const [currentId, setCurrentId] = useState<string | null>(null);
const [saveAlertVisible, setSaveAlertVisible] = useState(false);
const [initialLoadComplete, setInitialLoadComplete] = useState(false);
const [removedItems, setRemovedItems] = useState<
Record<string, { isPending: boolean; timerId?: number } | null>
>({});
const [itemChanges, setItemChanges] = useState<{
modified: string[];
deleted: string[];
reordered: string[];
}>({
modified: [],
deleted: [],
reordered: [],
});
const resetItemChanges = () => {
setItemChanges({
modified: [],
deleted: [],
reordered: [],
});
};
const [erroredItems, setErroredItems] = useState<string[]>([]);
const hasUnsavedChanges = useCallback(() => {
const changed = form.getFieldValue('changed');
const isFieldsTouched = form.isFieldsTouched();
const hasNewItems = items.some(item => !item.id.startsWith('existing_'));
const hasRemovedItems = items.some(item => item.removed);
return changed || isFieldsTouched || hasNewItems || hasRemovedItems;
}, [form, items]);
const validateForm = useCallback(async () => {
try {
const values = await form.validateFields();
setErroredItems([]);
return values;
} catch (error: unknown) {
if (error && typeof error === 'object' && 'errorFields' in error) {
const { errorFields } = error as {
errorFields: Array<{ name: (string | number)[] }>;
};
const errorItemIds = errorFields
.map(field => field.name[1])
.filter(
(id: string | number) =>
id && items.some(item => item.id === String(id)),
)
.map(String);
setErroredItems(errorItemIds);
}
return null;
}
}, [form, items]);
const handleErroredItems = useCallback(() => {
const formValidationFields = form.getFieldsError();
const erroredItemIds: string[] = [];
formValidationFields.forEach(field => {
const itemId = field.name[1] as string;
if (
field.errors.length > 0 &&
!erroredItemIds.includes(itemId) &&
!removedItems[itemId]
) {
erroredItemIds.push(itemId);
}
});
if (!erroredItemIds.length && erroredItems.length > 0) {
setErroredItems([]);
return;
}
if (
erroredItemIds.length > 0 &&
!isEqual(sortBy(erroredItems), sortBy(erroredItemIds))
) {
setErroredItems(erroredItemIds);
}
}, [form, erroredItems, removedItems]);
const resetForm = useCallback(
(isSaving = false) => {
setItems([]);
setCurrentId(null);
setSaveAlertVisible(false);
setInitialLoadComplete(false);
setErroredItems([]);
if (!isSaving) {
form.resetFields();
form.setFieldsValue({ changed: false });
}
},
[form],
);
const handleSave = useCallback(async () => {
const values = await validateForm();
if (values) {
const updatedItems = items.map(item => {
const formItemValues = values.filters?.[item.id] || {};
const isDeleted = itemChanges.deleted.includes(item.id);
const rawDataset = formItemValues.dataset;
const datasetId =
typeof rawDataset === 'object' && rawDataset?.value
? rawDataset.value
: rawDataset;
const formDatasetInfo = formItemValues.datasetInfo;
const datasetInfo =
formDatasetInfo &&
typeof formDatasetInfo === 'object' &&
formDatasetInfo.table_name
? {
value: formDatasetInfo.value,
label: formDatasetInfo.label,
table_name: formDatasetInfo.table_name,
schema: formDatasetInfo.schema,
}
: item.customization.datasetInfo;
const updatedItem = {
...item,
removed: isDeleted,
customization: {
...item.customization,
...formItemValues,
dataset: datasetId,
datasetInfo,
},
};
return updatedItem;
});
onSave(dashboardId, updatedItems);
resetForm(true);
resetItemChanges();
onCancel();
} else if (erroredItems.length > 0) {
setCurrentId(erroredItems[0]);
}
}, [
validateForm,
items,
itemChanges,
onSave,
dashboardId,
resetForm,
resetItemChanges,
onCancel,
erroredItems,
]);
const handleConfirmCancel = useCallback(() => {
resetForm();
onCancel();
}, [resetForm, onCancel]);
const handleCancel = useCallback(() => {
if (hasUnsavedChanges()) {
setSaveAlertVisible(true);
} else {
handleConfirmCancel();
}
}, [hasUnsavedChanges, handleConfirmCancel]);
const existingItems = useSelector(selectChartCustomizationItems);
const loadedDatasets = useSelector<RootState, DatasourcesState>(
({ datasources }) => datasources,
);
const charts = useSelector<RootState, ChartsState>(({ charts }) => charts);
const addItem = useCallback(() => {
const usedDatasetIds = new Set<number>();
items.forEach(existingItem => {
if (existingItem.removed) return;
const { dataset } = existingItem.customization;
if (dataset) {
let datasetId: number;
if (
typeof dataset === 'object' &&
dataset !== null &&
'value' in dataset
) {
datasetId = Number((dataset as { value: string | number }).value);
} else {
datasetId = Number(dataset);
}
if (!Number.isNaN(datasetId)) {
usedDatasetIds.add(datasetId);
}
}
});
let fallbackDatasetId: number | undefined = mostUsedDataset(
loadedDatasets,
charts,
);
if (fallbackDatasetId && usedDatasetIds.has(Number(fallbackDatasetId))) {
const availableDatasets = Object.values(loadedDatasets).filter(
dataset => !usedDatasetIds.has(dataset.id),
);
fallbackDatasetId =
availableDatasets.length > 0 ? availableDatasets[0].id : undefined;
}
const item = createDefaultChartCustomizationItem(
chartId,
fallbackDatasetId,
);
setItems([...items, item]);
setCurrentId(item.id);
const currentFormValues = form.getFieldsValue();
let formattedDataset = null;
if (fallbackDatasetId) {
const datasetInfo = Object.values(loadedDatasets).find(
dataset => dataset.id === Number(fallbackDatasetId),
);
formattedDataset = datasetInfo
? {
value: fallbackDatasetId,
label: DatasetSelectLabel({
id: Number(fallbackDatasetId),
table_name: datasetInfo.table_name || '',
schema: datasetInfo.schema || '',
database: {
database_name:
(datasetInfo.database?.database_name as string) ||
(datasetInfo.database?.name as string) ||
'',
},
}),
table_name: datasetInfo.table_name,
schema: datasetInfo.schema,
}
: {
value: fallbackDatasetId,
label: `Dataset ${fallbackDatasetId}`,
};
}
form.setFieldsValue({
filters: {
...currentFormValues.filters,
[item.id]: {
name: '',
description: '',
dataset: formattedDataset,
column: null,
sortFilter: false,
sortAscending: true,
sortMetric: null,
hasDefaultValue: false,
isRequired: false,
selectFirst: false,
},
},
});
}, [items, chartId, loadedDatasets, charts, form]);
const restoreItem = useCallback(
(id: string) => {
const removal = removedItems[id];
if (removal?.isPending && removal.timerId) {
clearTimeout(removal.timerId);
}
setRemovedItems(current => ({ ...current, [id]: null }));
setItemChanges(prev => ({
...prev,
deleted: prev.deleted.filter(deletedId => deletedId !== id),
}));
},
[removedItems],
);
const handleRemoveItem = useCallback(
(id: string) => {
const completeItemRemoval = (itemId: string) => {
setRemovedItems(removedItems => ({
...removedItems,
[itemId]: { isPending: false },
}));
};
const timerId = window.setTimeout(() => {
completeItemRemoval(id);
}, 3000);
setRemovedItems(removedItems => ({
...removedItems,
[id]: { isPending: true, timerId },
}));
setItemChanges(prev => {
const newChanges = {
...prev,
deleted: [...prev.deleted, id],
};
return newChanges;
});
setTimeout(() => {
handleErroredItems();
}, 0);
if (currentId === id) {
const remainingItems = items.filter(item => item.id !== id);
if (remainingItems.length > 0) {
setCurrentId(remainingItems[0].id);
}
}
},
[items, currentId, handleErroredItems],
);
useEffect(() => {
const currentItemRemoved = removedItems[currentId || ''];
if (currentItemRemoved && !currentItemRemoved.isPending) {
const nextItem = items.find(
item => !removedItems[item.id] && item.id !== currentId,
);
setCurrentId(nextItem?.id || null);
}
}, [currentId, removedItems, items]);
const handleValuesChange = useMemo(
() =>
debounce(() => {
setSaveAlertVisible(false);
handleErroredItems();
}, 1000),
[handleErroredItems],
);
const handleToggleExpand = useCallback(() => {
setExpanded(!expanded);
}, [expanded]);
useEffect(() => {
if (isOpen && !initialLoadComplete) {
form.resetFields();
resetItemChanges();
if (existingItems && existingItems.length > 0) {
setItems(existingItems);
const initialItem = initialItemId
? existingItems.find(item => item.id === initialItemId)
: existingItems[0];
const selectedItemId = initialItem?.id || existingItems[0].id;
setCurrentId(selectedItemId);
const formFilters: Record<string, any> = {};
existingItems.forEach(item => {
const datasetId = item.customization.dataset;
const savedDatasetInfo = item.customization.datasetInfo as
| {
value: number;
label: string;
table_name: string;
schema?: string;
database?: {
database_name?: string;
name?: string;
};
}
| undefined;
const datasetInfo = datasetId
? Object.values(loadedDatasets).find(
dataset => dataset.id === Number(datasetId),
)
: null;
formFilters[item.id] = {
...item.customization,
dataset: datasetId
? typeof datasetId === 'object' && !Array.isArray(datasetId)
? datasetId
: savedDatasetInfo && savedDatasetInfo.table_name
? {
value: datasetId,
label: DatasetSelectLabel({
id: Number(datasetId),
table_name: savedDatasetInfo.table_name || '',
schema: savedDatasetInfo.schema || '',
database: {
database_name:
savedDatasetInfo.database?.database_name ||
savedDatasetInfo.database?.name ||
'',
},
}),
table_name: savedDatasetInfo.table_name,
schema: savedDatasetInfo.schema,
}
: datasetInfo
? {
value: datasetId,
label: DatasetSelectLabel({
id: Number(datasetId),
table_name: datasetInfo.table_name || '',
schema: datasetInfo.schema || '',
database: {
database_name:
(datasetInfo.database?.database_name as string) ||
(datasetInfo.database?.name as string) ||
'',
},
}),
table_name: datasetInfo.table_name,
schema: datasetInfo.schema,
}
: {
value: datasetId,
label: `Dataset ${datasetId}`,
}
: null,
};
});
const initialFormValues = {
filters: formFilters,
changed: false,
};
form.setFieldsValue(initialFormValues);
} else {
const fallbackDatasetId = mostUsedDataset(loadedDatasets, charts);
const newItem = createDefaultChartCustomizationItem(
chartId,
fallbackDatasetId,
);
setCurrentId(newItem.id);
setItems([newItem]);
const datasetInfo = fallbackDatasetId
? Object.values(loadedDatasets).find(
dataset => dataset.id === Number(fallbackDatasetId),
)
: null;
const initialFormValues = {
filters: {
[newItem.id]: {
name: '',
description: '',
dataset: datasetInfo
? {
value: fallbackDatasetId,
label: DatasetSelectLabel({
id: Number(fallbackDatasetId),
table_name: datasetInfo.table_name || '',
schema: datasetInfo.schema || '',
database: {
database_name:
(datasetInfo.database?.database_name as string) ||
(datasetInfo.database?.name as string) ||
'',
},
}),
table_name: datasetInfo.table_name,
schema: datasetInfo.schema,
}
: fallbackDatasetId
? String(fallbackDatasetId)
: null,
column: null,
sortFilter: false,
sortAscending: true,
sortMetric: null,
hasDefaultValue: false,
isRequired: false,
selectFirst: false,
},
},
changed: false,
};
form.setFieldsValue(initialFormValues);
}
setInitialLoadComplete(true);
}
}, [
isOpen,
initialLoadComplete,
existingItems,
initialItemId,
form,
chartId,
loadedDatasets,
charts,
]);
useEffect(() => {
if (!isOpen) {
setInitialLoadComplete(false);
}
}, [isOpen]);
useEffect(() => {
if (!isEmpty(items)) {
setErroredItems(prevErroredItems =>
prevErroredItems.filter(
f => !items.find(item => item.id === f)?.removed,
),
);
}
}, [items]);
const leftPane = (
<div
css={{
minWidth: '290px',
maxWidth: '290px',
height: '100%',
display: 'flex',
flexDirection: 'column',
overflow: 'hidden',
borderRight: `1px solid ${theme.colorSplit}`,
}}
>
<ChartCustomizationTitlePane
items={items.filter(
item => !removedItems[item.id] || removedItems[item.id]?.isPending,
)}
currentId={currentId}
chartId={chartId}
setCurrentId={setCurrentId}
onChange={setCurrentId}
onAdd={addItem}
onRemove={handleRemoveItem}
restoreItem={restoreItem}
removedItems={removedItems}
erroredItems={erroredItems}
/>
</div>
);
const rightPane = (
<div
css={{
flex: 1,
overflow: 'auto',
padding: `${theme.sizeUnit * 4}px ${theme.sizeUnit * 4}px ${theme.sizeUnit * 4}px 0`,
}}
>
{items
.filter(
item => !removedItems[item.id] || removedItems[item.id]?.isPending,
)
.map(item => {
const isRemoved = !!removedItems[item.id];
return (
<div
key={item.id}
css={{
display: item.id === currentId ? 'block' : 'none',
}}
>
{isRemoved ? (
<RemovedFilter onClick={() => restoreItem(item.id)} />
) : (
<ChartCustomizationForm
form={form}
item={item}
removedItems={removedItems}
allItems={items}
onUpdate={updatedItem => {
setItems(prev =>
prev.map(i =>
i.id === updatedItem.id ? updatedItem : i,
),
);
form.setFieldsValue({
changed: true,
});
handleErroredItems();
}}
/>
)}
</div>
);
})}
</div>
);
const content = (
<div
css={{
display: 'flex',
height: '100%',
}}
>
{leftPane}
{rightPane}
</div>
);
return (
<BaseConfigModal
isOpen={isOpen}
title={t('Chart customization')}
expanded={expanded}
onCancel={handleCancel}
onSave={handleSave}
leftPane={content}
rightPane={null}
form={form}
onValuesChange={handleValuesChange}
onToggleExpand={handleToggleExpand}
canSave={!erroredItems.length}
saveAlertVisible={saveAlertVisible}
onDismissSaveAlert={() => setSaveAlertVisible(false)}
onConfirmCancel={handleConfirmCancel}
testId="chart-customization-modal"
/>
);
};
export default memo(ChartCustomizationModal);

View File

@@ -1,183 +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 { FC, forwardRef, MouseEvent } from 'react';
import { styled, t, css, useTheme } from '@superset-ui/core';
import { Icons, Flex } from '@superset-ui/core/components';
import { ChartCustomizationItem } from './types';
interface Props {
items: ChartCustomizationItem[];
currentId: string | null;
onChange: (id: string) => void;
onRemove: (id: string) => void;
restoreItem: (id: string) => void;
removedItems: Record<string, { isPending: boolean; timerId?: number } | null>;
erroredItems?: string[];
}
const FilterTitle = styled.div<{ selected: boolean; errored: boolean }>`
display: flex;
align-items: center;
justify-content: space-between;
padding: ${({ theme }) => theme.sizeUnit * 2}px
${({ theme }) => theme.sizeUnit * 3}px;
background-color: ${({ theme, selected }) =>
selected ? theme.colorPrimaryBg : theme.colorBgTextHover};
border: 1px solid
${({ theme, selected }) => (selected ? theme.colorPrimary : 'transparent')};
border-radius: ${({ theme }) => theme.borderRadius}px;
cursor: pointer;
&:hover {
background-color: ${({ theme }) => theme.colorBgTextHover};
}
${({ theme, errored }) =>
errored &&
`
&.errored div, &.errored .warning {
color: ${theme.colorErrorText};
}
`}
`;
const LabelWrapper = styled.div`
display: flex;
align-items: center;
flex: 1;
overflow: hidden;
`;
const TitleText = styled.div`
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
`;
const UndoButton = styled.span`
margin-left: auto;
color: ${({ theme }) => theme.colorPrimary};
cursor: pointer;
font-size: ${({ theme }) => theme.fontSizeSM}px;
&:hover {
text-decoration: underline;
}
`;
const TrashIcon = styled(Icons.DeleteOutlined)`
cursor: pointer;
margin-left: ${({ theme }) => theme.sizeUnit * 2}px;
color: ${({ theme }) => theme.colorTextSecondary};
&:hover {
color: ${({ theme }) => theme.colorErrorText};
}
`;
const StyledWarning = styled(Icons.ExclamationCircleOutlined)`
margin-left: ${({ theme }) => theme.sizeUnit * 2}px;
color: ${({ theme }) => theme.colorErrorText};
`;
const ChartCustomizationTitleContainer: FC<Props> = forwardRef(
(
{
items,
currentId,
onChange,
onRemove,
restoreItem,
removedItems,
erroredItems = [],
},
ref,
) => {
const theme = useTheme();
return (
<Flex
css={css`
flex-direction: column;
gap: ${theme.sizeUnit * 2}px;
`}
ref={ref as any}
>
{items.map(item => {
const isRemoved = !!removedItems[item.id];
const selected = item.id === currentId;
const isErrored = erroredItems.includes(item.id);
const displayName =
item.customization.name?.trim() || t('[untitled]');
return (
<FilterTitle
key={`group-by-title-${item.id}`}
role="tab"
tabIndex={0}
selected={selected}
errored={isErrored}
onClick={() => onChange(item.id)}
onKeyDown={e => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
onChange(item.id);
}
}}
>
<LabelWrapper>
<TitleText>
{isRemoved ? t('(Removed)') : displayName}
</TitleText>
{isRemoved && (
<UndoButton
role="button"
tabIndex={0}
onClick={(e: MouseEvent<HTMLElement>) => {
e.stopPropagation();
restoreItem(item.id);
}}
>
{t('Undo?')}
</UndoButton>
)}
</LabelWrapper>
{!isRemoved && (
<>
{isErrored && (
<StyledWarning className="warning" iconSize="s" />
)}
<TrashIcon
iconSize="m"
onClick={(e: MouseEvent<HTMLElement>) => {
e.stopPropagation();
onRemove(item.id);
}}
aria-label={t('Remove group by')}
/>
</>
)}
</FilterTitle>
);
})}
</Flex>
);
},
);
export default ChartCustomizationTitleContainer;

View File

@@ -1,123 +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 { FC, useRef } from 'react';
import { styled, t, useTheme } from '@superset-ui/core';
import { Button, Icons } from '@superset-ui/core/components';
import ChartCustomizationTitleContainer from './ChartCustomizationTitleContainer';
import { ChartCustomizationItem } from './types';
import { createDefaultChartCustomizationItem } from './utils';
interface Props {
items: ChartCustomizationItem[];
currentId: string | null;
chartId?: number;
onChange: (id: string) => void;
onAdd: (item: ChartCustomizationItem) => void;
onRemove: (id: string) => void;
restoreItem: (id: string) => void;
removedItems: Record<string, { isPending: boolean; timerId?: number } | null>;
setCurrentId: (id: string) => void;
erroredItems?: string[];
}
const PaneContainer = styled.div`
height: 100%;
display: flex;
flex-direction: column;
padding: ${({ theme }) => theme.sizeUnit * 3}px;
padding-top: 2px;
`;
const ChartCustomizationTitlePane: FC<Props> = ({
items,
currentId,
chartId,
onChange,
onAdd,
onRemove,
restoreItem,
removedItems,
setCurrentId,
erroredItems = [],
}) => {
const theme = useTheme();
const listRef = useRef<HTMLDivElement>(null);
const handleAdd = () => {
const newItem = createDefaultChartCustomizationItem(chartId);
onAdd(newItem);
setCurrentId(newItem.id);
setTimeout(() => {
listRef.current?.scroll({
top: listRef.current.scrollHeight,
behavior: 'smooth',
});
}, 50);
};
return (
<PaneContainer>
<div
ref={listRef}
css={{
flex: 1,
overflowY: 'auto',
}}
>
<ChartCustomizationTitleContainer
items={items}
currentId={currentId}
onChange={onChange}
onRemove={onRemove}
restoreItem={restoreItem}
removedItems={removedItems}
erroredItems={erroredItems}
/>
</div>
<div
css={{
display: 'flex',
justifyContent: 'center',
alignItems: 'flex-start',
paddingTop: theme.sizeUnit * 3,
}}
>
<Button
buttonSize="default"
buttonStyle="secondary"
aria-label={t('Add dynamic group by')}
icon={
<Icons.GroupOutlined
iconColor={theme.colorPrimaryActive}
iconSize="m"
/>
}
onClick={handleAdd}
data-test="add-groupby-button"
>
{t('Add dynamic group by')}
</Button>
</div>
</PaneContainer>
);
};
export default ChartCustomizationTitlePane;

View File

@@ -1,647 +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 { FC, useCallback, useEffect, useMemo, useState } from 'react';
import {
styled,
t,
css,
DataMaskStateWithId,
useTheme,
useTruncation,
} from '@superset-ui/core';
import {
Typography,
Select,
Popover,
Loading,
Icons,
Tooltip,
FormItem,
} from '@superset-ui/core/components';
import { useDispatch, useSelector } from 'react-redux';
import { RootState } from 'src/dashboard/types';
import {
setPendingChartCustomization,
loadChartCustomizationData,
} from 'src/dashboard/actions/chartCustomizationActions';
import { TooltipWithTruncation } from 'src/dashboard/components/nativeFilters/FilterCard/TooltipWithTruncation';
import { dispatchChartCustomizationHoverAction } from '../FilterBar/FilterControls/utils';
import { mergeExtraFormData } from '../utils';
import { ChartCustomizationItem } from './types';
interface GroupByFilterCardProps {
customizationItem: ChartCustomizationItem;
orientation?: 'vertical' | 'horizontal';
}
const Row = styled.div`
display: flex;
align-items: center;
margin: ${({ theme }) => theme.sizeUnit}px 0;
font-size: ${({ theme }) => theme.fontSizeSM}px;
&:first-of-type {
margin-top: 0;
}
&:last-of-type {
margin-bottom: 0;
}
`;
const RowLabel = styled.span`
color: ${({ theme }) => theme.colorTextSecondary};
padding-right: ${({ theme }) => theme.sizeUnit * 4}px;
margin-right: auto;
white-space: nowrap;
`;
const RowValue = styled.div`
color: ${({ theme }) => theme.colorText};
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
display: inline;
`;
const InternalRow = styled.div`
display: flex;
align-items: center;
overflow: hidden;
`;
const FilterTitle = styled(Typography.Text)`
font-size: ${({ theme }) => theme.fontSizeSM}px;
color: ${({ theme }) => theme.colorText};
font-weight: 600;
margin-bottom: ${({ theme }) => theme.sizeUnit}px;
display: flex;
align-items: center;
cursor: pointer;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
&:hover {
color: ${({ theme }) => theme.colorPrimary};
}
`;
const HorizontalFormItem = styled(FormItem)`
&& {
margin-bottom: 0;
align-items: center;
}
.ant-form-item-label {
display: flex;
align-items: center;
overflow: visible;
padding-bottom: 0;
margin-right: ${({ theme }) => theme.sizeUnit * 2}px;
& > label {
margin-bottom: 0;
padding: 0;
line-height: 1;
font-size: ${({ theme }) => theme.fontSizeSM}px;
font-weight: ${({ theme }) => theme.fontWeightNormal};
color: ${({ theme }) => theme.colorText};
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
&::after {
display: none;
}
}
}
.ant-form-item-control {
min-width: 164px;
max-width: none;
}
.select-container {
width: 100%;
}
/* Allow dropdown to expand beyond form item width */
.ant-select-dropdown {
min-width: 200px !important;
max-width: 400px !important;
}
`;
const ToolTipContainer = styled.div`
font-size: ${({ theme }) => theme.fontSize}px;
display: flex;
margin-bottom: ${({ theme }) => theme.sizeUnit}px;
`;
const RequiredFieldIndicator = () => (
<span
css={(theme: any) => ({
color: theme.colorError,
fontSize: `${theme.fontSizeSM}px`,
paddingLeft: '1px',
})}
>
*
</span>
);
const DescriptionTooltip = ({ description }: { description: string }) => (
<ToolTipContainer>
<Tooltip
title={description}
placement="right"
overlayInnerStyle={{
display: '-webkit-box',
WebkitLineClamp: 10,
WebkitBoxOrient: 'vertical',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'normal',
}}
>
<Icons.InfoCircleOutlined
className="text-muted"
role="button"
css={theme => ({
paddingLeft: `${theme.sizeUnit}px`,
})}
/>
</Tooltip>
</ToolTipContainer>
);
const GroupByFilterCardContent: FC<{
customizationItem: ChartCustomizationItem;
hidePopover: () => void;
}> = ({ customizationItem }) => {
const { description, customization } = customizationItem;
const { dataset, name } = customization || {};
const [titleRef, , titleTruncated] = useTruncation();
const displayName = name?.trim() || t('Dynamic group by');
const datasetLabel = useMemo(() => {
const { datasetInfo, dataset: datasetValue } =
customizationItem.customization;
if (datasetInfo) {
if ('table_name' in datasetInfo) {
return (datasetInfo as { table_name: string }).table_name;
}
if ('label' in datasetInfo) {
const { label } = datasetInfo as { label: string };
const tableNameMatch = label.match(/^([^([]+)/);
return tableNameMatch ? tableNameMatch[1].trim() : label;
}
}
if (datasetValue) {
if (typeof datasetValue === 'object' && 'label' in datasetValue) {
const { label } = datasetValue as { label: string };
const tableNameMatch = label.match(/^([^([]+)/);
return tableNameMatch ? tableNameMatch[1].trim() : label;
}
if (typeof datasetValue === 'object' && 'table_name' in datasetValue) {
return (datasetValue as { table_name: string }).table_name;
}
return `Dataset ${dataset}`;
}
return t('Not set');
}, [
customizationItem.customization.dataset,
customizationItem.customization.datasetInfo,
dataset,
]);
const aggregationDisplay = useMemo(() => {
if (customization.sortMetric) {
return customization.sortMetric.toUpperCase();
}
return t('None');
}, [customization.sortMetric]);
return (
<div>
<Row
css={theme => css`
margin-bottom: ${theme.sizeUnit * 3}px;
justify-content: flex-start;
`}
>
<InternalRow>
<Icons.GroupOutlined
iconSize="s"
css={theme => css`
margin-right: ${theme.sizeUnit}px;
`}
/>
<TooltipWithTruncation title={titleTruncated ? displayName : null}>
<div ref={titleRef}>
<Typography.Text strong>{displayName}</Typography.Text>
</div>
</TooltipWithTruncation>
</InternalRow>
</Row>
<Row>
<RowLabel>{t('Type')}</RowLabel>
<RowValue>{t('Dynamic group by')}</RowValue>
</Row>
<Row>
<RowLabel>{t('Dataset')}</RowLabel>
<RowValue>
{typeof datasetLabel === 'string' ? datasetLabel : 'Dataset'}
</RowValue>
</Row>
<Row>
<RowLabel>{t('Aggregation')}</RowLabel>
<RowValue>{aggregationDisplay}</RowValue>
</Row>
{description && (
<Row
css={theme => css`
margin-top: ${theme.sizeUnit * 2}px;
`}
>
<DescriptionTooltip description={description} />
</Row>
)}
</div>
);
};
const GroupByFilterCard: FC<GroupByFilterCardProps> = ({
customizationItem,
orientation = 'vertical',
}) => {
const theme = useTheme();
const { customization } = customizationItem;
const { dataset } = customization || {};
const [filterTitleRef, , titleElementsTruncated] = useTruncation();
const [loading, setLoading] = useState(false);
const [isHoverCardVisible, setIsHoverCardVisible] = useState(false);
const [columnOptions, setColumnOptions] = useState<
{ label: string; value: string }[]
>([]);
const dispatch = useDispatch();
const isHorizontalLayout = orientation === 'horizontal';
const hideHoverCard = useCallback(() => {
setIsHoverCardVisible(false);
}, []);
const setHoveredChartCustomization = useCallback(
() => dispatchChartCustomizationHoverAction(dispatch, customizationItem.id),
[dispatch, customizationItem.id],
);
const unsetHoveredChartCustomization = useCallback(
() => dispatchChartCustomizationHoverAction(dispatch),
[dispatch],
);
const isRequired = useMemo(
() => !!customizationItem.customization?.controlValues?.enableEmptyFilter,
[customizationItem.customization?.controlValues?.enableEmptyFilter],
);
const chartCustomizationLoading = useSelector<RootState, boolean>(
state =>
state.dashboardInfo.chartCustomizationLoading?.[customizationItem.id] ||
false,
);
const datasetId = useMemo(() => {
if (!dataset) return null;
if (typeof dataset === 'string') {
return dataset;
}
if (typeof dataset === 'object' && dataset !== null) {
if ('value' in dataset) {
return String((dataset as { value: string | number }).value);
}
if ('id' in dataset) {
return String((dataset as { id: string | number }).id);
}
}
return null;
}, [dataset]);
const columnName = customizationItem.customization?.column;
const canSelectMultiple =
customizationItem.customization?.canSelectMultiple ?? true;
const columnDisplayName = useMemo(() => {
if (customizationItem.customization?.name) {
return customizationItem.customization.name;
}
if (customizationItem.title) {
return customizationItem.title;
}
if (columnName) {
return columnName;
}
return t('Group By');
}, [
customizationItem.customization?.name,
customizationItem.title,
columnName,
]);
const useChartCustomizationDependencies = () => {
const dataMask = useSelector<RootState, DataMaskStateWithId>(
state => state.dataMask,
);
const filters = useSelector<RootState, any>(
state => state.nativeFilters.filters,
);
return useMemo(() => {
let dependencies = {};
Object.entries(filters).forEach(([filterId, filter]: [string, any]) => {
if (
filter.type === 'DIVIDER' ||
!dataMask[filterId]?.filterState?.value
) {
return;
}
const filterState = dataMask[filterId];
dependencies = mergeExtraFormData(
dependencies,
filterState?.extraFormData,
);
});
return dependencies;
}, [dataMask, filters]);
};
const dependencies = useChartCustomizationDependencies();
useEffect(() => {
if (datasetId && columnName) {
dispatch(
loadChartCustomizationData(customizationItem.id, datasetId, columnName),
);
}
}, [datasetId, columnName, dispatch, customizationItem.id, dependencies]);
useEffect(() => {
setLoading(chartCustomizationLoading);
}, [chartCustomizationLoading]);
useEffect(() => {
const fetchColumnOptions = async () => {
if (!dataset) return;
try {
const datasetId =
typeof dataset === 'string'
? dataset
: typeof dataset === 'object' &&
dataset !== null &&
'value' in dataset
? (dataset as { value: string | number }).value
: null;
if (!datasetId) return;
const response = await fetch(`/api/v1/dataset/${datasetId}`);
const data = await response.json();
if (data?.result?.columns) {
const options = data.result.columns
.filter((col: any) => col.filterable !== false)
.map((col: any) => ({
label: col.verbose_name || col.column_name || col.name,
value: col.column_name || col.name,
}));
setColumnOptions(options);
}
} catch (error) {
console.warn('Failed to fetch column options:', error);
setColumnOptions([]);
}
};
fetchColumnOptions();
}, [dataset]);
const displayTitle = columnDisplayName;
const description =
customizationItem.description?.trim() ||
customizationItem.customization.description?.trim();
return (
<div>
{!isHorizontalLayout && (
<Popover
placement="right"
overlayStyle={{ width: '280px' }}
content={
<GroupByFilterCardContent
customizationItem={customizationItem}
hidePopover={hideHoverCard}
/>
}
mouseEnterDelay={0.2}
mouseLeaveDelay={0.2}
onOpenChange={visible => {
setIsHoverCardVisible(visible);
}}
open={isHoverCardVisible}
arrow={false}
>
<div
css={css`
display: flex;
align-items: center;
margin-bottom: ${theme.sizeUnit}px;
`}
>
<TooltipWithTruncation
title={titleElementsTruncated ? displayTitle : null}
>
<div ref={filterTitleRef}>
<FilterTitle>
{displayTitle}
{isRequired && <RequiredFieldIndicator />}
</FilterTitle>
</div>
</TooltipWithTruncation>
{description && <DescriptionTooltip description={description} />}
</div>
</Popover>
)}
{isHorizontalLayout ? (
<HorizontalFormItem
label={
<Popover
placement="bottom"
overlayStyle={{ width: '240px' }}
content={
<GroupByFilterCardContent
customizationItem={customizationItem}
hidePopover={hideHoverCard}
/>
}
mouseEnterDelay={0.2}
mouseLeaveDelay={0.2}
onOpenChange={visible => {
setIsHoverCardVisible(visible);
}}
open={isHoverCardVisible}
arrow={false}
>
<div
style={{
display: 'flex',
alignItems: 'center',
cursor: 'pointer',
}}
>
{displayTitle}
{isRequired && <RequiredFieldIndicator />}
</div>
</Popover>
}
>
<div
onMouseEnter={setHoveredChartCustomization}
onMouseLeave={unsetHoveredChartCustomization}
>
<Select
allowClear
autoClearSearchValue
placeholder={t('Search columns...')}
value={columnName || null}
onChange={(value: string | string[]) => {
const columnValue = canSelectMultiple
? Array.isArray(value)
? value.length > 0
? value
: null
: value || null
: typeof value === 'string'
? value
: null;
const updatedCustomization = {
...customizationItem.customization,
column: columnValue,
};
dispatch(
setPendingChartCustomization({
id: customizationItem.id,
title: customizationItem.title,
customization: updatedCustomization,
}),
);
}}
options={columnOptions}
showSearch
mode={canSelectMultiple ? 'multiple' : undefined}
filterOption={(input, option) =>
((option?.label as string) ?? '')
.toLowerCase()
.includes(input.toLowerCase())
}
getPopupContainer={triggerNode => triggerNode.parentNode}
oneLine={isHorizontalLayout}
className="select-container"
/>
</div>
</HorizontalFormItem>
) : (
<div
css={css`
margin-bottom: ${theme.sizeUnit}px;
`}
onMouseEnter={setHoveredChartCustomization}
onMouseLeave={unsetHoveredChartCustomization}
>
<Select
allowClear
autoClearSearchValue
placeholder={t('Search columns...')}
value={columnName || null}
onChange={(value: string | string[]) => {
const columnValue = canSelectMultiple
? Array.isArray(value)
? value.length > 0
? value
: null
: value || null
: typeof value === 'string'
? value
: null;
const updatedCustomization = {
...customizationItem.customization,
column: columnValue,
};
dispatch(
setPendingChartCustomization({
id: customizationItem.id,
title: customizationItem.title,
customization: updatedCustomization,
}),
);
}}
options={columnOptions}
showSearch
mode={canSelectMultiple ? 'multiple' : undefined}
filterOption={(input, option) =>
((option?.label as string) ?? '')
.toLowerCase()
.includes(input.toLowerCase())
}
/>
</div>
)}
{loading && (
<div style={{ textAlign: 'center', marginTop: 8 }}>
<Loading position="inline" />
</div>
)}
</div>
);
};
export default GroupByFilterCard;

View File

@@ -1,262 +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 { createSelector } from '@reduxjs/toolkit';
import { RootState } from 'src/dashboard/types';
import { GroupByState } from 'src/dashboard/reducers/groupByCustomizations';
import { ChartCustomizationItem } from './types';
export const selectGroupByState = (state: RootState): GroupByState =>
state.groupByCustomizations?.groupByState || {};
export const selectGroupByValues: (
state: RootState,
groupById: string,
) => string[] = createSelector(
[selectGroupByState, (state: RootState, groupById: string) => groupById],
(groupByState, groupById): string[] =>
groupByState[groupById]?.selectedValues || [],
);
export const selectGroupByLoading: (
state: RootState,
groupById: string,
) => boolean = createSelector(
[selectGroupByState, (state: RootState, groupById: string) => groupById],
(groupByState, groupById): boolean =>
groupByState[groupById]?.isLoading || false,
);
export const selectGroupByOptions: (
state: RootState,
groupById: string,
) => Array<{ label: string; value: string }> = createSelector(
[selectGroupByState, (state: RootState, groupById: string) => groupById],
(groupByState, groupById): Array<{ label: string; value: string }> =>
groupByState[groupById]?.availableOptions || [],
);
export const selectGroupByFormData: (
state: RootState,
chartId: number,
) => {
groupby?: string[];
filters?: Array<{ col: string; op: string; val: string[] }>;
} = createSelector(
[
selectGroupByState,
(state: RootState) =>
state.dashboardInfo.metadata?.chart_customization_config || [],
(state: RootState, chartId: number) => chartId,
],
(
groupByState,
chartCustomizationItems: ChartCustomizationItem[],
chartId,
) => {
const groupByFormData: {
groupby?: string[];
filters?: Array<{ col: string; op: string; val: string[] }>;
} = {};
const matchingCustomizations = chartCustomizationItems.filter(item => {
if (item.removed) return false;
return !item.chartId || item.chartId === chartId;
});
const groupByColumns: string[] = [];
const allFilters: Array<{ col: string; op: string; val: string[] }> = [];
matchingCustomizations.forEach(item => {
const groupById = `chart_customization_${item.id}`;
const groupByValues = groupByState[groupById]?.selectedValues || [];
if (item.customization?.column) {
let columnNames: string[] = [];
if (typeof item.customization.column === 'string') {
columnNames = [item.customization.column];
} else if (Array.isArray(item.customization.column)) {
columnNames = item.customization.column.filter(
col => typeof col === 'string' && col.trim() !== '',
);
} else if (
typeof item.customization.column === 'object' &&
item.customization.column !== null
) {
const columnObj = item.customization.column as any;
const columnName =
columnObj.column_name || columnObj.name || String(columnObj);
if (columnName && columnName.trim() !== '') {
columnNames = [columnName];
}
} else {
return;
}
if (columnNames.length === 0) {
return;
}
columnNames.forEach(columnName => {
if (!groupByColumns.includes(columnName)) {
groupByColumns.push(columnName);
}
});
columnNames.forEach(columnName => {
if (groupByValues.length > 0) {
allFilters.push({
col: columnName,
op: 'IN',
val: groupByValues,
});
}
});
}
});
if (groupByColumns.length > 0) {
groupByFormData.groupby = groupByColumns;
}
if (allFilters.length > 0) {
groupByFormData.filters = allFilters;
}
return groupByFormData;
},
);
export const selectGroupByExtraFormData: (
state: RootState,
chartId: number,
datasetId: string,
) => {
groupby?: string[];
order_by_cols?: string[];
filters?: Array<{ col: string; op: string; val: string[] }>;
} = createSelector(
[
selectGroupByState,
(state: RootState) =>
state.dashboardInfo.metadata?.chart_customization_config || [],
(state: RootState, chartId: number, datasetId: string) => ({
chartId,
datasetId,
}),
],
(
groupByState,
chartCustomizationItems: ChartCustomizationItem[],
{ chartId, datasetId },
) => {
const extraFormData: {
groupby?: string[];
order_by_cols?: string[];
filters?: Array<{ col: string; op: string; val: string[] }>;
} = {};
const matchingCustomizations = chartCustomizationItems.filter(item => {
if (item.removed) return false;
const targetDatasetId = String(item.customization?.dataset || '');
const datasetMatches = targetDatasetId === datasetId;
const chartMatches = !item.chartId || item.chartId === chartId;
return datasetMatches && chartMatches;
});
const groupByColumns: string[] = [];
const allFilters: Array<{ col: string; op: string; val: string[] }> = [];
let orderByConfig: string[] | undefined;
matchingCustomizations.forEach(item => {
const { customization } = item;
const groupById = `chart_customization_${item.id}`;
const groupByValues = groupByState[groupById]?.selectedValues || [];
if (customization?.column) {
let columnNames: string[] = [];
if (typeof customization.column === 'string') {
columnNames = [customization.column];
} else if (Array.isArray(customization.column)) {
columnNames = customization.column.filter(
col => typeof col === 'string' && col.trim() !== '',
);
} else if (
typeof customization.column === 'object' &&
customization.column !== null
) {
const columnObj = customization.column as any;
const columnName =
columnObj.column_name || columnObj.name || String(columnObj);
if (columnName && columnName.trim() !== '') {
columnNames = [columnName];
}
} else {
return;
}
if (columnNames.length === 0) {
return;
}
columnNames.forEach(columnName => {
if (!groupByColumns.includes(columnName)) {
groupByColumns.push(columnName);
}
});
columnNames.forEach(columnName => {
if (groupByValues.length > 0) {
allFilters.push({
col: columnName,
op: 'IN',
val: groupByValues,
});
}
});
if (customization.sortFilter && customization.sortMetric) {
orderByConfig = [
JSON.stringify([
customization.sortMetric,
!customization.sortAscending,
]),
];
}
}
});
if (groupByColumns.length > 0) {
extraFormData.groupby = groupByColumns;
}
if (allFilters.length > 0) {
extraFormData.filters = allFilters;
}
if (orderByConfig) {
extraFormData.order_by_cols = orderByConfig;
}
return extraFormData;
},
);

View File

@@ -1,45 +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 { RootState } from 'src/dashboard/types';
import { ChartCustomizationItem } from './types';
export const selectChartCustomizationItems = (
state: RootState,
): ChartCustomizationItem[] => {
const { metadata } = state.dashboardInfo;
if (
metadata?.chart_customization_config &&
metadata.chart_customization_config.length > 0
) {
return metadata.chart_customization_config;
}
const legacyCustomization = metadata?.native_filter_configuration?.find(
(item: any) =>
item.type === 'CHART_CUSTOMIZATION' &&
item.id === 'chart_customization_groupby',
);
if (legacyCustomization?.chart_customization) {
return legacyCustomization.chart_customization;
}
return [];
};

View File

@@ -1,90 +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 { DataMask } from '@superset-ui/core';
interface DatasetReference {
value: string | number;
label?: string;
table_name?: string;
schema?: string;
}
export interface ColumnOption {
label: string;
value: string;
}
export interface GroupByCustomization {
name: string;
dataset: string | number | DatasetReference | null;
datasetInfo?: {
label: string;
value: number;
table_name: string;
};
column: string | string[] | null;
description?: string;
sortFilter?: boolean;
sortAscending?: boolean;
sortMetric?: string;
hasDefaultValue?: boolean;
defaultValue?: string;
isRequired?: boolean;
selectFirst?: boolean;
defaultDataMask?: DataMask;
defaultValueQueriesData?: ColumnOption[] | null;
aggregation?: string;
canSelectMultiple?: boolean;
controlValues?: {
enableEmptyFilter?: boolean;
};
}
export interface FilterOption {
label: string;
value: string;
}
export interface ChartCustomizationItem {
id: string;
title?: string;
removed?: boolean;
dataset?: string | null;
description?: string;
removeTimerId?: number;
chartId?: number;
settings?: {
sortFilter: boolean;
hasDefaultValue: boolean;
isRequired: boolean;
selectFirstByDefault: boolean;
};
customization: GroupByCustomization;
}
export interface ChartCustomizationChangesType {
modified: string[];
deleted: string[];
reordered: string[];
}
export interface ChartCustomizationRemoval {
isPending: boolean;
timerId: number;
}

View File

@@ -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.
*/
import { useState, useCallback } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { RootState } from 'src/dashboard/types';
import { saveChartCustomization } from 'src/dashboard/actions/chartCustomizationActions';
import { ChartCustomizationItem } from './types';
export const useChartCustomizationModal = (chartId?: number) => {
const [isOpen, setIsOpen] = useState(false);
const dashboardId = useSelector<RootState, number>(
state => state.dashboardInfo.id,
);
const dispatch = useDispatch();
const openChartCustomizationModal = useCallback(() => setIsOpen(true), []);
const closeChartCustomizationModal = useCallback(() => setIsOpen(false), []);
const handleSave = useCallback(
(dashboardId: number, items: ChartCustomizationItem[]) => {
dispatch(saveChartCustomization(items));
setIsOpen(false);
},
[dispatch],
);
return {
isOpen,
dashboardId,
chartId,
openChartCustomizationModal,
closeChartCustomizationModal,
handleSave,
};
};

View File

@@ -1,63 +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 { t } from '@superset-ui/core';
import { ChartCustomizationItem, GroupByCustomization } from './types';
export function generateGroupById(): string {
return `groupby_${Date.now()}`;
}
export const getChartCustomizationIds = (items: ChartCustomizationItem[]) =>
items.map(item => item.id);
export const createDefaultChartCustomizationItem = (
chartId?: number,
defaultDatasetId?: number,
): ChartCustomizationItem => ({
id: generateGroupById(),
title: t('[untitled]'),
dataset: null,
description: '',
removed: false,
chartId,
settings: {
sortFilter: false,
hasDefaultValue: false,
isRequired: false,
selectFirstByDefault: false,
},
customization: {
name: '',
dataset: defaultDatasetId ? String(defaultDatasetId) : null,
column: null,
sortAscending: true,
hasDefaultValue: false,
isRequired: false,
selectFirst: false,
},
});
export const ensureValidCustomization = (
customization: Partial<GroupByCustomization> = {},
): GroupByCustomization => ({
name: customization.name || '',
dataset: customization.dataset || null,
column: customization.column || null,
...customization,
});

View File

@@ -1,148 +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 { ReactNode, useState, useCallback } from 'react';
import type { FormInstance } from '@superset-ui/core/components';
import { ErrorBoundary } from 'src/components/ErrorBoundary';
import { BaseModalBody, BaseForm, BaseModalWrapper } from './SharedStyles';
import { ModalFooter } from './ModalFooter';
export interface BaseConfigModalProps {
isOpen: boolean;
title: string;
expanded?: boolean;
onCancel: () => void;
onSave: () => void;
leftPane: ReactNode;
rightPane: ReactNode;
footer?: ReactNode;
form?: FormInstance;
onValuesChange?: (changedValues: any, allValues: any) => void;
canSave?: boolean;
saveAlertVisible?: boolean;
onDismissSaveAlert?: () => void;
onConfirmCancel?: () => void;
onToggleExpand?: () => void;
testId?: string;
maskClosable?: boolean;
destroyOnClose?: boolean;
centered?: boolean;
}
export const BaseConfigModal = ({
isOpen,
title,
expanded = false,
onCancel,
onSave,
leftPane,
rightPane,
footer,
form,
onValuesChange,
canSave = true,
saveAlertVisible = false,
onDismissSaveAlert,
onConfirmCancel,
onToggleExpand,
testId = 'base-config-modal',
maskClosable = false,
destroyOnClose = true,
centered = true,
}: BaseConfigModalProps) => {
const [internalExpanded, setInternalExpanded] = useState(false);
const isExpandedControlled = onToggleExpand !== undefined;
const isExpanded = isExpandedControlled ? expanded : internalExpanded;
const handleToggleExpand = useCallback(() => {
if (isExpandedControlled && onToggleExpand) {
onToggleExpand();
} else {
setInternalExpanded(!internalExpanded);
}
}, [isExpandedControlled, onToggleExpand, internalExpanded]);
const handleCancel = useCallback(() => {
onCancel();
}, [onCancel]);
const handleSave = useCallback(() => {
onSave();
}, [onSave]);
const handleDismissSaveAlert = useCallback(() => {
if (onDismissSaveAlert) {
onDismissSaveAlert();
}
}, [onDismissSaveAlert]);
const handleConfirmCancel = useCallback(() => {
if (onConfirmCancel) {
onConfirmCancel();
} else {
onCancel();
}
}, [onConfirmCancel, onCancel]);
const defaultFooter = (
<ModalFooter
onCancel={handleCancel}
onSave={handleSave}
onConfirmCancel={handleConfirmCancel}
onDismiss={handleDismissSaveAlert}
saveAlertVisible={saveAlertVisible}
canSave={canSave}
expanded={isExpanded}
onToggleExpand={handleToggleExpand}
saveButtonTestId={`${testId}-save-button`}
cancelButtonTestId={`${testId}-cancel-button`}
/>
);
return (
<BaseModalWrapper
open={isOpen}
onCancel={handleCancel}
onOk={handleSave}
title={title}
footer={footer || defaultFooter}
centered={centered}
destroyOnClose={destroyOnClose}
maskClosable={maskClosable}
data-test={testId}
expanded={isExpanded}
>
<ErrorBoundary>
<BaseModalBody expanded={isExpanded}>
<BaseForm
form={form}
onValuesChange={onValuesChange}
layout="vertical"
css={{ width: '100%' }}
>
{leftPane}
{rightPane}
</BaseForm>
</BaseModalBody>
</ErrorBoundary>
</BaseModalWrapper>
);
};
export default BaseConfigModal;

View File

@@ -1,187 +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 { FC, ReactNode } from 'react';
import {
Button,
type OnClickHandler,
Alert,
Icons,
Flex,
} from '@superset-ui/core/components';
import { t, useTheme, styled, css } from '@superset-ui/core';
import { BaseExpandButtonWrapper } from './SharedStyles';
const StyledAlert = styled(Alert)`
text-align: left;
flex: 1;
& .ant-alert-action {
align-self: center;
}
`;
const StyledActionButtons = styled.div`
display: flex;
`;
const StyledFooterContainer = styled.div`
display: flex;
justify-content: flex-end;
align-items: flex-end;
`;
export interface ConfirmationAlertProps {
title: string;
children: ReactNode;
onConfirm: OnClickHandler;
onDismiss: OnClickHandler;
}
export function ConfirmationAlert({
title,
onConfirm,
onDismiss,
children,
}: ConfirmationAlertProps) {
return (
<StyledAlert
closable={false}
type="warning"
key="alert"
message={title}
description={children}
action={
<StyledActionButtons>
<Button
key="cancel"
buttonSize="small"
buttonStyle="secondary"
onClick={onDismiss}
>
{t('Keep editing')}
</Button>
<Button
key="submit"
buttonSize="small"
buttonStyle="primary"
onClick={onConfirm}
data-test="modal-confirm-cancel-button"
>
{t('Yes, cancel')}
</Button>
</StyledActionButtons>
}
/>
);
}
export interface ModalFooterProps {
onCancel: OnClickHandler;
onSave: OnClickHandler;
onConfirmCancel: OnClickHandler;
onDismiss: OnClickHandler;
saveAlertVisible: boolean;
canSave?: boolean;
expanded?: boolean;
onToggleExpand?: () => void;
saveButtonTestId?: string;
cancelButtonTestId?: string;
saveButtonText?: string;
cancelButtonText?: string;
confirmationTitle?: string;
confirmationMessage?: string;
}
export const ModalFooter: FC<ModalFooterProps> = ({
canSave = true,
onCancel,
onSave,
onDismiss,
onConfirmCancel,
saveAlertVisible,
expanded = false,
onToggleExpand,
saveButtonTestId = 'modal-save-button',
cancelButtonTestId = 'modal-cancel-button',
saveButtonText = t('Save'),
cancelButtonText = t('Cancel'),
confirmationTitle = t('There are unsaved changes.'),
confirmationMessage = t('Are you sure you want to cancel?'),
}) => {
const theme = useTheme();
if (saveAlertVisible) {
return (
<ConfirmationAlert
key="cancel-confirm"
title={confirmationTitle}
onConfirm={onConfirmCancel}
onDismiss={onDismiss}
>
{confirmationMessage}
</ConfirmationAlert>
);
}
return (
<StyledFooterContainer>
<Flex
css={css`
gap: 8px;
`}
>
<Button
key="cancel"
buttonStyle="secondary"
data-test={cancelButtonTestId}
onClick={onCancel}
>
{cancelButtonText}
</Button>
<Button
disabled={!canSave}
key="submit"
buttonStyle="primary"
onClick={onSave}
data-test={saveButtonTestId}
>
{saveButtonText}
</Button>
</Flex>
{onToggleExpand && (
<BaseExpandButtonWrapper>
{(() => {
const ToggleIcon = expanded
? Icons.FullscreenExitOutlined
: Icons.FullscreenOutlined;
return (
<ToggleIcon
iconSize="l"
iconColor={theme.colorTextSecondary}
onClick={onToggleExpand}
/>
);
})()}
</BaseExpandButtonWrapper>
)}
</StyledFooterContainer>
);
};
export default ModalFooter;

View File

@@ -1,110 +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 { styled, css } from '@superset-ui/core';
import { Form, StyledModal } from '@superset-ui/core/components';
const MODAL_MARGIN = 16;
const MIN_WIDTH = 880;
export interface BaseModalWrapperProps {
expanded: boolean;
}
export interface BaseModalBodyProps {
expanded: boolean;
}
export const BaseModalWrapper = styled(StyledModal)<BaseModalWrapperProps>`
min-width: ${MIN_WIDTH}px;
width: ${({ expanded }) => (expanded ? '100%' : MIN_WIDTH)} !important;
@media (max-width: ${MIN_WIDTH + MODAL_MARGIN * 2}px) {
width: 100% !important;
min-width: auto;
}
.ant-modal-body {
padding: 0px;
overflow: auto;
}
${({ expanded }) =>
expanded &&
css`
height: 100%;
.ant-modal-body {
flex: 1 1 auto;
}
.ant-modal-content {
height: 100%;
}
`}
`;
export const BaseModalBody = styled.div<BaseModalBodyProps>`
display: flex;
height: ${({ expanded }) => (expanded ? '100%' : '700px')};
flex-direction: row;
flex: 1;
.filters-list {
display: flex;
flex-direction: column;
}
`;
export const BaseForm = styled(Form)`
width: 100%;
`;
export const BaseExpandButtonWrapper = styled.div`
margin-left: ${({ theme }) => theme.sizeUnit * 4}px;
`;
export const BaseFormItem = styled(Form.Item)<{ expanded?: boolean }>`
width: ${({ expanded }) => (expanded ? '49%' : '260px')};
`;
export const BaseRowFormItem = styled(Form.Item)<{ expanded?: boolean }>`
min-width: ${({ expanded }) => (expanded ? '50%' : '260px')};
`;
export const BaseRowSubFormItem = styled(Form.Item)<{ expanded?: boolean }>`
min-width: ${({ expanded }) => (expanded ? '50%' : '260px')};
`;
export const BaseLabel = styled.span`
${({ theme }) => `
font-size: ${theme.fontSizeSM}px;
color: ${theme.colorTextSecondary};
`}
`;
export const BaseAsterisk = styled.span`
${({ theme }) => `
color: ${theme.colorError};
font-size: ${theme.fontSizeSM}px;
margin-left: ${theme.sizeUnit - 1}px;
&:before {
content: '*';
}
`}
`;

View File

@@ -30,7 +30,6 @@ import { Button } from '@superset-ui/core/components';
import { OPEN_FILTER_BAR_WIDTH } from 'src/dashboard/constants';
import tinycolor from 'tinycolor2';
import { FilterBarOrientation } from 'src/dashboard/types';
import { ChartCustomizationItem } from 'src/dashboard/components/nativeFilters/ChartCustomization/types';
import { getFilterBarTestId } from '../utils';
interface ActionButtonsProps {
@@ -39,7 +38,6 @@ interface ActionButtonsProps {
onClearAll: () => void;
dataMaskSelected: DataMaskState;
dataMaskApplied: DataMaskStateWithId;
chartCustomizationItems?: ChartCustomizationItem[];
isApplyDisabled: boolean;
filterBarOrientation?: FilterBarOrientation;
}
@@ -108,31 +106,17 @@ const ActionButtons = ({
dataMaskSelected,
isApplyDisabled,
filterBarOrientation = FilterBarOrientation.Vertical,
chartCustomizationItems,
}: ActionButtonsProps) => {
const isClearAllEnabled = useMemo(() => {
const hasSelectedChanges = Object.entries(dataMaskSelected).some(
([, mask]) => {
const hasValue = isDefined(mask?.filterState?.value);
const hasGroupBy = isDefined(mask?.ownState?.column);
return hasValue || hasGroupBy;
},
);
const hasAppliedChanges = Object.entries(dataMaskApplied).some(
([, mask]) => {
const hasValue = isDefined(mask?.filterState?.value);
const hasGroupBy = isDefined(mask?.ownState?.column);
return hasValue || hasGroupBy;
},
);
const hasChartCustomizations = chartCustomizationItems?.some(
item => item.customization?.column && !item.removed,
);
return hasSelectedChanges || hasAppliedChanges || hasChartCustomizations;
}, [dataMaskSelected, dataMaskApplied, chartCustomizationItems]);
const isClearAllEnabled = useMemo(
() =>
Object.values(dataMaskApplied).some(
filter =>
isDefined(dataMaskSelected[filter.id]?.filterState?.value) ||
(!dataMaskSelected[filter.id] &&
isDefined(filter.filterState?.value)),
),
[dataMaskApplied, dataMaskSelected],
);
const isVertical = filterBarOrientation === FilterBarOrientation.Vertical;
return (

View File

@@ -86,7 +86,7 @@ const CrossFilter = (props: {
/>
)}
{last && (
<div
<span
data-test="cross-filters-divider"
css={css`
${orientation === FilterBarOrientation.Horizontal
@@ -95,7 +95,6 @@ const CrossFilter = (props: {
height: 22px;
margin-left: ${theme.sizeUnit * 4}px;
margin-right: ${theme.sizeUnit}px;
flex-shrink: 0;
`
: `
width: 100%;

View File

@@ -26,11 +26,7 @@ import crossFiltersSelector from './selectors';
import VerticalCollapse from './VerticalCollapse';
import { useChartsVerboseMaps } from '../utils';
const CrossFiltersVertical = ({
hideHeader = false,
}: {
hideHeader?: boolean;
}) => {
const CrossFiltersVertical = () => {
const dataMask = useSelector<RootState, DataMaskStateWithId>(
state => state.dataMask,
);
@@ -44,12 +40,7 @@ const CrossFiltersVertical = ({
verboseMaps,
});
return (
<VerticalCollapse
crossFilters={selectedCrossFilters}
hideHeader={hideHeader}
/>
);
return <VerticalCollapse crossFilters={selectedCrossFilters} />;
};
export default CrossFiltersVertical;

View File

@@ -17,88 +17,17 @@
* under the License.
*/
import { useMemo, useState, useCallback } from 'react';
import { t, css, useTheme, SupersetTheme } from '@superset-ui/core';
import { Icons } from '@superset-ui/core/components/Icons';
import { useMemo } from 'react';
import { Collapse, Divider } from '@superset-ui/core/components';
import { t } from '@superset-ui/core';
import { FilterBarOrientation } from 'src/dashboard/types';
import CrossFilter from './CrossFilter';
import { CrossFilterIndicator } from '../../selectors';
const CrossFiltersVerticalCollapse = (props: {
crossFilters: CrossFilterIndicator[];
hideHeader?: boolean;
}) => {
const { crossFilters, hideHeader = false } = props;
const theme = useTheme();
const [isOpen, setIsOpen] = useState(true);
const toggleSection = useCallback(() => {
setIsOpen(prev => !prev);
}, []);
const sectionContainerStyle = useCallback(
(theme: SupersetTheme) => css`
margin-bottom: ${theme.sizeUnit * 3}px;
padding: 0 ${theme.sizeUnit * 4}px;
`,
[],
);
const sectionHeaderStyle = useCallback(
(theme: SupersetTheme) => css`
display: flex;
align-items: center;
justify-content: space-between;
padding: ${theme.sizeUnit * 2}px 0;
cursor: pointer;
user-select: none;
&:hover {
background: ${theme.colorBgTextHover};
margin: 0 -${theme.sizeUnit * 2}px;
padding: ${theme.sizeUnit * 2}px;
border-radius: ${theme.borderRadius}px;
}
`,
[],
);
const sectionTitleStyle = useCallback(
(theme: SupersetTheme) => css`
margin: 0;
font-size: ${theme.fontSize}px;
font-weight: ${theme.fontWeightStrong};
color: ${theme.colorText};
line-height: 1.3;
`,
[],
);
const sectionContentStyle = useCallback(
(theme: SupersetTheme) => css`
padding: ${theme.sizeUnit * 2}px 0;
`,
[],
);
const dividerStyle = useCallback(
(theme: SupersetTheme) => css`
height: 1px;
background: ${theme.colorSplit};
margin: ${theme.sizeUnit * 2}px 0;
`,
[],
);
const iconStyle = useCallback(
(isOpen: boolean, theme: SupersetTheme) => css`
transform: ${isOpen ? 'rotate(0deg)' : 'rotate(180deg)'};
transition: transform 0.2s ease;
color: ${theme.colorTextSecondary};
`,
[],
);
const { crossFilters } = props;
const crossFiltersIndicators = useMemo(
() =>
crossFilters.map(filter => (
@@ -116,27 +45,23 @@ const CrossFiltersVerticalCollapse = (props: {
}
return (
<div css={sectionContainerStyle}>
{!hideHeader && (
<div
css={sectionHeaderStyle}
onClick={toggleSection}
onKeyDown={e => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
toggleSection();
}
}}
role="button"
tabIndex={0}
>
<h4 css={sectionTitleStyle}>{t('Cross-filters')}</h4>
<Icons.UpOutlined iconSize="m" css={iconStyle(isOpen, theme)} />
</div>
)}
{isOpen && <div css={sectionContentStyle}>{crossFiltersIndicators}</div>}
{isOpen && <div css={dividerStyle} data-test="cross-filters-divider" />}
</div>
<Collapse
ghost
defaultActiveKey="crossFilters"
expandIconPosition="end"
items={[
{
key: 'crossFilters',
label: t('Cross-filters'),
children: (
<>
{crossFiltersIndicators}
<Divider data-test="cross-filters-divider" />
</>
),
},
]}
/>
);
};

View File

@@ -33,10 +33,6 @@ export const crossFiltersSelector = (props: {
}): CrossFilterIndicator[] => {
const { dataMask, chartIds, chartLayoutItems, verboseMaps } = props;
if (!chartIds || !Array.isArray(chartIds)) {
return [];
}
return chartIds
.map(chartId => {
const filterIndicator = getCrossFilterIndicator(

View File

@@ -184,9 +184,9 @@ describe('FilterBar', () => {
expect(container).toBeInTheDocument();
});
test('should render the "Actions" heading', () => {
test('should render the "Filters" heading', () => {
renderWrapper();
expect(screen.getByText('Actions')).toBeInTheDocument();
expect(screen.getByText('Filters')).toBeInTheDocument();
});
test('should render the "Clear all" option', () => {

View File

@@ -108,12 +108,7 @@ test('Popover shows cross-filtering option on by default', async () => {
test('Can enable/disable cross-filtering', async () => {
fetchMock.put('glob:*/api/v1/dashboard/1', {
result: {
json_metadata: JSON.stringify({
...initialState.dashboardInfo.metadata,
cross_filters_enabled: false,
}),
},
result: {},
});
await setup();
const settingsButton = screen.getByRole('button', {
@@ -138,10 +133,8 @@ test('Popover opens with "Vertical" selected', async () => {
userEvent.hover(screen.getByText('Orientation of filter bar'));
expect(await screen.findByText('Vertical (Left)')).toBeInTheDocument();
expect(screen.getByText('Horizontal (Top)')).toBeInTheDocument();
const verticalItem = screen.getByText('Vertical (Left)');
expect(
within(verticalItem.closest('li')!).getByLabelText('check'),
within(screen.getAllByRole('menuitem')[4]).getByLabelText('check'),
).toBeInTheDocument();
});
@@ -154,10 +147,8 @@ test('Popover opens with "Horizontal" selected', async () => {
userEvent.hover(screen.getByText('Orientation of filter bar'));
expect(await screen.findByText('Vertical (Left)')).toBeInTheDocument();
expect(screen.getByText('Horizontal (Top)')).toBeInTheDocument();
const horizontalItem = screen.getByText('Horizontal (Top)');
expect(
within(horizontalItem.closest('li')!).getByLabelText('check'),
within(screen.getAllByRole('menuitem')[5]).getByLabelText('check'),
).toBeInTheDocument();
});
@@ -219,10 +210,7 @@ test('On selection change, send request and update checked value', async () => {
});
test('On failed request, restore previous selection', async () => {
fetchMock.put(
'glob:*/api/v1/dashboard/1',
() => new Response('', { status: 400, statusText: 'Bad Request' }),
);
fetchMock.put('glob:*/api/v1/dashboard/1', 400);
const dangerToastSpy = jest.spyOn(mockedMessageActions, 'addDangerToast');

View File

@@ -32,8 +32,6 @@ import { Space } from '@superset-ui/core/components/Space';
import { clearDataMaskState } from 'src/dataMask/actions';
import { useFilters } from 'src/dashboard/components/nativeFilters/FilterBar/state';
import { useFilterConfigModal } from 'src/dashboard/components/nativeFilters/FilterBar/FilterConfigurationLink/useFilterConfigModal';
import { useChartCustomizationModal } from '../../ChartCustomization/useChartCustomizationModal';
import ChartCustomizationModal from '../../ChartCustomization/ChartCustomizationModal';
import { useCrossFiltersScopingModal } from '../CrossFilters/ScopingModal/useCrossFiltersScopingModal';
import FilterConfigurationLink from '../FilterConfigurationLink';
@@ -52,7 +50,6 @@ const StyledMenuLabel = styled.span`
const CROSS_FILTERS_MENU_KEY = 'cross-filters-menu-key';
const CROSS_FILTERS_SCOPING_MENU_KEY = 'cross-filters-scoping-menu-key';
const ADD_EDIT_FILTERS_MENU_KEY = 'add-edit-filters-menu-key';
const CHART_CUSTOMIZATION_MENU_KEY = 'chart-customization-menu-key';
const isOrientation = (o: SelectedKey): o is FilterBarOrientation =>
o === FilterBarOrientation.Vertical || o === FilterBarOrientation.Horizontal;
@@ -81,15 +78,6 @@ const FilterBarSettings = () => {
({ dashboardInfo }) => dashboardInfo.id,
);
const {
isOpen: isChartCustomizationModalOpen,
dashboardId: chartCustomizationDashboardId,
chartId: chartCustomizationChartId,
openChartCustomizationModal,
closeChartCustomizationModal,
handleSave: handleChartCustomizationSave,
} = useChartCustomizationModal();
const [openScopingModal, scopingModal] = useCrossFiltersScopingModal();
const { openFilterConfigModal, FilterConfigModalComponent } =
@@ -146,8 +134,6 @@ const FilterBarSettings = () => {
openScopingModal();
} else if (selectedKey === ADD_EDIT_FILTERS_MENU_KEY) {
openFilterConfigModal();
} else if (selectedKey === CHART_CUSTOMIZATION_MENU_KEY) {
openChartCustomizationModal();
}
},
[
@@ -155,7 +141,6 @@ const FilterBarSettings = () => {
toggleCrossFiltering,
toggleFilterBarOrientation,
openFilterConfigModal,
openChartCustomizationModal,
],
);
@@ -201,10 +186,6 @@ const FilterBarSettings = () => {
});
items.push({ type: 'divider' });
}
items.push({
key: CHART_CUSTOMIZATION_MENU_KEY,
label: t('Chart customization'),
});
if (canEdit) {
items.push({
key: 'placement',
@@ -221,7 +202,6 @@ const FilterBarSettings = () => {
<Icons.CheckOutlined
iconColor={theme.colorPrimary}
iconSize="m"
aria-label="check"
/>
)}
</Space>
@@ -239,7 +219,6 @@ const FilterBarSettings = () => {
css={css`
vertical-align: middle;
`}
aria-label="check"
/>
)}
</Space>
@@ -258,7 +237,7 @@ const FilterBarSettings = () => {
filterValues,
]);
if (!menuItems.length || !canEdit) {
if (!menuItems.length) {
return null;
}
@@ -299,15 +278,6 @@ const FilterBarSettings = () => {
</Dropdown>
{scopingModal}
{FilterConfigModalComponent}
{isChartCustomizationModalOpen && (
<ChartCustomizationModal
isOpen={isChartCustomizationModalOpen}
dashboardId={chartCustomizationDashboardId}
chartId={chartCustomizationChartId}
onCancel={closeChartCustomizationModal}
onSave={handleChartCustomizationSave}
/>
)}
</>
);
};

View File

@@ -35,8 +35,6 @@ import {
SupersetTheme,
t,
isNativeFilterWithDataMask,
useTheme,
styled,
} from '@superset-ui/core';
import {
createHtmlPortalNode,
@@ -52,12 +50,10 @@ import { FilterBarOrientation, RootState } from 'src/dashboard/types';
import {
DropdownContainer,
type DropdownRef as DropdownContainerRef,
Typography,
} from '@superset-ui/core/components';
import { Icons } from '@superset-ui/core/components/Icons';
import { useChartIds } from 'src/dashboard/util/charts/useChartIds';
import { useChartLayoutItems } from 'src/dashboard/util/useChartLayoutItems';
import { ChartCustomizationItem } from 'src/dashboard/components/nativeFilters/ChartCustomization/types';
import { FiltersOutOfScopeCollapsible } from '../FiltersOutOfScopeCollapsible';
import { useFilterControlFactory } from '../useFilterControlFactory';
import { FiltersDropdownContent } from '../FiltersDropdownContent';
@@ -65,69 +61,20 @@ import crossFiltersSelector from '../CrossFilters/selectors';
import CrossFilter from '../CrossFilters/CrossFilter';
import { useFilterOutlined } from '../useFilterOutlined';
import { useChartsVerboseMaps } from '../utils';
import GroupByFilterCard from '../../ChartCustomization/GroupByFilterCard';
import { selectChartCustomizationItems } from '../../ChartCustomization/selectors';
type FilterControlsProps = {
dataMaskSelected: DataMaskStateWithId;
onFilterSelectionChange: (filter: Filter, dataMask: DataMask) => void;
clearAllTriggers?: Record<string, boolean>;
onClearAllComplete?: (filterId: string) => void;
hideHeader?: boolean;
};
const SectionContainer = styled.div`
margin-bottom: ${({ theme }) => theme.sizeUnit * 3}px;
`;
const SectionHeader = styled.div`
display: flex;
align-items: center;
justify-content: space-between;
padding: ${({ theme }) => theme.sizeUnit * 2}px 0;
cursor: pointer;
user-select: none;
&:hover {
background: ${({ theme }) => theme.colorBgTextHover};
margin: 0 -${({ theme }) => theme.sizeUnit * 2}px;
padding: ${({ theme }) => theme.sizeUnit * 2}px;
border-radius: ${({ theme }) => theme.borderRadius}px;
}
`;
const { Title } = Typography;
const SectionContent = styled.div`
padding: ${({ theme }) => theme.sizeUnit * 2}px 0;
`;
const StyledDivider = styled.div`
height: 1px;
background: ${({ theme }) => theme.colorSplit};
margin: ${({ theme }) => theme.sizeUnit * 2}px 0;
`;
const StyledIcon = styled(Icons.UpOutlined)<{ isOpen: boolean }>`
transform: ${({ isOpen }) => (isOpen ? 'rotate(0deg)' : 'rotate(180deg)')};
transition: transform 0.2s ease;
color: ${({ theme }) => theme.colorTextSecondary};
`;
const ChartCustomizationContent = styled.div`
display: flex;
flex-direction: column;
gap: ${({ theme }) => theme.sizeUnit * 2}px;
`;
const FilterControls: FC<FilterControlsProps> = ({
dataMaskSelected,
onFilterSelectionChange,
clearAllTriggers,
onClearAllComplete,
hideHeader = false,
}) => {
const theme = useTheme();
const filterBarOrientation = useSelector<RootState, FilterBarOrientation>(
({ dashboardInfo }) => dashboardInfo.filterBarOrientation,
);
@@ -144,11 +91,6 @@ const FilterControls: FC<FilterControlsProps> = ({
const chartLayoutItems = useChartLayoutItems();
const verboseMaps = useChartsVerboseMaps();
const chartCustomizationItems = useSelector<
RootState,
ChartCustomizationItem[]
>(state => selectChartCustomizationItems(state));
const selectedCrossFilters = useMemo(
() =>
crossFiltersSelector({
@@ -186,18 +128,6 @@ const FilterControls: FC<FilterControlsProps> = ({
const dashboardHasTabs = useDashboardHasTabs();
const showCollapsePanel = dashboardHasTabs && filtersWithValues.length > 0;
const [sectionsOpen, setSectionsOpen] = useState({
filters: true,
chartCustomization: true,
});
const toggleSection = useCallback((section: keyof typeof sectionsOpen) => {
setSectionsOpen(prev => ({
...prev,
[section]: !prev[section],
}));
}, []);
const renderer = useCallback(
({ id }: Filter | Divider, index: number | undefined) => {
const filterIndex = filtersWithValues.findIndex(f => f.id === id);
@@ -217,101 +147,14 @@ const FilterControls: FC<FilterControlsProps> = ({
const renderVerticalContent = useCallback(
() => (
<>
{filtersInScope.length > 0 && (
<SectionContainer>
{!hideHeader && (
<SectionHeader
onClick={() => toggleSection('filters')}
onKeyDown={e => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
toggleSection('filters');
}
}}
role="button"
tabIndex={0}
>
<Title
level={5}
style={{
margin: 0,
fontSize: theme.fontSize,
fontWeight: theme.fontWeightNormal,
color: theme.colorText,
lineHeight: 1.3,
}}
>
{t('Filters')}
</Title>
<StyledIcon iconSize="m" isOpen={sectionsOpen.filters} />
</SectionHeader>
)}
{(hideHeader || sectionsOpen.filters) && (
<SectionContent>{filtersInScope.map(renderer)}</SectionContent>
)}
{(hideHeader || sectionsOpen.filters) && <StyledDivider />}
</SectionContainer>
)}
{showCollapsePanel && (hideHeader || sectionsOpen.filters) && (
{filtersInScope.map(renderer)}
{showCollapsePanel && (
<FiltersOutOfScopeCollapsible
filtersOutOfScope={filtersOutOfScope}
renderer={renderer}
forceRender={hasRequiredFirst}
renderer={renderer}
/>
)}
{chartCustomizationItems.length > 0 && (
<SectionContainer>
{!hideHeader && (
<SectionHeader
onClick={() => toggleSection('chartCustomization')}
onKeyDown={e => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
toggleSection('chartCustomization');
}
}}
role="button"
tabIndex={0}
>
<Title
level={5}
style={{
margin: 0,
fontSize: theme.fontSize,
fontWeight: theme.fontWeightNormal,
color: theme.colorText,
lineHeight: 1.3,
}}
>
{t('Chart Customization')}
</Title>
<StyledIcon
iconSize="m"
isOpen={sectionsOpen.chartCustomization}
/>
</SectionHeader>
)}
{(hideHeader || sectionsOpen.chartCustomization) && (
<SectionContent>
<ChartCustomizationContent>
{chartCustomizationItems
.filter(item => !item.removed)
.map(item => (
<GroupByFilterCard
key={item.id}
customizationItem={item}
/>
))}
</ChartCustomizationContent>
</SectionContent>
)}
{(hideHeader || sectionsOpen.chartCustomization) && (
<StyledDivider />
)}
</SectionContainer>
)}
</>
),
[
@@ -320,16 +163,6 @@ const FilterControls: FC<FilterControlsProps> = ({
showCollapsePanel,
filtersOutOfScope,
hasRequiredFirst,
chartCustomizationItems,
sectionsOpen,
toggleSection,
SectionContainer,
SectionHeader,
SectionContent,
StyledDivider,
StyledIcon,
ChartCustomizationContent,
hideHeader,
],
);
@@ -392,61 +225,8 @@ const FilterControls: FC<FilterControlsProps> = ({
</div>
),
}));
const dividerItems = [];
if (
(crossFilters.length > 0 || nativeFiltersInScope.length > 0) &&
chartCustomizationItems.length > 0
) {
dividerItems.push({
id: 'chart-customization-divider',
element: (
<div
css={css`
width: 1px;
height: 22px;
background: ${theme.colorBorder};
margin-left: ${theme.sizeUnit * 4}px;
margin-right: ${theme.sizeUnit}px;
flex-shrink: 0;
`}
/>
),
});
}
const chartCustomizations = chartCustomizationItems
.filter(item => !item.removed)
.map(item => ({
id: `chart-customization-${item.id}`,
element: (
<div
className="chart-customization-item-wrapper"
css={css`
flex-shrink: 0;
`}
>
<GroupByFilterCard
customizationItem={item}
orientation="horizontal"
/>
</div>
),
}));
return [
...chartCustomizations,
...dividerItems,
...crossFilters,
...nativeFiltersInScope,
];
}, [
filtersInScope,
renderer,
rendererCrossFilter,
selectedCrossFilters,
chartCustomizationItems,
theme,
]);
return [...crossFilters, ...nativeFiltersInScope];
}, [filtersInScope, renderer, rendererCrossFilter, selectedCrossFilters]);
const renderHorizontalContent = useCallback(
() => (

View File

@@ -23,8 +23,6 @@ import {
unsetFocusedNativeFilter,
setHoveredNativeFilter,
unsetHoveredNativeFilter,
setHoveredChartCustomization,
unsetHoveredChartCustomization,
} from 'src/dashboard/actions/nativeFilters';
import { Constants } from '@superset-ui/core/components';
@@ -49,14 +47,3 @@ export const dispatchFocusAction = debounce(
},
Constants.FAST_DEBOUNCE,
);
export const dispatchChartCustomizationHoverAction = debounce(
(dispatch: Dispatch<any>, id?: string) => {
if (id) {
dispatch(setHoveredChartCustomization(id));
} else {
dispatch(unsetHoveredChartCustomization());
}
},
Constants.FAST_DEBOUNCE,
);

View File

@@ -29,10 +29,10 @@ test('should render', () => {
expect(container).toBeInTheDocument();
});
test('should render the "Actions" heading', () => {
test('should render the "Filters" heading', () => {
const mockedProps = createProps();
render(<Header {...mockedProps} />, { useRedux: true });
expect(screen.getByText('Actions')).toBeInTheDocument();
expect(screen.getByText('Filters')).toBeInTheDocument();
});
test('should render the expand button', () => {

View File

@@ -68,7 +68,7 @@ type HeaderProps = {
const Header: FC<HeaderProps> = ({ toggleFiltersBar }) => (
<Wrapper>
<TitleArea>
<span>{t('Actions')}</span>
<span>{t('Filters')}</span>
<FilterBarSettings />
<HeaderButton
{...getFilterBarTestId('collapse-button')}

View File

@@ -29,8 +29,6 @@ import { useChartsVerboseMaps, getFilterBarTestId } from './utils';
import { HorizontalBarProps } from './types';
import FilterBarSettings from './FilterBarSettings';
import crossFiltersSelector from './CrossFilters/selectors';
import { selectChartCustomizationItems } from '../ChartCustomization/selectors';
import { ChartCustomizationItem } from '../ChartCustomization/types';
const HorizontalBar = styled.div`
${({ theme }) => `
@@ -92,15 +90,7 @@ const HorizontalFilterBar: FC<HorizontalBarProps> = ({
[chartIds, chartLayoutItems, dataMask, verboseMaps],
);
const chartCustomizationItems = useSelector<
RootState,
ChartCustomizationItem[]
>(state => selectChartCustomizationItems(state));
const hasFilters =
filterValues.length > 0 ||
selectedCrossFilters.length > 0 ||
chartCustomizationItems.length > 0;
const hasFilters = filterValues.length > 0 || selectedCrossFilters.length > 0;
return (
<HorizontalBar {...getFilterBarTestId()}>

View File

@@ -29,28 +29,15 @@ import {
createContext,
FC,
} from 'react';
import { useSelector } from 'react-redux';
import cx from 'classnames';
import { styled, t, useTheme, DataMaskStateWithId } from '@superset-ui/core';
import { RootState } from 'src/dashboard/types';
import { styled, t, useTheme } from '@superset-ui/core';
import { Icons } from '@superset-ui/core/components/Icons';
import { EmptyState, Loading } from '@superset-ui/core/components';
import { useChartLayoutItems } from 'src/dashboard/util/useChartLayoutItems';
import { useChartIds } from 'src/dashboard/util/charts/useChartIds';
import { selectChartCustomizationItems } from '../ChartCustomization/selectors';
import { getFilterBarTestId, useChartsVerboseMaps } from './utils';
import { getFilterBarTestId } from './utils';
import { VerticalBarProps } from './types';
import Header from './Header';
import FilterControls from './FilterControls/FilterControls';
import { ChartCustomizationItem } from '../ChartCustomization/types';
import CrossFiltersVertical from './CrossFilters/Vertical';
import crossFiltersSelector from './CrossFilters/selectors';
enum SectionType {
Filters = 'filters',
ChartCustomization = 'chartCustomization',
CrossFilters = 'crossFilters',
}
const BarWrapper = styled.div<{ width: number }>`
width: ${({ theme }) => theme.sizeUnit * 8}px;
@@ -172,84 +159,35 @@ const VerticalFilterBar: FC<VerticalBarProps> = ({
() => ({ overflow: 'auto', height, overscrollBehavior: 'contain' }),
[height],
);
const chartCustomizationItems = useSelector<
RootState,
ChartCustomizationItem[]
>(state => selectChartCustomizationItems(state));
const dataMask = useSelector<RootState, DataMaskStateWithId>(
state => state.dataMask,
const filterControls = useMemo(
() =>
filterValues.length === 0 ? (
<FilterBarEmptyStateContainer>
<EmptyState
size="small"
title={t('No global filters are currently added')}
image="filter.svg"
description={
canEdit &&
t(
'Click on "Add or Edit Filters" option in Settings to create new dashboard filters',
)
}
/>
</FilterBarEmptyStateContainer>
) : (
<FilterControlsWrapper>
<FilterControls
dataMaskSelected={dataMaskSelected}
onFilterSelectionChange={onSelectionChange}
clearAllTriggers={clearAllTriggers}
onClearAllComplete={onClearAllComplete}
/>
</FilterControlsWrapper>
),
[canEdit, dataMaskSelected, filterValues.length, onSelectionChange],
);
const chartIds = useChartIds();
const chartLayoutItems = useChartLayoutItems();
const verboseMaps = useChartsVerboseMaps();
const selectedCrossFilters = crossFiltersSelector({
dataMask,
chartIds,
chartLayoutItems,
verboseMaps,
});
// Determine available section types
const availableSectionTypes = useMemo(() => {
const types: SectionType[] = [];
if (filterValues.length > 0) {
types.push(SectionType.Filters);
}
if (chartCustomizationItems.length > 0) {
types.push(SectionType.ChartCustomization);
}
if (selectedCrossFilters.length > 0) {
types.push(SectionType.CrossFilters);
}
return types;
}, [
filterValues.length,
chartCustomizationItems.length,
selectedCrossFilters.length,
]);
const hasOnlyOneSectionType = availableSectionTypes.length === 1;
const filterControls = useMemo(() => {
const hasFiltersOrCustomizations =
filterValues.length > 0 || chartCustomizationItems.length > 0;
return hasFiltersOrCustomizations ? (
<FilterControlsWrapper>
<FilterControls
dataMaskSelected={dataMaskSelected}
onFilterSelectionChange={onSelectionChange}
hideHeader={hasOnlyOneSectionType}
/>
</FilterControlsWrapper>
) : (
<FilterBarEmptyStateContainer>
<EmptyState
size="small"
title={t('No global filters are currently added')}
image="filter.svg"
description={
canEdit &&
t(
'Click on "Add or Edit Filters" option in Settings to create new dashboard filters',
)
}
/>
</FilterBarEmptyStateContainer>
);
}, [
canEdit,
dataMaskSelected,
filterValues.length,
onSelectionChange,
chartCustomizationItems.length,
hasOnlyOneSectionType,
]);
return (
<FilterBarScrollContext.Provider value={isScrolling}>
@@ -290,7 +228,7 @@ const VerticalFilterBar: FC<VerticalBarProps> = ({
) : (
<div css={tabPaneStyle} onScroll={onScroll}>
<>
<CrossFiltersVertical hideHeader={hasOnlyOneSectionType} />
<CrossFiltersVertical />
{filterControls}
</>
</div>

View File

@@ -41,16 +41,6 @@ import {
import { Constants } from '@superset-ui/core/components';
import { useHistory } from 'react-router-dom';
import { updateDataMask } from 'src/dataMask/actions';
import { triggerQuery } from 'src/components/Chart/chartAction';
import {
saveChartCustomization,
setChartCustomization,
clearAllPendingChartCustomizations,
ChartCustomizationSavePayload,
clearAllChartCustomizationsFromMetadata,
} from 'src/dashboard/actions/chartCustomizationActions';
import { ChartCustomizationItem } from 'src/dashboard/components/nativeFilters/ChartCustomization/types';
import { useImmer } from 'use-immer';
import { isEmpty, isEqual, debounce } from 'lodash';
import { getInitialDataMask } from 'src/dataMask/reducer';
@@ -158,9 +148,6 @@ const FilterBar: FC<FiltersBarProps> = ({
const dataMaskApplied: DataMaskStateWithId = useNativeFiltersDataMask();
const [dataMaskSelected, setDataMaskSelected] =
useImmer<DataMaskStateWithId>(dataMaskApplied);
const chartCustomizationItems = useSelector<RootState, any[]>(
state => state.dashboardInfo.metadata?.chart_customization_config || [],
);
const dispatch = useDispatch();
const [updateKey, setUpdateKey] = useState(0);
const tabId = useTabId();
@@ -175,9 +162,6 @@ const FilterBar: FC<FiltersBarProps> = ({
({ dashboardInfo }) => dashboardInfo?.id,
);
const previousDashboardId = usePrevious(dashboardId);
const chartIds = useSelector<RootState, number[]>(
state => state.dashboardState.sliceIds || [],
);
const canEdit = useSelector<RootState, boolean>(
({ dashboardInfo }) => dashboardInfo.dash_edit_perm,
);
@@ -193,8 +177,6 @@ const FilterBar: FC<FiltersBarProps> = ({
const [initializedFilters, setInitializedFilters] = useState<Set<string>>(
new Set(),
);
const [hasClearedChartCustomizations, setHasClearedChartCustomizations] =
useState(false);
const dataMaskSelectedRef = useRef(dataMaskSelected);
dataMaskSelectedRef.current = dataMaskSelected;
@@ -233,15 +215,9 @@ const FilterBar: FC<FiltersBarProps> = ({
};
// Recalculate validation status
const isRequired = !!filter.controlValues?.enableEmptyFilter;
const value = baseDataMask.filterState?.value;
const isEmptyValue =
value == null ||
(Array.isArray(value) && value.length === 0) ||
(typeof value === 'string' && value.trim() === '');
const hasRequiredValue = isRequired && isEmptyValue;
const hasRequiredValue =
filter.controlValues?.enableEmptyFilter &&
baseDataMask.filterState?.value == null;
draft[filter.id] = {
...baseDataMask,
@@ -290,7 +266,7 @@ const FilterBar: FC<FiltersBarProps> = ({
useEffect(() => {
setDataMaskSelected(() => dataMaskApplied);
}, [dataMaskAppliedText, setDataMaskSelected, dashboardId]);
}, [dataMaskAppliedText, setDataMaskSelected]);
useEffect(() => {
// embedded users can't persist filter combinations
@@ -300,99 +276,16 @@ const FilterBar: FC<FiltersBarProps> = ({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [dashboardId, dataMaskAppliedText, history, updateKey, tabId]);
const pendingChartCustomizations = useSelector<
RootState,
Record<string, ChartCustomizationItem> | undefined
>(state => state.dashboardInfo.pendingChartCustomizations);
const handleApply = useCallback(() => {
dispatch(logEvent(LOG_ACTIONS_CHANGE_DASHBOARD_FILTER, {}));
setUpdateKey(1);
// Apply filter changes
Object.entries(dataMaskSelected).forEach(([filterId, dataMask]) => {
if (dataMask) {
dispatch(updateDataMask(filterId, dataMask));
}
});
if (
pendingChartCustomizations &&
Object.keys(pendingChartCustomizations).length > 0
) {
Object.values(pendingChartCustomizations).forEach(
(customization: any) => {
if (customization) {
const customizationFilterId = `chart_customization_${customization.id}`;
const dataMask = {
extraFormData: {},
filterState: {},
ownState: {
column: customization.customization?.column || null,
},
};
dispatch(updateDataMask(customizationFilterId, dataMask));
}
},
);
const pendingItems = Object.values(pendingChartCustomizations).filter(
Boolean,
) as ChartCustomizationSavePayload[];
if (pendingItems.length > 0) {
const newCustomizations: ChartCustomizationItem[] = pendingItems.map(
item => ({
id: item.id,
title: item.title,
removed: item.removed,
chartId: item.chartId,
customization: item.customization,
}),
);
const existingCustomizations = chartCustomizationItems || [];
const existingMap = new Map(
existingCustomizations.map(item => [item.id, item]),
);
newCustomizations.forEach(newItem => {
existingMap.set(newItem.id, newItem);
});
const mergedCustomizations = Array.from(existingMap.values());
dispatch(setChartCustomization(mergedCustomizations));
if (chartIds.length > 0) {
chartIds.forEach(chartId => {
dispatch(triggerQuery(true, chartId));
});
}
}
dispatch(clearAllPendingChartCustomizations());
} else if (hasClearedChartCustomizations) {
const clearedChartCustomizations = chartCustomizationItems.map(item => ({
...item,
customization: {
...item.customization,
column: null,
},
}));
dispatch(saveChartCustomization(clearedChartCustomizations));
}
setHasClearedChartCustomizations(false);
}, [
dataMaskSelected,
dispatch,
pendingChartCustomizations,
hasClearedChartCustomizations,
chartCustomizationItems,
dashboardId,
chartIds,
]);
}, [dataMaskSelected, dispatch]);
const handleClearAll = useCallback(() => {
const newClearAllTriggers = { ...clearAllTriggers };
@@ -408,52 +301,8 @@ const FilterBar: FC<FiltersBarProps> = ({
newClearAllTriggers[id] = true;
}
});
let hasChartCustomizationsToClear = false;
const allDataMasks = { ...dataMaskSelected, ...dataMaskApplied };
Object.keys(allDataMasks).forEach(key => {
if (key.startsWith('chart_customization_')) {
hasChartCustomizationsToClear = true;
}
});
if (!hasChartCustomizationsToClear && chartCustomizationItems.length > 0) {
chartCustomizationItems.forEach(item => {
if (item.customization?.column) {
const customizationFilterId = `chart_customization_${item.id}`;
const dataMask = {
filterState: {
value: item.customization.column,
},
ownState: {
column: item.customization.column,
},
extraFormData: {},
};
dispatch(updateDataMask(customizationFilterId, dataMask));
hasChartCustomizationsToClear = true;
}
});
}
if (hasChartCustomizationsToClear) {
dispatch(clearAllPendingChartCustomizations());
dispatch(clearAllChartCustomizationsFromMetadata());
setHasClearedChartCustomizations(true);
}
setClearAllTriggers(newClearAllTriggers);
}, [
dataMaskSelected,
dataMaskApplied,
filtersInScope,
chartCustomizationItems,
clearAllTriggers,
dispatch,
]);
}, [dataMaskSelected, filtersInScope, setDataMaskSelected, clearAllTriggers]);
const handleClearAllComplete = useCallback((filterId: string) => {
setClearAllTriggers(prev => {
@@ -464,46 +313,11 @@ const FilterBar: FC<FiltersBarProps> = ({
}, []);
useFilterUpdates(dataMaskSelected, setDataMaskSelected);
const hasPendingChartCustomizations =
pendingChartCustomizations &&
Object.keys(pendingChartCustomizations).length > 0;
const hasMissingRequiredChartCustomization =
chartCustomizationItems?.some(item => {
if (item.removed) return false;
const required = !!item.customization?.controlValues?.enableEmptyFilter;
if (!required) return false;
const pendingItem = pendingChartCustomizations?.[item.id];
const currentCustomization =
pendingItem?.customization || item.customization;
const columnValue = currentCustomization?.column;
if (!columnValue) return true;
if (Array.isArray(columnValue)) {
return columnValue.length === 0;
}
if (typeof columnValue === 'string') {
return columnValue.trim() === '';
}
return false;
}) || false;
const isApplyDisabled =
(checkIsApplyDisabled(
dataMaskSelected,
dataMaskApplied,
filtersInScope.filter(isNativeFilter),
) &&
!hasPendingChartCustomizations &&
!hasClearedChartCustomizations) ||
hasMissingRequiredChartCustomization;
const isApplyDisabled = checkIsApplyDisabled(
dataMaskSelected,
dataMaskApplied,
filtersInScope.filter(isNativeFilter),
);
const isInitialized = useInitialization();
const actions = useMemo(
@@ -516,7 +330,6 @@ const FilterBar: FC<FiltersBarProps> = ({
dataMaskSelected={dataMaskSelected}
dataMaskApplied={dataMaskApplied}
isApplyDisabled={isApplyDisabled}
chartCustomizationItems={chartCustomizationItems}
/>
),
[
@@ -525,9 +338,8 @@ const FilterBar: FC<FiltersBarProps> = ({
handleApply,
handleClearAll,
dataMaskSelected,
dataMaskApplied,
dataMaskAppliedText,
isApplyDisabled,
chartCustomizationItems,
],
);

View File

@@ -17,12 +17,12 @@
* under the License.
*/
import { DataMaskStateWithId, Filter, FilterState } from '@superset-ui/core';
import { useSelector } from 'react-redux';
import { createSelector } from '@reduxjs/toolkit';
import { areObjectsEqual } from 'src/reduxUtils';
import { DataMaskStateWithId, Filter, FilterState } from '@superset-ui/core';
import { testWithId } from 'src/utils/testUtils';
import { RootState } from 'src/dashboard/types';
import { useSelector } from 'react-redux';
import { createSelector } from '@reduxjs/toolkit';
export const getOnlyExtraFormData = (data: DataMaskStateWithId) =>
Object.values(data).reduce(
@@ -34,10 +34,6 @@ export const checkIsMissingRequiredValue = (
filter: Filter,
filterState?: FilterState,
) => {
const isRequired = !!filter.controlValues?.enableEmptyFilter;
if (!isRequired) return false;
const value = filterState?.value;
// TODO: this property should be unhardcoded
return (
@@ -59,29 +55,22 @@ export const checkIsApplyDisabled = (
if (!checkIsValidateError(dataMaskSelected)) {
return true;
}
const dataSelectedValues = Object.values(dataMaskSelected);
const dataAppliedValues = Object.values(dataMaskApplied);
const hasMissingRequiredFilter = filters.some(filter =>
checkIsMissingRequiredValue(
filter,
dataMaskSelected?.[filter?.id]?.filterState,
),
);
const areEqual = areObjectsEqual(
getOnlyExtraFormData(dataMaskSelected),
getOnlyExtraFormData(dataMaskApplied),
{ ignoreUndefined: true },
);
const result =
areEqual ||
return (
areObjectsEqual(
getOnlyExtraFormData(dataMaskSelected),
getOnlyExtraFormData(dataMaskApplied),
{ ignoreUndefined: true },
) ||
dataSelectedValues.length !== dataAppliedValues.length ||
hasMissingRequiredFilter;
return result;
filters.some(filter =>
checkIsMissingRequiredValue(
filter,
dataMaskSelected?.[filter?.id]?.filterState,
),
)
);
};
const chartsVerboseMapSelector = createSelector(

View File

@@ -24,7 +24,7 @@ interface CollapsibleControlProps {
initialValue?: boolean;
disabled?: boolean;
checked?: boolean;
title: ReactNode;
title: string;
tooltip?: string;
children: ReactNode;
onChange?: (checked: boolean) => void;

View File

@@ -34,14 +34,9 @@ import {
interface DatasetSelectProps {
onChange: (value: { label: string; value: number }) => void;
value?: { label: string; value: number };
excludeDatasetIds?: number[];
}
const DatasetSelect = ({
onChange,
value,
excludeDatasetIds = [],
}: DatasetSelectProps) => {
const DatasetSelect = ({ onChange, value }: DatasetSelectProps) => {
const getErrorMessage = useCallback(
({ error, message }: ClientErrorObject) => {
let errorText = message || error || t('An error has occurred');
@@ -53,45 +48,40 @@ const DatasetSelect = ({
[],
);
const loadDatasetOptions = useCallback(
async (search: string, page: number, pageSize: number) => {
const query = rison.encode({
columns: ['id', 'table_name', 'database.database_name', 'schema'],
filters: [{ col: 'table_name', opr: 'ct', value: search }],
page,
page_size: pageSize,
order_column: 'table_name',
order_direction: 'asc',
});
return cachedSupersetGet({
endpoint: `/api/v1/dataset/?q=${query}`,
const loadDatasetOptions = async (
search: string,
page: number,
pageSize: number,
) => {
const query = rison.encode({
columns: ['id', 'table_name', 'database.database_name', 'schema'],
filters: [{ col: 'table_name', opr: 'ct', value: search }],
page,
page_size: pageSize,
order_column: 'table_name',
order_direction: 'asc',
});
return cachedSupersetGet({
endpoint: `/api/v1/dataset/?q=${query}`,
})
.then((response: JsonResponse) => {
const list: {
label: string | ReactNode;
value: string | number;
}[] = response.json.result.map((item: Dataset) => ({
label: DatasetSelectLabel(item),
value: item.id,
}));
return {
data: list,
totalCount: response.json.count,
};
})
.then((response: JsonResponse) => {
const filteredResult = response.json.result.filter(
(item: Dataset) => !excludeDatasetIds.includes(item.id),
);
const list: {
label: string | ReactNode;
value: string | number;
}[] = filteredResult.map((item: Dataset) => ({
label: DatasetSelectLabel(item),
value: item.id,
}));
return {
data: list,
totalCount: filteredResult.length,
};
})
.catch(async error => {
const errorMessage = getErrorMessage(
await getClientErrorObject(error),
);
throw new Error(errorMessage);
});
},
[excludeDatasetIds, getErrorMessage],
);
.catch(async error => {
const errorMessage = getErrorMessage(await getClientErrorObject(error));
throw new Error(errorMessage);
});
};
return (
<AsyncSelect

View File

@@ -28,17 +28,16 @@ import {
useTheme,
} from '@superset-ui/core';
import { useDispatch } from 'react-redux';
import { Constants, Form, Icons } from '@superset-ui/core/components';
import {
Constants,
Form,
Icons,
StyledModal,
} from '@superset-ui/core/components';
import { ErrorBoundary } from 'src/components';
import { testWithId } from 'src/utils/testUtils';
import { updateCascadeParentIds } from 'src/dashboard/actions/nativeFilters';
import useEffectEvent from 'src/hooks/useEffectEvent';
import {
BaseModalWrapper,
BaseModalBody,
BaseForm,
BaseExpandButtonWrapper,
} from 'src/dashboard/components/nativeFilters/ConfigModal/SharedStyles';
import { useFilterConfigMap, useFilterConfiguration } from '../state';
import FilterConfigurePane from './FilterConfigurePane';
import FiltersConfigForm, {
@@ -63,13 +62,56 @@ import {
} from './utils';
import DividerConfigForm from './DividerConfigForm';
const StyledModalBody = styled(BaseModalBody)`
const MODAL_MARGIN = 16;
const MIN_WIDTH = 880;
const StyledModalWrapper = styled(StyledModal)<{ expanded: boolean }>`
min-width: ${MIN_WIDTH}px;
width: ${({ expanded }) => (expanded ? '100%' : MIN_WIDTH)} !important;
@media (max-width: ${MIN_WIDTH + MODAL_MARGIN * 2}px) {
width: 100% !important;
min-width: auto;
}
.ant-modal-body {
padding: 0px;
overflow: auto;
}
${({ expanded }) =>
expanded &&
css`
height: 100%;
.ant-modal-body {
flex: 1 1 auto;
}
.ant-modal-content {
height: 100%;
}
`}
`;
export const StyledModalBody = styled.div<{ expanded: boolean }>`
display: flex;
height: ${({ expanded }) => (expanded ? '100%' : '700px')};
flex-direction: row;
flex: 1;
.filters-list {
width: ${({ theme }) => theme.sizeUnit * 50}px;
overflow: auto;
}
`;
export const StyledForm = styled(Form)`
width: 100%;
`;
export const StyledExpandButtonWrapper = styled.div`
margin-left: ${({ theme }) => theme.sizeUnit * 4}px;
`;
export const FILTERS_CONFIG_MODAL_TEST_ID = 'filters-config-modal';
export const getFiltersConfigModalTestId = testWithId(
FILTERS_CONFIG_MODAL_TEST_ID,
@@ -669,7 +711,7 @@ function FiltersConfigModal({
}, []);
return (
<BaseModalWrapper
<StyledModalWrapper
open={isOpen}
maskClosable={false}
title={t('Add and edit filters')}
@@ -695,19 +737,19 @@ function FiltersConfigModal({
saveAlertVisible={saveAlertVisible}
onConfirmCancel={handleConfirmCancel}
/>
<BaseExpandButtonWrapper>
<StyledExpandButtonWrapper>
<ToggleIcon
iconSize="l"
iconColor={theme.colorIcon}
onClick={toggleExpand}
/>
</BaseExpandButtonWrapper>
</StyledExpandButtonWrapper>
</div>
}
>
<ErrorBoundary>
<StyledModalBody expanded={expanded}>
<BaseForm
<StyledForm
form={form}
onValuesChange={handleValuesChange}
layout="vertical"
@@ -726,10 +768,10 @@ function FiltersConfigModal({
>
{formList}
</FilterConfigurePane>
</BaseForm>
</StyledForm>
</StyledModalBody>
</ErrorBoundary>
</BaseModalWrapper>
</StyledModalWrapper>
);
}

View File

@@ -30,15 +30,11 @@ import { CHART_TYPE, TAB_TYPE } from '../../util/componentTypes';
const defaultFilterConfiguration: Filter[] = [];
export function useFilterConfiguration() {
return useSelector<any, FilterConfiguration>(state => {
const nativeFilterConfig =
return useSelector<any, FilterConfiguration>(
state =>
state.dashboardInfo?.metadata?.native_filter_configuration ||
defaultFilterConfiguration;
return nativeFilterConfig.filter(
(filter: any) => filter.type !== 'CHART_CUSTOMIZATION',
);
});
defaultFilterConfiguration,
);
}
/**

View File

@@ -23,16 +23,6 @@ import {
SET_CROSS_FILTERS_ENABLED,
DASHBOARD_INFO_FILTERS_CHANGED,
} from '../actions/dashboardInfo';
import {
SAVE_CHART_CUSTOMIZATION_COMPLETE,
INITIALIZE_CHART_CUSTOMIZATION,
SET_CHART_CUSTOMIZATION_DATA_LOADING,
SET_CHART_CUSTOMIZATION_DATA,
SET_PENDING_CHART_CUSTOMIZATION,
CLEAR_PENDING_CHART_CUSTOMIZATION,
CLEAR_ALL_PENDING_CHART_CUSTOMIZATIONS,
CLEAR_ALL_CHART_CUSTOMIZATIONS,
} from '../actions/chartCustomizationActions';
import { HYDRATE_DASHBOARD } from '../actions/hydrate';
export default function dashboardStateReducer(state = {}, action) {
@@ -85,95 +75,6 @@ export default function dashboardStateReducer(state = {}, action) {
...state,
crossFiltersEnabled: action.crossFiltersEnabled,
};
case SAVE_CHART_CUSTOMIZATION_COMPLETE:
return {
...state,
metadata: {
...state.metadata,
native_filter_configuration: [
...(state.metadata?.native_filter_configuration || []).filter(
item =>
!(
item.type === 'CHART_CUSTOMIZATION' &&
item.id === 'chart_customization_groupby'
),
),
],
chart_customization_config: action.chartCustomization,
},
last_modified_time: Math.round(new Date().getTime() / 1000),
};
case INITIALIZE_CHART_CUSTOMIZATION:
return {
...state,
metadata: {
...state.metadata,
native_filter_configuration: [
...(state.metadata?.native_filter_configuration || []).filter(
item =>
!(
item.type === 'CHART_CUSTOMIZATION' &&
item.id === 'chart_customization_groupby'
),
),
],
chart_customization_config: action.chartCustomization,
},
last_modified_time: Math.round(new Date().getTime() / 1000),
};
case SET_CHART_CUSTOMIZATION_DATA_LOADING:
return {
...state,
chartCustomizationLoading: {
...state.chartCustomizationLoading,
[action.itemId]: action.isLoading,
},
};
case SET_CHART_CUSTOMIZATION_DATA:
return {
...state,
chartCustomizationData: {
...state.chartCustomizationData,
[action.itemId]: action.data,
},
};
case SET_PENDING_CHART_CUSTOMIZATION:
return {
...state,
pendingChartCustomizations: {
...state.pendingChartCustomizations,
[action.pendingCustomization.id]: action.pendingCustomization,
},
};
case CLEAR_PENDING_CHART_CUSTOMIZATION:
return {
...state,
pendingChartCustomizations: {
...state.pendingChartCustomizations,
[action.itemId]: undefined,
},
};
case CLEAR_ALL_PENDING_CHART_CUSTOMIZATIONS:
return {
...state,
pendingChartCustomizations: {},
};
case CLEAR_ALL_CHART_CUSTOMIZATIONS:
return {
...state,
metadata: {
...state.metadata,
chart_customization_config:
state.metadata?.chart_customization_config?.map(customization => ({
...customization,
customization: {
...customization.customization,
column: null,
},
})) || [],
},
last_modified_time: Math.round(new Date().getTime() / 1000),
};
default:
return state;
}

View File

@@ -1,198 +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-param-reassign */
// <- When we work with Immer, we need reassign, so disabling lint
import { produce } from 'immer';
import { HYDRATE_DASHBOARD } from '../actions/hydrate';
export interface GroupByState {
[groupById: string]: {
id: string;
selectedValues: string[];
isLoading: boolean;
availableOptions: { label: string; value: string }[];
};
}
export interface GroupByCustomizationsState {
groupByState: GroupByState;
}
export const SET_GROUP_BY_VALUES = 'SET_GROUP_BY_VALUES';
export const SET_GROUP_BY_LOADING = 'SET_GROUP_BY_LOADING';
export const SET_GROUP_BY_OPTIONS = 'SET_GROUP_BY_OPTIONS';
export const CLEAR_GROUP_BY_STATE = 'CLEAR_GROUP_BY_STATE';
export interface SetGroupByValuesAction {
type: typeof SET_GROUP_BY_VALUES;
groupById: string;
values: string[];
}
export interface SetGroupByLoadingAction {
type: typeof SET_GROUP_BY_LOADING;
groupById: string;
isLoading: boolean;
}
export interface SetGroupByOptionsAction {
type: typeof SET_GROUP_BY_OPTIONS;
groupById: string;
options: { label: string; value: string }[];
}
export interface ClearGroupByStateAction {
type: typeof CLEAR_GROUP_BY_STATE;
}
export type GroupByAction =
| SetGroupByValuesAction
| SetGroupByLoadingAction
| SetGroupByOptionsAction
| ClearGroupByStateAction
| {
type: typeof HYDRATE_DASHBOARD;
data: {
dashboardInfo: {
metadata: { chart_customization_config?: unknown[] };
};
};
};
export const setGroupByValues = (
groupById: string,
values: string[],
): SetGroupByValuesAction => ({
type: SET_GROUP_BY_VALUES,
groupById,
values,
});
export const setGroupByLoading = (
groupById: string,
isLoading: boolean,
): SetGroupByLoadingAction => ({
type: SET_GROUP_BY_LOADING,
groupById,
isLoading,
});
export const setGroupByOptions = (
groupById: string,
options: { label: string; value: string }[],
): SetGroupByOptionsAction => ({
type: SET_GROUP_BY_OPTIONS,
groupById,
options,
});
export const clearGroupByState = (): ClearGroupByStateAction => ({
type: CLEAR_GROUP_BY_STATE,
});
const initialState: GroupByCustomizationsState = {
groupByState: {},
};
export default function groupByCustomizationsReducer(
state = initialState,
action: GroupByAction,
): GroupByCustomizationsState {
switch (action.type) {
case SET_GROUP_BY_VALUES:
return produce(state, draft => {
if (!draft.groupByState[action.groupById]) {
draft.groupByState[action.groupById] = {
id: action.groupById,
selectedValues: [],
isLoading: false,
availableOptions: [],
};
}
draft.groupByState[action.groupById].selectedValues = action.values;
});
case SET_GROUP_BY_LOADING:
return produce(state, draft => {
if (!draft.groupByState[action.groupById]) {
draft.groupByState[action.groupById] = {
id: action.groupById,
selectedValues: [],
isLoading: false,
availableOptions: [],
};
}
draft.groupByState[action.groupById].isLoading = action.isLoading;
});
case SET_GROUP_BY_OPTIONS:
return produce(state, draft => {
if (!draft.groupByState[action.groupById]) {
draft.groupByState[action.groupById] = {
id: action.groupById,
selectedValues: [],
isLoading: false,
availableOptions: [],
};
}
draft.groupByState[action.groupById].availableOptions = action.options;
});
case CLEAR_GROUP_BY_STATE:
return produce(state, draft => {
draft.groupByState = {};
});
case HYDRATE_DASHBOARD:
return produce(state, draft => {
const chartCustomizationItems =
action.data.dashboardInfo?.metadata?.chart_customization_config || [];
chartCustomizationItems.forEach((item: unknown) => {
if (
typeof item === 'object' &&
item !== null &&
'id' in item &&
'customization' in item &&
typeof item.customization === 'object' &&
item.customization !== null &&
'column' in item.customization
) {
const customizationFilterId = `chart_customization_${(item as { id: string }).id}`;
if ((item.customization as { column: string }).column) {
const { defaultDataMask } = item.customization as {
defaultDataMask?: { filterState?: { value?: string[] } };
};
draft.groupByState[customizationFilterId] = {
id: customizationFilterId,
selectedValues: defaultDataMask?.filterState?.value || [],
isLoading: false,
availableOptions: [],
};
}
}
});
});
default:
return state;
}
}

View File

@@ -24,8 +24,6 @@ import {
UNSET_FOCUSED_NATIVE_FILTER,
SET_HOVERED_NATIVE_FILTER,
UNSET_HOVERED_NATIVE_FILTER,
SET_HOVERED_CHART_CUSTOMIZATION,
UNSET_HOVERED_CHART_CUSTOMIZATION,
UPDATE_CASCADE_PARENT_IDS,
} from 'src/dashboard/actions/nativeFilters';
import {
@@ -36,18 +34,14 @@ import {
} from '@superset-ui/core';
import { HYDRATE_DASHBOARD } from '../actions/hydrate';
interface ExtendedNativeFiltersState extends NativeFiltersState {
hoveredChartCustomizationId?: string;
}
export function getInitialState({
filterConfig,
state: prevState,
}: {
filterConfig?: FilterConfiguration;
state?: ExtendedNativeFiltersState;
}): ExtendedNativeFiltersState {
const state: Partial<ExtendedNativeFiltersState> = {};
state?: NativeFiltersState;
}): NativeFiltersState {
const state: Partial<NativeFiltersState> = {};
const filters: Record<string, Filter | Divider> = {};
if (filterConfig) {
filterConfig.forEach(filter => {
@@ -59,27 +53,25 @@ export function getInitialState({
state.filters = prevState?.filters ?? {};
}
state.focusedFilterId = undefined;
state.hoveredChartCustomizationId = undefined;
return state as ExtendedNativeFiltersState;
return state as NativeFiltersState;
}
function handleFilterChangesComplete(
state: ExtendedNativeFiltersState,
state: NativeFiltersState,
filters: Filter[],
) {
const modifiedFilters = { ...state.filters };
filters.forEach(filter => {
modifiedFilters[filter.id] = filter;
});
const modifiedFilters = Object.fromEntries(
filters.map(filter => [filter.id, filter]),
);
return {
...state,
filters: modifiedFilters,
} as ExtendedNativeFiltersState;
} as NativeFiltersState;
}
export default function nativeFilterReducer(
state: ExtendedNativeFiltersState = {
state: NativeFiltersState = {
filters: {},
},
action: AnyFilterAction,
@@ -120,18 +112,6 @@ export default function nativeFilterReducer(
hoveredFilterId: undefined,
};
case SET_HOVERED_CHART_CUSTOMIZATION:
return {
...state,
hoveredChartCustomizationId: action.id,
};
case UNSET_HOVERED_CHART_CUSTOMIZATION:
return {
...state,
hoveredChartCustomizationId: undefined,
};
case UPDATE_CASCADE_PARENT_IDS:
return {
...state,

View File

@@ -34,11 +34,6 @@ import Database from 'src/types/Database';
import { UrlParamEntries } from 'src/utils/urlUtils';
import { UserWithPermissionsAndRoles } from 'src/types/bootstrapTypes';
import Owner from 'src/types/Owner';
import {
ChartCustomizationItem,
FilterOption,
} from './components/nativeFilters/ChartCustomization/types';
import { GroupByCustomizationsState } from './reducers/groupByCustomizations';
import { ChartState } from '../explore/types';
export type { Dashboard } from 'src/types/Dashboard';
@@ -148,7 +143,6 @@ export type DashboardInfo = {
shared_label_colors: string[];
map_label_colors: JsonObject;
cross_filters_enabled: boolean;
chart_customization_config?: ChartCustomizationItem[];
};
crossFiltersEnabled: boolean;
filterBarOrientation: FilterBarOrientation;
@@ -157,9 +151,6 @@ export type DashboardInfo = {
changed_by?: Owner;
created_by?: Owner;
owners: Owner[];
chartCustomizationData?: { [itemId: string]: FilterOption[] };
chartCustomizationLoading?: { [itemId: string]: boolean };
pendingChartCustomizations?: Record<string, ChartCustomizationItem>;
theme?: {
id: number;
name: string;
@@ -192,7 +183,6 @@ export type RootState = {
dataMask: DataMaskStateWithId;
impressionId: string;
nativeFilters: NativeFiltersState;
groupByCustomizations: GroupByCustomizationsState;
user: UserWithPermissionsAndRoles;
};

View File

@@ -1,128 +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 interface ChartTypeLimitation {
maxDimensions: number;
dimensionNames: string[];
warningMessage: (usedColumns: string[], ignoredColumns: string[]) => string;
}
export const CHART_TYPE_LIMITATIONS: Record<string, ChartTypeLimitation> = {
heatmap: {
maxDimensions: 1,
dimensionNames: ['column'],
warningMessage: (usedColumns, ignoredColumns) =>
`Heatmap charts only support one column dimension. Using "${usedColumns[0]}" only. Additional columns (${ignoredColumns.join(', ')}) will be ignored.`,
},
heatmap_v2: {
maxDimensions: 1,
dimensionNames: ['column'],
warningMessage: (usedColumns, ignoredColumns) =>
`Heatmap charts only support one column dimension. Using "${usedColumns[0]}" only. Additional columns (${ignoredColumns.join(', ')}) will be ignored.`,
},
waterfall: {
maxDimensions: 1,
dimensionNames: ['dimension'],
warningMessage: (usedColumns, ignoredColumns) =>
`Waterfall charts only support one dimension. Using "${usedColumns[0]}" only. Additional columns (${ignoredColumns.join(', ')}) will be ignored.`,
},
word_cloud: {
maxDimensions: 1,
dimensionNames: ['series'],
warningMessage: (usedColumns, ignoredColumns) =>
`Word cloud charts only support one series dimension. Using "${usedColumns[0]}" only. Additional columns (${ignoredColumns.join(', ')}) will be ignored.`,
},
graph_chart: {
maxDimensions: 2,
dimensionNames: ['source', 'target'],
warningMessage: (usedColumns, ignoredColumns) =>
`Graph charts only support two dimensions (source and target). Using "${usedColumns[0]}" for source and "${usedColumns[1]}" for target. Additional columns (${ignoredColumns.join(', ')}) will be ignored.`,
},
sankey_v2: {
maxDimensions: 2,
dimensionNames: ['source', 'target'],
warningMessage: (usedColumns, ignoredColumns) =>
`Sankey charts only support two dimensions (source and target). Using "${usedColumns[0]}" for source and "${usedColumns[1]}" for target. Additional columns (${ignoredColumns.join(', ')}) will be ignored.`,
},
bubble_v2: {
maxDimensions: 2,
dimensionNames: ['series', 'entity'],
warningMessage: (usedColumns, ignoredColumns) =>
`Bubble charts only support two dimensions (series and entity). Using "${usedColumns[0]}" for series and "${usedColumns[1]}" for entity. Additional columns (${ignoredColumns.join(', ')}) will be ignored.`,
},
};
export const CHARTS_WITHOUT_GROUPBY = [
'big_number',
'big_number_total',
'pop_kpi',
'cal_heatmap',
'country_map',
'gantt',
'world_map',
'deck_arc',
'deck_geojson',
'deck_grid',
'deck_hex',
'deck_heatmap',
'deck_multi',
'deck_polygon',
'deck_scatter',
'deck_screengrid',
'deck_contour',
'deck_path',
];
export const SINGLE_COLUMN_DIMENSION_CHARTS = [
'heatmap',
'heatmap_v2',
'waterfall',
];
export function getChartTypeLimitation(
chartType: string,
): ChartTypeLimitation | null {
return CHART_TYPE_LIMITATIONS[chartType] || null;
}
export function isSingleColumnDimensionChart(chartType: string): boolean {
return SINGLE_COLUMN_DIMENSION_CHARTS.includes(chartType);
}
export function isChartWithoutGroupBy(chartType: string): boolean {
return CHARTS_WITHOUT_GROUPBY.includes(chartType);
}
export function limitColumnsForChartType(
chartType: string,
columns: string[],
): { limitedColumns: string[]; ignoredColumns: string[]; warning?: string } {
const limitation = getChartTypeLimitation(chartType);
if (!limitation || columns.length <= limitation.maxDimensions) {
return { limitedColumns: columns, ignoredColumns: [] };
}
const limitedColumns = columns.slice(0, limitation.maxDimensions);
const ignoredColumns = columns.slice(limitation.maxDimensions);
const warning = limitation.warningMessage(limitedColumns, ignoredColumns);
return { limitedColumns, ignoredColumns, warning };
}

View File

@@ -23,22 +23,15 @@ import {
DataRecordValue,
JsonObject,
PartialFilters,
QueryFormExtraFilter,
} from '@superset-ui/core';
import {
ChartConfiguration,
ChartQueryPayload,
ActiveFilters,
} from 'src/dashboard/types';
import { ChartCustomizationItem } from 'src/dashboard/components/nativeFilters/ChartCustomization/types';
import { getExtraFormData } from 'src/dashboard/components/nativeFilters/utils';
import { isEqual } from 'lodash';
import { areObjectsEqual } from 'src/reduxUtils';
import {
isSingleColumnDimensionChart,
limitColumnsForChartType,
isChartWithoutGroupBy,
} from './chartTypeLimitations';
import { isEqual } from 'lodash';
import getEffectiveExtraFilters from './getEffectiveExtraFilters';
import { getAllActiveFilters } from '../activeAllDashboardFilters';
@@ -56,7 +49,6 @@ interface CachedFormData {
label_colors?: Record<string, string>;
shared_label_colors?: string[];
map_label_colors?: Record<string, string>;
chart_customization?: JsonObject;
layer_filter_scope?: {
[filterId: string]: number[];
};
@@ -80,7 +72,6 @@ const cachedFormdataByChart: Record<
export interface GetFormDataWithExtraFiltersArguments {
chartConfiguration: ChartConfiguration;
chartCustomizationItems?: ChartCustomizationItem[];
chart: ChartQueryPayload;
filters: DataRecordFilters;
colorScheme?: string;
@@ -94,7 +85,6 @@ export interface GetFormDataWithExtraFiltersArguments {
labelsColorMap?: Record<string, string>;
sharedLabelsColors?: string[];
allSliceIds: number[];
chartCustomization?: JsonObject;
activeFilters?: ActiveFilters;
}
@@ -114,337 +104,11 @@ const createFilterDataMapping = (
return filterDataMapping;
};
function extractColumnNames(columns: unknown[]): string[] {
const columnNames: string[] = [];
if (Array.isArray(columns)) {
columns.forEach((col: unknown) => {
if (typeof col === 'string') {
columnNames.push(col);
} else if (col && typeof col === 'object' && 'column_name' in col) {
columnNames.push((col as { column_name: string }).column_name);
}
});
}
return columnNames;
}
function buildExistingColumnsSet(chart: ChartQueryPayload): Set<string> {
const existingColumns = new Set<string>();
const chartType = chart.form_data?.viz_type;
const existingGroupBy = Array.isArray(chart.form_data?.groupby)
? chart.form_data.groupby
: chart.form_data?.groupby
? [chart.form_data.groupby]
: [];
existingGroupBy.forEach((col: string) => existingColumns.add(col));
const xAxisColumn = chart.form_data?.x_axis;
if (xAxisColumn && chartType !== 'heatmap' && chartType !== 'heatmap_v2') {
existingColumns.add(xAxisColumn);
}
const metrics = chart.form_data?.metrics || [];
metrics.forEach((metric: any) => {
if (typeof metric === 'string') {
existingColumns.add(metric);
} else if (metric && typeof metric === 'object' && 'column' in metric) {
const metricColumn = metric.column;
if (typeof metricColumn === 'string') {
existingColumns.add(metricColumn);
} else if (
metricColumn &&
typeof metricColumn === 'object' &&
'column_name' in metricColumn
) {
existingColumns.add(metricColumn.column_name);
}
}
});
const seriesColumn = chart.form_data?.series;
if (seriesColumn) existingColumns.add(seriesColumn);
const entityColumn = chart.form_data?.entity;
if (entityColumn) existingColumns.add(entityColumn);
const targetColumn = chart.form_data?.target;
if (targetColumn) existingColumns.add(targetColumn);
if (chartType === 'box_plot') {
const boxPlotColumns = extractColumnNames(chart.form_data?.columns || []);
boxPlotColumns.forEach(col => existingColumns.add(col));
}
if (chartType === 'pivot_table_v2') {
const pivotColumns = extractColumnNames(
chart.form_data?.groupbyColumns || [],
);
pivotColumns.forEach(col => existingColumns.add(col));
}
return existingColumns;
}
function extractCustomizationColumnNames(customization: any): string[] {
if (typeof customization.column === 'string') {
return [customization.column];
}
if (Array.isArray(customization.column)) {
return customization.column.filter(
(col: string) => typeof col === 'string' && col.trim() !== '',
);
}
if (
typeof customization.column === 'object' &&
customization.column !== null
) {
const columnObj = customization.column as any;
const columnName =
columnObj.column_name || columnObj.name || String(columnObj);
if (columnName && columnName.trim() !== '') {
return [columnName];
}
}
return [];
}
function applyChartSpecificGroupBy(
chartType: string,
groupByColumns: string[],
existingGroupBy: string[],
xAxisColumn?: string,
): any {
const groupByFormData: any = {};
if (groupByColumns.length === 0) return groupByFormData;
if (
chartType?.startsWith('echarts_timeseries') ||
chartType?.startsWith('echarts_area')
) {
if (xAxisColumn) {
const nonConflictingGroupByColumns = groupByColumns.filter(
columnName => columnName !== xAxisColumn,
);
groupByFormData.groupby =
nonConflictingGroupByColumns.length > 0
? nonConflictingGroupByColumns
: existingGroupBy;
} else {
groupByFormData.groupby =
groupByColumns.length > 0 ? groupByColumns : existingGroupBy;
}
} else if (chartType === 'word_cloud') {
const { limitedColumns } = limitColumnsForChartType(
chartType,
groupByColumns,
);
groupByFormData.series = limitedColumns[0];
groupByFormData.groupby = [];
} else if (chartType === 'heatmap' || chartType === 'heatmap_v2') {
groupByFormData.groupby =
groupByColumns.length > 0
? [groupByColumns[0]]
: existingGroupBy.filter(col => col !== xAxisColumn);
} else if (chartType === 'waterfall') {
const { limitedColumns } = limitColumnsForChartType(
chartType,
groupByColumns,
);
groupByFormData.groupby = [limitedColumns[0]];
} else if (chartType === 'sunburst_v2') {
groupByFormData.columns = groupByColumns;
groupByFormData.groupby = [];
} else if (chartType === 'graph_chart') {
const { limitedColumns } = limitColumnsForChartType(
chartType,
groupByColumns,
);
groupByFormData.source = limitedColumns[0];
if (limitedColumns.length > 1) {
groupByFormData.target = limitedColumns[1];
}
} else if (chartType === 'sankey_v2') {
const { limitedColumns } = limitColumnsForChartType(
chartType,
groupByColumns,
);
groupByFormData.source = limitedColumns[0];
if (limitedColumns.length > 1) {
groupByFormData.target = limitedColumns[1];
}
} else if (['chord'].includes(chartType)) {
groupByFormData.groupby = [...existingGroupBy, ...groupByColumns];
} else if (chartType === 'bubble_v2') {
const { limitedColumns } = limitColumnsForChartType(
chartType,
groupByColumns,
);
groupByFormData.series = limitedColumns[0];
if (limitedColumns.length > 1) {
groupByFormData.entity = limitedColumns[1];
}
groupByFormData.groupby = [];
} else if (chartType === 'pivot_table_v2') {
groupByFormData.groupbyColumns = groupByColumns;
} else if (chartType === 'treemap_v2') {
groupByFormData.groupby = groupByColumns;
} else {
groupByFormData.groupby = groupByColumns;
}
return groupByFormData;
}
function processGroupByCustomizations(
chartCustomizationItems: ChartCustomizationItem[],
chart: ChartQueryPayload,
groupByState: Record<string, { selectedValues: string[] }>,
): {
groupby?: string[];
order_by_cols?: string[];
filters?: QueryFormExtraFilter[];
x_axis?: string;
series?: string;
columns?: string[];
entity?: string;
source?: string;
target?: string;
groupbyColumns?: string[];
} {
if (!chartCustomizationItems || chartCustomizationItems.length === 0) {
return {};
}
const chartDataset = chart.form_data?.datasource;
if (!chartDataset) {
return {};
}
const chartDatasetParts = String(chartDataset).split('__');
const chartDatasetId = chartDatasetParts[0];
const matchingCustomizations = chartCustomizationItems.filter(item => {
if (item.removed) return false;
const targetDataset = item.customization?.dataset;
if (!targetDataset) return false;
const targetDatasetId = String(targetDataset);
const datasetMatches = chartDatasetId === targetDatasetId;
const chartMatches = !item.chartId || item.chartId === chart.id;
return datasetMatches && chartMatches;
});
const chartType = chart.form_data?.viz_type;
if (isChartWithoutGroupBy(chartType)) {
return {};
}
const existingColumns = buildExistingColumnsSet(chart);
const existingGroupBy = Array.isArray(chart.form_data?.groupby)
? chart.form_data.groupby
: chart.form_data?.groupby
? [chart.form_data.groupby]
: [];
const xAxisColumn = chart.form_data?.x_axis;
const groupByColumns: string[] = [];
const allFilters: QueryFormExtraFilter[] = [];
let orderByConfig: string[] | undefined;
let heatmapColumnAdded = false;
matchingCustomizations.forEach(item => {
const { customization } = item;
if (!customization) return;
const groupById = `chart_customization_${item.id}`;
const selectedValues = groupByState[groupById]?.selectedValues || [];
const columnNames = extractCustomizationColumnNames(customization);
if (columnNames.length === 0) {
return;
}
const nonConflictingColumns = columnNames.filter(
columnName => !existingColumns.has(columnName),
);
if (nonConflictingColumns.length === 0) {
return;
}
if (isSingleColumnDimensionChart(chartType)) {
if (!heatmapColumnAdded && nonConflictingColumns.length > 0) {
const firstColumn = nonConflictingColumns[0];
if (!groupByColumns.includes(firstColumn)) {
groupByColumns.push(firstColumn);
heatmapColumnAdded = true;
}
}
if (nonConflictingColumns.length > 1) {
limitColumnsForChartType(chartType, nonConflictingColumns);
}
} else {
nonConflictingColumns.forEach(columnName => {
if (!groupByColumns.includes(columnName)) {
groupByColumns.push(columnName);
}
});
}
columnNames.forEach(columnName => {
if (selectedValues.length > 0) {
allFilters.push({
col: columnName,
op: 'IN',
val: selectedValues,
});
}
});
if (customization.sortFilter && customization.sortMetric) {
orderByConfig = [
JSON.stringify([
customization.sortMetric,
!customization.sortAscending,
]),
];
}
});
const groupByFormData = applyChartSpecificGroupBy(
chartType,
groupByColumns,
existingGroupBy,
xAxisColumn,
);
if (allFilters.length > 0) {
groupByFormData.filters = allFilters;
}
if (orderByConfig) {
groupByFormData.order_by_cols = orderByConfig;
}
return groupByFormData;
}
// this function merge chart's formData with dashboard filters value,
// and generate a new formData which will be used in the new query.
// filters param only contains those applicable to this chart.
export default function getFormDataWithExtraFilters({
chart,
filters,
nativeFilters,
chartConfiguration,
chartCustomizationItems,
colorScheme,
ownColorScheme,
colorNamespace,
@@ -455,13 +119,9 @@ export default function getFormDataWithExtraFilters({
labelsColorMap,
sharedLabelsColors,
allSliceIds,
chartCustomization,
activeFilters: passedActiveFilters,
}: GetFormDataWithExtraFiltersArguments) {
const cachedFormData = cachedFormdataByChart[sliceId];
const dataMaskEqual = areObjectsEqual(cachedFormData?.dataMask, dataMask, {
ignoreUndefined: true,
});
if (
cachedFiltersByChart[sliceId] === filters &&
areObjectsEqual(cachedFormData?.own_color_scheme, ownColorScheme) &&
@@ -477,11 +137,10 @@ export default function getFormDataWithExtraFilters({
}) &&
isEqual(cachedFormData?.shared_label_colors, sharedLabelsColors) &&
!!cachedFormData &&
dataMaskEqual &&
areObjectsEqual(cachedFormData?.extraControls, extraControls, {
areObjectsEqual(cachedFormData?.dataMask, dataMask, {
ignoreUndefined: true,
}) &&
areObjectsEqual(cachedFormData?.chart_customization, chartCustomization, {
areObjectsEqual(cachedFormData?.extraControls, extraControls, {
ignoreUndefined: true,
})
) {
@@ -546,22 +205,6 @@ export default function getFormDataWithExtraFilters({
}
}
const groupByState: Record<string, { selectedValues: string[] }> = {};
Object.entries(dataMask).forEach(([key, mask]) => {
if (key.startsWith('chart_customization_')) {
const selectedValues = mask.filterState?.value;
if (Array.isArray(selectedValues)) {
groupByState[key] = { selectedValues };
}
}
});
const groupByFormData = processGroupByCustomizations(
chartCustomizationItems || [],
chart,
groupByState,
);
const formData: CachedFormDataWithExtraControls = {
...chart.form_data,
chart_id: chart.id,
@@ -575,18 +218,11 @@ export default function getFormDataWithExtraFilters({
extra_filters: getEffectiveExtraFilters(filters),
...extraData,
...extraControls,
...groupByFormData,
...(chartCustomization && { chart_customization: chartCustomization }),
...(layerFilterScope && { layer_filter_scope: layerFilterScope }),
};
cachedFiltersByChart[sliceId] = filters;
cachedFormdataByChart[sliceId] = {
...formData,
dataMask,
extraControls,
...(chartCustomization && { chart_customization: chartCustomization }),
};
cachedFormdataByChart[sliceId] = { ...formData, dataMask, extraControls };
return formData;
}

View File

@@ -26,7 +26,6 @@ import {
isNativeFilter,
} from '@superset-ui/core';
import { Slice } from 'src/types/Chart';
import { ChartCustomizationItem } from 'src/dashboard/components/nativeFilters/ChartCustomization/types';
function isGlobalScope(scope: number[], slices: Record<string, Slice>) {
return scope.length === Object.keys(slices).length;
@@ -112,33 +111,3 @@ export function getRelatedCharts(
return related;
}
export function getRelatedChartsForChartCustomization(
customizationItem: ChartCustomizationItem,
slices: Record<string, Slice>,
): number[] {
const { customization, chartId } = customizationItem;
const { dataset } = customization;
if (chartId) {
return [chartId];
}
if (!dataset) {
return [];
}
const targetDatasetId = String(dataset);
return Object.values(slices)
.filter(slice => {
const sliceDataset = slice.datasource;
if (!sliceDataset) return false;
const sliceDatasetParts = String(sliceDataset).split('__');
const sliceDatasetId = sliceDatasetParts[0];
return sliceDatasetId === targetDatasetId;
})
.map(slice => slice.slice_id);
}

View File

@@ -17,20 +17,13 @@
* under the License.
*/
import { useMemo } from 'react';
import { Filter, useTheme } from '@superset-ui/core';
import { useSelector } from 'react-redux';
import { useTheme, Filter } from '@superset-ui/core';
import { RootState } from 'src/dashboard/types';
import { selectChartCustomizationItems } from 'src/dashboard/components/nativeFilters/ChartCustomization/selectors';
import {
getRelatedCharts,
getRelatedChartsForChartCustomization,
} from './getRelatedCharts';
const unfocusedChartStyles = {
opacity: 0.3,
pointerEvents: 'none' as const,
};
import { getRelatedCharts } from './getRelatedCharts';
const unfocusedChartStyles = { opacity: 0.3, pointerEvents: 'none' };
const EMPTY = {};
const useFilterFocusHighlightStyles = (chartId: number) => {
@@ -47,46 +40,25 @@ const useFilterFocusHighlightStyles = (chartId: number) => {
);
const nativeFilters = useSelector((state: RootState) => state.nativeFilters);
const slices =
useSelector((state: RootState) => state.sliceEntities.slices) || {};
const chartCustomizationItems = useSelector(selectChartCustomizationItems);
const highlightedFilterId =
nativeFilters?.focusedFilterId || nativeFilters?.hoveredFilterId;
const highlightedChartCustomizationId = (nativeFilters as any)
?.hoveredChartCustomizationId;
if (!highlightedFilterId && !highlightedChartCustomizationId) {
if (!highlightedFilterId) {
return EMPTY;
}
if (highlightedFilterId) {
const relatedCharts = getRelatedCharts(
highlightedFilterId as string,
nativeFilters.filters[highlightedFilterId as string] as Filter,
slices,
);
const relatedCharts = getRelatedCharts(
highlightedFilterId as string,
nativeFilters.filters[highlightedFilterId as string] as Filter,
slices,
);
if (relatedCharts.includes(chartId)) {
return focusedChartStyles;
}
}
if (highlightedChartCustomizationId) {
const customizationItem = chartCustomizationItems.find(
item => item.id === highlightedChartCustomizationId,
);
if (customizationItem) {
const relatedCharts = getRelatedChartsForChartCustomization(
customizationItem,
slices,
);
if (relatedCharts.includes(chartId)) {
return focusedChartStyles;
}
}
if (highlightedFilterId && relatedCharts.includes(chartId)) {
return focusedChartStyles;
}
// inline styles are used here due to a performance issue when adding/changing a class, which causes a reflow

View File

@@ -32,12 +32,6 @@ export interface UpdateDataMask {
dataMask: DataMask;
}
export const REMOVE_DATA_MASK = 'REMOVE_DATA_MASK';
export interface RemoveDataMask {
type: typeof REMOVE_DATA_MASK;
filterId: string | number;
}
export const INIT_DATAMASK = 'INIT_DATAMASK';
export interface INITDATAMASK {
type: typeof INIT_DATAMASK;
@@ -78,13 +72,6 @@ export function clearDataMask(filterId: string | number) {
return updateDataMask(filterId, getInitialDataMask(filterId));
}
export function removeDataMask(filterId: string | number): RemoveDataMask {
return {
type: REMOVE_DATA_MASK,
filterId,
};
}
export function clearDataMaskState(): ClearDataMaskState {
return {
type: CLEAR_DATA_MASK_STATE,
@@ -94,5 +81,4 @@ export function clearDataMaskState(): ClearDataMaskState {
export type AnyDataMaskAction =
| ClearDataMaskState
| UpdateDataMask
| RemoveDataMask
| SetDataMaskForFilterChangesComplete;

View File

@@ -37,7 +37,6 @@ import { isEqual } from 'lodash';
import {
AnyDataMaskAction,
CLEAR_DATA_MASK_STATE,
REMOVE_DATA_MASK,
SET_DATA_MASK_FOR_FILTER_CHANGES_COMPLETE,
UPDATE_DATA_MASK,
} from './actions';
@@ -179,49 +178,6 @@ const dataMaskReducer = produce(
// @ts-ignore
action.data.dataMask,
);
{
const chartCustomizationItems =
(
action as {
data: {
dashboardInfo: {
metadata: { chart_customization_config?: unknown[] };
};
};
}
).data.dashboardInfo?.metadata?.chart_customization_config || [];
chartCustomizationItems.forEach((item: unknown) => {
if (
typeof item === 'object' &&
item !== null &&
'id' in item &&
'customization' in item &&
typeof item.customization === 'object' &&
item.customization !== null &&
'column' in item.customization
) {
const customizationFilterId = `chart_customization_${(item as { id: string }).id}`;
if ((item.customization as { column: string }).column) {
const { defaultDataMask } = item.customization as {
defaultDataMask?: { filterState?: { value?: string[] } };
};
cleanState[customizationFilterId] = {
...getInitialDataMask(customizationFilterId),
filterState: {
value: defaultDataMask?.filterState?.value || [],
},
ownState: {
column: (item.customization as { column: string }).column,
},
} as DataMaskWithId;
}
}
});
}
return cleanState;
case SET_DATA_MASK_FOR_FILTER_CHANGES_COMPLETE:
updateDataMaskForFilterChanges(
@@ -231,9 +187,6 @@ const dataMaskReducer = produce(
action.filters,
);
return cleanState;
case REMOVE_DATA_MASK:
delete draft[action.filterId];
return draft;
default:
return draft;
}

View File

@@ -59,13 +59,13 @@ import { kebabCase, isEqual } from 'lodash';
import {
Collapse,
Modal,
Loading,
Label,
Tooltip,
} from '@superset-ui/core/components';
import Tabs from '@superset-ui/core/components/Tabs';
import { PluginContext } from 'src/components';
import { useConfirmModal } from 'src/hooks/useConfirmModal';
import { getSectionsToRender } from 'src/explore/controlUtils';
import { ExploreActions } from 'src/explore/actions/exploreActions';
@@ -285,7 +285,7 @@ function useResetOnChangeRef(initialValue: () => any, resetOnChangeValue: any) {
export const ControlPanelsContainer = (props: ControlPanelsContainerProps) => {
const theme = useTheme();
const pluginContext = useContext(PluginContext);
const { showConfirm, ConfirmModal } = useConfirmModal();
const [modal, contextHolder] = Modal.useModal();
const prevState = usePrevious(props.exploreState);
const prevDatasource = usePrevious(props.exploreState.datasource);
@@ -323,12 +323,12 @@ export const ControlPanelsContainer = (props: ControlPanelsContainerProps) => {
filter.subject === x_axis,
);
if (noFilter) {
showConfirm({
modal.confirm({
title: t('The X-axis is not on the filters list'),
body: t(
`The X-axis is not on the filters list which will prevent it from being used in time range filters in dashboards. Would you like to add it to the filters list?`,
),
onConfirm: () => {
content:
t(`The X-axis is not on the filters list which will prevent it from being used in
time range filters in dashboards. Would you like to add it to the filters list?`),
onOk: () => {
setControlValue('adhoc_filters', [
...(adhoc_filters || []),
{
@@ -340,8 +340,6 @@ export const ControlPanelsContainer = (props: ControlPanelsContainerProps) => {
},
]);
},
confirmText: t('Yes'),
cancelText: t('No'),
});
}
}
@@ -352,7 +350,6 @@ export const ControlPanelsContainer = (props: ControlPanelsContainerProps) => {
defaultTimeFilter,
previousXAxis,
props.exploreState.datasource,
showConfirm,
]);
useEffect(() => {
@@ -854,6 +851,7 @@ export const ControlPanelsContainer = (props: ControlPanelsContainerProps) => {
return (
<>
{contextHolder}
<Styles ref={containerRef}>
<Tabs
id="controlSections"
@@ -961,7 +959,6 @@ export const ControlPanelsContainer = (props: ControlPanelsContainerProps) => {
/>
</div>
</Styles>
{ConfirmModal}
</>
);
};

View File

@@ -47,7 +47,6 @@ const createProps = () =>
onHide: jest.fn(),
onSave: jest.fn(),
addSuccessToast: jest.fn(),
addDangerToast: jest.fn(),
}) as PropertiesModalProps;
fetchMock.get('glob:*/api/v1/chart/318*', {

View File

@@ -21,6 +21,7 @@ import { ChangeEvent, useMemo, useState, useCallback, useEffect } from 'react';
import {
Input,
AsyncSelect,
Modal,
Collapse,
CollapseLabelInModal,
type SelectValue,
@@ -53,7 +54,6 @@ export type PropertiesModalProps = {
permissionsError?: string;
existingOwners?: SelectValue;
addSuccessToast: (msg: string) => void;
addDangerToast: (msg: string) => void;
};
function PropertiesModal({
@@ -62,7 +62,6 @@ function PropertiesModal({
onSave,
show,
addSuccessToast,
addDangerToast,
}: PropertiesModalProps) {
const [submitting, setSubmitting] = useState(false);
// values of form inputs
@@ -134,17 +133,17 @@ function PropertiesModal({
return selectTags;
}, [tags.length]);
const showError = useCallback(
({ error, statusText, message }: any) => {
let errorText = error || statusText || t('An error has occurred');
if (message === 'Forbidden') {
errorText = t('You do not have permission to edit this chart');
}
addDangerToast(errorText);
},
[addDangerToast, t],
);
function showError({ error, statusText, message }: any) {
let errorText = error || statusText || t('An error has occurred');
if (message === 'Forbidden') {
errorText = t('You do not have permission to edit this chart');
}
Modal.error({
title: t('Error'),
content: errorText,
okButtonProps: { danger: true, className: 'btn-danger' },
});
}
const fetchChartProperties = useCallback(
async function fetchChartProperties() {
@@ -180,7 +179,7 @@ function PropertiesModal({
showError(clientError);
}
},
[showError, slice.slice_id],
[slice.slice_id],
);
const loadOptions = useMemo(

View File

@@ -0,0 +1,170 @@
/**
* 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 configureStore from 'redux-mock-store';
import { DatasourceType } from '@superset-ui/core';
import {
fireEvent,
render,
screen,
userEvent,
waitFor,
} from 'spec/helpers/testing-library';
import DatasourceControl, {
getDatasourceTitle,
} from 'src/explore/components/controls/DatasourceControl';
const defaultProps = {
name: 'datasource',
label: 'Dataset',
value: '1__table',
datasource: {
name: 'birth_names',
type: 'table',
uid: '1__table',
id: 1,
columns: [],
metrics: [],
owners: [{ username: 'admin', userId: 1 }],
database: {
backend: 'mysql',
name: 'main',
},
health_check_message: 'Warning message!',
},
actions: {
setDatasource: jest.fn(),
},
onChange: jest.fn(),
user: {
createdOn: '2021-04-27T18:12:38.952304',
email: 'admin',
firstName: 'admin',
isActive: true,
lastName: 'admin',
permissions: {},
roles: { Admin: Array(173) },
userId: 1,
username: 'admin',
},
};
// eslint-disable-next-line no-restricted-globals -- TODO: Migrate from describe blocks
describe('DatasourceControl', () => {
const setup = (overrideProps = {}) => {
const mockStore = configureStore([]);
const store = mockStore({});
const props = {
...defaultProps,
...overrideProps,
};
return {
rendered: render(<DatasourceControl {...props} />, {
useRedux: true,
useRouter: true,
store,
}),
store,
props,
};
};
test('should not render Modal', () => {
setup();
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
});
test('should not render ChangeDatasourceModal', () => {
setup();
expect(screen.queryByTestId('Swap dataset-modal')).not.toBeInTheDocument();
});
test('show or hide Edit Datasource option', async () => {
const {
rendered: { container, rerender },
store,
props,
} = setup();
expect(
container.querySelector('[data-test="datasource-menu-trigger"]'),
).toBeInTheDocument();
userEvent.click(screen.getByLabelText('more'));
await waitFor(() => {
expect(screen.queryAllByRole('menuitem')).toHaveLength(3);
});
// Close the menu
userEvent.click(document.body);
await waitFor(() => {
expect(screen.queryAllByRole('menuitem')).toHaveLength(0);
});
rerender(<DatasourceControl {...{ ...props, isEditable: false }} />, {
useRedux: true,
useRouter: true,
store,
});
expect(
container.querySelector('[data-test="datasource-menu-trigger"]'),
).toBeInTheDocument();
userEvent.click(screen.getByLabelText('more'));
await waitFor(() => {
expect(screen.queryAllByRole('menuitem')).toHaveLength(2);
});
});
test('should render health check message', async () => {
setup();
const modalTrigger = screen.getByLabelText('warning');
expect(modalTrigger).toBeInTheDocument();
// Hover the modal so healthcheck message can show up
fireEvent.mouseOver(modalTrigger);
await waitFor(() => {
expect(
screen.getByText(defaultProps.datasource.health_check_message),
).toBeInTheDocument();
});
});
test('Gets Datasource Title', () => {
const sql = 'This is the sql';
const name = 'this is a name';
const emptyResult = '';
const queryDatasource1 = { type: DatasourceType.Query, sql };
let displayText = getDatasourceTitle(queryDatasource1);
expect(displayText).toBe(sql);
const queryDatasource2 = { type: DatasourceType.Query, sql: null };
displayText = getDatasourceTitle(queryDatasource2);
expect(displayText).toBe(null);
const queryDatasource3 = { type: 'random type', name };
displayText = getDatasourceTitle(queryDatasource3);
expect(displayText).toBe(name);
const queryDatasource4 = { type: 'random type' };
displayText = getDatasourceTitle(queryDatasource4);
expect(displayText).toBe(emptyResult);
displayText = getDatasourceTitle();
expect(displayText).toBe(emptyResult);
displayText = getDatasourceTitle(null);
expect(displayText).toBe(emptyResult);
displayText = getDatasourceTitle('I should not be a string');
expect(displayText).toBe(emptyResult);
displayText = getDatasourceTitle([]);
expect(displayText).toBe(emptyResult);
});
});

View File

@@ -0,0 +1,131 @@
/**
* 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 sinon from 'sinon';
import { getChartMetadataRegistry, ChartMetadata } from '@superset-ui/core';
import {
act,
cleanup,
render,
screen,
userEvent,
} from 'spec/helpers/testing-library';
import VizTypeControl from 'src/explore/components/controls/VizTypeControl';
import { DynamicPluginProvider } from 'src/components';
const defaultProps = {
name: 'viz_type',
label: 'Visualization Type',
value: 'vis1',
onChange: sinon.spy(),
isModalOpenInit: true,
};
/**
* AntD and/or the Icon component seems to be doing some kind of async changes,
* so even though the test passes, there is a warning an update to Icon was not
* wrapped in act(). This sufficiently act-ifies whatever side effects are going
* on and prevents those warnings.
*/
const waitForEffects = () =>
act(() => new Promise(resolve => setTimeout(resolve, 0)));
// Increase global timeout
jest.setTimeout(60000);
// Add cleanup after each test
afterEach(async () => {
cleanup();
// Wait for any pending effects to complete
await new Promise(resolve => setTimeout(resolve, 0));
});
// eslint-disable-next-line no-restricted-globals -- TODO: Migrate from describe blocks
describe('VizTypeControl', () => {
const registry = getChartMetadataRegistry();
registry
.registerValue(
'vis1',
new ChartMetadata({
name: 'vis1',
thumbnail: '',
tags: ['Featured'],
}),
)
.registerValue(
'vis2',
new ChartMetadata({
name: 'vis2',
thumbnail: '',
tags: ['foobar'],
}),
);
beforeEach(async () => {
render(
<DynamicPluginProvider>
<VizTypeControl {...defaultProps} />
</DynamicPluginProvider>,
{ useRedux: true },
);
await waitForEffects();
}, 30000); // Increase beforeEach timeout
test('calls onChange when submitted', async () => {
const thumbnail = await screen.findByTestId('viztype-selector-container', {
timeout: 15000,
});
const submit = await screen.findByText('Select', { timeout: 15000 });
await act(async () => {
userEvent.click(thumbnail);
await waitForEffects();
});
expect(defaultProps.onChange.called).toBe(false);
await act(async () => {
userEvent.click(submit);
await waitForEffects();
});
expect(defaultProps.onChange.called).toBe(true);
}, 30000);
test('filters images based on text input', async () => {
const thumbnails = await screen.findByTestId('viztype-selector-container', {
timeout: 15000,
});
expect(thumbnails).toBeInTheDocument();
const searchInput = await screen.findByPlaceholderText(
'Search all charts',
{ timeout: 15000 },
);
await act(async () => {
userEvent.type(searchInput, 'foo');
await waitForEffects();
});
const thumbnail = await screen.findByTestId('viztype-selector-container', {
timeout: 15000,
});
expect(thumbnail).toBeInTheDocument();
}, 30000);
});

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