axisTickLabelBuilder.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing,
  13. * software distributed under the License is distributed on an
  14. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15. * KIND, either express or implied. See the License for the
  16. * specific language governing permissions and limitations
  17. * under the License.
  18. */
  19. /**
  20. * AUTO-GENERATED FILE. DO NOT MODIFY.
  21. */
  22. /*
  23. * Licensed to the Apache Software Foundation (ASF) under one
  24. * or more contributor license agreements. See the NOTICE file
  25. * distributed with this work for additional information
  26. * regarding copyright ownership. The ASF licenses this file
  27. * to you under the Apache License, Version 2.0 (the
  28. * "License"); you may not use this file except in compliance
  29. * with the License. You may obtain a copy of the License at
  30. *
  31. * http://www.apache.org/licenses/LICENSE-2.0
  32. *
  33. * Unless required by applicable law or agreed to in writing,
  34. * software distributed under the License is distributed on an
  35. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36. * KIND, either express or implied. See the License for the
  37. * specific language governing permissions and limitations
  38. * under the License.
  39. */
  40. import * as zrUtil from 'zrender/lib/core/util.js';
  41. import * as textContain from 'zrender/lib/contain/text.js';
  42. import { makeInner } from '../util/model.js';
  43. import { makeLabelFormatter, getOptionCategoryInterval, shouldShowAllLabels } from './axisHelper.js';
  44. var inner = makeInner();
  45. export function createAxisLabels(axis) {
  46. // Only ordinal scale support tick interval
  47. return axis.type === 'category' ? makeCategoryLabels(axis) : makeRealNumberLabels(axis);
  48. }
  49. /**
  50. * @param {module:echats/coord/Axis} axis
  51. * @param {module:echarts/model/Model} tickModel For example, can be axisTick, splitLine, splitArea.
  52. * @return {Object} {
  53. * ticks: Array.<number>
  54. * tickCategoryInterval: number
  55. * }
  56. */
  57. export function createAxisTicks(axis, tickModel) {
  58. // Only ordinal scale support tick interval
  59. return axis.type === 'category' ? makeCategoryTicks(axis, tickModel) : {
  60. ticks: zrUtil.map(axis.scale.getTicks(), function (tick) {
  61. return tick.value;
  62. })
  63. };
  64. }
  65. function makeCategoryLabels(axis) {
  66. var labelModel = axis.getLabelModel();
  67. var result = makeCategoryLabelsActually(axis, labelModel);
  68. return !labelModel.get('show') || axis.scale.isBlank() ? {
  69. labels: [],
  70. labelCategoryInterval: result.labelCategoryInterval
  71. } : result;
  72. }
  73. function makeCategoryLabelsActually(axis, labelModel) {
  74. var labelsCache = getListCache(axis, 'labels');
  75. var optionLabelInterval = getOptionCategoryInterval(labelModel);
  76. var result = listCacheGet(labelsCache, optionLabelInterval);
  77. if (result) {
  78. return result;
  79. }
  80. var labels;
  81. var numericLabelInterval;
  82. if (zrUtil.isFunction(optionLabelInterval)) {
  83. labels = makeLabelsByCustomizedCategoryInterval(axis, optionLabelInterval);
  84. } else {
  85. numericLabelInterval = optionLabelInterval === 'auto' ? makeAutoCategoryInterval(axis) : optionLabelInterval;
  86. labels = makeLabelsByNumericCategoryInterval(axis, numericLabelInterval);
  87. } // Cache to avoid calling interval function repeatedly.
  88. return listCacheSet(labelsCache, optionLabelInterval, {
  89. labels: labels,
  90. labelCategoryInterval: numericLabelInterval
  91. });
  92. }
  93. function makeCategoryTicks(axis, tickModel) {
  94. var ticksCache = getListCache(axis, 'ticks');
  95. var optionTickInterval = getOptionCategoryInterval(tickModel);
  96. var result = listCacheGet(ticksCache, optionTickInterval);
  97. if (result) {
  98. return result;
  99. }
  100. var ticks;
  101. var tickCategoryInterval; // Optimize for the case that large category data and no label displayed,
  102. // we should not return all ticks.
  103. if (!tickModel.get('show') || axis.scale.isBlank()) {
  104. ticks = [];
  105. }
  106. if (zrUtil.isFunction(optionTickInterval)) {
  107. ticks = makeLabelsByCustomizedCategoryInterval(axis, optionTickInterval, true);
  108. } // Always use label interval by default despite label show. Consider this
  109. // scenario, Use multiple grid with the xAxis sync, and only one xAxis shows
  110. // labels. `splitLine` and `axisTick` should be consistent in this case.
  111. else if (optionTickInterval === 'auto') {
  112. var labelsResult = makeCategoryLabelsActually(axis, axis.getLabelModel());
  113. tickCategoryInterval = labelsResult.labelCategoryInterval;
  114. ticks = zrUtil.map(labelsResult.labels, function (labelItem) {
  115. return labelItem.tickValue;
  116. });
  117. } else {
  118. tickCategoryInterval = optionTickInterval;
  119. ticks = makeLabelsByNumericCategoryInterval(axis, tickCategoryInterval, true);
  120. } // Cache to avoid calling interval function repeatedly.
  121. return listCacheSet(ticksCache, optionTickInterval, {
  122. ticks: ticks,
  123. tickCategoryInterval: tickCategoryInterval
  124. });
  125. }
  126. function makeRealNumberLabels(axis) {
  127. var ticks = axis.scale.getTicks();
  128. var labelFormatter = makeLabelFormatter(axis);
  129. return {
  130. labels: zrUtil.map(ticks, function (tick, idx) {
  131. return {
  132. level: tick.level,
  133. formattedLabel: labelFormatter(tick, idx),
  134. rawLabel: axis.scale.getLabel(tick),
  135. tickValue: tick.value
  136. };
  137. })
  138. };
  139. }
  140. function getListCache(axis, prop) {
  141. // Because key can be a function, and cache size always is small, we use array cache.
  142. return inner(axis)[prop] || (inner(axis)[prop] = []);
  143. }
  144. function listCacheGet(cache, key) {
  145. for (var i = 0; i < cache.length; i++) {
  146. if (cache[i].key === key) {
  147. return cache[i].value;
  148. }
  149. }
  150. }
  151. function listCacheSet(cache, key, value) {
  152. cache.push({
  153. key: key,
  154. value: value
  155. });
  156. return value;
  157. }
  158. function makeAutoCategoryInterval(axis) {
  159. var result = inner(axis).autoInterval;
  160. return result != null ? result : inner(axis).autoInterval = axis.calculateCategoryInterval();
  161. }
  162. /**
  163. * Calculate interval for category axis ticks and labels.
  164. * To get precise result, at least one of `getRotate` and `isHorizontal`
  165. * should be implemented in axis.
  166. */
  167. export function calculateCategoryInterval(axis) {
  168. var params = fetchAutoCategoryIntervalCalculationParams(axis);
  169. var labelFormatter = makeLabelFormatter(axis);
  170. var rotation = (params.axisRotate - params.labelRotate) / 180 * Math.PI;
  171. var ordinalScale = axis.scale;
  172. var ordinalExtent = ordinalScale.getExtent(); // Providing this method is for optimization:
  173. // avoid generating a long array by `getTicks`
  174. // in large category data case.
  175. var tickCount = ordinalScale.count();
  176. if (ordinalExtent[1] - ordinalExtent[0] < 1) {
  177. return 0;
  178. }
  179. var step = 1; // Simple optimization. Empirical value: tick count should less than 40.
  180. if (tickCount > 40) {
  181. step = Math.max(1, Math.floor(tickCount / 40));
  182. }
  183. var tickValue = ordinalExtent[0];
  184. var unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
  185. var unitW = Math.abs(unitSpan * Math.cos(rotation));
  186. var unitH = Math.abs(unitSpan * Math.sin(rotation));
  187. var maxW = 0;
  188. var maxH = 0; // Caution: Performance sensitive for large category data.
  189. // Consider dataZoom, we should make appropriate step to avoid O(n) loop.
  190. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  191. var width = 0;
  192. var height = 0; // Not precise, do not consider align and vertical align
  193. // and each distance from axis line yet.
  194. var rect = textContain.getBoundingRect(labelFormatter({
  195. value: tickValue
  196. }), params.font, 'center', 'top'); // Magic number
  197. width = rect.width * 1.3;
  198. height = rect.height * 1.3; // Min size, void long loop.
  199. maxW = Math.max(maxW, width, 7);
  200. maxH = Math.max(maxH, height, 7);
  201. }
  202. var dw = maxW / unitW;
  203. var dh = maxH / unitH; // 0/0 is NaN, 1/0 is Infinity.
  204. isNaN(dw) && (dw = Infinity);
  205. isNaN(dh) && (dh = Infinity);
  206. var interval = Math.max(0, Math.floor(Math.min(dw, dh)));
  207. var cache = inner(axis.model);
  208. var axisExtent = axis.getExtent();
  209. var lastAutoInterval = cache.lastAutoInterval;
  210. var lastTickCount = cache.lastTickCount; // Use cache to keep interval stable while moving zoom window,
  211. // otherwise the calculated interval might jitter when the zoom
  212. // window size is close to the interval-changing size.
  213. // For example, if all of the axis labels are `a, b, c, d, e, f, g`.
  214. // The jitter will cause that sometimes the displayed labels are
  215. // `a, d, g` (interval: 2) sometimes `a, c, e`(interval: 1).
  216. if (lastAutoInterval != null && lastTickCount != null && Math.abs(lastAutoInterval - interval) <= 1 && Math.abs(lastTickCount - tickCount) <= 1 // Always choose the bigger one, otherwise the critical
  217. // point is not the same when zooming in or zooming out.
  218. && lastAutoInterval > interval // If the axis change is caused by chart resize, the cache should not
  219. // be used. Otherwise some hidden labels might not be shown again.
  220. && cache.axisExtent0 === axisExtent[0] && cache.axisExtent1 === axisExtent[1]) {
  221. interval = lastAutoInterval;
  222. } // Only update cache if cache not used, otherwise the
  223. // changing of interval is too insensitive.
  224. else {
  225. cache.lastTickCount = tickCount;
  226. cache.lastAutoInterval = interval;
  227. cache.axisExtent0 = axisExtent[0];
  228. cache.axisExtent1 = axisExtent[1];
  229. }
  230. return interval;
  231. }
  232. function fetchAutoCategoryIntervalCalculationParams(axis) {
  233. var labelModel = axis.getLabelModel();
  234. return {
  235. axisRotate: axis.getRotate ? axis.getRotate() : axis.isHorizontal && !axis.isHorizontal() ? 90 : 0,
  236. labelRotate: labelModel.get('rotate') || 0,
  237. font: labelModel.getFont()
  238. };
  239. }
  240. function makeLabelsByNumericCategoryInterval(axis, categoryInterval, onlyTick) {
  241. var labelFormatter = makeLabelFormatter(axis);
  242. var ordinalScale = axis.scale;
  243. var ordinalExtent = ordinalScale.getExtent();
  244. var labelModel = axis.getLabelModel();
  245. var result = []; // TODO: axisType: ordinalTime, pick the tick from each month/day/year/...
  246. var step = Math.max((categoryInterval || 0) + 1, 1);
  247. var startTick = ordinalExtent[0];
  248. var tickCount = ordinalScale.count(); // Calculate start tick based on zero if possible to keep label consistent
  249. // while zooming and moving while interval > 0. Otherwise the selection
  250. // of displayable ticks and symbols probably keep changing.
  251. // 3 is empirical value.
  252. if (startTick !== 0 && step > 1 && tickCount / step > 2) {
  253. startTick = Math.round(Math.ceil(startTick / step) * step);
  254. } // (1) Only add min max label here but leave overlap checking
  255. // to render stage, which also ensure the returned list
  256. // suitable for splitLine and splitArea rendering.
  257. // (2) Scales except category always contain min max label so
  258. // do not need to perform this process.
  259. var showAllLabel = shouldShowAllLabels(axis);
  260. var includeMinLabel = labelModel.get('showMinLabel') || showAllLabel;
  261. var includeMaxLabel = labelModel.get('showMaxLabel') || showAllLabel;
  262. if (includeMinLabel && startTick !== ordinalExtent[0]) {
  263. addItem(ordinalExtent[0]);
  264. } // Optimize: avoid generating large array by `ordinalScale.getTicks()`.
  265. var tickValue = startTick;
  266. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  267. addItem(tickValue);
  268. }
  269. if (includeMaxLabel && tickValue - step !== ordinalExtent[1]) {
  270. addItem(ordinalExtent[1]);
  271. }
  272. function addItem(tickValue) {
  273. var tickObj = {
  274. value: tickValue
  275. };
  276. result.push(onlyTick ? tickValue : {
  277. formattedLabel: labelFormatter(tickObj),
  278. rawLabel: ordinalScale.getLabel(tickObj),
  279. tickValue: tickValue
  280. });
  281. }
  282. return result;
  283. }
  284. function makeLabelsByCustomizedCategoryInterval(axis, categoryInterval, onlyTick) {
  285. var ordinalScale = axis.scale;
  286. var labelFormatter = makeLabelFormatter(axis);
  287. var result = [];
  288. zrUtil.each(ordinalScale.getTicks(), function (tick) {
  289. var rawLabel = ordinalScale.getLabel(tick);
  290. var tickValue = tick.value;
  291. if (categoryInterval(tick.value, rawLabel)) {
  292. result.push(onlyTick ? tickValue : {
  293. formattedLabel: labelFormatter(tick),
  294. rawLabel: rawLabel,
  295. tickValue: tickValue
  296. });
  297. }
  298. });
  299. return result;
  300. }