axisTickLabelBuilder.js 13 KB

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