axisTickLabelBuilder.js 13 KB

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