import { h as createHashMap, F as isFunction, J as eqNaN, q as isArray, K as parsePercent, b as each, _ as __extends, r as retrieve2, L as retrieve3, M as Point, N as rotate, O as create, Q as retrieve, U as applyTransform, g as extend, y as isString, V as filter, W as defaults, i as isObject, n as map, X as copyTransform, Y as invert, $ as identity, a0 as mul, B as BoundingRect, o as isNumber } from './types-B2BKSWi4.js';
import { m as makeInner, h as eachSeriesOnAxis, j as initExtentForUnion, k as isAxisOnBand, l as eachKeyOnAxis, n as isIntervalScale, o as isLogScale, p as isTimeScale, u as unionExtentStartFromNumber, q as unionExtentEndFromNumber, v as extentHasValue, w as isNullableNumberFinite, x as isOrdinalScale, y as discourageOnAxisZero, z as SCALE_EXTENT_KIND_MAPPING, A as mathMin, B as mathMax, E as ensureExtentAscSimply, F as isValidNumberForExtent, G as getCoordForCoordSysUsageKindBox, H as unionExtentFromNumber, I as unionExtentFromExtent, J as getDataDimensionsOnAxis, K as ensureCopyTransform, L as ensureCopyRect, N as LabelMarginType, O as expandOrShrinkRect, P as isBoundingRectAxisAligned, X as XY, W as WH, Q as OrientedBoundingRect, R as getLayoutParams, T as mergeLayoutParam, U as tokens, C as ComponentModel, Y as Group, Z as remRadian, _ as isNameLocationCenter, $ as ZRText, a0 as createTextStyle, a1 as setTooltipConfig, a2 as getECData, a3 as hasBreaks, a4 as Line, a5 as subPixelOptimizeLine, a6 as normalizeSymbolOffset, a7 as createSymbol, a8 as createAxisLabelsComputingContext, a9 as getTickValueOutermost, M as Model, aa as Rect, ab as shouldShowAllLabels, ac as isRadianAroundZero, ad as AxisTickLabelComputingKind, ae as isIntervalOrLogScale, af as SINGLE_REFERRING } from './axisBand-Boln6nAY.js';

/**
 * NOTICE: Can be only used in `ensureScaleStore(axisLike)`.
 *
 * In most cases the instances of `Axis` and `Scale` are one-to-one mapping and share the same lifecycle.
 * But in some external usage (such as echarts-gl), axis instance does not necessarily exist, and only
 * scale instance and axisModel are used. Therefore we store the internal info on scale instance directly.
 */
var scaleInner = makeInner();
var AXIS_EXTENT_INFO_BUILD_FROM_COORD_SYS_UPDATE = 1;
var AXIS_EXTENT_INFO_BUILD_FROM_EMPTY = 3;
var ScaleRawExtentInfo = /** @class */function () {
  function ScaleRawExtentInfo(scale, model,
  // Typically: data extent from all series on this axis.
  dataExtent, requireStartValue, requireContainShape) {
    var isOrdinal = isOrdinalScale(scale);
    var axisDataLen = isOrdinal
    // FIXME: there is a flaw here: if there is no "block" data processor like `dataZoom`,
    // and progressive rendering is using, here the category result might just only contain
    // the processed chunk rather than the entire result.
    ? model.getCategories().length : null;
    // [CATEGORY_AXIS_MODEL_DATA_IS_EMPTY_ARRAY]:
    // This is only for backward compatibility - `xxxAxis: {data: []}` can declare this axis as
    // a "category" axis and use `series.data` to determine its extent but the axis is blank - only
    // axis line is displayed. This is a conincidence, but it is used in some cases.
    var categoryAxisModelDataIsEmptyArray;
    if (isOrdinal) {
      var axisModelDataArray = model.getCategories(true);
      categoryAxisModelDataIsEmptyArray = axisModelDataArray && !axisModelDataArray.length;
    }
    // NOTE: also considered the input dataExtent may be still in the initialized state `[Infinity, -Infinity]`.
    var dataMM = dataExtent.slice();
    // custom dataMin/dataMax.
    // Also considered `modelDataMinMax[0] > modelDataMinMax[1]` may occur.
    if (isIntervalScale(scale) || isLogScale(scale) || isTimeScale(scale)) {
      unionExtentStartFromNumber(dataMM, parseAxisModelMinMax(scale, model.get('dataMin', true)));
      unionExtentEndFromNumber(dataMM, parseAxisModelMinMax(scale, model.get('dataMax', true)));
    }
    if (!extentHasValue(dataMM)) {
      // dataMM may be still `[Infinity, -Infinity]`, we use `NaN` on the subsequent calculations
      // to force the `noZoomEffMM` to be `[NaN, NaN]` if needed.
      dataMM[0] = dataMM[1] = NaN;
    }
    var noZoomEffMM = [];
    var fixMM = [false, false];
    // Notice: When min/max is not set (that is, when there are null/undefined,
    // which is the most common case), these cases should be ensured:
    // (1) For 'ordinal', show all axis.data.
    // (2) For others:
    //      + `boundaryGap` is applied (if min/max set, boundaryGap is
    //      disabled).
    //      + If `needIncludeZero`, min/max should be zero, otherwise, min/max should
    //      be the result that originalExtent enlarged by boundaryGap.
    // (3) If no data, it should be ensured that `scale.setBlank` is set.
    var modelMinRaw = model.get('min', true);
    if (modelMinRaw === 'dataMin') {
      noZoomEffMM[0] = dataMM[0];
      fixMM[0] = true;
    } else {
      noZoomEffMM[0] = parseAxisModelMinMax(scale, isFunction(modelMinRaw)
      // This callback always provides users the full data extent (before data is filtered).
      ? modelMinRaw({
        min: dataMM[0],
        max: dataMM[1]
      }) : modelMinRaw);
      // If `xxxAxis.min: null/undefined`, min should not be fixed.
      fixMM[0] = noZoomEffMM[0] != null;
    }
    var modelMaxRaw = model.get('max', true);
    if (modelMaxRaw === 'dataMax') {
      noZoomEffMM[1] = dataMM[1];
      fixMM[1] = true;
    } else {
      noZoomEffMM[1] = parseAxisModelMinMax(scale, isFunction(modelMaxRaw)
      // This callback always provides users the full data extent (before data is filtered).
      ? modelMaxRaw({
        min: dataMM[0],
        max: dataMM[1]
      }) : modelMaxRaw);
      // If `xxxAxis.max: null/undefined`, max should not be fixed.
      fixMM[1] = noZoomEffMM[1] != null;
    }
    var boundaryGap = parseBoundaryGapOption(scale, model);
    var span = !isOrdinal
    // PENDING: Historicall behavior but may not reasonable enough.
    ? dataMM[1] - dataMM[0] || Math.abs(dataMM[0]) : null;
    // NOTE: If a numeric axis min/max is specified as 'dataMin'/'dataMax',
    // `boundaryGap` will not be used.
    if (noZoomEffMM[0] == null) {
      noZoomEffMM[0] = isOrdinal ? categoryAxisModelDataIsEmptyArray ? dataMM[0] : axisDataLen ? 0 : NaN : dataMM[0] - boundaryGap[0] * span;
    }
    if (noZoomEffMM[1] == null) {
      noZoomEffMM[1] = isOrdinal ? categoryAxisModelDataIsEmptyArray ? dataMM[1] : axisDataLen ? axisDataLen - 1 : NaN : dataMM[1] + boundaryGap[1] * span;
    }
    // Normalize to `NaN` if invalid; e.g., this may occur when `dataMM` has Infinity.
    !isValidNumberForExtent(noZoomEffMM[0]) && (noZoomEffMM[0] = NaN);
    !isValidNumberForExtent(noZoomEffMM[1]) && (noZoomEffMM[1] = NaN);
    var isBlank = categoryAxisModelDataIsEmptyArray || eqNaN(noZoomEffMM[0]) || eqNaN(noZoomEffMM[1]) || isOrdinal && !axisDataLen;
    // NOTE: `needIncludeZero` is not applicable to LogScale, TimeScale, OrdinalScale.
    var needIncludeZeroApplicable = isIntervalScale(scale);
    var needIncludeZero = needIncludeZeroApplicable && model.needIncludeZero && model.needIncludeZero();
    if (needIncludeZero) {
      if (noZoomEffMM[0] > 0 && noZoomEffMM[1] > 0 && !fixMM[0]) {
        noZoomEffMM[0] = 0;
        // fixMM[0] = true;
      }
      if (noZoomEffMM[0] < 0 && noZoomEffMM[1] < 0 && !fixMM[1]) {
        noZoomEffMM[1] = 0;
        // fixMM[1] = true;
      }
    }
    var needToggleAxisInverse = false;
    if (noZoomEffMM[0] > noZoomEffMM[1]) {
      // Historically, if users set `xxxAxis.min > xxxAxis.max`, or `xxxAxis.max < dataExtent[0]`,
      // or `xxxAxis.min > dataExtent[1]` the behavior is sometimes like `xxxAxis.inverse = true`,
      // sometimes abnormal. We remain backward compatible with the former one, though this feature
      // may not be reasonable.
      // And handle it after "needIncludeZero" is also for backward compatibility.
      noZoomEffMM.reverse();
      needToggleAxisInverse = true;
    }
    var startValue = parseAxisModelMinMax(scale, model.get('startValue', true));
    var startValueSpecified = startValue != null;
    if (!isNullableNumberFinite(startValue) && requireStartValue) {
      startValue = scale.getDefaultStartValue ? scale.getDefaultStartValue() : 0;
    }
    if (isNullableNumberFinite(startValue)
    // Keep backward compatibility and enable `xxxAxis.scale: true` enabled on bar series:
    // if `xxxAxis.scale: true` and `startValue` is not specified, do not union the default `startValue`,
    && (startValueSpecified || !needIncludeZeroApplicable || needIncludeZero)) {
      if (startValue < noZoomEffMM[0] && !fixMM[0]) {
        noZoomEffMM[0] = startValue;
        fixMM[0] = true;
      } else if (startValue > noZoomEffMM[1] && !fixMM[1]) {
        noZoomEffMM[1] = startValue;
        fixMM[1] = true;
      }
    }
    var internal = this._i = {
      scale: scale,
      dataMM: dataMM,
      noZoomEffMM: noZoomEffMM,
      zoomMM: [],
      fixMM: fixMM,
      zoomFixMM: [false, false],
      startValue: startValue,
      isBlank: isBlank,
      incl0: needIncludeZero,
      tggAxInv: needToggleAxisInverse,
      ctnShp: requireContainShape
    };
    sanitizeExtent(internal, noZoomEffMM);
  }
  ScaleRawExtentInfo.prototype.makeNoZoom = function () {
    return this._i.noZoomEffMM.slice();
  };
  ScaleRawExtentInfo.prototype.makeFinal = function () {
    var internal = this._i;
    var zoomMM = internal.zoomMM;
    var noZoomEffMM = internal.noZoomEffMM;
    var zoomFixMM = internal.zoomFixMM;
    var fixMM = internal.fixMM;
    var result = {
      fixMM: fixMM,
      zoomFixMM: zoomFixMM,
      isBlank: internal.isBlank,
      incl0: internal.incl0,
      tggAxInv: internal.tggAxInv,
      ctnShp: internal.ctnShp,
      effMM: noZoomEffMM.slice()
    };
    var effMM = result.effMM;
    // NOTE: Switching `fixMM` probably leads to abrupt extent changes when draging a `dataZoom`
    //  handle, since `fixMM` impact the "nice extent" and "nice ticks" calculation.
    //  Consider a case:
    //    dataZoom `start` is 2% but its `end` is 100%, (or vice versa), we currently only set `fixMM[0]`
    //    as `true` but remain `fixMM[1]` as `false` for this case to avoid unnecessary abrupt change.
    //    Incidentally, the effect is not unacceptable if we set both `fixMM[0]/[1]` as `true`.
    if (zoomMM[0] != null) {
      effMM[0] = zoomMM[0];
      fixMM[0] = zoomFixMM[0] = true;
    }
    if (zoomMM[1] != null) {
      effMM[1] = zoomMM[1];
      fixMM[1] = zoomFixMM[1] = true;
    }
    sanitizeExtent(internal, effMM);
    return result;
  };
  ScaleRawExtentInfo.prototype.makeRenderInfo = function () {
    return {
      startValue: this._i.startValue
    };
  };
  /**
   * NOTICE:
   *  - Do not set them if the percent are 0% or 100%. (See `AxisProxy['reset']`.)
   *  - The caller must ensure `start <= end` and the range is equal or less then `noZoomEffMM`.
   *    (See `AxisProxy['calculateDataWindow']`.)
   *  - The outcome `_zoomMM` may have both `NullUndefined` and a finite value, like `[undefined, 123]`.
   */
  ScaleRawExtentInfo.prototype.setZoomMM = function (idxMinMax, val) {
    this._i.zoomMM[idxMinMax] = val;
  };
  return ScaleRawExtentInfo;
}();
/**
 * Should be called when a new extent is created or modified.
 */
