axisTickLabelBuilder.js 15 KB

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