EnxDev commented on code in PR #43938:
URL: https://github.com/apache/superset/pull/43938#discussion_r4145788307


##########
superset-frontend/plugins/plugin-chart-ag-grid-table/src/controlPanel.tsx:
##########
@@ -63,12 +65,8 @@ import { PAGE_SIZE_OPTIONS, SERVER_PAGE_SIZE_OPTIONS } from 
'./consts';
 /**
  * Generate comparison column names for a given column.
  */
-const generateComparisonColumns = (colname: string) => [
-  `${t('Main')} ${colname}`,
-  `# ${colname}`,
-  `△ ${colname}`,
-  `% ${colname}`,
-];
+const generateComparisonColumns = (colname: string) =>
+  getTimeComparisonColumnKeys(colname);

Review Comment:
   **[P2] Preserve legacy localized column settings**
   
   This changes the column editor's comparison keys from localized names to 
`Main …`, but existing `column_config` entries are not migrated. For example, 
an Italian chart can retain `Principale revenue: { columnWidth: 300 }`: the 
renderer's fallback reads it, but `ColumnConfigControl` no longer recognizes 
that key. Editing an unrelated column then drops the saved entry because 
`setColumnConfig` retains only keys present in `colnames`. I reproduced this 
with an edit to `region`.
   
   Please migrate or normalize the saved configuration before the editor reads 
and filters it. The equivalent change in the standard Table control panel needs 
the same handling.