function sanitizeExtent(internal, mm) {
  var scale = internal.scale;
  var dataMM = internal.dataMM;
  if (scale.sanitize) {
    mm[0] = scale.sanitize(mm[0], dataMM);
    mm[1] = scale.sanitize(mm[1], dataMM);
    ensureExtentAscSimply(mm);
  }
}
function parseAxisModelMinMax(scale, minMax) {
  return minMax == null ? null // null/undefined means not specified and other default values can be applied.
  : eqNaN(minMax) ? NaN // NaN means a deliberate invalid number.
  : scale.parse(minMax);
}
function parseBoundaryGapOption(scale, model) {
  var boundaryGapOptionArr;
  if (isOrdinalScale(scale)) {
    boundaryGapOptionArr = [0, 0];
  } else {
    var boundaryGap = model.get('boundaryGap');
    if (typeof boundaryGap === 'boolean') {
      boundaryGap = null;
    }
    boundaryGapOptionArr = isArray(boundaryGap) ? boundaryGap : [boundaryGap, boundaryGap];
  }
  return [parseBoundaryGapOptionItem(boundaryGapOptionArr[0]), parseBoundaryGapOptionItem(boundaryGapOptionArr[1])];
}
function parseBoundaryGapOptionItem(opt) {
  return parsePercent(typeof opt === 'boolean' ? 0 : opt, 1) || 0;
}
/**
 * NOTE: `associateSeriesWithAxis` is not necessarily called, e.g., when
 * an axis is not used by any series.
 */
function ensureScaleStore(axisLike) {
  var store = scaleInner(axisLike.scale);
  if (!store.extent) {
    store.extent = initExtentForUnion();
  }
  return store;
}
/**
 * This supports union extent on case like: pie (or other similar series)
 * lays out on cartesian2d.
 * @see scaleRawExtentInfoCreate
 */
function scaleRawExtentInfoEnableBoxCoordSysUsage(axisLike, coordSysDimIdxMap) {
  ensureScaleStore(axisLike).dimIdxInCoord = coordSysDimIdxMap.get(axisLike.dim);
}
/**
 * @usage
 *  class SomeCoordSys {
 *      static create() {
 *          ecModel.eachSeries(function (seriesModel) {
 *              associateSeriesWithAxis(axis1, seriesModel, ...);
 *              associateSeriesWithAxis(axis2, seriesModel, ...);
 *              // ...
 *          });
 *      }
 *      update() {
 *          scaleRawExtentInfoCreate(axis1);
 *          scaleRawExtentInfoCreate(axis2);
 *      }
 *  }
 *  class AxisProxy {
 *      reset() {
 *          scaleRawExtentInfoCreate(axis1);
 *      }
 *  }
 *
 * NOTICE:
 *  - `associateSeriesWithAxis`(in `axisStatistics.ts`) should be called in:
 *    - Coord sys create method.
 *  - `scaleRawExtentInfoCreate` should be typically called in:
 *    - `dataZoom` processor. It requires processing like:
 *      1. Filter series data by dataZoom1;
 *      2. Union the filtered data and init the extent of the orthogonal axes, which is the 100% of dataZoom2;
 *      3. Filter series data by dataZoom2;
 *      4. ...
 *    - Coord sys update method, for other axes that not covered by `dataZoom`.
 *      NOTE: If a `dataZoom` covers this series, this data and its extent has been dataZoom-filtered.
 *      Therefore this handling should not before `dataZoom`.
 *  - The callback of `min`/`max` in ec option should NOT be called multiple times,
 *    therefore, we initialize `ScaleRawExtentInfo` uniformly in `scaleRawExtentInfoCreate`.
 *
 * @see SCALE_EXTENT_CONSTRUCTION for the full processing flow.
 */
function scaleRawExtentInfoCreate(axis, from) {
  var scale = axis.scale;
  var model = axis.model;
  var axisDim = axis.dim;
  if (scale.rawExtentInfo) {
    return;
  }
  scaleRawExtentInfoCreateDeal(scale, axis, axisDim, model, from);
}
function scaleRawExtentInfoCreateDeal(scale, axis, axisDim, model, from) {
  var scaleStore = ensureScaleStore(axis);
  var extent = scaleStore.extent;
  var requireStartValue = false;
  eachSeriesOnAxis(axis, function (seriesModel) {
    if (seriesModel.boxCoordinateSystem) {
      // This supports union extent on case like: pie (or other similar series)
      // lays out on cartesian2d.
      var coord = getCoordForCoordSysUsageKindBox(seriesModel).coord;
      var dimIdx = scaleStore.dimIdxInCoord;
      if (!(dimIdx >= 0)) ;
      // Only `[val1, val2]` case needs to be supported currently.
      else if (isArray(coord)) {
        var coordItem = coord[dimIdx];
        if (coordItem != null && !isArray(coordItem)) {
          unionExtentFromNumber(extent, scale.parse(coordItem));
        }
      }
    } else if (seriesModel.coordinateSystem) {
      // NOTE: This data may have been filtered by dataZoom on orthogonal axes.
      var data_1 = seriesModel.getData();
      if (data_1) {
        var filter_1 = scale.getFilter ? scale.getFilter() : null;
        each(getDataDimensionsOnAxis(data_1, axisDim), function (dim) {
          unionExtentFromExtent(extent, data_1.getApproximateExtent(dim, filter_1));
        });
      }
      if (seriesModel.__requireStartValue && seriesModel.__requireStartValue(axis)) {
        requireStartValue = true;
      }
    }
  });
  var requireContainShape = determineRequireContainShape(scale, axis, model);
  var rawExtentInfo = new ScaleRawExtentInfo(scale, model, extent, requireStartValue, requireContainShape);
  injectScaleRawExtentInfo(scale, rawExtentInfo, from);
  scaleStore.extent = null; // Clean up
}
/**
 * `rawExtentInfo` may not be created in some cases, such as no series declared or extra useless
 * axes declared in ec option. In this case we still create a default one for that empty axis.
 */
function scaleRawExtentInfoBuildDefault(axisLike, dataExtent) {
  var scale = axisLike.scale;
  injectScaleRawExtentInfo(scale, new ScaleRawExtentInfo(scale, axisLike.model, dataExtent, false, false), AXIS_EXTENT_INFO_BUILD_FROM_EMPTY);
}
function injectScaleRawExtentInfo(scale, scaleRawExtentInfo, from) {
  // @ts-ignore
  scale.rawExtentInfo = scaleRawExtentInfo;
  // @ts-ignore
  scaleRawExtentInfo.from = from;
}
/**
 * See `axisSnippets.ts` for some commonly used handlers.
 *
 * FIXME:
 *  `boundaryGap: true` (i.e., `onBand: true` in code) has long been supported on category axis.
 *  And it is implemented in different code and not merged to this implementation yet.
 */
function registerAxisContainShapeHandler(
// `axisStatKey` is used to quickly omit irrelevant handlers,
// since handlers need to be iterated per axis.
axisStatKey, handler) {
  axisContainShapeHandlerMap.set(axisStatKey, handler);
}
var axisContainShapeHandlerMap = createHashMap();
/**
 * Prepare axis scale extent before "nice".
 * Item of returned array can only be number (including Infinity and NaN).
 */
function adoptScaleRawExtentInfoAndPrepare(scale, model, ecModel, axis, externalDataExtent) {
  if (!scale.rawExtentInfo) {
    scaleRawExtentInfoBuildDefault({
      scale: scale,
      model: model
    }, initExtentForUnion());
  }
  var rawExtentResult = scale.rawExtentInfo.makeFinal();
  // NOTE: This `scale.setExtent()` is required by:
  //  - `axisNiceTicks.ts` and `axisAlignTicks.ts`, where the internal `scaleMapper` may be required.
  var effectiveMinMax = rawExtentResult.effMM;
  scale.setExtent(effectiveMinMax[0], effectiveMinMax[1]);
  scale.setBlank(rawExtentResult.isBlank);
  if (axis && rawExtentResult.tggAxInv && ecModel && !ecModel.get('legacyMinMaxDontInverseAxis')) {
    axis.inverse = !axis.inverse;
  }
  return rawExtentResult;
}
function determineRequireContainShape(scale, axis, model) {
  var onBand = isAxisOnBand(scale, model);
  var modelContainShape = model.get('containShape', true);
  if (modelContainShape == null && !onBand) {
    modelContainShape = true;
  }
  if (!modelContainShape) {
    return false;
  }
  var requireContainShape = false;
  eachKeyOnAxis(axis, function (axisStatKey) {
    requireContainShape = !!axisContainShapeHandlerMap.get(axisStatKey) || requireContainShape;
  });
  return requireContainShape;
}
/**
 * This implements ec option `someAxis.containShape`. That is, expand scale extent slightly to
 * ensure shapes of specific series are fully contained in the axis extent without overflow.
 *
 * NOTICE:
 *  Scale extent (data extent) and axis pixel extent (pixel extent) and are required as inputs.
 *    - See BAND_WIDTH_USED_SCALE_LINEAR_SPAN.
 *    - Axis pixel extent has been set outside, though it may be modified later (e.g., via `outerBounds`).
 *
 * @tutorial [AXIS_CONTAIN_SHAPE_PROCESSING_ORDER]
 *  This is a trade-off between the following 2 approaches:
 *    - Steps: (the current implementation)
 *        1. Process `dataZoom` based on a full window `noZoomEffMM`.
 *        2. Perform "nice" or "align" scale, where `intervalScaleEnsureValidExtent`-ish may be performed to
 *           expand extent to avoid `extent[0] === extent[1]`.
 *        3. Calculate linear supplement of containShape based on the final result.
 *      Cons:
 *        - Abrupt changes occur when zooming away from 0% or 100%.
 *        - Edge shapes are clipped in "dataZoom shadow".
 *    - Steps: (discarded)
 *        1. Calculate linear supplement of containShape based on `noZoomEffMM` and
 *           `intervalScaleEnsureValidExtent`-ish.
 *        2. Process `dataZoom` based on a full window `noZoomEffMM + linearSupplement`.
 *        3. Perform "nice"/"align" scale.
 *      Cons:
 *        - Input `startValue: 0` (in ec option or action) does not corresponds to `0%`, which is unacceptable.
 *        - Not easy to perform `intervalScaleEnsureValidExtent`-ish before "nice"/"align" processing.
 *
 * @see SCALE_EXTENT_CONSTRUCTION for the full processing flow.
 */
