ECharts的配置优先级策略
Learning by Code Wiki of ECharts.
The “most specific wins” priority system
ECharts uses a “most specific wins” priority system for various elements and configurations beyond just tooltips and axisPointers. This means that options defined closer to a specific component or data item will generally override more general, global settings. Here are some additional cases and information about priority:
1. General Component Options:
- Component-specific options vs. Theme vs. Default: When a component is initialized or its options are merged, ECharts first applies the theme, then the component’s
defaultOption, and finally merges the user-provided options. For example,ComponentModel.mergeDefaultAndThemeandGlobalModel._mergeOptionshow this cascading merge. This allows for theme customization and sensible defaults while giving the user ultimate control.
2. Styling (Line, Item, Area, Text Styles):
- Mixins and Mappers: ECharts uses mixins like
LineStyleMixin,ItemStyleMixin,AreaStyleMixin, andTextStyleMixin(fromsrc/model/mixin/lineStyle.ts,src/model/mixin/itemStyle.ts,src/model/mixin/areaStyle.ts,src/model/mixin/textStyle.tsrespectively) to provide consistent styling. ThemakeStyleMapperutility (src/model/mixin/makeStyleMapper.ts) facilitates mapping these generic model properties to ZRender-specific style objects. - Inheritance and Overrides: Styles can be inherited. For example, in
LegendView.getLegendStyle,itemStyle.fill === 'inherit'means it will use theitemVisualStyle[drawType]. This implies a priority where explicit settings on thelegendItemModeloverride inherited series visuals. - Palette and Decals: The
PaletteMixin(src/model/mixin/palette.ts) handles color and decal assignment, ensuring visual consistency from configured palettes.LegendView.getLegendStyledemonstrates how a decal can be explicitly set or inherited (itemStyle.decal = (!decalStyle || decalStyle === 'inherit') ? itemVisualStyle.decal : createOrUpdatePatternFromDecal(decalStyle, api)).
3. Marker Components (MarkLine, MarkPoint, MarkArea):
- Data Item > Series > Global: Marker configurations follow a similar priority.
- Data Item Options: The highest priority is given to options defined on individual
dataitems within amarkPoint,markLine, ormarkAreaseries. For example,markPoint.data[i].symbolwill overridemarkPoint.symbol. This is evident inMarkPointView.renderSerieswhereitemModel.getShallow('symbol')is retrieved first. - Marker Series Options: If not specified on a data item, options like
symbol,symbolSize,symbolRotate, andsymbolOffsetfrom theMarkPointModel(src/component/marker/MarkPointModel.ts) orMarkLineModel(src/component/marker/MarkLineModel.ts) apply to all its data points. This is shown inMarkPointView.renderSeriesandMarkLineView.renderSeries. - Derived Properties:
MarkLineView.renderSeriesalso shows howlineStyle.strokecan be explicitly set or will default tofromData.getItemVisual(idx, 'style').fill. zandzlevel:MarkPointModelandMarkLineModelhavezproperties. This determines rendering order, with higherzvalues rendering on top.MarkPointViewsetsz2on visual items based onitemModel.get('z2').
- Data Item Options: The highest priority is given to options defined on individual
4. dataZoom Components:
start/endvs.startValue/endValuevs.rangeMode:DataZoomModel(src/component/dataZoom/DataZoomModel.ts) has a complex priority for defining the zoom range.start/end(percentage) andstartValue/endValue(actual data values) can be specified.- If both percentage and value are provided,
DataZoomModel._updateRangeUseandDataZoomModel._doInitindicate thatstart/end(percentage) generally take precedence overstartValue/endValueunless explicitly overridden byrangeMode. - The
rangeModeproperty['value', 'value']explicitly forcesstartValue/endValueto be used.
- Throttle:
DataZoomModel._setDefaultThrottleshows that ifthrottleis explicitly set ininputRawOption, it overrides the auto-calculated throttle value.
5. graphic Components:
- Element-specific options: For graphic elements, individual element options (
GraphicComponentElementOptionfromsrc/component/graphic/GraphicModel.ts) override more general settings. zlevel,z,z2:GraphicComponentView._updateElementsandupdateCommonAttrsshow that these properties can be defined on individual graphic elements. Ifzlevelorzare not explicitly set on an element, the globalgraphicModel.get('zlevel')andgraphicModel.get('z')are used as defaults.- CSS-like Properties: The graphic component supports various CSS-like properties for layout and styling, like
x,y,width,height,left,right,top,bottom, which are resolved bylayoutUtil.positionElementinGraphicComponentView._relocate.
6. Legend Components:
LegendModelData Items: Each item in a legend’sdataarray can have its owniconandtextStyleproperties (LegendModel.getData). These item-specific settings override the generalLegendModelproperties, as shown inLegendView._createItem.inactiveColorandinactiveBorderColor: These are used when a legend item is not selected, overriding the active colors.selector: Theselectoroption allows for ‘all’ or ‘inverse’ selection buttons.LegendModel._updateSelectornormalizes these options, giving precedence to explicitly definedtitlevalues over default locale-based titles.pageIcons: ForScrollableLegendModel(src/component/legend/ScrollableLegendModel.ts),pageIconscan be configured globally.
7. Toolbox Features:
- Feature-specific options: Each toolbox feature (e.g.,
saveAsImage,magicType,dataZoom,restore) has its owndefaultOptionand can be configured individually. For example,ToolboxSaveAsImageFeatureOptiondefinesbackgroundColor,name,excludeComponents, andpixelRatiospecifically for the save image feature. iconandtitle: These can be defined globally for the toolbox or specifically for each feature, with feature-specific settings taking precedence, as seen inToolboxDataZoomFeature.getDefaultOptionandToolboxMagicType.getIcons.iconStatus: ThesetIconStatusmethod (used inToolboxDataZoomFeatureandToolboxMagicType) allows dynamically changing the visual state of a feature icon (e.g., ‘emphasis’ or ‘normal’), effectively overriding the default appearance.
In summary, ECharts is designed for extensibility and granular control. Configurations are typically applied in a layered fashion: global defaults -> theme -> component-level defaults -> series-level options -> data-item or element-specific options. This allows users to set broad chart styles and behaviors while providing the flexibility to customize individual elements as needed.
A case: grid.tooltip.axisPointer VS. xAxis.axisPointer
ECharts manages tooltip and axisPointer configurations with a hierarchical priority system, where more specific settings override general ones. This allows for fine-grained control over how tooltips and axisPointers behave across different components and series. The priority order, from highest to lowest, is as follows:
Component/Data Item
tooltipoptions:- Individual Data Items: The highest priority is given to
tooltipoptions defined directly on individual data items within a series. This is processed by the_showSeriesItemTooltipfunction insrc/component/tooltip/TooltipView.ts. - Component-specific
tooltipConfig: Certain components (likelegendortoolbox) can define their owntooltipConfig, which takes precedence for those specific elements. This is handled by_showComponentItemTooltipinsrc/component/tooltip/TooltipView.ts. - Marker
tooltip: Markers such asmarkPoint,markLine, andmarkAreaalso have their owntooltipconfigurations, for example,markArea.tooltipinsrc/component/marker/MarkAreaModel.ts,markLine.tooltipinsrc/component/marker/MarkLineModel.ts, andmarkPoint.tooltipinsrc/component/marker/MarkPointModel.ts. These configurations are typically set totrigger: 'item'.
- Individual Data Items: The highest priority is given to
Series
tooltipoptions: If atooltipis not defined on a specific data item, ECharts falls back to thetooltipoption configured at the series level. This configuration is part of theseries.tooltipproperty. The_showSeriesItemTooltipfunction insrc/component/tooltip/TooltipView.tsalso considers this level.Coordinate System
tooltipoptions:- Grid
tooltip: For Cartesian coordinate systems (grids), thegridcomponent can have its owntooltipconfiguration. This is less common for generaltooltipsettings but applies toaxisPointersettings within the grid. TheGridModelinsrc/coord/cartesian/GridModel.tsis where this can be configured. - Polar
tooltip: Similar to grids, polar coordinate systems can also have their owntooltipconfigurations.
- Grid
xAxis/yAxis/angleAxis/radiusAxisaxisPointeroptions:- Each axis model (e.g.,
CartesianAxisModelinsrc/coord/cartesian/AxisModel.tsforxAxisandyAxis, orPolarAxisModelforradiusAxisinsrc/component/axisPointer/PolarAxisPointer.ts) can define anaxisPointerconfiguration. This is used to determine how the axisPointer behaves when interacting with that specific axis. - The
axisPointercan be configured with properties liketype('line','shadow','cross'),snap,lineStyle,shadowStyle, andlabel. - The
collectfunction insrc/component/axisPointer/modelHelper.tsaggregates these axis-specificaxisPointermodels. - The
AxisViewclass (e.g.,CartesianAxisViewinsrc/component/axis/CartesianAxisView.tsandRadiusAxisViewinsrc/component/axis/RadiusAxisView.ts) uses thisaxisPointerconfiguration to render the visual elements.
- Each axis model (e.g.,
Global
tooltip.axisPointeroption:- If no specific
axisPointerconfiguration is found on an individual axis, ECharts uses the globaltooltip.axisPointersetting, as defined inTooltipModel.defaultOptioninsrc/component/tooltip/TooltipModel.ts. This provides a default behavior for all axisPointers in the chart. - This global configuration also supports
linkproperty, allowing multiple axisPointers to be linked together, which is handled by thecollectfunction insrc/component/axisPointer/modelHelper.ts.
- If no specific
Global
tooltipoption:- The lowest priority is the global
tooltipoption, defined in thetooltipcomponent directly, as seen inTooltipModel.defaultOptioninsrc/component/tooltip/TooltipModel.ts. This sets the default behavior for all tooltips in the chart if no more specific configuration overrides it. This includes general properties likeshow,trigger,alwaysShowContent,backgroundColor,textStyle, etc.
- The lowest priority is the global
How ECharts Resolves Priorities:
The buildTooltipModel function in src/component/tooltip/TooltipView.ts is crucial for resolving this hierarchy. It takes a cascade of tooltip configurations (from data items, series, coordinate systems, and global settings) and merges them into a single effective tooltip model, with later (more specific) options overriding earlier (more general) ones.
For axisPointers, the modelHelper.collect function in src/component/axisPointer/modelHelper.ts processes axisPointer configurations, prioritizing local settings (e.g., axis.axisPointer) over global tooltip.axisPointer settings. It also creates a temporary axisPointerModel when a tooltip with trigger: 'axis' is used on a coordinate system or series, effectively making the tooltip’s axisPointer configuration take precedence for those triggered axes.
In essence, ECharts follows a “most specific wins” rule, where configurations defined closer to the data or component being interacted with will override more general, higher-level settings.