format.js 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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. var zrUtil = require("zrender/lib/core/util");
  20. var textContain = require("zrender/lib/contain/text");
  21. var numberUtil = require("./number");
  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 Text from 'zrender/src/graphic/Text';
  41. /**
  42. * add commas after every three numbers
  43. * @param {string|number} x
  44. * @return {string}
  45. */
  46. function addCommas(x) {
  47. if (isNaN(x)) {
  48. return '-';
  49. }
  50. x = (x + '').split('.');
  51. return x[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g, '$1,') + (x.length > 1 ? '.' + x[1] : '');
  52. }
  53. /**
  54. * @param {string} str
  55. * @param {boolean} [upperCaseFirst=false]
  56. * @return {string} str
  57. */
  58. function toCamelCase(str, upperCaseFirst) {
  59. str = (str || '').toLowerCase().replace(/-(.)/g, function (match, group1) {
  60. return group1.toUpperCase();
  61. });
  62. if (upperCaseFirst && str) {
  63. str = str.charAt(0).toUpperCase() + str.slice(1);
  64. }
  65. return str;
  66. }
  67. var normalizeCssArray = zrUtil.normalizeCssArray;
  68. var replaceReg = /([&<>"'])/g;
  69. var replaceMap = {
  70. '&': '&amp;',
  71. '<': '&lt;',
  72. '>': '&gt;',
  73. '"': '&quot;',
  74. '\'': '&#39;'
  75. };
  76. function encodeHTML(source) {
  77. return source == null ? '' : (source + '').replace(replaceReg, function (str, c) {
  78. return replaceMap[c];
  79. });
  80. }
  81. var TPL_VAR_ALIAS = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
  82. var wrapVar = function (varName, seriesIdx) {
  83. return '{' + varName + (seriesIdx == null ? '' : seriesIdx) + '}';
  84. };
  85. /**
  86. * Template formatter
  87. * @param {string} tpl
  88. * @param {Array.<Object>|Object} paramsList
  89. * @param {boolean} [encode=false]
  90. * @return {string}
  91. */
  92. function formatTpl(tpl, paramsList, encode) {
  93. if (!zrUtil.isArray(paramsList)) {
  94. paramsList = [paramsList];
  95. }
  96. var seriesLen = paramsList.length;
  97. if (!seriesLen) {
  98. return '';
  99. }
  100. var $vars = paramsList[0].$vars || [];
  101. for (var i = 0; i < $vars.length; i++) {
  102. var alias = TPL_VAR_ALIAS[i];
  103. tpl = tpl.replace(wrapVar(alias), wrapVar(alias, 0));
  104. }
  105. for (var seriesIdx = 0; seriesIdx < seriesLen; seriesIdx++) {
  106. for (var k = 0; k < $vars.length; k++) {
  107. var val = paramsList[seriesIdx][$vars[k]];
  108. tpl = tpl.replace(wrapVar(TPL_VAR_ALIAS[k], seriesIdx), encode ? encodeHTML(val) : val);
  109. }
  110. }
  111. return tpl;
  112. }
  113. /**
  114. * simple Template formatter
  115. *
  116. * @param {string} tpl
  117. * @param {Object} param
  118. * @param {boolean} [encode=false]
  119. * @return {string}
  120. */
  121. function formatTplSimple(tpl, param, encode) {
  122. zrUtil.each(param, function (value, key) {
  123. tpl = tpl.replace('{' + key + '}', encode ? encodeHTML(value) : value);
  124. });
  125. return tpl;
  126. }
  127. /**
  128. * @param {Object|string} [opt] If string, means color.
  129. * @param {string} [opt.color]
  130. * @param {string} [opt.extraCssText]
  131. * @param {string} [opt.type='item'] 'item' or 'subItem'
  132. * @param {string} [opt.renderMode='html'] render mode of tooltip, 'html' or 'richText'
  133. * @param {string} [opt.markerId='X'] id name for marker. If only one marker is in a rich text, this can be omitted.
  134. * @return {string}
  135. */
  136. function getTooltipMarker(opt, extraCssText) {
  137. opt = zrUtil.isString(opt) ? {
  138. color: opt,
  139. extraCssText: extraCssText
  140. } : opt || {};
  141. var color = opt.color;
  142. var type = opt.type;
  143. var extraCssText = opt.extraCssText;
  144. var renderMode = opt.renderMode || 'html';
  145. var markerId = opt.markerId || 'X';
  146. if (!color) {
  147. return '';
  148. }
  149. if (renderMode === 'html') {
  150. 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:' + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>' : '<span style="display:inline-block;margin-right:5px;' + 'border-radius:10px;width:10px;height:10px;background-color:' + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>';
  151. } else {
  152. // Space for rich element marker
  153. return {
  154. renderMode: renderMode,
  155. content: '{marker' + markerId + '|} ',
  156. style: {
  157. color: color
  158. }
  159. };
  160. }
  161. }
  162. function pad(str, len) {
  163. str += '';
  164. return '0000'.substr(0, len - str.length) + str;
  165. }
  166. /**
  167. * ISO Date format
  168. * @param {string} tpl
  169. * @param {number} value
  170. * @param {boolean} [isUTC=false] Default in local time.
  171. * see `module:echarts/scale/Time`
  172. * and `module:echarts/util/number#parseDate`.
  173. * @inner
  174. */
  175. function formatTime(tpl, value, isUTC) {
  176. if (tpl === 'week' || tpl === 'month' || tpl === 'quarter' || tpl === 'half-year' || tpl === 'year') {
  177. tpl = 'MM-dd\nyyyy';
  178. }
  179. var date = numberUtil.parseDate(value);
  180. var utc = isUTC ? 'UTC' : '';
  181. var y = date['get' + utc + 'FullYear']();
  182. var M = date['get' + utc + 'Month']() + 1;
  183. var d = date['get' + utc + 'Date']();
  184. var h = date['get' + utc + 'Hours']();
  185. var m = date['get' + utc + 'Minutes']();
  186. var s = date['get' + utc + 'Seconds']();
  187. var S = date['get' + utc + 'Milliseconds']();
  188. 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));
  189. return tpl;
  190. }
  191. /**
  192. * Capital first
  193. * @param {string} str
  194. * @return {string}
  195. */
  196. function capitalFirst(str) {
  197. return str ? str.charAt(0).toUpperCase() + str.substr(1) : str;
  198. }
  199. var truncateText = textContain.truncateText;
  200. /**
  201. * @public
  202. * @param {Object} opt
  203. * @param {string} opt.text
  204. * @param {string} opt.font
  205. * @param {string} [opt.textAlign='left']
  206. * @param {string} [opt.textVerticalAlign='top']
  207. * @param {Array.<number>} [opt.textPadding]
  208. * @param {number} [opt.textLineHeight]
  209. * @param {Object} [opt.rich]
  210. * @param {Object} [opt.truncate]
  211. * @return {Object} {x, y, width, height, lineHeight}
  212. */
  213. function getTextBoundingRect(opt) {
  214. return textContain.getBoundingRect(opt.text, opt.font, opt.textAlign, opt.textVerticalAlign, opt.textPadding, opt.textLineHeight, opt.rich, opt.truncate);
  215. }
  216. /**
  217. * @deprecated
  218. * the `textLineHeight` was added later.
  219. * For backward compatiblility, put it as the last parameter.
  220. * But deprecated this interface. Please use `getTextBoundingRect` instead.
  221. */
  222. function getTextRect(text, font, textAlign, textVerticalAlign, textPadding, rich, truncate, textLineHeight) {
  223. return textContain.getBoundingRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate);
  224. }
  225. /**
  226. * open new tab
  227. * @param {string} link url
  228. * @param {string} target blank or self
  229. */
  230. function windowOpen(link, target) {
  231. if (target === '_blank' || target === 'blank') {
  232. var blank = window.open();
  233. blank.opener = null;
  234. blank.location = link;
  235. } else {
  236. window.open(link, target);
  237. }
  238. }
  239. exports.addCommas = addCommas;
  240. exports.toCamelCase = toCamelCase;
  241. exports.normalizeCssArray = normalizeCssArray;
  242. exports.encodeHTML = encodeHTML;
  243. exports.formatTpl = formatTpl;
  244. exports.formatTplSimple = formatTplSimple;
  245. exports.getTooltipMarker = getTooltipMarker;
  246. exports.formatTime = formatTime;
  247. exports.capitalFirst = capitalFirst;
  248. exports.truncateText = truncateText;
  249. exports.getTextBoundingRect = getTextBoundingRect;
  250. exports.getTextRect = getTextRect;
  251. exports.windowOpen = windowOpen;