function adoptScaleExtentKindMapping(axis, scale, rawExtentResult, ecModel) {
  if (!rawExtentResult.ctnShp) {
    return;
  }
  var linearSupplement;
  eachKeyOnAxis(axis, function (axisStatKey) {
    var handler = axisContainShapeHandlerMap.get(axisStatKey);
    if (handler) {
      // This feature can be implemented by either expanding axis extent or scale extent. The choice depends
      // on whether series shape sizes are defined in pixels or data space. For example, scatter series glyph
      // sizes is mainly defined in pixel, while bar series `bandWidth` is mainly determined by given percents
      // of data scale. Since currently scatter does not require this feature, we implement it only on the
      // data scale.
      var singleLinearSupplement = handler(axis, ecModel);
      if (singleLinearSupplement) {
        linearSupplement = linearSupplement || [0, 0];
        unionExtentStartFromNumber(linearSupplement, singleLinearSupplement[0]);
        unionExtentEndFromNumber(linearSupplement, singleLinearSupplement[1]);
        // Consider the consistency of `onZero` behavior (not varying by series data; otherwise error-prone
        // to users), if any `containShape` really performed on this axis, discourage `onZero`.
        discourageOnAxisZero(axis);
      }
    }
  });
  if (!linearSupplement) {
    return;
  }
  var scaleExtent = scale.getExtent();
  if (isOrdinalScale(scale)) {
    if (!axis.onBand) {
      // - Zooming on `OrdinalScale` auto "snaps" to integer ticks, which causes edge shapes to
      //   always overlap and be clipped at the boundaries. Therefore we always supplement it with
      //   half bandWith to avoid that overlapping.
      // - `linearSupplement` is typically [-0.5, 0.5] in this case. `linearSupplement` exists only
      //   if any series call `registerAxisContainShapeHandler`.
      // - PENDING: For historical reason, `onBand: true` has another implementation to handle
      //   this case. Merge them to this?
      scale.setExtent2(SCALE_EXTENT_KIND_MAPPING, mathMin(scaleExtent[0], scaleExtent[0] + linearSupplement[0]), mathMax(scaleExtent[1], scaleExtent[1] + linearSupplement[1]));
    }
  } else {
    // For other cases, `SCALE_EXTENT_KIND_MAPPING` is only used on the full window of `dataZoom`,
    // where the visual result is more intuitive when zooming: when dataZoom is applied and its ends
    // (i.e., `zoomMM`) do not reach 0% or 100%, the axis ends should exactly respect to the dataZoom
    // ends, and shapes are clipped if overflowing.
    var scaleExtentExpanded = scaleExtent.slice();
    if (!rawExtentResult.zoomFixMM[0]) {
      scaleExtentExpanded[0] = mathMin(scaleExtentExpanded[0], scale.transformOut(scale.transformIn(scaleExtentExpanded[0], null) + linearSupplement[0], null));
    }
    if (!rawExtentResult.zoomFixMM[1]) {
      scaleExtentExpanded[1] = mathMax(scaleExtentExpanded[1], scale.transformOut(scale.transformIn(scaleExtentExpanded[1], null) + linearSupplement[1], null));
    }
    if (scaleExtentExpanded[0] < scaleExtent[0] || scaleExtentExpanded[1] > scaleExtent[1]) {
      scale.setExtent2(SCALE_EXTENT_KIND_MAPPING, scaleExtentExpanded[0], scaleExtentExpanded[1]);
    }
  }
  // NOTE: since currently `SCALE_EXTENT_KIND_MAPPING` is never required to be displayed, we
  // do not need to find a proper precision for that. But if it is required in the future, We
  // can use `getAcceptableTickPrecision` to find a proper precision.
}

var LABEL_LAYOUT_BASE_PROPS = ['label', 'labelLine', 'layoutOption', 'priority', 'defaultAttr', 'marginForce', 'minMarginForce', 'marginDefault', 'suggestIgnore'];
var LABEL_LAYOUT_DIRTY_BIT_OTHERS = 1;
var LABEL_LAYOUT_DIRTY_BIT_OBB = 2;
var LABEL_LAYOUT_DIRTY_ALL = LABEL_LAYOUT_DIRTY_BIT_OTHERS | LABEL_LAYOUT_DIRTY_BIT_OBB;
function setLabelLayoutDirty(labelGeometry, dirtyOrClear, dirtyBits) {
  dirtyBits = dirtyBits || LABEL_LAYOUT_DIRTY_ALL;
  dirtyOrClear ? labelGeometry.dirty |= dirtyBits : labelGeometry.dirty &= ~dirtyBits;
}
function isLabelLayoutDirty(labelGeometry, dirtyBits) {
  dirtyBits = dirtyBits || LABEL_LAYOUT_DIRTY_ALL;
  return labelGeometry.dirty == null || !!(labelGeometry.dirty & dirtyBits);
}
/**
 * [CAUTION]
 *  - No auto dirty propagation mechanism yet. If the transform of the raw label or any of its ancestors is
 *    changed, must sync the changes to the props of `LabelGeometry` by:
 *    either explicitly call:
 *      `setLabelLayoutDirty(labelLayout, true); ensureLabelLayoutWithGeometry(labelLayout);`
 *    or call (if only translation is performed):
 *      `labelLayoutApplyTranslation(labelLayout);`
 *  - `label.ignore` is not necessarily falsy, and not considered in computing `LabelGeometry`,
 *    since it might be modified by some overlap resolving handling.
 *  - To duplicate or make a variation:
 *    use `newLabelLayoutWithGeometry`.
 *
 * The result can also be the input of this method.
 * @return `NullUndefined` if and only if `labelLayout` is `NullUndefined`.
 */
function ensureLabelLayoutWithGeometry(labelLayout) {
  if (!labelLayout) {
    return;
  }
  if (isLabelLayoutDirty(labelLayout)) {
    computeLabelGeometry(labelLayout, labelLayout.label, labelLayout);
  }
  return labelLayout;
}
/**
 * The props in `out` will be filled if existing, or created.
 */
function computeLabelGeometry(out, label, opt) {
  // [CAUTION] These props may be modified directly for performance consideration,
  //  therefore, do not output the internal data structure of zrender Element.
  var rawTransform = label.getComputedTransform();
  out.transform = ensureCopyTransform(out.transform, rawTransform);
  // NOTE: should call `getBoundingRect` after `getComputedTransform`, or may get an inaccurate bounding rect.
  //  The reason is that `getComputedTransform` calls `__host.updateInnerText()` internally, which updates the label
  //  by `textConfig` mounted on the host.
  // PENDING: add a dirty bit for that in zrender?
  var outLocalRect = out.localRect = ensureCopyRect(out.localRect, label.getBoundingRect());
  var labelStyleExt = label.style;
  var margin = labelStyleExt.margin;
  var marginForce = opt && opt.marginForce;
  var minMarginForce = opt && opt.minMarginForce;
  var marginDefault = opt && opt.marginDefault;
  var marginType = labelStyleExt.__marginType;
  if (marginType == null && marginDefault) {
    margin = marginDefault;
    marginType = LabelMarginType.textMargin;
  }
  // `textMargin` and `minMargin` can not exist both.
  for (var i = 0; i < 4; i++) {
    _tmpLabelMargin[i] = marginType === LabelMarginType.minMargin && minMarginForce && minMarginForce[i] != null ? minMarginForce[i] : marginForce && marginForce[i] != null ? marginForce[i] : margin ? margin[i] : 0;
  }
  if (marginType === LabelMarginType.textMargin) {
    expandOrShrinkRect(outLocalRect, _tmpLabelMargin, false, false);
  }
  var outGlobalRect = out.rect = ensureCopyRect(out.rect, outLocalRect);
  if (rawTransform) {
    outGlobalRect.applyTransform(rawTransform);
  }
  // Notice: label.style.margin is actually `minMargin / 2`, handled by `setTextStyleCommon`.
  if (marginType === LabelMarginType.minMargin) {
    expandOrShrinkRect(outGlobalRect, _tmpLabelMargin, false, false);
  }
  out.axisAligned = isBoundingRectAxisAligned(rawTransform);
  (out.label = out.label || {}).ignore = label.ignore;
  setLabelLayoutDirty(out, false);
  setLabelLayoutDirty(out, true, LABEL_LAYOUT_DIRTY_BIT_OBB);
  // Do not remove `obb` (if existing) for reuse, just reset the dirty bit.
  return out;
}
var _tmpLabelMargin = [0, 0, 0, 0];
/**
 * The props in `out` will be filled if existing, or created.
 */
function computeLabelGeometry2(out, rawLocalRect, rawTransform) {
  out.transform = ensureCopyTransform(out.transform, rawTransform);
  out.localRect = ensureCopyRect(out.localRect, rawLocalRect);
  out.rect = ensureCopyRect(out.rect, rawLocalRect);
  if (rawTransform) {
    out.rect.applyTransform(rawTransform);
  }
  out.axisAligned = isBoundingRectAxisAligned(rawTransform);
  out.obb = undefined; // Reset to undefined, will be created by `ensureOBB` when using.
  (out.label = out.label || {}).ignore = false;
  return out;
}
/**
 * This is a shortcut of
 *   ```js
 *   labelLayout.label.x = newX;
 *   labelLayout.label.y = newY;
 *   setLabelLayoutDirty(labelLayout, true);
 *   ensureLabelLayoutWithGeometry(labelLayout);
 *   ```
 * and provide better performance in this common case.
 */
function labelLayoutApplyTranslation(labelLayout, offset) {
  if (!labelLayout) {
    return;
  }
  labelLayout.label.x += offset.x;
  labelLayout.label.y += offset.y;
  labelLayout.label.markRedraw();
  var transform = labelLayout.transform;
  if (transform) {
    transform[4] += offset.x;
    transform[5] += offset.y;
  }
  var globalRect = labelLayout.rect;
  if (globalRect) {
    globalRect.x += offset.x;
    globalRect.y += offset.y;
  }
  var obb = labelLayout.obb;
  if (obb) {
    obb.fromBoundingRect(labelLayout.localRect, transform);
  }
}
/**
 * To duplicate or make a variation of a label layout.
 * Copy the only relevant properties to avoid the conflict or wrongly reuse of the props of `LabelLayoutWithGeometry`.
 */
function newLabelLayoutWithGeometry(newBaseWithDefaults, source) {
  for (var i = 0; i < LABEL_LAYOUT_BASE_PROPS.length; i++) {
    var prop = LABEL_LAYOUT_BASE_PROPS[i];
    if (newBaseWithDefaults[prop] == null) {
      newBaseWithDefaults[prop] = source[prop];
    }
  }
  return ensureLabelLayoutWithGeometry(newBaseWithDefaults);
}
/**
 * Create obb if no one, can cache it.
 */
function ensureOBB(labelGeometry) {
  var obb = labelGeometry.obb;
  if (!obb || isLabelLayoutDirty(labelGeometry, LABEL_LAYOUT_DIRTY_BIT_OBB)) {
    labelGeometry.obb = obb = obb || new OrientedBoundingRect();
    obb.fromBoundingRect(labelGeometry.localRect, labelGeometry.transform);
    setLabelLayoutDirty(labelGeometry, false, LABEL_LAYOUT_DIRTY_BIT_OBB);
  }
  return obb;
}
/**
 * Adjust labels on x/y direction to avoid overlap.
 *
 * PENDING: the current implementation is based on the global bounding rect rather than the local rect,
 *  which may be not preferable in some edge cases when the label has rotation, but works for most cases,
 *  since rotation is unnecessary when there is sufficient space, while squeezing is applied regardless
 *  of overlapping when there is no enough space.
 *
 * NOTICE:
 *  - The input `list` and its content will be modified (sort, label.x/y, rect).
 *  - The caller should sync the modifications to the other parts by
 *    `setLabelLayoutDirty` and `ensureLabelLayoutWithGeometry` if needed.
 *
 * @return adjusted
 */