##########
superset-frontend/plugins/plugin-chart-table/src/TableChart.tsx:
##########
@@ -884,10 +897,18 @@ export default function TableChart<D extends DataRecord = 
DataRecord>(
 
   // Compute visible columns before groupHeaderColumns to ensure index 
consistency.
   // This filters out columns with config.visible === false.
-  const visibleColumnsMeta = useMemo(
-    () => filteredColumnsMeta.filter(col => col.config?.visible !== false),
-    [filteredColumnsMeta],
-  );
+  const { visibleColumnsMeta, hasHeaderGroups } = useMemo(() => {
+    const visible = filteredColumnsMeta.filter(
+      col => col.config?.visible !== false,
+    );
+    const hasGroups = hasRenderableHeaderGroups(headerGroups, visible);
+    return {
+      visibleColumnsMeta: hasGroups
+        ? orderColumnsByHeaderGroups(visible, headerGroups)

Review Comment:
   **[P2] Reset previous column ordering when enabling groups**
   
   If a user drags a column before adding a header group, React Table retains 
its internal `columnOrder` while the grouping headers use this newly computed 
order. Hiding/resetting `allow_rearrange_columns` prevents further dragging but 
does not clear that existing order. In a component test, dragging `abc.com` to 
the front and then grouping `sum__num` on the right left the `Metrics` group 
header above `abc.com`.
   
   Please reset the table's column order when header groups take over ordering, 
or derive the grouping headers from the table's actual visible order.



##########
superset-frontend/src/explore/components/controls/HeaderGroupsControl/HeaderGroupEditor.tsx:
##########
@@ -0,0 +1,558 @@
+/**
+ * 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 { useRef, useState, type ReactNode } from 'react';
+import { t } from '@apache-superset/core/translation';
+import { css, styled } from '@apache-superset/core/theme';
+import { Button, Input, Popover, Select } from '@superset-ui/core/components';
+import { Radio } from '@superset-ui/core/components/Radio';
+import { Icons } from '@superset-ui/core/components/Icons';
+import {
+  HeaderGroupColumnOption,
+  HeaderGroupConfig,
+  HeaderGroupLabelAlign,
+  HeaderGroupPlacement,
+  MAX_HEADER_GROUP_DEPTH,
+} from './types';
+import {
+  canSaveHeaderGroup,
+  createHeaderGroup,
+  normalizeSelectedColumns,
+  moveHeaderGroupAt,
+  removeHeaderGroupAt,
+  updateHeaderGroupAt,
+} from './utils';
+
+export type HeaderGroupEditorProps = {
+  group?: HeaderGroupConfig;
+  path: number[];
+  columnOptions: HeaderGroupColumnOption[];
+  usedColumns: Set<string>;
+  onChange?: (path: number[], next: HeaderGroupConfig) => void;
+  onAddChild?: (path: number[]) => void;
+  onRemove?: (path: number[]) => void;
+  onSave?: (group: HeaderGroupConfig) => void;
+  mode?: 'add' | 'edit';
+  children?: ReactNode;
+};
+
+const FormStack = styled.div`
+  ${({ theme }) => css`
+    display: flex;
+    flex-direction: column;
+    gap: ${theme.sizeUnit * 3}px;
+    min-width: ${theme.sizeUnit * 92}px;
+  `}
+`;
+
+const FieldRow = styled.div`
+  ${({ theme }) => css`
+    display: flex;
+    flex-direction: column;
+    gap: ${theme.sizeUnit}px;
+  `}
+`;
+
+const InlineFields = styled.div`
+  ${({ theme }) => css`
+    display: flex;
+    flex-wrap: nowrap;
+    align-items: flex-start;
+    gap: ${theme.sizeUnit * 3}px;
+
+    & > *:first-of-type {
+      flex: 1.4 1 auto;
+    }
+
+    & > *:last-of-type {
+      flex: 1 1 auto;
+    }
+  `}
+`;
+
+const CompactRadioGroup = styled.div`
+  ${({ theme }) => css`
+    .ant-radio-group {
+      display: flex;
+      flex-wrap: nowrap;
+      width: 100%;
+    }
+
+    .ant-radio-button-wrapper {
+      flex: 1 1 auto;
+      height: ${theme.sizeUnit * 6}px;
+      line-height: ${theme.sizeUnit * 6 - 2}px;
+      padding-inline: ${theme.sizeUnit}px;
+      font-size: ${theme.fontSizeSM}px;
+      text-align: center;
+    }
+  `}
+`;
+
+const FieldLabel = styled.span`
+  ${({ theme }) => css`
+    color: ${theme.colorTextSecondary};
+    font-size: ${theme.fontSizeSM}px;
+  `}
+`;
+
+const FieldError = styled.span`
+  ${({ theme }) => css`
+    color: ${theme.colorError};
+    font-size: ${theme.fontSizeSM}px;
+  `}
+`;
+
+const NestedCard = styled.div`
+  ${({ theme }) => css`
+    display: flex;
+    flex-direction: column;
+    gap: ${theme.sizeUnit * 2}px;
+    padding: ${theme.sizeUnit * 2}px;
+    border: 1px solid ${theme.colorBorder};
+    border-radius: ${theme.borderRadius}px;
+  `}
+`;
+
+const NestedHeader = styled.div`
+  ${({ theme }) => css`
+    display: flex;
+    align-items: center;
+    justify-content: space-between;
+    gap: ${theme.sizeUnit}px;
+    font-weight: ${theme.fontWeightStrong};
+  `}
+`;
+
+const NestedHeaderActions = styled.div`
+  display: inline-flex;
+  align-items: center;
+`;
+
+const PopoverTitleRow = styled.div`
+  display: flex;
+  align-items: center;
+  justify-content: space-between;
+  gap: ${({ theme }) => theme.sizeUnit}px;
+`;
+
+const ApplyRow = styled.div`
+  display: flex;
+  justify-content: flex-end;
+`;
+
+function SettingsToggle({
+  collapsed,
+  onToggle,
+}: {
+  collapsed: boolean;
+  onToggle: () => void;
+}) {
+  return (
+    <Button
+      buttonStyle="link"
+      buttonSize="small"
+      aria-label={collapsed ? t('Expand settings') : t('Collapse settings')}
+      onClick={event => {
+        event.preventDefault();
+        event.stopPropagation();
+        onToggle();
+      }}
+      icon={
+        collapsed ? (
+          <Icons.DownOutlined iconSize="s" />
+        ) : (
+          <Icons.UpOutlined iconSize="s" />
+        )
+      }
+    />
+  );
+}
+
+const LABEL_ALIGN_OPTIONS: { label: string; value: HeaderGroupLabelAlign }[] = 
[
+  { label: t('Left'), value: 'left' },
+  { label: t('Center'), value: 'center' },
+  { label: t('Right'), value: 'right' },
+];
+
+const PLACEMENT_OPTIONS: { label: string; value: HeaderGroupPlacement }[] = [
+  { label: t('Left'), value: 'left' },
+  { label: t('Right'), value: 'right' },
+];
+
+export function getGroupTitle(path: number[]): string {
+  const numberedPath = path.map(index => index + 1).join('.');
+  return path.length === 1
+    ? t('Group %s', numberedPath)
+    : t('Subgroup %s', numberedPath);
+}
+
+function HeaderGroupForm({
+  group,
+  path,
+  columnOptions,
+  usedColumns,
+  onChange,
+  onAddChild,
+  onRemove,
+  onMove,
+  onApply,
+  showRemove = false,
+  siblingCount = 1,
+  settingsCollapsed: settingsCollapsedProp,
+  onToggleSettings,
+  showNameError = false,
+}: {
+  group: HeaderGroupConfig;
+  path: number[];
+  columnOptions: HeaderGroupColumnOption[];
+  usedColumns: Set<string>;
+  onChange: (path: number[], next: HeaderGroupConfig) => void;
+  onAddChild: (path: number[]) => void;
+  onRemove: (path: number[]) => void;
+  onMove: (path: number[], toIndex: number) => void;
+  onApply?: () => void;
+  showRemove?: boolean;
+  siblingCount?: number;
+  settingsCollapsed?: boolean;
+  onToggleSettings?: () => void;
+  showNameError?: boolean;
+}) {
+  const availableOptions = columnOptions.filter(
+    option =>
+      (group.columns ?? []).includes(option.value) ||
+      !usedColumns.has(option.value),
+  );
+  const [localCollapsed, setLocalCollapsed] = useState(false);
+  const [nameTouched, setNameTouched] = useState(false);
+  const hadNameOnOpen = useRef(Boolean(group.label?.trim()));
+  const canSave = canSaveHeaderGroup(group);
+  const nameError =
+    showNameError &&
+    !group.label?.trim() &&
+    (hadNameOnOpen.current || nameTouched)
+      ? t('Name is required')
+      : undefined;
+  const isTimeCompareGroup = group.source === 'time_compare';
+  const isTopLevel = path.length === 1;
+  const hasSubgroups = (group.children ?? []).length > 0;
+  const canCollapse = showRemove || hasSubgroups;
+  const isCollapseControlled = settingsCollapsedProp !== undefined;
+  const settingsCollapsed = isCollapseControlled
+    ? Boolean(settingsCollapsedProp)
+    : localCollapsed;
+  const showSettings = !canCollapse || !settingsCollapsed;
+  const toggleSettings =
+    onToggleSettings ?? (() => setLocalCollapsed(collapsed => !collapsed));
+
+  return (
+    <FormStack data-test="header-group-editor">
+      {showRemove && (
+        <NestedHeader>
+          <span>{getGroupTitle(path)}</span>
+          <NestedHeaderActions>
+            {canCollapse && (
+              <SettingsToggle
+                collapsed={settingsCollapsed}
+                onToggle={toggleSettings}
+              />
+            )}
+            <Button
+              buttonStyle="link"
+              buttonSize="small"
+              aria-label={t('Move group left')}
+              disabled={path[path.length - 1] === 0}
+              onClick={() => onMove(path, path[path.length - 1] - 1)}
+              icon={<Icons.LeftOutlined iconSize="s" />}
+            />
+            <Button
+              buttonStyle="link"
+              buttonSize="small"
+              aria-label={t('Move group right')}
+              disabled={path[path.length - 1] >= siblingCount - 1}
+              onClick={() => onMove(path, path[path.length - 1] + 1)}
+              icon={<Icons.RightOutlined iconSize="s" />}
+            />
+            <Button
+              buttonStyle="link"
+              buttonSize="small"
+              aria-label={t('Remove group')}
+              onClick={() => onRemove(path)}
+              icon={<Icons.DeleteOutlined iconSize="s" />}
+            />
+          </NestedHeaderActions>
+        </NestedHeader>
+      )}
+      {showSettings && (
+        <>
+          <FieldRow>
+            <FieldLabel>{t('Name')}</FieldLabel>
+            <Input
+              aria-label={t('Group name')}
+              value={group.label}
+              placeholder={t('Enter group name')}
+              status={nameError ? 'error' : undefined}
+              disabled={isTimeCompareGroup}
+              onChange={event => {
+                setNameTouched(true);
+                onChange(path, { ...group, label: event.target.value });
+              }}
+            />
+            {nameError && <FieldError role="alert">{nameError}</FieldError>}
+          </FieldRow>
+          <FieldRow>
+            <FieldLabel>{t('Columns')}</FieldLabel>
+            <Select
+              ariaLabel={t('Group columns')}
+              mode="multiple"
+              allowClear={!isTimeCompareGroup}
+              showSearch={!isTimeCompareGroup}
+              disabled={isTimeCompareGroup}
+              value={group.columns ?? []}
+              options={availableOptions}
+              placeholder={t('Select columns')}
+              maxTagCount={3}
+              onChange={columns => {
+                onChange(path, {
+                  ...group,
+                  columns: normalizeSelectedColumns(columns),
+                });
+              }}
+            />
+          </FieldRow>
+          <InlineFields>
+            <FieldRow>
+              <FieldLabel>{t('Label position')}</FieldLabel>
+              <CompactRadioGroup>
+                <Radio.Group
+                  size="small"
+                  optionType="button"
+                  value={group.labelAlign ?? 'center'}
+                  onChange={event =>
+                    onChange(path, {
+                      ...group,
+                      labelAlign: event.target.value as HeaderGroupLabelAlign,
+                    })
+                  }
+                >
+                  {LABEL_ALIGN_OPTIONS.map(option => (
+                    <Radio.Button key={option.value} value={option.value}>
+                      {option.label}
+                    </Radio.Button>
+                  ))}
+                </Radio.Group>
+              </CompactRadioGroup>
+            </FieldRow>
+            <FieldRow>
+              <FieldLabel>
+                {isTopLevel ? t('Table side') : t('Position')}
+              </FieldLabel>
+              <CompactRadioGroup>
+                <Radio.Group
+                  size="small"
+                  optionType="button"
+                  value={group.placement ?? 'right'}
+                  onChange={event =>
+                    onChange(path, {
+                      ...group,
+                      placement: event.target.value as HeaderGroupPlacement,
+                    })
+                  }
+                >
+                  {PLACEMENT_OPTIONS.map(option => (
+                    <Radio.Button key={option.value} value={option.value}>
+                      {option.label}
+                    </Radio.Button>
+                  ))}
+                </Radio.Group>
+              </CompactRadioGroup>
+            </FieldRow>
+          </InlineFields>
+        </>
+      )}
+      {(group.children ?? []).length > 0 && (
+        <FieldRow>
+          {(group.children ?? []).map((child, index) => (
+            <NestedCard key={child.id}>
+              <HeaderGroupForm
+                group={child}
+                path={[...path, index]}
+                columnOptions={columnOptions}
+                usedColumns={usedColumns}
+                onChange={onChange}
+                onAddChild={onAddChild}
+                onRemove={onRemove}
+                onMove={onMove}
+                showRemove
+                siblingCount={(group.children ?? []).length}
+                showNameError={showNameError}
+              />
+            </NestedCard>
+          ))}
+        </FieldRow>
+      )}
+      {path.length < MAX_HEADER_GROUP_DEPTH && !isTimeCompareGroup && (
+        <Button
+          buttonStyle="dashed"
+          buttonSize="small"
+          disabled={!canSave}
+          icon={<Icons.PlusOutlined iconSize="s" />}
+          onClick={() => {
+            if (canSave) {
+              onAddChild(path);
+            }
+          }}
+        >
+          {t('Add subgroup')}
+        </Button>
+      )}
+      {onApply && (
+        <ApplyRow>
+          <Button buttonStyle="primary" disabled={!canSave} onClick={onApply}>
+            {t('Apply')}
+          </Button>
+        </ApplyRow>
+      )}
+    </FormStack>
+  );
+}
+
+export default function HeaderGroupEditor({
+  children,
+  group,
+  path,
+  columnOptions,
+  usedColumns,
+  onChange,
+  onSave,
+  mode = 'edit',
+}: HeaderGroupEditorProps) {
+  const [visible, setVisible] = useState(false);
+  const [settingsCollapsed, setSettingsCollapsed] = useState(false);
+  const [draft, setDraft] = useState<HeaderGroupConfig>(
+    group ?? createHeaderGroup(),
+  );
+
+  const isAddMode = mode === 'add';
+  const currentGroup = draft;
+  const canCollapseRoot = (currentGroup.children ?? []).length > 0;
+
+  const toDraftPath = (nextPath: number[]) =>
+    isAddMode ? nextPath : [0, ...nextPath.slice(path.length)];
+
+  const handleOpenChange = (open: boolean) => {
+    setVisible(open);
+    if (open) {
+      setDraft(
+        isAddMode ? createHeaderGroup() : (group ?? createHeaderGroup()),
+      );
+      setSettingsCollapsed(false);
+    }
+  };
+
+  const persistDraftIfValid = (nextDraft: HeaderGroupConfig) => {
+    if (!isAddMode && canSaveHeaderGroup(nextDraft)) {
+      onChange?.(path, nextDraft);
+    }
+  };
+
+  const handleChange = (nextPath: number[], next: HeaderGroupConfig) => {
+    const nextDraft = updateHeaderGroupAt(
+      [draft],
+      toDraftPath(nextPath),
+      () => next,
+    )[0]!;
+    setDraft(nextDraft);
+    persistDraftIfValid(nextDraft);
+  };
+
+  const handleAddChild = (nextPath: number[]) => {
+    const nextDraft = updateHeaderGroupAt(
+      [draft],
+      toDraftPath(nextPath),
+      current => ({
+        ...current,
+        children: [...(current.children ?? []), createHeaderGroup()],
+      }),
+    )[0]!;
+    setDraft(nextDraft);
+  };
+
+  const handleRemove = (nextPath: number[]) => {
+    const nextDraft = removeHeaderGroupAt([draft], toDraftPath(nextPath))[0]!;
+    setDraft(nextDraft);
+    persistDraftIfValid(nextDraft);
+  };
+
+  const handleMove = (nextPath: number[], toIndex: number) => {
+    const nextDraft = moveHeaderGroupAt(
+      [draft],
+      toDraftPath(nextPath),
+      toIndex,
+    )[0]!;
+    setDraft(nextDraft);
+    persistDraftIfValid(nextDraft);
+  };
+
+  const handleApply = () => {
+    if (!canSaveHeaderGroup(draft)) {
+      return;
+    }
+    onSave?.(draft);
+    setVisible(false);
+    setDraft(createHeaderGroup());
+  };
+
+  return (
+    <Popover
+      title={
+        <PopoverTitleRow>
+          <span>{isAddMode ? t('Add group') : getGroupTitle(path)}</span>
+          {canCollapseRoot && (
+            <SettingsToggle
+              collapsed={settingsCollapsed}
+              onToggle={() => setSettingsCollapsed(collapsed => !collapsed)}
+            />
+          )}
+        </PopoverTitleRow>
+      }
+      trigger={['click']}
+      open={visible}
+      onOpenChange={handleOpenChange}
+      destroyOnHidden
+      overlayStyle={{ maxWidth: 480 }}
+      content={
+        <HeaderGroupForm
+          group={currentGroup}
+          path={isAddMode ? [0] : path}
+          columnOptions={columnOptions}
+          usedColumns={usedColumns}

Review Comment:
   **[P2] Include draft selections when reserving columns**
   
   `usedColumns` comes from the saved groups and does not include the current 
draft. In Add group, select `SUM(sales)` for the parent, add a named subgroup, 
and select `SUM(sales)` again: the option remains available and Apply saves 
both assignments. I reproduced the duplicate in the emitted configuration. The 
renderers assign the column to one group, so the other header disappears 
despite the subgroup passing validation.
   
   Please account for selections throughout the draft tree when computing 
available columns, while allowing each group to retain its own selections.



##########
superset-frontend/packages/superset-ui-chart-controls/src/utils/headerGroups.ts:
##########
@@ -0,0 +1,876 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import { t } from '@apache-superset/core/translation';
+import {
+  ComparisonType,
+  ensureIsArray,
+  getColumnLabel,
+  getMetricLabel,
+  QueryFormColumn,
+  QueryFormMetric,
+  QueryMode,
+  SqlaFormData,
+} from '@superset-ui/core';
+import { isEmpty, last } from 'lodash-es';
+import {
+  isPercentMetric,
+  isRegularMetric,
+  shouldSkipMetricColumn,
+} from './metricColumnFilter';
+
+export type HeaderGroupLabelAlign = 'left' | 'center' | 'right';
+
+export type HeaderGroupPlacement = 'left' | 'right';
+
+export type HeaderGroupConfig = {
+  id: string;
+  label: string;
+  columns: string[];
+  labelAlign?: HeaderGroupLabelAlign;
+  placement?: HeaderGroupPlacement;
+  source?: 'time_compare';
+  children?: HeaderGroupConfig[];
+};
+
+export type HeaderGroupCell = {
+  key: string;
+  label: string;
+  colSpan: number;
+  rowSpan: number;
+  columnIndex: number;
+  labelAlign?: HeaderGroupLabelAlign;
+  isLastColumn: boolean;
+};
+
+export const TIME_COMPARE_MAIN_KEY = 'Main';
+
+const TIME_COMPARE_SYMBOL_PREFIXES = ['#', '△', '%'] as const;
+
+type TimeCompareSlot = {
+  metric: string;
+  isMain: boolean;
+  prefix: string;
+};
+
+function getMainComparisonPrefixes(): string[] {
+  return [...new Set([t('Main'), TIME_COMPARE_MAIN_KEY])];
+}
+
+function isTimeCompareSymbolPrefix(
+  prefix: string,
+): prefix is (typeof TIME_COMPARE_SYMBOL_PREFIXES)[number] {
+  return (TIME_COMPARE_SYMBOL_PREFIXES as readonly string[]).includes(prefix);
+}
+
+function parseTimeComparisonSlot(column: string): TimeCompareSlot | null {
+  for (const prefix of TIME_COMPARE_SYMBOL_PREFIXES) {
+    if (column.startsWith(`${prefix} `)) {
+      return { metric: column.slice(prefix.length + 1), isMain: false, prefix 
};
+    }
+  }
+  for (const prefix of getMainComparisonPrefixes()) {
+    if (column.startsWith(`${prefix} `)) {
+      return {
+        metric: column.slice(prefix.length + 1),
+        isMain: true,
+        prefix: TIME_COMPARE_MAIN_KEY,
+      };
+    }
+  }
+  return null;
+}
+
+function inferMainSlotFromSiblings(
+  column: string,
+  visibleKeys: string[],
+): TimeCompareSlot | null {
+  const space = column.indexOf(' ');
+  if (space <= 0) {
+    return null;
+  }
+  const metric = column.slice(space + 1);
+  if (
+    !metric ||
+    !TIME_COMPARE_SYMBOL_PREFIXES.some(symbol =>
+      visibleKeys.includes(`${symbol} ${metric}`),
+    )
+  ) {
+    return null;
+  }
+  return { metric, isMain: true, prefix: TIME_COMPARE_MAIN_KEY };
+}
+
+function resolveTimeComparisonSlotKeys(
+  slot: TimeCompareSlot,
+  visibleKeys: string[],
+): string[] {
+  if (!slot.isMain) {
+    const key = `${slot.prefix} ${slot.metric}`;
+    return visibleKeys.filter(item => item === key);
+  }
+  const wanted = new Set(
+    getMainComparisonPrefixes().map(prefix => `${prefix} ${slot.metric}`),
+  );
+  const matches = visibleKeys.filter(key => wanted.has(key));
+  if (matches.length > 0) {
+    return matches;
+  }
+  const alternatives = visibleKeys.filter(key => {
+    const space = key.indexOf(' ');
+    if (space <= 0) {
+      return false;
+    }
+    const prefix = key.slice(0, space);
+    return (
+      !isTimeCompareSymbolPrefix(prefix) && key.slice(space + 1) === 
slot.metric
+    );
+  });
+  return alternatives.length === 1 ? alternatives : [];
+}
+
+/**
+ * Locale-independent comparison column keys. `Main` is a stored slot id.
+ * Chart headers display `t('Main')` and may use a translated data key.
+ */
+export function getTimeComparisonColumnKeys(colname: string): string[] {
+  return [
+    `${TIME_COMPARE_MAIN_KEY} ${colname}`,
+    `# ${colname}`,
+    `△ ${colname}`,
+    `% ${colname}`,
+  ];
+}
+
+export function toStoredTimeComparisonColumnKey(
+  column: string,
+  visibleKeys: string[] = [],
+): string {
+  const slot =
+    parseTimeComparisonSlot(column) ??
+    inferMainSlotFromSiblings(column, visibleKeys);
+  if (!slot) {
+    return column;
+  }
+  if (
+    visibleKeys.length > 0 &&
+    resolveTimeComparisonSlotKeys(slot, visibleKeys).length === 0
+  ) {
+    return column;
+  }
+  return slot.isMain
+    ? `${TIME_COMPARE_MAIN_KEY} ${slot.metric}`
+    : `${slot.prefix} ${slot.metric}`;
+}
+
+export function expandGroupColumnKey(
+  identifier: string,
+  visibleKeys: string[],
+): string[] {
+  const visible = new Set(visibleKeys);
+  if (visible.has(identifier)) {
+    return [identifier];
+  }
+  const slot =
+    parseTimeComparisonSlot(identifier) ??
+    inferMainSlotFromSiblings(identifier, visibleKeys);
+  if (slot) {
+    return resolveTimeComparisonSlotKeys(slot, visibleKeys);
+  }
+  const candidates = [
+    `%${identifier}`,
+    ...getTimeComparisonColumnKeys(identifier),
+    `${t('Main')} ${identifier}`,
+  ];
+  const matchSet = new Set(candidates.filter(key => visible.has(key)));
+  return visibleKeys.filter(key => matchSet.has(key));
+}
+
+export function buildTimeComparisonHeaderGroups(
+  metricKeys: string[],
+  labelFor: (key: string) => string = key => key,
+): HeaderGroupConfig[] {
+  return metricKeys.map(key => ({
+    id: `time-compare-${key}`,
+    label: labelFor(key),
+    columns: getTimeComparisonColumnKeys(key),
+    labelAlign: 'left',
+    placement: 'right',
+    source: 'time_compare',
+  }));
+}
+
+function isTimeComparisonSlotKey(column: string, prefix: string): boolean {
+  return column.startsWith(`${prefix} `);
+}
+
+function remapTimeComparisonColumns(
+  columns: string[],
+  currentKeys: string[],
+): string[] {
+  const currentSet = new Set(currentKeys);
+  if (columns.every(column => currentSet.has(column))) {
+    return columns;
+  }
+  const mainKey = currentKeys.find(
+    key =>
+      !isTimeComparisonSlotKey(key, '#') &&
+      !isTimeComparisonSlotKey(key, '△') &&
+      !isTimeComparisonSlotKey(key, '%'),
+  );
+  const hashKey = currentKeys.find(key => isTimeComparisonSlotKey(key, '#'));
+  const deltaKey = currentKeys.find(key => isTimeComparisonSlotKey(key, '△'));
+  const percentKey = currentKeys.find(key => isTimeComparisonSlotKey(key, 
'%'));
+  const remapped = columns
+    .map(column => {
+      if (currentSet.has(column)) {
+        return column;
+      }
+      if (isTimeComparisonSlotKey(column, '#')) {
+        return hashKey;
+      }
+      if (isTimeComparisonSlotKey(column, '△')) {
+        return deltaKey;
+      }
+      if (isTimeComparisonSlotKey(column, '%')) {
+        return percentKey;
+      }
+      return mainKey;
+    })
+    .filter((column): column is string => Boolean(column));
+  return remapped.length > 0 ? [...new Set(remapped)] : currentKeys;
+}
+
+function refreshTimeComparisonGroup(
+  group: HeaderGroupConfig,
+  currentKeys: string[],
+  replaceColumns: boolean,
+  nextLabel?: string,
+): HeaderGroupConfig {
+  return {
+    ...group,
+    ...(replaceColumns && nextLabel !== undefined ? { label: nextLabel } : {}),
+    columns: replaceColumns
+      ? currentKeys
+      : remapTimeComparisonColumns(group.columns ?? [], currentKeys),
+    children: group.children?.map(child =>
+      refreshTimeComparisonGroup(child, currentKeys, false),
+    ),
+  };
+}
+
+function remapUserGroupComparisonColumns(
+  group: HeaderGroupConfig,
+  visibleKeys: string[],
+): HeaderGroupConfig {
+  return {
+    ...group,
+    columns: (group.columns ?? []).map(column =>
+      toStoredTimeComparisonColumnKey(column, visibleKeys),
+    ),
+    children: group.children?.map(child =>
+      remapUserGroupComparisonColumns(child, visibleKeys),
+    ),
+  };
+}
+
+export function syncTimeComparisonGroups(
+  groups: HeaderGroupConfig[],
+  timeComparisonGroups: HeaderGroupConfig[] = [],
+): HeaderGroupConfig[] {
+  const autoById = new Map(
+    timeComparisonGroups.map(group => [group.id, group]),
+  );
+  const existingAutoIds = new Set(
+    groups
+      .filter(group => group.source === 'time_compare')
+      .map(group => group.id),
+  );
+  const comparisonKeys = timeComparisonGroups.flatMap(
+    group => group.columns ?? [],
+  );
+  const kept = groups
+    .filter(group => group.source !== 'time_compare' || autoById.has(group.id))
+    .map(group => {
+      if (group.source !== 'time_compare') {
+        return remapUserGroupComparisonColumns(group, comparisonKeys);
+      }
+      const fresh = autoById.get(group.id) as HeaderGroupConfig;
+      return refreshTimeComparisonGroup(
+        group,
+        fresh.columns,
+        true,
+        fresh.label,
+      );
+    });
+  const missing = timeComparisonGroups.filter(
+    group => !existingAutoIds.has(group.id),
+  );
+  return missing.length === 0 ? kept : [...kept, ...missing];
+}
+
+export function headerGroupsHaveSameContent(
+  left: HeaderGroupConfig[],
+  right: HeaderGroupConfig[],
+): boolean {
+  if (left.length !== right.length) {
+    return false;
+  }
+  return left.every((group, index) => {
+    const other = right[index];
+    if (
+      group.id !== other.id ||
+      group.label !== other.label ||
+      group.columns.length !== other.columns.length ||
+      group.columns.some(
+        (column, colIndex) => column !== other.columns[colIndex],
+      )
+    ) {
+      return false;
+    }
+    return headerGroupsHaveSameContent(
+      group.children ?? [],
+      other.children ?? [],
+    );
+  });
+}
+
+function labelFromVerboseMap(
+  key: string,
+  verboseMap?: Record<string, string> | string[] | null,
+): string {
+  if (!verboseMap || Array.isArray(verboseMap)) {
+    return key;
+  }
+  if (key.startsWith('%')) {
+    const baseKey = key.replace('%', '');
+    if (Object.prototype.hasOwnProperty.call(verboseMap, baseKey)) {
+      return `%${verboseMap[baseKey]}`;
+    }
+  }
+  return verboseMap[key] ?? key;
+}
+
+function columnOptionLabel(
+  colname: string,
+  verboseMap?: Record<string, string> | string[] | null,
+): string {
+  const slot = parseTimeComparisonSlot(colname);
+  if (!slot) {
+    return labelFromVerboseMap(colname, verboseMap);
+  }
+  const metricLabel = labelFromVerboseMap(slot.metric, verboseMap);
+  const prefix = slot.isMain ? t('Main') : slot.prefix;
+  return `${prefix} ${metricLabel}`;
+}
+
+export function resolveHeaderGroups(
+  headerGroups: HeaderGroupConfig[] | undefined,
+  options: {
+    timeCompareEnabled: boolean;
+    metricKeys: string[];
+    verboseMap?: Record<string, string> | string[] | null;
+  },
+): HeaderGroupConfig[] {
+  return syncTimeComparisonGroups(
+    headerGroups ?? [],
+    options.timeCompareEnabled
+      ? buildTimeComparisonHeaderGroups(options.metricKeys, key =>
+          labelFromVerboseMap(key, options.verboseMap),
+        )
+      : [],
+  );
+}
+
+function splitChildGroups(group: HeaderGroupConfig): {
+  left: HeaderGroupConfig[];
+  right: HeaderGroupConfig[];
+} {
+  const children = group.children ?? [];
+  return {
+    left: children.filter(child => child.placement === 'left'),
+    right: children.filter(child => child.placement !== 'left'),
+  };
+}
+
+export function collectHeaderGroupLeaves(group: HeaderGroupConfig): string[] {
+  const { left, right } = splitChildGroups(group);
+  return [
+    ...left.flatMap(collectHeaderGroupLeaves),
+    ...(group.columns ?? []),
+    ...right.flatMap(collectHeaderGroupLeaves),
+  ];
+}
+
+export function getHeaderGroupDepth(group: HeaderGroupConfig): number {
+  const children = group.children ?? [];
+  if (children.length === 0) {
+    return 1;
+  }
+  return 1 + Math.max(...children.map(getHeaderGroupDepth));
+}
+
+export function getHeaderGroupsMaxDepth(groups: HeaderGroupConfig[]): number {
+  if (groups.length === 0) {
+    return 0;
+  }
+  return Math.max(...groups.map(getHeaderGroupDepth));
+}
+
+type AncestorInfo = {
+  labels: string[];
+  ids: string[];
+  aligns: HeaderGroupLabelAlign[];
+};
+
+function buildAncestorMap(
+  groups: HeaderGroupConfig[],
+  visibleKeys: string[],
+  ancestors: AncestorInfo = { labels: [], ids: [], aligns: [] },
+  map: Map<string, AncestorInfo> = new Map(),
+): Map<string, AncestorInfo> {
+  groups.forEach(group => {
+    const next = {
+      labels: [...ancestors.labels, group.label],
+      ids: [...ancestors.ids, group.id],
+      aligns: [...ancestors.aligns, group.labelAlign ?? 'center'],
+    };
+    (group.columns ?? []).forEach(column => {
+      expandGroupColumnKey(column, visibleKeys).forEach(key => {
+        if (!map.has(key)) {
+          map.set(key, next);
+        }
+      });
+    });
+    if (group.children?.length) {
+      buildAncestorMap(group.children, visibleKeys, next, map);
+    }
+  });
+  return map;
+}
+
+function collectGroupedColumns<T extends { key: string; metricName?: string }>(
+  groups: HeaderGroupConfig[],
+  columns: T[],
+  byKey: Map<string, T>,
+  seen: Set<string>,
+): T[] {
+  const visibleKeys = columns.map(column => column.key);
+  return groups.flatMap(collectHeaderGroupLeaves).reduce<T[]>((acc, key) => {
+    const resolvedKeys = [
+      ...expandGroupColumnKey(key, visibleKeys),
+      ...columns
+        .filter(column => column.metricName === key && !seen.has(column.key))
+        .map(column => column.key),
+    ];
+    resolvedKeys.forEach(resolvedKey => {
+      const column = byKey.get(resolvedKey);
+      if (!column || seen.has(resolvedKey)) {
+        return;
+      }
+      seen.add(resolvedKey);
+      acc.push(column);
+    });
+    return acc;
+  }, []);
+}
+
+export function orderColumnsByHeaderGroups<
+  T extends { key: string; metricName?: string },
+>(columns: T[], groups: HeaderGroupConfig[]): T[] {
+  const visibleKeys = columns.map(column => column.key);
+  const identifiers = groups.flatMap(collectHeaderGroupLeaves);
+  const leafSet = new Set([
+    ...identifiers.flatMap(key => expandGroupColumnKey(key, visibleKeys)),
+    ...columns
+      .filter(
+        column => column.metricName && identifiers.includes(column.metricName),
+      )
+      .map(column => column.key),
+  ]);
+  const byKey = new Map(columns.map(column => [column.key, column]));
+  const ungrouped = columns.filter(column => !leafSet.has(column.key));
+  const seen = new Set<string>();
+  const leftGroups = groups.filter(group => group.placement === 'left');
+  const rightGroups = groups.filter(group => group.placement !== 'left');
+  const leftGrouped = collectGroupedColumns(leftGroups, columns, byKey, seen);
+  const rightGrouped = collectGroupedColumns(rightGroups, columns, byKey, 
seen);
+  return [...leftGrouped, ...ungrouped, ...rightGrouped];
+}
+
+export function buildHeaderGroupRows(
+  groups: HeaderGroupConfig[],
+  columnKeys: string[],
+): HeaderGroupCell[][] {
+  const ancestorMap = buildAncestorMap(groups, columnKeys);
+  const maxDepth = getHeaderGroupsMaxDepth(groups);
+  if (maxDepth === 0 || columnKeys.length === 0 || ancestorMap.size === 0) {
+    return [];
+  }
+
+  const covered: boolean[][] = Array.from({ length: maxDepth }, () =>
+    Array.from({ length: columnKeys.length }, () => false),
+  );
+  const rows: HeaderGroupCell[][] = Array.from({ length: maxDepth }, () => []);
+
+  for (let level = 0; level < maxDepth; level += 1) {
+    let colIndex = 0;
+    while (colIndex < columnKeys.length) {
+      if (covered[level][colIndex]) {
+        colIndex += 1;
+        continue;
+      }
+
+      const columnKey = columnKeys[colIndex];
+      const ancestor = ancestorMap.get(columnKey);
+      const labels = ancestor?.labels ?? [];
+      const ids = ancestor?.ids ?? [];
+      const label = labels[level];
+
+      if (label !== undefined) {
+        let colSpan = 1;
+        while (colIndex + colSpan < columnKeys.length) {
+          const nextLabels =
+            ancestorMap.get(columnKeys[colIndex + colSpan])?.labels ?? [];
+          const sharesPrefix = labels
+            .slice(0, level + 1)
+            .every((item, index) => nextLabels[index] === item);

Review Comment:
   **[P2] Compare group IDs when combining header cells**
   
   This compares ancestor labels rather than group identity. Two adjacent, 
distinct groups named `Total`, one left-aligned and one right-aligned, produce 
a single header with `colSpan: 2` and the first group's alignment. A regression 
test expecting two cells returns only one. Group names are not required to be 
unique, so separate groups can lose their boundary and settings.
   
   Please compare the ancestor ID paths when determining whether neighboring 
columns share a group.



-- 
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]

Reply via email to