utils.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771
  1. /*
  2. Copyright (C) 2025 QuantumNous
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Affero General Public License as
  5. published by the Free Software Foundation, either version 3 of the
  6. License, or (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Affero General Public License for more details.
  11. You should have received a copy of the GNU Affero General Public License
  12. along with this program. If not, see <https://www.gnu.org/licenses/>.
  13. For commercial licensing, please contact support@quantumnous.com
  14. */
  15. import { Toast, Pagination } from '@douyinfe/semi-ui';
  16. import { toastConstants } from '../constants';
  17. import React from 'react';
  18. import { toast } from 'react-toastify';
  19. import { THINK_TAG_REGEX, MESSAGE_ROLES } from '../constants/playground.constants';
  20. import { TABLE_COMPACT_MODES_KEY } from '../constants';
  21. import { MOBILE_BREAKPOINT } from '../hooks/common/useIsMobile.js';
  22. const HTMLToastContent = ({ htmlContent }) => {
  23. return <div dangerouslySetInnerHTML={{ __html: htmlContent }} />;
  24. };
  25. export default HTMLToastContent;
  26. export function isAdmin() {
  27. let user = localStorage.getItem('user');
  28. if (!user) return false;
  29. user = JSON.parse(user);
  30. return user.role >= 10;
  31. }
  32. export function isRoot() {
  33. let user = localStorage.getItem('user');
  34. if (!user) return false;
  35. user = JSON.parse(user);
  36. return user.role >= 100;
  37. }
  38. export function getSystemName() {
  39. let system_name = localStorage.getItem('system_name');
  40. if (!system_name) return 'New API';
  41. return system_name;
  42. }
  43. export function getLogo() {
  44. let logo = localStorage.getItem('logo');
  45. if (!logo) return '/logo.png';
  46. return logo;
  47. }
  48. export function getUserIdFromLocalStorage() {
  49. let user = localStorage.getItem('user');
  50. if (!user) return -1;
  51. user = JSON.parse(user);
  52. return user.id;
  53. }
  54. export function getFooterHTML() {
  55. return localStorage.getItem('footer_html');
  56. }
  57. export async function copy(text) {
  58. let okay = true;
  59. try {
  60. await navigator.clipboard.writeText(text);
  61. } catch (e) {
  62. try {
  63. // 构建input 执行 复制命令
  64. var _input = window.document.createElement('input');
  65. _input.value = text;
  66. window.document.body.appendChild(_input);
  67. _input.select();
  68. window.document.execCommand('Copy');
  69. window.document.body.removeChild(_input);
  70. } catch (e) {
  71. okay = false;
  72. console.error(e);
  73. }
  74. }
  75. return okay;
  76. }
  77. // isMobile 函数已移除,请改用 useIsMobile Hook
  78. let showErrorOptions = { autoClose: toastConstants.ERROR_TIMEOUT };
  79. let showWarningOptions = { autoClose: toastConstants.WARNING_TIMEOUT };
  80. let showSuccessOptions = { autoClose: toastConstants.SUCCESS_TIMEOUT };
  81. let showInfoOptions = { autoClose: toastConstants.INFO_TIMEOUT };
  82. let showNoticeOptions = { autoClose: false };
  83. const isMobileScreen = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`).matches;
  84. if (isMobileScreen) {
  85. showErrorOptions.position = 'top-center';
  86. // showErrorOptions.transition = 'flip';
  87. showSuccessOptions.position = 'top-center';
  88. // showSuccessOptions.transition = 'flip';
  89. showInfoOptions.position = 'top-center';
  90. // showInfoOptions.transition = 'flip';
  91. showNoticeOptions.position = 'top-center';
  92. // showNoticeOptions.transition = 'flip';
  93. }
  94. export function showError(error) {
  95. console.error(error);
  96. if (error.message) {
  97. if (error.name === 'AxiosError') {
  98. switch (error.response.status) {
  99. case 401:
  100. // 清除用户状态
  101. localStorage.removeItem('user');
  102. // toast.error('错误:未登录或登录已过期,请重新登录!', showErrorOptions);
  103. window.location.href = '/login?expired=true';
  104. break;
  105. case 429:
  106. Toast.error('错误:请求次数过多,请稍后再试!');
  107. break;
  108. case 500:
  109. Toast.error('错误:服务器内部错误,请联系管理员!');
  110. break;
  111. case 405:
  112. Toast.info('本站仅作演示之用,无服务端!');
  113. break;
  114. default:
  115. Toast.error('错误:' + error.message);
  116. }
  117. return;
  118. }
  119. Toast.error('错误:' + error.message);
  120. } else {
  121. Toast.error('错误:' + error);
  122. }
  123. }
  124. export function showWarning(message) {
  125. Toast.warning(message);
  126. }
  127. export function showSuccess(message) {
  128. Toast.success(message);
  129. }
  130. export function showInfo(message) {
  131. Toast.info(message);
  132. }
  133. export function showNotice(message, isHTML = false) {
  134. if (isHTML) {
  135. toast(<HTMLToastContent htmlContent={message} />, showNoticeOptions);
  136. } else {
  137. Toast.info(message);
  138. }
  139. }
  140. export function openPage(url) {
  141. window.open(url);
  142. }
  143. export function removeTrailingSlash(url) {
  144. if (!url) return '';
  145. if (url.endsWith('/')) {
  146. return url.slice(0, -1);
  147. } else {
  148. return url;
  149. }
  150. }
  151. export function getTodayStartTimestamp() {
  152. var now = new Date();
  153. now.setHours(0, 0, 0, 0);
  154. return Math.floor(now.getTime() / 1000);
  155. }
  156. export function timestamp2string(timestamp) {
  157. let date = new Date(timestamp * 1000);
  158. let year = date.getFullYear().toString();
  159. let month = (date.getMonth() + 1).toString();
  160. let day = date.getDate().toString();
  161. let hour = date.getHours().toString();
  162. let minute = date.getMinutes().toString();
  163. let second = date.getSeconds().toString();
  164. if (month.length === 1) {
  165. month = '0' + month;
  166. }
  167. if (day.length === 1) {
  168. day = '0' + day;
  169. }
  170. if (hour.length === 1) {
  171. hour = '0' + hour;
  172. }
  173. if (minute.length === 1) {
  174. minute = '0' + minute;
  175. }
  176. if (second.length === 1) {
  177. second = '0' + second;
  178. }
  179. return (
  180. year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second
  181. );
  182. }
  183. export function timestamp2string1(timestamp, dataExportDefaultTime = 'hour') {
  184. let date = new Date(timestamp * 1000);
  185. // let year = date.getFullYear().toString();
  186. let month = (date.getMonth() + 1).toString();
  187. let day = date.getDate().toString();
  188. let hour = date.getHours().toString();
  189. if (day === '24') {
  190. console.log('timestamp', timestamp);
  191. }
  192. if (month.length === 1) {
  193. month = '0' + month;
  194. }
  195. if (day.length === 1) {
  196. day = '0' + day;
  197. }
  198. if (hour.length === 1) {
  199. hour = '0' + hour;
  200. }
  201. let str = month + '-' + day;
  202. if (dataExportDefaultTime === 'hour') {
  203. str += ' ' + hour + ':00';
  204. } else if (dataExportDefaultTime === 'week') {
  205. let nextWeek = new Date(timestamp * 1000 + 6 * 24 * 60 * 60 * 1000);
  206. let nextMonth = (nextWeek.getMonth() + 1).toString();
  207. let nextDay = nextWeek.getDate().toString();
  208. if (nextMonth.length === 1) {
  209. nextMonth = '0' + nextMonth;
  210. }
  211. if (nextDay.length === 1) {
  212. nextDay = '0' + nextDay;
  213. }
  214. str += ' - ' + nextMonth + '-' + nextDay;
  215. }
  216. return str;
  217. }
  218. export function downloadTextAsFile(text, filename) {
  219. let blob = new Blob([text], { type: 'text/plain;charset=utf-8' });
  220. let url = URL.createObjectURL(blob);
  221. let a = document.createElement('a');
  222. a.href = url;
  223. a.download = filename;
  224. a.click();
  225. }
  226. export const verifyJSON = (str) => {
  227. try {
  228. JSON.parse(str);
  229. } catch (e) {
  230. return false;
  231. }
  232. return true;
  233. };
  234. export function verifyJSONPromise(value) {
  235. try {
  236. JSON.parse(value);
  237. return Promise.resolve();
  238. } catch (e) {
  239. return Promise.reject('不是合法的 JSON 字符串');
  240. }
  241. }
  242. export function shouldShowPrompt(id) {
  243. let prompt = localStorage.getItem(`prompt-${id}`);
  244. return !prompt;
  245. }
  246. export function setPromptShown(id) {
  247. localStorage.setItem(`prompt-${id}`, 'true');
  248. }
  249. /**
  250. * 比较两个对象的属性,找出有变化的属性,并返回包含变化属性信息的数组
  251. * @param {Object} oldObject - 旧对象
  252. * @param {Object} newObject - 新对象
  253. * @return {Array} 包含变化属性信息的数组,每个元素是一个对象,包含 key, oldValue 和 newValue
  254. */
  255. export function compareObjects(oldObject, newObject) {
  256. const changedProperties = [];
  257. // 比较两个对象的属性
  258. for (const key in oldObject) {
  259. if (oldObject.hasOwnProperty(key) && newObject.hasOwnProperty(key)) {
  260. if (oldObject[key] !== newObject[key]) {
  261. changedProperties.push({
  262. key: key,
  263. oldValue: oldObject[key],
  264. newValue: newObject[key],
  265. });
  266. }
  267. }
  268. }
  269. return changedProperties;
  270. }
  271. // playground message
  272. // 生成唯一ID
  273. let messageId = 4;
  274. export const generateMessageId = () => `${messageId++}`;
  275. // 提取消息中的文本内容
  276. export const getTextContent = (message) => {
  277. if (!message || !message.content) return '';
  278. if (Array.isArray(message.content)) {
  279. const textContent = message.content.find(item => item.type === 'text');
  280. return textContent?.text || '';
  281. }
  282. return typeof message.content === 'string' ? message.content : '';
  283. };
  284. // 处理 think 标签
  285. export const processThinkTags = (content, reasoningContent = '') => {
  286. if (!content || !content.includes('<think>')) {
  287. return { content, reasoningContent };
  288. }
  289. const thoughts = [];
  290. const replyParts = [];
  291. let lastIndex = 0;
  292. let match;
  293. THINK_TAG_REGEX.lastIndex = 0;
  294. while ((match = THINK_TAG_REGEX.exec(content)) !== null) {
  295. replyParts.push(content.substring(lastIndex, match.index));
  296. thoughts.push(match[1]);
  297. lastIndex = match.index + match[0].length;
  298. }
  299. replyParts.push(content.substring(lastIndex));
  300. const processedContent = replyParts.join('').replace(/<\/?think>/g, '').trim();
  301. const thoughtsStr = thoughts.join('\n\n---\n\n');
  302. const processedReasoningContent = reasoningContent && thoughtsStr
  303. ? `${reasoningContent}\n\n---\n\n${thoughtsStr}`
  304. : reasoningContent || thoughtsStr;
  305. return {
  306. content: processedContent,
  307. reasoningContent: processedReasoningContent
  308. };
  309. };
  310. // 处理未完成的 think 标签
  311. export const processIncompleteThinkTags = (content, reasoningContent = '') => {
  312. if (!content) return { content: '', reasoningContent };
  313. const lastOpenThinkIndex = content.lastIndexOf('<think>');
  314. if (lastOpenThinkIndex === -1) {
  315. return processThinkTags(content, reasoningContent);
  316. }
  317. const fragmentAfterLastOpen = content.substring(lastOpenThinkIndex);
  318. if (!fragmentAfterLastOpen.includes('</think>')) {
  319. const unclosedThought = fragmentAfterLastOpen.substring('<think>'.length).trim();
  320. const cleanContent = content.substring(0, lastOpenThinkIndex);
  321. const processedReasoningContent = unclosedThought
  322. ? reasoningContent ? `${reasoningContent}\n\n---\n\n${unclosedThought}` : unclosedThought
  323. : reasoningContent;
  324. return processThinkTags(cleanContent, processedReasoningContent);
  325. }
  326. return processThinkTags(content, reasoningContent);
  327. };
  328. // 构建消息内容(包含图片)
  329. export const buildMessageContent = (textContent, imageUrls = [], imageEnabled = false) => {
  330. if (!textContent && (!imageUrls || imageUrls.length === 0)) {
  331. return '';
  332. }
  333. const validImageUrls = imageUrls.filter(url => url && url.trim() !== '');
  334. if (imageEnabled && validImageUrls.length > 0) {
  335. return [
  336. { type: 'text', text: textContent || '' },
  337. ...validImageUrls.map(url => ({
  338. type: 'image_url',
  339. image_url: { url: url.trim() }
  340. }))
  341. ];
  342. }
  343. return textContent || '';
  344. };
  345. // 创建新消息
  346. export const createMessage = (role, content, options = {}) => ({
  347. role,
  348. content,
  349. createAt: Date.now(),
  350. id: generateMessageId(),
  351. ...options
  352. });
  353. // 创建加载中的助手消息
  354. export const createLoadingAssistantMessage = () => createMessage(
  355. MESSAGE_ROLES.ASSISTANT,
  356. '',
  357. {
  358. reasoningContent: '',
  359. isReasoningExpanded: true,
  360. isThinkingComplete: false,
  361. hasAutoCollapsed: false,
  362. status: 'loading'
  363. }
  364. );
  365. // 检查消息是否包含图片
  366. export const hasImageContent = (message) => {
  367. return message &&
  368. Array.isArray(message.content) &&
  369. message.content.some(item => item.type === 'image_url');
  370. };
  371. // 格式化消息用于API请求
  372. export const formatMessageForAPI = (message) => {
  373. if (!message) return null;
  374. return {
  375. role: message.role,
  376. content: message.content
  377. };
  378. };
  379. // 验证消息是否有效
  380. export const isValidMessage = (message) => {
  381. return message &&
  382. message.role &&
  383. (message.content || message.content === '');
  384. };
  385. // 获取最后一条用户消息
  386. export const getLastUserMessage = (messages) => {
  387. if (!Array.isArray(messages)) return null;
  388. for (let i = messages.length - 1; i >= 0; i--) {
  389. if (messages[i].role === MESSAGE_ROLES.USER) {
  390. return messages[i];
  391. }
  392. }
  393. return null;
  394. };
  395. // 获取最后一条助手消息
  396. export const getLastAssistantMessage = (messages) => {
  397. if (!Array.isArray(messages)) return null;
  398. for (let i = messages.length - 1; i >= 0; i--) {
  399. if (messages[i].role === MESSAGE_ROLES.ASSISTANT) {
  400. return messages[i];
  401. }
  402. }
  403. return null;
  404. };
  405. // 计算相对时间(几天前、几小时前等)
  406. export const getRelativeTime = (publishDate) => {
  407. if (!publishDate) return '';
  408. const now = new Date();
  409. const pubDate = new Date(publishDate);
  410. // 如果日期无效,返回原始字符串
  411. if (isNaN(pubDate.getTime())) return publishDate;
  412. const diffMs = now.getTime() - pubDate.getTime();
  413. const diffSeconds = Math.floor(diffMs / 1000);
  414. const diffMinutes = Math.floor(diffSeconds / 60);
  415. const diffHours = Math.floor(diffMinutes / 60);
  416. const diffDays = Math.floor(diffHours / 24);
  417. const diffWeeks = Math.floor(diffDays / 7);
  418. const diffMonths = Math.floor(diffDays / 30);
  419. const diffYears = Math.floor(diffDays / 365);
  420. // 如果是未来时间,显示具体日期
  421. if (diffMs < 0) {
  422. return formatDateString(pubDate);
  423. }
  424. // 根据时间差返回相应的描述
  425. if (diffSeconds < 60) {
  426. return '刚刚';
  427. } else if (diffMinutes < 60) {
  428. return `${diffMinutes} 分钟前`;
  429. } else if (diffHours < 24) {
  430. return `${diffHours} 小时前`;
  431. } else if (diffDays < 7) {
  432. return `${diffDays} 天前`;
  433. } else if (diffWeeks < 4) {
  434. return `${diffWeeks} 周前`;
  435. } else if (diffMonths < 12) {
  436. return `${diffMonths} 个月前`;
  437. } else if (diffYears < 2) {
  438. return '1 年前';
  439. } else {
  440. // 超过2年显示具体日期
  441. return formatDateString(pubDate);
  442. }
  443. };
  444. // 格式化日期字符串
  445. export const formatDateString = (date) => {
  446. const year = date.getFullYear();
  447. const month = String(date.getMonth() + 1).padStart(2, '0');
  448. const day = String(date.getDate()).padStart(2, '0');
  449. return `${year}-${month}-${day}`;
  450. };
  451. // 格式化日期时间字符串(包含时间)
  452. export const formatDateTimeString = (date) => {
  453. const year = date.getFullYear();
  454. const month = String(date.getMonth() + 1).padStart(2, '0');
  455. const day = String(date.getDate()).padStart(2, '0');
  456. const hours = String(date.getHours()).padStart(2, '0');
  457. const minutes = String(date.getMinutes()).padStart(2, '0');
  458. return `${year}-${month}-${day} ${hours}:${minutes}`;
  459. };
  460. function readTableCompactModes() {
  461. try {
  462. const json = localStorage.getItem(TABLE_COMPACT_MODES_KEY);
  463. return json ? JSON.parse(json) : {};
  464. } catch {
  465. return {};
  466. }
  467. }
  468. function writeTableCompactModes(modes) {
  469. try {
  470. localStorage.setItem(TABLE_COMPACT_MODES_KEY, JSON.stringify(modes));
  471. } catch {
  472. // ignore
  473. }
  474. }
  475. export function getTableCompactMode(tableKey = 'global') {
  476. const modes = readTableCompactModes();
  477. return !!modes[tableKey];
  478. }
  479. export function setTableCompactMode(compact, tableKey = 'global') {
  480. const modes = readTableCompactModes();
  481. modes[tableKey] = compact;
  482. writeTableCompactModes(modes);
  483. }
  484. // -------------------------------
  485. // Select 组件统一过滤逻辑
  486. // 使用方式: <Select filter={selectFilter} ... />
  487. // 统一的 Select 搜索过滤逻辑 -- 支持同时匹配 option.value 与 option.label
  488. export const selectFilter = (input, option) => {
  489. if (!input) return true;
  490. const keyword = input.trim().toLowerCase();
  491. const valueText = (option?.value ?? '').toString().toLowerCase();
  492. const labelText = (option?.label ?? '').toString().toLowerCase();
  493. return valueText.includes(keyword) || labelText.includes(keyword);
  494. };
  495. // -------------------------------
  496. // 模型定价计算工具函数
  497. export const calculateModelPrice = ({
  498. record,
  499. selectedGroup,
  500. groupRatio,
  501. tokenUnit,
  502. displayPrice,
  503. currency,
  504. precision = 4,
  505. }) => {
  506. // 1. 选择实际使用的分组
  507. let usedGroup = selectedGroup;
  508. let usedGroupRatio = groupRatio[selectedGroup];
  509. if (selectedGroup === 'all' || usedGroupRatio === undefined) {
  510. // 在模型可用分组中选择倍率最小的分组,若无则使用 1
  511. let minRatio = Number.POSITIVE_INFINITY;
  512. if (Array.isArray(record.enable_groups) && record.enable_groups.length > 0) {
  513. record.enable_groups.forEach((g) => {
  514. const r = groupRatio[g];
  515. if (r !== undefined && r < minRatio) {
  516. minRatio = r;
  517. usedGroup = g;
  518. usedGroupRatio = r;
  519. }
  520. });
  521. }
  522. // 如果找不到合适分组倍率,回退为 1
  523. if (usedGroupRatio === undefined) {
  524. usedGroupRatio = 1;
  525. }
  526. }
  527. // 2. 根据计费类型计算价格
  528. if (record.quota_type === 0) {
  529. // 按量计费
  530. const inputRatioPriceUSD = record.model_ratio * 2 * usedGroupRatio;
  531. const completionRatioPriceUSD = record.model_ratio * record.completion_ratio * 2 * usedGroupRatio;
  532. const unitDivisor = tokenUnit === 'K' ? 1000 : 1;
  533. const unitLabel = tokenUnit === 'K' ? 'K' : 'M';
  534. const rawDisplayInput = displayPrice(inputRatioPriceUSD);
  535. const rawDisplayCompletion = displayPrice(completionRatioPriceUSD);
  536. const numInput = parseFloat(rawDisplayInput.replace(/[^0-9.]/g, '')) / unitDivisor;
  537. const numCompletion = parseFloat(rawDisplayCompletion.replace(/[^0-9.]/g, '')) / unitDivisor;
  538. return {
  539. inputPrice: `${currency === 'CNY' ? '¥' : '$'}${numInput.toFixed(precision)}`,
  540. completionPrice: `${currency === 'CNY' ? '¥' : '$'}${numCompletion.toFixed(precision)}`,
  541. unitLabel,
  542. isPerToken: true,
  543. usedGroup,
  544. usedGroupRatio,
  545. };
  546. }
  547. // 按次计费
  548. const priceUSD = parseFloat(record.model_price) * usedGroupRatio;
  549. const displayVal = displayPrice(priceUSD);
  550. return {
  551. price: displayVal,
  552. isPerToken: false,
  553. usedGroup,
  554. usedGroupRatio,
  555. };
  556. };
  557. // 格式化价格信息(用于卡片视图)
  558. export const formatPriceInfo = (priceData, t) => {
  559. const groupTag = priceData.usedGroup ? (
  560. <span style={{ color: 'var(--semi-color-text-1)' }} className="ml-1 text-xs">
  561. {t('分组')} {priceData.usedGroup}
  562. </span>
  563. ) : null;
  564. if (priceData.isPerToken) {
  565. return (
  566. <>
  567. <span style={{ color: 'var(--semi-color-text-1)' }}>
  568. {t('提示')} {priceData.inputPrice}/{priceData.unitLabel}
  569. </span>
  570. <span style={{ color: 'var(--semi-color-text-1)' }}>
  571. {t('补全')} {priceData.completionPrice}/{priceData.unitLabel}
  572. </span>
  573. {groupTag}
  574. </>
  575. );
  576. }
  577. return (
  578. <>
  579. <span style={{ color: 'var(--semi-color-text-1)' }}>
  580. {t('模型价格')} {priceData.price}
  581. </span>
  582. {groupTag}
  583. </>
  584. );
  585. };
  586. // -------------------------------
  587. // CardPro 分页配置函数
  588. // 用于创建 CardPro 的 paginationArea 配置
  589. export const createCardProPagination = ({
  590. currentPage,
  591. pageSize,
  592. total,
  593. onPageChange,
  594. onPageSizeChange,
  595. isMobile = false,
  596. pageSizeOpts = [10, 20, 50, 100],
  597. showSizeChanger = true,
  598. t = (key) => key,
  599. }) => {
  600. if (!total || total <= 0) return null;
  601. const start = (currentPage - 1) * pageSize + 1;
  602. const end = Math.min(currentPage * pageSize, total);
  603. const totalText = `${t('显示第')} ${start} ${t('条 - 第')} ${end} ${t('条,共')} ${total} ${t('条')}`;
  604. return (
  605. <>
  606. {/* 桌面端左侧总数信息 */}
  607. {!isMobile && (
  608. <span
  609. className="text-sm select-none"
  610. style={{ color: 'var(--semi-color-text-2)' }}
  611. >
  612. {totalText}
  613. </span>
  614. )}
  615. {/* 右侧分页控件 */}
  616. <Pagination
  617. currentPage={currentPage}
  618. pageSize={pageSize}
  619. total={total}
  620. pageSizeOpts={pageSizeOpts}
  621. showSizeChanger={showSizeChanger}
  622. onPageSizeChange={onPageSizeChange}
  623. onPageChange={onPageChange}
  624. size={isMobile ? "small" : "default"}
  625. showQuickJumper={isMobile}
  626. showTotal
  627. />
  628. </>
  629. );
  630. };
  631. // 模型定价筛选条件默认值
  632. const DEFAULT_PRICING_FILTERS = {
  633. search: '',
  634. showWithRecharge: false,
  635. currency: 'USD',
  636. showRatio: false,
  637. viewMode: 'card',
  638. tokenUnit: 'M',
  639. filterGroup: 'all',
  640. filterQuotaType: 'all',
  641. filterEndpointType: 'all',
  642. filterVendor: 'all',
  643. filterTag: 'all',
  644. currentPage: 1,
  645. };
  646. // 重置模型定价筛选条件
  647. export const resetPricingFilters = ({
  648. handleChange,
  649. setShowWithRecharge,
  650. setCurrency,
  651. setShowRatio,
  652. setViewMode,
  653. setFilterGroup,
  654. setFilterQuotaType,
  655. setFilterEndpointType,
  656. setFilterVendor,
  657. setFilterTag,
  658. setCurrentPage,
  659. setTokenUnit,
  660. }) => {
  661. handleChange?.(DEFAULT_PRICING_FILTERS.search);
  662. setShowWithRecharge?.(DEFAULT_PRICING_FILTERS.showWithRecharge);
  663. setCurrency?.(DEFAULT_PRICING_FILTERS.currency);
  664. setShowRatio?.(DEFAULT_PRICING_FILTERS.showRatio);
  665. setViewMode?.(DEFAULT_PRICING_FILTERS.viewMode);
  666. setTokenUnit?.(DEFAULT_PRICING_FILTERS.tokenUnit);
  667. setFilterGroup?.(DEFAULT_PRICING_FILTERS.filterGroup);
  668. setFilterQuotaType?.(DEFAULT_PRICING_FILTERS.filterQuotaType);
  669. setFilterEndpointType?.(DEFAULT_PRICING_FILTERS.filterEndpointType);
  670. setFilterVendor?.(DEFAULT_PRICING_FILTERS.filterVendor);
  671. setFilterTag?.(DEFAULT_PRICING_FILTERS.filterTag);
  672. setCurrentPage?.(DEFAULT_PRICING_FILTERS.currentPage);
  673. };