formatters.tsx 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. import {Release} from '@sentry/release-parser';
  2. import round from 'lodash/round';
  3. import {t, tn} from 'sentry/locale';
  4. import {CommitAuthor, User} from 'sentry/types';
  5. export function userDisplayName(user: User | CommitAuthor, includeEmail = true): string {
  6. let displayName = String(user?.name ?? t('Unknown author')).trim();
  7. if (displayName.length <= 0) {
  8. displayName = t('Unknown author');
  9. }
  10. const email = String(user?.email ?? '').trim();
  11. if (email.length > 0 && email !== displayName && includeEmail) {
  12. displayName += ' (' + email + ')';
  13. }
  14. return displayName;
  15. }
  16. export const formatVersion = (rawVersion: string, withPackage = false) => {
  17. try {
  18. const parsedVersion = new Release(rawVersion);
  19. const versionToDisplay = parsedVersion.describe();
  20. if (versionToDisplay.length) {
  21. return `${versionToDisplay}${
  22. withPackage && parsedVersion.package ? `, ${parsedVersion.package}` : ''
  23. }`;
  24. }
  25. return rawVersion;
  26. } catch {
  27. return rawVersion;
  28. }
  29. };
  30. function roundWithFixed(
  31. value: number,
  32. fixedDigits: number
  33. ): {label: string; result: number} {
  34. const label = value.toFixed(fixedDigits);
  35. const result = fixedDigits <= 0 ? Math.round(value) : value;
  36. return {label, result};
  37. }
  38. // in milliseconds
  39. export const MONTH = 2629800000;
  40. export const WEEK = 604800000;
  41. export const DAY = 86400000;
  42. export const HOUR = 3600000;
  43. export const MINUTE = 60000;
  44. export const SECOND = 1000;
  45. /**
  46. * Returns a human redable duration rounded to the largest unit.
  47. *
  48. * e.g. 2 days, or 3 months, or 25 seoconds
  49. *
  50. * Use `getExactDuration` for exact durations
  51. */
  52. export function getDuration(
  53. seconds: number,
  54. fixedDigits: number = 0,
  55. abbreviation: boolean = false,
  56. extraShort: boolean = false,
  57. absolute: boolean = false
  58. ): string {
  59. const absValue = Math.abs(seconds * 1000);
  60. // value in milliseconds
  61. const msValue = absolute ? absValue : seconds * 1000;
  62. if (absValue >= MONTH && !extraShort) {
  63. const {label, result} = roundWithFixed(msValue / MONTH, fixedDigits);
  64. return `${label}${abbreviation ? t('mo') : ` ${tn('month', 'months', result)}`}`;
  65. }
  66. if (absValue >= WEEK) {
  67. const {label, result} = roundWithFixed(msValue / WEEK, fixedDigits);
  68. if (extraShort) {
  69. return `${label}${t('w')}`;
  70. }
  71. if (abbreviation) {
  72. return `${label}${t('wk')}`;
  73. }
  74. return `${label} ${tn('week', 'weeks', result)}`;
  75. }
  76. if (absValue >= DAY) {
  77. const {label, result} = roundWithFixed(msValue / DAY, fixedDigits);
  78. if (extraShort || abbreviation) {
  79. return `${label}${t('d')}`;
  80. }
  81. return `${label} ${tn('day', 'days', result)}`;
  82. }
  83. if (absValue >= HOUR) {
  84. const {label, result} = roundWithFixed(msValue / HOUR, fixedDigits);
  85. if (extraShort) {
  86. return `${label}${t('h')}`;
  87. }
  88. if (abbreviation) {
  89. return `${label}${t('hr')}`;
  90. }
  91. return `${label} ${tn('hour', 'hours', result)}`;
  92. }
  93. if (absValue >= MINUTE) {
  94. const {label, result} = roundWithFixed(msValue / MINUTE, fixedDigits);
  95. if (extraShort) {
  96. return `${label}${t('m')}`;
  97. }
  98. if (abbreviation) {
  99. return `${label}${t('min')}`;
  100. }
  101. return `${label} ${tn('minute', 'minutes', result)}`;
  102. }
  103. if (absValue >= SECOND) {
  104. const {label, result} = roundWithFixed(msValue / SECOND, fixedDigits);
  105. if (extraShort || abbreviation) {
  106. return `${label}${t('s')}`;
  107. }
  108. return `${label} ${tn('second', 'seconds', result)}`;
  109. }
  110. const {label, result} = roundWithFixed(msValue, fixedDigits);
  111. if (extraShort || abbreviation) {
  112. return `${label}${t('ms')}`;
  113. }
  114. return `${label} ${tn('millisecond', 'milliseconds', result)}`;
  115. }
  116. /**
  117. * Returns a human readable exact duration.
  118. *
  119. * e.g. 1 hour 25 minutes 15 seconds
  120. */
  121. export function getExactDuration(seconds: number, abbreviation: boolean = false) {
  122. const convertDuration = (secs: number, abbr: boolean): string => {
  123. // value in milliseconds
  124. const msValue = round(secs * 1000);
  125. const value = round(Math.abs(secs * 1000));
  126. const divideBy = (time: number) => {
  127. return {
  128. quotient: msValue < 0 ? Math.ceil(msValue / time) : Math.floor(msValue / time),
  129. remainder: msValue % time,
  130. };
  131. };
  132. if (value >= WEEK) {
  133. const {quotient, remainder} = divideBy(WEEK);
  134. const suffix = abbr ? t('wk') : ` ${tn('week', 'weeks', quotient)}`;
  135. return `${quotient}${suffix} ${convertDuration(remainder / 1000, abbr)}`;
  136. }
  137. if (value >= DAY) {
  138. const {quotient, remainder} = divideBy(DAY);
  139. const suffix = abbr ? t('d') : ` ${tn('day', 'days', quotient)}`;
  140. return `${quotient}${suffix} ${convertDuration(remainder / 1000, abbr)}`;
  141. }
  142. if (value >= HOUR) {
  143. const {quotient, remainder} = divideBy(HOUR);
  144. const suffix = abbr ? t('hr') : ` ${tn('hour', 'hours', quotient)}`;
  145. return `${quotient}${suffix} ${convertDuration(remainder / 1000, abbr)}`;
  146. }
  147. if (value >= MINUTE) {
  148. const {quotient, remainder} = divideBy(MINUTE);
  149. const suffix = abbr ? t('min') : ` ${tn('minute', 'minutes', quotient)}`;
  150. return `${quotient}${suffix} ${convertDuration(remainder / 1000, abbr)}`;
  151. }
  152. if (value >= SECOND) {
  153. const {quotient, remainder} = divideBy(SECOND);
  154. const suffix = abbr ? t('s') : ` ${tn('second', 'seconds', quotient)}`;
  155. return `${quotient}${suffix} ${convertDuration(remainder / 1000, abbr)}`;
  156. }
  157. if (value === 0) {
  158. return '';
  159. }
  160. const suffix = abbr ? t('ms') : ` ${tn('millisecond', 'milliseconds', value)}`;
  161. return `${msValue}${suffix}`;
  162. };
  163. const result = convertDuration(seconds, abbreviation).trim();
  164. if (result.length) {
  165. return result;
  166. }
  167. return `0${abbreviation ? t('ms') : ` ${t('milliseconds')}`}`;
  168. }
  169. export function formatSecondsToClock(
  170. seconds: number,
  171. {padAll}: {padAll: boolean} = {padAll: true}
  172. ) {
  173. if (seconds === 0 || isNaN(seconds)) {
  174. return padAll ? '00:00' : '0:00';
  175. }
  176. const divideBy = (msValue: number, time: number) => {
  177. return {
  178. quotient: msValue < 0 ? Math.ceil(msValue / time) : Math.floor(msValue / time),
  179. remainder: msValue % time,
  180. };
  181. };
  182. // value in milliseconds
  183. const absMSValue = round(Math.abs(seconds * 1000));
  184. const {quotient: hours, remainder: rMins} = divideBy(absMSValue, HOUR);
  185. const {quotient: minutes, remainder: rSeconds} = divideBy(rMins, MINUTE);
  186. const {quotient: secs, remainder: milliseconds} = divideBy(rSeconds, SECOND);
  187. const fill = (num: number) => (num < 10 ? `0${num}` : String(num));
  188. const parts = hours
  189. ? [padAll ? fill(hours) : hours, fill(minutes), fill(secs)]
  190. : [padAll ? fill(minutes) : minutes, fill(secs)];
  191. const ms = `000${milliseconds}`.slice(-3);
  192. return milliseconds ? `${parts.join(':')}.${ms}` : parts.join(':');
  193. }
  194. export function parseClockToSeconds(clock: string) {
  195. const [rest, milliseconds] = clock.split('.');
  196. const parts = rest.split(':');
  197. let seconds = 0;
  198. const progression = [MONTH, WEEK, DAY, HOUR, MINUTE, SECOND].slice(parts.length * -1);
  199. for (let i = 0; i < parts.length; i++) {
  200. const num = Number(parts[i]) || 0;
  201. const time = progression[i] / 1000;
  202. seconds += num * time;
  203. }
  204. const ms = Number(milliseconds) || 0;
  205. return seconds + ms / 1000;
  206. }
  207. export function formatFloat(number: number, places: number) {
  208. const multi = Math.pow(10, places);
  209. return parseInt((number * multi).toString(), 10) / multi;
  210. }
  211. /**
  212. * Format a value between 0 and 1 as a percentage
  213. */
  214. export function formatPercentage(value: number, places: number = 2) {
  215. if (value === 0) {
  216. return '0%';
  217. }
  218. return (
  219. round(value * 100, places).toLocaleString(undefined, {
  220. maximumFractionDigits: places,
  221. }) + '%'
  222. );
  223. }
  224. const numberFormats = [
  225. [1000000000, 'b'],
  226. [1000000, 'm'],
  227. [1000, 'k'],
  228. ] as const;
  229. export function formatAbbreviatedNumber(number: number | string) {
  230. number = Number(number);
  231. let lookup: (typeof numberFormats)[number];
  232. // eslint-disable-next-line no-cond-assign
  233. for (let i = 0; (lookup = numberFormats[i]); i++) {
  234. const [suffixNum, suffix] = lookup;
  235. const shortValue = Math.floor(number / suffixNum);
  236. const fitsBound = number % suffixNum;
  237. if (shortValue <= 0) {
  238. continue;
  239. }
  240. return shortValue / 10 > 1 || !fitsBound
  241. ? `${shortValue}${suffix}`
  242. : `${formatFloat(number / suffixNum, 1)}${suffix}`;
  243. }
  244. return number.toLocaleString();
  245. }
  246. export function formatRate(value: number, rateUnit?: string) {
  247. return `${value}/${rateUnit ?? 's'}`;
  248. }