sadpandajoe commented on code in PR #38865: URL: https://github.com/apache/superset/pull/38865#discussion_r4350619667
########## superset-frontend/src/dashboard/util/useDynamicChartTitle.ts: ########## @@ -0,0 +1,115 @@ +/** + * 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 { useSelector } from 'react-redux'; +import { Filter, NativeFilterType } from '@superset-ui/core'; +import { TIME_FILTER_MAP } from 'src/explore/constants'; +import type { DynamicTitleConfig, RootState } from 'src/dashboard/types'; +import { useFilterConfiguration } from '../components/nativeFilters/state'; +import { + getAppliedColumns, + getRejectedColumns, +} from '../components/nativeFilters/selectors'; +import { DASHBOARD_ROOT_ID } from './constants'; +import { + createChartLayoutItemMap, + getChartIdsInFilterScope, +} from './getChartIdsInFilterScope'; +import { useChartLayoutItems } from './useChartLayoutItems'; +import { + getDynamicTitleFilterValue, + hasNoTemporalTitleSupport, + resolveDynamicTitle, +} from './dynamicTitle'; + +export function useDynamicChartTitle( + chartId: number, + baseTitle: string, + config?: DynamicTitleConfig, +) { + const enabled = Boolean(config); + const nativeFilters = useFilterConfiguration(); + const dataMask = useSelector((state: RootState) => + enabled ? state.dataMask : undefined, + ); + const layoutItems = useChartLayoutItems(); + const chart = useSelector((state: RootState) => + enabled ? state.charts[chartId] : undefined, + ); + const datasource = useSelector((state: RootState) => + enabled && chart?.form_data?.datasource + ? state.datasources[chart.form_data.datasource] + : undefined, + ); + const filters = useMemo(() => { + if (!enabled) { + return []; + } + const layoutMap = createChartLayoutItemMap(layoutItems); + const chartIds = Array.from(layoutMap.keys()); + const rejectedColumns = getRejectedColumns(chart); + const appliedColumns = getAppliedColumns(chart); + const noTemporalSupport = hasNoTemporalTitleSupport( + datasource, + chart?.form_data, + ); + return nativeFilters + .filter( + (filter): filter is Filter => + filter.type === NativeFilterType.NativeFilter && + getChartIdsInFilterScope( + filter.scope ?? { rootPath: [DASHBOARD_ROOT_ID], excluded: [] }, + chartIds, + layoutMap, + ).includes(chartId), + ) + .map(filter => { + const mask = dataMask?.[filter.id]; + const rejected = + rejectedColumns.has(filter.targets?.[0]?.column?.name ?? '') || + Object.entries(TIME_FILTER_MAP).some( + ([field, column]) => + mask?.extraFormData?.[field as keyof typeof TIME_FILTER_MAP] !== + undefined && + (rejectedColumns.has(column) || + (noTemporalSupport && !appliedColumns.has(column))), + ); + return { + id: filter.id, + name: filter.name || filter.id, + value: rejected Review Comment: This reads each in-scope time filter's value on its own, but the chart query merges `time_range` from all applied filters with last-writer-wins, so only one of them is actually used. With two time-range filters in scope (A = "Last week", B = "Last year", B merged last) and `{{chart_title}} in {{period_a}}` mapped to A, the chart queries last year's data while the title reads "Revenue in Last week". Neither the scope check nor the rejected-column check catches that A was overridden. Should an overridden time filter be treated as having no value here, so the title falls back to the base title? ########## superset-frontend/src/dashboard/components/ChartTitleEditor/index.tsx: ########## @@ -0,0 +1,226 @@ +/** + * 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 { KeyboardEvent, useId, useState } from 'react'; +import { t } from '@apache-superset/core/translation'; +import { + Checkbox, + Form, + Input, + Modal, + Select, + Typography, +} from '@superset-ui/core/components'; +import type { DynamicTitleConfig } from 'src/dashboard/types'; +import { + CHART_TITLE_ALIAS, + createDynamicTitleAlias, + extractDynamicTitleAliases, + getChartBaseTitle, + getInvalidDynamicTitleAliases, + hasInvalidDynamicTitleTokens, +} from 'src/dashboard/util/dynamicTitle'; +import { useDynamicChartTitle } from 'src/dashboard/util/useDynamicChartTitle'; + +interface ChartTitleEditorProps { + chartId: number; + baseTitle: string; + originalTitle: string; + config?: DynamicTitleConfig; + onApply: (baseTitle: string, config?: DynamicTitleConfig) => void; + onHide: () => void; +} + +export default function ChartTitleEditor({ + chartId, + baseTitle, + originalTitle, + config, + onApply, + onHide, +}: ChartTitleEditorProps) { + const id = useId(); + const [title, setTitle] = useState(baseTitle); + const [enabled, setEnabled] = useState(Boolean(config)); + const [template, setTemplate] = useState( + typeof config?.template === 'string' ? config.template : '', + ); + const [tokenMappings, setTokenMappings] = useState( + config?.tokenMappings && typeof config.tokenMappings === 'object' + ? config.tokenMappings + : {}, + ); + const [submitted, setSubmitted] = useState(false); + const draft = { template, tokenMappings }; + const { filters, title: preview } = useDynamicChartTitle( + chartId, + getChartBaseTitle(title, originalTitle), + enabled ? draft : undefined, + ); + const invalidAliases = getInvalidDynamicTitleAliases(draft, filters); + const error = !template.trim() + ? t('Enter a title template.') + : hasInvalidDynamicTitleTokens(template) + ? t('Use tokens in the format {{filter_name}}.') + : invalidAliases.length + ? t('Update or remove invalid tokens: %s', invalidAliases.join(', ')) + : undefined; + + const insertToken = (value: string) => { + let alias = CHART_TITLE_ALIAS; + if (value !== CHART_TITLE_ALIAS) { + const filter = filters.find(item => item.id === value); + if (!filter) { + return; + } + alias = + Object.entries(tokenMappings).find( + ([key, filterId]) => + filterId === value && + /^[a-zA-Z0-9_]+$/.test(key) && + key !== CHART_TITLE_ALIAS, + )?.[0] ?? + createDynamicTitleAlias(filter.name, Object.keys(tokenMappings)); + setTokenMappings(previous => ({ ...previous, [alias]: value })); + } + setTemplate( + previous => + `${previous}${previous && !/\s$/.test(previous) ? ' ' : ''}{{${alias}}}`, + ); + }; + + const apply = () => { + setSubmitted(true); + if (enabled && error) { + return; + } + const aliases = extractDynamicTitleAliases(template); + onApply( Review Comment: `apply` always passes the resolved base title (`title`, seeded from `getChartBaseTitle(override, originalTitle)`) to `onApply`, and `ChartHolder` stores it as `sliceNameOverride`. So for a chart with no override, simply enabling a dynamic title and clicking Apply, or even opening the editor and applying unchanged, saves an explicit override equal to the current chart name. If the chart is later renamed from "Revenue" to "Sales", this placement and its `{{chart_title}}` keep showing "Revenue". Could the original override state be preserved unless the Base title field was actually edited? -- 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]