function shiftLayoutOnXY(list, xyDimIdx,
// 0 for x, 1 for y
minBound,
// for x, leftBound; for y, topBound
maxBound,
// for x, rightBound; for y, bottomBound
// If average the shifts on all labels and add them to 0
// TODO: Not sure if should enable it.
// Pros: The angle of lines will distribute more equally
// Cons: In some layout. It may not what user wanted. like in pie. the label of last sector is usually changed unexpectedly.
balanceShift) {
  var len = list.length;
  var xyDim = XY[xyDimIdx];
  var sizeDim = WH[xyDimIdx];
  if (len < 2) {
    return false;
  }
  list.sort(function (a, b) {
    return a.rect[xyDim] - b.rect[xyDim];
  });
  var lastPos = 0;
  var delta;
  var adjusted = false;
  for (var i = 0; i < len; i++) {
    var item = list[i];
    var rect = item.rect;
    delta = rect[xyDim] - lastPos;
    if (delta < 0) {
      // shiftForward(i, len, -delta);
      rect[xyDim] -= delta;
      item.label[xyDim] -= delta;
      adjusted = true;
    }
    lastPos = rect[xyDim] + rect[sizeDim];
  }
  // TODO bleedMargin?
  var first = list[0];
  var last = list[len - 1];
  var minGap;
  var maxGap;
  updateMinMaxGap();
  // If ends exceed two bounds, squeeze at most 80%, then take the gap of two bounds.
  minGap < 0 && squeezeGaps(-minGap, 0.8);
  maxGap < 0 && squeezeGaps(maxGap, 0.8);
  updateMinMaxGap();
  takeBoundsGap(minGap, maxGap, 1);
  takeBoundsGap(maxGap, minGap, -1);
  // Handle bailout when there is not enough space.
  updateMinMaxGap();
  if (minGap < 0) {
    squeezeWhenBailout(-minGap);
  }
  if (maxGap < 0) {
    squeezeWhenBailout(maxGap);
  }
  function updateMinMaxGap() {
    minGap = first.rect[xyDim] - minBound;
    maxGap = maxBound - last.rect[xyDim] - last.rect[sizeDim];
  }
  function takeBoundsGap(gapThisBound, gapOtherBound, moveDir) {
    if (gapThisBound < 0) {
      // Move from other gap if can.
      var moveFromMaxGap = Math.min(gapOtherBound, -gapThisBound);
      if (moveFromMaxGap > 0) {
        shiftList(moveFromMaxGap * moveDir, 0, len);
        var remained = moveFromMaxGap + gapThisBound;
        if (remained < 0) {
          squeezeGaps(-remained * moveDir, 1);
        }
      } else {
        squeezeGaps(-gapThisBound * moveDir, 1);
      }
    }
  }
  function shiftList(delta, start, end) {
    if (delta !== 0) {
      adjusted = true;
    }
    for (var i = start; i < end; i++) {
      var item = list[i];
      var rect = item.rect;
      rect[xyDim] += delta;
      item.label[xyDim] += delta;
    }
  }
  // Squeeze gaps if the labels exceed margin.
  function squeezeGaps(delta, maxSqeezePercent) {
    var gaps = [];
    var totalGaps = 0;
    for (var i = 1; i < len; i++) {
      var prevItemRect = list[i - 1].rect;
      var gap = Math.max(list[i].rect[xyDim] - prevItemRect[xyDim] - prevItemRect[sizeDim], 0);
      gaps.push(gap);
      totalGaps += gap;
    }
    if (!totalGaps) {
      return;
    }
    var squeezePercent = Math.min(Math.abs(delta) / totalGaps, maxSqeezePercent);
    if (delta > 0) {
      for (var i = 0; i < len - 1; i++) {
        // Distribute the shift delta to all gaps.
        var movement = gaps[i] * squeezePercent;
        // Forward
        shiftList(movement, 0, i + 1);
      }
    } else {
      // Backward
      for (var i = len - 1; i > 0; i--) {
        // Distribute the shift delta to all gaps.
        var movement = gaps[i - 1] * squeezePercent;
        shiftList(-movement, i, len);
      }
    }
  }
  /**
   * Squeeze to allow overlap if there is no more space available.
   * Let other overlapping strategy like hideOverlap do the job instead of keep exceeding the bounds.
   */
  function squeezeWhenBailout(delta) {
    var dir = delta < 0 ? -1 : 1;
    delta = Math.abs(delta);
    var moveForEachLabel = Math.ceil(delta / (len - 1));
    for (var i = 0; i < len - 1; i++) {
      if (dir > 0) {
        // Forward
        shiftList(moveForEachLabel, 0, i + 1);
      } else {
        // Backward
        shiftList(-moveForEachLabel, len - i - 1, len);
      }
      delta -= moveForEachLabel;
      if (delta <= 0) {
        return;
      }
    }
  }
  return adjusted;
}
/**
 * [NOTICE - restore]:
 *  'series:layoutlabels' may be triggered during some EC_PARTIAL_UPDATE passes, such as zooming in series.graph/geo
 *  (`updateLabelLayout`), where the modified `Element` props should be restorable from `defaultAttr`.
 *  @see `SavedLabelAttr` in `LabelManager.ts`
 *  `restoreIgnore` can be called to perform the restore, if needed.
 *
 * [NOTICE - state]:
 *  Regarding Element's states, this method is only designed for the normal state.
 *  PENDING: although currently this method is effectively called in other states in `updateLabelLayout` case,
 *      the bad case is not noticeable in the zooming scenario.
 */
function hideOverlap(labelList) {
  var displayedLabels = [];
  // TODO, render overflow visible first, put in the displayedLabels.
  labelList.sort(function (a, b) {
    return (b.suggestIgnore ? 1 : 0) - (a.suggestIgnore ? 1 : 0) || b.priority - a.priority;
  });
  function hideEl(el) {
    if (!el.ignore) {
      // Show on emphasis.
      var emphasisState = el.ensureState('emphasis');
      if (emphasisState.ignore == null) {
        emphasisState.ignore = false;
      }
    }
    el.ignore = true;
  }
  for (var i = 0; i < labelList.length; i++) {
    var labelItem = ensureLabelLayoutWithGeometry(labelList[i]);
    // The current `el.ignore` is involved, since some previous overlap
    // resolving strategies may have set `el.ignore` to true.
    if (labelItem.label.ignore) {
      continue;
    }
    var label = labelItem.label;
    var labelLine = labelItem.labelLine;
    // NOTICE: even when the with/height of globalRect of a label is 0, the label line should
    // still be displayed, since we should follow the concept of "truncation", meaning that
    // something exists even if it cannot be fully displayed. A visible label line is necessary
    // to allow users to get a tooltip with label info on hover.
    var overlapped = false;
    for (var j = 0; j < displayedLabels.length; j++) {
      if (labelIntersect(labelItem, displayedLabels[j], null, {
        touchThreshold: 0.05
      })) {
        overlapped = true;
        break;
      }
    }
    // TODO Callback to determine if this overlap should be handled?
    if (overlapped) {
      hideEl(label);
      labelLine && hideEl(labelLine);
    } else {
      displayedLabels.push(labelItem);
    }
  }
}
/**
 * Enable fast check for performance; use obb if inevitable.
 * If `mtv` is used, `targetLayoutInfo` can be moved based on the values filled into `mtv`.
 *
 * This method is based only on the current `Element` states (regardless of other states).
 * Typically this method (and the entire layout process) is performed in normal state.
 */
function labelIntersect(baseLayoutInfo, targetLayoutInfo, mtv, intersectOpt) {
  if (!baseLayoutInfo || !targetLayoutInfo) {
    return false;
  }
  if (baseLayoutInfo.label && baseLayoutInfo.label.ignore || targetLayoutInfo.label && targetLayoutInfo.label.ignore) {
    return false;
  }
  // Fast rejection.
  if (!baseLayoutInfo.rect.intersect(targetLayoutInfo.rect, mtv, intersectOpt)) {
    return false;
  }
  if (baseLayoutInfo.axisAligned && targetLayoutInfo.axisAligned) {
    return true; // obb is the same as the normal bounding rect.
  }
  return ensureOBB(baseLayoutInfo).intersect(ensureOBB(targetLayoutInfo), mtv, intersectOpt);
}

// For backward compatibility, do not use a margin. Although the labels might touch the edge of
// the canvas, the chart canvas probably does not have an border or a different background color within a page.
var OUTER_BOUNDS_DEFAULT = {
  left: 0,
  right: 0,
  top: 0,
  bottom: 0
};
var OUTER_BOUNDS_CLAMP_DEFAULT = ['25%', '25%'];
var COORD_SYS_TYPE_CARTESIAN_2D = 'cartesian2d';
var GridModel = /** @class */function (_super) {
  __extends(GridModel, _super);
  function GridModel() {
    return _super !== null && _super.apply(this, arguments) || this;
  }
  GridModel.prototype.mergeDefaultAndTheme = function (option, ecModel) {
    var outerBoundsCp = getLayoutParams(option.outerBounds);
    _super.prototype.mergeDefaultAndTheme.apply(this, arguments);
    if (outerBoundsCp && option.outerBounds) {
      mergeLayoutParam(option.outerBounds, outerBoundsCp);
    }
  };
  GridModel.prototype.mergeOption = function (newOption, ecModel) {
    _super.prototype.mergeOption.apply(this, arguments);
    if (this.option.outerBounds && newOption.outerBounds) {
      mergeLayoutParam(this.option.outerBounds, newOption.outerBounds);
    }
  };
  GridModel.type = 'grid';
  GridModel.dependencies = ['xAxis', 'yAxis'];
  GridModel.layoutMode = 'box';
  GridModel.defaultOption = {
    show: false,
    // zlevel: 0,
    z: 0,
    left: '15%',
    top: 65,
    right: '10%',
    bottom: 80,
    // If grid size contain label
    containLabel: false,
    outerBoundsMode: 'auto',
    outerBounds: OUTER_BOUNDS_DEFAULT,
    outerBoundsContain: 'all',
    outerBoundsClampWidth: OUTER_BOUNDS_CLAMP_DEFAULT[0],
    outerBoundsClampHeight: OUTER_BOUNDS_CLAMP_DEFAULT[1],
    // width: {totalWidth} - left - right,
    // height: {totalHeight} - top - bottom,
    backgroundColor: tokens.color.transparent,
    borderWidth: 1,
    borderColor: tokens.color.neutral30
  };
  return GridModel;
}(ComponentModel);

/*
* 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.
*/


/**
 * AUTO-GENERATED FILE. DO NOT MODIFY.
 */

/*
* 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.
*/
var _impl = null;
function getAxisBreakHelper() {
  return _impl;
}

var AXIS_BREAK_EXPAND_ACTION_TYPE = 'expandAxisBreak';

var PI = Math.PI;
var DEFAULT_CENTER_NAME_MARGIN_LEVELS = [[1, 2, 1, 2], [5, 3, 5, 3], [8, 3, 8, 3]];
var DEFAULT_ENDS_NAME_MARGIN_LEVELS = [[0, 1, 0, 1], [0, 3, 0, 3], [0, 3, 0, 3]];
var getLabelInner = makeInner();
var getTickInner = makeInner();
/**
 * A context shared by difference axisBuilder instances.
 * For cross-axes overlap resolving.
 *
 * Lifecycle constraint: should not over a pass of ec main process.
 *  If model is changed, the context must be disposed.
 *
 * @see AxisBuilderLocalContext
 */
