sadpandajoe commented on code in PR #43863:
URL: https://github.com/apache/superset/pull/43863#discussion_r4109311842


##########
superset-frontend/packages/superset-ui-core/src/query/extractQueryFields.ts:
##########
@@ -49,6 +49,10 @@ export default function extractQueryFields(
     secondary_metric: 'metrics',
     left_metric: 'metrics',
     right_metric: 'metrics',
+    open: 'metrics',

Review Comment:
   This registers `open`/`close`/`high`/`low` as metrics for every chart's 
query building, but the separate list that `getStandardizedControls` reads when 
a user switches chart types wasn't updated to include them — so switching from 
Candlestick to another chart type drops all four OHLC metrics instead of 
carrying them over, unlike how other charts register their standardized fields 
in both places. Should these four keys be added there too?



##########
superset-frontend/plugins/plugin-chart-echarts/src/Candlestick/transformProps.ts:
##########
@@ -0,0 +1,767 @@
+/**
+ * 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 {
+  AxisType,
+  CategoricalColorNamespace,
+  CurrencyFormatter,
+  DataRecord,
+  ensureIsArray,
+  getColumnLabel,
+  getMetricLabel,
+  getNumberFormatter,
+  getTimeFormatter,
+  getXAxisLabel,
+  NumberFormatter,
+  rgbToHex,
+  tooltipHtml,
+} from '@superset-ui/core';
+import { GenericDataType } from '@apache-superset/core/common';
+import { t } from '@apache-superset/core/translation';
+import type { CustomSeriesOption, CustomSeriesRenderItem } from 'echarts';
+import type { CandlestickSeriesOption, LineSeriesOption } from 
'echarts/charts';
+import type { EChartsCoreOption } from 'echarts/core';
+import type { CallbackDataParams } from 'echarts/types/src/util/types';
+import {
+  CandlestickChartTransformedProps,
+  EchartsCandlestickChartProps,
+  EchartsCandlestickFormData,
+  OhlcValue,
+  LookupKey,
+} from './types';
+import {
+  CANDLESTICK_SERIES_NAME,
+  DEFAULT_DECREASE_COLOR,
+  DEFAULT_FORM_DATA,
+  DEFAULT_INCREASE_COLOR,
+  DIRECTION_LABELS,
+  OHLC_LABELS,
+  OHLC_TICK_WIDTH_RATIO,
+} from './constants';
+import { defaultGrid, defaultYAxis } from '../defaults';
+import { getDefaultTooltip } from '../utils/tooltip';
+import {
+  extractGroupbyLabel,
+  getColtypesMapping,
+  getLegendProps,
+} from '../utils/series';
+import { convertInteger } from '../utils/convertInteger';
+import { mergeCustomEChartOptions } from '../utils/mergeCustomEChartOptions';
+import { safeParseEChartOptions } from '../utils/safeEChartOptionsParser';
+import { TIMESERIES_CONSTANTS } from '../constants';
+import { getPadding } from '../Timeseries/transformers';
+import { LegendOrientation, LegendType, Refs } from '../types';
+import { resolveLegendLayout } from '../utils/legendLayout';
+import {
+  calculateMA,
+  MA_LINE_OPACITY,
+  movingAverageName,
+  parseMovingAveragePeriods,
+} from './utils';
+
+type CandlestickDatum = NonNullable<CandlestickSeriesOption['data']>[number];
+type AxisTooltipParams = CallbackDataParams & {
+  axisValue?: string | number;
+  axisValueLabel?: string;
+};
+const NULL_LOOKUP_KEY = Symbol('candlestick-null');
+
+function toNumber(value: unknown): number | null {
+  if (value === null || value === undefined || value === '') {
+    return null;
+  }
+  const numeric = Number(value);
+  return Number.isFinite(numeric) ? numeric : null;
+}
+
+function getOwnValue<T extends object>(
+  object: T,
+  key: string,
+): T[keyof T] | undefined {
+  return key && Object.hasOwn(object, key) ? object[key as keyof T] : 
undefined;
+}
+
+function toLookupKey(value: unknown): LookupKey {
+  return value == null ? NULL_LOOKUP_KEY : String(value);
+}
+
+function getOhlc(
+  datum: DataRecord,
+  openLabel: string,
+  closeLabel: string,
+  lowLabel: string,
+  highLabel: string,
+): OhlcValue | null {
+  const open = toNumber(getOwnValue(datum, openLabel));
+  const close = toNumber(getOwnValue(datum, closeLabel));
+  const low = toNumber(getOwnValue(datum, lowLabel));
+  const high = toNumber(getOwnValue(datum, highLabel));
+  if (open === null || close === null || low === null || high === null) {
+    return null;
+  }
+  return [open, close, low, high];
+}
+
+function toCandlestickDatum(ohlc: OhlcValue | null): CandlestickDatum {
+  return ohlc ?? [];
+}
+
+function toOhlcBarDatum(
+  ohlc: OhlcValue | null,
+  categoryIndex: number,
+  color: string,
+) {
+  if (!ohlc) {
+    return [];
+  }
+  return {
+    value: [categoryIndex, ...ohlc],
+    itemStyle: {
+      color,
+    },
+  };
+}
+
+function getDirectionItemStyle(increaseHex: string, decreaseHex: string) {
+  return {
+    color: increaseHex,
+    color0: decreaseHex,
+    borderColor: increaseHex,
+    borderColor0: decreaseHex,
+  };
+}
+
+function getSeriesItemStyle(seriesColor: string, hollowFill: string) {
+  return {
+    color: seriesColor,
+    color0: hollowFill,
+    borderColor: seriesColor,
+    borderColor0: seriesColor,
+  };
+}
+
+const renderOhlcItem: CustomSeriesRenderItem = (_params, item) => {
+  const x = toNumber(item.value(0));
+  const open = toNumber(item.value(1));
+  const close = toNumber(item.value(2));
+  const low = toNumber(item.value(3));
+  const high = toNumber(item.value(4));
+  if (
+    x === null ||
+    open === null ||
+    close === null ||
+    low === null ||
+    high === null
+  ) {
+    return null;
+  }
+
+  const openPoint = item.coord([x, open]);
+  const closePoint = item.coord([x, close]);
+  const lowPoint = item.coord([x, low]);
+  const highPoint = item.coord([x, high]);
+  const categorySize = item.size?.([1, 0]);
+  const categoryWidth = Array.isArray(categorySize)
+    ? categorySize[0]
+    : categorySize;
+  if (categoryWidth == null || !Number.isFinite(categoryWidth)) {
+    return null;
+  }
+  const halfWidth = categoryWidth * OHLC_TICK_WIDTH_RATIO;
+  const style = item.style({
+    stroke: item.visual('color'),
+  });
+
+  return {
+    type: 'group',
+    children: [
+      {
+        type: 'line',
+        shape: {
+          x1: lowPoint[0],
+          y1: lowPoint[1],
+          x2: highPoint[0],
+          y2: highPoint[1],
+        },
+        style,
+      },
+      {
+        type: 'line',
+        shape: {
+          x1: openPoint[0],
+          y1: openPoint[1],
+          x2: openPoint[0] - halfWidth,
+          y2: openPoint[1],
+        },
+        style,
+      },
+      {
+        type: 'line',
+        shape: {
+          x1: closePoint[0],
+          y1: closePoint[1],
+          x2: closePoint[0] + halfWidth,
+          y2: closePoint[1],
+        },
+        style,
+      },
+    ],
+  };
+};
+
+function extractOhlc(value: unknown): OhlcValue | null {
+  if (!Array.isArray(value)) {
+    return null;
+  }
+  const raw = value.length >= 5 ? value.slice(1, 5) : value.slice(0, 4);
+  if (raw.length !== 4) {
+    return null;
+  }
+  const [open, close, low, high] = raw.map(item => Number(item));
+  if ([open, close, low, high].some(item => !Number.isFinite(item))) {
+    return null;
+  }
+  return [open, close, low, high];
+}
+
+function extractLineValue(item: CallbackDataParams): number | null {
+  const raw = item.value ?? item.data;

Review Comment:
   On a date where a series has no candle, its moving-average line is padded 
with `null` further down, but `raw` resolves to that `null` here and 
`Number(null)` is `0` and finite — so the tooltip shows a fabricated `0` for 
that point instead of omitting it, unlike the `'-'` warm-up placeholder which 
is correctly skipped. Should a `null` raw value be treated as "no data" the 
same way?



##########
superset-frontend/plugins/plugin-chart-echarts/src/Candlestick/controlPanel.tsx:
##########
@@ -0,0 +1,417 @@
+/**
+ * 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 {
+  ensureIsArray,
+  getColumnLabel,
+  QueryFormColumn,
+  validateNonEmpty,
+} from '@superset-ui/core';
+import {
+  ControlPanelConfig,
+  ControlPanelsContainerProps,
+  ControlSubSectionHeader,
+  D3_TIME_FORMAT_DOCS,
+  DEFAULT_TIME_FORMAT,
+  getStandardizedControls,
+  sections,
+  sharedControls,
+} from '@superset-ui/chart-controls';
+import {
+  legendSection,
+  tooltipTimeFormatControl,
+  tooltipValuesFormatControl,
+  xAxisLabelInterval,
+  xAxisLabelRotation,
+} from '../controls';
+import {
+  CANDLESTICK_SERIES_NAME,
+  DEFAULT_DECREASE_COLOR,
+  DEFAULT_INCREASE_COLOR,
+  DEFAULT_SERIES_STYLE,
+} from './constants';
+import { MOVING_AVERAGE_PERIODS } from './utils';
+
+function hasSeriesDimension({
+  controls,
+}: ControlPanelsContainerProps): boolean {
+  return ensureIsArray(controls?.series?.value).length > 0;
+}
+
+type QueryRow = Record<string, unknown>;
+type ChartQueryResponse = { data?: QueryRow[] };
+
+const uniqueSeriesCountByResponse = new WeakMap<
+  ChartQueryResponse,
+  Map<string, number>
+>();
+
+function getSeriesColumnLabel(
+  props: ControlPanelsContainerProps,
+): string | undefined {
+  const [series] = ensureIsArray(props.controls?.series?.value);
+  if (series == null) {
+    return undefined;
+  }
+  return getColumnLabel(series as QueryFormColumn);
+}
+
+function getChartQueryResponse(
+  props: ControlPanelsContainerProps,
+): ChartQueryResponse | undefined {
+  return (props as { chart?: { queriesResponse?: ChartQueryResponse[] } 
}).chart
+    ?.queriesResponse?.[0];
+}
+
+function countUniqueSeriesValues(
+  props: ControlPanelsContainerProps,
+): number | undefined {
+  const seriesColumn = getSeriesColumnLabel(props);
+  if (!seriesColumn) {
+    return undefined;
+  }
+  const queryResponse = getChartQueryResponse(props);
+  const rows = queryResponse?.data;
+  if (!queryResponse || !rows) {
+    return undefined;
+  }
+  let cachedByColumn = uniqueSeriesCountByResponse.get(queryResponse);
+  if (!cachedByColumn) {
+    cachedByColumn = new Map<string, number>();
+    uniqueSeriesCountByResponse.set(queryResponse, cachedByColumn);
+  }
+  const cachedCount = cachedByColumn.get(seriesColumn);
+  if (cachedCount !== undefined) {
+    return cachedCount;
+  }
+  const count = new Set(
+    rows.map(row =>
+      row[seriesColumn] == null ? null : String(row[seriesColumn]),
+    ),
+  ).size;
+  cachedByColumn.set(seriesColumn, count);
+  return count;
+}
+
+function hasMultipleSeries(props: ControlPanelsContainerProps): boolean {
+  return (countUniqueSeriesValues(props) ?? 0) > 1;
+}
+
+function showColorByDirection(props: ControlPanelsContainerProps): boolean {
+  return !hasMultipleSeries(props);
+}
+
+function showDirectionColors(props: ControlPanelsContainerProps): boolean {
+  return (
+    showColorByDirection(props) &&
+    props.controls?.color_by_direction?.value !== false
+  );
+}
+
+function showColorScheme(props: ControlPanelsContainerProps): boolean {
+  return (
+    hasMultipleSeries(props) ||
+    props.controls?.color_by_direction?.value === false
+  );
+}
+
+const config: ControlPanelConfig = {
+  controlPanelSections: [
+    {
+      label: t('Query'),
+      expanded: true,
+      controlSetRows: [
+        ['x_axis'],
+        ['time_grain_sqla'],
+        [
+          {
+            name: 'open',
+            config: {
+              ...sharedControls.metric,
+              label: t('Open'),
+              description: t('Opening value for each period.'),
+              validators: [validateNonEmpty],
+            },
+          },
+        ],
+        [
+          {
+            name: 'close',
+            config: {
+              ...sharedControls.metric,
+              label: t('Close'),
+              description: t('Closing value for each period.'),
+              validators: [validateNonEmpty],
+            },
+          },
+        ],
+        [
+          {
+            name: 'high',
+            config: {
+              ...sharedControls.metric,
+              label: t('High'),
+              description: t('Highest value for each period.'),
+              validators: [validateNonEmpty],
+            },
+          },
+        ],
+        [
+          {
+            name: 'low',
+            config: {
+              ...sharedControls.metric,
+              label: t('Low'),
+              description: t('Lowest value for each period.'),
+              validators: [validateNonEmpty],
+            },
+          },
+        ],
+        ['series'],
+        ['adhoc_filters'],
+        ['row_limit'],
+      ],
+    },
+    sections.titleControls,
+    {
+      label: t('Chart Options'),
+      expanded: true,
+      controlSetRows: [
+        ['zoomable'],
+        [
+          {
+            name: 'series_style',
+            config: {
+              type: 'SelectControl',
+              label: t('Series style'),
+              renderTrigger: true,
+              default: DEFAULT_SERIES_STYLE,
+              clearable: false,
+              choices: [
+                ['candlestick', t('Candlestick')],
+                ['ohlc', t('OHLC')],
+              ],
+              description: t(
+                'Candlestick draws a filled body between open and close. OHLC 
draws ticks for open and close on a high-low stem.',
+              ),
+            },
+          },
+        ],
+        [
+          {
+            name: 'candlestick_series_name',
+            config: {
+              type: 'TextControl',
+              label: t('Series name'),
+              default: CANDLESTICK_SERIES_NAME,

Review Comment:
   This translated string is evaluated once in the author's browser locale and 
used as the control's saved default, so an untouched control persists that 
translation into the chart's saved params — a dashboard viewer in a different 
locale then sees the original author's word for "Candlestick," not their own. 
Since the transform already falls back to this same constant at render time 
when the value is empty, should the control have no baked-in default (or use it 
only as a placeholder) so the translation resolves per viewer instead?



##########
superset-frontend/plugins/plugin-chart-echarts/src/Candlestick/EchartsCandlestick.tsx:
##########
@@ -0,0 +1,176 @@
+/**
+ * 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 } from 'react';
+import {
+  BinaryQueryObjectFilterClause,
+  TimeGranularity,
+} from '@superset-ui/core';
+import { GenericDataType } from '@apache-superset/core/common';
+import Echart from '../components/Echart';
+import { EchartsHandler, EventHandlers } from '../types';
+import { CandlestickChartTransformedProps } from './types';
+
+type ContextMenuEvent = {
+  event?: { stop?: () => void; event?: PointerEvent };
+  dataIndex?: number;
+  seriesName?: string;
+  seriesType?: string;
+};
+
+function toFilterValue(value: unknown): string | number | boolean | null {
+  if (value == null) {
+    return null;
+  }
+  if (value instanceof Date) {
+    return value.valueOf();
+  }
+  if (
+    typeof value === 'string' ||
+    typeof value === 'number' ||
+    typeof value === 'boolean'
+  ) {
+    return value;
+  }
+  return String(value);
+}
+
+function toFilterClause(
+  col: string,
+  value: unknown,
+  formattedVal: string,
+  grain?: TimeGranularity,
+): BinaryQueryObjectFilterClause {
+  const val = toFilterValue(value);
+  if (val == null) {
+    return {
+      col,
+      op: 'IS NULL' as BinaryQueryObjectFilterClause['op'],
+      val: null,
+      formattedVal,
+    };
+  }
+  return {
+    col,
+    op: '==',
+    val,
+    formattedVal,
+    ...(grain ? { grain } : {}),
+  };
+}
+
+export default function EchartsCandlestick(
+  props: CandlestickChartTransformedProps,
+) {
+  const {
+    height,
+    width,
+    echartOptions,
+    refs,
+    onLegendStateChanged,
+    onContextMenu,
+    formData,
+    coltypeMapping,
+    xAxisColumn,
+    seriesColumn,
+    xValues,
+    xLabels,
+    seriesValues,
+  } = props;
+  const echartRef = useRef<EchartsHandler | null>(null);
+  // eslint-disable-next-line no-param-reassign
+  refs.echartRef = echartRef;
+
+  const hideTooltip = () => {
+    echartRef.current?.getEchartInstance()?.dispatchAction({ type: 'hideTip' 
});
+  };
+
+  const eventHandlers: EventHandlers = {
+    legendselectchanged: payload => {
+      onLegendStateChanged?.(payload.selected);
+    },
+    legendselectall: payload => {
+      onLegendStateChanged?.(payload.selected);
+    },
+    legendinverseselect: payload => {
+      onLegendStateChanged?.(payload.selected);
+    },
+    contextmenu: (eventParams: ContextMenuEvent) => {
+      if (!onContextMenu) {
+        return;
+      }
+      eventParams.event?.stop?.();
+      hideTooltip();
+      const pointerEvent = eventParams.event?.event;
+      if (!pointerEvent) {
+        return;
+      }
+      const drillToDetailFilters: BinaryQueryObjectFilterClause[] = [];
+      const categoryIndex = eventParams.dataIndex;
+      if (
+        xAxisColumn &&
+        categoryIndex != null &&
+        categoryIndex >= 0 &&
+        categoryIndex < xValues.length
+      ) {
+        const xValue = xValues[categoryIndex];
+        const isTemporal =
+          coltypeMapping?.[xAxisColumn] === GenericDataType.Temporal;
+        drillToDetailFilters.push(
+          toFilterClause(
+            xAxisColumn,
+            xValue,
+            xLabels[categoryIndex] ?? String(xValue ?? ''),
+            isTemporal
+              ? (formData.timeGrainSqla as TimeGranularity | undefined)
+              : undefined,
+          ),
+        );
+      }
+      if (seriesColumn && eventParams.seriesType !== 'line') {
+        const seriesValue = seriesValues.find(

Review Comment:
   This looks up the series value by its display name, but a real `null` series 
value and a literal "<NULL>" string value in the same column can both display 
as the same null placeholder — so right-clicking the second one finds the first 
matching entry and drills with the wrong series' value/filter. Should this look 
up by series index instead of display name?



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