helpers.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. // components
  2. import {Text} from 'recharts';
  3. // utils
  4. import dayjs from 'dayjs';
  5. // constants
  6. import CLUBS from '@constants/clubs';
  7. // represent large numbers in a shortened format
  8. export const numFormatter = (num, decimals = 2) => {
  9. num=Number(num);
  10. if (num > 999 && num < 1000000) {
  11. return (num / 1000).toFixed(decimals) + 'K';
  12. } else if (num > 1000000) {
  13. return (num / 1000000).toFixed(decimals) + 'M';
  14. } else if (num <= 999) {
  15. return num.toFixed(decimals);
  16. }
  17. }
  18. // random integer generator
  19. export const getRandomInt = (min, max) => {
  20. return Math.floor(Math.random() * (max - min + 1)) + min;
  21. }
  22. // add zero to numbers less than 10
  23. export function addZero(num) {
  24. return num < 10 ? '0' + num : num;
  25. }
  26. // grid y-axis or x-axis points generator for recharts
  27. /**
  28. *
  29. * @param id - container id
  30. * @param gutter - grid gutter
  31. * @param axis - 'x' or 'y'
  32. * @returns {*[]} - array of grid points
  33. */
  34. export const generateGridPoints = (id, gutter = 20, axis = 'y') => {
  35. const gridWidth = document.getElementById(id).offsetWidth;
  36. const gridHeight = document.getElementById(id).offsetHeight;
  37. let points = [];
  38. for (let i = 0; i < (axis === 'y' ? gridWidth : gridHeight); i += gutter) {
  39. points.push(i);
  40. }
  41. return points;
  42. }
  43. // prevent default behavior for all forms and links with href="#"
  44. export const preventDefault = () => {
  45. document.querySelectorAll('form').forEach(form => {
  46. form.addEventListener('submit', e => e.preventDefault());
  47. });
  48. document.querySelectorAll('a[href="#"]').forEach(a => {
  49. a.addEventListener('click', e => e.preventDefault());
  50. });
  51. }
  52. // get club info by id
  53. /** @param id - club id
  54. *
  55. * @param id
  56. * @returns {{country: string, color: string, city: string, name: string, logo: *, id: string, shortName: string} | {country: string, color: string, city: string, name: string, logo: *, id: string, shortName: string} | {country: string, color: string, city: string, name: string, logo: *, id: string, shortName: string} | {country: string, color: string, city: string, name: string, logo: *, id: string, shortName: string} | {country: string, color: string, city: string, name: string, logo: *, id: string, shortName: string}}
  57. */
  58. export const getClubInfo = (id) => CLUBS.find((club) => club.id === id);
  59. // get array of month days (date and weekday)
  60. export const getMonthDays = (month = dayjs().month(), year = dayjs().year()) => {
  61. const days = [];
  62. const daysInMonth = dayjs(`${year}-${month + 1}`).daysInMonth();
  63. for (let i = 1; i <= daysInMonth; i++) {
  64. days.push({
  65. date: dayjs(`${year}-${month + 1}-${i}`).format('DD'),
  66. weekday: dayjs(`${year}-${month + 1}-${i}`).format('dd')
  67. });
  68. }
  69. return days;
  70. }
  71. /**
  72. * render polar angle axis
  73. * @param payload
  74. * @param x
  75. * @param y
  76. * @param cx
  77. * @param cy
  78. * @param rest
  79. * @returns {JSX.Element}
  80. */
  81. export const renderPolarAngleAxis = ({payload, x, y, cx, cy, ...rest}) => {
  82. return (
  83. <Text
  84. {...rest}
  85. verticalAnchor="middle"
  86. textAnchor="middle"
  87. y={y + (y - cy) / 8}
  88. x={x + (x - cx) / 5}
  89. fill="var(--btn-text)"
  90. >
  91. {payload.value}
  92. </Text>
  93. );
  94. }
  95. /**
  96. * modify card number
  97. * @param cardNumber
  98. * @returns {string}
  99. */
  100. export const modifyCardNumber = (cardNumber) => {
  101. const lastDigits = cardNumber.substring(8);
  102. const maskedDigits = "**** ";
  103. // Combine the modified parts to form the final card number
  104. const modifiedCardNumber = maskedDigits + lastDigits.slice(-4);
  105. return modifiedCardNumber;
  106. }
  107. export const localStorageGet=(key,defaultValue="")=>{
  108. let value=localStorage.getItem(key);
  109. if (value==null)value=defaultValue;
  110. return value;
  111. }
  112. export const localStorageSet=(key,value)=>{
  113. localStorage.setItem(key,value);
  114. }
  115. export const getHttpMsg=(data)=>{
  116. let result=data.result;
  117. if (result==null)result=data.msg;
  118. let msg="";
  119. if (result!=null){
  120. let key=result[0];
  121. let def=result[1];
  122. if (global.i18n.exists(key))msg=global.i18n.t(key);
  123. else msg=def;
  124. }
  125. return msg;
  126. }
  127. export const sleep=async (time)=>{
  128. return new Promise((resolve, reject) => {
  129. setTimeout(() => {
  130. resolve(true);
  131. }, time);
  132. });
  133. }
  134. export const stringFormat=(str,args)=>{
  135. if (str==null)return str;
  136. if (args==null)args=[];
  137. return str.replace(/{(\d+)}/g, function(match, number) {
  138. return typeof args[number] != 'undefined'
  139. ? args[number]
  140. : match
  141. ;
  142. });
  143. }
  144. export const formatDate=(timestamp,format=null)=>{
  145. let date=new Date(timestamp);
  146. let year = `${date.getFullYear()}`;
  147. let month = `${date.getMonth() + 1}`;
  148. if (month.length === 1) {
  149. month = `0${month}`;
  150. }
  151. let day = `${date.getDate()}`;
  152. if (day.length === 1) {
  153. day = `0${day}`;
  154. }
  155. let hours = `${date.getHours()}`;
  156. if (hours.length === 1) {
  157. hours = `0${hours}`;
  158. }
  159. let minutes = `${date.getMinutes()}`;
  160. if (minutes.length === 1) {
  161. minutes = `0${minutes}`;
  162. }
  163. let seconds = `${date.getSeconds()}`;
  164. if (seconds.length === 1) {
  165. seconds = `0${seconds}`;
  166. }
  167. return (format || "yyyy-MM-dd hh:mm:ss")
  168. .replace(/yyyy/g, year)
  169. .replace(/MM/g, month)
  170. .replace(/dd/g, day)
  171. .replace(/hh/g, hours)
  172. .replace(/mm/g, minutes)
  173. .replace(/ss/g, seconds);
  174. }
  175. export const formatTime=(time,isms=false)=>{
  176. if (time==null)return "";
  177. let seconds=time;
  178. //毫秒
  179. if(isms)seconds=Math.floor(time/1000);
  180. let hours = Math.floor(seconds / 3600);
  181. let minutes = Math.floor((seconds % 3600) / 60);
  182. let remainingSeconds = seconds % 60;
  183. let formattedTime = `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(remainingSeconds).padStart(2, '0')}`;
  184. return formattedTime;
  185. }
  186. export const openFullScreen=()=>{
  187. var elem = document.documentElement; // 获取整个文档的根元素
  188. if (elem.requestFullscreen) {
  189. elem.requestFullscreen();
  190. } else if (elem.mozRequestFullScreen) {
  191. elem.mozRequestFullScreen();
  192. } else if (elem.webkitRequestFullscreen) {
  193. elem.webkitRequestFullscreen();
  194. } else if (elem.msRequestFullscreen) {
  195. elem.msRequestFullscreen();
  196. }
  197. }
  198. export const validateBRPhone=(t)=>{
  199. if (t && 11 === t.length) {
  200. var e = parseInt(t.substring(0, 2), 10)
  201. , i = parseInt(t.charAt(2), 10);
  202. return e >= 11 && e <= 99 && 9 == i
  203. }
  204. return false;
  205. }
  206. export const validateCountryPhone=(country,phone)=>{
  207. return validateBRPhone(phone);
  208. }
  209. export const formatCash=(cash,fixed=2)=>{
  210. cash=Number(cash);
  211. cash=cash/global.CASH_BASE;
  212. return cash.toFixed(fixed);
  213. }
  214. export const getUrlParam=(name)=>{
  215. if (window.location==null||window.location.href==null)return null;
  216. let url = window.location.href;
  217. return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(url) || [, ""])[1].replace(/\+/g, '%20')) || null;
  218. }