var AxisBuilderSharedContext = /** @class */function () {
  function AxisBuilderSharedContext(resolveAxisNameOverlap) {
    /**
     * [CAUTION] Do not modify this data structure outside this class.
     */
    this.recordMap = {};
    this.resolveAxisNameOverlap = resolveAxisNameOverlap;
  }
  AxisBuilderSharedContext.prototype.ensureRecord = function (axisModel) {
    var dim = axisModel.axis.dim;
    var idx = axisModel.componentIndex;
    var recordMap = this.recordMap;
    var records = recordMap[dim] || (recordMap[dim] = []);
    return records[idx] || (records[idx] = {
      ready: {}
    });
  };
  return AxisBuilderSharedContext;
}();
/**
 * [CAUTION]
 *  1. The call of this function must be after axisLabel overlap handlings
 *     (such as `hideOverlap`, `fixMinMaxLabelShow`) and after transform calculating.
 *  2. Can be called multiple times and should be idempotent.
 */
function resetOverlapRecordToShared(cfg, shared, axisModel, labelLayoutList) {
  var axis = axisModel.axis;
  var record = shared.ensureRecord(axisModel);
  var labelInfoList = [];
  var stOccupiedRect;
  var useStOccupiedRect = hasAxisName(cfg.axisName) && isNameLocationCenter(cfg.nameLocation);
  each(labelLayoutList, function (layout) {
    var layoutInfo = ensureLabelLayoutWithGeometry(layout);
    if (!layoutInfo || layoutInfo.label.ignore) {
      return;
    }
    labelInfoList.push(layoutInfo);
    var transGroup = record.transGroup;
    if (useStOccupiedRect) {
      // Transform to "standard axis" for creating stOccupiedRect (the label rects union).
      transGroup.transform ? invert(_stTransTmp, transGroup.transform) : identity(_stTransTmp);
      if (layoutInfo.transform) {
        mul(_stTransTmp, _stTransTmp, layoutInfo.transform);
      }
      BoundingRect.copy(_stLabelRectTmp, layoutInfo.localRect);
      _stLabelRectTmp.applyTransform(_stTransTmp);
      stOccupiedRect ? stOccupiedRect.union(_stLabelRectTmp) : BoundingRect.copy(stOccupiedRect = new BoundingRect(0, 0, 0, 0), _stLabelRectTmp);
    }
  });
  var sortByDim = Math.abs(record.dirVec.x) > 0.1 ? 'x' : 'y';
  var sortByValue = record.transGroup[sortByDim];
  labelInfoList.sort(function (info1, info2) {
    return Math.abs(info1.label[sortByDim] - sortByValue) - Math.abs(info2.label[sortByDim] - sortByValue);
  });
  if (useStOccupiedRect && stOccupiedRect) {
    var extent = axis.getExtent();
    var axisLineX = Math.min(extent[0], extent[1]);
    var axisLineWidth = Math.max(extent[0], extent[1]) - axisLineX;
    // If `nameLocation` is 'middle', enlarge axis labels boundingRect to axisLine to avoid bad
    //  case like that axis name is placed in the gap between axis labels and axis line.
    // If only one label exists, the entire band should be occupied for
    // visual consistency, so extent it to [0, canvas width].
    stOccupiedRect.union(new BoundingRect(axisLineX, 0, axisLineWidth, 1));
  }
  record.stOccupiedRect = stOccupiedRect;
  record.labelInfoList = labelInfoList;
}
var _stTransTmp = create();
var _stLabelRectTmp = new BoundingRect(0, 0, 0, 0);
/**
 * The default resolver does not involve other axes within the same coordinate system.
 */
var resolveAxisNameOverlapDefault = function (cfg, ctx, axisModel, nameLayoutInfo, nameMoveDirVec, thisRecord) {
  if (isNameLocationCenter(cfg.nameLocation)) {
    var stOccupiedRect = thisRecord.stOccupiedRect;
    if (stOccupiedRect) {
      moveIfOverlap(computeLabelGeometry2({}, stOccupiedRect, thisRecord.transGroup.transform), nameLayoutInfo, nameMoveDirVec);
    }
  } else {
    moveIfOverlapByLinearLabels(thisRecord.labelInfoList, thisRecord.dirVec, nameLayoutInfo, nameMoveDirVec);
  }
};
// [NOTICE] not consider ignore.
function moveIfOverlap(basedLayoutInfo, movableLayoutInfo, moveDirVec) {
  var mtv = new Point();
  if (labelIntersect(basedLayoutInfo, movableLayoutInfo, mtv, {
    direction: Math.atan2(moveDirVec.y, moveDirVec.x),
    bidirectional: false,
    touchThreshold: 0.05
  })) {
    labelLayoutApplyTranslation(movableLayoutInfo, mtv);
  }
}
function moveIfOverlapByLinearLabels(baseLayoutInfoList, baseDirVec, movableLayoutInfo, moveDirVec) {
  // Detect and move from far to close.
  var sameDir = Point.dot(moveDirVec, baseDirVec) >= 0;
  for (var idx = 0, len = baseLayoutInfoList.length; idx < len; idx++) {
    var labelInfo = baseLayoutInfoList[sameDir ? idx : len - 1 - idx];
    if (!labelInfo.label.ignore) {
      moveIfOverlap(labelInfo, movableLayoutInfo, moveDirVec);
    }
  }
}
/**
 * @caution
 * - Ensure it is called after the data processing stage finished.
 * - It might be called before `CahrtView#render`, sush as called at `CoordinateSystem#update`,
 *  thus ensure the result the same whenever it is called.
 *
 * A builder for a straight-line axis.
 *
 * A final axis is translated and rotated from a "standard axis".
 * So opt.position and opt.rotation is required.
 *
 * A "standard axis" is the axis [0,0]-->[abs(axisExtent[1]-axisExtent[0]),0]
 * for example: [0,0]-->[50,0]
 */
