axisTickLabelBuilder.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  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. }
  88. // Cache to avoid calling interval function repeatedly.
  89. return listCacheSet(labelsCache, optionLabelInterval, {
  90. labels: labels,
  91. labelCategoryInterval: numericLabelInterval
  92. });
  93. }
  94. function makeCategoryTicks(axis, tickModel) {
  95. var ticksCache = getListCache(axis, 'ticks');
  96. var optionTickInterval = getOptionCategoryInterval(tickModel);
  97. var result = listCacheGet(ticksCache, optionTickInterval);
  98. if (result) {
  99. return result;
  100. }
  101. var ticks;
  102. var tickCategoryInterval;
  103. // Optimize for the case that large category data and no label displayed,
  104. // we should not return all ticks.
  105. if (!tickModel.get('show') || axis.scale.isBlank()) {
  106. ticks = [];
  107. }
  108. if (zrUtil.isFunction(optionTickInterval)) {
  109. ticks = makeLabelsByCustomizedCategoryInterval(axis, optionTickInterval, true);
  110. }
  111. // Always use label interval by default despite label show. Consider this
  112. // scenario, Use multiple grid with the xAxis sync, and only one xAxis shows
  113. // labels. `splitLine` and `axisTick` should be consistent in this case.
  114. else if (optionTickInterval === 'auto') {
  115. var labelsResult = makeCategoryLabelsActually(axis, axis.getLabelModel());
  116. tickCategoryInterval = labelsResult.labelCategoryInterval;
  117. ticks = zrUtil.map(labelsResult.labels, function (labelItem) {
  118. return labelItem.tickValue;
  119. });
  120. } else {
  121. tickCategoryInterval = optionTickInterval;
  122. ticks = makeLabelsByNumericCategoryInterval(axis, tickCategoryInterval, true);
  123. }
  124. // Cache to avoid calling interval function repeatedly.
  125. return listCacheSet(ticksCache, optionTickInterval, {
  126. ticks: ticks,
  127. tickCategoryInterval: tickCategoryInterval
  128. });
  129. }
  130. function makeRealNumberLabels(axis) {
  131. var ticks = axis.scale.getTicks();
  132. var labelFormatter = makeLabelFormatter(axis);
  133. return {
  134. labels: zrUtil.map(ticks, function (tick, idx) {
  135. return {
  136. level: tick.level,
  137. formattedLabel: labelFormatter(tick, idx),
  138. rawLabel: axis.scale.getLabel(tick),
  139. tickValue: tick.value
  140. };
  141. })
  142. };
  143. }
  144. function getListCache(axis, prop) {
  145. // Because key can be a function, and cache size always is small, we use array cache.
  146. return inner(axis)[prop] || (inner(axis)[prop] = []);
  147. }
  148. function listCacheGet(cache, key) {
  149. for (var i = 0; i < cache.length; i++) {
  150. if (cache[i].key === key) {
  151. return cache[i].value;
  152. }
  153. }
  154. }
  155. function listCacheSet(cache, key, value) {
  156. cache.push({
  157. key: key,
  158. value: value
  159. });
  160. return value;
  161. }
  162. function makeAutoCategoryInterval(axis) {
  163. var result = inner(axis).autoInterval;
  164. return result != null ? result : inner(axis).autoInterval = axis.calculateCategoryInterval();
  165. }
  166. /**
  167. * Calculate interval for category axis ticks and labels.
  168. * To get precise result, at least one of `getRotate` and `isHorizontal`
  169. * should be implemented in axis.
  170. */
  171. export function calculateCategoryInterval(axis) {
  172. var params = fetchAutoCategoryIntervalCalculationParams(axis);
  173. var labelFormatter = makeLabelFormatter(axis);
  174. var rotation = (params.axisRotate - params.labelRotate) / 180 * Math.PI;
  175. var ordinalScale = axis.scale;
  176. var ordinalExtent = ordinalScale.getExtent();
  177. // Providing this method is for optimization:
  178. // avoid generating a long array by `getTicks`
  179. // in large category data case.
  180. var tickCount = ordinalScale.count();
  181. if (ordinalExtent[1] - ordinalExtent[0] < 1) {
  182. return 0;
  183. }
  184. var step = 1;
  185. // Simple optimization. Empirical value: tick count should less than 40.
  186. if (tickCount > 40) {
  187. step = Math.max(1, Math.floor(tickCount / 40));
  188. }
  189. var tickValue = ordinalExtent[0];
  190. var unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
  191. var unitW = Math.abs(unitSpan * Math.cos(rotation));
  192. var unitH = Math.abs(unitSpan * Math.sin(rotation));
  193. var maxW = 0;
  194. var maxH = 0;
  195. // Caution: Performance sensitive for large category data.
  196. // Consider dataZoom, we should make appropriate step to avoid O(n) loop.
  197. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  198. var width = 0;
  199. var height = 0;
  200. // Not precise, do not consider align and vertical align
  201. // and each distance from axis line yet.
  202. var rect = textContain.getBoundingRect(labelFormatter({
  203. value: tickValue
  204. }), params.font, 'center', 'top');
  205. // Magic number
  206. width = rect.width * 1.3;
  207. height = rect.height * 1.3;
  208. // Min size, void long loop.
  209. maxW = Math.max(maxW, width, 7);
  210. maxH = Math.max(maxH, height, 7);
  211. }
  212. var dw = maxW / unitW;
  213. var dh = maxH / unitH;
  214. // 0/0 is NaN, 1/0 is Infinity.
  215. isNaN(dw) && (dw = Infinity);
  216. isNaN(dh) && (dh = Infinity);
  217. var interval = Math.max(0, Math.floor(Math.min(dw, dh)));
  218. var cache = inner(axis.model);
  219. var axisExtent = axis.getExtent();
  220. var lastAutoInterval = cache.lastAutoInterval;
  221. var lastTickCount = cache.lastTickCount;
  222. // Use cache to keep interval stable while moving zoom window,
  223. // otherwise the calculated interval might jitter when the zoom
  224. // window size is close to the interval-changing size.
  225. // For example, if all of the axis labels are `a, b, c, d, e, f, g`.
  226. // The jitter will cause that sometimes the displayed labels are
  227. // `a, d, g` (interval: 2) sometimes `a, c, e`(interval: 1).
  228. if (lastAutoInterval != null && lastTickCount != null && Math.abs(lastAutoInterval - interval) <= 1 && Math.abs(lastTickCount - tickCount) <= 1
  229. // Always choose the bigger one, otherwise the critical
  230. // point is not the same when zooming in or zooming out.
  231. && lastAutoInterval > interval
  232. // If the axis change is caused by chart resize, the cache should not
  233. // be used. Otherwise some hidden labels might not be shown again.
  234. && cache.axisExtent0 === axisExtent[0] && cache.axisExtent1 === axisExtent[1]) {
  235. interval = lastAutoInterval;
  236. }
  237. // Only update cache if cache not used, otherwise the
  238. // changing of interval is too insensitive.
  239. else {
  240. cache.lastTickCount = tickCount;
  241. cache.lastAutoInterval = interval;
  242. cache.axisExtent0 = axisExtent[0];
  243. cache.axisExtent1 = axisExtent[1];
  244. }
  245. return interval;
  246. }
  247. function fetchAutoCategoryIntervalCalculationParams(axis) {
  248. var labelModel = axis.getLabelModel();
  249. return {
  250. axisRotate: axis.getRotate ? axis.getRotate() : axis.isHorizontal && !axis.isHorizontal() ? 90 : 0,
  251. labelRotate: labelModel.get('rotate') || 0,
  252. font: labelModel.getFont()
  253. };
  254. }
  255. function makeLabelsByNumericCategoryInterval(axis, categoryInterval, onlyTick) {
  256. var labelFormatter = makeLabelFormatter(axis);
  257. var ordinalScale = axis.scale;
  258. var ordinalExtent = ordinalScale.getExtent();
  259. var labelModel = axis.getLabelModel();
  260. var result = [];
  261. // TODO: axisType: ordinalTime, pick the tick from each month/day/year/...
  262. var step = Math.max((categoryInterval || 0) + 1, 1);
  263. var startTick = ordinalExtent[0];
  264. var tickCount = ordinalScale.count();
  265. // Calculate start tick based on zero if possible to keep label consistent
  266. // while zooming and moving while interval > 0. Otherwise the selection
  267. // of displayable ticks and symbols probably keep changing.
  268. // 3 is empirical value.
  269. if (startTick !== 0 && step > 1 && tickCount / step > 2) {
  270. startTick = Math.round(Math.ceil(startTick / step) * step);
  271. }
  272. // (1) Only add min max label here but leave overlap checking
  273. // to render stage, which also ensure the returned list
  274. // suitable for splitLine and splitArea rendering.
  275. // (2) Scales except category always contain min max label so
  276. // do not need to perform this process.
  277. var showAllLabel = shouldShowAllLabels(axis);
  278. var includeMinLabel = labelModel.get('showMinLabel') || showAllLabel;
  279. var includeMaxLabel = labelModel.get('showMaxLabel') || showAllLabel;
  280. if (includeMinLabel && startTick !== ordinalExtent[0]) {
  281. addItem(ordinalExtent[0]);
  282. }
  283. // Optimize: avoid generating large array by `ordinalScale.getTicks()`.
  284. var tickValue = startTick;
  285. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  286. addItem(tickValue);
  287. }
  288. if (includeMaxLabel && tickValue - step !== ordinalExtent[1]) {
  289. addItem(ordinalExtent[1]);
  290. }
  291. function addItem(tickValue) {
  292. var tickObj = {
  293. value: tickValue
  294. };
  295. result.push(onlyTick ? tickValue : {
  296. formattedLabel: labelFormatter(tickObj),
  297. rawLabel: ordinalScale.getLabel(tickObj),
  298. tickValue: tickValue
  299. });
  300. }
  301. return result;
  302. }
  303. function makeLabelsByCustomizedCategoryInterval(axis, categoryInterval, onlyTick) {
  304. var ordinalScale = axis.scale;
  305. var labelFormatter = makeLabelFormatter(axis);
  306. var result = [];
  307. zrUtil.each(ordinalScale.getTicks(), function (tick) {
  308. var rawLabel = ordinalScale.getLabel(tick);
  309. var tickValue = tick.value;
  310. if (categoryInterval(tick.value, rawLabel)) {
  311. result.push(onlyTick ? tickValue : {
  312. formattedLabel: labelFormatter(tick),
  313. rawLabel: rawLabel,
  314. tickValue: tickValue
  315. });
  316. }
  317. });
  318. return result;
  319. }