Time.js 19 KB

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