var AxisBuilder = /** @class */function () {
  /**
   * [CAUTION]: axisModel.axis.extent/scale must be ready to use.
   */
  function AxisBuilder(axisModel, api, opt, shared) {
    this.group = new Group();
    this._axisModel = axisModel;
    this._api = api;
    this._local = {};
    this._shared = shared || new AxisBuilderSharedContext(resolveAxisNameOverlapDefault);
    this._resetCfgDetermined(opt);
  }
  /**
   * Regarding axis label related configurations, only the change of label.x/y is supported; other
   * changes are not necessary and not performant. To be specific, only `axis.position`
   * (and consequently `labelOffset`) and `axis.extent` can be changed, and assume everything in
   * `axisModel` are not changed.
   * Axis line related configurations can be changed since this method can only be called
   * before they are created.
   */
  AxisBuilder.prototype.updateCfg = function (opt) {
    var raw = this._cfg.raw;
    raw.position = opt.position;
    raw.labelOffset = opt.labelOffset;
    this._resetCfgDetermined(raw);
  };
  /**
   * [CAUTION] For debug usage. Never change it outside!
   */
  AxisBuilder.prototype.__getRawCfg = function () {
    return this._cfg.raw;
  };
  AxisBuilder.prototype._resetCfgDetermined = function (raw) {
    var axisModel = this._axisModel;
    // FIXME:
    //  Currently there is no uniformed way to set default values if an option
    //  is specified null/undefined by user (intentionally or unintentionally),
    //  e.g. null/undefined is not a illegal value for `nameLocation`.
    //  Try to use `getDefaultOption` to address it. But radar has no `getDefaultOption`.
    var axisModelDefaultOption = axisModel.getDefaultOption ? axisModel.getDefaultOption() : {};
    // Default value
    var axisName = retrieve2(raw.axisName, axisModel.get('name'));
    var nameMoveOverlapOption = axisModel.get('nameMoveOverlap');
    if (nameMoveOverlapOption == null || nameMoveOverlapOption === 'auto') {
      nameMoveOverlapOption = retrieve2(raw.defaultNameMoveOverlap, true);
    }
    var cfg = {
      raw: raw,
      position: raw.position,
      rotation: raw.rotation,
      nameDirection: retrieve2(raw.nameDirection, 1),
      tickDirection: retrieve2(raw.tickDirection, 1),
      labelDirection: retrieve2(raw.labelDirection, 1),
      labelOffset: retrieve2(raw.labelOffset, 0),
      silent: retrieve2(raw.silent, true),
      axisName: axisName,
      nameLocation: retrieve3(axisModel.get('nameLocation'), axisModelDefaultOption.nameLocation, 'end'),
      shouldNameMoveOverlap: hasAxisName(axisName) && nameMoveOverlapOption,
      optionHideOverlap: axisModel.get(['axisLabel', 'hideOverlap']),
      showMinorTicks: axisModel.get(['minorTick', 'show'])
    };
    this._cfg = cfg;
    // FIXME Not use a separate text group?
    var transformGroup = new Group({
      x: cfg.position[0],
      y: cfg.position[1],
      rotation: cfg.rotation
    });
    transformGroup.updateTransform();
    this._transformGroup = transformGroup;
    var record = this._shared.ensureRecord(axisModel);
    record.transGroup = this._transformGroup;
    record.dirVec = new Point(Math.cos(-cfg.rotation), Math.sin(-cfg.rotation));
  };
  AxisBuilder.prototype.build = function (axisPartNameMap, extraParams) {
    var _this = this;
    if (!axisPartNameMap) {
      axisPartNameMap = {
        axisLine: true,
        axisTickLabelEstimate: false,
        axisTickLabelDetermine: true,
        axisName: true
      };
    }
    each(AXIS_BUILDER_AXIS_PART_NAMES, function (partName) {
      if (axisPartNameMap[partName]) {
        builders[partName](_this._cfg, _this._local, _this._shared, _this._axisModel, _this.group, _this._transformGroup, _this._api, extraParams || {});
      }
    });
    return this;
  };
  /**
   * Currently only get text align/verticalAlign by rotation.
   * NO `position` is involved, otherwise it have to be performed for each `updateAxisLabelChangableProps`.
   */
  AxisBuilder.innerTextLayout = function (axisRotation, textRotation, direction) {
    var rotationDiff = remRadian(textRotation - axisRotation);
    var textAlign;
    var textVerticalAlign;
    if (isRadianAroundZero(rotationDiff)) {
      // Label is parallel with axis line.
      textVerticalAlign = direction > 0 ? 'top' : 'bottom';
      textAlign = 'center';
    } else if (isRadianAroundZero(rotationDiff - PI)) {
      // Label is inverse parallel with axis line.
      textVerticalAlign = direction > 0 ? 'bottom' : 'top';
      textAlign = 'center';
    } else {
      textVerticalAlign = 'middle';
      if (rotationDiff > 0 && rotationDiff < PI) {
        textAlign = direction > 0 ? 'right' : 'left';
      } else {
        textAlign = direction > 0 ? 'left' : 'right';
      }
    }
    return {
      rotation: rotationDiff,
      textAlign: textAlign,
      textVerticalAlign: textVerticalAlign
    };
  };
  AxisBuilder.makeAxisEventDataBase = function (axisModel) {
    var eventData = {
      componentType: axisModel.mainType,
      componentIndex: axisModel.componentIndex
    };
    eventData[axisModel.mainType + 'Index'] = axisModel.componentIndex;
    return eventData;
  };
  AxisBuilder.isLabelSilent = function (axisModel) {
    var tooltipOpt = axisModel.get('tooltip');
    return axisModel.get('silent')
    // Consider mouse cursor, add these restrictions.
    || !(axisModel.get('triggerEvent') || tooltipOpt && tooltipOpt.show);
  };
  return AxisBuilder;
}();
// Sorted by dependency order.
var AXIS_BUILDER_AXIS_PART_NAMES = ['axisLine', 'axisTickLabelEstimate', 'axisTickLabelDetermine', 'axisName'];
var builders = {
  axisLine: function (cfg, local, shared, axisModel, group, transformGroup, api) {
    var shown = axisModel.get(['axisLine', 'show']);
    if (shown === 'auto') {
      shown = true;
      if (cfg.raw.axisLineAutoShow != null) {
        shown = !!cfg.raw.axisLineAutoShow;
      }
    }
    if (!shown) {
      return;
    }
    var extent = axisModel.axis.getExtent();
    var matrix = transformGroup.transform;
    var pt1 = [extent[0], 0];
    var pt2 = [extent[1], 0];
    var inverse = pt1[0] > pt2[0];
    if (matrix) {
      applyTransform(pt1, pt1, matrix);
      applyTransform(pt2, pt2, matrix);
    }
    var lineStyle = extend({
      lineCap: 'round'
    }, axisModel.getModel(['axisLine', 'lineStyle']).getLineStyle());
    var pathBaseProp = {
      strokeContainThreshold: cfg.raw.strokeContainThreshold || 5,
      silent: true,
      z2: 1,
      style: lineStyle
    };
    if (axisModel.get(['axisLine', 'breakLine']) && hasBreaks(axisModel.axis.scale)) {
      getAxisBreakHelper().buildAxisBreakLine(axisModel, group, transformGroup, pathBaseProp);
    } else {
      var line = new Line(extend({
        shape: {
          x1: pt1[0],
          y1: pt1[1],
          x2: pt2[0],
          y2: pt2[1]
        }
      }, pathBaseProp));
      subPixelOptimizeLine(line.shape, line.style.lineWidth);
      line.anid = 'line';
      group.add(line);
    }
    var arrows = axisModel.get(['axisLine', 'symbol']);
    if (arrows != null) {
      var arrowSize = axisModel.get(['axisLine', 'symbolSize']);
      if (isString(arrows)) {
        // Use the same arrow for start and end point
        arrows = [arrows, arrows];
      }
      if (isString(arrowSize) || isNumber(arrowSize)) {
        // Use the same size for width and height
        arrowSize = [arrowSize, arrowSize];
      }
      var arrowOffset = normalizeSymbolOffset(axisModel.get(['axisLine', 'symbolOffset']) || 0, arrowSize);
      var symbolWidth_1 = arrowSize[0];
      var symbolHeight_1 = arrowSize[1];
      each([{
        rotate: cfg.rotation + Math.PI / 2,
        offset: arrowOffset[0],
        r: 0
      }, {
        rotate: cfg.rotation - Math.PI / 2,
        offset: arrowOffset[1],
        r: Math.sqrt((pt1[0] - pt2[0]) * (pt1[0] - pt2[0]) + (pt1[1] - pt2[1]) * (pt1[1] - pt2[1]))
      }], function (point, index) {
        if (arrows[index] !== 'none' && arrows[index] != null) {
          var symbol = createSymbol(arrows[index], -symbolWidth_1 / 2, -symbolHeight_1 / 2, symbolWidth_1, symbolHeight_1, lineStyle.stroke, true);
          // Calculate arrow position with offset
          var r = point.r + point.offset;
          var pt = inverse ? pt2 : pt1;
          symbol.attr({
            rotation: point.rotate,
            x: pt[0] + r * Math.cos(cfg.rotation),
            y: pt[1] - r * Math.sin(cfg.rotation),
            silent: true,
            z2: 11
          });
          group.add(symbol);
        }
      });
    }
  },
  /**
   * [CAUTION] This method can be called multiple times, following the change due to `resetCfg` called
   *  in size measurement. Thus this method should be idempotent, and should be performant.
   */
  axisTickLabelEstimate: function (cfg, local, shared, axisModel, group, transformGroup, api, extraParams) {
    var needCallLayout = dealLastTickLabelResultReusable(local, group, extraParams);
    if (needCallLayout) {
      layOutAxisTickLabel(cfg, local, shared, axisModel, group, transformGroup, api, AxisTickLabelComputingKind.estimate);
    }
  },
  /**
   * Finish axis tick label build.
   * Can be only called once.
   */
  axisTickLabelDetermine: function (cfg, local, shared, axisModel, group, transformGroup, api, extraParams) {
    var needCallLayout = dealLastTickLabelResultReusable(local, group, extraParams);
    if (needCallLayout) {
      layOutAxisTickLabel(cfg, local, shared, axisModel, group, transformGroup, api, AxisTickLabelComputingKind.determine);
    }
    var ticksEls = buildAxisMajorTicks(cfg, group, transformGroup, axisModel);
    syncLabelIgnoreToMajorTicks(cfg, local.labelLayoutList, ticksEls);
    buildAxisMinorTicks(cfg, group, transformGroup, axisModel, cfg.tickDirection);
  },
  /**
   * [CAUTION] This method can be called multiple times, following the change due to `resetCfg` called
   *  in size measurement. Thus this method should be idempotent, and should be performant.
   */
  axisName: function (cfg, local, shared, axisModel, group, transformGroup, api, extraParams) {
    var sharedRecord = shared.ensureRecord(axisModel);
    // Remove the existing name result created in estimation phase.
    if (local.nameEl) {
      group.remove(local.nameEl);
      local.nameEl = sharedRecord.nameLayout = sharedRecord.nameLocation = null;
    }
    var name = cfg.axisName;
    if (!hasAxisName(name)) {
      return;
    }
    var nameLocation = cfg.nameLocation;
    var nameDirection = cfg.nameDirection;
    var textStyleModel = axisModel.getModel('nameTextStyle');
    var gap = axisModel.get('nameGap') || 0;
    var extent = axisModel.axis.getExtent();
    var gapStartEndSignal = axisModel.axis.inverse ? -1 : 1;
    var pos = new Point(0, 0);
    var nameMoveDirVec = new Point(0, 0);
    if (nameLocation === 'start') {
      pos.x = extent[0] - gapStartEndSignal * gap;
      nameMoveDirVec.x = -gapStartEndSignal;
    } else if (nameLocation === 'end') {
      pos.x = extent[1] + gapStartEndSignal * gap;
      nameMoveDirVec.x = gapStartEndSignal;
    } else {
      // 'middle' or 'center'
      pos.x = (extent[0] + extent[1]) / 2;
      pos.y = cfg.labelOffset + nameDirection * gap;
      nameMoveDirVec.y = nameDirection;
    }
    var mt = create();
    nameMoveDirVec.transform(rotate(mt, mt, cfg.rotation));
    var nameRotation = axisModel.get('nameRotate');
    if (nameRotation != null) {
      nameRotation = nameRotation * PI / 180; // To radian.
    }
    var labelLayout;
    var axisNameAvailableWidth;
    if (isNameLocationCenter(nameLocation)) {
      labelLayout = AxisBuilder.innerTextLayout(cfg.rotation, nameRotation != null ? nameRotation : cfg.rotation,
      // Adapt to axis.
      nameDirection);
    } else {
      labelLayout = endTextLayout(cfg.rotation, nameLocation, nameRotation || 0, extent);
      axisNameAvailableWidth = cfg.raw.axisNameAvailableWidth;
      if (axisNameAvailableWidth != null) {
        axisNameAvailableWidth = Math.abs(axisNameAvailableWidth / Math.sin(labelLayout.rotation));
        !isFinite(axisNameAvailableWidth) && (axisNameAvailableWidth = null);
      }
    }
    var textFont = textStyleModel.getFont();
    var truncateOpt = axisModel.get('nameTruncate', true) || {};
    var ellipsis = truncateOpt.ellipsis;
    var maxWidth = retrieve(cfg.raw.nameTruncateMaxWidth, truncateOpt.maxWidth, axisNameAvailableWidth);
    var nameMarginLevel = extraParams.nameMarginLevel || 0;
    var textEl = new ZRText({
      x: pos.x,
      y: pos.y,
      rotation: labelLayout.rotation,
      silent: AxisBuilder.isLabelSilent(axisModel),
      style: createTextStyle(textStyleModel, {
        text: name,
        font: textFont,
        overflow: 'truncate',
        width: maxWidth,
        ellipsis: ellipsis,
        fill: textStyleModel.getTextColor() || axisModel.get(['axisLine', 'lineStyle', 'color']),
        align: textStyleModel.get('align') || labelLayout.textAlign,
        verticalAlign: textStyleModel.get('verticalAlign') || labelLayout.textVerticalAlign
      }),
      z2: 1
    });
    setTooltipConfig({
      el: textEl,
      componentModel: axisModel,
      itemName: name
    });
    textEl.__fullText = name;
    // Id for animation
    textEl.anid = 'name';
    if (axisModel.get('triggerEvent')) {
      var eventData = AxisBuilder.makeAxisEventDataBase(axisModel);
      eventData.targetType = 'axisName';
      eventData.name = name;
      getECData(textEl).eventData = eventData;
    }
    transformGroup.add(textEl);
    textEl.updateTransform();
    local.nameEl = textEl;
    var nameLayout = sharedRecord.nameLayout = ensureLabelLayoutWithGeometry({
      label: textEl,
      priority: textEl.z2,
      defaultAttr: {
        ignore: textEl.ignore
      },
      marginDefault: isNameLocationCenter(nameLocation)
      // Make axis name visually far from axis labels.
      // (but not too aggressive, consider multiple small charts)
      ? DEFAULT_CENTER_NAME_MARGIN_LEVELS[nameMarginLevel]
      // top/button margin is set to `0` to inserted the xAxis name into the indention
      // above the axis labels to save space. (see example below.)
      : DEFAULT_ENDS_NAME_MARGIN_LEVELS[nameMarginLevel]
    });
    sharedRecord.nameLocation = nameLocation;
    group.add(textEl);
    textEl.decomposeTransform();
    if (cfg.shouldNameMoveOverlap && nameLayout) {
      var record = shared.ensureRecord(axisModel);
      shared.resolveAxisNameOverlap(cfg, shared, axisModel, nameLayout, nameMoveDirVec, record);
    }
  }
};
function layOutAxisTickLabel(cfg, local, shared, axisModel, group, transformGroup, api, kind) {
  if (!axisLabelBuildResultExists(local)) {
    buildAxisLabel(cfg, local, group, kind, axisModel, api);
  }
  var labelLayoutList = local.labelLayoutList;
  updateAxisLabelChangableProps(cfg, axisModel, labelLayoutList, transformGroup);
  var optionHideOverlap = cfg.optionHideOverlap;
  fixMinMaxLabelShow(axisModel, labelLayoutList, optionHideOverlap);
  if (optionHideOverlap) {
    // This bit fixes the label overlap issue for the time chart.
    // See https://github.com/apache/echarts/issues/14266 for more.
    hideOverlap(
    // Filter the already ignored labels by the previous overlap resolving methods.
    filter(labelLayoutList, function (layout) {
      return layout && !layout.label.ignore;
    }));
  }
  // Always call it even this axis has no name, since it serves in overlapping detection
  // and grid outerBounds on other axis.
  resetOverlapRecordToShared(cfg, shared, axisModel, labelLayoutList);
}
function endTextLayout(rotation, textPosition, textRotate, extent) {
  var rotationDiff = remRadian(textRotate - rotation);
  var textAlign;
  var textVerticalAlign;
  var inverse = extent[0] > extent[1];
  var onLeft = textPosition === 'start' && !inverse || textPosition !== 'start' && inverse;
  if (isRadianAroundZero(rotationDiff - PI / 2)) {
    textVerticalAlign = onLeft ? 'bottom' : 'top';
    textAlign = 'center';
  } else if (isRadianAroundZero(rotationDiff - PI * 1.5)) {
    textVerticalAlign = onLeft ? 'top' : 'bottom';
    textAlign = 'center';
  } else {
    textVerticalAlign = 'middle';
    if (rotationDiff < PI * 1.5 && rotationDiff > PI / 2) {
      textAlign = onLeft ? 'left' : 'right';
    } else {
      textAlign = onLeft ? 'right' : 'left';
    }
  }
  return {
    rotation: rotationDiff,
    textAlign: textAlign,
    textVerticalAlign: textVerticalAlign
  };
}
/**
 * Assume `labelLayoutList` has no `label.ignore: true`.
 * Assume `labelLayoutList` have been sorted by value ascending order.
 */
