axisTickLabelBuilder.js 14 KB

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