Time.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  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 { __extends } from "tslib";
  41. /*
  42. * A third-party license is embedded for some of the code in this file:
  43. * The "scaleLevels" was originally copied from "d3.js" with some
  44. * modifications made for this project.
  45. * (See more details in the comment on the definition of "scaleLevels" below.)
  46. * The use of the source code of this file is also subject to the terms
  47. * and consitions of the license of "d3.js" (BSD-3Clause, see
  48. * </licenses/LICENSE-d3>).
  49. */
  50. // [About UTC and local time zone]:
  51. // In most cases, `number.parseDate` will treat input data string as local time
  52. // (except time zone is specified in time string). And `format.formateTime` returns
  53. // local time by default. option.useUTC is false by default. This design has
  54. // considered these common cases:
  55. // (1) Time that is persistent in server is in UTC, but it is needed to be displayed
  56. // in local time by default.
  57. // (2) By default, the input data string (e.g., '2011-01-02') should be displayed
  58. // as its original time, without any time difference.
  59. import * as numberUtil from '../util/number.js';
  60. import { ONE_SECOND, ONE_MINUTE, ONE_HOUR, ONE_DAY, ONE_YEAR, format, leveledFormat, getUnitValue, timeUnits, fullLeveledFormatter, getPrimaryTimeUnit, isPrimaryTimeUnit, getDefaultFormatPrecisionOfInterval, fullYearGetterName, monthSetterName, fullYearSetterName, dateSetterName, hoursGetterName, hoursSetterName, minutesSetterName, secondsSetterName, millisecondsSetterName, monthGetterName, dateGetterName, minutesGetterName, secondsGetterName, millisecondsGetterName } from '../util/time.js';
  61. import * as scaleHelper from './helper.js';
  62. import IntervalScale from './Interval.js';
  63. import Scale from './Scale.js';
  64. import { warn } from '../util/log.js';
  65. import { filter, isNumber, map } from 'zrender/lib/core/util.js';
  66. // FIXME 公用?
  67. var bisect = function (a, x, lo, hi) {
  68. while (lo < hi) {
  69. var mid = lo + hi >>> 1;
  70. if (a[mid][1] < x) {
  71. lo = mid + 1;
  72. } else {
  73. hi = mid;
  74. }
  75. }
  76. return lo;
  77. };
  78. var TimeScale = /** @class */function (_super) {
  79. __extends(TimeScale, _super);
  80. function TimeScale(settings) {
  81. var _this = _super.call(this, settings) || this;
  82. _this.type = 'time';
  83. return _this;
  84. }
  85. /**
  86. * Get label is mainly for other components like dataZoom, tooltip.
  87. */
  88. TimeScale.prototype.getLabel = function (tick) {
  89. var useUTC = this.getSetting('useUTC');
  90. return format(tick.value, fullLeveledFormatter[getDefaultFormatPrecisionOfInterval(getPrimaryTimeUnit(this._minLevelUnit))] || fullLeveledFormatter.second, useUTC, this.getSetting('locale'));
  91. };
  92. TimeScale.prototype.getFormattedLabel = function (tick, idx, labelFormatter) {
  93. var isUTC = this.getSetting('useUTC');
  94. var lang = this.getSetting('locale');
  95. return leveledFormat(tick, idx, labelFormatter, lang, isUTC);
  96. };
  97. /**
  98. * @override
  99. */
  100. TimeScale.prototype.getTicks = function () {
  101. var interval = this._interval;
  102. var extent = this._extent;
  103. var ticks = [];
  104. // If interval is 0, return [];
  105. if (!interval) {
  106. return ticks;
  107. }
  108. ticks.push({
  109. value: extent[0],
  110. level: 0
  111. });
  112. var useUTC = this.getSetting('useUTC');
  113. var innerTicks = getIntervalTicks(this._minLevelUnit, this._approxInterval, useUTC, extent);
  114. ticks = ticks.concat(innerTicks);
  115. ticks.push({
  116. value: extent[1],
  117. level: 0
  118. });
  119. return ticks;
  120. };
  121. TimeScale.prototype.calcNiceExtent = function (opt) {
  122. var extent = this._extent;
  123. // If extent start and end are same, expand them
  124. if (extent[0] === extent[1]) {
  125. // Expand extent
  126. extent[0] -= ONE_DAY;
  127. extent[1] += ONE_DAY;
  128. }
  129. // If there are no data and extent are [Infinity, -Infinity]
  130. if (extent[1] === -Infinity && extent[0] === Infinity) {
  131. var d = new Date();
  132. extent[1] = +new Date(d.getFullYear(), d.getMonth(), d.getDate());
  133. extent[0] = extent[1] - ONE_DAY;
  134. }
  135. this.calcNiceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  136. };
  137. TimeScale.prototype.calcNiceTicks = function (approxTickNum, minInterval, maxInterval) {
  138. approxTickNum = approxTickNum || 10;
  139. var extent = this._extent;
  140. var span = extent[1] - extent[0];
  141. this._approxInterval = span / approxTickNum;
  142. if (minInterval != null && this._approxInterval < minInterval) {
  143. this._approxInterval = minInterval;
  144. }
  145. if (maxInterval != null && this._approxInterval > maxInterval) {
  146. this._approxInterval = maxInterval;
  147. }
  148. var scaleIntervalsLen = scaleIntervals.length;
  149. var idx = Math.min(bisect(scaleIntervals, this._approxInterval, 0, scaleIntervalsLen), scaleIntervalsLen - 1);
  150. // Interval that can be used to calculate ticks
  151. this._interval = scaleIntervals[idx][1];
  152. // Min level used when picking ticks from top down.
  153. // We check one more level to avoid the ticks are to sparse in some case.
  154. this._minLevelUnit = scaleIntervals[Math.max(idx - 1, 0)][0];
  155. };
  156. TimeScale.prototype.parse = function (val) {
  157. // val might be float.
  158. return isNumber(val) ? val : +numberUtil.parseDate(val);
  159. };
  160. TimeScale.prototype.contain = function (val) {
  161. return scaleHelper.contain(this.parse(val), this._extent);
  162. };
  163. TimeScale.prototype.normalize = function (val) {
  164. return scaleHelper.normalize(this.parse(val), this._extent);
  165. };
  166. TimeScale.prototype.scale = function (val) {
  167. return scaleHelper.scale(val, this._extent);
  168. };
  169. TimeScale.type = 'time';
  170. return TimeScale;
  171. }(IntervalScale);
  172. /**
  173. * This implementation was originally copied from "d3.js"
  174. * <https://github.com/d3/d3/blob/b516d77fb8566b576088e73410437494717ada26/src/time/scale.js>
  175. * with some modifications made for this program.
  176. * See the license statement at the head of this file.
  177. */
  178. var scaleIntervals = [
  179. // Format interval
  180. ['second', ONE_SECOND], ['minute', ONE_MINUTE], ['hour', ONE_HOUR], ['quarter-day', ONE_HOUR * 6], ['half-day', ONE_HOUR * 12], ['day', ONE_DAY * 1.2], ['half-week', ONE_DAY * 3.5], ['week', ONE_DAY * 7], ['month', ONE_DAY * 31], ['quarter', ONE_DAY * 95], ['half-year', ONE_YEAR / 2], ['year', ONE_YEAR] // 1Y
  181. ];
  182. function isUnitValueSame(unit, valueA, valueB, isUTC) {
  183. var dateA = numberUtil.parseDate(valueA);
  184. var dateB = numberUtil.parseDate(valueB);
  185. var isSame = function (unit) {
  186. return getUnitValue(dateA, unit, isUTC) === getUnitValue(dateB, unit, isUTC);
  187. };
  188. var isSameYear = function () {
  189. return isSame('year');
  190. };
  191. // const isSameHalfYear = () => isSameYear() && isSame('half-year');
  192. // const isSameQuater = () => isSameYear() && isSame('quarter');
  193. var isSameMonth = function () {
  194. return isSameYear() && isSame('month');
  195. };
  196. var isSameDay = function () {
  197. return isSameMonth() && isSame('day');
  198. };
  199. // const isSameHalfDay = () => isSameDay() && isSame('half-day');
  200. var isSameHour = function () {
  201. return isSameDay() && isSame('hour');
  202. };
  203. var isSameMinute = function () {
  204. return isSameHour() && isSame('minute');
  205. };
  206. var isSameSecond = function () {
  207. return isSameMinute() && isSame('second');
  208. };
  209. var isSameMilliSecond = function () {
  210. return isSameSecond() && isSame('millisecond');
  211. };
  212. switch (unit) {
  213. case 'year':
  214. return isSameYear();
  215. case 'month':
  216. return isSameMonth();
  217. case 'day':
  218. return isSameDay();
  219. case 'hour':
  220. return isSameHour();
  221. case 'minute':
  222. return isSameMinute();
  223. case 'second':
  224. return isSameSecond();
  225. case 'millisecond':
  226. return isSameMilliSecond();
  227. }
  228. }
  229. // const primaryUnitGetters = {
  230. // year: fullYearGetterName(),
  231. // month: monthGetterName(),
  232. // day: dateGetterName(),
  233. // hour: hoursGetterName(),
  234. // minute: minutesGetterName(),
  235. // second: secondsGetterName(),
  236. // millisecond: millisecondsGetterName()
  237. // };
  238. // const primaryUnitUTCGetters = {
  239. // year: fullYearGetterName(true),
  240. // month: monthGetterName(true),
  241. // day: dateGetterName(true),
  242. // hour: hoursGetterName(true),
  243. // minute: minutesGetterName(true),
  244. // second: secondsGetterName(true),
  245. // millisecond: millisecondsGetterName(true)
  246. // };
  247. // function moveTick(date: Date, unitName: TimeUnit, step: number, isUTC: boolean) {
  248. // step = step || 1;
  249. // switch (getPrimaryTimeUnit(unitName)) {
  250. // case 'year':
  251. // date[fullYearSetterName(isUTC)](date[fullYearGetterName(isUTC)]() + step);
  252. // break;
  253. // case 'month':
  254. // date[monthSetterName(isUTC)](date[monthGetterName(isUTC)]() + step);
  255. // break;
  256. // case 'day':
  257. // date[dateSetterName(isUTC)](date[dateGetterName(isUTC)]() + step);
  258. // break;
  259. // case 'hour':
  260. // date[hoursSetterName(isUTC)](date[hoursGetterName(isUTC)]() + step);
  261. // break;
  262. // case 'minute':
  263. // date[minutesSetterName(isUTC)](date[minutesGetterName(isUTC)]() + step);
  264. // break;
  265. // case 'second':
  266. // date[secondsSetterName(isUTC)](date[secondsGetterName(isUTC)]() + step);
  267. // break;
  268. // case 'millisecond':
  269. // date[millisecondsSetterName(isUTC)](date[millisecondsGetterName(isUTC)]() + step);
  270. // break;
  271. // }
  272. // return date.getTime();
  273. // }
  274. // const DATE_INTERVALS = [[8, 7.5], [4, 3.5], [2, 1.5]];
  275. // const MONTH_INTERVALS = [[6, 5.5], [3, 2.5], [2, 1.5]];
  276. // const MINUTES_SECONDS_INTERVALS = [[30, 30], [20, 20], [15, 15], [10, 10], [5, 5], [2, 2]];
  277. function getDateInterval(approxInterval, daysInMonth) {
  278. approxInterval /= ONE_DAY;
  279. return approxInterval > 16 ? 16
  280. // Math.floor(daysInMonth / 2) + 1 // In this case we only want one tick between two months.
  281. : approxInterval > 7.5 ? 7 // TODO week 7 or day 8?
  282. : approxInterval > 3.5 ? 4 : approxInterval > 1.5 ? 2 : 1;
  283. }
  284. function getMonthInterval(approxInterval) {
  285. var APPROX_ONE_MONTH = 30 * ONE_DAY;
  286. approxInterval /= APPROX_ONE_MONTH;
  287. return approxInterval > 6 ? 6 : approxInterval > 3 ? 3 : approxInterval > 2 ? 2 : 1;
  288. }
  289. function getHourInterval(approxInterval) {
  290. approxInterval /= ONE_HOUR;
  291. return approxInterval > 12 ? 12 : approxInterval > 6 ? 6 : approxInterval > 3.5 ? 4 : approxInterval > 2 ? 2 : 1;
  292. }
  293. function getMinutesAndSecondsInterval(approxInterval, isMinutes) {
  294. approxInterval /= isMinutes ? ONE_MINUTE : ONE_SECOND;
  295. return approxInterval > 30 ? 30 : approxInterval > 20 ? 20 : approxInterval > 15 ? 15 : approxInterval > 10 ? 10 : approxInterval > 5 ? 5 : approxInterval > 2 ? 2 : 1;
  296. }
  297. function getMillisecondsInterval(approxInterval) {
  298. return numberUtil.nice(approxInterval, true);
  299. }
  300. function getFirstTimestampOfUnit(date, unitName, isUTC) {
  301. var outDate = new Date(date);
  302. switch (getPrimaryTimeUnit(unitName)) {
  303. case 'year':
  304. case 'month':
  305. outDate[monthSetterName(isUTC)](0);
  306. case 'day':
  307. outDate[dateSetterName(isUTC)](1);
  308. case 'hour':
  309. outDate[hoursSetterName(isUTC)](0);
  310. case 'minute':
  311. outDate[minutesSetterName(isUTC)](0);
  312. case 'second':
  313. outDate[secondsSetterName(isUTC)](0);
  314. outDate[millisecondsSetterName(isUTC)](0);
  315. }
  316. return outDate.getTime();
  317. }
  318. function getIntervalTicks(bottomUnitName, approxInterval, isUTC, extent) {
  319. var safeLimit = 10000;
  320. var unitNames = timeUnits;
  321. var iter = 0;
  322. function addTicksInSpan(interval, minTimestamp, maxTimestamp, getMethodName, setMethodName, isDate, out) {
  323. var date = new Date(minTimestamp);
  324. var dateTime = minTimestamp;
  325. var d = date[getMethodName]();
  326. // if (isDate) {
  327. // d -= 1; // Starts with 0; PENDING
  328. // }
  329. while (dateTime < maxTimestamp && dateTime <= extent[1]) {
  330. out.push({
  331. value: dateTime
  332. });
  333. d += interval;
  334. date[setMethodName](d);
  335. dateTime = date.getTime();
  336. }
  337. // This extra tick is for calcuating ticks of next level. Will not been added to the final result
  338. out.push({
  339. value: dateTime,
  340. notAdd: true
  341. });
  342. }
  343. function addLevelTicks(unitName, lastLevelTicks, levelTicks) {
  344. var newAddedTicks = [];
  345. var isFirstLevel = !lastLevelTicks.length;
  346. if (isUnitValueSame(getPrimaryTimeUnit(unitName), extent[0], extent[1], isUTC)) {
  347. return;
  348. }
  349. if (isFirstLevel) {
  350. lastLevelTicks = [{
  351. // TODO Optimize. Not include so may ticks.
  352. value: getFirstTimestampOfUnit(new Date(extent[0]), unitName, isUTC)
  353. }, {
  354. value: extent[1]
  355. }];
  356. }
  357. for (var i = 0; i < lastLevelTicks.length - 1; i++) {
  358. var startTick = lastLevelTicks[i].value;
  359. var endTick = lastLevelTicks[i + 1].value;
  360. if (startTick === endTick) {
  361. continue;
  362. }
  363. var interval = void 0;
  364. var getterName = void 0;
  365. var setterName = void 0;
  366. var isDate = false;
  367. switch (unitName) {
  368. case 'year':
  369. interval = Math.max(1, Math.round(approxInterval / ONE_DAY / 365));
  370. getterName = fullYearGetterName(isUTC);
  371. setterName = fullYearSetterName(isUTC);
  372. break;
  373. case 'half-year':
  374. case 'quarter':
  375. case 'month':
  376. interval = getMonthInterval(approxInterval);
  377. getterName = monthGetterName(isUTC);
  378. setterName = monthSetterName(isUTC);
  379. break;
  380. case 'week': // PENDING If week is added. Ignore day.
  381. case 'half-week':
  382. case 'day':
  383. interval = getDateInterval(approxInterval, 31); // Use 32 days and let interval been 16
  384. getterName = dateGetterName(isUTC);
  385. setterName = dateSetterName(isUTC);
  386. isDate = true;
  387. break;
  388. case 'half-day':
  389. case 'quarter-day':
  390. case 'hour':
  391. interval = getHourInterval(approxInterval);
  392. getterName = hoursGetterName(isUTC);
  393. setterName = hoursSetterName(isUTC);
  394. break;
  395. case 'minute':
  396. interval = getMinutesAndSecondsInterval(approxInterval, true);
  397. getterName = minutesGetterName(isUTC);
  398. setterName = minutesSetterName(isUTC);
  399. break;
  400. case 'second':
  401. interval = getMinutesAndSecondsInterval(approxInterval, false);
  402. getterName = secondsGetterName(isUTC);
  403. setterName = secondsSetterName(isUTC);
  404. break;
  405. case 'millisecond':
  406. interval = getMillisecondsInterval(approxInterval);
  407. getterName = millisecondsGetterName(isUTC);
  408. setterName = millisecondsSetterName(isUTC);
  409. break;
  410. }
  411. addTicksInSpan(interval, startTick, endTick, getterName, setterName, isDate, newAddedTicks);
  412. if (unitName === 'year' && levelTicks.length > 1 && i === 0) {
  413. // Add nearest years to the left extent.
  414. levelTicks.unshift({
  415. value: levelTicks[0].value - interval
  416. });
  417. }
  418. }
  419. for (var i = 0; i < newAddedTicks.length; i++) {
  420. levelTicks.push(newAddedTicks[i]);
  421. }
  422. // newAddedTicks.length && console.log(unitName, newAddedTicks);
  423. return newAddedTicks;
  424. }
  425. var levelsTicks = [];
  426. var currentLevelTicks = [];
  427. var tickCount = 0;
  428. var lastLevelTickCount = 0;
  429. for (var i = 0; i < unitNames.length && iter++ < safeLimit; ++i) {
  430. var primaryTimeUnit = getPrimaryTimeUnit(unitNames[i]);
  431. if (!isPrimaryTimeUnit(unitNames[i])) {
  432. // TODO
  433. continue;
  434. }
  435. addLevelTicks(unitNames[i], levelsTicks[levelsTicks.length - 1] || [], currentLevelTicks);
  436. var nextPrimaryTimeUnit = unitNames[i + 1] ? getPrimaryTimeUnit(unitNames[i + 1]) : null;
  437. if (primaryTimeUnit !== nextPrimaryTimeUnit) {
  438. if (currentLevelTicks.length) {
  439. lastLevelTickCount = tickCount;
  440. // Remove the duplicate so the tick count can be precisely.
  441. currentLevelTicks.sort(function (a, b) {
  442. return a.value - b.value;
  443. });
  444. var levelTicksRemoveDuplicated = [];
  445. for (var i_1 = 0; i_1 < currentLevelTicks.length; ++i_1) {
  446. var tickValue = currentLevelTicks[i_1].value;
  447. if (i_1 === 0 || currentLevelTicks[i_1 - 1].value !== tickValue) {
  448. levelTicksRemoveDuplicated.push(currentLevelTicks[i_1]);
  449. if (tickValue >= extent[0] && tickValue <= extent[1]) {
  450. tickCount++;
  451. }
  452. }
  453. }
  454. var targetTickNum = (extent[1] - extent[0]) / approxInterval;
  455. // Added too much in this level and not too less in last level
  456. if (tickCount > targetTickNum * 1.5 && lastLevelTickCount > targetTickNum / 1.5) {
  457. break;
  458. }
  459. // Only treat primary time unit as one level.
  460. levelsTicks.push(levelTicksRemoveDuplicated);
  461. if (tickCount > targetTickNum || bottomUnitName === unitNames[i]) {
  462. break;
  463. }
  464. }
  465. // Reset if next unitName is primary
  466. currentLevelTicks = [];
  467. }
  468. }
  469. if (process.env.NODE_ENV !== 'production') {
  470. if (iter >= safeLimit) {
  471. warn('Exceed safe limit.');
  472. }
  473. }
  474. var levelsTicksInExtent = filter(map(levelsTicks, function (levelTicks) {
  475. return filter(levelTicks, function (tick) {
  476. return tick.value >= extent[0] && tick.value <= extent[1] && !tick.notAdd;
  477. });
  478. }), function (levelTicks) {
  479. return levelTicks.length > 0;
  480. });
  481. var ticks = [];
  482. var maxLevel = levelsTicksInExtent.length - 1;
  483. for (var i = 0; i < levelsTicksInExtent.length; ++i) {
  484. var levelTicks = levelsTicksInExtent[i];
  485. for (var k = 0; k < levelTicks.length; ++k) {
  486. ticks.push({
  487. value: levelTicks[k].value,
  488. level: maxLevel - i
  489. });
  490. }
  491. }
  492. ticks.sort(function (a, b) {
  493. return a.value - b.value;
  494. });
  495. // Remove duplicates
  496. var result = [];
  497. for (var i = 0; i < ticks.length; ++i) {
  498. if (i === 0 || ticks[i].value !== ticks[i - 1].value) {
  499. result.push(ticks[i]);
  500. }
  501. }
  502. return result;
  503. }
  504. Scale.registerClass(TimeScale);
  505. export default TimeScale;