Time.js 19 KB

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