function fixMinMaxLabelShow(axisModel, labelLayoutList, optionHideOverlap) {
  var axis = axisModel.axis;
  var customValuesOption = axisModel.get(['axisLabel', 'customValues']);
  if (shouldShowAllLabels(axis)) {
    return;
  }
  // FIXME
  // Have not consider onBand yet, where tick els is more than label els.
  // Assert no ignore in labels.
  function deal(showMinMaxLabelOption, outmostLabelIdx, innerLabelIdx) {
    var outmostLabelLayout = ensureLabelLayoutWithGeometry(labelLayoutList[outmostLabelIdx]);
    var innerLabelLayout = ensureLabelLayoutWithGeometry(labelLayoutList[innerLabelIdx]);
    var scale = axis.scale;
    if (!outmostLabelLayout || !innerLabelLayout) {
      return;
    }
    if (showMinMaxLabelOption == null) {
      if (!optionHideOverlap && customValuesOption) {
        // In this case, users are unlikely to expect labels to be hidden.
        return;
      }
      var tick = getLabelInner(outmostLabelLayout.label).labelInfo.tick;
      if (
      // TimeScale does not expand extent to "nice", so eliminate labels that are not nice.
      isTimeScale(scale) && tick.notNice
      // Category axis does not expect tick that out of axisLabel.internal to be displayed
      // unless required.
      || isOrdinalScale(scale) && tick.offInterval) {
        ignoreEl(outmostLabelLayout.label);
        return;
      }
    }
    if (showMinMaxLabelOption === false || outmostLabelLayout.suggestIgnore) {
      ignoreEl(outmostLabelLayout.label);
      return;
    }
    if (innerLabelLayout.suggestIgnore) {
      ignoreEl(innerLabelLayout.label);
      return;
    }
    // PENDING: Originally we thought `optionHideOverlap === false` means do not hide anything,
    //  since currently the bounding rect of text might not accurate enough and might slightly bigger,
    //  which causes false positive. But `optionHideOverlap: null/undfined` is falsy and likely
    //  be treated as false.
    // In most fonts the glyph does not reach the boundary of the bounding rect.
    // This is needed to avoid too aggressive to hide two elements that meet at the edge
    // due to compact layout by the same bounding rect or OBB.
    var touchThreshold = 0.1;
    // This treatment is for backward compatibility. And `!optionHideOverlap` implies that
    // the user accepts the visual touch between adjacent labels, thus "hide min/max label"
    // should be conservative, since the space might be sufficient in this case.
    if (!optionHideOverlap) {
      var marginForce = [0, 0, 0, 0];
      // Make a copy to apply `ignoreMargin`.
      outmostLabelLayout = newLabelLayoutWithGeometry({
        marginForce: marginForce
      }, outmostLabelLayout);
      innerLabelLayout = newLabelLayoutWithGeometry({
        marginForce: marginForce
      }, innerLabelLayout);
    }
    if (labelIntersect(outmostLabelLayout, innerLabelLayout, null, {
      touchThreshold: touchThreshold
    })) {
      if (showMinMaxLabelOption) {
        ignoreEl(innerLabelLayout.label);
      } else {
        ignoreEl(outmostLabelLayout.label);
      }
    }
  }
  // If min or max are user set, we need to check
  // If the tick on min(max) are overlap on their neighbour tick
  // If they are overlapped, we need to hide the min(max) tick label
  var showMinLabelOption = axisModel.get(['axisLabel', 'showMinLabel']);
  var showMaxLabelOption = axisModel.get(['axisLabel', 'showMaxLabel']);
  var labelsLen = labelLayoutList.length;
  deal(showMinLabelOption, 0, 1);
  deal(showMaxLabelOption, labelsLen - 1, labelsLen - 2);
}
// Under default settings, it is visually odd to display a tick without its label,
// since ticks extend from axis line towards labels and serve as visual guide.
// PENDING: Is there opposite cases?
function syncLabelIgnoreToMajorTicks(cfg, labelLayoutList, tickEls) {
  if (cfg.showMinorTicks) {
    // It probably unreasonable to hide major ticks when show minor ticks.
    return;
  }
  each(labelLayoutList, function (labelLayout) {
    if (labelLayout && labelLayout.label.ignore) {
      for (var idx = 0; idx < tickEls.length; idx++) {
        var tickEl = tickEls[idx];
        // Assume small array, linear search is fine for performance.
        // PENDING: measure?
        var tickInner = getTickInner(tickEl);
        var labelInner = getLabelInner(labelLayout.label);
        if (tickInner.tickValue != null && !tickInner.onBand && tickInner.tickValue === labelInner.labelInfo.tick.value) {
          ignoreEl(tickEl);
          return;
        }
      }
    }
  });
}
function ignoreEl(el) {
  el && (el.ignore = true);
}
function createTicks(ticksCoords, tickTransform, tickEndCoord, tickLineStyle, anidPrefix) {
  var tickEls = [];
  var pt1 = [];
  var pt2 = [];
  for (var i = 0; i < ticksCoords.length; i++) {
    var tickCoord = ticksCoords[i].coord;
    pt1[0] = tickCoord;
    pt1[1] = 0;
    pt2[0] = tickCoord;
    pt2[1] = tickEndCoord;
    if (tickTransform) {
      applyTransform(pt1, pt1, tickTransform);
      applyTransform(pt2, pt2, tickTransform);
    }
    // Tick line, Not use group transform to have better line draw
    var tickEl = new Line({
      shape: {
        x1: pt1[0],
        y1: pt1[1],
        x2: pt2[0],
        y2: pt2[1]
      },
      style: tickLineStyle,
      z2: 2,
      autoBatch: true,
      silent: true
    });
    subPixelOptimizeLine(tickEl.shape, tickEl.style.lineWidth);
    tickEl.anid = anidPrefix + '_' + ticksCoords[i].tickValue;
    tickEls.push(tickEl);
    var inner = getTickInner(tickEl);
    inner.onBand = !!ticksCoords[i].onBand;
    inner.tickValue = ticksCoords[i].tickValue;
  }
  return tickEls;
}
function buildAxisMajorTicks(cfg, group, transformGroup, axisModel) {
  var axis = axisModel.axis;
  var tickModel = axisModel.getModel('axisTick');
  var shown = tickModel.get('show');
  if (shown === 'auto') {
    shown = true;
    if (cfg.raw.axisTickAutoShow != null) {
      shown = !!cfg.raw.axisTickAutoShow;
    }
  }
  if (!shown || axis.scale.isBlank()) {
    return [];
  }
  var lineStyleModel = tickModel.getModel('lineStyle');
  var tickEndCoord = cfg.tickDirection * tickModel.get('length');
  var ticksCoords = axis.getTicksCoords();
  var ticksEls = createTicks(ticksCoords, transformGroup.transform, tickEndCoord, defaults(lineStyleModel.getLineStyle(), {
    stroke: axisModel.get(['axisLine', 'lineStyle', 'color'])
  }), 'ticks');
  for (var i = 0; i < ticksEls.length; i++) {
    group.add(ticksEls[i]);
  }
  return ticksEls;
}
function buildAxisMinorTicks(cfg, group, transformGroup, axisModel, tickDirection) {
  var axis = axisModel.axis;
  var minorTickModel = axisModel.getModel('minorTick');
  if (!cfg.showMinorTicks || axis.scale.isBlank()) {
    return;
  }
  var minorTicksCoords = axis.getMinorTicksCoords();
  if (!minorTicksCoords.length) {
    return;
  }
  var lineStyleModel = minorTickModel.getModel('lineStyle');
  var tickEndCoord = tickDirection * minorTickModel.get('length');
  var minorTickLineStyle = defaults(lineStyleModel.getLineStyle(), defaults(axisModel.getModel('axisTick').getLineStyle(), {
    stroke: axisModel.get(['axisLine', 'lineStyle', 'color'])
  }));
  for (var i = 0; i < minorTicksCoords.length; i++) {
    var minorTicksEls = createTicks(minorTicksCoords[i], transformGroup.transform, tickEndCoord, minorTickLineStyle, 'minorticks_' + i);
    for (var k = 0; k < minorTicksEls.length; k++) {
      group.add(minorTicksEls[k]);
    }
  }
}
// Return whether need to call `layOutAxisTickLabel` again.
function dealLastTickLabelResultReusable(local, group, extraParams) {
  if (axisLabelBuildResultExists(local)) {
    var axisLabelsCreationContext = local.axisLabelsCreationContext;
    var noPxChangeTryDetermine = axisLabelsCreationContext.out.noPxChangeTryDetermine;
    if (extraParams.noPxChange) {
      var canDetermine = true;
      for (var idx = 0; idx < noPxChangeTryDetermine.length; idx++) {
        canDetermine = canDetermine && noPxChangeTryDetermine[idx]();
      }
      if (canDetermine) {
        return false;
      }
    }
    if (noPxChangeTryDetermine.length) {
      // Remove the result of `buildAxisLabel`
      group.remove(local.labelGroup);
      axisLabelBuildResultSet(local, null, null, null);
    }
  }
  return true;
}
function buildAxisLabel(cfg, local, group, kind, axisModel, api) {
  var axis = axisModel.axis;
  var show = retrieve(cfg.raw.axisLabelShow, axisModel.get(['axisLabel', 'show']));
  var labelGroup = new Group();
  group.add(labelGroup);
  var axisLabelCreationCtx = createAxisLabelsComputingContext(kind);
  if (!show || axis.scale.isBlank()) {
    axisLabelBuildResultSet(local, [], labelGroup, axisLabelCreationCtx);
    return;
  }
  var labelModel = axisModel.getModel('axisLabel');
  var labels = axis.getViewLabels(axisLabelCreationCtx);
  // Special label rotate.
  var labelRotation = (retrieve(cfg.raw.labelRotate, labelModel.get('rotate')) || 0) * PI / 180;
  var labelLayout = AxisBuilder.innerTextLayout(cfg.rotation, labelRotation, cfg.labelDirection);
  var rawCategoryData = axisModel.getCategories && axisModel.getCategories(true);
  var labelEls = [];
  var triggerEvent = axisModel.get('triggerEvent');
  var z2Min = Infinity;
  var z2Max = -Infinity;
  each(labels, function (labelItem, index) {
    var _a;
    var labelItemTick = labelItem.tick;
    var formattedLabel = labelItem.formattedLabel;
    var rawLabel = labelItem.rawLabel;
    var itemLabelModel = labelModel;
    var tickValue = getTickValueOutermost(axis.scale, labelItemTick);
    if (rawCategoryData && rawCategoryData[tickValue]) {
      var rawCategoryItem = rawCategoryData[tickValue];
      if (isObject(rawCategoryItem) && rawCategoryItem.textStyle) {
        itemLabelModel = new Model(rawCategoryItem.textStyle, labelModel, axisModel.ecModel);
      }
    }
    var textColor = itemLabelModel.getTextColor() || axisModel.get(['axisLine', 'lineStyle', 'color']);
    var align = itemLabelModel.getShallow('align', true) || labelLayout.textAlign;
    var alignMin = retrieve2(itemLabelModel.getShallow('alignMinLabel', true), align);
    var alignMax = retrieve2(itemLabelModel.getShallow('alignMaxLabel', true), align);
    var verticalAlign = itemLabelModel.getShallow('verticalAlign', true) || itemLabelModel.getShallow('baseline', true) || labelLayout.textVerticalAlign;
    var verticalAlignMin = retrieve2(itemLabelModel.getShallow('verticalAlignMinLabel', true), verticalAlign);
    var verticalAlignMax = retrieve2(itemLabelModel.getShallow('verticalAlignMaxLabel', true), verticalAlign);
    var z2 = 10 + (((_a = labelItemTick.time) === null || _a === void 0 ? void 0 : _a.level) || 0);
    z2Min = Math.min(z2Min, z2);
    z2Max = Math.max(z2Max, z2);
    var textEl = new ZRText({
      // --- transform props start ---
      // All of the transform props MUST not be set here, but should be set in
      // `updateAxisLabelChangableProps`, because they may change in estimation,
      // and need to calculate based on global coord sys by `decomposeTransform`.
      x: 0,
      y: 0,
      rotation: 0,
      // --- transform props end ---
      silent: AxisBuilder.isLabelSilent(axisModel),
      z2: z2,
      style: createTextStyle(itemLabelModel, {
        text: formattedLabel,
        align: index === 0 ? alignMin : index === labels.length - 1 ? alignMax : align,
        verticalAlign: index === 0 ? verticalAlignMin : index === labels.length - 1 ? verticalAlignMax : verticalAlign,
        fill: isFunction(textColor) ? textColor(
        // (1) In category axis with data zoom, tick is not the original
        // index of axis.data. So tick should not be exposed to user
        // in category axis.
        // (2) Compatible with previous version, which always use formatted label as
        // input. But in interval scale the formatted label is like '223,445', which
        // maked user replace ','. So we modify it to return original val but remain
        // it as 'string' to avoid error in replacing.
        axis.type === 'category' ? rawLabel : axis.type === 'value' ? tickValue + '' : tickValue, index) : textColor
      })
    });
    textEl.anid = 'label_' + tickValue;
    var inner = getLabelInner(textEl);
    inner.labelInfo = labelItem;
    inner.layoutRotation = labelLayout.rotation;
    setTooltipConfig({
      el: textEl,
      componentModel: axisModel,
      itemName: formattedLabel,
      formatterParamsExtra: {
        isTruncated: function () {
          return textEl.isTruncated;
        },
        value: rawLabel,
        tickIndex: index
      }
    });
    // Pack data for mouse event
    if (triggerEvent) {
      var eventData = AxisBuilder.makeAxisEventDataBase(axisModel);
      eventData.targetType = 'axisLabel';
      eventData.value = rawLabel;
      eventData.tickIndex = index;
      var labelItemTickBreak = labelItem.tick["break"];
      if (labelItemTickBreak) {
        var labelItemTickBreakParsedBreak = labelItemTickBreak.parsedBreak;
        eventData["break"] = {
          // type: labelItem.break.type,
          start: labelItemTickBreakParsedBreak.vmin,
          end: labelItemTickBreakParsedBreak.vmax
        };
      }
      if (axis.type === 'category') {
        eventData.dataIndex = tickValue;
      }
      getECData(textEl).eventData = eventData;
      if (labelItemTickBreak) {
        addBreakEventHandler(axisModel, api, textEl, labelItemTickBreak);
      }
    }
    labelEls.push(textEl);
    labelGroup.add(textEl);
  });
  var labelLayoutList = map(labelEls, function (label) {
    return {
      label: label,
      priority: getLabelInner(label).labelInfo.tick["break"] ? label.z2 + (z2Max - z2Min + 1) // Make break labels be highest priority.
      : label.z2,
      defaultAttr: {
        ignore: label.ignore
      }
    };
  });
  axisLabelBuildResultSet(local, labelLayoutList, labelGroup, axisLabelCreationCtx);
}
// Indicate that `layOutAxisTickLabel` has been called.
function axisLabelBuildResultExists(local) {
  return !!local.labelLayoutList;
}
function axisLabelBuildResultSet(local, labelLayoutList, labelGroup, axisLabelsCreationContext) {
  // Ensure the same lifetime.
  local.labelLayoutList = labelLayoutList;
  local.labelGroup = labelGroup;
  local.axisLabelsCreationContext = axisLabelsCreationContext;
}
function updateAxisLabelChangableProps(cfg, axisModel, labelLayoutList, transformGroup) {
  var labelMargin = axisModel.get(['axisLabel', 'margin']);
  each(labelLayoutList, function (layout, idx) {
    var geometry = ensureLabelLayoutWithGeometry(layout);
    if (!geometry) {
      return;
    }
    var labelEl = geometry.label;
    var inner = getLabelInner(labelEl);
    // See the comment in `suggestIgnore`.
    geometry.suggestIgnore = labelEl.ignore;
    // Currently no `ignore:true` is set in `buildAxisLabel`
    // But `ignore:true` may be set subsequently for overlap handling, thus reset it here.
    labelEl.ignore = false;
    copyTransform(_tmpLayoutEl, _tmpLayoutElReset);
    var axis = axisModel.axis;
    _tmpLayoutEl.x = axis.dataToCoord(getTickValueOutermost(axis.scale, inner.labelInfo.tick));
    _tmpLayoutEl.y = cfg.labelOffset + cfg.labelDirection * labelMargin;
    _tmpLayoutEl.rotation = inner.layoutRotation;
    transformGroup.add(_tmpLayoutEl);
    _tmpLayoutEl.updateTransform();
    transformGroup.remove(_tmpLayoutEl);
    _tmpLayoutEl.decomposeTransform();
    copyTransform(labelEl, _tmpLayoutEl);
    labelEl.markRedraw();
    setLabelLayoutDirty(geometry, true);
    ensureLabelLayoutWithGeometry(geometry);
  });
}
var _tmpLayoutEl = new Rect();
var _tmpLayoutElReset = new Rect();
function hasAxisName(axisName) {
  return !!axisName;
}
function addBreakEventHandler(axisModel, api, textEl, visualBreak) {
  textEl.on('click', function (params) {
    var payload = {
      type: AXIS_BREAK_EXPAND_ACTION_TYPE,
      breaks: [{
        start: visualBreak.parsedBreak.breakOption.start,
        end: visualBreak.parsedBreak.breakOption.end
      }]
    };
    payload[axisModel.axis.dim + "AxisIndex"] = axisModel.componentIndex;
    api.dispatchAction(payload);
  });
}

