You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@superset.apache.org by "YuriyKrasilnikov (via GitHub)" <gi...@apache.org> on 2026/02/08 10:35:32 UTC
[PR] feat: content localization for dashboards, charts, and filters [superset]
YuriyKrasilnikov opened a new pull request, #37790:
URL: https://github.com/apache/superset/pull/37790
## Summary
Adds content localization support to Apache Superset — dashboard titles, chart names/descriptions, and native filter labels can be translated per locale. Viewers see content in their UI language automatically.
- `translations` JSON column on Dashboard and Slice models with `LocalizableMixin`
- API: localized responses by default, editor mode via `?include_translations=true`
- Frontend: inline `LocaleSwitcher` dropdown in Input suffix for switching between DEFAULT and per-locale text
- Jinja macro `{{ current_user_locale() }}` for locale-aware SQL queries
- Embedded SDK `setLocale()` method for dynamic locale switching
- Export/import support with backward compatibility
- Feature-flagged (`ENABLE_CONTENT_LOCALIZATION`, default: off)
- XSS sanitization, BCP 47 validation, configurable size limits
Resolves #37789
## Test plan
- [ ] ~150 unit tests (models, API schemas, validation, frontend components)
- [ ] 4 Playwright E2E tests (CRUD, locale switching, available locales, UI integration)
- [ ] Manual: enable flag → create dashboard → add translations via LocaleSwitcher → switch UI language → verify localized content
- [ ] Verify feature flag OFF: no UI changes, PUT with translations rejected
- [ ] Verify export/import roundtrip preserves translations
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "YuriyKrasilnikov (via GitHub)" <gi...@apache.org>.
YuriyKrasilnikov commented on code in PR #37790:
URL: https://github.com/apache/superset/pull/37790#discussion_r2783894108
##########
superset/dashboards/schemas.py:
##########
@@ -257,8 +273,121 @@ def post_dump(self, serialized: dict[str, Any], **kwargs: Any) -> dict[str, Any]
del serialized["owners"]
del serialized["changed_by_name"]
del serialized["changed_by"]
+
+ # Apply content localization when feature is enabled
+ if is_feature_enabled("ENABLE_CONTENT_LOCALIZATION"):
+ self._apply_localization(serialized, obj)
+
return serialized
+ def _apply_localization(self, serialized: dict[str, Any], obj: Any) -> None:
Review Comment:
False positive. \`validate_translations()\` explicitly accepts \`None\`:
1. Type signature: \`translations: dict[str, dict[str, str]] | None\`
2. First line: \`if translations is None: return\`
3. Docstring: \`>>> validate_translations(None) # passes (clears translations)\`
4. Dedicated test: \`test_validate_translations_none_passes\` in \`validation_test.py:144\`
Same issue was flagged on the previous review round at \`schemas.py:606\` — already answered there.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "YuriyKrasilnikov (via GitHub)" <gi...@apache.org>.
YuriyKrasilnikov commented on PR #37790:
URL: https://github.com/apache/superset/pull/37790#issuecomment-3874447639
### Update: DeferredInput component
Fixes the input lag that remained in translation fields after the debounce fix. The debounce only addressed the lightweight `formChanged()` notification — the heavy state update (`setNativeFilterFieldValues`, `handleTranslationChange`) still fired synchronously on every keystroke, causing the entire parent tree to re-render mid-typing.
**Root cause:** antd `Form.Item` with `name` prop makes inputs uncontrolled (fast), but locale-mode translation inputs can't use `name` binding (they write to nested JSON, not a flat form field). So they fall back to controlled `value` + `onChange` — and when `onChange` triggers a heavy state update on every keystroke, input becomes visibly laggy.
**Solution:** new `DeferredInput` component that decouples typing from state propagation. Internally maintains local state for instant keystroke feedback. Propagates to parent only on blur or after 300ms debounce. Accepts external `value` prop for locale switching and form resets, with `lastPropagatedRef` to avoid echo-induced cursor jumps.
Applied to all 4 translation input locations:
- `FiltersConfigForm` — filter name
- `MetricLabelTranslations` — adhoc metric label
- `Chart PropertiesModal` — chart name (split: `Input` for default mode, `DeferredInput` for locale mode)
- `Dashboard BasicInfoSection` — dashboard title
Also moved `LocaleSwitcher` from `AdhocMetricEditPopoverTitle` (popover title bar — click conflicts, translations not saving) to popover body via dedicated `MetricLabelTranslations` component.
10 unit tests for DeferredInput covering debounce, blur flush, unmount flush, external value sync, echo protection, props forwarding. All existing tests pass (62 across 4 suites).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "YuriyKrasilnikov (via GitHub)" <gi...@apache.org>.
YuriyKrasilnikov commented on code in PR #37790:
URL: https://github.com/apache/superset/pull/37790#discussion_r2783786242
##########
superset-frontend/src/dashboard/components/nativeFilters/FiltersConfigModal/FiltersConfigForm/FiltersConfigForm.tsx:
##########
@@ -569,6 +585,109 @@ const FiltersConfigForm = (
[filterId, form, formChanged],
);
+ const localizationEnabled = isFeatureEnabled(
+ FeatureFlag.EnableContentLocalization,
+ );
+
+ const currentTranslations: Translations =
+ formFilter?.translations ?? filterToEdit?.translations ?? {};
+
+ useEffect(() => {
+ if (filterToEdit?.translations) {
+ setNativeFilterFieldValues(form, filterId, {
+ translations: filterToEdit.translations,
+ });
+ }
+ }, [filterId, filterToEdit?.translations, form]);
+
+ useEffect(() => {
+ if (localizationEnabled) {
+ SupersetClient.get({
+ endpoint: '/api/v1/localization/available_locales',
+ }).then(
+ response => {
+ const { locales, default_locale } = response.json.result;
+ setAllLocales(locales);
+ setDefaultLocale(default_locale);
+ },
+ err => logging.error('Failed to fetch available locales', err),
+ );
+ }
+ }, [localizationEnabled]);
+
+ // Refs for values read during initialization but not triggering re-runs.
+ // Without refs, editing a translation would reset the active locale
+ // because currentTranslations changes on every keystroke.
+ const currentTranslationsRef = useRef(currentTranslations);
+ currentTranslationsRef.current = currentTranslations;
+ const userLocaleRef = useRef(userLocale);
+ userLocaleRef.current = userLocale;
+
+ // Initialize nameActiveLocale when switching between filters.
+ useEffect(() => {
+ if (
+ localizationEnabled &&
+ currentTranslationsRef.current.name?.[userLocaleRef.current]
+ ) {
+ setNameActiveLocale(userLocaleRef.current);
+ } else {
+ setNameActiveLocale(DEFAULT_LOCALE_KEY);
+ }
+ }, [localizationEnabled, filterId]);
+
+ const handleNameTranslationChange = useCallback(
+ (value: string) => {
+ const updated: Translations = {
+ ...currentTranslationsRef.current,
+ name: { ...currentTranslationsRef.current.name, [nameActiveLocale]: value },
Review Comment:
Not a bug. Object spread with `undefined` is explicitly safe per ECMAScript spec.
**CopyDataProperties** (ECMA-262, §14.18) step 3:
> If source is **undefined** or **null**, return target.
Runtime proof (Node v20):
```js
const translations = {};
({ ...translations.name, de: "German" }) // → { de: "German" }
```
This is fundamentally different from **array spread** (`[...undefined]` → TypeError) because array spread requires an iterable, while object spread has an explicit null/undefined guard in the spec.
The author was already aware — line 630 in the same file uses optional chaining for the *read* path (`currentTranslationsRef.current.name?.[userLocaleRef.current]`), while correctly relying on spread-is-safe behavior for the *construction* path.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "YuriyKrasilnikov (via GitHub)" <gi...@apache.org>.
YuriyKrasilnikov commented on code in PR #37790:
URL: https://github.com/apache/superset/pull/37790#discussion_r2783892774
##########
superset-frontend/src/explore/components/PropertiesModal/index.tsx:
##########
@@ -258,6 +292,18 @@ function PropertiesModal({
// get the owners of this slice
useEffect(() => {
fetchChartProperties();
+ if (isFeatureEnabled(FeatureFlag.EnableContentLocalization)) {
+ SupersetClient.get({
+ endpoint: '/api/v1/localization/available_locales',
+ }).then(
+ response => {
+ const { locales, default_locale } = response.json.result;
+ setAllLocales(locales);
+ setDefaultLocale(default_locale);
+ },
+ err => logging.error('Failed to fetch available locales', err),
Review Comment:
Same intentional design as Dashboard PropertiesModal (commit \`c01af6ab12\`).
\`showError\` calls \`addDangerToast\` — showing a red error toast for a background locales fetch that the user didn't trigger is poor UX. Additionally, \`showError\` expects \`getClientErrorObject\` output (\`{error, statusText, message}\`), not a raw rejection — using it directly would require extra wrapping for no user benefit.
The modal works perfectly without locales — title, description, owners, cache timeout, certification, tags all function normally. Silent \`logging.error\` is the correct choice.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on PR #37790:
URL: https://github.com/apache/superset/pull/37790#issuecomment-4732409983
Huge effort here @YuriyKrasilnikov. It's gone conflicting, so a rebase on `master` would help. This rides on SIP-205 (#37789) which is still open though — I think we want that settled before a change this size can land. If you need help with the rebase (a lot of stuff has been migrated to typescript) say the word. Thanks!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "YuriyKrasilnikov (via GitHub)" <gi...@apache.org>.
YuriyKrasilnikov commented on PR #37790:
URL: https://github.com/apache/superset/pull/37790#issuecomment-3871921882
## What this commit does
This is a stabilization pass over the content localization feature. After the initial implementation landed, we ran a thorough audit that uncovered several integration issues that only manifest in real usage — not in isolated unit tests.
**The most impactful fix** is the filter translation input becoming unresponsive after 1-2 keystrokes. Root cause: `handleNameTranslationChange` called `formChanged()` synchronously on every keystroke, while the default name input used a debounced version. Each synchronous call triggered a state update cascade through the parent modal, which recreated the callback (due to `currentTranslations` in deps), causing React to lose focus on the controlled input. The fix uses `currentTranslationsRef` (which was already prepared but unused) and `debouncedFormChanged()` — making translation editing behave identically to default name editing.
**Import/Export was silently broken** for any dashboard or chart that had translations. Marshmallow schemas used `unknown="raise"`, so the `translations` field in YAML caused import to fail. Adding the field to `ImportV1DashboardSchema` and `ImportV1ChartSchema` fixes the round-trip.
**Several API endpoints returned un-localized content**: the chart entity endpoint (`/dashboard/{id}/charts`), list endpoints, and the etag cache didn't account for locale — meaning two users with different locales could get each other's cached responses.
The commit also includes comprehensive test coverage for all the above: 4 Playwright E2E scenarios verifying end-to-end localization on a real dashboard, plus Python and Jest unit tests for each fix. All linting (ruff, isort, mypy) passes clean.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #37790:
URL: https://github.com/apache/superset/pull/37790#issuecomment-3919119355
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers a full AI review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #37790:
URL: https://github.com/apache/superset/pull/37790#discussion_r3827569222
##########
superset/migrations/versions/2026-02-04_14-00_1af0da0adfec_add_translations_column.py:
##########
@@ -0,0 +1,80 @@
+# 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.
+"""Add translations column to dashboards and slices.
+
+The translations column stores user-generated content translations
+in JSON format:
+
+ {
+ "field_name": {
+ "locale": "translated_value"
+ }
+ }
+
+Example for dashboards:
+
+ {
+ "dashboard_title": {"de": "Verkaufs-Dashboard", "fr": "Tableau de bord"},
+ "description": {"de": "Monatlicher Verkaufsbericht"}
+ }
+
+Example for slices:
+
+ {
+ "slice_name": {"de": "Umsatz nach Region", "fr": "Chiffre d'affaires"},
+ "description": {"de": "Quartalsumsatz nach Vertriebsregion"}
+ }
+
+This enables localization of user-created content (dashboard titles,
+chart names, filter labels) based on the viewer's UI language setting.
+Controlled by ENABLE_CONTENT_LOCALIZATION feature flag.
+
+Revision ID: 1af0da0adfec
+Revises: 9787190b3d89
+Create Date: 2026-02-04 14:00:00.000000
+
+"""
+
+from sqlalchemy import Column, JSON
+
+from superset.migrations.shared.utils import add_columns, drop_columns
+
+# revision identifiers, used by Alembic.
+revision = "1af0da0adfec"
+down_revision = "9787190b3d89"
Review Comment:
This revision creates a second Alembic head: `2025_12_18_0220_create_tasks_table.py` already uses `9787190b3d89` as its `down_revision`. That makes `superset db upgrade` unable to resolve a single head, so deployments cannot create these columns. Should this be chained to the current head (or merged with the other branch)?
##########
superset/localization/localizable_mixin.py:
##########
@@ -0,0 +1,117 @@
+# 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.
+"""
+LocalizableMixin for SQLAlchemy models.
+
+Provides content localization support for user-generated content fields.
+Models that inherit this mixin can store and retrieve translations for
+fields like titles and descriptions based on the viewer's locale.
+
+Translations are stored in a JSON column with the following structure:
+{
+ "field_name": {
+ "locale": "translated_value"
+ }
+}
+
+Example:
+{
+ "dashboard_title": {"de": "Verkaufs-Dashboard", "fr": "Tableau de bord"},
+ "description": {"de": "Monatlicher Verkaufsbericht"}
+}
+"""
+
+from typing import Any
+
+from superset.localization.locale_utils import get_translation
+
+
+class LocalizableMixin:
+ """
+ Mixin providing content localization for SQLAlchemy models.
+
+ Requires the model to have a `translations` attribute (JSON column).
+ Provides methods for getting localized values with fallback support,
+ setting translations, and listing available locales.
+ """
+
+ translations: dict[str, dict[str, str]] | None
+
+ def get_localized(self, field: str, locale: str) -> Any:
+ """
+ Get localized value for a field with fallback support.
+
+ Fallback chain:
+ 1. Exact locale match (e.g., "de-DE")
+ 2. Base language fallback (e.g., "de" from "de-DE")
+ 3. Original field value
+
+ Args:
+ field: The field name to get localized value for
+ locale: The locale code (e.g., "de", "de-DE", "fr")
+
+ Returns:
+ The localized value if translation exists, otherwise the original
+ field value.
+ """
+ if not self.translations:
+ return getattr(self, field)
+
+ field_translations = self.translations.get(field, {})
+
+ translated = get_translation(field_translations, locale)
+ if translated is not None:
+ return translated
+
+ return getattr(self, field)
+
+ def set_translation(self, field: str, locale: str, value: str) -> None:
+ """
+ Set translation for a field and locale.
+
+ Creates the translations dict and field dict if they don't exist.
+
+ Args:
+ field: The field name to set translation for
+ locale: The locale code (e.g., "de", "fr")
+ value: The translated value
+ """
+ if self.translations is None:
+ self.translations = {}
+
+ if field not in self.translations:
+ self.translations[field] = {}
+
+ self.translations[field][locale] = value
Review Comment:
After a model has persisted translations, this only mutates the nested JSON dictionary. Plain SQLAlchemy `JSON` columns do not mark nested in-place changes dirty, so adding a second locale can be lost on commit and reload. Should this reassign the column (or flag it modified) after updating the nested map?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #37790:
URL: https://github.com/apache/superset/pull/37790#issuecomment-6307976935
### ⚠️ Possible DB migration conflict
@YuriyKrasilnikov the base branch `master` picked up a new database migration under `superset/migrations/` after this PR was opened, and this PR adds or modifies migration files too. Alembic migrations form a single linear chain, so if both branch off the same parent revision, merging this PR as-is could leave the migration history with two heads instead of one, which makes `superset db upgrade` fail with `Multiple head revisions are present`.
To check and, if needed, fix this:
1. Rebase this branch onto the latest `master`.
2. Run `superset db heads`. If it lists more than one revision, you have a conflict.
3. In your new migration's script, update `down_revision` (and the `Revises` comment) to point at the other head instead, so the chain has a single head again.
See [Merging DB Migrations](https://superset.apache.org/docs/contributing/development#merging-db-migrations) in the contributing guide for a worked example.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #37790:
URL: https://github.com/apache/superset/pull/37790#issuecomment-3916780464
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers a full AI review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #37790:
URL: https://github.com/apache/superset/pull/37790#issuecomment-3917431621
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers a full AI review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "netlify[bot] (via GitHub)" <gi...@apache.org>.
netlify[bot] commented on PR #37790:
URL: https://github.com/apache/superset/pull/37790#issuecomment-3866980610
### <span aria-hidden="true">✅</span> Deploy Preview for *superset-docs-preview* ready!
| Name | Link |
|:-:|------------------------|
|<span aria-hidden="true">🔨</span> Latest commit | c76fb808fe323a2201605689aa5a17f31bbcd5c5 |
|<span aria-hidden="true">🔍</span> Latest deploy log | https://app.netlify.com/projects/superset-docs-preview/deploys/698866f494313100085ed726 |
|<span aria-hidden="true">😎</span> Deploy Preview | [https://deploy-preview-37790--superset-docs-preview.netlify.app](https://deploy-preview-37790--superset-docs-preview.netlify.app) |
|<span aria-hidden="true">📱</span> Preview on mobile | <details><summary> Toggle QR Code... </summary><br /><br /><br /><br />_Use your smartphone camera to open QR code link._</details> |
---
<!-- [superset-docs-preview Preview](https://deploy-preview-37790--superset-docs-preview.netlify.app) -->
_To edit notification comments on pull requests, go to your [Netlify project configuration](https://app.netlify.com/projects/superset-docs-preview/configuration/notifications#deploy-notifications)._
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "YuriyKrasilnikov (via GitHub)" <gi...@apache.org>.
YuriyKrasilnikov commented on PR #37790:
URL: https://github.com/apache/superset/pull/37790#issuecomment-3872851488
### Update: AdhocMetric/AdhocColumn label translations
Adds inline translation support for custom metric and column labels visible on dashboards (tooltips, legends, axes, table headers).
**Architecture:** Identical to native filters — `translations` stored directly in the metric/column object within `Slice.params`. No DB migration needed.
```json
{
"label": "Total Revenue",
"hasCustomLabel": true,
"translations": {"label": {"de": "Gesamtumsatz", "fr": "Revenu total"}}
}
```
**Backend:**
- `localize_metric_labels()` utility in `superset/localization/metric_label_utils.py` — processes `form_data.metrics[]` and `form_data.columns[]`, replaces labels for user locale
- Integrated in `ChartEntityResponseSchema.post_dump()` (dashboard charts endpoint)
- `translations` field added to `ChartDataAdhocMetricSchema` for validation
- Only objects with `hasCustomLabel=true` + `translations.label` are processed; string refs (SavedMetric/PhysicalColumn) pass through
**Frontend:**
- `translations` field added to `AdhocMetricBase`, `AdhocColumn` types, and `AdhocMetric` class
- `AdhocMetricEditPopoverTitle` renders `LocaleSwitcher` when feature flag is on and metric has custom label
- `AdhocMetricPopoverTrigger` manages translations state, includes in saved metric object
**Tests:**
- 20 backend unit tests (`metric_label_localization_test.py`): translation, no-translation, hasCustomLabel=false, columns, string refs, mixed types, locale fallback, no-mutation, edge cases
- 4 schema integration tests (`chart_schema_localization_test.py`): metric/column labels in form_data, feature flag off, mixed string/dict metrics
- 5 existing frontend tests pass with updated mocks
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "github-actions[bot] (via GitHub) via notifications" <no...@superset.apache.org>.
github-actions[bot] commented on PR #37790:
URL: https://github.com/apache/superset/pull/37790#issuecomment-7112226039
### ⚠️ Possible DB migration conflict
@YuriyKrasilnikov the base branch `master` picked up a new database migration under `superset/migrations/` after this PR was opened, and this PR adds or modifies migration files too. Alembic migrations form a single linear chain, so if both branch off the same parent revision, merging this PR as-is could leave the migration history with two heads instead of one, which makes `superset db upgrade` fail with `Multiple head revisions are present`.
To check and, if needed, fix this:
1. Rebase this branch onto the latest `master`.
2. Run `superset db heads`. If it lists more than one revision, you have a conflict.
3. In your new migration's script, update `down_revision` (and the `Revises` comment) to point at the other head instead, so the chain has a single head again.
See [Merging DB Migrations](https://superset.apache.org/docs/contributing/development#merging-db-migrations) in the contributing guide for a worked example.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #37790:
URL: https://github.com/apache/superset/pull/37790#issuecomment-3866977488
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #37790:
URL: https://github.com/apache/superset/pull/37790#issuecomment-3922878049
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers a full AI review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #37790:
URL: https://github.com/apache/superset/pull/37790#issuecomment-5704341410
# 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️❗ @YuriyKrasilnikov Your base branch `master` has also updated `superset/migrations`.
**Please consider rebasing your branch and [resolving potential db migration conflicts](https://superset.apache.org/docs/contributing/development#merging-db-migrations).**
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #37790:
URL: https://github.com/apache/superset/pull/37790#issuecomment-5941597427
### ⚠️ Possible DB migration conflict
@YuriyKrasilnikov the base branch `master` picked up a new database migration under `superset/migrations/` after this PR was opened, and this PR adds or modifies migration files too. Alembic migrations form a single linear chain, so if both branch off the same parent revision, merging this PR as-is could leave the migration history with two heads instead of one, which makes `superset db upgrade` fail with `Multiple head revisions are present`.
To check and, if needed, fix this:
1. Rebase this branch onto the latest `master`.
2. Run `superset db heads`. If it lists more than one revision, you have a conflict.
3. In your new migration's script, update `down_revision` (and the `Revises` comment) to point at the other head instead, so the chain has a single head again.
See [Merging DB Migrations](https://superset.apache.org/docs/contributing/development#merging-db-migrations) in the contributing guide for a worked example.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "github-actions[bot] (via GitHub) via notifications" <no...@superset.apache.org>.
github-actions[bot] commented on PR #37790:
URL: https://github.com/apache/superset/pull/37790#issuecomment-7174317837
### ⚠️ Possible DB migration conflict
@YuriyKrasilnikov the base branch `master` picked up a new database migration under `superset/migrations/` after this PR was opened, and this PR adds or modifies migration files too. Alembic migrations form a single linear chain, so if both branch off the same parent revision, merging this PR as-is could leave the migration history with two heads instead of one, which makes `superset db upgrade` fail with `Multiple head revisions are present`.
To check and, if needed, fix this:
1. Rebase this branch onto the latest `master`.
2. Run `superset db heads`. If it lists more than one revision, you have a conflict.
3. In your new migration's script, update `down_revision` (and the `Revises` comment) to point at the other head instead, so the chain has a single head again.
See [Merging DB Migrations](https://superset.apache.org/docs/contributing/development#merging-db-migrations) in the contributing guide for a worked example.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "github-actions[bot] (via GitHub) via notifications" <no...@superset.apache.org>.
github-actions[bot] commented on PR #37790:
URL: https://github.com/apache/superset/pull/37790#issuecomment-7429291103
### ⚠️ Possible DB migration conflict
@YuriyKrasilnikov the base branch `master` picked up a new database migration under `superset/migrations/` after this PR was opened, and this PR adds or modifies migration files too. Alembic migrations form a single linear chain, so if both branch off the same parent revision, merging this PR as-is could leave the migration history with two heads instead of one, which makes `superset db upgrade` fail with `Multiple head revisions are present`.
To check and, if needed, fix this:
1. Rebase this branch onto the latest `master`.
2. Run `superset db heads`. If it lists more than one revision, you have a conflict.
3. In your new migration's script, update `down_revision` (and the `Revises` comment) to point at the other head instead, so the chain has a single head again.
See [Merging DB Migrations](https://superset.apache.org/docs/contributing/development#merging-db-migrations) in the contributing guide for a worked example.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #37790:
URL: https://github.com/apache/superset/pull/37790#discussion_r2818620004
##########
superset-frontend/src/components/TranslationEditor/utils.ts:
##########
@@ -0,0 +1,163 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import type { Translations } from 'src/types/Localization';
+import type { QueryFormMetric } from '@superset-ui/core';
+import getBootstrapData from 'src/utils/getBootstrapData';
+
+/**
+ * Sentinel value representing the default (untranslated) column text
+ * in the locale switcher. Not a real locale code.
+ */
+export const DEFAULT_LOCALE_KEY = 'default';
+
+/** Remove empty-string translation values; drop fields with no translations. */
+export function stripEmptyValues(translations: Translations): Translations {
+ const cleaned: Translations = {};
+ for (const [field, locales] of Object.entries(translations)) {
+ const filtered: Record<string, string> = {};
+ for (const [locale, value] of Object.entries(locales)) {
+ if (value) {
+ filtered[locale] = value;
+ }
+ }
+ if (Object.keys(filtered).length > 0) {
+ cleaned[field] = filtered;
+ }
+ }
+ return cleaned;
+}
+
+/** Count non-empty translations for a specific field. */
+export function countFieldTranslations(
+ translations: Translations,
+ fieldName: string,
+): number {
+ const fieldMap = translations[fieldName];
+ if (!fieldMap) return 0;
+ return Object.values(fieldMap).filter(Boolean).length;
Review Comment:
**Suggestion:** The translation count helper currently includes the sentinel default locale key in its count, so default (untranslated) text will be treated as a translation, inflating the count and potentially breaking any logic that depends on whether there are real translations or not. It should explicitly exclude the `DEFAULT_LOCALE_KEY` when counting. [logic error]
<details>
<summary><b>Severity Level:</b> Major ⚠️</summary>
```mdx
- ⚠️ Translation editor may overreport number of available translations.
- ⚠️ UI badges depending on counts may show misleading numbers.
- ⚠️ Logic checking "has translations" may behave incorrectly.
```
</details>
```suggestion
return Object.entries(fieldMap)
.filter(
([locale, value]) => locale !== DEFAULT_LOCALE_KEY && Boolean(value),
)
.length;
```
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. In a test or caller, import `countFieldTranslations` and `DEFAULT_LOCALE_KEY` from
`superset-frontend/src/components/TranslationEditor/utils.ts` (function at lines 47–53,
constant at line 27).
2. Construct a `translations` object for some field, e.g. `{ label: {
[DEFAULT_LOCALE_KEY]: 'Sales', de: 'Verkäufe' } }`, where the `DEFAULT_LOCALE_KEY` entry
represents the untranslated base text.
3. Call `countFieldTranslations(translations, 'label')` so execution enters the
implementation at `utils.ts:47–53`.
4. Observe the returned value is `2` (both `default` and `de` counted) even though there
is only one real translation locale; the current implementation counts all non-empty
entries and does not exclude the sentinel `DEFAULT_LOCALE_KEY`.
```
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset-frontend/src/components/TranslationEditor/utils.ts
**Line:** 53:53
**Comment:**
*Logic Error: The translation count helper currently includes the sentinel default locale key in its count, so default (untranslated) text will be treated as a translation, inflating the count and potentially breaking any logic that depends on whether there are real translations or not. It should explicitly exclude the `DEFAULT_LOCALE_KEY` when counting.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=2df2680831b317d8029a1b29e9711ce2d9123dc7ee243e85df2810576aca7eb7&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=2df2680831b317d8029a1b29e9711ce2d9123dc7ee243e85df2810576aca7eb7&reaction=dislike'>👎</a>
##########
superset-frontend/src/components/TranslationEditor/LocaleSwitcher.tsx:
##########
@@ -0,0 +1,253 @@
+/**
+ * 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 { useCallback, useMemo, useState } from 'react';
+import type { MenuProps } from 'antd';
+import { t } from '@apache-superset/core';
+import { css, useTheme } from '@apache-superset/core/ui';
+import {
+ Badge,
+ Dropdown,
+ Icons,
+} from '@superset-ui/core/components';
+import type { Translations, LocaleInfo } from 'src/types/Localization';
+import { DEFAULT_LOCALE_KEY, countFieldTranslations } from './utils';
+
+export interface LocaleSwitcherProps {
+ /** Translation field key (e.g., 'dashboard_title', 'slice_name'). */
+ fieldName: string;
+ /** Current default (column) value — used for ✓ indicator on DEFAULT. */
+ defaultValue: string;
+ /** Full translations object for the entity. */
+ translations: Translations;
+ /** All configured locales from server (including default locale). */
+ allLocales: LocaleInfo[];
+ /** Server's default locale code (e.g., 'en'). */
+ defaultLocale: string;
+ /** Current user's UI locale code from session. */
+ userLocale: string;
+ /** Currently active locale. Controlled by parent. */
+ activeLocale: string;
+ /** Called when user picks a locale from the dropdown. */
+ onLocaleChange: (locale: string) => void;
+ /** Human-readable field label for accessibility (e.g., 'Dashboard Title'). */
+ fieldLabel: string;
+ /** When false, renders as a read-only indicator without dropdown. Default true. */
+ interactive?: boolean;
+ /** Called when the dropdown opens or closes. */
+ onDropdownOpenChange?: (open: boolean) => void;
+}
+
+/**
+ * Inline locale dropdown rendered as an Input suffix.
+ *
+ * Displays the currently active locale (DEFAULT or a specific language)
+ * with a badge showing translation count. Click opens a dropdown to
+ * switch between DEFAULT text and per-locale translations.
+ *
+ * Yellow highlight indicates the user's locale has no translation.
+ */
+export default function LocaleSwitcher({
+ fieldName,
+ defaultValue,
+ translations,
+ allLocales,
+ defaultLocale,
+ userLocale,
+ activeLocale,
+ onLocaleChange,
+ fieldLabel,
+ interactive = true,
+ onDropdownOpenChange,
+}: LocaleSwitcherProps) {
+ const theme = useTheme();
+
+ const fieldTranslations = translations[fieldName] ?? {};
+ const translationCount = countFieldTranslations(translations, fieldName);
+
+ const userLocaleHasTranslation =
+ userLocale === defaultLocale || Boolean(fieldTranslations[userLocale]);
+ const isWarning = !userLocaleHasTranslation;
+
+ const localeMap = useMemo(
+ () => new Map(allLocales.map(loc => [loc.code, loc])),
+ [allLocales],
+ );
+
+ const sortedLocales = useMemo(
+ () => [...allLocales].sort((a, b) => a.code.localeCompare(b.code)),
+ [allLocales],
+ );
+
+ const isDefault = activeLocale === DEFAULT_LOCALE_KEY;
+ const activeLocaleInfo = isDefault ? undefined : localeMap.get(activeLocale);
+ const triggerFlag = activeLocaleInfo?.flag;
+
+ const menuItems: MenuProps['items'] = useMemo(() => {
+ const checkIcon = (
+ <Icons.CheckOutlined
+ iconSize="s"
+ css={css`
+ font-size: 12px;
+ `}
+ />
+ );
+ const noIcon = (
+ <span
+ css={css`
+ display: inline-block;
+ width: 14px;
+ `}
+ />
+ );
+
+ return [
+ {
+ key: DEFAULT_LOCALE_KEY,
+ icon: defaultValue ? checkIcon : noIcon,
+ label: (
+ <span
+ css={css`
+ font-weight: ${activeLocale === DEFAULT_LOCALE_KEY ? 600 : 400};
+ `}
+ >
+ {t('DEFAULT')}
+ </span>
+ ),
+ },
+ { type: 'divider' as const },
+ ...sortedLocales.map(locale => ({
+ key: locale.code,
+ icon: fieldTranslations[locale.code] ? checkIcon : noIcon,
+ label: (
+ <span
+ css={css`
+ font-weight: ${activeLocale === locale.code ? 600 : 400};
+ `}
+ >
+ {locale.flag ? `${locale.flag} ` : ''}
+ {locale.name}
+ </span>
+ ),
+ })),
+ ];
+ }, [
+ sortedLocales,
+ fieldTranslations,
+ defaultValue,
+ activeLocale,
+ ]);
+
+ const [dropdownOpen, setDropdownOpen] = useState(false);
+
+ const handleOpenChange = useCallback(
+ (open: boolean) => {
+ setDropdownOpen(open);
+ onDropdownOpenChange?.(open);
+ },
+ [onDropdownOpenChange],
+ );
+
+ const handleMenuClick: MenuProps['onClick'] = ({ key }) => {
+ onLocaleChange(key);
+ handleOpenChange(false);
+ };
+
+ const suffixColor = isWarning ? theme.colorWarning : theme.colorText;
+
+ const ariaLabel = t(
+ 'Locale switcher for %s: %s (%s translations)',
+ fieldLabel,
+ isDefault ? t('DEFAULT') : activeLocale,
+ translationCount,
+ );
+
+ const iconElement = triggerFlag ? (
+ <span
+ css={css`
+ font-size: 14px;
+ `}
+ >
+ {triggerFlag}
+ </span>
+ ) : (
+ <Icons.GlobalOutlined
+ iconSize="m"
+ css={css`
+ color: ${suffixColor};
+ `}
+ />
+ );
+
+ const indicatorCss = css`
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ line-height: 1;
+ color: ${suffixColor};
+ white-space: nowrap;
+ user-select: none;
+ `;
+
+ if (!interactive) {
+ return (
+ <span aria-label={ariaLabel} css={indicatorCss}>
+ {iconElement}
+ <Badge count={translationCount} size="small" showZero={false} />
+ </span>
+ );
+ }
+
+ return (
+ <Dropdown
+ menu={{ items: menuItems, onClick: handleMenuClick }}
+ trigger={['click']}
+ open={dropdownOpen}
+ onOpenChange={handleOpenChange}
+ getPopupContainer={() => document.body}
+ >
+ <span
+ role="button"
+ tabIndex={0}
+ aria-label={ariaLabel}
+ onClick={e => e.stopPropagation()}
+ onKeyDown={e => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.stopPropagation();
+ e.preventDefault();
+ setDropdownOpen(prev => !prev);
Review Comment:
**Suggestion:** When the user toggles the dropdown with keyboard (Enter/Space), the component updates its internal `dropdownOpen` state directly but does not call the `onDropdownOpenChange` callback, so consumers relying on this callback only see open/close changes for mouse clicks and not for keyboard interactions, causing inconsistent external state and making the documented API misleading. [logic error]
<details>
<summary><b>Severity Level:</b> Major ⚠️</summary>
```mdx
- ⚠️ Keyboard toggling doesn't trigger onDropdownOpenChange callback for consumers.
- ⚠️ External state synced to dropdown open state becomes inconsistent.
- ⚠️ Accessibility keyboard users experience subtly different behavior than mouse.
```
</details>
```suggestion
handleOpenChange(!dropdownOpen);
```
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. Render `LocaleSwitcher`
(superset-frontend/src/components/TranslationEditor/LocaleSwitcher.tsx) with `interactive`
left as default `true` and pass a non-noop `onDropdownOpenChange` callback (e.g., logging
to console).
2. Focus the locale switcher trigger `<span>` by tabbing to it in the UI; this uses the
element defined at lines 224–240 with `role="button"` and `tabIndex={0}`.
3. Press `Space` or `Enter` so `onKeyDown` at lines 229–235 executes, calling
`setDropdownOpen(prev => !prev)` and updating the controlled `open` prop on the
surrounding `<Dropdown>` at lines 217–223, causing the menu to open/close.
4. Observe that the `onDropdownOpenChange` callback passed into props is never invoked for
this keyboard toggle path because `handleOpenChange` (lines 158–164), which is responsible
for calling `onDropdownOpenChange`, is not used in `onKeyDown`, whereas mouse-driven
open/close flows through `onOpenChange={handleOpenChange}` on the `<Dropdown>`.
```
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset-frontend/src/components/TranslationEditor/LocaleSwitcher.tsx
**Line:** 233:233
**Comment:**
*Logic Error: When the user toggles the dropdown with keyboard (Enter/Space), the component updates its internal `dropdownOpen` state directly but does not call the `onDropdownOpenChange` callback, so consumers relying on this callback only see open/close changes for mouse clicks and not for keyboard interactions, causing inconsistent external state and making the documented API misleading.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=bc0543a53a4cebcafa3e77bf4d4aba7ebfbee564f760779092db99fa109a276e&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=bc0543a53a4cebcafa3e77bf4d4aba7ebfbee564f760779092db99fa109a276e&reaction=dislike'>👎</a>
##########
superset-frontend/packages/superset-ui-core/src/query/getLocalizedFormDataValue.ts:
##########
@@ -0,0 +1,49 @@
+/**
+ * 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.
+ */
+
+/**
+ * Resolve a localized value for a formData text field.
+ *
+ * Looks up `translations[fieldName][locale]` with base language fallback
+ * (e.g., "de" from "de-AT").
+ *
+ * @param translations - The translations object from formData (field → locale → value)
+ * @param fieldName - The control name (e.g., "x_axis_title", "subtitle")
+ * @param locale - The user's locale (e.g., "de", "de-AT")
+ * @returns The translated string, or undefined if no translation exists
+ */
+export default function getLocalizedFormDataValue(
+ translations: Record<string, Record<string, string>> | undefined,
+ fieldName: string,
+ locale?: string,
+): string | undefined {
+ if (!translations || !locale) return undefined;
+
+ const fieldTranslations = translations[fieldName];
+ if (!fieldTranslations) return undefined;
+
+ if (fieldTranslations[locale]) return fieldTranslations[locale];
+
+ const baseLang = locale.split('-')[0];
+ if (baseLang !== locale && fieldTranslations[baseLang]) {
Review Comment:
**Suggestion:** The function treats translation values as truthy when deciding whether a translation exists, so if a valid translation is an empty string (e.g., intentionally blank label), it will be ignored and the function will incorrectly fall back to another locale or return undefined. The check should instead verify the presence of a key in the translations map, not the truthiness of its value, so that empty string translations are respected. [logic error]
<details>
<summary><b>Severity Level:</b> Major ⚠️</summary>
```mdx
- ⚠️ Localized formData fields cannot intentionally be blank.
- ⚠️ Fallback locale text appears instead of empty translation.
```
</details>
```suggestion
if (locale in fieldTranslations) {
return fieldTranslations[locale];
}
const baseLang = locale.split('-')[0];
if (baseLang !== locale && baseLang in fieldTranslations) {
```
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. Build or run the frontend including `getLocalizedFormDataValue` at
`superset-frontend/packages/superset-ui-core/src/query/getLocalizedFormDataValue.ts:31-49`.
2. In a unit test or caller, invoke `getLocalizedFormDataValue` with `translations = {
subtitle: { 'de': '', 'en': 'My subtitle' } }`, `fieldName = 'subtitle'`, and `locale =
'de'`.
3. Inside the function at lines 38-41, `fieldTranslations` is `{ 'de': '', 'en': 'My
subtitle' }` and `fieldTranslations[locale]` evaluates to `''` which is falsy, so the `if
(fieldTranslations[locale])` check fails and does not return the empty string.
4. Execution proceeds to the fallback logic at lines 43-46; if no base-language key is
used or differs, the function returns `undefined` instead of the explicitly configured
empty string, so callers cannot distinguish between "no translation" and "intentionally
blank".
```
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset-frontend/packages/superset-ui-core/src/query/getLocalizedFormDataValue.ts
**Line:** 41:44
**Comment:**
*Logic Error: The function treats translation values as truthy when deciding whether a translation exists, so if a valid translation is an empty string (e.g., intentionally blank label), it will be ignored and the function will incorrectly fall back to another locale or return undefined. The check should instead verify the presence of a key in the translations map, not the truthiness of its value, so that empty string translations are respected.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=6fd48310d55624c4259d7f9c5ccd54b553c6db86b0d1fdbd0f8b7554ac975461&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=6fd48310d55624c4259d7f9c5ccd54b553c6db86b0d1fdbd0f8b7554ac975461&reaction=dislike'>👎</a>
##########
superset-frontend/plugins/plugin-chart-echarts/src/MixedTimeseries/transformProps.ts:
##########
@@ -223,6 +228,24 @@ export default function transformProps(
metricsB = [],
}: EchartsMixedTimeseriesFormData = { ...DEFAULT_FORM_DATA, ...formData };
+ const localizedMetricLabelMap = buildLocalizedMetricLabelMap(
+ [...metrics, ...metricsB],
+ locale,
+ );
+
+ const localizedXAxisTitle =
+ getLocalizedFormDataValue(formData.translations, 'x_axis_title', locale) ??
+ xAxisTitle;
+ const localizedYAxisTitle =
+ getLocalizedFormDataValue(formData.translations, 'y_axis_title', locale) ??
+ yAxisTitle;
+ const localizedYAxisTitleSecondary =
+ getLocalizedFormDataValue(
+ formData.translations,
+ 'yAxisTitleSecondary',
+ locale,
Review Comment:
**Suggestion:** The secondary Y-axis title uses a camelCase translation key (`'yAxisTitleSecondary'`) while all other localized form-data keys use snake_case, so any translations stored under the expected key (e.g. `'y_axis_title_secondary'`) will never be found and the axis title will not localize as intended. [logic error]
<details>
<summary><b>Severity Level:</b> Major ⚠️</summary>
```mdx
- ⚠️ Secondary Y-axis title remains untranslated in localized charts.
- ⚠️ MixedTimeseries legend/axis localization appears inconsistent to users.
```
</details>
```suggestion
'y_axis_title_secondary',
```
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. Create or edit a Mixed Timeseries chart in Superset so it uses a secondary Y-axis
(chart type wired to `transformProps` in
`plugins/plugin-chart-echarts/src/MixedTimeseries/transformProps.ts`).
2. In the chart's customize/axis controls, set a secondary Y-axis title (this populates
`formData.yAxisTitleSecondary` and, via localization, a translation entry under the
control key `y_axis_title_secondary` in `formData.translations`).
3. Configure a non-default UI locale (e.g. `de`) and provide a localized value for the
secondary Y-axis title so `formData.translations['y_axis_title_secondary']['de']` is set
when the chart is loaded.
4. View the chart in that locale so `transformProps` runs: at lines 243–248 it calls
`getLocalizedFormDataValue(formData.translations, 'yAxisTitleSecondary', locale)`, which
returns `undefined` because the translations map is keyed by `y_axis_title_secondary`; the
code then falls back to `yAxisTitleSecondary`, and at lines ~700–714 assigns `name:
localizedYAxisTitleSecondary` to `yAxis[1]`, resulting in the secondary Y-axis title not
being localized while other axis titles (looked up via `'x_axis_title'` and
`'y_axis_title'`) are localized correctly.
```
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset-frontend/plugins/plugin-chart-echarts/src/MixedTimeseries/transformProps.ts
**Line:** 246:246
**Comment:**
*Logic Error: The secondary Y-axis title uses a camelCase translation key (`'yAxisTitleSecondary'`) while all other localized form-data keys use snake_case, so any translations stored under the expected key (e.g. `'y_axis_title_secondary'`) will never be found and the axis title will not localize as intended.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=1851f7d7422bb459d6ff451d4ac90d9bd8a0bfc404790ba8716281dff6798d11&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=1851f7d7422bb459d6ff451d4ac90d9bd8a0bfc404790ba8716281dff6798d11&reaction=dislike'>👎</a>
##########
superset-frontend/src/explore/components/SaveModal.tsx:
##########
@@ -152,8 +163,30 @@ class SaveModal extends Component<SaveModalProps, SaveModalState> {
);
}
}
+
+ if (
+ isFeatureEnabled(FeatureFlag.EnableContentLocalization) &&
+ this.props.slice?.slice_id
+ ) {
+ try {
+ const response = await SupersetClient.get({
+ endpoint: `/api/v1/chart/${this.props.slice.slice_id}?include_translations=true`,
+ });
+ const chart = response.json.result;
+ this.setState({
+ newSliceName: chart.slice_name || this.state.newSliceName,
+ translations: chart.translations ?? {},
Review Comment:
**Suggestion:** After fetching chart translations in componentDidMount, the code unconditionally overwrites the current chart name with the server value whenever it is non-empty; if the user has already started editing the name before the request resolves, their changes will be silently clobbered by the async response. Use a functional setState and only apply the server value when the current name is still empty, while also preserving any existing translations. [logic error]
<details>
<summary><b>Severity Level:</b> Major ⚠️</summary>
```mdx
- ❌ Save chart modal discards in-progress chart name edits.
- ⚠️ Affects existing charts with localization feature enabled.
```
</details>
```suggestion
this.setState(prevState => ({
newSliceName:
prevState.newSliceName || chart.slice_name || prevState.newSliceName,
translations: chart.translations ?? prevState.translations ?? {},
}));
```
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. Open an existing saved chart in Explore and click the "Save" button to open the
SaveModal, which renders `SaveModal` in
`superset-frontend/src/explore/components/SaveModal.tsx` and triggers its
`componentDidMount()` method (around lines 117–186).
2. With `ENABLE_CONTENT_LOCALIZATION` enabled and `this.props.slice.slice_id` present,
`componentDidMount()` enters the `if
(isFeatureEnabled(FeatureFlag.EnableContentLocalization) && this.props.slice?.slice_id)`
block (lines ~167–183) and issues an async GET via `SupersetClient.get()` to
`/api/v1/chart/{slice_id}?include_translations=true` (line 172).
3. While that request is in flight (non-trivial network latency), the user edits the
"Chart name" field in the modal; this field is rendered as `TranslatableSliceNameField` in
`renderSaveChartModal()` (lines ~635–666) with `onChange={this.onSliceNameChange}`, which
invokes `onSliceNameChange()` (lines ~195–198) to update `this.state.newSliceName` with
the user's typed value.
4. When the GET request resolves, the code at lines 172–178 runs `this.setState({
newSliceName: chart.slice_name || this.state.newSliceName, ... })`; since
`chart.slice_name` is non-empty for an existing chart, it wins the `||` expression and
overwrites the user-edited `newSliceName` with the server value, silently discarding the
in-progress edit in the SaveModal UI.
```
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset-frontend/src/explore/components/SaveModal.tsx
**Line:** 176:178
**Comment:**
*Logic Error: After fetching chart translations in componentDidMount, the code unconditionally overwrites the current chart name with the server value whenever it is non-empty; if the user has already started editing the name before the request resolves, their changes will be silently clobbered by the async response. Use a functional setState and only apply the server value when the current name is still empty, while also preserving any existing translations.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=5ce8a2ce4b842f4ebf349a4a259ca8f99ff94d5dc4e5e24e55d10b190a25971f&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=5ce8a2ce4b842f4ebf349a4a259ca8f99ff94d5dc4e5e24e55d10b190a25971f&reaction=dislike'>👎</a>
##########
superset-frontend/src/dashboard/components/nativeFilters/FiltersConfigModal/FiltersConfigForm/FiltersConfigForm.tsx:
##########
@@ -569,6 +586,109 @@ const FiltersConfigForm = (
[filterId, form, formChanged],
);
+ const localizationEnabled = isFeatureEnabled(
+ FeatureFlag.EnableContentLocalization,
+ );
+
+ const currentTranslations: Translations =
+ formFilter?.translations ?? filterToEdit?.translations ?? {};
+
+ useEffect(() => {
+ if (filterToEdit?.translations) {
+ setNativeFilterFieldValues(form, filterId, {
+ translations: filterToEdit.translations,
+ });
+ }
+ }, [filterId, filterToEdit?.translations, form]);
+
+ useEffect(() => {
+ if (localizationEnabled) {
+ SupersetClient.get({
+ endpoint: '/api/v1/localization/available_locales',
+ }).then(
+ response => {
+ const { locales, default_locale } = response.json.result;
+ setAllLocales(locales);
+ setDefaultLocale(default_locale);
+ },
+ err => logging.error('Failed to fetch available locales', err),
+ );
+ }
+ }, [localizationEnabled]);
+
+ // Refs for values read during initialization but not triggering re-runs.
+ // Without refs, editing a translation would reset the active locale
+ // because currentTranslations changes on every keystroke.
+ const currentTranslationsRef = useRef(currentTranslations);
+ currentTranslationsRef.current = currentTranslations;
+ const userLocaleRef = useRef(userLocale);
+ userLocaleRef.current = userLocale;
+
+ // Initialize nameActiveLocale when switching between filters.
+ useEffect(() => {
+ if (
+ localizationEnabled &&
+ currentTranslationsRef.current.name?.[userLocaleRef.current]
+ ) {
+ setNameActiveLocale(userLocaleRef.current);
+ } else {
+ setNameActiveLocale(DEFAULT_LOCALE_KEY);
+ }
+ }, [localizationEnabled, filterId]);
+
+ const handleNameTranslationChange = useCallback(
+ (value: string) => {
+ const updated: Translations = {
+ ...currentTranslationsRef.current,
+ name: { ...currentTranslationsRef.current.name, [nameActiveLocale]: value },
+ };
Review Comment:
**Suggestion:** When there is no existing `name` entry in the translations object, spreading `currentTranslationsRef.current.name` will attempt to spread `undefined`, causing a runtime TypeError ("Cannot convert undefined or null to object") the first time a translation is edited; guard this by falling back to an empty object before spreading. [logic error]
<details>
<summary><b>Severity Level:</b> Critical 🚨</summary>
```mdx
- ❌ Editing filter name translation crashes dashboard native filter modal.
- ⚠️ Prevents adding localized names for new native filters.
```
</details>
```suggestion
name: {
...(currentTranslationsRef.current.name ?? {}),
[nameActiveLocale]: value,
},
```
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. Enable the content localization feature flag on the backend so
`isFeatureEnabled(FeatureFlag.EnableContentLocalization)` returns true, ensuring the
localization logic in `FiltersConfigForm`
(`superset-frontend/src/dashboard/components/nativeFilters/FiltersConfigModal/FiltersConfigForm/FiltersConfigForm.tsx`)
is active.
2. Open any dashboard and launch the Native Filters configuration modal, which renders the
`FiltersConfigForm` component for a given filter (`FiltersConfigForm` is the configuration
UI for native filters in this modal).
3. Use a filter that has no `translations` persisted yet (for new filters,
`filterToEdit?.translations` and `formFilter?.translations` are `undefined`, so
`currentTranslations` and `currentTranslationsRef.current` are `{}` without a `name`
property at the time `handleNameTranslationChange` is defined).
4. In the filter configuration tab, enter a non-empty default filter name so
`handleNameLocaleChange` allows switching away from `DEFAULT_LOCALE_KEY`, then use the
inline `LocaleSwitcher` suffix on the name input to select a non-default locale; this
flips `nameActiveLocale` and causes `isEditingFilterTranslation` to become true, rendering
the `TranslationInput` whose `onChange` prop calls `handleNameTranslationChange`.
5. Start typing into the translated name field; on the first keystroke,
`handleNameTranslationChange` executes and evaluates `name: {
...currentTranslationsRef.current.name, [nameActiveLocale]: value }` at
`FiltersConfigForm.tsx:640-646`, where `currentTranslationsRef.current.name` is
`undefined`, causing a runtime `TypeError: Cannot convert undefined or null to object`
when the spread operator attempts to spread `undefined`, breaking the filter configuration
UI for that filter.
```
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset-frontend/src/dashboard/components/nativeFilters/FiltersConfigModal/FiltersConfigForm/FiltersConfigForm.tsx
**Line:** 644:644
**Comment:**
*Logic Error: When there is no existing `name` entry in the translations object, spreading `currentTranslationsRef.current.name` will attempt to spread `undefined`, causing a runtime TypeError ("Cannot convert undefined or null to object") the first time a translation is edited; guard this by falling back to an empty object before spreading.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=649f66cc86ac131017d5281c79d29512615fbd126bf92f648d90f0c9362ca8bb&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=649f66cc86ac131017d5281c79d29512615fbd126bf92f648d90f0c9362ca8bb&reaction=dislike'>👎</a>
##########
superset/localization/schema_mixin.py:
##########
@@ -0,0 +1,93 @@
+# 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.
+"""
+Marshmallow mixin for translations field.
+
+Provides translations field with feature flag validation and XSS sanitization.
+Used by all schemas that accept user-provided translations (Post, Put, Copy).
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from marshmallow import ValidationError, fields, post_load, validates_schema
+
+from superset import is_feature_enabled
+from superset.localization.sanitization import sanitize_translations
+from superset.localization.validation import validate_translations
+
+
+class TranslatableSchemaMixin:
+ """
+ Mixin for Marshmallow schemas that accept a ``translations`` field.
+
+ Adds:
+ - ``translations`` dict field (optional, nullable)
+ - ``@validates_schema``: feature flag check + structure validation
+ - ``@post_load``: XSS sanitization of translation values
+
+ Usage::
+
+ class MySchema(TranslatableSchemaMixin, Schema):
+ name = fields.String()
+ """
+
+ translations = fields.Dict(
+ metadata={"description": "Translations dict for content localization"},
+ allow_none=True,
+ )
+
+ @validates_schema
+ def validate_translations_data(
+ self, data: dict[str, Any], **kwargs: Any
+ ) -> None:
+ """
+ Validate translations field: feature flag and structure.
+
+ Checks:
+ 1. Feature flag ENABLE_CONTENT_LOCALIZATION must be enabled
+ 2. Structure must be valid: {field: {locale: value}}
+
+ Raises:
+ ValidationError: If feature disabled or structure invalid.
+ """
+ if "translations" not in data:
+ return
+
+ if not is_feature_enabled("ENABLE_CONTENT_LOCALIZATION"):
+ raise ValidationError(
+ "Content localization is not enabled. "
+ "Set ENABLE_CONTENT_LOCALIZATION=True to use translations.",
+ field_name="translations",
+ )
+
+ validate_translations(data["translations"])
Review Comment:
**Suggestion:** The schema declares the translations field as nullable, but the schema-level validator still runs and enforces the feature flag and structure checks when translations is explicitly set to null, causing valid requests with `"translations": null` to either fail validation or be passed as None into the structure validator which expects a dict-like object. [logic error]
<details>
<summary><b>Severity Level:</b> Major ⚠️</summary>
```mdx
- ❌ Post/Put/Copy schemas using mixin reject null translations.
- ⚠️ Dashboard and chart localization APIs may raise server errors.
- ⚠️ Optional nullable field behaves inconsistently with schema declaration.
```
</details>
```suggestion
translations = data.get("translations")
# Allow explicitly null translations when field is nullable
if translations is None:
return
if not is_feature_enabled("ENABLE_CONTENT_LOCALIZATION"):
raise ValidationError(
"Content localization is not enabled. "
"Set ENABLE_CONTENT_LOCALIZATION=True to use translations.",
field_name="translations",
)
validate_translations(translations)
```
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. Import `TranslatableSchemaMixin` from `superset/localization/schema_mixin.py:35` into a
test module or Python shell.
2. Define a Marshmallow schema subclass that mixes in `TranslatableSchemaMixin` (e.g.,
`class TestSchema(TranslatableSchemaMixin, Schema): name = fields.String()`), so that
`validate_translations_data` at lines 55–79 is executed during `.load()`.
3. With feature flag `ENABLE_CONTENT_LOCALIZATION` enabled (so the feature-flag check at
line 72 passes), call `TestSchema().load({"name": "foo", "translations": None})` so that
`data` passed into `validate_translations_data` contains `"translations": None`.
4. Inside `validate_translations_data` (`schema_mixin.py:69–79`), the condition `if
"translations" not in data:` at line 69 is false because the key is present, so the
function unconditionally calls `validate_translations(data["translations"])` at line 79
with `None`, turning a field declared `allow_none=True` into a value that must pass the
translations feature flag and structure validation, and potentially raising if
`validate_translations` expects a mapping.
```
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset/localization/schema_mixin.py
**Line:** 69:79
**Comment:**
*Logic Error: The schema declares the translations field as nullable, but the schema-level validator still runs and enforces the feature flag and structure checks when translations is explicitly set to null, causing valid requests with `"translations": null` to either fail validation or be passed as None into the structure validator which expects a dict-like object.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=3c78813fcf3495f2571b90d4c65db55ed83f62a779ec9bc9983ef26ab1ffe2dd&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=3c78813fcf3495f2571b90d4c65db55ed83f62a779ec9bc9983ef26ab1ffe2dd&reaction=dislike'>👎</a>
##########
superset-frontend/src/locale/LocaleController.ts:
##########
@@ -0,0 +1,263 @@
+/**
+ * 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 { configure, t as translate, tn as translateN } from '@apache-superset/core/ui';
+import type { LanguagePack } from '@apache-superset/core/ui';
+import { SupersetClient } from '@superset-ui/core';
+import { extendedDayjs as dayjs } from '@superset-ui/core/utils/dates';
+import { logging } from '@apache-superset/core';
+
+const DEFAULT_LANGUAGE_PACK: LanguagePack = {
+ domain: 'superset',
+ locale_data: {
+ superset: {
+ '': {
+ domain: 'superset',
+ lang: 'en',
+ plural_forms: 'nplurals=2; plural=(n != 1)',
+ },
+ },
+ },
+};
+
+export interface LocaleControllerOptions {
+ /** Initial locale code (e.g., 'en', 'ru', 'de') */
+ initialLocale?: string;
+ /** Callback invoked when locale changes */
+ onChange?: (locale: string) => void;
+ /** Skip initial language pack fetch (for cases when it's already loaded) */
+ skipInitialFetch?: boolean;
+}
+
+/**
+ * LocaleController manages application localization state reactively.
+ *
+ * This controller follows the same architectural pattern as ThemeController:
+ * - Owns and manages locale state
+ * - Notifies subscribers via onChange callbacks
+ * - Does NOT reload the page
+ * - Enables reactive updates in React via LocaleProvider
+ *
+ * Usage:
+ * ```typescript
+ * const controller = new LocaleController({ initialLocale: 'en' });
+ *
+ * // Subscribe to changes
+ * controller.onChange(locale => console.log('Locale changed:', locale));
+ *
+ * // Change locale (fetches language pack, updates state, notifies listeners)
+ * await controller.setLocale('ru');
+ * ```
+ */
+export class LocaleController {
+ private currentLocale: string;
+
+ private onChangeCallbacks: Set<(locale: string) => void> = new Set();
+
+ private isInitialized = false;
+
+ private pendingLocaleChange: Promise<void> | null = null;
+
+ constructor(options: LocaleControllerOptions = {}) {
+ const { initialLocale = 'en', onChange, skipInitialFetch = false } = options;
+
+ this.currentLocale = initialLocale;
+
+ if (onChange) {
+ this.onChangeCallbacks.add(onChange);
+ }
+
+ // If not skipping initial fetch and locale is not 'en', fetch language pack
+ if (!skipInitialFetch && initialLocale !== 'en') {
+ this.initializeLocale(initialLocale);
Review Comment:
**Suggestion:** The constructor starts an asynchronous locale initialization via `initializeLocale` without wiring it into `pendingLocaleChange`, so if `setLocale` is called while initialization is still in flight, the two async operations can race and the final active locale may end up being the initial one instead of the last requested locale. To fix this, ensure the initialization promise is stored in `pendingLocaleChange` so that `setLocale` waits for it before running its own update, preserving the "last call wins" behavior. [race condition]
<details>
<summary><b>Severity Level:</b> Critical 🚨</summary>
```mdx
- ❌ Locale may revert from user-selected to initial language.
- ❌ Locale-dependent dashboard and chart text show wrong language.
- ⚠️ Embedded SDK dynamic `setLocale` calls become unreliable.
- ⚠️ React listeners re-render with stale `currentLocale` value.
```
</details>
```suggestion
// Track the initialization promise so subsequent setLocale calls wait for it
this.pendingLocaleChange = this.initializeLocale(initialLocale);
```
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. Instantiate `LocaleController` with a non-English initial locale and default options,
e.g. `new LocaleController({ initialLocale: 'fr' })`, which triggers
`initializeLocale(initialLocale)` in the constructor at
`superset-frontend/src/locale/LocaleController.ts:77-89` without setting
`pendingLocaleChange`.
2. Before the async `initializeLocale('fr')` call (lines 192-201) resolves its
`SupersetClient.get` request (lines 220-227), call `controller.setLocale('de')` on the
same instance, invoking `setLocale` at lines 130-148 while `pendingLocaleChange` is still
`null`.
3. Inside `setLocale` (lines 130-148), the `if (this.pendingLocaleChange)` guard at lines
136-139 does nothing because `pendingLocaleChange` was never set by the constructor;
`this.pendingLocaleChange = this.doSetLocale('de')` is then assigned at line 142, and
`doSetLocale('de')` (lines 207-214) starts its own fetch and calls `applyLocale('de',
...)` (lines 236-248), setting `this.currentLocale` to `'de'`.
4. After `setLocale('de')` has completed and the UI has re-rendered in German, the
original `initializeLocale('fr')` call from the constructor finally resolves; it calls
`applyLocale('fr', ...)` at lines 192-201, which sets `this.currentLocale` back to `'fr'`
and notifies listeners at lines 247-248, so the app ends up localized in French (the
initial locale) instead of the user-requested German, demonstrating the race condition.
```
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset-frontend/src/locale/LocaleController.ts
**Line:** 88:88
**Comment:**
*Race Condition: The constructor starts an asynchronous locale initialization via `initializeLocale` without wiring it into `pendingLocaleChange`, so if `setLocale` is called while initialization is still in flight, the two async operations can race and the final active locale may end up being the initial one instead of the last requested locale. To fix this, ensure the initialization promise is stored in `pendingLocaleChange` so that `setLocale` waits for it before running its own update, preserving the "last call wins" behavior.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=5835445543ae710bd08f19ec40d12337287a45b3f71acf39b5455046d3bfd5d9&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=5835445543ae710bd08f19ec40d12337287a45b3f71acf39b5455046d3bfd5d9&reaction=dislike'>👎</a>
##########
superset/dashboards/schemas.py:
##########
@@ -257,8 +273,108 @@ def post_dump(self, serialized: dict[str, Any], **kwargs: Any) -> dict[str, Any]
del serialized["owners"]
del serialized["changed_by_name"]
del serialized["changed_by"]
Review Comment:
**Suggestion:** In the dashboard response post-dump hook, deleting keys from `serialized` unconditionally will raise `KeyError` if those fields were excluded (for example via `only`/`exclude` when instantiating the schema), so using `pop` with a default makes the hook robust without changing behavior when the keys are present. [possible bug]
<details>
<summary><b>Severity Level:</b> Major ⚠️</summary>
```mdx
- ❌ Guest dashboard serialization can crash with restricted field sets.
- ⚠️ Guest-facing dashboard APIs may intermittently return 500 errors.
```
</details>
```suggestion
serialized.pop("owners", None)
serialized.pop("changed_by_name", None)
serialized.pop("changed_by", None)
```
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. In a Python shell, import `DashboardGetResponseSchema` from
`superset.dashboards.schemas` (class defined at `superset/dashboards/schemas.py:228-260`).
2. Create a minimal dashboard-like object with attributes `id`, `slug`, `url`,
`dashboard_title`, etc., but you do not need `owners`, `changed_by_name`, or `changed_by`
attributes for this reproduction.
3. Instantiate the schema with a restricted field set so those keys are not serialized,
e.g. `schema = DashboardGetResponseSchema(only=("id", "dashboard_title"))`, and ensure
`security_manager.is_guest_user()` returns `True` (e.g. by configuring a guest user or
monkeypatching during a test).
4. Call `schema.dump(obj)`; the `@post_dump` method at
`superset/dashboards/schemas.py:262-281` executes, and because `"owners"`,
`"changed_by_name"`, and `"changed_by"` are absent from `serialized`, the `del
serialized["owners"]` / `del serialized["changed_by_name"]` / `del
serialized["changed_by"]` statements at lines 272-275 raise `KeyError`, causing the dump
(and any API using this schema) to fail.
```
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset/dashboards/schemas.py
**Line:** 273:275
**Comment:**
*Possible Bug: In the dashboard response post-dump hook, deleting keys from `serialized` unconditionally will raise `KeyError` if those fields were excluded (for example via `only`/`exclude` when instantiating the schema), so using `pop` with a default makes the hook robust without changing behavior when the keys are present.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=9e98f7f7103ceadcad9a0209b81f8e7114d9976a80feccf47da4b2adc55439ff&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=9e98f7f7103ceadcad9a0209b81f8e7114d9976a80feccf47da4b2adc55439ff&reaction=dislike'>👎</a>
##########
superset-frontend/src/explore/components/PropertiesModal/index.tsx:
##########
@@ -258,6 +293,18 @@ function PropertiesModal({
// get the owners of this slice
useEffect(() => {
fetchChartProperties();
+ if (isFeatureEnabled(FeatureFlag.EnableContentLocalization)) {
+ SupersetClient.get({
+ endpoint: '/api/v1/localization/available_locales',
+ }).then(
+ response => {
+ const { locales, default_locale } = response.json.result;
+ setAllLocales(locales);
+ setDefaultLocale(default_locale);
+ },
+ err => logging.error('Failed to fetch available locales', err),
+ );
+ }
}, [slice.slice_id]);
Review Comment:
**Suggestion:** The effect that loads chart properties and available locales only re-runs when the slice ID changes, even though it depends on `fetchChartProperties` (which closes over `userLocale`) and indirectly on `userLocale` itself; if the user's locale changes while the Properties modal is open, the modal will keep showing translations for the old locale and never refetch, which is a stale-state logic bug and will also be flagged by the React hooks linter. [logic error]
<details>
<summary><b>Severity Level:</b> Major ⚠️</summary>
```mdx
- ⚠️ React hooks linter flags stale dependency in PropertiesModal effect.
- ⚠️ Translations not refreshed if user locale changes mid-session.
```
</details>
```suggestion
}, [slice.slice_id, fetchChartProperties, userLocale]);
```
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. Run the frontend linting task (or CI) that includes the React hooks ESLint plugin over
`superset-frontend/src/explore/components/PropertiesModal/index.tsx`.
2. ESLint inspects the `useEffect` at lines 293–308, which uses the `fetchChartProperties`
callback but has a dependency array of `[slice.slice_id]`.
3. Since `fetchChartProperties` is defined with `useCallback` at lines ~167–215 and
depends on `userLocale` (via its dependency list `[showError, slice.slice_id,
userLocale]`), the `react-hooks/exhaustive-deps` rule reports a missing dependency warning
for this effect.
4. At runtime, if anything in the app updates `state.common.locale` (the Redux value read
at lines 60–62 via `useSelector`), `fetchChartProperties` is recreated with the new
`userLocale`, but the `useEffect` at 293–308 does not re-run (because its dependencies
exclude `fetchChartProperties` and `userLocale`), so the modal keeps whatever translations
and active locale state were loaded for the previous locale, demonstrating stale state if
live locale switching is supported.
```
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset-frontend/src/explore/components/PropertiesModal/index.tsx
**Line:** 308:308
**Comment:**
*Logic Error: The effect that loads chart properties and available locales only re-runs when the slice ID changes, even though it depends on `fetchChartProperties` (which closes over `userLocale`) and indirectly on `userLocale` itself; if the user's locale changes while the Properties modal is open, the modal will keep showing translations for the old locale and never refetch, which is a stale-state logic bug and will also be flagged by the React hooks linter.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=0d6ff9b5623af59cb69ac714a87628bad5175964caffd95733c9a42eb47d390e&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=0d6ff9b5623af59cb69ac714a87628bad5175964caffd95733c9a42eb47d390e&reaction=dislike'>👎</a>
##########
superset-frontend/src/explore/components/controls/TranslatableTextControl/index.tsx:
##########
@@ -0,0 +1,294 @@
+/**
+ * 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 {
+ ChangeEvent,
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from 'react';
+import { useSelector } from 'react-redux';
+import { logging } from '@apache-superset/core';
+import { isFeatureEnabled, FeatureFlag } from '@superset-ui/core';
+import { Constants, Input } from '@superset-ui/core/components';
+import { SupersetClient } from '@superset-ui/core/connection';
+import { debounce } from 'lodash';
+import ControlHeader from '../../ControlHeader';
+import TextControl from '../TextControl';
+import TranslationInput from 'src/components/TranslationInput';
+import {
+ LocaleSwitcher,
+ DEFAULT_LOCALE_KEY,
+} from 'src/components/TranslationEditor';
+import type { Translations, LocaleInfo } from 'src/types/Localization';
+import type { ExploreActions } from 'src/explore/actions/exploreActions';
+import type { QueryFormData } from '@superset-ui/core';
+
+export interface TranslatableTextControlProps {
+ name: string;
+ label?: string;
+ description?: string;
+ placeholder?: string;
+ value?: string | null;
+ disabled?: boolean;
+ onChange?: (value: string, errors: any[]) => void;
+ actions?: Partial<ExploreActions> & Pick<ExploreActions, 'setControlValue'>;
+ formData?: QueryFormData | null;
+ renderTrigger?: boolean;
+ [key: string]: unknown;
+}
+
+export default function TranslatableTextControl({
+ name,
+ label,
+ value,
+ onChange,
+ actions,
+ formData,
+ placeholder,
+ disabled,
+ ...rest
+}: TranslatableTextControlProps) {
+ const localizationEnabled = isFeatureEnabled(
+ FeatureFlag.EnableContentLocalization,
+ );
+
+ // --- Locale state (hooks always called, effects gated by flag) ---
+ const [allLocales, setAllLocales] = useState<LocaleInfo[]>([]);
+ const [defaultLocale, setDefaultLocale] = useState('');
+ const userLocale: string = useSelector(
+ (state: { common: { locale: string } }) => state.common.locale,
+ );
+ const [activeLocale, setActiveLocale] = useState(DEFAULT_LOCALE_KEY);
+ const [localesLoaded, setLocalesLoaded] = useState(false);
+
+ useEffect(() => {
+ if (!localizationEnabled) return;
+ SupersetClient.get({
+ endpoint: '/api/v1/localization/available_locales',
+ }).then(
+ response => {
+ const { locales, default_locale } = response.json.result;
+ setAllLocales(locales);
+ setDefaultLocale(default_locale);
+ setLocalesLoaded(true);
+ },
+ err => logging.error('Failed to fetch available locales', err),
+ );
+ }, [localizationEnabled]);
+
+ const translations: Translations = (formData as Record<string, unknown>)
+ ?.translations as Translations ?? {};
+ const fieldTranslations = translations[name] ?? {};
+
+ const translationsRef = useRef(translations);
+ translationsRef.current = translations;
+ const fieldTranslationsRef = useRef(fieldTranslations);
+ fieldTranslationsRef.current = fieldTranslations;
+
+ useEffect(() => {
+ if (!localizationEnabled || !localesLoaded || !userLocale) return;
+ if (fieldTranslationsRef.current[userLocale]) {
+ setActiveLocale(userLocale);
+ } else {
+ setActiveLocale(DEFAULT_LOCALE_KEY);
+ }
+ }, [localizationEnabled, localesLoaded, userLocale]);
+
+ // --- Feature flag off → plain TextControl ---
+ if (!localizationEnabled) {
+ return (
+ <TextControl
+ name={name}
+ label={label}
+ value={value}
+ onChange={onChange}
+ placeholder={placeholder}
+ disabled={disabled}
+ {...rest}
+ />
+ );
+ }
+
+ const isLocaleMode = activeLocale !== DEFAULT_LOCALE_KEY;
+ const defaultValue = String(value ?? '');
+
+ const localeSwitcher =
+ allLocales.length > 0 ? (
+ <LocaleSwitcher
+ fieldName={name}
+ defaultValue={defaultValue}
+ translations={translations}
+ allLocales={allLocales}
+ defaultLocale={defaultLocale}
+ userLocale={userLocale}
+ activeLocale={activeLocale}
+ onLocaleChange={setActiveLocale}
+ fieldLabel={String(label ?? name)}
+ />
+ ) : null;
+
+ if (isLocaleMode) {
+ return (
+ <TranslatableTextControlLocaleMode
+ name={name}
+ label={label}
+ translationValue={fieldTranslations[activeLocale] ?? ''}
+ placeholder={defaultValue}
+ disabled={disabled}
+ suffix={localeSwitcher}
+ activeLocale={activeLocale}
+ translationsRef={translationsRef}
+ fieldTranslationsRef={fieldTranslationsRef}
+ setControlValue={actions?.setControlValue}
+ controlHeaderProps={rest}
+ />
+ );
+ }
+
+ return (
+ <TranslatableTextControlDefaultMode
+ name={name}
+ label={label}
+ value={defaultValue}
+ placeholder={placeholder}
+ disabled={disabled}
+ suffix={localeSwitcher}
+ onChange={onChange}
+ controlHeaderProps={rest}
+ />
+ );
+}
+
+// --- Default locale mode: Input with debounced onChange ---
+function TranslatableTextControlDefaultMode({
+ name,
+ label,
+ value,
+ placeholder,
+ disabled,
+ suffix,
+ onChange,
+ controlHeaderProps,
+}: {
+ name: string;
+ label?: string;
+ value: string;
+ placeholder?: string;
+ disabled?: boolean;
+ suffix: React.ReactNode;
+ onChange?: (value: string, errors: any[]) => void;
+ controlHeaderProps: Record<string, unknown>;
+}) {
+ const [localValue, setLocalValue] = useState(value);
+ const prevValueRef = useRef(value);
+
+ if (prevValueRef.current !== value) {
+ prevValueRef.current = value;
+ }
+ const displayValue =
+ prevValueRef.current !== value ? value : localValue;
+
+ const debouncedOnChange = useMemo(
+ () =>
+ debounce((val: string) => {
+ onChange?.(val, []);
+ }, Constants.FAST_DEBOUNCE),
+ [onChange],
+ );
+
+ const handleChange = useCallback(
+ (e: ChangeEvent<HTMLInputElement>) => {
+ setLocalValue(e.target.value);
+ debouncedOnChange(e.target.value);
+ },
+ [debouncedOnChange],
+ );
+
+ return (
+ <div>
+ <ControlHeader name={name} label={label} {...controlHeaderProps} />
+ <Input
+ type="text"
+ data-test="inline-name"
+ placeholder={placeholder}
+ onChange={handleChange}
+ value={displayValue}
Review Comment:
**Suggestion:** The default-mode text control keeps its own `localValue` state but never updates it when the `value` prop changes; instead it uses a `prevValueRef`/`displayValue` check that always resolves to `localValue`, so external updates (e.g., reset from parent form) are ignored and the input shows stale text. Replace this with a `useEffect` that synchronizes `localValue` whenever `value` changes and bind the input directly to `localValue`. [logic error]
<details>
<summary><b>Severity Level:</b> Major ⚠️</summary>
```mdx
- ⚠️ Default-mode TranslatableTextControl ignores parent updates to value prop.
- ⚠️ Explore form controls can display stale values after programmatic changes.
```
</details>
```suggestion
useEffect(() => {
setLocalValue(value);
}, [value]);
const debouncedOnChange = useMemo(
() =>
debounce((val: string) => {
onChange?.(val, []);
}, Constants.FAST_DEBOUNCE),
[onChange],
);
const handleChange = useCallback(
(e: ChangeEvent<HTMLInputElement>) => {
setLocalValue(e.target.value);
debouncedOnChange(e.target.value);
},
[debouncedOnChange],
);
return (
<div>
<ControlHeader name={name} label={label} {...controlHeaderProps} />
<Input
type="text"
data-test="inline-name"
placeholder={placeholder}
onChange={handleChange}
value={localValue}
```
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. Ensure `FeatureFlag.EnableContentLocalization` is enabled so `TranslatableTextControl`
follows the localization path and reaches `TranslatableTextControlDefaultMode` when
`activeLocale === DEFAULT_LOCALE_KEY` in
`superset-frontend/src/explore/components/controls/TranslatableTextControl/index.tsx`
(around lines 166–177).
2. Render `TranslatableTextControl` with `value="First"` and `formData` such that
`translations[name]` is empty, causing `isLocaleMode` to be false and
`TranslatableTextControlDefaultMode` (lines 180–240) to be used; the inner state
`localValue` is initialized to `"First"` at line 200.
3. Later, update the parent state so that `TranslatableTextControl` is re-rendered with
`value="Second"` while the component instance remains mounted (no unmount/remount), a
normal React pattern for programmatic control resets or external updates of form values.
4. On re-render, in `TranslatableTextControlDefaultMode` (lines 200–207),
`prevValueRef.current` is immediately set to the new `value` before computing
`displayValue`, so `prevValueRef.current !== value` is false and `displayValue` resolves
to the stale `localValue` (`"First"`); the `<Input>` at lines 225–237 continues to show
`"First"` instead of `"Second"`, demonstrating that external updates to the `value` prop
are ignored.
```
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset-frontend/src/explore/components/controls/TranslatableTextControl/index.tsx
**Line:** 201:233
**Comment:**
*Logic Error: The default-mode text control keeps its own `localValue` state but never updates it when the `value` prop changes; instead it uses a `prevValueRef`/`displayValue` check that always resolves to `localValue`, so external updates (e.g., reset from parent form) are ignored and the input shows stale text. Replace this with a `useEffect` that synchronizes `localValue` whenever `value` changes and bind the input directly to `localValue`.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=78f1a478cf2185106b645903e2e15404e0ba931804c684ccd73ea75019c7307f&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=78f1a478cf2185106b645903e2e15404e0ba931804c684ccd73ea75019c7307f&reaction=dislike'>👎</a>
##########
superset-frontend/src/locale/LocaleProvider.tsx:
##########
@@ -0,0 +1,180 @@
+/**
+ * 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 {
+ createContext,
+ useCallback,
+ useContext,
+ useEffect,
+ useMemo,
+ useState,
+} from 'react';
+import { LocaleController } from './LocaleController';
+
+/**
+ * Locale context value provided to consumers.
+ */
+export interface LocaleContextType {
+ /** Current locale code (e.g., 'en', 'ru', 'de') */
+ locale: string;
+ /** Whether a locale change is in progress */
+ isLoading: boolean;
+ /** Whether the locale controller has been initialized */
+ isReady: boolean;
+ /** Change the application locale */
+ setLocale: (locale: string) => Promise<void>;
+ /** Translate a string using the current locale */
+ t: (key: string, ...args: unknown[]) => string;
+ /** Translate a string with pluralization */
+ tn: (key: string, ...args: unknown[]) => string;
+}
+
+const LocaleContext = createContext<LocaleContextType | null>(null);
+
+interface LocaleProviderProps {
+ children: React.ReactNode;
+ controller: LocaleController;
+}
+
+/**
+ * LocaleProvider integrates LocaleController with React.
+ *
+ * This provider follows the same pattern as SupersetThemeProvider:
+ * - Subscribes to controller changes via useEffect
+ * - Triggers re-renders when locale changes
+ * - Provides context for child components
+ *
+ * Usage:
+ * ```tsx
+ * const controller = new LocaleController({ initialLocale: 'en' });
+ *
+ * function App() {
+ * return (
+ * <LocaleProvider controller={controller}>
+ * <MyComponent />
+ * </LocaleProvider>
+ * );
+ * }
+ *
+ * function MyComponent() {
+ * const { locale, setLocale, t } = useLocaleContext();
+ * return <div>{t('Hello')}</div>;
+ * }
+ * ```
+ */
+export function LocaleProvider({
+ children,
+ controller,
+}: LocaleProviderProps): JSX.Element {
+ const [locale, setLocaleState] = useState<string>(controller.getLocale());
+ const [isLoading, setIsLoading] = useState<boolean>(false);
+ const [isReady, setIsReady] = useState<boolean>(controller.isReady());
+
+ // Subscribe to controller changes
+ useEffect(() => {
+ const unsubscribe = controller.onChange(newLocale => {
+ setLocaleState(newLocale);
+ setIsLoading(false);
+ setIsReady(controller.isReady());
+ });
+
+ // Update isReady state periodically until controller is initialized
+ // This handles the case where controller is initializing asynchronously
+ if (!controller.isReady()) {
+ const checkReady = setInterval(() => {
+ if (controller.isReady()) {
+ setIsReady(true);
+ clearInterval(checkReady);
+ }
+ }, 50);
+
+ return () => {
+ unsubscribe();
+ clearInterval(checkReady);
+ };
+ }
+
+ return unsubscribe;
+ }, [controller]);
+
+ const setLocale = useCallback(
+ async (newLocale: string): Promise<void> => {
+ setIsLoading(true);
+ try {
+ await controller.setLocale(newLocale);
+ } catch (error) {
+ setIsLoading(false);
+ throw error;
+ }
Review Comment:
**Suggestion:** The `setLocale` callback sets `isLoading` to true before calling `controller.setLocale` but only resets it in the `catch` path, so if `setLocale` resolves without error and does not trigger an `onChange` (for example when called with the current locale), `isLoading` remains stuck as true and the UI will show an infinite loading state. Move the `setIsLoading(false)` into a `finally` block so it always runs regardless of success, failure, or whether callbacks fire. [logic error]
<details>
<summary><b>Severity Level:</b> Major ⚠️</summary>
```mdx
- ⚠️ LocaleSwitcher UI may show perpetual loading indicator.
- ⚠️ Components gating render on isLoading may never settle.
- ⚠️ Embedded localization flows can misreport request completion state.
```
</details>
```suggestion
} finally {
setIsLoading(false);
```
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. Render `LocaleProvider` from `superset-frontend/src/locale/LocaleProvider.tsx:82-155`
with a real `LocaleController` instance imported from `./LocaleController`.
2. Inside any child component wrapped by `LocaleProvider`, obtain `setLocale` from
`useLocaleContext()` defined at `LocaleProvider.tsx:163-170` and call
`setLocale(currentLocale)` where `currentLocale` equals `controller.getLocale()`.
3. The `setLocale` implementation at `LocaleProvider.tsx:117-128` sets `isLoading` to
`true` and awaits `controller.setLocale(newLocale)`; since this is a no-op locale change,
`LocaleController` typically short-circuits and does not fire the `onChange` callback
registered in the `useEffect` subscription at `LocaleProvider.tsx:90-95`.
4. Because the `catch` block at `LocaleProvider.tsx:121-124` is not entered (no error
thrown) and the `onChange` subscription is not invoked, there is no code path that calls
`setIsLoading(false)`, leaving `isLoading` stuck `true` for any consumers relying on that
flag.
```
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset-frontend/src/locale/LocaleProvider.tsx
**Line:** 122:124
**Comment:**
*Logic Error: The `setLocale` callback sets `isLoading` to true before calling `controller.setLocale` but only resets it in the `catch` path, so if `setLocale` resolves without error and does not trigger an `onChange` (for example when called with the current locale), `isLoading` remains stuck as true and the UI will show an infinite loading state. Move the `setIsLoading(false)` into a `finally` block so it always runs regardless of success, failure, or whether callbacks fire.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=c55b51e5c96f37aafd253f9c7dbf33e77ee7f0d585416908fa9577c18776ec60&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=c55b51e5c96f37aafd253f9c7dbf33e77ee7f0d585416908fa9577c18776ec60&reaction=dislike'>👎</a>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #37790:
URL: https://github.com/apache/superset/pull/37790#issuecomment-3927570958
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers a full AI review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #37790:
URL: https://github.com/apache/superset/pull/37790#discussion_r2779126405
##########
superset-frontend/src/dashboard/components/PropertiesModal/index.tsx:
##########
@@ -672,6 +747,34 @@ const PropertiesModal = ({
<BasicInfoSection
form={form}
validationStatus={validationStatus}
+ activeLocale={
+ isFeatureEnabled(FeatureFlag.EnableContentLocalization)
+ ? titleActiveLocale
+ : undefined
+ }
+ translationValue={
+ titleActiveLocale !== DEFAULT_LOCALE_KEY
+ ? translations.dashboard_title?.[titleActiveLocale] ?? ''
+ : undefined
+ }
+ onTranslationChange={handleTitleTranslationChange}
+ localeSwitcher={
+ isFeatureEnabled(
+ FeatureFlag.EnableContentLocalization,
+ ) ? (
+ <LocaleSwitcher
+ fieldName="dashboard_title"
+ defaultValue={dashboardInfo?.title ?? ''}
Review Comment:
**Suggestion:** The locale switcher is given `defaultValue={dashboardInfo?.title ?? ''}`, which becomes stale if the user edits the dashboard title in the form before opening the translation editor; this causes the translation UI to show an outdated "default" text. It should instead use the current form field value (falling back to the loaded title) so the translation editor always reflects the latest default title. [logic error]
<details>
<summary><b>Severity Level:</b> Major ⚠️</summary>
```mdx
- ⚠️ Dashboard title translation editor shows outdated default string.
- ⚠️ Translators may create translations for obsolete dashboard names.
- ⚠️ Minor UX inconsistency in dashboard properties modal.
```
</details>
```suggestion
defaultValue={
form.getFieldValue('title') ?? dashboardInfo?.title ?? ''
}
```
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. Ensure the `EnableContentLocalization` feature flag is enabled so the locale switcher
is rendered in `PropertiesModal`
(superset-frontend/src/dashboard/components/PropertiesModal/index.tsx:747-777).
2. Open any dashboard and launch the Dashboard Properties modal, which renders
`PropertiesModal` with `show=true` and initial `dashboardInfo.title` loaded via
`handleDashboardData` (same file: lines ~184-212, 225-229, 552-585).
3. In the "General information" section rendered by `BasicInfoSection` (lines 747-778),
edit the dashboard name field bound to the Ant Design `Form` instance (`form` created at
lines 108-112); this updates the form's `'title'` field but does not update
`dashboardInfo.title`, which is only set in `handleDashboardData`.
4. While the modal is still open and unsaved, open the translation UI for the dashboard
title via the embedded `<LocaleSwitcher>` passed through the `localeSwitcher` prop (lines
761-777).
5. Observe that `LocaleSwitcher` receives `defaultValue={dashboardInfo?.title ?? ''}`
(line 767), which still contains the original title from load time rather than the updated
`form` value, so any "default text" shown in the translation editor is stale compared to
the visible title field.
```
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset-frontend/src/dashboard/components/PropertiesModal/index.tsx
**Line:** 767:767
**Comment:**
*Logic Error: The locale switcher is given `defaultValue={dashboardInfo?.title ?? ''}`, which becomes stale if the user edits the dashboard title in the form before opening the translation editor; this causes the translation UI to show an outdated "default" text. It should instead use the current form field value (falling back to the loaded title) so the translation editor always reflects the latest default title.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=46ca29f41fa05f0b33003d8a67fde862dd9cf90aec1b9babbe79b724a1dd8b22&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=46ca29f41fa05f0b33003d8a67fde862dd9cf90aec1b9babbe79b724a1dd8b22&reaction=dislike'>👎</a>
##########
superset-frontend/src/dashboard/components/PropertiesModal/sections/BasicInfoSection.tsx:
##########
@@ -58,8 +82,21 @@ const BasicInfoSection = ({
placeholder={t('The display name of your dashboard')}
data-test="dashboard-title-input"
type="text"
+ suffix={!isEditingTranslation ? localeSwitcher : undefined}
/>
</FormItem>
+ {isEditingTranslation && (
+ <Input
+ value={translationValue}
Review Comment:
**Suggestion:** The translation input is controlled via the optional `translationValue` prop, and passing `undefined` as the `value` can cause React to treat the field as uncontrolled initially and then controlled after updates, resulting in warnings and potentially inconsistent input behavior; defaulting to an empty string avoids this. [possible bug]
<details>
<summary><b>Severity Level:</b> Major ⚠️</summary>
```mdx
- WARNING React logs uncontrolled-to-controlled warning during translation editing.
- WARNING Dev console noise affects debugging dashboard localization flows.
```
</details>
```suggestion
value={translationValue ?? ''}
```
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. A parent component renders `BasicInfoSection` from
`superset-frontend/src/dashboard/components/PropertiesModal/sections/BasicInfoSection.tsx`
with `activeLocale` set to a non-default locale (so `isEditingTranslation` at lines 52–53
evaluates to `true`) and omits an initial translation value, leaving `translationValue` as
`undefined`.
2. Because `isEditingTranslation === true`, the translation `<Input>` at lines 88–98 is
rendered with `value={translationValue}` at line 90. With `translationValue` undefined,
React treats this as an uncontrolled input on initial render.
3. When the user types into the translation field, the `onChange` handler at lines 91–93
calls `onTranslationChange?.(e.target.value)`, and the parent updates its state to a
non-empty string, passing a defined `translationValue` back into `BasicInfoSection` on the
next render.
4. On this subsequent render, the same `<Input>` now has a defined `value` prop, so React
switches the field from uncontrolled to controlled and logs a console warning about
changing an uncontrolled input to controlled during dashboard title localization flows.
```
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset-frontend/src/dashboard/components/PropertiesModal/sections/BasicInfoSection.tsx
**Line:** 90:90
**Comment:**
*Possible Bug: The translation input is controlled via the optional `translationValue` prop, and passing `undefined` as the `value` can cause React to treat the field as uncontrolled initially and then controlled after updates, resulting in warnings and potentially inconsistent input behavior; defaulting to an empty string avoids this.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=1a7dedc7ded328ba487acec8a4425ddbfc18353131629ac4bb6a2d341416da9d&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=1a7dedc7ded328ba487acec8a4425ddbfc18353131629ac4bb6a2d341416da9d&reaction=dislike'>👎</a>
##########
superset-frontend/src/explore/components/PropertiesModal/PropertiesModal.test.tsx:
##########
@@ -471,3 +493,74 @@ test('Should display only custom tags when tagging system is enabled', async ()
mockIsFeatureEnabled.mockRestore();
});
+
+test('locale switcher hidden when content localization flag is off', async () => {
+ const props = createProps();
+ renderModal(props);
+ await waitFor(() => {
+ expect(screen.getByRole('dialog')).toBeInTheDocument();
+ });
+ expect(
+ screen.queryByRole('button', { name: /Locale switcher for/i }),
+ ).not.toBeInTheDocument();
+});
+
+test('locale switcher visible when content localization flag is on', async () => {
+ mockedIsFeatureEnabled.mockImplementation(
+ flag => flag === FeatureFlag.EnableContentLocalization,
+ );
+ const props = createProps();
+ renderModal(props);
+ await waitFor(() => {
+ expect(
+ screen.getByRole('button', {
+ name: /Locale switcher for Chart Name/i,
+ }),
+ ).toBeInTheDocument();
+ });
+ mockedIsFeatureEnabled.mockRestore();
Review Comment:
**Suggestion:** `mockedIsFeatureEnabled` is defined as a plain `jest.fn()` via `jest.mock`, so calling `mockRestore()` on it will throw at runtime because `mockRestore` only exists on spies created with `jest.spyOn`; use `mockReset()` to clear the implementation between tests instead. [logic error]
<details>
<summary><b>Severity Level:</b> Major ⚠️</summary>
```mdx
- ❌ Locale switcher visibility test fails with Jest runtime error.
- ⚠️ Frontend test suite may fail, blocking PR verification.
```
</details>
```suggestion
mockedIsFeatureEnabled.mockReset();
```
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. Run the frontend Jest tests, including
`superset-frontend/src/explore/components/PropertiesModal/PropertiesModal.test.tsx`.
2. In this file, `isFeatureEnabled` from `@superset-ui/core` is mocked at the top with
`jest.fn()` via `jest.mock('@superset-ui/core', ...)` (lines 30–33 in the PR hunk), and
`mockedIsFeatureEnabled` is just a typed alias of this mock (lines 35–37).
3. The test `locale switcher visible when content localization flag is on` (introduced
around line 508 in the PR hunk) calls `mockedIsFeatureEnabled.mockImplementation(...)`
and, at the end of the test, executes `mockedIsFeatureEnabled.mockRestore();` at line 521.
4. At runtime, Jest mock functions created with `jest.fn()` do not support `mockRestore`
(that method only works for spies created via `jest.spyOn`), so calling
`mockedIsFeatureEnabled.mockRestore()` throws an error (e.g. "mockRestore is not a
function"), causing this test – and the entire `PropertiesModal.test.tsx` suite – to fail
before completing. Note: there is a pre‑existing identical misuse in the "tagging system"
test earlier in the same file, so fixing only this line is necessary but not sufficient to
make the suite pass.
```
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset-frontend/src/explore/components/PropertiesModal/PropertiesModal.test.tsx
**Line:** 521:521
**Comment:**
*Logic Error: `mockedIsFeatureEnabled` is defined as a plain `jest.fn()` via `jest.mock`, so calling `mockRestore()` on it will throw at runtime because `mockRestore` only exists on spies created with `jest.spyOn`; use `mockReset()` to clear the implementation between tests instead.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=d783300d11c9c2f152e5df4cb42aa55dc4fcc64959cf647db5f3246985513e50&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=d783300d11c9c2f152e5df4cb42aa55dc4fcc64959cf647db5f3246985513e50&reaction=dislike'>👎</a>
##########
superset-frontend/src/dashboard/components/PropertiesModal/sections/BasicInfoSection.tsx:
##########
@@ -58,8 +82,21 @@ const BasicInfoSection = ({
placeholder={t('The display name of your dashboard')}
data-test="dashboard-title-input"
type="text"
+ suffix={!isEditingTranslation ? localeSwitcher : undefined}
/>
</FormItem>
+ {isEditingTranslation && (
+ <Input
+ value={translationValue}
+ onChange={(e: ChangeEvent<HTMLInputElement>) =>
+ onTranslationChange?.(e.target.value)
+ }
+ placeholder={t('Translation for %s', activeLocale.toUpperCase())}
+ data-test="dashboard-title-input"
Review Comment:
**Suggestion:** Both the default title input and the translation input share the same `data-test` attribute, which can cause automated tests to interact with the wrong field when both exist in the DOM (e.g., in some testing setups), making tests flaky and assertions ambiguous; giving the translation input a distinct test id avoids this collision. [possible bug]
<details>
<summary><b>Severity Level:</b> Major ⚠️</summary>
```mdx
- WARNING Automated tests may target hidden dashboard title input.
- WARNING Locale switching E2E tests can become flaky or ambiguous.
```
</details>
```suggestion
data-test="dashboard-title-translation-input"
```
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. Enable the content localization feature flag so the `localeSwitcher` suffix is passed
to `BasicInfoSection` (file
`superset-frontend/src/dashboard/components/PropertiesModal/sections/BasicInfoSection.tsx`)
and a non-default `activeLocale` is used, making `isEditingTranslation` at lines 52–53
evaluate to `true`.
2. In this state, the default title `<Input>` inside the `<FormItem name="title">` at
lines 69–86 remains mounted but hidden, with `data-test="dashboard-title-input"` at line
83, while the translation `<Input>` at lines 88–98 is also rendered with the same
`data-test="dashboard-title-input"` at line 95.
3. A Playwright or Cypress test for the dashboard properties modal that selects
`[data-test="dashboard-title-input"]` during a non-default locale scenario (as described
in the PR's E2E test plan) may resolve the hidden default input instead of the visible
translation input.
4. As a result, automated tests attempting to type or assert against the dashboard title
in a translated locale can become flaky or interact with the wrong input element whenever
both inputs exist in the DOM with the same test identifier.
```
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset-frontend/src/dashboard/components/PropertiesModal/sections/BasicInfoSection.tsx
**Line:** 95:95
**Comment:**
*Possible Bug: Both the default title input and the translation input share the same `data-test` attribute, which can cause automated tests to interact with the wrong field when both exist in the DOM (e.g., in some testing setups), making tests flaky and assertions ambiguous; giving the translation input a distinct test id avoids this collision.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=967548fe6233f0f6835a70624581c553cde7f9ab67fc475ec212a8ae8ef9ffff&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=967548fe6233f0f6835a70624581c553cde7f9ab67fc475ec212a8ae8ef9ffff&reaction=dislike'>👎</a>
##########
superset-frontend/src/components/TranslationEditor/LocaleSwitcher.tsx:
##########
@@ -0,0 +1,216 @@
+/**
+ * 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 { useMemo } from 'react';
+import type { MenuProps } from 'antd';
+import { t } from '@apache-superset/core';
+import { css, useTheme } from '@apache-superset/core/ui';
+import {
+ Badge,
+ Dropdown,
+ Icons,
+} from '@superset-ui/core/components';
+import type { Translations, LocaleInfo } from 'src/types/Localization';
+import { DEFAULT_LOCALE_KEY, countFieldTranslations } from './utils';
+
+export interface LocaleSwitcherProps {
+ /** Translation field key (e.g., 'dashboard_title', 'slice_name'). */
+ fieldName: string;
+ /** Current default (column) value — used for ✓ indicator on DEFAULT. */
+ defaultValue: string;
+ /** Full translations object for the entity. */
+ translations: Translations;
+ /** All configured locales from server (including default locale). */
+ allLocales: LocaleInfo[];
+ /** Server's default locale code (e.g., 'en'). */
+ defaultLocale: string;
+ /** Current user's UI locale code from session. */
+ userLocale: string;
+ /** Currently active locale. Controlled by parent. */
+ activeLocale: string;
+ /** Called when user picks a locale from the dropdown. */
+ onLocaleChange: (locale: string) => void;
+ /** Human-readable field label for accessibility (e.g., 'Dashboard Title'). */
+ fieldLabel: string;
+}
+
+/**
+ * Inline locale dropdown rendered as an Input suffix.
+ *
+ * Displays the currently active locale (DEFAULT or a specific language)
+ * with a badge showing translation count. Click opens a dropdown to
+ * switch between DEFAULT text and per-locale translations.
+ *
+ * Yellow highlight indicates the user's locale has no translation.
+ */
+export default function LocaleSwitcher({
+ fieldName,
+ defaultValue,
+ translations,
+ allLocales,
+ defaultLocale,
+ userLocale,
+ activeLocale,
+ onLocaleChange,
+ fieldLabel,
+}: LocaleSwitcherProps) {
+ const theme = useTheme();
+
+ const fieldTranslations = translations[fieldName] ?? {};
+ const translationCount = countFieldTranslations(translations, fieldName);
+
+ const userLocaleHasTranslation =
+ userLocale === defaultLocale || Boolean(fieldTranslations[userLocale]);
+ const isWarning = !userLocaleHasTranslation;
+
+ const localeMap = useMemo(
+ () => new Map(allLocales.map(loc => [loc.code, loc])),
+ [allLocales],
+ );
+
+ const sortedLocales = useMemo(
+ () => [...allLocales].sort((a, b) => a.code.localeCompare(b.code)),
+ [allLocales],
+ );
+
+ const isDefault = activeLocale === DEFAULT_LOCALE_KEY;
+ const activeLocaleInfo = isDefault ? undefined : localeMap.get(activeLocale);
+ const triggerFlag = activeLocaleInfo?.flag;
+
+ const menuItems: MenuProps['items'] = useMemo(() => {
+ const checkIcon = (
+ <Icons.CheckOutlined
+ iconSize="s"
+ css={css`
+ font-size: 12px;
+ `}
+ />
+ );
+ const noIcon = (
+ <span
+ css={css`
+ display: inline-block;
+ width: 14px;
+ `}
+ />
+ );
+
+ return [
+ {
+ key: DEFAULT_LOCALE_KEY,
+ icon: defaultValue ? checkIcon : noIcon,
+ label: (
+ <span
+ css={css`
+ font-weight: ${activeLocale === DEFAULT_LOCALE_KEY ? 600 : 400};
+ `}
+ >
+ {t('DEFAULT')}
+ </span>
+ ),
+ },
+ { type: 'divider' as const },
+ ...sortedLocales.map(locale => ({
+ key: locale.code,
+ icon: fieldTranslations[locale.code] ? checkIcon : noIcon,
+ label: (
+ <span
+ css={css`
+ font-weight: ${activeLocale === locale.code ? 600 : 400};
+ `}
+ >
+ {locale.flag ? `${locale.flag} ` : ''}
+ {locale.name}
+ </span>
+ ),
+ })),
+ ];
+ }, [
+ sortedLocales,
+ fieldTranslations,
+ defaultValue,
+ activeLocale,
+ ]);
+
+ const handleMenuClick: MenuProps['onClick'] = ({ key }) => {
+ onLocaleChange(key);
+ };
+
+ const suffixColor = isWarning ? theme.colorWarning : theme.colorText;
+
+ return (
+ <Dropdown
+ menu={{ items: menuItems, onClick: handleMenuClick }}
+ trigger={['click']}
+ getPopupContainer={() => document.body}
+ >
+ <span
+ role="button"
+ tabIndex={0}
+ aria-label={t(
+ 'Locale switcher for %s: %s (%s translations)',
+ fieldLabel,
+ isDefault ? t('DEFAULT') : activeLocale,
+ translationCount,
+ )}
+ onClick={e => e.stopPropagation()}
+ onKeyDown={e => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.stopPropagation();
+ e.preventDefault();
+ }
Review Comment:
**Suggestion:** The suffix element is focusable and has `role="button"`, but its keydown handler for Enter/Space only stops propagation and prevents default without triggering the dropdown, making it impossible to open the locale menu via keyboard; programmatically invoking a click in this handler restores keyboard accessibility. [logic error]
<details>
<summary><b>Severity Level:</b> Major ⚠️</summary>
```mdx
- ❌ Keyboard users cannot open locale switcher dropdown control.
- ⚠️ Affects translation editing for dashboards, charts, and filters.
```
</details>
```suggestion
(e.currentTarget as HTMLElement).click();
```
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. Render the `LocaleSwitcher` component from
`superset-frontend/src/components/TranslationEditor/LocaleSwitcher.tsx` as used in the
translation editor, and focus the suffix `<span>` that has `role="button"` and
`tabIndex={0}` at lines 161-187 by tabbing to it.
2. Confirm the surrounding `Dropdown` from `@superset-ui/core/components` is configured
with `trigger={['click']}` at lines 157-160, meaning it opens only on click events.
3. While the suffix `<span>` is focused, press the Enter key (or Space); the `onKeyDown`
handler at lines 172-176 intercepts the event, calling `e.stopPropagation()` and
`e.preventDefault()` without performing any additional action.
4. Because the default browser action for Enter/Space (synthesizing a click on the focused
button-like element) is prevented, no click event is emitted, so the `Dropdown` never
opens from keyboard interaction, while it still opens correctly when the user clicks with
a mouse.
```
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset-frontend/src/components/TranslationEditor/LocaleSwitcher.tsx
**Line:** 176:176
**Comment:**
*Logic Error: The suffix element is focusable and has `role="button"`, but its keydown handler for Enter/Space only stops propagation and prevents default without triggering the dropdown, making it impossible to open the locale menu via keyboard; programmatically invoking a click in this handler restores keyboard accessibility.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=56e452b35212f0ab06b8d1ce186c1dc11d6d83d7f9dad1ffccdff8b4a35f2c65&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=56e452b35212f0ab06b8d1ce186c1dc11d6d83d7f9dad1ffccdff8b4a35f2c65&reaction=dislike'>👎</a>
##########
superset-frontend/src/explore/components/PropertiesModal/PropertiesModal.test.tsx:
##########
@@ -471,3 +493,74 @@ test('Should display only custom tags when tagging system is enabled', async ()
mockIsFeatureEnabled.mockRestore();
});
+
+test('locale switcher hidden when content localization flag is off', async () => {
+ const props = createProps();
+ renderModal(props);
+ await waitFor(() => {
+ expect(screen.getByRole('dialog')).toBeInTheDocument();
+ });
+ expect(
+ screen.queryByRole('button', { name: /Locale switcher for/i }),
+ ).not.toBeInTheDocument();
+});
+
+test('locale switcher visible when content localization flag is on', async () => {
+ mockedIsFeatureEnabled.mockImplementation(
+ flag => flag === FeatureFlag.EnableContentLocalization,
+ );
+ const props = createProps();
+ renderModal(props);
+ await waitFor(() => {
+ expect(
+ screen.getByRole('button', {
+ name: /Locale switcher for Chart Name/i,
+ }),
+ ).toBeInTheDocument();
+ });
+ mockedIsFeatureEnabled.mockRestore();
+});
+
+test('clicking locale switcher opens dropdown with locales', async () => {
+ mockedIsFeatureEnabled.mockImplementation(
+ flag => flag === FeatureFlag.EnableContentLocalization,
+ );
+ const props = createProps();
+ renderModal(props);
+ await waitFor(() => {
+ expect(
+ screen.getByRole('button', { name: /Locale switcher for Chart Name/i }),
+ ).toBeInTheDocument();
+ });
+ await userEvent.click(
+ screen.getByRole('button', { name: /Locale switcher for Chart Name/i }),
+ );
+ await waitFor(() => {
+ expect(screen.getByText('English')).toBeInTheDocument();
+ expect(screen.getByText('German')).toBeInTheDocument();
+ });
+ mockedIsFeatureEnabled.mockRestore();
Review Comment:
**Suggestion:** The second use of `mockedIsFeatureEnabled.mockRestore()` has the same issue: it targets a `jest.fn()` mock, not a spy, and will cause a runtime error; replace it with `mockReset()` to correctly clear the mock state. [logic error]
<details>
<summary><b>Severity Level:</b> Major ⚠️</summary>
```mdx
- ❌ Locale switcher dropdown test crashes due to invalid mockRestore.
- ⚠️ Aggregated test failures hinder validating localization UI behavior.
```
</details>
```suggestion
mockedIsFeatureEnabled.mockReset();
```
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. Run Jest on
`superset-frontend/src/explore/components/PropertiesModal/PropertiesModal.test.tsx`.
2. At the top of the file, `isFeatureEnabled` is mocked with `jest.fn()` via
`jest.mock('@superset-ui/core', ...)`, and `mockedIsFeatureEnabled` is a typed alias of
that mock (lines 30–37 in the PR hunk).
3. In the test `clicking locale switcher opens dropdown with locales` (introduced around
line 524), the code sets `mockedIsFeatureEnabled.mockImplementation(...)` and later calls
`mockedIsFeatureEnabled.mockRestore();` at line 542.
4. Because `mockedIsFeatureEnabled` is a plain `jest.fn()` mock and not a spy created with
`jest.spyOn`, invoking `.mockRestore()` at line 542 triggers Jest's runtime error for
non‑spy mocks, causing this test case to error out; combined with the other `mockRestore`
usages in this file, this keeps the entire test suite from completing successfully.
```
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset-frontend/src/explore/components/PropertiesModal/PropertiesModal.test.tsx
**Line:** 542:542
**Comment:**
*Logic Error: The second use of `mockedIsFeatureEnabled.mockRestore()` has the same issue: it targets a `jest.fn()` mock, not a spy, and will cause a runtime error; replace it with `mockReset()` to correctly clear the mock state.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=a97d33637e378beeddbd13e79bcbbe9d246d13f3684999caccc0c8d297c046f9&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=a97d33637e378beeddbd13e79bcbbe9d246d13f3684999caccc0c8d297c046f9&reaction=dislike'>👎</a>
##########
superset/localization/locale_utils.py:
##########
@@ -0,0 +1,150 @@
+# 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.
+"""
+Locale detection utilities for content localization.
+
+Provides functions to detect and resolve user's preferred locale
+for displaying localized content (dashboard titles, chart names, etc.).
+
+Locale detection priority:
+1. Explicit locale parameter (API override)
+2. Flask session locale (user preference)
+3. Accept-Language HTTP header (browser preference)
+4. Default locale from BABEL_DEFAULT_LOCALE config
+"""
+
+from flask import current_app, has_request_context, request, session
+
+DEFAULT_LOCALE = "en"
+
+
+def parse_accept_language(header: str) -> list[str]:
+ """
+ Parse Accept-Language HTTP header into sorted locale list.
+
+ Parses RFC 7231 Accept-Language header format and returns locales
+ sorted by quality value (q) in descending order.
+
+ Args:
+ header: Accept-Language header value (e.g., "de-DE, de;q=0.9, en;q=0.8")
+
+ Returns:
+ List of locale codes sorted by quality descending.
+ Empty list if header is empty.
+
+ Examples:
+ >>> parse_accept_language("de-DE, de;q=0.9, en;q=0.8")
+ ["de-DE", "de", "en"]
+ >>> parse_accept_language("fr;q=0.7, de;q=0.9")
+ ["de", "fr"]
+ """
+ if not header or not header.strip():
+ return []
+
+ locales_with_quality: list[tuple[str, float]] = []
+
+ for part in header.split(","):
+ part = part.strip()
+ if not part:
+ continue
+
+ # Parse locale and quality
+ if ";" in part:
+ locale_part, quality_part = part.split(";", 1)
+ locale = locale_part.strip()
+ quality = _parse_quality(quality_part)
+ else:
+ locale = part.strip()
+ quality = 1.0 # Default quality per RFC 7231
+
+ # Skip wildcard
+ if locale == "*":
+ continue
+
+ locales_with_quality.append((locale, quality))
+
+ # Sort by quality descending, preserve order for equal quality
+ locales_with_quality.sort(key=lambda x: x[1], reverse=True)
+
+ return [locale for locale, _ in locales_with_quality]
+
+
+def _parse_quality(quality_part: str) -> float:
+ """
+ Parse quality value from Accept-Language quality parameter.
+
+ Args:
+ quality_part: Quality parameter (e.g., "q=0.9")
+
+ Returns:
+ Quality value as float. Returns 0.0 for invalid values.
+ """
+ quality_part = quality_part.strip()
+ if not quality_part.startswith("q="):
+ return 0.0
+
+ try:
+ return float(quality_part[2:])
+ except ValueError:
+ return 0.0
+
+
+def get_user_locale(locale: str | None = None, validate: bool = False) -> str:
+ """
+ Get user's locale for content localization.
+
+ Resolves locale using priority chain:
+ 1. Explicit locale parameter (if provided)
+ 2. Flask session["locale"] (user preference)
+ 3. Accept-Language header best match
+ 4. BABEL_DEFAULT_LOCALE config value
+
+ Args:
+ locale: Explicit locale override. If provided, takes priority.
+ validate: If True, validates locale against LANGUAGES config.
+ Invalid locales fall back to default.
+
+ Returns:
+ Locale code string (e.g., "de", "fr-FR", "en").
+ """
+ resolved_locale: str | None = None
+
+ # Priority 1: Explicit parameter
+ if locale:
+ resolved_locale = locale
+
+ # Priority 2: Session locale
+ if not resolved_locale:
Review Comment:
**Suggestion:** Accessing the Flask `session` object without first checking for a request context will raise a runtime "working outside of request context" error if `get_user_locale` is called from CLI tasks, background jobs, or any code path without an active request. [possible bug]
<details>
<summary><b>Severity Level:</b> Critical 🚨</summary>
```mdx
- ❌ CLI/background uses of get_user_locale crash with RuntimeError.
- ⚠️ Jinja macro current_user_locale() unsafe in scheduled queries.
```
</details>
```suggestion
# Priority 2: Session locale (only if in request context)
if not resolved_locale and has_request_context():
```
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. In a Python shell, create a Superset Flask app context only (no request context):
`from superset.app import create_app; app = create_app(); app.app_context().push()`.
2. Import and call `get_user_locale()` from `superset/localization/locale_utils.py:106`
within this app context:
`from superset.localization.locale_utils import get_user_locale; get_user_locale()`.
3. Inside `get_user_locale` at `superset/localization/locale_utils.py:130-132`, the code
executes:
`resolved_locale = session.get("locale")` without checking `has_request_context()`.
4. Because there is no active request context, accessing `session` raises `RuntimeError:
Working outside of request context`, causing any CLI task, background job, or Jinja macro
using `get_user_locale` in non-request contexts to crash.
```
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset/localization/locale_utils.py
**Line:** 130:131
**Comment:**
*Possible Bug: Accessing the Flask `session` object without first checking for a request context will raise a runtime "working outside of request context" error if `get_user_locale` is called from CLI tasks, background jobs, or any code path without an active request.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=5a58b5ef51eac819fdfc9418c59a2f99d0b2354fb90f59d4c6f88779743c8fc9&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=5a58b5ef51eac819fdfc9418c59a2f99d0b2354fb90f59d4c6f88779743c8fc9&reaction=dislike'>👎</a>
##########
superset-frontend/src/dashboard/components/nativeFilters/FiltersConfigModal/FiltersConfigModal.test.tsx:
##########
@@ -157,6 +164,26 @@ function setupFetchMocks() {
});
}
+fetchMock.get('glob:*/api/v1/localization/available_locales', {
+ body: {
+ result: {
+ locales: [
+ { code: 'en', name: 'English' },
+ { code: 'de', name: 'German' },
+ { code: 'fr', name: 'French' },
+ ],
+ default_locale: 'en',
+ },
+ },
+});
+
+const filterTranslations = {
+ name: {
+ de: 'Bundesland',
+ fr: 'État',
+ },
+};
+
const FILTER_TYPE_REGEX = /^filter type$/i;
const FILTER_NAME_REGEX = /^filter name$/i;
Review Comment:
**Suggestion:** The mock for the localization `available_locales` endpoint is registered once at module load but `fetchMock.removeRoutes()` in `afterEach` clears all routes, and `setupFetchMocks()` (called in every `beforeEach`) does not re-register this endpoint, so only the first test has the route mocked while subsequent tests that trigger the localization fetch will hit an unmocked URL and fail or behave inconsistently. [logic error]
<details>
<summary><b>Severity Level:</b> Major ⚠️</summary>
```mdx
- ❌ Localization-related native filter tests depend on this mock.
- ❌ CI test runs may intermittently fail on localization tests.
- ⚠️ Makes content localization feature tests unreliable and flaky.
- ⚠️ Increases debugging time for frontend test failures.
```
</details>
```suggestion
fetchMock.get('glob:*/api/v1/localization/available_locales', {
body: {
result: {
locales: [
{ code: 'en', name: 'English' },
{ code: 'de', name: 'German' },
{ code: 'fr', name: 'French' },
],
default_locale: 'en',
},
},
});
}
```
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. Open
`superset-frontend/src/dashboard/components/nativeFilters/FiltersConfigModal/FiltersConfigModal.test.tsx`
and note:
- `setupFetchMocks()` definition at ~lines 120–160.
- The standalone `fetchMock.get('glob:*/api/v1/localization/available_locales', ...)`
immediately after `setupFetchMocks()` (around lines 167–178).
- The Jest hooks: `beforeEach(() => { setupFetchMocks(); });` and `afterEach(() => {
...; fetchMock.removeRoutes(); });` near the top of the test file.
2. Observe that `afterEach` calls `fetchMock.removeRoutes()` (same file, afterEach block
around lines 90–110), which clears *all* registered fetch-mock routes after every test,
including the `available_locales` route registered once at module load.
3. Observe the localization tests in the same file:
- `test('locale switcher visible when content localization flag is on', async () => {
... })`
- `test('clicking locale switcher opens dropdown with locales', async () => { ... })`
- Each of these sets `mockedIsFeatureEnabled.mockImplementation(flag => flag ===
FeatureFlag.EnableContentLocalization)` so `FeatureFlag.EnableContentLocalization` is
true during render, causing the FiltersConfigModal / LocaleSwitcher code to request
`*/api/v1/localization/available_locales` (the test expectations for labels `'English'`
and `'German'` match the mocked response body).
4. Run Jest for this file (e.g. `npm test -- FiltersConfigModal.test.tsx`):
- The early tests (e.g. `'renders a value filter type'`) run first, `afterEach`
executes and `fetchMock.removeRoutes()` clears the globally-registered
`available_locales` mock before any localization test uses it.
- For the first localization-enabled test (e.g. `'locale switcher visible when content
localization flag is on'`), `beforeEach` re-runs `setupFetchMocks()`, but **does not**
re-register `available_locales`.
- When the component under test fetches `*/api/v1/localization/available_locales`,
there is no matching fetch-mock route, so the request is unmatched and will either fall
through to real `fetch` (failing in test environment) or be treated as an error by
fetch-mock, making these tests fail or flaky.
```
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset-frontend/src/dashboard/components/nativeFilters/FiltersConfigModal/FiltersConfigModal.test.tsx
**Line:** 188:188
**Comment:**
*Logic Error: The mock for the localization `available_locales` endpoint is registered once at module load but `fetchMock.removeRoutes()` in `afterEach` clears all routes, and `setupFetchMocks()` (called in every `beforeEach`) does not re-register this endpoint, so only the first test has the route mocked while subsequent tests that trigger the localization fetch will hit an unmocked URL and fail or behave inconsistently.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=611621b133c4e123e1839bd48276afc03a9aaddd7ded6af08b4a6c1784b058c4&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=611621b133c4e123e1839bd48276afc03a9aaddd7ded6af08b4a6c1784b058c4&reaction=dislike'>👎</a>
##########
superset/localization/api.py:
##########
@@ -0,0 +1,108 @@
+# 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.
+"""REST API for content localization configuration."""
+
+import logging
+
+from flask import current_app, Response
+from flask_appbuilder.api import expose, protect, safe
+
+from superset.constants import MODEL_API_RW_METHOD_PERMISSION_MAP
+from superset.extensions import event_logger
+from superset.localization.schemas import AvailableLocalesResponseSchema
+from superset.views.base_api import BaseSupersetApi, statsd_metrics
+
+logger = logging.getLogger(__name__)
+
+DEFAULT_LOCALE = "en"
+
+
+def get_available_locales_data() -> dict[str, list[dict[str, str]] | str]:
+ """
+ Build available locales response data from Flask config.
+
+ Reads LANGUAGES and BABEL_DEFAULT_LOCALE from current_app.config
+ and transforms to response format.
+
+ Returns:
+ Dict with 'locales' list and 'default_locale' string.
+ """
+ languages: dict[str, dict[str, str]] = current_app.config.get("LANGUAGES", {})
+ default_locale = current_app.config.get("BABEL_DEFAULT_LOCALE", DEFAULT_LOCALE)
+
+ # Transform dict to sorted list
+ locales = [
+ {"code": code, "name": meta["name"], "flag": meta["flag"]}
+ for code, meta in sorted(languages.items())
Review Comment:
**Suggestion:** The code assumes every entry in the LANGUAGES config is a dict with "name" and "flag" keys, so a misconfigured or partially specified LANGUAGES (missing those keys or using non-dict values) will raise a KeyError or TypeError and cause the /available_locales endpoint to 500 instead of failing gracefully; using dict.get with sensible defaults and guarding against non-dict entries avoids this runtime failure. [possible bug]
<details>
<summary><b>Severity Level:</b> Major ⚠️</summary>
```mdx
- ❌ GET /api/v1/localization/available_locales can return HTTP 500.
- ⚠️ Translation editor UI cannot load available locales list.
- ⚠️ Failure triggered only by malformed LANGUAGES configuration.
```
</details>
```suggestion
{
"code": code,
"name": meta.get("name", code) if isinstance(meta, dict) else code,
"flag": meta.get("flag", "") if isinstance(meta, dict) else "",
}
for code, meta in sorted(languages.items())
if isinstance(meta, dict)
```
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. Configure Superset with a malformed LANGUAGES config so that at least one value is not
a dict with "name" and "flag" keys (used via current_app.config["LANGUAGES"] in
`superset/localization/api.py:44`).
2. Start the Superset web server so that `LocalizationRestApi` (defined in
`superset/localization/api.py:56-72`) is registered.
3. Call the localization endpoint exposed at `LocalizationRestApi.get_available_locales`
(`@expose("/available_locales", methods=("GET",))` at
`superset/localization/api.py:73-82`), e.g. via HTTP GET
`/api/v1/localization/available_locales`.
4. During the request, `get_available_locales_data()` at
`superset/localization/api.py:34-53` iterates over `languages.items()` and executes
`meta["name"]` / `meta["flag"]` at lines 48-50; for any misconfigured entry (missing keys
or non-dict value), this raises `KeyError` or `TypeError`, propagating up and causing an
HTTP 500 response instead of a graceful, schema-conforming payload.
```
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset/localization/api.py
**Line:** 49:50
**Comment:**
*Possible Bug: The code assumes every entry in the LANGUAGES config is a dict with "name" and "flag" keys, so a misconfigured or partially specified LANGUAGES (missing those keys or using non-dict values) will raise a KeyError or TypeError and cause the /available_locales endpoint to 500 instead of failing gracefully; using dict.get with sensible defaults and guarding against non-dict entries avoids this runtime failure.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=8df02b5eeb08e2f5efd9310bfc031fdbf8da73d29dcc21b251ede1ec1a1da303&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=8df02b5eeb08e2f5efd9310bfc031fdbf8da73d29dcc21b251ede1ec1a1da303&reaction=dislike'>👎</a>
##########
superset-frontend/src/dashboard/components/nativeFilters/FiltersConfigModal/FiltersConfigForm/FiltersConfigForm.tsx:
##########
@@ -569,6 +583,96 @@ const FiltersConfigForm = (
[filterId, form, formChanged],
);
+ const localizationEnabled = isFeatureEnabled(
+ FeatureFlag.EnableContentLocalization,
+ );
+
+ const currentTranslations: Translations =
+ formFilter?.translations ?? filterToEdit?.translations ?? {};
+
+ useEffect(() => {
+ if (filterToEdit?.translations) {
+ setNativeFilterFieldValues(form, filterId, {
+ translations: filterToEdit.translations,
+ });
+ }
+ }, [filterId, filterToEdit?.translations, form]);
+
+ useEffect(() => {
+ if (localizationEnabled) {
+ SupersetClient.get({
+ endpoint: '/api/v1/localization/available_locales',
+ }).then(
+ response => {
+ const { locales, default_locale } = response.json.result;
+ setAllLocales(locales);
+ setDefaultLocale(default_locale);
+ },
+ err => getClientErrorObject(err).then(setError),
Review Comment:
**Suggestion:** The localization locales fetch reuses the generic `error` state used for default-value query failures, so a failure to load available locales will incorrectly surface as a "Cannot load filter" error in the default value section and may hide the default-value UI until another refresh clears it; handle localization errors separately (e.g., with a toast) instead of setting this shared error. [logic error]
<details>
<summary><b>Severity Level:</b> Major ⚠️</summary>
```mdx
- ⚠️ Default value editor hidden after locales API failure.
- ⚠️ Misleading "Cannot load filter" error shown to users.
- ⚠️ Users blocked from configuring default filter values.
```
</details>
```suggestion
err =>
getClientErrorObject(err).then(clientError =>
addDangerToast(
clientError.error || t('Failed to load available locales'),
),
),
```
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. Enable the content localization feature flag so `localizationEnabled` is true in
`FiltersConfigForm` (this component is defined in
`superset-frontend/src/dashboard/components/nativeFilters/FiltersConfigModal/FiltersConfigForm/FiltersConfigForm.tsx`
and mounted when opening the Native Filters configuration modal for a dashboard filter).
2. Cause `/api/v1/localization/available_locales` to fail, e.g. by misconfiguring the
backend or temporarily returning HTTP 500, so that the `SupersetClient.get` call in the
`useEffect` at lines 601–614 rejects.
3. Open the Native Filters configuration modal for any filter so that `FiltersConfigForm`
mounts and the localization `useEffect` runs; on request failure the `err` handler calls
`getClientErrorObject(err).then(setError)` which sets the shared `error` state declared
near the top of this file (`const [error, setError] = useState<ClientErrorObject>();`).
4. In the same modal, scroll to the "Default Value" section where `error` is consumed
around the `DefaultValue` rendering (`error ? <ErrorMessageWithStackTrace ... /> :
<DefaultValue ... />` inside the `DefaultValueContainer`), and observe that the UI shows a
"Cannot load filter" error and hides the default-value picker even though the dataset
query itself is not failing; this incorrect error state persists until a successful
default-value refresh clears it.
```
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset-frontend/src/dashboard/components/nativeFilters/FiltersConfigModal/FiltersConfigForm/FiltersConfigForm.tsx
**Line:** 611:611
**Comment:**
*Logic Error: The localization locales fetch reuses the generic `error` state used for default-value query failures, so a failure to load available locales will incorrectly surface as a "Cannot load filter" error in the default value section and may hide the default-value UI until another refresh clears it; handle localization errors separately (e.g., with a toast) instead of setting this shared error.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=27392454ebd6be844980940d5f08f29b1816feec481895200719a8ee7c3c8efc&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=27392454ebd6be844980940d5f08f29b1816feec481895200719a8ee7c3c8efc&reaction=dislike'>👎</a>
##########
superset-frontend/src/explore/components/PropertiesModal/PropertiesModal.test.tsx:
##########
@@ -471,3 +493,74 @@ test('Should display only custom tags when tagging system is enabled', async ()
mockIsFeatureEnabled.mockRestore();
});
+
+test('locale switcher hidden when content localization flag is off', async () => {
+ const props = createProps();
+ renderModal(props);
+ await waitFor(() => {
+ expect(screen.getByRole('dialog')).toBeInTheDocument();
+ });
+ expect(
+ screen.queryByRole('button', { name: /Locale switcher for/i }),
+ ).not.toBeInTheDocument();
+});
+
+test('locale switcher visible when content localization flag is on', async () => {
+ mockedIsFeatureEnabled.mockImplementation(
+ flag => flag === FeatureFlag.EnableContentLocalization,
+ );
+ const props = createProps();
+ renderModal(props);
+ await waitFor(() => {
+ expect(
+ screen.getByRole('button', {
+ name: /Locale switcher for Chart Name/i,
+ }),
+ ).toBeInTheDocument();
+ });
+ mockedIsFeatureEnabled.mockRestore();
+});
+
+test('clicking locale switcher opens dropdown with locales', async () => {
+ mockedIsFeatureEnabled.mockImplementation(
+ flag => flag === FeatureFlag.EnableContentLocalization,
+ );
+ const props = createProps();
+ renderModal(props);
+ await waitFor(() => {
+ expect(
+ screen.getByRole('button', { name: /Locale switcher for Chart Name/i }),
+ ).toBeInTheDocument();
+ });
+ await userEvent.click(
+ screen.getByRole('button', { name: /Locale switcher for Chart Name/i }),
+ );
+ await waitFor(() => {
+ expect(screen.getByText('English')).toBeInTheDocument();
+ expect(screen.getByText('German')).toBeInTheDocument();
+ });
+ mockedIsFeatureEnabled.mockRestore();
+});
+
+test('save includes translations in PUT payload', async () => {
+ const put = jest.spyOn(SupersetClient, 'put');
+ put.mockResolvedValue({ json: { result: {} } } as unknown as ReturnType<
+ typeof SupersetClient.put
+ >);
+ mockedIsFeatureEnabled.mockImplementation(
+ flag => flag === FeatureFlag.EnableContentLocalization,
+ );
+ const props = createProps();
+ renderModal(props);
+ await waitFor(() => {
+ expect(screen.getByRole('button', { name: 'Save' })).toBeEnabled();
+ });
+ await userEvent.click(screen.getByRole('button', { name: 'Save' }));
+ await waitFor(() => {
+ expect(put).toHaveBeenCalledTimes(1);
+ });
+ const putBody = JSON.parse(put.mock.calls[0][0].body as string);
+ expect(putBody.translations).toEqual(chartTranslations);
+ put.mockRestore();
+ mockedIsFeatureEnabled.mockRestore();
Review Comment:
**Suggestion:** The final `mockedIsFeatureEnabled.mockRestore()` in the save test suffers from the same problem as above—`mockedIsFeatureEnabled` is a module-level `jest.fn()` mock, not a spy, so calling `mockRestore()` will fail; use `mockReset()` to restore its default behavior after the test. [logic error]
<details>
<summary><b>Severity Level:</b> Major ⚠️</summary>
```mdx
- ❌ Save-with-translations test fails due to misuse of mockRestore.
- ⚠️ Makes it harder to validate PUT payload for translations.
```
</details>
```suggestion
mockedIsFeatureEnabled.mockReset();
```
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. Execute the Jest suite for
`superset-frontend/src/explore/components/PropertiesModal/PropertiesModal.test.tsx`.
2. As above, note that `isFeatureEnabled` is mocked with `jest.fn()` via
`jest.mock('@superset-ui/core', ...)`, and `mockedIsFeatureEnabled` simply references that
mock (lines 30–37 in the PR hunk).
3. In the test `save includes translations in PUT payload` (introduced around lines
545–566), the code sets `mockedIsFeatureEnabled.mockImplementation(...)` to enable the
content-localization feature flag and, at the end of the test, invokes
`mockedIsFeatureEnabled.mockRestore();` at line 565.
4. Since `mockedIsFeatureEnabled` is not a spy created with `jest.spyOn` but a standalone
`jest.fn()` mock, calling `.mockRestore()` at line 565 throws a Jest runtime error,
preventing this save/PUT-payload test from completing and contributing to overall frontend
test failures.
```
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset-frontend/src/explore/components/PropertiesModal/PropertiesModal.test.tsx
**Line:** 565:565
**Comment:**
*Logic Error: The final `mockedIsFeatureEnabled.mockRestore()` in the save test suffers from the same problem as above—`mockedIsFeatureEnabled` is a module-level `jest.fn()` mock, not a spy, so calling `mockRestore()` will fail; use `mockReset()` to restore its default behavior after the test.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=6169320341e2ed360f6f560dd56341d8d828d1a5b68dbf8c07170023feefe738&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=6169320341e2ed360f6f560dd56341d8d828d1a5b68dbf8c07170023feefe738&reaction=dislike'>👎</a>
##########
superset-frontend/playwright/pages/DashboardPage.ts:
##########
@@ -125,4 +125,22 @@ export class DashboardPage {
await menu.selectSubmenuItem('Download', optionText);
return downloadPromise;
}
+
+ /**
+ * Enter edit mode by clicking "Edit dashboard" button.
+ * Required before accessing edit-only menu items like "Edit properties".
+ */
+ async enterEditMode(): Promise<void> {
+ await this.page.click('[data-test="edit-dashboard-button"]');
+ }
+
+ /**
+ * Click "Edit properties" in the header actions menu.
+ * Requires edit mode — call enterEditMode() first.
+ */
+ async clickEditProperties(): Promise<void> {
+ await this.openHeaderActionsMenu();
+ const menu = this.page.locator(DashboardPage.SELECTORS.HEADER_ACTIONS_MENU);
+ await menu.getByText('Edit properties', { exact: true }).click();
Review Comment:
**Suggestion:** The Playwright selector for the "Edit properties" menu item relies on the visible text "Edit properties", which will change under content localization and cause tests using this helper to fail or hang when the UI is not in English; use a stable, non-localized selector (e.g., a data-test attribute) instead so tests remain robust across locales. [logic error]
<details>
<summary><b>Severity Level:</b> Major ⚠️</summary>
```mdx
- ⚠️ Dashboard edit E2E tests fail under non-English UI locale.
- ⚠️ Blocks reliable automation for locale-switching dashboard scenarios.
```
</details>
```suggestion
await menu.locator('[data-test="edit-properties-menu-item"]').click();
```
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. Start the Superset frontend with the PR code and configure the UI to use a non-English
locale so that header menu items are translated (existing Superset i18n behavior; this
affects the label for the edit-properties action).
2. In a Playwright test, construct a `DashboardPage` instance from
`superset-frontend/playwright/pages/DashboardPage.ts` and navigate to a dashboard via
`gotoById()` or `gotoBySlug()`, then call `waitForLoad()` to ensure the header is
rendered.
3. Call `enterEditMode()` (lines 133–135 in `DashboardPage.ts`) so that the edit-only
header actions, including the properties menu item, become available in the header actions
menu.
4. Invoke `clickEditProperties()` (lines 141–145 in `DashboardPage.ts`); this calls
`openHeaderActionsMenu()` and then `menu.getByText('Edit properties', { exact: true
}).click()`. Because the menu item text is now translated and no longer exactly `'Edit
properties'`, Playwright fails to find the element and times out, causing the E2E test
using this helper to fail or hang whenever it runs under a non-English locale.
```
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset-frontend/playwright/pages/DashboardPage.ts
**Line:** 144:144
**Comment:**
*Logic Error: The Playwright selector for the "Edit properties" menu item relies on the visible text "Edit properties", which will change under content localization and cause tests using this helper to fail or hang when the UI is not in English; use a stable, non-localized selector (e.g., a data-test attribute) instead so tests remain robust across locales.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=69bda1faf96e4cd9b62581fb75682ed8e982f45e247650702bf3193c39f002bd&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=69bda1faf96e4cd9b62581fb75682ed8e982f45e247650702bf3193c39f002bd&reaction=dislike'>👎</a>
##########
superset/dashboards/schemas.py:
##########
@@ -445,6 +574,50 @@ class DashboardPutSchema(BaseDashboardSchema):
fields.Integer(metadata={"description": tags_description}, allow_none=True)
)
uuid = fields.UUID(allow_none=True)
+ translations = fields.Dict(
+ metadata={"description": "Translations dict for content localization"},
+ allow_none=True,
+ )
+
+ @validates_schema
+ def validate_translations_data(
+ self, data: dict[str, Any], **kwargs: Any
+ ) -> None:
+ """
+ Validate translations field: feature flag and structure.
+
+ Checks:
+ 1. Feature flag ENABLE_CONTENT_LOCALIZATION must be enabled
+ 2. Structure must be valid: {field: {locale: value}}
+
+ Raises:
+ ValidationError: If feature disabled or structure invalid.
+ """
+ if "translations" not in data:
+ return
+
+ if not is_feature_enabled("ENABLE_CONTENT_LOCALIZATION"):
+ raise ValidationError(
+ "Content localization is not enabled. "
+ "Set ENABLE_CONTENT_LOCALIZATION=True to use translations.",
+ field_name="translations",
+ )
+
+ validate_translations(data["translations"])
Review Comment:
**Suggestion:** The schema allows `translations` to be `None` (`allow_none=True`), but the schema-level validator unconditionally passes this value into `validate_translations`, which is likely to expect a dictionary and may raise a non-ValidationError (e.g. TypeError), resulting in a 500 instead of a clean validation error or acceptance of `null` as "no translations". [type error]
<details>
<summary><b>Severity Level:</b> Major ⚠️</summary>
```mdx
- ❌ PUT /api/v1/dashboard fails when translations explicitly null.
- ⚠️ External clients cannot clear translations using null payload.
- ⚠️ Risk of 500 error from schema validator.
```
</details>
```suggestion
translations = data.get("translations")
# Allow explicit null (treated the same as absence of translations)
if translations is None:
return
if not is_feature_enabled("ENABLE_CONTENT_LOCALIZATION"):
raise ValidationError(
"Content localization is not enabled. "
"Set ENABLE_CONTENT_LOCALIZATION=True to use translations.",
field_name="translations",
)
validate_translations(translations)
```
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. Call the dashboard update endpoint `PUT /api/v1/dashboard/<id>` (handled by the
Dashboard REST API that uses `DashboardPutSchema` for request validation; schema defined
in `superset/dashboards/schemas.py:610-676` in the final file).
2. In the JSON payload, include `"translations": null` while `ENABLE_CONTENT_LOCALIZATION`
is enabled so that the request reaches `DashboardPutSchema.translations` (field declared
at `superset/dashboards/schemas.py:672-676`).
3. Marshmallow deserializes the payload: because `translations` is declared as
`fields.Dict(..., allow_none=True)`, the deserialized `data` passed into
`validate_translations_data` at `superset/dashboards/schemas.py:582-606` contains the key
`"translations"` with value `None`.
4. Inside `validate_translations_data`, the `"translations" in data` check passes and
`validate_translations(data["translations"])` is invoked with `None` at line 606; since
`validate_translations` (from `superset.localization`) is designed to validate a mapping
of translations, passing `None` can result in a non-`ValidationError` exception (e.g.
`TypeError`) or an unexpected validation failure, producing a 500 or rejecting `null`
despite `allow_none=True`.
```
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset/dashboards/schemas.py
**Line:** 599:606
**Comment:**
*Type Error: The schema allows `translations` to be `None` (`allow_none=True`), but the schema-level validator unconditionally passes this value into `validate_translations`, which is likely to expect a dictionary and may raise a non-ValidationError (e.g. TypeError), resulting in a 500 instead of a clean validation error or acceptance of `null` as "no translations".
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=4d879dab4a9a8665436dfc3a5252648eac6a7269ba2ca0717c726b8dcfbb06a1&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=4d879dab4a9a8665436dfc3a5252648eac6a7269ba2ca0717c726b8dcfbb06a1&reaction=dislike'>👎</a>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "YuriyKrasilnikov (via GitHub)" <gi...@apache.org>.
YuriyKrasilnikov commented on code in PR #37790:
URL: https://github.com/apache/superset/pull/37790#discussion_r2779269666
##########
superset/dashboards/schemas.py:
##########
@@ -445,6 +574,50 @@ class DashboardPutSchema(BaseDashboardSchema):
fields.Integer(metadata={"description": tags_description}, allow_none=True)
)
uuid = fields.UUID(allow_none=True)
+ translations = fields.Dict(
+ metadata={"description": "Translations dict for content localization"},
+ allow_none=True,
+ )
+
+ @validates_schema
+ def validate_translations_data(
+ self, data: dict[str, Any], **kwargs: Any
+ ) -> None:
+ """
+ Validate translations field: feature flag and structure.
+
+ Checks:
+ 1. Feature flag ENABLE_CONTENT_LOCALIZATION must be enabled
+ 2. Structure must be valid: {field: {locale: value}}
+
+ Raises:
+ ValidationError: If feature disabled or structure invalid.
+ """
+ if "translations" not in data:
+ return
+
+ if not is_feature_enabled("ENABLE_CONTENT_LOCALIZATION"):
+ raise ValidationError(
+ "Content localization is not enabled. "
+ "Set ENABLE_CONTENT_LOCALIZATION=True to use translations.",
+ field_name="translations",
+ )
+
+ validate_translations(data["translations"])
Review Comment:
False positive. `validate_translations()` explicitly handles `None` as the first guard clause:
```python
# superset/localization/validation.py:128-129
if translations is None:
return
```
The function signature also declares `None` as a valid input: `translations: dict[str, dict[str, str]] | None`.
The call chain is safe:
1. `allow_none=True` on the Marshmallow field → `data["translations"]` can be `None`
2. `validate_translations(None)` → early return, no TypeError
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #37790:
URL: https://github.com/apache/superset/pull/37790#issuecomment-5719096788
# 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️❗ @YuriyKrasilnikov Your base branch `master` has also updated `superset/migrations`.
**Please consider rebasing your branch and [resolving potential db migration conflicts](https://superset.apache.org/docs/contributing/development#merging-db-migrations).**
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #37790:
URL: https://github.com/apache/superset/pull/37790#issuecomment-6070746010
### ⚠️ Possible DB migration conflict
@YuriyKrasilnikov the base branch `master` picked up a new database migration under `superset/migrations/` after this PR was opened, and this PR adds or modifies migration files too. Alembic migrations form a single linear chain, so if both branch off the same parent revision, merging this PR as-is could leave the migration history with two heads instead of one, which makes `superset db upgrade` fail with `Multiple head revisions are present`.
To check and, if needed, fix this:
1. Rebase this branch onto the latest `master`.
2. Run `superset db heads`. If it lists more than one revision, you have a conflict.
3. In your new migration's script, update `down_revision` (and the `Revises` comment) to point at the other head instead, so the chain has a single head again.
See [Merging DB Migrations](https://superset.apache.org/docs/contributing/development#merging-db-migrations) in the contributing guide for a worked example.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "YuriyKrasilnikov (via GitHub)" <gi...@apache.org>.
YuriyKrasilnikov commented on code in PR #37790:
URL: https://github.com/apache/superset/pull/37790#discussion_r2783882373
##########
superset-frontend/playwright/tests/experimental/localization/chart-title-localization.spec.ts:
##########
@@ -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 { test, expect } from '@playwright/test';
+import {
+ apiPutDashboard,
+ apiDeleteDashboard,
+ createTestDashboard,
+} from '../../../helpers/api/dashboard';
+import {
+ apiPutChart,
+ apiDeleteChart,
+ createTestChart,
+} from '../../../helpers/api/chart';
+import {
+ createTestVirtualDataset,
+ apiDeleteDataset,
+} from '../../../helpers/api/dataset';
+import {
+ createTestDatabase,
+ apiDeleteDatabase,
+} from '../../../helpers/api/database';
+import { DashboardPage } from '../../../pages/DashboardPage';
+import { TIMEOUT } from '../../../utils/constants';
+
+/**
+ * Chart Title Localization E2E Tests
+ *
+ * Verifies that chart titles on a dashboard are displayed in the
+ * user's session locale when translations exist on the chart.
+ *
+ * Prerequisites:
+ * - Superset running with ENABLE_CONTENT_LOCALIZATION = True
+ * - Multiple LANGUAGES configured in superset_config.py
+ * - Admin user authenticated (via global-setup)
+ */
+
+const GERMAN_CHART_TITLE = 'Deutscher Diagrammtitel';
+
+// File-scope state (reset in beforeEach)
+let testResources: {
+ dashboardIds: number[];
+ chartIds: number[];
+ datasetIds: number[];
+ databaseIds: number[];
+};
+
+test.beforeEach(async () => {
+ testResources = {
+ dashboardIds: [],
+ chartIds: [],
+ datasetIds: [],
+ databaseIds: [],
+ };
+});
+
+test.afterEach(async ({ page }) => {
+ // Reset locale to English
+ await page.request.get('lang/en', { maxRedirects: 0 }).catch(() => {});
+
+ // Cleanup in reverse creation order: charts → dashboards → datasets → databases
+ // Sequential per group to respect FK constraints
+ await Promise.all(
+ testResources.chartIds.map(id =>
+ apiDeleteChart(page, id, { failOnStatusCode: false }).catch(e =>
+ console.warn(`[Cleanup] chart ${id}:`, String(e)),
+ ),
+ ),
+ );
+ await Promise.all(
+ testResources.dashboardIds.map(id =>
+ apiDeleteDashboard(page, id, { failOnStatusCode: false }).catch(e =>
+ console.warn(`[Cleanup] dashboard ${id}:`, String(e)),
+ ),
+ ),
+ );
+ await Promise.all(
+ testResources.datasetIds.map(id =>
+ apiDeleteDataset(page, id, { failOnStatusCode: false }).catch(e =>
+ console.warn(`[Cleanup] dataset ${id}:`, String(e)),
+ ),
+ ),
+ );
+ await Promise.all(
+ testResources.databaseIds.map(id =>
+ apiDeleteDatabase(page, id, { failOnStatusCode: false }).catch(e =>
+ console.warn(`[Cleanup] database ${id}:`, String(e)),
+ ),
+ ),
+ );
+});
+
+/**
+ * Build minimal position_json with a single chart component.
+ */
+function buildPositionJson(
+ chartId: number,
+ chartUuid: string,
+ sliceName: string,
+ dashboardTitle: string,
+): string {
+ return JSON.stringify({
+ DASHBOARD_VERSION_KEY: 'v2',
+ ROOT_ID: { type: 'ROOT', id: 'ROOT_ID', children: ['GRID_ID'] },
+ GRID_ID: {
+ type: 'GRID',
+ id: 'GRID_ID',
+ children: ['ROW-test1'],
+ },
+ HEADER_ID: {
+ type: 'HEADER',
+ id: 'HEADER_ID',
+ meta: { text: dashboardTitle },
+ },
+ 'ROW-test1': {
+ type: 'ROW',
+ id: 'ROW-test1',
+ children: ['CHART-test1'],
+ meta: { background: 'BACKGROUND_TRANSPARENT' },
+ },
+ 'CHART-test1': {
+ type: 'CHART',
+ id: 'CHART-test1',
+ children: [],
+ meta: {
+ chartId,
+ sliceName,
+ uuid: chartUuid,
+ width: 12,
+ height: 50,
+ },
+ },
+ });
+}
+
+test('should display localized chart title on dashboard when session locale has translation', async ({
+ page,
+}) => {
+ const suffix = Date.now();
+
+ // 1. Create test database and virtual dataset
+ const dbId = await createTestDatabase(page, `test_chart_loc_db_${suffix}`);
+ expect(dbId).not.toBeNull();
+ testResources.databaseIds.push(dbId!);
+
+ const datasetId = await createTestVirtualDataset(
+ page,
+ `test_chart_loc_ds_${suffix}`,
+ dbId!,
+ );
+ expect(datasetId).not.toBeNull();
+ testResources.datasetIds.push(datasetId!);
+
+ // 2. Create chart and dashboard
+ const originalTitle = `test_chart_loc_${suffix}`;
+ const chart = await createTestChart(page, originalTitle, datasetId!);
+ expect(chart).not.toBeNull();
+ testResources.chartIds.push(chart!.id);
+
+ const dashboardTitle = `test_dash_chart_loc_${suffix}`;
+ const dashboardId = await createTestDashboard(page, dashboardTitle);
+ expect(dashboardId).not.toBeNull();
+ testResources.dashboardIds.push(dashboardId!);
+
+ // 3. Associate chart with dashboard and set German translation
+ const putChartRes = await apiPutChart(page, chart!.id, {
+ dashboards: [dashboardId!],
+ translations: { slice_name: { de: GERMAN_CHART_TITLE } },
+ });
+ expect(putChartRes.ok()).toBe(true);
+
+ // 4. Set dashboard layout with the chart
+ const putDashRes = await apiPutDashboard(page, dashboardId!, {
+ position_json: buildPositionJson(
+ chart!.id,
+ chart!.uuid,
+ originalTitle,
+ dashboardTitle,
+ ),
+ });
+ expect(putDashRes.ok()).toBe(true);
+
+ // 5. Switch session locale to German
+ await page.request.get('lang/de', { maxRedirects: 0 });
+
+ // 6. Navigate to dashboard and verify localized chart title
+ const dashboardPage = new DashboardPage(page);
+ await dashboardPage.gotoById(dashboardId!);
+ await dashboardPage.waitForLoad({ timeout: TIMEOUT.PAGE_LOAD });
+
+ // Chart header should show German title
+ const chartHeader = page.locator('[data-test="slice-header"]').first();
+ await expect(chartHeader).toContainText(GERMAN_CHART_TITLE, {
+ timeout: TIMEOUT.API_RESPONSE,
+ });
+});
+
+test('should display original chart title when session locale has no translation', async ({
+ page,
+}) => {
+ const suffix = Date.now();
+
+ // 1. Create test database and virtual dataset
+ const dbId = await createTestDatabase(page, `test_chart_orig_db_${suffix}`);
+ expect(dbId).not.toBeNull();
+ testResources.databaseIds.push(dbId!);
+
+ const datasetId = await createTestVirtualDataset(
+ page,
+ `test_chart_orig_ds_${suffix}`,
+ dbId!,
+ );
+ expect(datasetId).not.toBeNull();
+ testResources.datasetIds.push(datasetId!);
+
+ // 2. Create chart and dashboard
+ const originalTitle = `test_chart_orig_${suffix}`;
+ const chart = await createTestChart(page, originalTitle, datasetId!);
+ expect(chart).not.toBeNull();
+ testResources.chartIds.push(chart!.id);
+
+ const dashboardTitle = `test_dash_chart_orig_${suffix}`;
+ const dashboardId = await createTestDashboard(page, dashboardTitle);
+ expect(dashboardId).not.toBeNull();
+ testResources.dashboardIds.push(dashboardId!);
+
+ // 3. Associate chart with dashboard and set German translation (no French)
+ await apiPutChart(page, chart!.id, {
+ dashboards: [dashboardId!],
+ translations: { slice_name: { de: GERMAN_CHART_TITLE } },
+ });
+
+ // Set dashboard layout
+ await apiPutDashboard(page, dashboardId!, {
+ position_json: buildPositionJson(
+ chart!.id,
+ chart!.uuid,
+ originalTitle,
+ dashboardTitle,
+ ),
+ });
Review Comment:
Not a bug. \`apiPutChart\` and \`apiPutDashboard\` use \`failOnStatusCode: true\` by default (\`requests.ts:153\`). Playwright **automatically throws** on any non-2xx response — the \`await\` line itself fails the test immediately with a clear HTTP status error.
The explicit \`expect(res.ok()).toBe(true)\` in the first test is redundant belt-and-suspenders — it can never actually fail because \`failOnStatusCode: true\` already threw before \`.ok()\` could return \`false\`.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "YuriyKrasilnikov (via GitHub)" <gi...@apache.org>.
YuriyKrasilnikov commented on code in PR #37790:
URL: https://github.com/apache/superset/pull/37790#discussion_r2783872740
##########
superset-frontend/playwright/helpers/api/chart.ts:
##########
@@ -0,0 +1,153 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import { Page, APIResponse } from '@playwright/test';
+import {
+ apiGet,
+ apiPost,
+ apiPut,
+ apiDelete,
+ ApiRequestOptions,
+} from './requests';
+
+export const ENDPOINTS = {
+ CHART: 'api/v1/chart/',
+} as const;
+
+/** Payload for POST /api/v1/chart/ */
+export interface ChartCreatePayload {
+ slice_name: string;
+ datasource_id: number;
+ datasource_type: string;
+ viz_type?: string;
+ owners?: number[];
+ dashboards?: number[];
+ params?: string;
+}
+
+/** Payload for PUT /api/v1/chart/{id} */
+export interface ChartUpdatePayload {
+ slice_name?: string;
+ owners?: number[];
+ dashboards?: number[];
+ translations?: Record<string, Record<string, string>>;
+}
+
+/** Chart data shape from API responses */
+export interface ChartResult {
+ id: number;
+ uuid: string;
+ slice_name: string;
+ viz_type?: string;
+ translations?: Record<string, Record<string, string>>;
+ available_locales?: string[];
+}
+
+/**
+ * POST /api/v1/chart/
+ * Creates a new chart.
+ */
+export async function apiPostChart(
+ page: Page,
+ payload: ChartCreatePayload,
+): Promise<APIResponse> {
+ return apiPost(page, ENDPOINTS.CHART, payload);
+}
+
+/**
+ * GET /api/v1/chart/{id}
+ * Fetches chart details.
+ */
+export async function apiGetChart(
+ page: Page,
+ chartId: number,
+ options?: ApiRequestOptions,
+): Promise<APIResponse> {
+ return apiGet(page, `${ENDPOINTS.CHART}${chartId}`, options);
+}
+
+/**
+ * PUT /api/v1/chart/{id}
+ * Updates chart fields including translations.
+ */
+export async function apiPutChart(
+ page: Page,
+ chartId: number,
+ data: ChartUpdatePayload,
+ options?: ApiRequestOptions,
+): Promise<APIResponse> {
+ return apiPut(page, `${ENDPOINTS.CHART}${chartId}`, data, options);
+}
+
+/**
+ * DELETE /api/v1/chart/{id}
+ * Removes a chart.
+ */
+export async function apiDeleteChart(
+ page: Page,
+ chartId: number,
+ options?: ApiRequestOptions,
+): Promise<APIResponse> {
+ return apiDelete(page, `${ENDPOINTS.CHART}${chartId}`, options);
+}
+
+/**
+ * Creates a minimal chart for testing.
+ * Requires a datasource (use createTestVirtualDataset first).
+ * Fetches UUID via GET after creation (not in POST response).
+ * @returns Chart ID and UUID, or null on failure.
+ */
+export async function createTestChart(
+ page: Page,
+ sliceName: string,
+ datasourceId: number,
+): Promise<{ id: number; uuid: string } | null> {
+ const response = await apiPostChart(page, {
+ slice_name: sliceName,
+ datasource_id: datasourceId,
+ datasource_type: 'table',
+ viz_type: 'table',
+ owners: [],
+ });
Review Comment:
Not a bug. \`failOnStatusCode: true\` is the default in all \`apiPost\`/\`apiGet\` helpers (\`requests.ts:133\`), so Playwright throws on non-2xx before \`response.ok()\` is reached — the null-return path is dead code.
This is a **codebase-wide pattern**, not specific to this PR. All four \`createTest*\` helpers (\`createTestChart\`, \`createTestDashboard\`, \`createTestDatabase\`, \`createTestVirtualDataset\`) have the same structure. Every caller immediately asserts \`expect(result).not.toBeNull()\`, so the outcome is identical either way.
Helpers that genuinely need graceful null-return (e.g. \`getDatabaseByName\`, \`getDatasetByName\`) explicitly pass \`{ failOnStatusCode: false }\`.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #37790:
URL: https://github.com/apache/superset/pull/37790#issuecomment-5786546023
### ⚠️ Possible DB migration conflict
@YuriyKrasilnikov the base branch `master` picked up a new database migration under `superset/migrations/` after this PR was opened, and this PR adds or modifies migration files too. Alembic migrations form a single linear chain, so if both branch off the same parent revision, merging this PR as-is could leave the migration history with two heads instead of one, which makes `superset db upgrade` fail with `Multiple head revisions are present`.
To check and, if needed, fix this:
1. Rebase this branch onto the latest `master`.
2. Run `superset db heads`. If it lists more than one revision, you have a conflict.
3. In your new migration's script, update `down_revision` (and the `Revises` comment) to point at the other head instead, so the chain has a single head again.
See [Merging DB Migrations](https://superset.apache.org/docs/contributing/development#merging-db-migrations) in the contributing guide for a worked example.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #37790:
URL: https://github.com/apache/superset/pull/37790#issuecomment-5953083404
### ⚠️ Possible DB migration conflict
@YuriyKrasilnikov the base branch `master` picked up a new database migration under `superset/migrations/` after this PR was opened, and this PR adds or modifies migration files too. Alembic migrations form a single linear chain, so if both branch off the same parent revision, merging this PR as-is could leave the migration history with two heads instead of one, which makes `superset db upgrade` fail with `Multiple head revisions are present`.
To check and, if needed, fix this:
1. Rebase this branch onto the latest `master`.
2. Run `superset db heads`. If it lists more than one revision, you have a conflict.
3. In your new migration's script, update `down_revision` (and the `Revises` comment) to point at the other head instead, so the chain has a single head again.
See [Merging DB Migrations](https://superset.apache.org/docs/contributing/development#merging-db-migrations) in the contributing guide for a worked example.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #37790:
URL: https://github.com/apache/superset/pull/37790#issuecomment-6281393117
### ⚠️ Possible DB migration conflict
@YuriyKrasilnikov the base branch `master` picked up a new database migration under `superset/migrations/` after this PR was opened, and this PR adds or modifies migration files too. Alembic migrations form a single linear chain, so if both branch off the same parent revision, merging this PR as-is could leave the migration history with two heads instead of one, which makes `superset db upgrade` fail with `Multiple head revisions are present`.
To check and, if needed, fix this:
1. Rebase this branch onto the latest `master`.
2. Run `superset db heads`. If it lists more than one revision, you have a conflict.
3. In your new migration's script, update `down_revision` (and the `Revises` comment) to point at the other head instead, so the chain has a single head again.
See [Merging DB Migrations](https://superset.apache.org/docs/contributing/development#merging-db-migrations) in the contributing guide for a worked example.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "github-actions[bot] (via GitHub) via notifications" <no...@superset.apache.org>.
github-actions[bot] commented on PR #37790:
URL: https://github.com/apache/superset/pull/37790#issuecomment-7038833051
### ⚠️ Possible DB migration conflict
@YuriyKrasilnikov the base branch `master` picked up a new database migration under `superset/migrations/` after this PR was opened, and this PR adds or modifies migration files too. Alembic migrations form a single linear chain, so if both branch off the same parent revision, merging this PR as-is could leave the migration history with two heads instead of one, which makes `superset db upgrade` fail with `Multiple head revisions are present`.
To check and, if needed, fix this:
1. Rebase this branch onto the latest `master`.
2. Run `superset db heads`. If it lists more than one revision, you have a conflict.
3. In your new migration's script, update `down_revision` (and the `Revises` comment) to point at the other head instead, so the chain has a single head again.
See [Merging DB Migrations](https://superset.apache.org/docs/contributing/development#merging-db-migrations) in the contributing guide for a worked example.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "github-actions[bot] (via GitHub) via notifications" <no...@superset.apache.org>.
github-actions[bot] commented on PR #37790:
URL: https://github.com/apache/superset/pull/37790#issuecomment-7370403891
### ⚠️ Possible DB migration conflict
@YuriyKrasilnikov the base branch `master` picked up a new database migration under `superset/migrations/` after this PR was opened, and this PR adds or modifies migration files too. Alembic migrations form a single linear chain, so if both branch off the same parent revision, merging this PR as-is could leave the migration history with two heads instead of one, which makes `superset db upgrade` fail with `Multiple head revisions are present`.
To check and, if needed, fix this:
1. Rebase this branch onto the latest `master`.
2. Run `superset db heads`. If it lists more than one revision, you have a conflict.
3. In your new migration's script, update `down_revision` (and the `Revises` comment) to point at the other head instead, so the chain has a single head again.
See [Merging DB Migrations](https://superset.apache.org/docs/contributing/development#merging-db-migrations) in the contributing guide for a worked example.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #37790:
URL: https://github.com/apache/superset/pull/37790#issuecomment-3927927804
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers a full AI review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #37790:
URL: https://github.com/apache/superset/pull/37790#issuecomment-3872265692
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers a full AI review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "YuriyKrasilnikov (via GitHub)" <gi...@apache.org>.
YuriyKrasilnikov commented on code in PR #37790:
URL: https://github.com/apache/superset/pull/37790#discussion_r2779220889
##########
superset-frontend/src/dashboard/components/PropertiesModal/sections/BasicInfoSection.tsx:
##########
@@ -58,8 +82,21 @@ const BasicInfoSection = ({
placeholder={t('The display name of your dashboard')}
data-test="dashboard-title-input"
type="text"
+ suffix={!isEditingTranslation ? localeSwitcher : undefined}
/>
</FormItem>
+ {isEditingTranslation && (
+ <Input
+ value={translationValue}
Review Comment:
Not an issue. The translation Input (line 88) only renders when `isEditingTranslation === true`, which requires `activeLocale !== DEFAULT_LOCALE_KEY`. In that code path, `translationValue` is computed as:
```tsx
translations.dashboard_title?.[titleActiveLocale] ?? ''
```
The `?? ''` fallback guarantees a string value — never `undefined`. The Input never transitions from uncontrolled to controlled because it is not rendered when `translationValue` would be `undefined`.
Same pattern is used consistently across all three integration points (Dashboard PropertiesModal, Chart PropertiesModal, FiltersConfigForm).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #37790:
URL: https://github.com/apache/superset/pull/37790#issuecomment-5706352886
# 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️❗ @YuriyKrasilnikov Your base branch `master` has also updated `superset/migrations`.
**Please consider rebasing your branch and [resolving potential db migration conflicts](https://superset.apache.org/docs/contributing/development#merging-db-migrations).**
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #37790:
URL: https://github.com/apache/superset/pull/37790#issuecomment-6461081625
### ⚠️ Possible DB migration conflict
@YuriyKrasilnikov the base branch `master` picked up a new database migration under `superset/migrations/` after this PR was opened, and this PR adds or modifies migration files too. Alembic migrations form a single linear chain, so if both branch off the same parent revision, merging this PR as-is could leave the migration history with two heads instead of one, which makes `superset db upgrade` fail with `Multiple head revisions are present`.
To check and, if needed, fix this:
1. Rebase this branch onto the latest `master`.
2. Run `superset db heads`. If it lists more than one revision, you have a conflict.
3. In your new migration's script, update `down_revision` (and the `Revises` comment) to point at the other head instead, so the chain has a single head again.
See [Merging DB Migrations](https://superset.apache.org/docs/contributing/development#merging-db-migrations) in the contributing guide for a worked example.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "github-actions[bot] (via GitHub) via notifications" <no...@superset.apache.org>.
github-actions[bot] commented on PR #37790:
URL: https://github.com/apache/superset/pull/37790#issuecomment-6589605197
### ⚠️ Possible DB migration conflict
@YuriyKrasilnikov the base branch `master` picked up a new database migration under `superset/migrations/` after this PR was opened, and this PR adds or modifies migration files too. Alembic migrations form a single linear chain, so if both branch off the same parent revision, merging this PR as-is could leave the migration history with two heads instead of one, which makes `superset db upgrade` fail with `Multiple head revisions are present`.
To check and, if needed, fix this:
1. Rebase this branch onto the latest `master`.
2. Run `superset db heads`. If it lists more than one revision, you have a conflict.
3. In your new migration's script, update `down_revision` (and the `Revises` comment) to point at the other head instead, so the chain has a single head again.
See [Merging DB Migrations](https://superset.apache.org/docs/contributing/development#merging-db-migrations) in the contributing guide for a worked example.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "github-actions[bot] (via GitHub) via notifications" <no...@superset.apache.org>.
github-actions[bot] commented on PR #37790:
URL: https://github.com/apache/superset/pull/37790#issuecomment-7281329900
### ⚠️ Possible DB migration conflict
@YuriyKrasilnikov the base branch `master` picked up a new database migration under `superset/migrations/` after this PR was opened, and this PR adds or modifies migration files too. Alembic migrations form a single linear chain, so if both branch off the same parent revision, merging this PR as-is could leave the migration history with two heads instead of one, which makes `superset db upgrade` fail with `Multiple head revisions are present`.
To check and, if needed, fix this:
1. Rebase this branch onto the latest `master`.
2. Run `superset db heads`. If it lists more than one revision, you have a conflict.
3. In your new migration's script, update `down_revision` (and the `Revises` comment) to point at the other head instead, so the chain has a single head again.
See [Merging DB Migrations](https://superset.apache.org/docs/contributing/development#merging-db-migrations) in the contributing guide for a worked example.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "YuriyKrasilnikov (via GitHub)" <gi...@apache.org>.
YuriyKrasilnikov commented on PR #37790:
URL: https://github.com/apache/superset/pull/37790#issuecomment-3938650328
@mistercrunch @michael-s-molina @betodealmeida @eschutho @sadpandajoe
This PR implements the complete Content Localization feature (SIP-201 #37789) — enabling translation of user-created content (chart names, dashboard titles, metric labels, axis titles, annotations) without requiring dashboard duplication per language.
The feature is **fully gated behind the `ENABLE_CONTENT_LOCALIZATION` feature flag** with zero impact on existing deployments when disabled.
### Current state
The implementation spans **~20k lines across 220 files** (68 commits). This volume is not practical to review as a single PR.
### Proposed approach: 7 stacked PRs
I propose splitting this into a series of independently reviewable PRs, each delivering standalone value:
| # | Scope | Depends on | Value |
|---|-------|------------|-------|
| **1** | **Backend**: models, migration, `LocalizableMixin`, API (`available_locales`, `?include_translations`), XSS sanitization, validation, Jinja `current_user_locale()` | — | API contract and data layer |
| **2** | **Frontend core**: `LocaleSwitcher`, `useTranslatableTitle`, `TranslationInput`, PropertiesModals (Dashboard, Chart, Native Filter), inline title editors | 1 | Translation management UI |
| **3a** | **Metric labels**: `buildLocalizedMetricLabelMap` + 20 chart types (Table, Timeseries, Pie, Bar, Funnel, Gauge, Radar, Sunburst, Treemap, Sankey, Pivot, MixedTimeseries, BoxPlot, Graph, Tree, Gantt, BigNumber) | 2 | Localized metrics in visualizations |
| **3b** | **Column labels**: `buildLocalizedColumnLabelMap` + Table, Pivot Table, adhoc columns | 2 | Localized column headers |
| **3c** | **Axis titles & labels**: `TranslatableTextControl`, `getLocalizedFormDataValue` + axis titles (Timeseries, MixedTimeseries, Bubble, BoxPlot, Gantt, Histogram), BigNumber subtitle, Waterfall labels | 2 | Localized axes and chart-specific text |
| **3d** | **Annotations**: `getLocalizedAnnotationName` + Timeseries, MixedTimeseries | 2 | Localized annotation layer names |
| **4** | **Embedded SDK + E2E**: `setLocale()`, `initialLocale`, reactive `LocaleController`, Playwright tests | 2 | SDK support and test coverage |
PRs 3a–3d and 4 have no dependencies on each other and can be reviewed and merged in any order once PR 2 is in.
### Questions
1. Is this decomposition acceptable, or would you prefer a different grouping?
2. Should I proceed with splitting now, or wait for SIP-201 formal approval first?
3. Would a running demo instance be useful for evaluating the feature before code review?
The complete implementation is functional on this branch for early evaluation if needed.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #37790:
URL: https://github.com/apache/superset/pull/37790#issuecomment-3867326938
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers a full AI review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "YuriyKrasilnikov (via GitHub)" <gi...@apache.org>.
YuriyKrasilnikov commented on code in PR #37790:
URL: https://github.com/apache/superset/pull/37790#discussion_r2783889106
##########
superset-frontend/src/dashboard/components/PropertiesModal/index.tsx:
##########
@@ -448,6 +481,19 @@ const PropertiesModal = ({
t('An error occurred while fetching available themes'),
);
});
+
+ if (isFeatureEnabled(FeatureFlag.EnableContentLocalization)) {
+ SupersetClient.get({
+ endpoint: '/api/v1/localization/available_locales',
+ }).then(
+ response => {
+ const { locales, default_locale } = response.json.result;
+ setAllLocales(locales);
+ setDefaultLocale(default_locale);
+ },
+ err => logging.error('Failed to fetch available locales', err),
Review Comment:
Intentional design. Commit \`c01af6ab12\` explicitly replaced \`handleErrorResponse\` with \`logging.error\` here.
The old \`handleErrorResponse\` showed a red danger toast for a background auxiliary fetch that the user did not initiate — confusing UX. If the locales endpoint fails, the LocaleSwitcher simply renders with no locale options (\`allLocales\` stays \`[]\`), and the entire dashboard properties modal works normally. This is the correct graceful degradation.
The pattern is consistent across all four integration points (Dashboard PropertiesModal, Chart PropertiesModal, FiltersConfigForm, AdhocMetricEditPopoverTitle) and follows the established Superset pattern for optional auxiliary fetches (cf. \`keyValue.tsx\`).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #37790:
URL: https://github.com/apache/superset/pull/37790#issuecomment-3874661223
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers a full AI review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #37790:
URL: https://github.com/apache/superset/pull/37790#discussion_r2782886057
##########
superset-frontend/playwright/tests/experimental/localization/filter-name-localization.spec.ts:
##########
@@ -0,0 +1,209 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import { test, expect } from '@playwright/test';
+import {
+ apiPutDashboard,
+ apiDeleteDashboard,
+ createTestDashboard,
+} from '../../../helpers/api/dashboard';
+import {
+ createTestVirtualDataset,
+ apiDeleteDataset,
+} from '../../../helpers/api/dataset';
+import {
+ createTestDatabase,
+ apiDeleteDatabase,
+} from '../../../helpers/api/database';
+import { DashboardPage } from '../../../pages/DashboardPage';
+import { TIMEOUT } from '../../../utils/constants';
+
+/**
+ * Native Filter Name Localization E2E Tests
+ *
+ * Verifies that native filter names on a dashboard are displayed in the
+ * user's session locale when translations exist in the filter configuration.
+ *
+ * Prerequisites:
+ * - Superset running with ENABLE_CONTENT_LOCALIZATION = True
+ * - Multiple LANGUAGES configured in superset_config.py
+ * - Admin user authenticated (via global-setup)
+ */
+
+const ORIGINAL_FILTER_NAME = 'Year Filter';
+const GERMAN_FILTER_NAME = 'Jahresfilter';
+
+// File-scope state (reset in beforeEach)
+let testResources: {
+ dashboardIds: number[];
+ datasetIds: number[];
+ databaseIds: number[];
+};
+
+test.beforeEach(async () => {
+ testResources = { dashboardIds: [], datasetIds: [], databaseIds: [] };
+});
+
+test.afterEach(async ({ page }) => {
+ // Reset locale to English
+ await page.request.get('lang/en', { maxRedirects: 0 }).catch(() => {});
+
+ // Sequential per group to respect FK constraints
+ await Promise.all(
+ testResources.dashboardIds.map(id =>
+ apiDeleteDashboard(page, id, { failOnStatusCode: false }).catch(e =>
+ console.warn(`[Cleanup] dashboard ${id}:`, String(e)),
+ ),
+ ),
+ );
+ await Promise.all(
+ testResources.datasetIds.map(id =>
+ apiDeleteDataset(page, id, { failOnStatusCode: false }).catch(e =>
+ console.warn(`[Cleanup] dataset ${id}:`, String(e)),
+ ),
+ ),
+ );
+ await Promise.all(
+ testResources.databaseIds.map(id =>
+ apiDeleteDatabase(page, id, { failOnStatusCode: false }).catch(e =>
+ console.warn(`[Cleanup] database ${id}:`, String(e)),
+ ),
+ ),
+ );
+});
+
+/**
+ * Build json_metadata with a native filter that has translations.
+ */
+function buildFilterMetadata(
+ datasetId: number,
+ filterName: string,
+ translations: Record<string, string>,
+): string {
+ return JSON.stringify({
+ native_filter_configuration: [
+ {
+ id: 'NATIVE_FILTER-test1',
+ name: filterName,
+ filterType: 'filter_select',
+ targets: [{ datasetId, column: { name: 'id' } }],
+ defaultDataMask: { filterState: {} },
+ controlValues: {
+ enableEmptyFilter: false,
+ multiSelect: true,
+ inverseSelection: false,
+ },
+ cascadeParentIds: [],
+ scope: { rootPath: ['ROOT_ID'], excluded: [] },
+ translations: { name: translations },
+ },
+ ],
+ show_native_filters: true,
+ });
+}
+
+test('should display localized filter name on dashboard when session locale has translation', async ({
+ page,
+}) => {
+ const suffix = Date.now();
+
+ // 1. Create test database and virtual dataset (filter needs a valid datasource)
+ const dbId = await createTestDatabase(page, `test_filter_loc_db_${suffix}`);
+ expect(dbId).not.toBeNull();
+ testResources.databaseIds.push(dbId!);
+
+ const datasetId = await createTestVirtualDataset(
+ page,
+ `test_filter_loc_ds_${suffix}`,
+ dbId!,
+ );
+ expect(datasetId).not.toBeNull();
+ testResources.datasetIds.push(datasetId!);
+
+ // 2. Create dashboard with native filter + German translation
+ const dashboardTitle = `test_dash_filter_loc_${suffix}`;
+ const dashboardId = await createTestDashboard(page, dashboardTitle);
+ expect(dashboardId).not.toBeNull();
+ testResources.dashboardIds.push(dashboardId!);
+
+ const putRes = await apiPutDashboard(page, dashboardId!, {
+ json_metadata: buildFilterMetadata(datasetId!, ORIGINAL_FILTER_NAME, {
+ de: GERMAN_FILTER_NAME,
+ }),
+ });
+ expect(putRes.ok()).toBe(true);
+
+ // 3. Switch session locale to German
+ await page.request.get('lang/de', { maxRedirects: 0 });
+
+ // 4. Navigate to dashboard
+ const dashboardPage = new DashboardPage(page);
+ await dashboardPage.gotoById(dashboardId!);
+ await dashboardPage.waitForLoad({ timeout: TIMEOUT.PAGE_LOAD });
+
+ // 5. Verify filter name is localized
+ const filterName = page.locator('[data-test="filter-control-name"]').first();
+ await expect(filterName).toContainText(GERMAN_FILTER_NAME, {
+ timeout: TIMEOUT.API_RESPONSE,
+ });
+});
+
+test('should display original filter name when session locale has no translation', async ({
+ page,
+}) => {
+ const suffix = Date.now();
+
+ // 1. Create test database and virtual dataset
+ const dbId = await createTestDatabase(page, `test_filter_orig_db_${suffix}`);
+ expect(dbId).not.toBeNull();
+ testResources.databaseIds.push(dbId!);
+
+ const datasetId = await createTestVirtualDataset(
+ page,
+ `test_filter_orig_ds_${suffix}`,
+ dbId!,
+ );
+ expect(datasetId).not.toBeNull();
+ testResources.datasetIds.push(datasetId!);
+
+ // 2. Create dashboard with native filter + only German translation
+ const dashboardTitle = `test_dash_filter_orig_${suffix}`;
+ const dashboardId = await createTestDashboard(page, dashboardTitle);
+ expect(dashboardId).not.toBeNull();
+ testResources.dashboardIds.push(dashboardId!);
+
+ await apiPutDashboard(page, dashboardId!, {
+ json_metadata: buildFilterMetadata(datasetId!, ORIGINAL_FILTER_NAME, {
+ de: GERMAN_FILTER_NAME,
+ }),
+ });
Review Comment:
**Suggestion:** In the "no translation" filter name test, the PUT that updates the dashboard's `json_metadata` is not validated, so if the request fails (e.g., bad filter config) the test will only fail later when asserting the UI, making it harder to detect and diagnose the real error. [possible bug]
<details>
<summary><b>Severity Level:</b> Major ⚠️</summary>
```mdx
- ⚠️ Filter-name fallback E2E test can hide dashboard API failures.
- ⚠️ Debugging localization regressions becomes harder due to opaque errors.
```
</details>
```suggestion
const putRes = await apiPutDashboard(page, dashboardId!, {
json_metadata: buildFilterMetadata(datasetId!, ORIGINAL_FILTER_NAME, {
de: GERMAN_FILTER_NAME,
}),
});
expect(putRes.ok()).toBe(true);
```
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. Execute the Playwright test `should display original filter name when session locale
has no translation` in
`superset-frontend/playwright/tests/experimental/localization/filter-name-localization.spec.ts`
(lines 167–209).
2. Within this test, a dashboard is created (lines 185–189), then `apiPutDashboard` is
called at lines 191–195 to update `json_metadata` with a native filter and German
translation, but the returned `APIResponse` is ignored.
3. If the underlying dashboard update endpoint used by `apiPutDashboard` (implemented in
`superset-frontend/playwright/helpers/api/dashboard.ts`, see surrounding helpers like
`apiDeleteDashboard` at lines 104–110) starts returning a non-OK status for this payload
(for example due to a regression in json_metadata validation), the test will still proceed
to switch locale and open the dashboard (lines 197–203).
4. The final assertion at lines 205–208 uses
`page.locator('[data-test="filter-control-name"]').first()` and
`expect(...).toContainText(ORIGINAL_FILTER_NAME, ...)`; this will fail with a generic
locator timeout or text mismatch instead of clearly surfacing the failed PUT, making the
root cause (API failure) harder to diagnose. Adding `expect(putRes.ok()).toBe(true)`
immediately after the PUT would fail fast with an explicit API error.
```
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset-frontend/playwright/tests/experimental/localization/filter-name-localization.spec.ts
**Line:** 191:195
**Comment:**
*Possible Bug: In the "no translation" filter name test, the PUT that updates the dashboard's `json_metadata` is not validated, so if the request fails (e.g., bad filter config) the test will only fail later when asserting the UI, making it harder to detect and diagnose the real error.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=43c45ca542254c078c49863040d70507c374a1db2fec342ede42adb44614691d&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=43c45ca542254c078c49863040d70507c374a1db2fec342ede42adb44614691d&reaction=dislike'>👎</a>
##########
superset-frontend/playwright/helpers/api/chart.ts:
##########
@@ -0,0 +1,153 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import { Page, APIResponse } from '@playwright/test';
+import {
+ apiGet,
+ apiPost,
+ apiPut,
+ apiDelete,
+ ApiRequestOptions,
+} from './requests';
+
+export const ENDPOINTS = {
+ CHART: 'api/v1/chart/',
+} as const;
+
+/** Payload for POST /api/v1/chart/ */
+export interface ChartCreatePayload {
+ slice_name: string;
+ datasource_id: number;
+ datasource_type: string;
+ viz_type?: string;
+ owners?: number[];
+ dashboards?: number[];
+ params?: string;
+}
+
+/** Payload for PUT /api/v1/chart/{id} */
+export interface ChartUpdatePayload {
+ slice_name?: string;
+ owners?: number[];
+ dashboards?: number[];
+ translations?: Record<string, Record<string, string>>;
+}
+
+/** Chart data shape from API responses */
+export interface ChartResult {
+ id: number;
+ uuid: string;
+ slice_name: string;
+ viz_type?: string;
+ translations?: Record<string, Record<string, string>>;
+ available_locales?: string[];
+}
+
+/**
+ * POST /api/v1/chart/
+ * Creates a new chart.
+ */
+export async function apiPostChart(
+ page: Page,
+ payload: ChartCreatePayload,
+): Promise<APIResponse> {
+ return apiPost(page, ENDPOINTS.CHART, payload);
+}
+
+/**
+ * GET /api/v1/chart/{id}
+ * Fetches chart details.
+ */
+export async function apiGetChart(
+ page: Page,
+ chartId: number,
+ options?: ApiRequestOptions,
+): Promise<APIResponse> {
+ return apiGet(page, `${ENDPOINTS.CHART}${chartId}`, options);
+}
+
+/**
+ * PUT /api/v1/chart/{id}
+ * Updates chart fields including translations.
+ */
+export async function apiPutChart(
+ page: Page,
+ chartId: number,
+ data: ChartUpdatePayload,
+ options?: ApiRequestOptions,
+): Promise<APIResponse> {
+ return apiPut(page, `${ENDPOINTS.CHART}${chartId}`, data, options);
+}
+
+/**
+ * DELETE /api/v1/chart/{id}
+ * Removes a chart.
+ */
+export async function apiDeleteChart(
+ page: Page,
+ chartId: number,
+ options?: ApiRequestOptions,
+): Promise<APIResponse> {
+ return apiDelete(page, `${ENDPOINTS.CHART}${chartId}`, options);
+}
+
+/**
+ * Creates a minimal chart for testing.
+ * Requires a datasource (use createTestVirtualDataset first).
+ * Fetches UUID via GET after creation (not in POST response).
+ * @returns Chart ID and UUID, or null on failure.
+ */
+export async function createTestChart(
+ page: Page,
+ sliceName: string,
+ datasourceId: number,
+): Promise<{ id: number; uuid: string } | null> {
+ const response = await apiPostChart(page, {
+ slice_name: sliceName,
+ datasource_id: datasourceId,
+ datasource_type: 'table',
+ viz_type: 'table',
+ owners: [],
+ });
Review Comment:
**Suggestion:** The helper `createTestChart` is documented to return `null` on failure and checks `response.ok()`, but it calls `apiPostChart`/`apiPost` with the default `failOnStatusCode: true`, so any non-2xx status will cause Playwright to throw before reaching the `ok()` check, resulting in an unhandled exception instead of a graceful `null` return. [possible bug]
<details>
<summary><b>Severity Level:</b> Major ⚠️</summary>
```mdx
- ⚠️ Tests using createTestChart crash on non-2xx responses.
- ⚠️ Helper contract "null on failure" not actually respected.
```
</details>
```suggestion
const response = await apiPost(page, ENDPOINTS.CHART, {
slice_name: sliceName,
datasource_id: datasourceId,
datasource_type: 'table',
viz_type: 'table',
owners: [],
}, { failOnStatusCode: false });
```
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. In a Playwright test, call `createTestChart(page, sliceName, datasourceId)` from
`superset-frontend/playwright/helpers/api/chart.ts:116` with a `datasourceId` or payload
that causes the backend `/api/v1/chart/` endpoint to return a 4xx/5xx response (e.g.,
nonexistent datasource).
2. `createTestChart` calls `apiPostChart` at
`superset-frontend/playwright/helpers/api/chart.ts:66`, which in turn calls `apiPost(page,
ENDPOINTS.CHART, payload)` from
`superset-frontend/playwright/helpers/api/requests.ts:121-135` without passing any
options.
3. Inside `apiPost`, the request is sent via `page.request.post(url, { data, headers,
params, failOnStatusCode: options?.failOnStatusCode ?? true })` (see
`requests.ts:127-135`), so `failOnStatusCode` is `true` for this call.
4. When the backend responds with a non-2xx status, Playwright throws from
`page.request.post` due to `failOnStatusCode: true`, so execution never reaches the `if
(!response.ok()) { ... return null; }` block in `createTestChart`, and the caller observes
an unhandled exception instead of the documented `null` return on failure.
```
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset-frontend/playwright/helpers/api/chart.ts
**Line:** 121:127
**Comment:**
*Possible Bug: The helper `createTestChart` is documented to return `null` on failure and checks `response.ok()`, but it calls `apiPostChart`/`apiPost` with the default `failOnStatusCode: true`, so any non-2xx status will cause Playwright to throw before reaching the `ok()` check, resulting in an unhandled exception instead of a graceful `null` return.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=77082fbd22a8c3460745c7393e517b82332a628146ead483df76a099ddfc2923&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=77082fbd22a8c3460745c7393e517b82332a628146ead483df76a099ddfc2923&reaction=dislike'>👎</a>
##########
superset-frontend/src/dashboard/components/nativeFilters/FiltersConfigModal/FiltersConfigForm/FiltersConfigForm.tsx:
##########
@@ -569,6 +585,109 @@ const FiltersConfigForm = (
[filterId, form, formChanged],
);
+ const localizationEnabled = isFeatureEnabled(
+ FeatureFlag.EnableContentLocalization,
+ );
+
+ const currentTranslations: Translations =
+ formFilter?.translations ?? filterToEdit?.translations ?? {};
+
+ useEffect(() => {
+ if (filterToEdit?.translations) {
+ setNativeFilterFieldValues(form, filterId, {
+ translations: filterToEdit.translations,
+ });
+ }
+ }, [filterId, filterToEdit?.translations, form]);
+
+ useEffect(() => {
+ if (localizationEnabled) {
+ SupersetClient.get({
+ endpoint: '/api/v1/localization/available_locales',
+ }).then(
+ response => {
+ const { locales, default_locale } = response.json.result;
+ setAllLocales(locales);
+ setDefaultLocale(default_locale);
+ },
+ err => logging.error('Failed to fetch available locales', err),
+ );
+ }
+ }, [localizationEnabled]);
+
+ // Refs for values read during initialization but not triggering re-runs.
+ // Without refs, editing a translation would reset the active locale
+ // because currentTranslations changes on every keystroke.
+ const currentTranslationsRef = useRef(currentTranslations);
+ currentTranslationsRef.current = currentTranslations;
+ const userLocaleRef = useRef(userLocale);
+ userLocaleRef.current = userLocale;
+
+ // Initialize nameActiveLocale when switching between filters.
+ useEffect(() => {
+ if (
+ localizationEnabled &&
+ currentTranslationsRef.current.name?.[userLocaleRef.current]
+ ) {
+ setNameActiveLocale(userLocaleRef.current);
+ } else {
+ setNameActiveLocale(DEFAULT_LOCALE_KEY);
+ }
+ }, [localizationEnabled, filterId]);
+
+ const handleNameTranslationChange = useCallback(
+ (value: string) => {
+ const updated: Translations = {
+ ...currentTranslationsRef.current,
+ name: { ...currentTranslationsRef.current.name, [nameActiveLocale]: value },
Review Comment:
**Suggestion:** When creating the updated translations object, spreading `currentTranslationsRef.current.name` directly will throw a runtime TypeError if `name` is undefined (i.e., when there are no existing name translations), because object spread cannot operate on `undefined` or `null`; you should default it to an empty object before spreading. [type error]
<details>
<summary><b>Severity Level:</b> Critical 🚨</summary>
```mdx
- ❌ Editing filter name translations crashes native filters configuration.
- ⚠️ Localization feature unstable for dashboard native filter editors.
```
</details>
```suggestion
name: {
...(currentTranslationsRef.current.name ?? {}),
[nameActiveLocale]: value,
},
```
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. Enable the `ENABLE_CONTENT_LOCALIZATION` feature flag so
`isFeatureEnabled(FeatureFlag.EnableContentLocalization)` returns true in
`FiltersConfigForm.tsx` (around lines 210–260), making `localizationEnabled` true.
2. In the Superset UI, open any dashboard and launch the Native Filters configuration
modal, which renders the `FiltersConfigForm` component
(`superset-frontend/src/dashboard/components/nativeFilters/FiltersConfigModal/FiltersConfigForm/FiltersConfigForm.tsx`).
3. Create a new native filter or edit an existing one that has no `translations` saved
yet; on first render, `formFilter?.translations ?? filterToEdit?.translations ?? {}`
(lines ~585–595) yields `{}`, so `currentTranslations.name` is `undefined`.
4. In the filter configuration tab, use the inline `LocaleSwitcher` rendered in the name
field suffix (JSX block around lines ~720–760) to select a non-default locale, then type
in the translation input (rendered when `isEditingFilterTranslation` is true); this
triggers `handleNameTranslationChange` (lines 638–650), which executes `name: {
...currentTranslationsRef.current.name, [nameActiveLocale]: value }` with
`currentTranslationsRef.current.name === undefined`, causing a runtime `TypeError: Cannot
convert undefined or null to object` and breaking the modal.
```
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset-frontend/src/dashboard/components/nativeFilters/FiltersConfigModal/FiltersConfigForm/FiltersConfigForm.tsx
**Line:** 642:642
**Comment:**
*Type Error: When creating the updated translations object, spreading `currentTranslationsRef.current.name` directly will throw a runtime TypeError if `name` is undefined (i.e., when there are no existing name translations), because object spread cannot operate on `undefined` or `null`; you should default it to an empty object before spreading.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=39541a69e56192a41d3b49cb8804b12bc817b1a56e823183aca7679d0bf93259&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=39541a69e56192a41d3b49cb8804b12bc817b1a56e823183aca7679d0bf93259&reaction=dislike'>👎</a>
##########
superset-frontend/playwright/tests/experimental/localization/chart-title-localization.spec.ts:
##########
@@ -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 { test, expect } from '@playwright/test';
+import {
+ apiPutDashboard,
+ apiDeleteDashboard,
+ createTestDashboard,
+} from '../../../helpers/api/dashboard';
+import {
+ apiPutChart,
+ apiDeleteChart,
+ createTestChart,
+} from '../../../helpers/api/chart';
+import {
+ createTestVirtualDataset,
+ apiDeleteDataset,
+} from '../../../helpers/api/dataset';
+import {
+ createTestDatabase,
+ apiDeleteDatabase,
+} from '../../../helpers/api/database';
+import { DashboardPage } from '../../../pages/DashboardPage';
+import { TIMEOUT } from '../../../utils/constants';
+
+/**
+ * Chart Title Localization E2E Tests
+ *
+ * Verifies that chart titles on a dashboard are displayed in the
+ * user's session locale when translations exist on the chart.
+ *
+ * Prerequisites:
+ * - Superset running with ENABLE_CONTENT_LOCALIZATION = True
+ * - Multiple LANGUAGES configured in superset_config.py
+ * - Admin user authenticated (via global-setup)
+ */
+
+const GERMAN_CHART_TITLE = 'Deutscher Diagrammtitel';
+
+// File-scope state (reset in beforeEach)
+let testResources: {
+ dashboardIds: number[];
+ chartIds: number[];
+ datasetIds: number[];
+ databaseIds: number[];
+};
+
+test.beforeEach(async () => {
+ testResources = {
+ dashboardIds: [],
+ chartIds: [],
+ datasetIds: [],
+ databaseIds: [],
+ };
+});
+
+test.afterEach(async ({ page }) => {
+ // Reset locale to English
+ await page.request.get('lang/en', { maxRedirects: 0 }).catch(() => {});
+
+ // Cleanup in reverse creation order: charts → dashboards → datasets → databases
+ // Sequential per group to respect FK constraints
+ await Promise.all(
+ testResources.chartIds.map(id =>
+ apiDeleteChart(page, id, { failOnStatusCode: false }).catch(e =>
+ console.warn(`[Cleanup] chart ${id}:`, String(e)),
+ ),
+ ),
+ );
+ await Promise.all(
+ testResources.dashboardIds.map(id =>
+ apiDeleteDashboard(page, id, { failOnStatusCode: false }).catch(e =>
+ console.warn(`[Cleanup] dashboard ${id}:`, String(e)),
+ ),
+ ),
+ );
+ await Promise.all(
+ testResources.datasetIds.map(id =>
+ apiDeleteDataset(page, id, { failOnStatusCode: false }).catch(e =>
+ console.warn(`[Cleanup] dataset ${id}:`, String(e)),
+ ),
+ ),
+ );
+ await Promise.all(
+ testResources.databaseIds.map(id =>
+ apiDeleteDatabase(page, id, { failOnStatusCode: false }).catch(e =>
+ console.warn(`[Cleanup] database ${id}:`, String(e)),
+ ),
+ ),
+ );
+});
+
+/**
+ * Build minimal position_json with a single chart component.
+ */
+function buildPositionJson(
+ chartId: number,
+ chartUuid: string,
+ sliceName: string,
+ dashboardTitle: string,
+): string {
+ return JSON.stringify({
+ DASHBOARD_VERSION_KEY: 'v2',
+ ROOT_ID: { type: 'ROOT', id: 'ROOT_ID', children: ['GRID_ID'] },
+ GRID_ID: {
+ type: 'GRID',
+ id: 'GRID_ID',
+ children: ['ROW-test1'],
+ },
+ HEADER_ID: {
+ type: 'HEADER',
+ id: 'HEADER_ID',
+ meta: { text: dashboardTitle },
+ },
+ 'ROW-test1': {
+ type: 'ROW',
+ id: 'ROW-test1',
+ children: ['CHART-test1'],
+ meta: { background: 'BACKGROUND_TRANSPARENT' },
+ },
+ 'CHART-test1': {
+ type: 'CHART',
+ id: 'CHART-test1',
+ children: [],
+ meta: {
+ chartId,
+ sliceName,
+ uuid: chartUuid,
+ width: 12,
+ height: 50,
+ },
+ },
+ });
+}
+
+test('should display localized chart title on dashboard when session locale has translation', async ({
+ page,
+}) => {
+ const suffix = Date.now();
+
+ // 1. Create test database and virtual dataset
+ const dbId = await createTestDatabase(page, `test_chart_loc_db_${suffix}`);
+ expect(dbId).not.toBeNull();
+ testResources.databaseIds.push(dbId!);
+
+ const datasetId = await createTestVirtualDataset(
+ page,
+ `test_chart_loc_ds_${suffix}`,
+ dbId!,
+ );
+ expect(datasetId).not.toBeNull();
+ testResources.datasetIds.push(datasetId!);
+
+ // 2. Create chart and dashboard
+ const originalTitle = `test_chart_loc_${suffix}`;
+ const chart = await createTestChart(page, originalTitle, datasetId!);
+ expect(chart).not.toBeNull();
+ testResources.chartIds.push(chart!.id);
+
+ const dashboardTitle = `test_dash_chart_loc_${suffix}`;
+ const dashboardId = await createTestDashboard(page, dashboardTitle);
+ expect(dashboardId).not.toBeNull();
+ testResources.dashboardIds.push(dashboardId!);
+
+ // 3. Associate chart with dashboard and set German translation
+ const putChartRes = await apiPutChart(page, chart!.id, {
+ dashboards: [dashboardId!],
+ translations: { slice_name: { de: GERMAN_CHART_TITLE } },
+ });
+ expect(putChartRes.ok()).toBe(true);
+
+ // 4. Set dashboard layout with the chart
+ const putDashRes = await apiPutDashboard(page, dashboardId!, {
+ position_json: buildPositionJson(
+ chart!.id,
+ chart!.uuid,
+ originalTitle,
+ dashboardTitle,
+ ),
+ });
+ expect(putDashRes.ok()).toBe(true);
+
+ // 5. Switch session locale to German
+ await page.request.get('lang/de', { maxRedirects: 0 });
+
+ // 6. Navigate to dashboard and verify localized chart title
+ const dashboardPage = new DashboardPage(page);
+ await dashboardPage.gotoById(dashboardId!);
+ await dashboardPage.waitForLoad({ timeout: TIMEOUT.PAGE_LOAD });
+
+ // Chart header should show German title
+ const chartHeader = page.locator('[data-test="slice-header"]').first();
+ await expect(chartHeader).toContainText(GERMAN_CHART_TITLE, {
+ timeout: TIMEOUT.API_RESPONSE,
+ });
+});
+
+test('should display original chart title when session locale has no translation', async ({
+ page,
+}) => {
+ const suffix = Date.now();
+
+ // 1. Create test database and virtual dataset
+ const dbId = await createTestDatabase(page, `test_chart_orig_db_${suffix}`);
+ expect(dbId).not.toBeNull();
+ testResources.databaseIds.push(dbId!);
+
+ const datasetId = await createTestVirtualDataset(
+ page,
+ `test_chart_orig_ds_${suffix}`,
+ dbId!,
+ );
+ expect(datasetId).not.toBeNull();
+ testResources.datasetIds.push(datasetId!);
+
+ // 2. Create chart and dashboard
+ const originalTitle = `test_chart_orig_${suffix}`;
+ const chart = await createTestChart(page, originalTitle, datasetId!);
+ expect(chart).not.toBeNull();
+ testResources.chartIds.push(chart!.id);
+
+ const dashboardTitle = `test_dash_chart_orig_${suffix}`;
+ const dashboardId = await createTestDashboard(page, dashboardTitle);
+ expect(dashboardId).not.toBeNull();
+ testResources.dashboardIds.push(dashboardId!);
+
+ // 3. Associate chart with dashboard and set German translation (no French)
+ await apiPutChart(page, chart!.id, {
+ dashboards: [dashboardId!],
+ translations: { slice_name: { de: GERMAN_CHART_TITLE } },
+ });
+
+ // Set dashboard layout
+ await apiPutDashboard(page, dashboardId!, {
+ position_json: buildPositionJson(
+ chart!.id,
+ chart!.uuid,
+ originalTitle,
+ dashboardTitle,
+ ),
+ });
Review Comment:
**Suggestion:** In the "no translation" chart title test, the PUT requests that associate the chart with the dashboard and update the dashboard layout are not checked for success, so if either call fails the test will later fail with a confusing UI assertion error instead of clearly failing at the API step. [possible bug]
<details>
<summary><b>Severity Level:</b> Major ⚠️</summary>
```mdx
- ⚠️ Localization E2E test can fail with misleading UI error.
- ⚠️ Backend regressions in chart/dashboard APIs may go unnoticed.
```
</details>
```suggestion
const putChartRes = await apiPutChart(page, chart!.id, {
dashboards: [dashboardId!],
translations: { slice_name: { de: GERMAN_CHART_TITLE } },
});
expect(putChartRes.ok()).toBe(true);
// Set dashboard layout
const putDashRes = await apiPutDashboard(page, dashboardId!, {
position_json: buildPositionJson(
chart!.id,
chart!.uuid,
originalTitle,
dashboardTitle,
),
});
expect(putDashRes.ok()).toBe(true);
```
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. Run the Playwright test file
`superset-frontend/playwright/tests/experimental/localization/chart-title-localization.spec.ts`,
focusing on the second test `test('should display original chart title when session locale
has no translation', ...)` defined near lines 214–271.
2. During this test, observe the API setup section at lines 243–257 where `apiPutChart`
and `apiPutDashboard` are awaited without checking their responses:
- `await apiPutChart(page, chart!.id, { ... })` at lines 244–247.
- `await apiPutDashboard(page, dashboardId!, { ... })` at lines 250–257.
3. If the Superset backend returns a non-2xx status for either call (for example due to a
temporary backend error or misconfigured `ENABLE_CONTENT_LOCALIZATION` feature flag),
these failures are silently ignored because the `Response` objects are not inspected or
asserted.
4. The test then proceeds to navigate to the dashboard and assert the chart title in the
UI at lines 259–270; because the chart–dashboard association or layout might not have been
persisted, the final `expect(chartHeader).toContainText(originalTitle, ...)` assertion
fails with a generic UI mismatch, obscuring the original API failure that actually caused
the problem.
```
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset-frontend/playwright/tests/experimental/localization/chart-title-localization.spec.ts
**Line:** 244:257
**Comment:**
*Possible Bug: In the "no translation" chart title test, the PUT requests that associate the chart with the dashboard and update the dashboard layout are not checked for success, so if either call fails the test will later fail with a confusing UI assertion error instead of clearly failing at the API step.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=590ff6d660901df5e7fa56497d2093f8621dec4963795d05c326da5091c43758&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=590ff6d660901df5e7fa56497d2093f8621dec4963795d05c326da5091c43758&reaction=dislike'>👎</a>
##########
superset-frontend/src/explore/components/PropertiesModal/index.tsx:
##########
@@ -258,6 +292,18 @@ function PropertiesModal({
// get the owners of this slice
useEffect(() => {
fetchChartProperties();
+ if (isFeatureEnabled(FeatureFlag.EnableContentLocalization)) {
+ SupersetClient.get({
+ endpoint: '/api/v1/localization/available_locales',
+ }).then(
+ response => {
+ const { locales, default_locale } = response.json.result;
+ setAllLocales(locales);
+ setDefaultLocale(default_locale);
+ },
+ err => logging.error('Failed to fetch available locales', err),
Review Comment:
**Suggestion:** The error handler for fetching available locales now only logs the failure and no longer calls the existing user-facing `showError` helper, so when this request fails the UI silently proceeds with empty locale data and gives no feedback to the user, which is inconsistent with other error paths and can leave localization controls misconfigured without explanation. [logic error]
<details>
<summary><b>Severity Level:</b> Major ⚠️</summary>
```mdx
- ⚠️ Locale list load failures are silent in chart properties modal.
- ⚠️ Translation controls may appear empty without user-facing explanation.
- ⚠️ Inconsistent error handling vs `fetchChartProperties` failures.
```
</details>
```suggestion
err => {
logging.error('Failed to fetch available locales', err);
getClientErrorObject(err).then(showError);
},
```
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. Enable the content localization feature flag so that
`FeatureFlag.EnableContentLocalization` is true on the frontend (this controls the
localization branch in `PropertiesModal` at
`superset-frontend/src/explore/components/PropertiesModal/index.tsx:289-307`).
2. In the running Superset instance, open the Explore view for any existing chart and open
the "Chart properties" modal, which renders the `PropertiesModal` component defined in
`superset-frontend/src/explore/components/PropertiesModal/index.tsx`.
3. While the modal is open, the `useEffect` hook at `index.tsx:289-307` runs, calling
`SupersetClient.get({ endpoint: '/api/v1/localization/available_locales' })` and attaching
the `.then(…, err => logging.error('Failed to fetch available locales', err))` handler at
`index.tsx:296-305`.
4. Cause the `/api/v1/localization/available_locales` request to fail (for example by
stopping the backend, misconfiguring the endpoint, or injecting a 500 in a proxy); observe
in the browser devtools console that an error is logged, but no toast is shown (unlike
other errors that go through `showError` at `index.tsx:153-163`), and the locale-related
state (`allLocales`, `defaultLocale`) remains at their initial empty values without any
user-facing explanation.
```
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset-frontend/src/explore/components/PropertiesModal/index.tsx
**Line:** 304:304
**Comment:**
*Logic Error: The error handler for fetching available locales now only logs the failure and no longer calls the existing user-facing `showError` helper, so when this request fails the UI silently proceeds with empty locale data and gives no feedback to the user, which is inconsistent with other error paths and can leave localization controls misconfigured without explanation.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=45d83989696a377b7381546725a109e3300326624a7ef1fc3a22fc652c265d1a&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=45d83989696a377b7381546725a109e3300326624a7ef1fc3a22fc652c265d1a&reaction=dislike'>👎</a>
##########
superset-frontend/src/dashboard/components/PropertiesModal/index.tsx:
##########
@@ -448,6 +481,19 @@ const PropertiesModal = ({
t('An error occurred while fetching available themes'),
);
});
+
+ if (isFeatureEnabled(FeatureFlag.EnableContentLocalization)) {
+ SupersetClient.get({
+ endpoint: '/api/v1/localization/available_locales',
+ }).then(
+ response => {
+ const { locales, default_locale } = response.json.result;
+ setAllLocales(locales);
+ setDefaultLocale(default_locale);
+ },
+ err => logging.error('Failed to fetch available locales', err),
Review Comment:
**Suggestion:** The error handler for the available locales request only logs to the console and does not surface any user-visible feedback, so when this API fails the locale switcher silently breaks with no locales loaded and no explanation to the user; reusing the existing error handler will restore consistent error reporting behavior. [logic error]
<details>
<summary><b>Severity Level:</b> Major ⚠️</summary>
```mdx
- ⚠️ Dashboard properties modal locale list fails silently on errors.
- ⚠️ Users see non-working locale switcher without any explanation.
- ⚠️ Inconsistent error handling versus other SupersetClient.get calls.
```
</details>
```suggestion
handleErrorResponse,
```
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. Enable the `EnableContentLocalization` feature flag so the localization-specific code
path is active (checked in `PropertiesModal` at
`superset-frontend/src/dashboard/components/PropertiesModal/index.tsx:485`).
2. Open the Dashboard "Properties" modal in the UI, which renders the `PropertiesModal`
component exported from
`superset-frontend/src/dashboard/components/PropertiesModal/index.tsx` and triggers the
`useEffect` starting around line 451 when `show` is true.
3. While the modal is open, cause the `/api/v1/localization/available_locales` request to
fail (for example, by using browser devtools to go offline or by having the backend return
a 500), so that the `SupersetClient.get` call at lines 485–494 rejects.
4. Observe that the rejection handler `err => logging.error('Failed to fetch available
locales', err)` at line 494 only logs the error (via `logging.error`) and does not invoke
`handleErrorResponse`, meaning no `addDangerToast` message is shown to the user even
though the locale list did not load and the locale switcher cannot function correctly.
```
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset-frontend/src/dashboard/components/PropertiesModal/index.tsx
**Line:** 494:494
**Comment:**
*Logic Error: The error handler for the available locales request only logs to the console and does not surface any user-visible feedback, so when this API fails the locale switcher silently breaks with no locales loaded and no explanation to the user; reusing the existing error handler will restore consistent error reporting behavior.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=7932963596ca91c38db47014f59c25ea3f620ae4d1f7b59b389495771a0acd0d&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=7932963596ca91c38db47014f59c25ea3f620ae4d1f7b59b389495771a0acd0d&reaction=dislike'>👎</a>
##########
superset/dashboards/schemas.py:
##########
@@ -257,8 +273,121 @@ def post_dump(self, serialized: dict[str, Any], **kwargs: Any) -> dict[str, Any]
del serialized["owners"]
del serialized["changed_by_name"]
del serialized["changed_by"]
+
+ # Apply content localization when feature is enabled
+ if is_feature_enabled("ENABLE_CONTENT_LOCALIZATION"):
+ self._apply_localization(serialized, obj)
+
return serialized
+ def _apply_localization(self, serialized: dict[str, Any], obj: Any) -> None:
Review Comment:
**Suggestion:** The translations validator treats the mere presence of the `translations` key as requiring structural validation, so when the field is explicitly set to null (which is allowed by the schema), it will pass `None` into `validate_translations`, likely causing a runtime error instead of cleanly accepting or ignoring the null value; this should short-circuit when the value is None. [logic error]
<details>
<summary><b>Severity Level:</b> Major ⚠️</summary>
```mdx
- ❌ Dashboard update fails when translations explicitly sent as null.
- ⚠️ Breaks API clients clearing translations using null payload.
```
</details>
```suggestion
translations = data.get("translations")
if translations is None:
return
if not is_feature_enabled("ENABLE_CONTENT_LOCALIZATION"):
raise ValidationError(
"Content localization is not enabled. "
"Set ENABLE_CONTENT_LOCALIZATION=True to use translations.",
field_name="translations",
)
validate_translations(translations)
```
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. Enable the `ENABLE_CONTENT_LOCALIZATION` feature flag in `superset/config.py`, then
start the Superset web server.
2. Call the dashboard update endpoint `PUT /api/v1/dashboard/<dashboard_id>` implemented
in `superset/dashboards/api.py` (DashboardRestApi), sending JSON that includes
`"translations": null` along with other valid dashboard fields.
3. The request payload is validated using `DashboardPutSchema` in
`superset/dashboards/schemas.py`, which invokes `validate_translations_data` during schema
validation.
4. Because the `translations` key is present with value `None`, `data["translations"]` is
`None`; with the feature flag enabled, `validate_translations(data["translations"])`
receives `None` instead of a dict, causing it to treat the value as invalid (or raise a
type error) even though the field is declared with `allow_none=True`, so clients that send
`null` cannot successfully update dashboards.
```
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset/dashboards/schemas.py
**Line:** 274:283
**Comment:**
*Logic Error: The translations validator treats the mere presence of the `translations` key as requiring structural validation, so when the field is explicitly set to null (which is allowed by the schema), it will pass `None` into `validate_translations`, likely causing a runtime error instead of cleanly accepting or ignoring the null value; this should short-circuit when the value is None.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=9c280d70c6558e038b7bee7b2cbf815035a4bad2b2975d16c4884182c85d4a65&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=9c280d70c6558e038b7bee7b2cbf815035a4bad2b2975d16c4884182c85d4a65&reaction=dislike'>👎</a>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #37790:
URL: https://github.com/apache/superset/pull/37790#issuecomment-6022155709
### ⚠️ Possible DB migration conflict
@YuriyKrasilnikov the base branch `master` picked up a new database migration under `superset/migrations/` after this PR was opened, and this PR adds or modifies migration files too. Alembic migrations form a single linear chain, so if both branch off the same parent revision, merging this PR as-is could leave the migration history with two heads instead of one, which makes `superset db upgrade` fail with `Multiple head revisions are present`.
To check and, if needed, fix this:
1. Rebase this branch onto the latest `master`.
2. Run `superset db heads`. If it lists more than one revision, you have a conflict.
3. In your new migration's script, update `down_revision` (and the `Revises` comment) to point at the other head instead, so the chain has a single head again.
See [Merging DB Migrations](https://superset.apache.org/docs/contributing/development#merging-db-migrations) in the contributing guide for a worked example.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "github-actions[bot] (via GitHub) via notifications" <no...@superset.apache.org>.
github-actions[bot] commented on PR #37790:
URL: https://github.com/apache/superset/pull/37790#issuecomment-7023952442
### ⚠️ Possible DB migration conflict
@YuriyKrasilnikov the base branch `master` picked up a new database migration under `superset/migrations/` after this PR was opened, and this PR adds or modifies migration files too. Alembic migrations form a single linear chain, so if both branch off the same parent revision, merging this PR as-is could leave the migration history with two heads instead of one, which makes `superset db upgrade` fail with `Multiple head revisions are present`.
To check and, if needed, fix this:
1. Rebase this branch onto the latest `master`.
2. Run `superset db heads`. If it lists more than one revision, you have a conflict.
3. In your new migration's script, update `down_revision` (and the `Revises` comment) to point at the other head instead, so the chain has a single head again.
See [Merging DB Migrations](https://superset.apache.org/docs/contributing/development#merging-db-migrations) in the contributing guide for a worked example.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #37790:
URL: https://github.com/apache/superset/pull/37790#issuecomment-3873102343
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers a full AI review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "YuriyKrasilnikov (via GitHub)" <gi...@apache.org>.
YuriyKrasilnikov commented on code in PR #37790:
URL: https://github.com/apache/superset/pull/37790#discussion_r2779278149
##########
superset/localization/api.py:
##########
@@ -0,0 +1,108 @@
+# 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.
+"""REST API for content localization configuration."""
+
+import logging
+
+from flask import current_app, Response
+from flask_appbuilder.api import expose, protect, safe
+
+from superset.constants import MODEL_API_RW_METHOD_PERMISSION_MAP
+from superset.extensions import event_logger
+from superset.localization.schemas import AvailableLocalesResponseSchema
+from superset.views.base_api import BaseSupersetApi, statsd_metrics
+
+logger = logging.getLogger(__name__)
+
+DEFAULT_LOCALE = "en"
+
+
+def get_available_locales_data() -> dict[str, list[dict[str, str]] | str]:
+ """
+ Build available locales response data from Flask config.
+
+ Reads LANGUAGES and BABEL_DEFAULT_LOCALE from current_app.config
+ and transforms to response format.
+
+ Returns:
+ Dict with 'locales' list and 'default_locale' string.
+ """
+ languages: dict[str, dict[str, str]] = current_app.config.get("LANGUAGES", {})
+ default_locale = current_app.config.get("BABEL_DEFAULT_LOCALE", DEFAULT_LOCALE)
+
+ # Transform dict to sorted list
+ locales = [
+ {"code": code, "name": meta["name"], "flag": meta["flag"]}
+ for code, meta in sorted(languages.items())
Review Comment:
False positive. `LANGUAGES` is a standard Flask-Babel config with a well-documented format — every entry is `{"flag": str, "name": str}` (see `config.py:421-436`, 15 entries, all identical structure).
Direct key access `meta["name"]` is intentional — fail-fast on misconfiguration rather than silently returning fallback values. If someone breaks the `LANGUAGES` format, the entire Flask-Babel layer (locale selection, UI translations) breaks too, not just this endpoint.
Adding `.get()` with defaults would mask config errors instead of surfacing them.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "YuriyKrasilnikov (via GitHub)" <gi...@apache.org>.
YuriyKrasilnikov commented on code in PR #37790:
URL: https://github.com/apache/superset/pull/37790#discussion_r2783884988
##########
superset-frontend/playwright/tests/experimental/localization/filter-name-localization.spec.ts:
##########
@@ -0,0 +1,209 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import { test, expect } from '@playwright/test';
+import {
+ apiPutDashboard,
+ apiDeleteDashboard,
+ createTestDashboard,
+} from '../../../helpers/api/dashboard';
+import {
+ createTestVirtualDataset,
+ apiDeleteDataset,
+} from '../../../helpers/api/dataset';
+import {
+ createTestDatabase,
+ apiDeleteDatabase,
+} from '../../../helpers/api/database';
+import { DashboardPage } from '../../../pages/DashboardPage';
+import { TIMEOUT } from '../../../utils/constants';
+
+/**
+ * Native Filter Name Localization E2E Tests
+ *
+ * Verifies that native filter names on a dashboard are displayed in the
+ * user's session locale when translations exist in the filter configuration.
+ *
+ * Prerequisites:
+ * - Superset running with ENABLE_CONTENT_LOCALIZATION = True
+ * - Multiple LANGUAGES configured in superset_config.py
+ * - Admin user authenticated (via global-setup)
+ */
+
+const ORIGINAL_FILTER_NAME = 'Year Filter';
+const GERMAN_FILTER_NAME = 'Jahresfilter';
+
+// File-scope state (reset in beforeEach)
+let testResources: {
+ dashboardIds: number[];
+ datasetIds: number[];
+ databaseIds: number[];
+};
+
+test.beforeEach(async () => {
+ testResources = { dashboardIds: [], datasetIds: [], databaseIds: [] };
+});
+
+test.afterEach(async ({ page }) => {
+ // Reset locale to English
+ await page.request.get('lang/en', { maxRedirects: 0 }).catch(() => {});
+
+ // Sequential per group to respect FK constraints
+ await Promise.all(
+ testResources.dashboardIds.map(id =>
+ apiDeleteDashboard(page, id, { failOnStatusCode: false }).catch(e =>
+ console.warn(`[Cleanup] dashboard ${id}:`, String(e)),
+ ),
+ ),
+ );
+ await Promise.all(
+ testResources.datasetIds.map(id =>
+ apiDeleteDataset(page, id, { failOnStatusCode: false }).catch(e =>
+ console.warn(`[Cleanup] dataset ${id}:`, String(e)),
+ ),
+ ),
+ );
+ await Promise.all(
+ testResources.databaseIds.map(id =>
+ apiDeleteDatabase(page, id, { failOnStatusCode: false }).catch(e =>
+ console.warn(`[Cleanup] database ${id}:`, String(e)),
+ ),
+ ),
+ );
+});
+
+/**
+ * Build json_metadata with a native filter that has translations.
+ */
+function buildFilterMetadata(
+ datasetId: number,
+ filterName: string,
+ translations: Record<string, string>,
+): string {
+ return JSON.stringify({
+ native_filter_configuration: [
+ {
+ id: 'NATIVE_FILTER-test1',
+ name: filterName,
+ filterType: 'filter_select',
+ targets: [{ datasetId, column: { name: 'id' } }],
+ defaultDataMask: { filterState: {} },
+ controlValues: {
+ enableEmptyFilter: false,
+ multiSelect: true,
+ inverseSelection: false,
+ },
+ cascadeParentIds: [],
+ scope: { rootPath: ['ROOT_ID'], excluded: [] },
+ translations: { name: translations },
+ },
+ ],
+ show_native_filters: true,
+ });
+}
+
+test('should display localized filter name on dashboard when session locale has translation', async ({
+ page,
+}) => {
+ const suffix = Date.now();
+
+ // 1. Create test database and virtual dataset (filter needs a valid datasource)
+ const dbId = await createTestDatabase(page, `test_filter_loc_db_${suffix}`);
+ expect(dbId).not.toBeNull();
+ testResources.databaseIds.push(dbId!);
+
+ const datasetId = await createTestVirtualDataset(
+ page,
+ `test_filter_loc_ds_${suffix}`,
+ dbId!,
+ );
+ expect(datasetId).not.toBeNull();
+ testResources.datasetIds.push(datasetId!);
+
+ // 2. Create dashboard with native filter + German translation
+ const dashboardTitle = `test_dash_filter_loc_${suffix}`;
+ const dashboardId = await createTestDashboard(page, dashboardTitle);
+ expect(dashboardId).not.toBeNull();
+ testResources.dashboardIds.push(dashboardId!);
+
+ const putRes = await apiPutDashboard(page, dashboardId!, {
+ json_metadata: buildFilterMetadata(datasetId!, ORIGINAL_FILTER_NAME, {
+ de: GERMAN_FILTER_NAME,
+ }),
+ });
+ expect(putRes.ok()).toBe(true);
+
+ // 3. Switch session locale to German
+ await page.request.get('lang/de', { maxRedirects: 0 });
+
+ // 4. Navigate to dashboard
+ const dashboardPage = new DashboardPage(page);
+ await dashboardPage.gotoById(dashboardId!);
+ await dashboardPage.waitForLoad({ timeout: TIMEOUT.PAGE_LOAD });
+
+ // 5. Verify filter name is localized
+ const filterName = page.locator('[data-test="filter-control-name"]').first();
+ await expect(filterName).toContainText(GERMAN_FILTER_NAME, {
+ timeout: TIMEOUT.API_RESPONSE,
+ });
+});
+
+test('should display original filter name when session locale has no translation', async ({
+ page,
+}) => {
+ const suffix = Date.now();
+
+ // 1. Create test database and virtual dataset
+ const dbId = await createTestDatabase(page, `test_filter_orig_db_${suffix}`);
+ expect(dbId).not.toBeNull();
+ testResources.databaseIds.push(dbId!);
+
+ const datasetId = await createTestVirtualDataset(
+ page,
+ `test_filter_orig_ds_${suffix}`,
+ dbId!,
+ );
+ expect(datasetId).not.toBeNull();
+ testResources.datasetIds.push(datasetId!);
+
+ // 2. Create dashboard with native filter + only German translation
+ const dashboardTitle = `test_dash_filter_orig_${suffix}`;
+ const dashboardId = await createTestDashboard(page, dashboardTitle);
+ expect(dashboardId).not.toBeNull();
+ testResources.dashboardIds.push(dashboardId!);
+
+ await apiPutDashboard(page, dashboardId!, {
+ json_metadata: buildFilterMetadata(datasetId!, ORIGINAL_FILTER_NAME, {
+ de: GERMAN_FILTER_NAME,
+ }),
+ });
Review Comment:
Same as above. \`apiPutDashboard\` defaults to \`failOnStatusCode: true\` (\`requests.ts:153\`), so Playwright throws on non-2xx automatically. The \`await\` line fails the test immediately — there is no scenario where the PUT silently fails and the test proceeds to UI assertions.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #37790:
URL: https://github.com/apache/superset/pull/37790#discussion_r2820584918
##########
superset-frontend/src/explore/components/controls/DndColumnSelectControl/DndColumnSelectPopoverTitle.tsx:
##########
@@ -36,58 +55,202 @@ const StyledInput = styled(Input)`
border-color: ${({ theme }) => theme.colorSplit};
`;
+const StyledTranslationInput = styled(TranslationInput)`
+ border-radius: ${({ theme }) => theme.borderRadius};
+ height: 26px;
+ padding-left: ${({ theme }) => theme.sizeUnit * 2.5}px;
+`;
+
export const DndColumnSelectPopoverTitle = ({
title,
onChange,
isEditDisabled,
hasCustomLabel,
+ translations,
+ onTranslationsChange,
}: DndColumnSelectPopoverTitleProps) => {
const theme = useTheme();
const [isHovered, setIsHovered] = useState(false);
const [isEditMode, setIsEditMode] = useState(false);
- const onMouseOver = useCallback(() => {
- setIsHovered(true);
- }, []);
+ const localizationEnabled = isFeatureEnabled(
+ FeatureFlag.EnableContentLocalization,
+ );
+ const showLocale =
+ localizationEnabled &&
+ hasCustomLabel &&
+ onTranslationsChange !== undefined;
- const onMouseOut = useCallback(() => {
- setIsHovered(false);
- }, []);
+ const [allLocales, setAllLocales] = useState<LocaleInfo[]>([]);
+ const [defaultLocale, setDefaultLocale] = useState('');
+ const userLocale: string = useSelector(
+ (state: { common: { locale: string } }) => state.common.locale,
+ );
+ const [activeLocale, setActiveLocale] = useState(DEFAULT_LOCALE_KEY);
+ const [localesLoaded, setLocalesLoaded] = useState(false);
+
+ const translationsRef = useRef(translations);
+ translationsRef.current = translations;
+
+ useEffect(() => {
+ if (!showLocale) return;
+ SupersetClient.get({
+ endpoint: '/api/v1/localization/available_locales',
+ }).then(
+ response => {
+ const { locales, default_locale } = response.json.result;
+ setAllLocales(locales);
+ setDefaultLocale(default_locale);
+ setLocalesLoaded(true);
+ },
+ err => logging.error('Failed to fetch available locales', err),
+ );
+ }, [showLocale]);
+
+ useEffect(() => {
+ if (!localesLoaded || !userLocale) return;
+ const labelTranslations = translationsRef.current?.label;
+ if (labelTranslations?.[userLocale]) {
+ setActiveLocale(userLocale);
+ } else {
+ setActiveLocale(DEFAULT_LOCALE_KEY);
+ }
+ }, [localesLoaded, userLocale]);
- const onClick = useCallback(() => {
- setIsEditMode(true);
+ const isLocaleMode = activeLocale !== DEFAULT_LOCALE_KEY;
+ const localeReady = showLocale && allLocales.length > 0;
+
+ const dropdownOpenRef = useRef(false);
+ const inputRef = useRef<InputRef>(null);
+
+ const handleDropdownOpenChange = useCallback((open: boolean) => {
+ if (open) {
+ dropdownOpenRef.current = true;
+ } else {
+ requestAnimationFrame(() => {
+ dropdownOpenRef.current = false;
+ inputRef.current?.focus();
+ });
+ }
}, []);
+ const onMouseOver = useCallback(() => setIsHovered(true), []);
+ const onMouseOut = useCallback(() => setIsHovered(false), []);
+ const onClick = useCallback(() => setIsEditMode(true), []);
+
const onBlur = useCallback(() => {
+ if (dropdownOpenRef.current) return;
setIsEditMode(false);
}, []);
const onInputBlur = useCallback(
- e => {
+ (e: React.FocusEvent<HTMLInputElement>) => {
+ if (dropdownOpenRef.current) return;
if (e.target.value === '') {
onChange(e);
}
- onBlur();
+ setIsEditMode(false);
+ },
+ [onChange],
+ );
+
+ const handleTranslationValue = useCallback(
+ (value: string) => {
+ onTranslationsChange?.({
+ ...translationsRef.current,
+ label: {
Review Comment:
**Suggestion:** When updating translations, the code spreads `translationsRef.current` directly; if no translations exist yet this is `undefined`, and spreading it will throw a runtime TypeError the first time a translation is edited. Use a default empty object when `translationsRef.current` is undefined so the spread is always safe. [type error]
<details>
<summary><b>Severity Level:</b> Critical 🚨</summary>
```mdx
- ❌ First-time column label translation edit throws runtime TypeError.
- ⚠️ Column localization UI breaks until user refreshes page.
```
</details>
```suggestion
...(translationsRef.current ?? {}),
```
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. Ensure frontend is built with this PR code and feature flag
`ENABLE_CONTENT_LOCALIZATION` is enabled so
`isFeatureEnabled(FeatureFlag.EnableContentLocalization)` returns true in
`DndColumnSelectPopoverTitle`
(`superset-frontend/src/explore/components/controls/DndColumnSelectControl/DndColumnSelectPopoverTitle.tsx`).
2. Navigate to a view that renders `DndColumnSelectPopoverTitle` for a column with a
custom label and localization enabled (parent passes `hasCustomLabel={true}`,
`onTranslationsChange={...}`, and either omits `translations` or passes it as `undefined`,
which is the state for columns with no saved translations yet).
3. In the UI, click the column label to enter edit mode, use the inline `LocaleSwitcher`
(rendered via `localeSwitcher` in the same file) to switch from `DEFAULT` to a non-default
locale so that the locale-specific `<StyledTranslationInput>` is shown with
`onChange={handleTranslationValue}` (see final file state, `StyledTranslationInput`
usage).
4. Type any character into the translation input; this calls `handleTranslationValue`
which executes `onTranslationsChange?.({ ...translationsRef.current, ... })` at lines
160–166 while `translationsRef.current` is still `undefined`, causing
`...translationsRef.current` to throw `TypeError: Cannot convert undefined or null to
object` and breaking the React component for that control.
```
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset-frontend/src/explore/components/controls/DndColumnSelectControl/DndColumnSelectPopoverTitle.tsx
**Line:** 161:161
**Comment:**
*Type Error: When updating translations, the code spreads `translationsRef.current` directly; if no translations exist yet this is `undefined`, and spreading it will throw a runtime TypeError the first time a translation is edited. Use a default empty object when `translationsRef.current` is undefined so the spread is always safe.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=6b2e64b56d49b99dd781d78dcd389c937d3587a0080fbe5f17c9398fc7aecc75&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=6b2e64b56d49b99dd781d78dcd389c937d3587a0080fbe5f17c9398fc7aecc75&reaction=dislike'>👎</a>
##########
superset-frontend/src/components/TranslationEditor/LocaleSwitcher.tsx:
##########
@@ -0,0 +1,253 @@
+/**
+ * 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 { useCallback, useMemo, useState } from 'react';
+import type { MenuProps } from 'antd';
+import { t } from '@apache-superset/core';
+import { css, useTheme } from '@apache-superset/core/ui';
+import {
+ Badge,
+ Dropdown,
+ Icons,
+} from '@superset-ui/core/components';
+import type { Translations, LocaleInfo } from 'src/types/Localization';
+import { DEFAULT_LOCALE_KEY, countFieldTranslations } from './utils';
+
+export interface LocaleSwitcherProps {
+ /** Translation field key (e.g., 'dashboard_title', 'slice_name'). */
+ fieldName: string;
+ /** Current default (column) value — used for ✓ indicator on DEFAULT. */
+ defaultValue: string;
+ /** Full translations object for the entity. */
+ translations: Translations;
+ /** All configured locales from server (including default locale). */
+ allLocales: LocaleInfo[];
+ /** Server's default locale code (e.g., 'en'). */
+ defaultLocale: string;
+ /** Current user's UI locale code from session. */
+ userLocale: string;
+ /** Currently active locale. Controlled by parent. */
+ activeLocale: string;
+ /** Called when user picks a locale from the dropdown. */
+ onLocaleChange: (locale: string) => void;
+ /** Human-readable field label for accessibility (e.g., 'Dashboard Title'). */
+ fieldLabel: string;
+ /** When false, renders as a read-only indicator without dropdown. Default true. */
+ interactive?: boolean;
+ /** Called when the dropdown opens or closes. */
+ onDropdownOpenChange?: (open: boolean) => void;
+}
+
+/**
+ * Inline locale dropdown rendered as an Input suffix.
+ *
+ * Displays the currently active locale (DEFAULT or a specific language)
+ * with a badge showing translation count. Click opens a dropdown to
+ * switch between DEFAULT text and per-locale translations.
+ *
+ * Yellow highlight indicates the user's locale has no translation.
+ */
+export default function LocaleSwitcher({
+ fieldName,
+ defaultValue,
+ translations,
+ allLocales,
+ defaultLocale,
+ userLocale,
+ activeLocale,
+ onLocaleChange,
+ fieldLabel,
+ interactive = true,
+ onDropdownOpenChange,
+}: LocaleSwitcherProps) {
+ const theme = useTheme();
+
+ const fieldTranslations = translations[fieldName] ?? {};
+ const translationCount = countFieldTranslations(translations, fieldName);
+
+ const userLocaleHasTranslation =
+ userLocale === defaultLocale || Boolean(fieldTranslations[userLocale]);
Review Comment:
**Suggestion:** The warning highlight logic only checks for an exact `userLocale` match in `fieldTranslations`, but `getLocalizedValue` falls back from regional locales like `de-AT` to their base language `de`; this means the LocaleSwitcher will incorrectly show a warning for users with regional locale codes even when a base-language translation exists and is actually used. Update `userLocaleHasTranslation` to consider the base language (substring before `-`) when no exact match is present so the warning state matches the real localization behavior. [logic error]
<details>
<summary><b>Severity Level:</b> Major ⚠️</summary>
```mdx
- ⚠️ Locale indicator shows warnings despite usable base-language translation.
- ⚠️ Editors may believe translations missing for regional locales.
- ⚠️ Inaccurate visual signals reduce trust in localization tooling.
```
</details>
```suggestion
const userLocaleBase = userLocale.split('-')[0];
const userLocaleHasTranslation =
userLocale === defaultLocale ||
Boolean(
fieldTranslations[userLocale] ||
(userLocaleBase !== userLocale && fieldTranslations[userLocaleBase]),
);
```
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. Configure content localization so that a field (e.g., dashboard title) has a
translation only for the base language code, for example `translations[fieldName] = { de:
'Umsatz-Dashboard' }`, and no entry for `de-AT`. This object is passed into the
`LocaleSwitcher` component in
`superset-frontend/src/components/TranslationEditor/LocaleSwitcher.tsx:65-77` via the
`translations` and `fieldName` props.
2. Ensure the application's default locale is `en` and the current user's UI locale (prop
`userLocale`) is a regional variant like `de-AT`, while `allLocales` contains both `de`
and `de-AT`. This results in `fieldTranslations` (computed at `LocaleSwitcher.tsx:80`)
having a key for `de` but not for `de-AT`.
3. Render the editor UI that uses `LocaleSwitcher` as the suffix for that field's input
(e.g., dashboard title editor). When the component renders, code at
`LocaleSwitcher.tsx:83-85` computes `userLocaleHasTranslation` as `false` because it only
checks `fieldTranslations[userLocale]` (`de-AT`) and does not consider
`fieldTranslations['de']`.
4. Observe that the component sets `isWarning = true` at `LocaleSwitcher.tsx:85`, which
drives the warning color `suffixColor = theme.colorWarning` at
`LocaleSwitcher.tsx:171-173`, causing the locale indicator to appear as a
missing-translation warning even though the runtime localization logic (which falls back
from `de-AT` to `de`) actually provides a translated value to the user.
```
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset-frontend/src/components/TranslationEditor/LocaleSwitcher.tsx
**Line:** 83:84
**Comment:**
*Logic Error: The warning highlight logic only checks for an exact `userLocale` match in `fieldTranslations`, but `getLocalizedValue` falls back from regional locales like `de-AT` to their base language `de`; this means the LocaleSwitcher will incorrectly show a warning for users with regional locale codes even when a base-language translation exists and is actually used. Update `userLocaleHasTranslation` to consider the base language (substring before `-`) when no exact match is present so the warning state matches the real localization behavior.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=38b71a217dc8b01955d78c8ed6adc749598825933f0fd441d6e091946576c7b5&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=38b71a217dc8b01955d78c8ed6adc749598825933f0fd441d6e091946576c7b5&reaction=dislike'>👎</a>
##########
superset-frontend/plugins/plugin-chart-echarts/src/MixedTimeseries/transformProps.ts:
##########
@@ -223,6 +228,24 @@ export default function transformProps(
metricsB = [],
}: EchartsMixedTimeseriesFormData = { ...DEFAULT_FORM_DATA, ...formData };
+ const localizedMetricLabelMap = buildLocalizedMetricLabelMap(
+ [...metrics, ...metricsB],
+ locale,
+ );
+
+ const localizedXAxisTitle =
+ getLocalizedFormDataValue(formData.translations, 'x_axis_title', locale) ??
+ xAxisTitle;
+ const localizedYAxisTitle =
+ getLocalizedFormDataValue(formData.translations, 'y_axis_title', locale) ??
+ yAxisTitle;
+ const localizedYAxisTitleSecondary =
+ getLocalizedFormDataValue(
+ formData.translations,
+ 'yAxisTitleSecondary',
Review Comment:
**Suggestion:** The secondary Y-axis title localization looks up translations using the key `'yAxisTitleSecondary'`, but other fields use snake_case keys that match control names (e.g., `'x_axis_title'`, `'y_axis_title'`), so any translations stored under the expected `'y_axis_title_secondary'` key will never be found and the secondary Y-axis title will remain untranslated. Update the lookup key to the correct snake_case value so localization works. [logic error]
<details>
<summary><b>Severity Level:</b> Major ⚠️</summary>
```mdx
- ⚠️ Secondary Y-axis titles stay untranslated in localized dashboards.
- ⚠️ Inconsistent localization behavior between primary and secondary axes.
```
</details>
```suggestion
'y_axis_title_secondary',
```
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. Render a MixedTimeseries chart, which calls `transformProps` at
`superset-frontend/plugins/plugin-chart-echarts/src/MixedTimeseries/transformProps.ts:124-231`
with `formData` including axis title translations under `formData.translations`.
2. Note that other axis titles use snake_case translation keys: `localizedXAxisTitle` uses
`'x_axis_title'` and `localizedYAxisTitle` uses `'y_axis_title'` at lines 236-241,
matching standard control keys.
3. Store a secondary Y-axis title translation under the consistent snake_case key
`formData.translations['y_axis_title_secondary'][<locale>]` (the natural pattern alongside
`'x_axis_title'` and `'y_axis_title'`).
4. When `transformProps` runs, `localizedYAxisTitleSecondary` is computed at lines 242-247
using the camelCase key `'yAxisTitleSecondary'`, so `getLocalizedFormDataValue` returns
`undefined` and the fallback `yAxisTitleSecondary` is used; at lines 697-714 where
`yAxis[1].name` is set to `localizedYAxisTitleSecondary`, the rendered secondary Y-axis
title remains unlocalized.
```
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset-frontend/plugins/plugin-chart-echarts/src/MixedTimeseries/transformProps.ts
**Line:** 245:245
**Comment:**
*Logic Error: The secondary Y-axis title localization looks up translations using the key `'yAxisTitleSecondary'`, but other fields use snake_case keys that match control names (e.g., `'x_axis_title'`, `'y_axis_title'`), so any translations stored under the expected `'y_axis_title_secondary'` key will never be found and the secondary Y-axis title will remain untranslated. Update the lookup key to the correct snake_case value so localization works.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=38177dd9263e0c73c297707b8642e8a70c7d36736c1f0c1ef6768c00802aa30b&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=38177dd9263e0c73c297707b8642e8a70c7d36736c1f0c1ef6768c00802aa30b&reaction=dislike'>👎</a>
##########
superset/localization/schema_mixin.py:
##########
@@ -0,0 +1,93 @@
+# 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.
+"""
+Marshmallow mixin for translations field.
+
+Provides translations field with feature flag validation and XSS sanitization.
+Used by all schemas that accept user-provided translations (Post, Put, Copy).
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from marshmallow import ValidationError, fields, post_load, validates_schema
+
+from superset import is_feature_enabled
+from superset.localization.sanitization import sanitize_translations
+from superset.localization.validation import validate_translations
+
+
+class TranslatableSchemaMixin:
+ """
+ Mixin for Marshmallow schemas that accept a ``translations`` field.
+
+ Adds:
+ - ``translations`` dict field (optional, nullable)
+ - ``@validates_schema``: feature flag check + structure validation
+ - ``@post_load``: XSS sanitization of translation values
+
+ Usage::
+
+ class MySchema(TranslatableSchemaMixin, Schema):
+ name = fields.String()
+ """
+
+ translations = fields.Dict(
+ metadata={"description": "Translations dict for content localization"},
+ allow_none=True,
+ )
+
+ @validates_schema
+ def validate_translations_data(
+ self, data: dict[str, Any], **kwargs: Any
+ ) -> None:
+ """
+ Validate translations field: feature flag and structure.
+
+ Checks:
+ 1. Feature flag ENABLE_CONTENT_LOCALIZATION must be enabled
+ 2. Structure must be valid: {field: {locale: value}}
+
+ Raises:
+ ValidationError: If feature disabled or structure invalid.
+ """
+ if "translations" not in data or data["translations"] is None:
+ return
+
+ if not is_feature_enabled("ENABLE_CONTENT_LOCALIZATION"):
+ raise ValidationError(
+ "Content localization is not enabled. "
+ "Set ENABLE_CONTENT_LOCALIZATION=True to use translations.",
+ field_name="translations",
+ )
+
+ validate_translations(data["translations"])
+
+ @post_load
+ def sanitize_translations_xss(
+ self, data: dict[str, Any], **kwargs: Any
+ ) -> dict[str, Any]:
+ """
+ Strip HTML from translation values to prevent XSS.
+
+ Sanitization runs after validation. All HTML tags are removed,
+ storing plain text that React will escape when rendering.
+ """
+ if "translations" in data:
Review Comment:
**Suggestion:** When the request payload includes `"translations": null`, Marshmallow will deserialize this to `data["translations"] = None`, and the `post_load` hook unconditionally passes this None value into `sanitize_translations`, which is likely implemented to operate on a dict and can raise a TypeError; adding a None check keeps behavior consistent with the validator and prevents crashes. [type error]
<details>
<summary><b>Severity Level:</b> Major ⚠️</summary>
```mdx
- ❌ Dashboard or chart save fails when translations sent as null.
- ⚠️ Feature-flagged localization endpoints less robust to client payloads.
```
</details>
```suggestion
if "translations" in data and data["translations"] is not None:
```
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. A Marshmallow schema responsible for dashboard/chart/filter create/update mixes in
`TranslatableSchemaMixin` from `superset/localization/schema_mixin.py`.
2. A client of that API endpoint sends a JSON payload with `"translations": null`
(explicitly clearing translations), which Marshmallow deserializes to
`data["translations"] = None`.
3. During `.load()`, the `@validates_schema` method `validate_translations_data` at
`superset/localization/schema_mixin.py:55-80` sees `data["translations"] is None` and
returns early, treating this as valid.
4. The `@post_load` hook `sanitize_translations_xss` at
`superset/localization/schema_mixin.py:81-93` then executes, hits `if "translations" in
data:`, and calls `sanitize_translations(data["translations"])` with `None`; if
`sanitize_translations` expects a dict of translations (as implied by
`validate_translations` and the mixin docstring), this results in a runtime `TypeError`,
causing the API request to fail.
```
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset/localization/schema_mixin.py
**Line:** 91:91
**Comment:**
*Type Error: When the request payload includes `"translations": null`, Marshmallow will deserialize this to `data["translations"] = None`, and the `post_load` hook unconditionally passes this None value into `sanitize_translations`, which is likely implemented to operate on a dict and can raise a TypeError; adding a None check keeps behavior consistent with the validator and prevents crashes.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=7405a664f1c6771f8c3d492e0025c8c607a62421569e6a5a6da262a8357ea2c3&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=7405a664f1c6771f8c3d492e0025c8c607a62421569e6a5a6da262a8357ea2c3&reaction=dislike'>👎</a>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "YuriyKrasilnikov (via GitHub)" <gi...@apache.org>.
YuriyKrasilnikov commented on PR #37790:
URL: https://github.com/apache/superset/pull/37790#issuecomment-3919062103
## Response to CodeAnt AI reviews (Feb 17 + Feb 18)
Verified all 16 findings against the actual code. 5 were real bugs and have been fixed in `90614091ba`. 11 are false positives.
---
### Fixed (5) — commit `90614091ba`
**1. TranslatableTextControl `prevValueRef` broken pattern** (`index.tsx:201-207`)
Real bug. `prevValueRef.current` is updated on line 204 BEFORE the `displayValue` check on line 206, so `prevValueRef.current !== value` is always `false` after the ref update → `displayValue` always equals `localValue` → external value changes (undo, chart switch) are ignored.
Replaced with `useEffect` sync — the established Superset pattern for functional components (`BoundsControl.tsx:79-81`).
**2. LocaleSwitcher keyboard toggle bypassing `handleOpenChange`** (`LocaleSwitcher.tsx:233`)
Real bug. `setDropdownOpen(prev => !prev)` bypasses `handleOpenChange`, so `onDropdownOpenChange` callback never fires for keyboard users. Two consumers rely on this callback for focus management: `AdhocMetricEditPopoverTitle` (uses `dropdownOpenRef` to track state) and `DndColumnSelectPopoverTitle` (calls `inputRef.current?.focus()` on close).
One-line fix: `handleOpenChange(!dropdownOpen)` — same handler for mouse and keyboard, matching Superset's `DrillBySubmenu` pattern.
**3. LocaleProvider `isLoading` stuck on success** (`LocaleProvider.tsx:122-124`)
Real bug. `setIsLoading(true)` at line 118, but only reset in the `catch` path. When `controller.setLocale(currentLocale)` → controller early returns (line 132-134 in LocaleController) → `onChange` not fired → `isLoading` stuck `true`.
Changed `catch` to `finally` — the dominant Superset pattern (3 of 4 loading state examples: `DrillDetailPane`, `SamplesPane`, `UploadDataModel`).
**4. LocaleController `initializeLocale` race condition** (`LocaleController.ts:88`)
Real bug. Constructor fires `this.initializeLocale(initialLocale)` without storing the promise in `pendingLocaleChange`. If `setLocale()` is called during init, the guard at line 137 (`if (this.pendingLocaleChange)`) does nothing → two concurrent fetches race → locale can revert to initial.
One-line fix: `this.pendingLocaleChange = this.initializeLocale(initialLocale)` — leverages the existing dedup mechanism. Same pattern as `preamble.ts` storing init promises.
**5. `schema_mixin` `translations=null` validation** (`schema_mixin.py:69`)
Real bug (partial). The check `if "translations" not in data` misses the case where `translations` is explicitly `null` — Marshmallow passes `None` as the value when `allow_none=True`. The feature flag check at line 72 would block `null` when the feature is disabled, even though `null` means "no translations."
However, the crash claim is incorrect — `validate_translations(None)` handles `None` safely (early return at `validation.py:128-129`).
Fixed: `if "translations" not in data or data["translations"] is None: return`
---
### False positives (11)
**6. `getLocalizedFormDataValue` empty string truthy check** (`getLocalizedFormDataValue.ts:41`)
Not a bug. Empty string is not a valid translation value — the entire pipeline enforces this:
- Frontend: `stripEmptyValues()` (`utils.ts:30-44`) removes empty strings before API call
- Backend: `validate_translations()` (`validation.py:155`) enforces `min_length=1`
- Backend: `sanitize_translations()` filters empty values after HTML stripping
The truthy check is intentional and consistent across `getLocalizedFormDataValue`, `getLocalizedValue`, `countFieldTranslations`, and `buildLocalizedMetricLabelMap`.
**7 + 13. MixedTimeseries `yAxisTitleSecondary` key casing** (`transformProps.ts:245`) — flagged twice across two reviews
Not a bug. The suggestion assumes translations are keyed by snake_case (`y_axis_title_secondary`), but that's incorrect.
The control panel defines `name: 'yAxisTitleSecondary'` (camelCase) at `controlPanel.tsx:486`. `convertKeysToCamelCase` (`convertKeysToCamelCase.ts:22-33`) is **shallow** — it uses `mapKeys` on top-level formData keys only. The `translations` dict is a nested value, so its internal keys are NOT converted. Both storage (TranslatableTextControl writes to `translations[control.name]`) and lookup (`getLocalizedFormDataValue(translations, 'yAxisTitleSecondary')`) use the same camelCase key from the control's `name` property.
**8. `countFieldTranslations` counting `DEFAULT_LOCALE_KEY`** (`utils.ts:53`)
Not a bug. `DEFAULT_LOCALE_KEY = 'default'` is a UI-only sentinel used in LocaleSwitcher to represent "editing the default column value." It is never stored in the `translations` JSON column in the database. The database format is `{field: {locale_code: value}}` where locale codes are real codes like `"en"`, `"de"`, `"ru"`. The `default` key cannot appear in the translations map — `stripEmptyValues()` at save time and `validate_translations()` at API level both operate on real locale codes only.
**9 + 15. Object spread `undefined`** — FiltersConfigForm (`FiltersConfigForm.tsx:644`) + DndColumnSelectPopoverTitle (`DndColumnSelectPopoverTitle.tsx:160`) — flagged twice across two reviews
Not a bug. Object spread with `undefined` is explicitly safe per ECMAScript spec. **CopyDataProperties** (ECMA-262, §14.18) step 3: if source is `undefined` or `null`, return target. `({ ...undefined, de: "German" })` → `{ de: "German" }`.
Pre-existing Superset code uses the same pattern: `useStoredSidebarWidth.ts:30,45` (Jul 2022) — `useRef<Record<string, number>>()` with no initial value, then `{ ...widthsMapRef.current, [id]: updatedWidth }` where `.current` can be `undefined`.
The nested level in both components already has an explicit guard (`?.label ?? {}`, `?.name ?? {}`), showing awareness of the undefined case — handled where the spec does NOT provide safety (property access on undefined).
**10. PropertiesModal `useEffect` stale dependency** (`PropertiesModal/index.tsx:308`)
Not a bug. The effect at line 294 intentionally loads chart data once when the modal opens (on `slice.slice_id` change). `userLocale` comes from Redux `state.common.locale` which is set in `preamble.ts` at app init and does not change during a session — changing locale in Superset requires a page reload. Adding `fetchChartProperties` to the deps would cause unnecessary re-fetches for a value that is effectively constant. The code passes `react-hooks/exhaustive-deps` in CI.
**11. `dashboards/schemas.py` `del` → `pop` for guest user fields** (`schemas.py:273-275`)
Pre-existing code — authored in commit `386d4e054` (Dec 2023), not part of this PR. The fields are always present in the serialized dict:
- `owners`: SQLAlchemy `relationship()` (line 151 in `dashboard.py`) — always exists
- `changed_by_name`: `@property` (line 260) — always returns `str`
- `changed_by`: inherited from `AuditMixin` — always exists
Marshmallow `@post_dump` includes all declared schema fields when the source object attributes exist. `KeyError` is impossible. The scenario of instantiating with `only=("id", "dashboard_title")` doesn't happen — this schema is used exclusively by the dashboard REST API at full field set.
**12. SaveModal.tsx name overwrite race condition** (`SaveModal.tsx:176-178`)
Not a practical issue. The theoretical race window is ~300-700ms (awaiting `loadDashboard` + `loadTabs` + translations fetch). The pre-existing code in the same `componentDidMount` (lines 150-157, commit `386d4e054`, Dec 2023) has the identical pattern for the `dashboard` field — `setState` after async fetch without loading gate.
The name field already shows the correct value from `props.sliceName` at mount. The API response replaces it with the original (non-localized) name from `include_translations=true` — this is intentional for the editor mode. `chart.slice_name || this.state.newSliceName` also preserves user input if the API returns empty.
**14. LocaleSwitcher warning for regional locales** (`LocaleSwitcher.tsx:83-84`)
Not a bug. The scenario requires a hyphen-format locale like `de-AT`, but Superset `LANGUAGES` config (`config.py:421-440`) uses base codes and underscore variants only: `en`, `de`, `pt_BR`, `zh_TW`, etc. The `session["locale"]` value (`initialization/__init__.py:994`) is always a key from `LANGUAGES` — never hyphen-separated.
More importantly, the proposed fix would make things **worse**. The LocaleSwitcher warning correctly reflects what the user actually sees: both `LocaleSwitcher` (exact match) and `getLocalizedValue` (`split('-')` only) behave identically for underscore-separated locales — `'pt_BR'.split('-')[0]` = `'pt_BR'` (no fallback). Adding base-language fallback only to LocaleSwitcher would make the warning say "translation exists" while the rendered text shows the default value.
The backend `get_translation()` (`locale_utils.py:123`) handles both separators (`for sep in ("-", "_")`), but this is a separate backend-frontend consistency question, not a LocaleSwitcher bug.
**16. `sanitize_translations(None)` crash in `@post_load`** (`schema_mixin.py:91`)
Not a bug. `sanitize_translations()` explicitly accepts `None`:
1. Type signature (`sanitization.py:64-66`): `translations: dict[str, dict[str, str]] | None`
2. Guard clause (`sanitization.py:85-86`): `if translations is None: return None`
3. Docstring example (`sanitization.py:82-83`): `>>> sanitize_translations(None)` → `None`
4. Dedicated test (`xss_sanitization_test.py:119-121`): `assert sanitize_translations(None) is None`
The call chain is: Marshmallow deserializes `"translations": null` → `data["translations"] = None` → `@post_load` calls `sanitize_translations(None)` → returns `None` → `data["translations"]` stays `None`. No TypeError possible.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #37790:
URL: https://github.com/apache/superset/pull/37790#discussion_r2827854841
##########
superset-frontend/src/components/TranslationEditor/useTranslatableTitle.ts:
##########
@@ -0,0 +1,159 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { type ReactNode, createElement, useCallback, useMemo, useState } from 'react';
+import { useSelector } from 'react-redux';
+import { t } from '@apache-superset/core';
+import { isFeatureEnabled, FeatureFlag } from '@superset-ui/core';
+import type { Translations } from 'src/types/Localization';
+import LocaleSwitcher from './LocaleSwitcher';
+import { DEFAULT_LOCALE_KEY } from './utils';
+import useAvailableLocales from './useAvailableLocales';
+
+export interface UseTranslatableTitleParams {
+ /** Current default title. */
+ title: string;
+ /** Full translations object for the entity. */
+ translations?: Translations;
+ /** Translation field key (e.g., 'sliceNameOverride', 'text', 'slice_name'). */
+ fieldName: string;
+ /** Save default title callback. */
+ onSaveTitle: (value: string) => void;
+ /** Save translations callback. */
+ onTranslationsChange: (translations: Translations) => void;
+ /** Human-readable field label for accessibility (e.g., 'Chart Name'). */
+ fieldLabel: string;
+}
+
+export interface UseTranslatableTitleResult {
+ /** Title to display in EditableTitle — localized value when in locale mode. */
+ displayTitle: string;
+ /** Routes to onSaveTitle or onTranslationsChange based on activeLocale. */
+ handleSave: (value: string) => void;
+ /** 'DEFAULT' or a locale code (e.g., 'de'). */
+ activeLocale: string;
+ /** Switch the active locale. */
+ setActiveLocale: (locale: string) => void;
+ /** Whether a specific locale (not DEFAULT) is active. */
+ isLocaleMode: boolean;
+ /** Pre-rendered LocaleSwitcher component, or null when feature is off / no locales. */
+ localeSwitcher: ReactNode | null;
+ /** Whether locale UI should be shown. */
+ showLocale: boolean;
+ /** Placeholder for translation input when in locale mode. */
+ placeholder: string;
+}
+
+/**
+ * Hook for inline translatable title editors.
+ *
+ * Encapsulates locale state, display value resolution, save routing,
+ * and LocaleSwitcher rendering for components like SliceHeader, Tab,
+ * ExploreChartHeader, and Dashboard Header.
+ */
+export default function useTranslatableTitle({
+ title,
+ translations,
+ fieldName,
+ onSaveTitle,
+ onTranslationsChange,
+ fieldLabel,
+}: UseTranslatableTitleParams): UseTranslatableTitleResult {
+ const localizationEnabled = isFeatureEnabled(
+ FeatureFlag.EnableContentLocalization,
+ );
+ const { allLocales, defaultLocale } = useAvailableLocales();
+ const userLocale: string = useSelector(
+ (state: { common: { locale: string } }) => state.common?.locale ?? 'en',
+ );
+
+ const [activeLocale, setActiveLocale] = useState(DEFAULT_LOCALE_KEY);
+
+ const isLocaleMode = activeLocale !== DEFAULT_LOCALE_KEY;
+ const showLocale =
+ localizationEnabled && allLocales.length > 0 && translations !== undefined;
+
Review Comment:
**Suggestion:** The `showLocale` flag is only true when `translations` is not `undefined`, which means the locale switcher will never render for dashboards/charts whose translations field is initially undefined, preventing users from adding the first translation even when the feature flag and locales are configured. To fix this, don't gate `showLocale` on `translations` being defined and instead treat an undefined value as an empty translation map. [logic error]
<details>
<summary><b>Severity Level:</b> Critical 🚨</summary>
```mdx
- ❌ New dashboards cannot add any locale-specific titles.
- ❌ Chart and filter translations UI never appears initially.
- ⚠️ Localization feature effectively unusable for fresh content.
```
</details>
```suggestion
localizationEnabled && allLocales.length > 0;
```
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. Enable content localization so `localizationEnabled` is true and configure at least one
locale, making `allLocales.length > 0` via `useAvailableLocales()` in
`superset-frontend/src/components/TranslationEditor/useTranslatableTitle.ts:80`.
2. Open an editor UI (e.g., SliceHeader, Tab, ExploreChartHeader, or Dashboard Header as
documented in this hook's comment at lines 64-68) for a newly created dashboard/chart
whose `translations` field is absent/null in the API response, so its caller passes
`translations` as `undefined` into `useTranslatableTitle(...)`.
3. When the hook runs, `showLocale` is computed at lines 88-90 as `localizationEnabled &&
allLocales.length > 0 && translations !== undefined`; since `translations` is `undefined`
for this new entity, `showLocale` becomes `false` even though localization is enabled and
locales exist.
4. In the same hook, the `localeSwitcher` memo at lines 124-137 sees `showLocale ===
false` and returns `null`, so the rendered header/editor UI never shows the
`LocaleSwitcher` component, preventing the user from adding the first translation for that
dashboard/chart.
```
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset-frontend/src/components/TranslationEditor/useTranslatableTitle.ts
**Line:** 90:90
**Comment:**
*Logic Error: The `showLocale` flag is only true when `translations` is not `undefined`, which means the locale switcher will never render for dashboards/charts whose translations field is initially undefined, preventing users from adding the first translation even when the feature flag and locales are configured. To fix this, don't gate `showLocale` on `translations` being defined and instead treat an undefined value as an empty translation map.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=d0f97bc480d8eda8446bfca4855ce42a568b965efaad208f6eeb2b56541f9580&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F37790&comment_hash=d0f97bc480d8eda8446bfca4855ce42a568b965efaad208f6eeb2b56541f9580&reaction=dislike'>👎</a>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #37790:
URL: https://github.com/apache/superset/pull/37790#issuecomment-6455868302
### ⚠️ Possible DB migration conflict
@YuriyKrasilnikov the base branch `master` picked up a new database migration under `superset/migrations/` after this PR was opened, and this PR adds or modifies migration files too. Alembic migrations form a single linear chain, so if both branch off the same parent revision, merging this PR as-is could leave the migration history with two heads instead of one, which makes `superset db upgrade` fail with `Multiple head revisions are present`.
To check and, if needed, fix this:
1. Rebase this branch onto the latest `master`.
2. Run `superset db heads`. If it lists more than one revision, you have a conflict.
3. In your new migration's script, update `down_revision` (and the `Revises` comment) to point at the other head instead, so the chain has a single head again.
See [Merging DB Migrations](https://superset.apache.org/docs/contributing/development#merging-db-migrations) in the contributing guide for a worked example.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #37790:
URL: https://github.com/apache/superset/pull/37790#issuecomment-5763316077
# 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️ 🙅♂️❗ @YuriyKrasilnikov Your base branch `master` has also updated `superset/migrations`.
**Please consider rebasing your branch and [resolving potential db migration conflicts](https://superset.apache.org/docs/contributing/development#merging-db-migrations).**
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #37790:
URL: https://github.com/apache/superset/pull/37790#issuecomment-6102862785
### ⚠️ Possible DB migration conflict
@YuriyKrasilnikov the base branch `master` picked up a new database migration under `superset/migrations/` after this PR was opened, and this PR adds or modifies migration files too. Alembic migrations form a single linear chain, so if both branch off the same parent revision, merging this PR as-is could leave the migration history with two heads instead of one, which makes `superset db upgrade` fail with `Multiple head revisions are present`.
To check and, if needed, fix this:
1. Rebase this branch onto the latest `master`.
2. Run `superset db heads`. If it lists more than one revision, you have a conflict.
3. In your new migration's script, update `down_revision` (and the `Revises` comment) to point at the other head instead, so the chain has a single head again.
See [Merging DB Migrations](https://superset.apache.org/docs/contributing/development#merging-db-migrations) in the contributing guide for a worked example.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: content localization for dashboards, charts, and filters [superset]
Posted by "github-actions[bot] (via GitHub) via notifications" <no...@superset.apache.org>.
github-actions[bot] commented on PR #37790:
URL: https://github.com/apache/superset/pull/37790#issuecomment-7047510853
### ⚠️ Possible DB migration conflict
@YuriyKrasilnikov the base branch `master` picked up a new database migration under `superset/migrations/` after this PR was opened, and this PR adds or modifies migration files too. Alembic migrations form a single linear chain, so if both branch off the same parent revision, merging this PR as-is could leave the migration history with two heads instead of one, which makes `superset db upgrade` fail with `Multiple head revisions are present`.
To check and, if needed, fix this:
1. Rebase this branch onto the latest `master`.
2. Run `superset db heads`. If it lists more than one revision, you have a conflict.
3. In your new migration's script, update `down_revision` (and the `Revises` comment) to point at the other head instead, so the chain has a single head again.
See [Merging DB Migrations](https://superset.apache.org/docs/contributing/development#merging-db-migrations) in the contributing guide for a worked example.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org