axisTickLabelBuilder.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  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 modelInner = makeInner();
  45. var axisInner = makeInner();
  46. export var AxisTickLabelComputingKind = {
  47. estimate: 1,
  48. determine: 2
  49. };
  50. export function createAxisLabelsComputingContext(kind) {
  51. return {
  52. out: {
  53. noPxChangeTryDetermine: []
  54. },
  55. kind: kind
  56. };
  57. }
  58. function tickValuesToNumbers(axis, values) {
  59. var nums = zrUtil.map(values, function (val) {
  60. return axis.scale.parse(val);
  61. });
  62. if (axis.type === 'time' && nums.length > 0) {
  63. // Time axis needs duplicate first/last tick (see TimeScale.getTicks())
  64. // The first and last tick/label don't get drawn
  65. nums.sort();
  66. nums.unshift(nums[0]);
  67. nums.push(nums[nums.length - 1]);
  68. }
  69. return nums;
  70. }
  71. export function createAxisLabels(axis, ctx) {
  72. var custom = axis.getLabelModel().get('customValues');
  73. if (custom) {
  74. var labelFormatter_1 = makeLabelFormatter(axis);
  75. var extent_1 = axis.scale.getExtent();
  76. var tickNumbers = tickValuesToNumbers(axis, custom);
  77. var ticks = zrUtil.filter(tickNumbers, function (val) {
  78. return val >= extent_1[0] && val <= extent_1[1];
  79. });
  80. return {
  81. labels: zrUtil.map(ticks, function (numval) {
  82. var tick = {
  83. value: numval
  84. };
  85. return {
  86. formattedLabel: labelFormatter_1(tick),
  87. rawLabel: axis.scale.getLabel(tick),
  88. tickValue: numval,
  89. time: undefined,
  90. "break": undefined
  91. };
  92. })
  93. };
  94. }
  95. // Only ordinal scale support tick interval
  96. return axis.type === 'category' ? makeCategoryLabels(axis, ctx) : makeRealNumberLabels(axis);
  97. }
  98. /**
  99. * @param tickModel For example, can be axisTick, splitLine, splitArea.
  100. */
  101. export function createAxisTicks(axis, tickModel, opt) {
  102. var custom = axis.getTickModel().get('customValues');
  103. if (custom) {
  104. var extent_2 = axis.scale.getExtent();
  105. var tickNumbers = tickValuesToNumbers(axis, custom);
  106. return {
  107. ticks: zrUtil.filter(tickNumbers, function (val) {
  108. return val >= extent_2[0] && val <= extent_2[1];
  109. })
  110. };
  111. }
  112. // Only ordinal scale support tick interval
  113. return axis.type === 'category' ? makeCategoryTicks(axis, tickModel) : {
  114. ticks: zrUtil.map(axis.scale.getTicks(opt), function (tick) {
  115. return tick.value;
  116. })
  117. };
  118. }
  119. function makeCategoryLabels(axis, ctx) {
  120. var labelModel = axis.getLabelModel();
  121. var result = makeCategoryLabelsActually(axis, labelModel, ctx);
  122. return !labelModel.get('show') || axis.scale.isBlank() ? {
  123. labels: []
  124. } : result;
  125. }
  126. function makeCategoryLabelsActually(axis, labelModel, ctx) {
  127. var labelsCache = ensureCategoryLabelCache(axis);
  128. var optionLabelInterval = getOptionCategoryInterval(labelModel);
  129. var isEstimate = ctx.kind === AxisTickLabelComputingKind.estimate;
  130. // In AxisTickLabelComputingKind.estimate, the result likely varies during a single
  131. // pass of ec main process,due to the change of axisExtent, and will not be shared with
  132. // splitLine. Therefore no cache is used.
  133. if (!isEstimate) {
  134. // PENDING: check necessary?
  135. var result_1 = axisCacheGet(labelsCache, optionLabelInterval);
  136. if (result_1) {
  137. return result_1;
  138. }
  139. }
  140. var labels;
  141. var numericLabelInterval;
  142. if (zrUtil.isFunction(optionLabelInterval)) {
  143. labels = makeLabelsByCustomizedCategoryInterval(axis, optionLabelInterval);
  144. } else {
  145. numericLabelInterval = optionLabelInterval === 'auto' ? makeAutoCategoryInterval(axis, ctx) : optionLabelInterval;
  146. labels = makeLabelsByNumericCategoryInterval(axis, numericLabelInterval);
  147. }
  148. var result = {
  149. labels: labels,
  150. labelCategoryInterval: numericLabelInterval
  151. };
  152. if (!isEstimate) {
  153. axisCacheSet(labelsCache, optionLabelInterval, result);
  154. } else {
  155. ctx.out.noPxChangeTryDetermine.push(function () {
  156. axisCacheSet(labelsCache, optionLabelInterval, result);
  157. return true;
  158. });
  159. }
  160. return result;
  161. }
  162. function makeCategoryTicks(axis, tickModel) {
  163. var ticksCache = ensureCategoryTickCache(axis);
  164. var optionTickInterval = getOptionCategoryInterval(tickModel);
  165. var result = axisCacheGet(ticksCache, optionTickInterval);
  166. if (result) {
  167. return result;
  168. }
  169. var ticks;
  170. var tickCategoryInterval;
  171. // Optimize for the case that large category data and no label displayed,
  172. // we should not return all ticks.
  173. if (!tickModel.get('show') || axis.scale.isBlank()) {
  174. ticks = [];
  175. }
  176. if (zrUtil.isFunction(optionTickInterval)) {
  177. ticks = makeLabelsByCustomizedCategoryInterval(axis, optionTickInterval, true);
  178. }
  179. // Always use label interval by default despite label show. Consider this
  180. // scenario, Use multiple grid with the xAxis sync, and only one xAxis shows
  181. // labels. `splitLine` and `axisTick` should be consistent in this case.
  182. else if (optionTickInterval === 'auto') {
  183. var labelsResult = makeCategoryLabelsActually(axis, axis.getLabelModel(), createAxisLabelsComputingContext(AxisTickLabelComputingKind.determine));
  184. tickCategoryInterval = labelsResult.labelCategoryInterval;
  185. ticks = zrUtil.map(labelsResult.labels, function (labelItem) {
  186. return labelItem.tickValue;
  187. });
  188. } else {
  189. tickCategoryInterval = optionTickInterval;
  190. ticks = makeLabelsByNumericCategoryInterval(axis, tickCategoryInterval, true);
  191. }
  192. // Cache to avoid calling interval function repeatedly.
  193. return axisCacheSet(ticksCache, optionTickInterval, {
  194. ticks: ticks,
  195. tickCategoryInterval: tickCategoryInterval
  196. });
  197. }
  198. function makeRealNumberLabels(axis) {
  199. var ticks = axis.scale.getTicks();
  200. var labelFormatter = makeLabelFormatter(axis);
  201. return {
  202. labels: zrUtil.map(ticks, function (tick, idx) {
  203. return {
  204. formattedLabel: labelFormatter(tick, idx),
  205. rawLabel: axis.scale.getLabel(tick),
  206. tickValue: tick.value,
  207. time: tick.time,
  208. "break": tick["break"]
  209. };
  210. })
  211. };
  212. }
  213. // Large category data calculation is performance sensitive, and ticks and label probably will
  214. // be fetched multiple times (e.g. shared by splitLine and axisTick). So we cache the result.
  215. // axis is created each time during a ec process, so we do not need to clear cache.
  216. var ensureCategoryTickCache = initAxisCacheMethod('axisTick');
  217. var ensureCategoryLabelCache = initAxisCacheMethod('axisLabel');
  218. /**
  219. * PENDING: refactor to JS Map? Because key can be a function or more complicated object, and
  220. * cache size always is small, and currently no JS Map object key polyfill, we use a simple
  221. * array cache instead of plain object hash.
  222. */
  223. function initAxisCacheMethod(prop) {
  224. return function ensureCache(axis) {
  225. return axisInner(axis)[prop] || (axisInner(axis)[prop] = {
  226. list: []
  227. });
  228. };
  229. }
  230. function axisCacheGet(cache, key) {
  231. for (var i = 0; i < cache.list.length; i++) {
  232. if (cache.list[i].key === key) {
  233. return cache.list[i].value;
  234. }
  235. }
  236. }
  237. function axisCacheSet(cache, key, value) {
  238. cache.list.push({
  239. key: key,
  240. value: value
  241. });
  242. return value;
  243. }
  244. function makeAutoCategoryInterval(axis, ctx) {
  245. if (ctx.kind === AxisTickLabelComputingKind.estimate) {
  246. // Currently axisTick is not involved in estimate kind, and the result likely varies during a
  247. // single pass of ec main process, due to the change of axisExtent. Therefore no cache is used.
  248. var result_2 = axis.calculateCategoryInterval(ctx);
  249. ctx.out.noPxChangeTryDetermine.push(function () {
  250. axisInner(axis).autoInterval = result_2;
  251. return true;
  252. });
  253. return result_2;
  254. }
  255. // Both tick and label uses this result, cacah it to avoid recompute.
  256. var result = axisInner(axis).autoInterval;
  257. return result != null ? result : axisInner(axis).autoInterval = axis.calculateCategoryInterval(ctx);
  258. }
  259. /**
  260. * Calculate interval for category axis ticks and labels.
  261. * Use a stretegy to try to avoid overlapping.
  262. * To get precise result, at least one of `getRotate` and `isHorizontal`
  263. * should be implemented in axis.
  264. */
  265. export function calculateCategoryInterval(axis, ctx) {
  266. var kind = ctx.kind;
  267. var params = fetchAutoCategoryIntervalCalculationParams(axis);
  268. var labelFormatter = makeLabelFormatter(axis);
  269. var rotation = (params.axisRotate - params.labelRotate) / 180 * Math.PI;
  270. var ordinalScale = axis.scale;
  271. var ordinalExtent = ordinalScale.getExtent();
  272. // Providing this method is for optimization:
  273. // avoid generating a long array by `getTicks`
  274. // in large category data case.
  275. var tickCount = ordinalScale.count();
  276. if (ordinalExtent[1] - ordinalExtent[0] < 1) {
  277. return 0;
  278. }
  279. var step = 1;
  280. // Simple optimization. Arbitrary value.
  281. var maxCount = 40;
  282. if (tickCount > maxCount) {
  283. step = Math.max(1, Math.floor(tickCount / maxCount));
  284. }
  285. var tickValue = ordinalExtent[0];
  286. var unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
  287. var unitW = Math.abs(unitSpan * Math.cos(rotation));
  288. var unitH = Math.abs(unitSpan * Math.sin(rotation));
  289. var maxW = 0;
  290. var maxH = 0;
  291. // Caution: Performance sensitive for large category data.
  292. // Consider dataZoom, we should make appropriate step to avoid O(n) loop.
  293. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  294. var width = 0;
  295. var height = 0;
  296. // Not precise, do not consider align and vertical align
  297. // and each distance from axis line yet.
  298. var rect = textContain.getBoundingRect(labelFormatter({
  299. value: tickValue
  300. }), params.font, 'center', 'top');
  301. // Magic number
  302. width = rect.width * 1.3;
  303. height = rect.height * 1.3;
  304. // Min size, void long loop.
  305. maxW = Math.max(maxW, width, 7);
  306. maxH = Math.max(maxH, height, 7);
  307. }
  308. var dw = maxW / unitW;
  309. var dh = maxH / unitH;
  310. // 0/0 is NaN, 1/0 is Infinity.
  311. isNaN(dw) && (dw = Infinity);
  312. isNaN(dh) && (dh = Infinity);
  313. var interval = Math.max(0, Math.floor(Math.min(dw, dh)));
  314. if (kind === AxisTickLabelComputingKind.estimate) {
  315. // In estimate kind, the inteval likely varies, thus do not erase the cache.
  316. ctx.out.noPxChangeTryDetermine.push(zrUtil.bind(calculateCategoryIntervalTryDetermine, null, axis, interval, tickCount));
  317. return interval;
  318. }
  319. var lastInterval = calculateCategoryIntervalDealCache(axis, interval, tickCount);
  320. return lastInterval != null ? lastInterval : interval;
  321. }
  322. function calculateCategoryIntervalTryDetermine(axis, interval, tickCount) {
  323. return calculateCategoryIntervalDealCache(axis, interval, tickCount) == null;
  324. }
  325. // Return the lastInterval if need to use it, otherwise return NullUndefined and save cache.
  326. function calculateCategoryIntervalDealCache(axis, interval, tickCount) {
  327. var cache = modelInner(axis.model);
  328. var axisExtent = axis.getExtent();
  329. var lastAutoInterval = cache.lastAutoInterval;
  330. var lastTickCount = cache.lastTickCount;
  331. // Use cache to keep interval stable while moving zoom window,
  332. // otherwise the calculated interval might jitter when the zoom
  333. // window size is close to the interval-changing size.
  334. // For example, if all of the axis labels are `a, b, c, d, e, f, g`.
  335. // The jitter will cause that sometimes the displayed labels are
  336. // `a, d, g` (interval: 2) sometimes `a, c, e`(interval: 1).
  337. if (lastAutoInterval != null && lastTickCount != null && Math.abs(lastAutoInterval - interval) <= 1 && Math.abs(lastTickCount - tickCount) <= 1
  338. // Always choose the bigger one, otherwise the critical
  339. // point is not the same when zooming in or zooming out.
  340. && lastAutoInterval > interval
  341. // If the axis change is caused by chart resize, the cache should not
  342. // be used. Otherwise some hidden labels might not be shown again.
  343. && cache.axisExtent0 === axisExtent[0] && cache.axisExtent1 === axisExtent[1]) {
  344. return lastAutoInterval;
  345. }
  346. // Only update cache if cache not used, otherwise the
  347. // changing of interval is too insensitive.
  348. else {
  349. cache.lastTickCount = tickCount;
  350. cache.lastAutoInterval = interval;
  351. cache.axisExtent0 = axisExtent[0];
  352. cache.axisExtent1 = axisExtent[1];
  353. }
  354. }
  355. function fetchAutoCategoryIntervalCalculationParams(axis) {
  356. var labelModel = axis.getLabelModel();
  357. return {
  358. axisRotate: axis.getRotate ? axis.getRotate() : axis.isHorizontal && !axis.isHorizontal() ? 90 : 0,
  359. labelRotate: labelModel.get('rotate') || 0,
  360. font: labelModel.getFont()
  361. };
  362. }
  363. function makeLabelsByNumericCategoryInterval(axis, categoryInterval, onlyTick) {
  364. var labelFormatter = makeLabelFormatter(axis);
  365. var ordinalScale = axis.scale;
  366. var ordinalExtent = ordinalScale.getExtent();
  367. var labelModel = axis.getLabelModel();
  368. var result = [];
  369. // TODO: axisType: ordinalTime, pick the tick from each month/day/year/...
  370. var step = Math.max((categoryInterval || 0) + 1, 1);
  371. var startTick = ordinalExtent[0];
  372. var tickCount = ordinalScale.count();
  373. // Calculate start tick based on zero if possible to keep label consistent
  374. // while zooming and moving while interval > 0. Otherwise the selection
  375. // of displayable ticks and symbols probably keep changing.
  376. // 3 is empirical value.
  377. if (startTick !== 0 && step > 1 && tickCount / step > 2) {
  378. startTick = Math.round(Math.ceil(startTick / step) * step);
  379. }
  380. // (1) Only add min max label here but leave overlap checking
  381. // to render stage, which also ensure the returned list
  382. // suitable for splitLine and splitArea rendering.
  383. // (2) Scales except category always contain min max label so
  384. // do not need to perform this process.
  385. var showAllLabel = shouldShowAllLabels(axis);
  386. var includeMinLabel = labelModel.get('showMinLabel') || showAllLabel;
  387. var includeMaxLabel = labelModel.get('showMaxLabel') || showAllLabel;
  388. if (includeMinLabel && startTick !== ordinalExtent[0]) {
  389. addItem(ordinalExtent[0]);
  390. }
  391. // Optimize: avoid generating large array by `ordinalScale.getTicks()`.
  392. var tickValue = startTick;
  393. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  394. addItem(tickValue);
  395. }
  396. if (includeMaxLabel && tickValue - step !== ordinalExtent[1]) {
  397. addItem(ordinalExtent[1]);
  398. }
  399. function addItem(tickValue) {
  400. var tickObj = {
  401. value: tickValue
  402. };
  403. result.push(onlyTick ? tickValue : {
  404. formattedLabel: labelFormatter(tickObj),
  405. rawLabel: ordinalScale.getLabel(tickObj),
  406. tickValue: tickValue,
  407. time: undefined,
  408. "break": undefined
  409. });
  410. }
  411. return result;
  412. }
  413. function makeLabelsByCustomizedCategoryInterval(axis, categoryInterval, onlyTick) {
  414. var ordinalScale = axis.scale;
  415. var labelFormatter = makeLabelFormatter(axis);
  416. var result = [];
  417. zrUtil.each(ordinalScale.getTicks(), function (tick) {
  418. var rawLabel = ordinalScale.getLabel(tick);
  419. var tickValue = tick.value;
  420. if (categoryInterval(tick.value, rawLabel)) {
  421. result.push(onlyTick ? tickValue : {
  422. formattedLabel: labelFormatter(tick),
  423. rawLabel: rawLabel,
  424. tickValue: tickValue,
  425. time: undefined,
  426. "break": undefined
  427. });
  428. }
  429. });
  430. return result;
  431. }