format.js 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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';
  41. import { parseDate, isNumeric, numericToNumber } from './number';
  42. import { format as timeFormat, pad } from './time';
  43. import { deprecateReplaceLog } from './log';
  44. /**
  45. * Add a comma each three digit.
  46. */
  47. export function addCommas(x) {
  48. if (!isNumeric(x)) {
  49. return zrUtil.isString(x) ? x : '-';
  50. }
  51. var parts = (x + '').split('.');
  52. return parts[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g, '$1,') + (parts.length > 1 ? '.' + parts[1] : '');
  53. }
  54. export function toCamelCase(str, upperCaseFirst) {
  55. str = (str || '').toLowerCase().replace(/-(.)/g, function (match, group1) {
  56. return group1.toUpperCase();
  57. });
  58. if (upperCaseFirst && str) {
  59. str = str.charAt(0).toUpperCase() + str.slice(1);
  60. }
  61. return str;
  62. }
  63. export var normalizeCssArray = zrUtil.normalizeCssArray;
  64. var replaceReg = /([&<>"'])/g;
  65. var replaceMap = {
  66. '&': '&amp;',
  67. '<': '&lt;',
  68. '>': '&gt;',
  69. '"': '&quot;',
  70. '\'': '&#39;'
  71. };
  72. export function encodeHTML(source) {
  73. return source == null ? '' : (source + '').replace(replaceReg, function (str, c) {
  74. return replaceMap[c];
  75. });
  76. }
  77. /**
  78. * Make value user readable for tooltip and label.
  79. * "User readable":
  80. * Try to not print programmer-specific text like NaN, Infinity, null, undefined.
  81. * Avoid to display an empty string, which users can not recognize there is
  82. * a value and it might look like a bug.
  83. */
  84. export function makeValueReadable(value, valueType, useUTC) {
  85. var USER_READABLE_DEFUALT_TIME_PATTERN = '{yyyy}-{MM}-{dd} {hh}:{mm}:{ss}';
  86. function stringToUserReadable(str) {
  87. return str && zrUtil.trim(str) ? str : '-';
  88. }
  89. function isNumberUserReadable(num) {
  90. return !!(num != null && !isNaN(num) && isFinite(num));
  91. }
  92. var isTypeTime = valueType === 'time';
  93. var isValueDate = value instanceof Date;
  94. if (isTypeTime || isValueDate) {
  95. var date = isTypeTime ? parseDate(value) : value;
  96. if (!isNaN(+date)) {
  97. return timeFormat(date, USER_READABLE_DEFUALT_TIME_PATTERN, useUTC);
  98. } else if (isValueDate) {
  99. return '-';
  100. } // In other cases, continue to try to display the value in the following code.
  101. }
  102. if (valueType === 'ordinal') {
  103. return zrUtil.isStringSafe(value) ? stringToUserReadable(value) : zrUtil.isNumber(value) ? isNumberUserReadable(value) ? value + '' : '-' : '-';
  104. } // By default.
  105. var numericResult = numericToNumber(value);
  106. return isNumberUserReadable(numericResult) ? addCommas(numericResult) : zrUtil.isStringSafe(value) ? stringToUserReadable(value) : '-';
  107. }
  108. var TPL_VAR_ALIAS = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
  109. var wrapVar = function (varName, seriesIdx) {
  110. return '{' + varName + (seriesIdx == null ? '' : seriesIdx) + '}';
  111. };
  112. /**
  113. * Template formatter
  114. * @param {Array.<Object>|Object} paramsList
  115. */
  116. export function formatTpl(tpl, paramsList, encode) {
  117. if (!zrUtil.isArray(paramsList)) {
  118. paramsList = [paramsList];
  119. }
  120. var seriesLen = paramsList.length;
  121. if (!seriesLen) {
  122. return '';
  123. }
  124. var $vars = paramsList[0].$vars || [];
  125. for (var i = 0; i < $vars.length; i++) {
  126. var alias = TPL_VAR_ALIAS[i];
  127. tpl = tpl.replace(wrapVar(alias), wrapVar(alias, 0));
  128. }
  129. for (var seriesIdx = 0; seriesIdx < seriesLen; seriesIdx++) {
  130. for (var k = 0; k < $vars.length; k++) {
  131. var val = paramsList[seriesIdx][$vars[k]];
  132. tpl = tpl.replace(wrapVar(TPL_VAR_ALIAS[k], seriesIdx), encode ? encodeHTML(val) : val);
  133. }
  134. }
  135. return tpl;
  136. }
  137. /**
  138. * simple Template formatter
  139. */
  140. export function formatTplSimple(tpl, param, encode) {
  141. zrUtil.each(param, function (value, key) {
  142. tpl = tpl.replace('{' + key + '}', encode ? encodeHTML(value) : value);
  143. });
  144. return tpl;
  145. }
  146. export function getTooltipMarker(inOpt, extraCssText) {
  147. var opt = zrUtil.isString(inOpt) ? {
  148. color: inOpt,
  149. extraCssText: extraCssText
  150. } : inOpt || {};
  151. var color = opt.color;
  152. var type = opt.type;
  153. extraCssText = opt.extraCssText;
  154. var renderMode = opt.renderMode || 'html';
  155. if (!color) {
  156. return '';
  157. }
  158. if (renderMode === 'html') {
  159. return type === 'subItem' ? '<span style="display:inline-block;vertical-align:middle;margin-right:8px;margin-left:3px;' + 'border-radius:4px;width:4px;height:4px;background-color:' // Only support string
  160. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>' : '<span style="display:inline-block;margin-right:4px;' + 'border-radius:10px;width:10px;height:10px;background-color:' + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>';
  161. } else {
  162. // Should better not to auto generate style name by auto-increment number here.
  163. // Because this util is usually called in tooltip formatter, which is probably
  164. // called repeatly when mouse move and the auto-increment number increases fast.
  165. // Users can make their own style name by theirselves, make it unique and readable.
  166. var markerId = opt.markerId || 'markerX';
  167. return {
  168. renderMode: renderMode,
  169. content: '{' + markerId + '|} ',
  170. style: type === 'subItem' ? {
  171. width: 4,
  172. height: 4,
  173. borderRadius: 2,
  174. backgroundColor: color
  175. } : {
  176. width: 10,
  177. height: 10,
  178. borderRadius: 5,
  179. backgroundColor: color
  180. }
  181. };
  182. }
  183. }
  184. /**
  185. * @deprecated Use `time/format` instead.
  186. * ISO Date format
  187. * @param {string} tpl
  188. * @param {number} value
  189. * @param {boolean} [isUTC=false] Default in local time.
  190. * see `module:echarts/scale/Time`
  191. * and `module:echarts/util/number#parseDate`.
  192. * @inner
  193. */
  194. export function formatTime(tpl, value, isUTC) {
  195. if (process.env.NODE_ENV !== 'production') {
  196. deprecateReplaceLog('echarts.format.formatTime', 'echarts.time.format');
  197. }
  198. if (tpl === 'week' || tpl === 'month' || tpl === 'quarter' || tpl === 'half-year' || tpl === 'year') {
  199. tpl = 'MM-dd\nyyyy';
  200. }
  201. var date = parseDate(value);
  202. var utc = isUTC ? 'UTC' : '';
  203. var y = date['get' + utc + 'FullYear']();
  204. var M = date['get' + utc + 'Month']() + 1;
  205. var d = date['get' + utc + 'Date']();
  206. var h = date['get' + utc + 'Hours']();
  207. var m = date['get' + utc + 'Minutes']();
  208. var s = date['get' + utc + 'Seconds']();
  209. var S = date['get' + utc + 'Milliseconds']();
  210. tpl = tpl.replace('MM', pad(M, 2)).replace('M', M).replace('yyyy', y).replace('yy', y % 100 + '').replace('dd', pad(d, 2)).replace('d', d).replace('hh', pad(h, 2)).replace('h', h).replace('mm', pad(m, 2)).replace('m', m).replace('ss', pad(s, 2)).replace('s', s).replace('SSS', pad(S, 3));
  211. return tpl;
  212. }
  213. /**
  214. * Capital first
  215. * @param {string} str
  216. * @return {string}
  217. */
  218. export function capitalFirst(str) {
  219. return str ? str.charAt(0).toUpperCase() + str.substr(1) : str;
  220. }
  221. /**
  222. * @return Never be null/undefined.
  223. */
  224. export function convertToColorString(color, defaultColor) {
  225. defaultColor = defaultColor || 'transparent';
  226. return zrUtil.isString(color) ? color : zrUtil.isObject(color) ? color.colorStops && (color.colorStops[0] || {}).color || defaultColor : defaultColor;
  227. }
  228. export { truncateText } from 'zrender/lib/graphic/helper/parseText';
  229. /**
  230. * open new tab
  231. * @param link url
  232. * @param target blank or self
  233. */
  234. export function windowOpen(link, target) {
  235. /* global window */
  236. if (target === '_blank' || target === 'blank') {
  237. var blank = window.open();
  238. blank.opener = null;
  239. blank.location.href = link;
  240. } else {
  241. window.open(link, target);
  242. }
  243. }
  244. export { getTextRect } from '../legacy/getTextRect';