utils.jsx 22 KB

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