formatters.tsx 8.5 KB

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