sadpandajoe commented on code in PR #37378: URL: https://github.com/apache/superset/pull/37378#discussion_r2775440369
########## superset-frontend/src/theme/utils/themeStructureValidation.ts: ########## @@ -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. + */ +import type { AnyThemeConfig } from '@apache-superset/core/ui'; +import { isValidTokenName } from './antdTokenNames'; + +export interface ValidationIssue { + tokenName: string; + severity: 'error' | 'warning'; + message: string; +} + +export interface ValidationResult { + valid: boolean; // false if ANY errors exist (warnings don't affect this) + errors: ValidationIssue[]; + warnings: ValidationIssue[]; +} + +/** + * Validates theme structure and token names. + * - ERRORS block save/apply (invalid structure, empty themes) + * - WARNINGS allow save/apply but show in editor (unknown tokens, null values) + * + * This validation does NOT check token values - Ant Design handles that at runtime. + */ +export function validateTheme(themeConfig: AnyThemeConfig): ValidationResult { + const errors: ValidationIssue[] = []; + const warnings: ValidationIssue[] = []; + + // ERROR: Null/invalid config + if (!themeConfig || typeof themeConfig !== 'object') { + errors.push({ + tokenName: '_root', + severity: 'error', + message: 'Theme configuration must be a valid object', + }); + return { valid: false, errors, warnings }; + } + + // ERROR: Empty theme (no tokens, no algorithm, no components) + const hasTokens = + themeConfig.token && Object.keys(themeConfig.token).length > 0; + const hasAlgorithm = Boolean(themeConfig.algorithm); + const hasComponents = + themeConfig.components && Object.keys(themeConfig.components).length > 0; + + if (!hasTokens && !hasAlgorithm && !hasComponents) { + errors.push({ + tokenName: '_root', + severity: 'error', + message: + 'Theme cannot be empty. Add at least one token, algorithm, or component override.', + }); + return { valid: false, errors, warnings }; + } + + // WARNING: Unknown token names (likely typos) + // Guard against non-object token values (e.g., string, array, number) + const rawToken = themeConfig.token; + const tokens = + rawToken && typeof rawToken === 'object' && !Array.isArray(rawToken) + ? rawToken + : {}; + + if (rawToken && tokens !== rawToken) { + errors.push({ + tokenName: '_root', + severity: 'error', + message: + 'Token configuration must be an object, not an array or primitive', + }); + return { valid: false, errors, warnings }; + } + + // ERROR: components must be an object if present + const rawComponents = themeConfig.components; + if ( + rawComponents !== undefined && + rawComponents !== null && + (typeof rawComponents !== 'object' || Array.isArray(rawComponents)) + ) { + errors.push({ + tokenName: '_root', + severity: 'error', + message: + 'Components configuration must be an object, not an array or primitive', + }); + return { valid: false, errors, warnings }; + } + + // ERROR: algorithm must be a string or array of strings if present + const rawAlgorithm = themeConfig.algorithm; + if (rawAlgorithm !== undefined && rawAlgorithm !== null) { + const isValidAlgorithm = + typeof rawAlgorithm === 'string' || + (Array.isArray(rawAlgorithm) && + rawAlgorithm.every(a => typeof a === 'string')); + if (!isValidAlgorithm) { + errors.push({ + tokenName: '_root', + severity: 'error', + message: + 'Algorithm must be a string or array of strings (e.g., "dark" or ["dark", "compact"])', Review Comment: This is **by design**. The backend uses string algorithm names (`"dark"`, `"compact"`, etc.) which are then resolved to Ant Design algorithm functions at runtime by `normalizeThemeConfig`. Theme configurations are stored as JSON in the database, and JSON cannot serialize functions. So: 1. Themes are stored with string algorithms: `{ algorithm: "dark" }` 2. `normalizeThemeConfig()` resolves strings to functions: `"dark"` → `theme.darkAlgorithm` 3. Validation checks the stored format (strings), not the runtime format (functions) Accepting functions in validation would be inconsistent with what's actually stored and validated by the backend. ########## superset-frontend/src/theme/ThemeController.ts: ########## @@ -796,10 +830,25 @@ export class ThemeController { this.loadFonts(fontUrls); } catch (error) { console.error('Failed to apply theme:', error); - this.fallbackToDefaultMode(); + // Re-throw the error so updateTheme can handle fallback logic + throw error; } } + private async applyThemeWithRecovery(theme: AnyThemeConfig): Promise<void> { + // Note: This method re-throws errors to the caller instead of calling + // fallbackToDefaultMode directly, to avoid infinite recursion since + // fallbackToDefaultMode calls this method. The caller's try/catch + // handles the fallback flow. + const normalizedConfig = normalizeThemeConfig(theme); + this.globalTheme.setConfig(normalizedConfig); + + // Load custom fonts if specified, mirroring applyTheme() behavior Review Comment: The minor duplication between `applyTheme` and `applyThemeWithRecovery` is **intentional**. They have different error handling semantics: - `applyTheme`: Logs errors and re-throws for `updateTheme` to handle fallback - `applyThemeWithRecovery`: Re-throws without logging to avoid duplicate logs (caller already logs) Extracting to a shared internal method would add complexity without clear benefit - the duplication is just 4 lines. The comment on line 839-842 documents why `applyThemeWithRecovery` doesn't call `fallbackToDefaultMode`. -- 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: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