/**
 * [__CAUTION__]
 *  MUST guarantee: if only the input `rect` and `axis.extent` changed,
 *  only `layout.position` changes.
 *  This character is replied on `grid.contain` calculation in `AxisBuilder`.
 *  @see updateCartesianAxisViewCommonPartBuilder
 *
 * Can only be called after coordinate system creation stage.
 * (Can be called before coordinate system update stage).
 */
function layout(rect, axisModel, opt) {
  opt = opt || {};
  var axis = axisModel.axis;
  var layout = {};
  var otherAxisOnZeroOf = axis.getAxesOnZeroOf()[0];
  var rawAxisPosition = axis.position;
  var axisPosition = otherAxisOnZeroOf ? 'onZero' : rawAxisPosition;
  var axisDim = axis.dim;
  var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  var idx = {
    left: 0,
    right: 1,
    top: 0,
    bottom: 1,
    onZero: 2
  };
  var axisOffset = axisModel.get('offset') || 0;
  var posBound = axisDim === 'x' ? [rectBound[2] - axisOffset, rectBound[3] + axisOffset] : [rectBound[0] - axisOffset, rectBound[1] + axisOffset];
  if (otherAxisOnZeroOf) {
    var onZeroCoord = otherAxisOnZeroOf.toGlobalCoord(otherAxisOnZeroOf.dataToCoord(0));
    posBound[idx.onZero] = Math.max(Math.min(onZeroCoord, posBound[1]), posBound[0]);
  }
  // Axis position
  layout.position = [axisDim === 'y' ? posBound[idx[axisPosition]] : rectBound[0], axisDim === 'x' ? posBound[idx[axisPosition]] : rectBound[3]];
  // Axis rotation
  layout.rotation = Math.PI / 2 * (axisDim === 'x' ? 0 : 1);
  // Tick and label direction, x y is axisDim
  var dirMap = {
    top: -1,
    bottom: 1,
    left: -1,
    right: 1
  };
  layout.labelDirection = layout.tickDirection = layout.nameDirection = dirMap[rawAxisPosition];
  layout.labelOffset = otherAxisOnZeroOf ? posBound[idx[rawAxisPosition]] - posBound[idx.onZero] : 0;
  if (axisModel.get(['axisTick', 'inside'])) {
    layout.tickDirection = -layout.tickDirection;
  }
  if (retrieve(opt.labelInside, axisModel.get(['axisLabel', 'inside']))) {
    layout.labelDirection = -layout.labelDirection;
  }
  // Special label rotation
  var labelRotate = axisModel.get(['axisLabel', 'rotate']);
  layout.labelRotate = axisPosition === 'top' ? -labelRotate : labelRotate;
  // Over splitLine and splitArea
  layout.z2 = 1;
  return layout;
}
/**
 * Note: If pie (or other similar series) use cartesian2d, here
 *  option `seriesModel.get('coordinateSystem') === 'cartesian2d'`
 *  and `seriesModel.coordinateSystem !== cartesian2dCoordSysInstance`
 *  and `seriesModel.boxCoordinateSystem === cartesian2dCoordSysInstance`,
 *  the logic below is probably wrong, therefore skip it temporarily.
 */
function isCartesian2DInjectedAsDataCoordSys(seriesModel) {
  return seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'cartesian2d';
}
function findAxisModels(seriesModel) {
  var axisModelMap = {
    xAxisModel: null,
    yAxisModel: null
  };
  each(axisModelMap, function (v, key) {
    var axisType = key.replace(/Model$/, '');
    var axisModel = seriesModel.getReferringComponents(axisType, SINGLE_REFERRING).models[0];
    axisModelMap[key] = axisModel;
  });
  return axisModelMap;
}
function createCartesianAxisViewCommonPartBuilder(gridRect, cartesians, axisModel, api, ctx, defaultNameMoveOverlap) {
  var layoutResult = layout(gridRect, axisModel);
  var axisLineAutoShow = false;
  var axisTickAutoShow = false;
  // Not show axisTick or axisLine if other axis is category / time
  for (var i = 0; i < cartesians.length; i++) {
    if (isIntervalOrLogScale(cartesians[i].getOtherAxis(axisModel.axis).scale)) {
      // Still show axis tick or axisLine if other axis is value / log
      axisLineAutoShow = axisTickAutoShow = true;
      if (axisModel.axis.type === 'category' && axisModel.axis.onBand) {
        axisTickAutoShow = false;
      }
    }
  }
  layoutResult.axisLineAutoShow = axisLineAutoShow;
  layoutResult.axisTickAutoShow = axisTickAutoShow;
  layoutResult.defaultNameMoveOverlap = defaultNameMoveOverlap;
  return new AxisBuilder(axisModel, api, layoutResult, ctx);
}
function updateCartesianAxisViewCommonPartBuilder(axisBuilder, gridRect, axisModel) {
  var newRaw = layout(gridRect, axisModel);
  axisBuilder.updateCfg(newRaw);
}

export { AxisBuilderSharedContext as A, COORD_SYS_TYPE_CARTESIAN_2D as C, GridModel as G, OUTER_BOUNDS_DEFAULT as O, adoptScaleRawExtentInfoAndPrepare as a, adoptScaleExtentKindMapping as b, computeLabelGeometry as c, scaleRawExtentInfoCreate as d, scaleRawExtentInfoEnableBoxCoordSysUsage as e, createCartesianAxisViewCommonPartBuilder as f, getLabelInner as g, OUTER_BOUNDS_CLAMP_DEFAULT as h, isCartesian2DInjectedAsDataCoordSys as i, resolveAxisNameOverlapDefault as j, findAxisModels as k, AXIS_EXTENT_INFO_BUILD_FROM_COORD_SYS_UPDATE as l, moveIfOverlapByLinearLabels as m, AxisBuilder as n, layout as o, registerAxisContainShapeHandler as r, shiftLayoutOnXY as s, updateCartesianAxisViewCommonPartBuilder as u };
