formatters.tsx 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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. export function getDuration(
  46. seconds: number,
  47. fixedDigits: number = 0,
  48. abbreviation: boolean = false,
  49. extraShort: boolean = false
  50. ): string {
  51. // value in milliseconds
  52. const msValue = seconds * 1000;
  53. const value = Math.abs(msValue);
  54. if (value >= MONTH && !extraShort) {
  55. const {label, result} = roundWithFixed(msValue / MONTH, fixedDigits);
  56. return `${label}${abbreviation ? t('mo') : ` ${tn('month', 'months', result)}`}`;
  57. }
  58. if (value >= WEEK) {
  59. const {label, result} = roundWithFixed(msValue / WEEK, fixedDigits);
  60. if (extraShort) {
  61. return `${label}${t('w')}`;
  62. }
  63. if (abbreviation) {
  64. return `${label}${t('wk')}`;
  65. }
  66. return `${label} ${tn('week', 'weeks', result)}`;
  67. }
  68. if (value >= DAY) {
  69. const {label, result} = roundWithFixed(msValue / DAY, fixedDigits);
  70. return `${label}${
  71. abbreviation || extraShort ? t('d') : ` ${tn('day', 'days', result)}`
  72. }`;
  73. }
  74. if (value >= HOUR) {
  75. const {label, result} = roundWithFixed(msValue / HOUR, fixedDigits);
  76. if (extraShort) {
  77. return `${label}${t('h')}`;
  78. }
  79. if (abbreviation) {
  80. return `${label}${t('hr')}`;
  81. }
  82. return `${label} ${tn('hour', 'hours', result)}`;
  83. }
  84. if (value >= MINUTE) {
  85. const {label, result} = roundWithFixed(msValue / MINUTE, fixedDigits);
  86. if (extraShort) {
  87. return `${label}${t('m')}`;
  88. }
  89. if (abbreviation) {
  90. return `${label}${t('min')}`;
  91. }
  92. return `${label} ${tn('minute', 'minutes', result)}`;
  93. }
  94. if (value >= SECOND) {
  95. const {label, result} = roundWithFixed(msValue / SECOND, fixedDigits);
  96. if (extraShort || abbreviation) {
  97. return `${label}${t('s')}`;
  98. }
  99. return `${label} ${tn('second', 'seconds', result)}`;
  100. }
  101. const {label} = roundWithFixed(msValue, fixedDigits);
  102. return label + t('ms');
  103. }
  104. export function getExactDuration(seconds: number, abbreviation: boolean = false) {
  105. const convertDuration = (secs: number, abbr: boolean): string => {
  106. // value in milliseconds
  107. const msValue = round(secs * 1000);
  108. const value = round(Math.abs(secs * 1000));
  109. const divideBy = (time: number) => {
  110. return {
  111. quotient: msValue < 0 ? Math.ceil(msValue / time) : Math.floor(msValue / time),
  112. remainder: msValue % time,
  113. };
  114. };
  115. if (value >= WEEK) {
  116. const {quotient, remainder} = divideBy(WEEK);
  117. return `${quotient}${
  118. abbr ? t('wk') : ` ${tn('week', 'weeks', quotient)}`
  119. } ${convertDuration(remainder / 1000, abbr)}`;
  120. }
  121. if (value >= DAY) {
  122. const {quotient, remainder} = divideBy(DAY);
  123. return `${quotient}${
  124. abbr ? t('d') : ` ${tn('day', 'days', quotient)}`
  125. } ${convertDuration(remainder / 1000, abbr)}`;
  126. }
  127. if (value >= HOUR) {
  128. const {quotient, remainder} = divideBy(HOUR);
  129. return `${quotient}${
  130. abbr ? t('hr') : ` ${tn('hour', 'hours', quotient)}`
  131. } ${convertDuration(remainder / 1000, abbr)}`;
  132. }
  133. if (value >= MINUTE) {
  134. const {quotient, remainder} = divideBy(MINUTE);
  135. return `${quotient}${
  136. abbr ? t('min') : ` ${tn('minute', 'minutes', quotient)}`
  137. } ${convertDuration(remainder / 1000, abbr)}`;
  138. }
  139. if (value >= SECOND) {
  140. const {quotient, remainder} = divideBy(SECOND);
  141. return `${quotient}${
  142. abbr ? t('s') : ` ${tn('second', 'seconds', quotient)}`
  143. } ${convertDuration(remainder / 1000, abbr)}`;
  144. }
  145. if (value === 0) {
  146. return '';
  147. }
  148. return `${msValue}${abbr ? t('ms') : ` ${tn('millisecond', 'milliseconds', value)}`}`;
  149. };
  150. const result = convertDuration(seconds, abbreviation).trim();
  151. if (result.length) {
  152. return result;
  153. }
  154. return `0${abbreviation ? t('ms') : ` ${t('milliseconds')}`}`;
  155. }
  156. export function formatSecondsToClock(
  157. seconds: number,
  158. {padAll}: {padAll: boolean} = {padAll: true}
  159. ) {
  160. if (seconds === 0 || isNaN(seconds)) {
  161. return padAll ? '00:00' : '0:00';
  162. }
  163. const divideBy = (msValue: number, time: number) => {
  164. return {
  165. quotient: msValue < 0 ? Math.ceil(msValue / time) : Math.floor(msValue / time),
  166. remainder: msValue % time,
  167. };
  168. };
  169. // value in milliseconds
  170. const absMSValue = round(Math.abs(seconds * 1000));
  171. const {quotient: hours, remainder: rMins} = divideBy(absMSValue, HOUR);
  172. const {quotient: minutes, remainder: rSeconds} = divideBy(rMins, MINUTE);
  173. const {quotient: secs, remainder: milliseconds} = divideBy(rSeconds, SECOND);
  174. const fill = (num: number) => (num < 10 ? `0${num}` : String(num));
  175. const parts = hours
  176. ? [padAll ? fill(hours) : hours, fill(minutes), fill(secs)]
  177. : [padAll ? fill(minutes) : minutes, fill(secs)];
  178. const ms = `000${milliseconds}`.slice(-3);
  179. return milliseconds ? `${parts.join(':')}.${ms}` : parts.join(':');
  180. }
  181. export function parseClockToSeconds(clock: string) {
  182. const [rest, milliseconds] = clock.split('.');
  183. const parts = rest.split(':');
  184. let seconds = 0;
  185. const progression = [MONTH, WEEK, DAY, HOUR, MINUTE, SECOND].slice(parts.length * -1);
  186. for (let i = 0; i < parts.length; i++) {
  187. const num = Number(parts[i]) || 0;
  188. const time = progression[i] / 1000;
  189. seconds += num * time;
  190. }
  191. const ms = Number(milliseconds) || 0;
  192. return seconds + ms / 1000;
  193. }
  194. export function formatFloat(number: number, places: number) {
  195. const multi = Math.pow(10, places);
  196. return parseInt((number * multi).toString(), 10) / multi;
  197. }
  198. /**
  199. * Format a value between 0 and 1 as a percentage
  200. */
  201. export function formatPercentage(value: number, places: number = 2) {
  202. if (value === 0) {
  203. return '0%';
  204. }
  205. return (
  206. round(value * 100, places).toLocaleString(undefined, {
  207. maximumFractionDigits: places,
  208. }) + '%'
  209. );
  210. }
  211. const numberFormats = [
  212. [1000000000, 'b'],
  213. [1000000, 'm'],
  214. [1000, 'k'],
  215. ] as const;
  216. export function formatAbbreviatedNumber(number: number | string) {
  217. number = Number(number);
  218. let lookup: typeof numberFormats[number];
  219. // eslint-disable-next-line no-cond-assign
  220. for (let i = 0; (lookup = numberFormats[i]); i++) {
  221. const [suffixNum, suffix] = lookup;
  222. const shortValue = Math.floor(number / suffixNum);
  223. const fitsBound = number % suffixNum;
  224. if (shortValue <= 0) {
  225. continue;
  226. }
  227. return shortValue / 10 > 1 || !fitsBound
  228. ? `${shortValue}${suffix}`
  229. : `${formatFloat(number / suffixNum, 1)}${suffix}`;
  230. }
  231. return number.toLocaleString();
  232. }