index.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. import { apiInterceptors, collectApp, getAppList, newDialogue, recommendApps, unCollectApp } from '@/client/api';
  2. import { SearchOutlined, StarFilled, StarOutlined } from '@ant-design/icons';
  3. import { useRequest } from 'ahooks';
  4. import type { SegmentedProps } from 'antd';
  5. import { Avatar, Button, ConfigProvider, Input, Segmented, Spin, message } from 'antd';
  6. import cls from 'classnames';
  7. import { NextPage } from 'next';
  8. import { useRouter } from 'next/router';
  9. import { useContext, useEffect, useState } from 'react';
  10. import { useTranslation } from 'react-i18next';
  11. import type { GridCellRenderer, Index, IndexRange } from 'react-virtualized';
  12. import { AutoSizer, Grid, InfiniteLoader } from 'react-virtualized';
  13. import { ChatContext } from '@/app/chat-context';
  14. import IconFont from '@/new-components/common/Icon';
  15. import BlurredCard from '@/new-components/common/blurredCard';
  16. import { AppListResponse } from '@/types/app';
  17. import moment from 'moment';
  18. import { UserInfoResponse } from '@/types/userinfo';
  19. import { STORAGE_USERINFO_KEY } from '../utils/constants';
  20. const Playground: NextPage = () => {
  21. const router = useRouter();
  22. const { t } = useTranslation();
  23. const { setAgent, setCurrentDialogInfo, model } = useContext(ChatContext);
  24. const [activeKey, setActiveKey] = useState<string>('all');
  25. const [apps, setApps] = useState<any>({
  26. app_list: [],
  27. total_count: 0,
  28. });
  29. const items: SegmentedProps['options'] = [
  30. {
  31. value: 'recommend',
  32. label: t('recommend_apps'),
  33. },
  34. {
  35. value: 'all',
  36. label: t('all_apps'),
  37. },
  38. {
  39. value: 'collected',
  40. label: t('my_collected_apps'),
  41. },
  42. ];
  43. const getAppListWithParams = (params: Record<string, string>) =>
  44. apiInterceptors(
  45. getAppList({
  46. page_no: '1',
  47. page_size: '12',
  48. ...params,
  49. }),
  50. );
  51. const getHotAppList = (params: Record<string, string>) =>
  52. apiInterceptors(
  53. recommendApps({
  54. page_no: '1',
  55. page_size: '12',
  56. ...params,
  57. }),
  58. );
  59. // 获取应用列表
  60. const { run: getAppListFn, loading } = useRequest(
  61. async (app_name = '', page_no = '1', page_size = '12') => {
  62. switch (activeKey) {
  63. case 'recommend':
  64. return await getHotAppList({
  65. ...{ page_no, page_size },
  66. });
  67. case 'collected':
  68. return await getAppListWithParams({
  69. is_collected: 'true',
  70. ignore_user: 'true',
  71. published: 'true',
  72. need_owner_info: 'true',
  73. ...{ app_name, page_no, page_size },
  74. });
  75. case 'all':
  76. return await getAppListWithParams({
  77. ignore_user: 'true',
  78. published: 'true',
  79. need_owner_info: 'true',
  80. ...{ app_name, page_no, page_size },
  81. });
  82. default:
  83. return [];
  84. }
  85. },
  86. {
  87. manual: true,
  88. onSuccess: (res: [any, [] | AppListResponse]) => {
  89. const [_error, data] = res;
  90. if (activeKey === 'recommend') {
  91. if (Array.isArray(data)) {
  92. return setApps({
  93. app_list: data,
  94. total_count: data.length,
  95. });
  96. }
  97. } else {
  98. if ('app_list' in data) {
  99. const code = data?.app_list?.[0]?.app_code;
  100. const index = code ? apps.app_list.findIndex((item: any) => item.app_code === code) : -1;
  101. if (index !== -1) {
  102. const finallyIndex = Math.floor(index / 12) * 12;
  103. setApps(
  104. {
  105. app_list: apps.app_list.toSpliced(finallyIndex, 12, ...data.app_list) || [],
  106. total_count: data?.total_count || 0,
  107. } || {},
  108. );
  109. } else {
  110. console.log('concat');
  111. setApps(
  112. {
  113. app_list: apps.app_list.concat(data?.app_list) || [],
  114. total_count: data?.total_count || 0,
  115. } || {},
  116. );
  117. }
  118. }
  119. }
  120. },
  121. debounceWait: 500,
  122. },
  123. );
  124. const onSearch = async (e: any) => {
  125. setApps({
  126. app_list: [],
  127. total_count: 0,
  128. });
  129. getAppListFn(e.target.value);
  130. };
  131. const collect = async (data: Record<string, any>) => {
  132. const [error] = await apiInterceptors(
  133. data.is_collected === 'true'
  134. ? unCollectApp({ app_code: data.app_code })
  135. : collectApp({ app_code: data.app_code }),
  136. );
  137. const index = apps.app_list.findIndex((item: any) => item.app_code === data.app_code);
  138. if (error) return;
  139. if (data.is_collected === 'true') {
  140. message.success(t('cancel_success'));
  141. } else {
  142. message.success(t('collect_success'));
  143. }
  144. getAppListFn('', (Math.floor(index / 12) + 1).toString());
  145. };
  146. const columnCount = 3;
  147. function isRowLoaded({ index }: Index) {
  148. return !!apps.app_list[index]; // 检查给定的索引是否已经加载
  149. }
  150. function loadMoreRows({ startIndex, stopIndex }: IndexRange) {
  151. const pageSize = 12;
  152. const currentPage = Math.ceil(startIndex / pageSize) + 1; // 计算当前页数
  153. console.log(startIndex, stopIndex, currentPage);
  154. // 这里应该是一个从服务器获取更多数据的异步操作
  155. // 例如,你可能会调用 API 并返回一个 Promise
  156. return getAppListFn('', currentPage.toString());
  157. }
  158. const cellRenderer: GridCellRenderer = ({ columnIndex, key, rowIndex, style }) => {
  159. // 计算数组中的索引
  160. const index = rowIndex * columnCount + columnIndex;
  161. if (!isRowLoaded({ index })) return null;
  162. const item = apps.app_list[index];
  163. return (
  164. <div key={key} style={style} >
  165. <BlurredCard
  166. key={item.app_code}
  167. name={item.app_name}
  168. description={item.app_describe}
  169. className='w-11/12 hover:bg-slate-200'
  170. RightTop={
  171. item.is_collected === 'true' ? (
  172. <StarFilled
  173. onClick={() => collect(item)}
  174. style={{
  175. height: '21px',
  176. cursor: 'pointer',
  177. color: '#f9c533',
  178. }}
  179. />
  180. ) : (
  181. <StarOutlined
  182. onClick={() => collect(item)}
  183. style={{
  184. height: '21px',
  185. cursor: 'pointer',
  186. }}
  187. />
  188. )
  189. }
  190. onClick={async () => {
  191. // 原生应用跳转
  192. if (item.team_mode === 'native_app') {
  193. const { chat_scene = '' } = item.team_context;
  194. const [, res] = await apiInterceptors(newDialogue({ chat_mode: chat_scene }));
  195. if (res) {
  196. setCurrentDialogInfo?.({
  197. chat_scene: res.chat_mode,
  198. app_code: item.app_code,
  199. });
  200. localStorage.setItem(
  201. 'cur_dialog_info',
  202. JSON.stringify({
  203. chat_scene: res.chat_mode,
  204. app_code: item.app_code,
  205. }),
  206. );
  207. router.push(`/chat?scene=${chat_scene}&id=${res.conv_uid}${model ? `&model=${model}` : ''}`);
  208. }
  209. } else {
  210. // 自定义应用
  211. const [, res] = await apiInterceptors(newDialogue({ chat_mode: 'chat_agent' }));
  212. if (res) {
  213. setCurrentDialogInfo?.({
  214. chat_scene: res.chat_mode,
  215. app_code: item.app_code,
  216. });
  217. localStorage.setItem(
  218. 'cur_dialog_info',
  219. JSON.stringify({
  220. chat_scene: res.chat_mode,
  221. app_code: item.app_code,
  222. }),
  223. );
  224. setAgent?.(item.app_code);
  225. router.push(`/chat/?scene=chat_agent&id=${res.conv_uid}${model ? `&model=${model}` : ''}`);
  226. }
  227. }
  228. }}
  229. LeftBottom={
  230. <div className='flex gap-8 items-center text-[#878c93] text-sm dark:text-stone-200'
  231. >
  232. {item.owner_name && (
  233. <div className='flex gap-1 items-center'>
  234. <Avatar
  235. src={item?.owner_avatar_url}
  236. className='bg-gradient-to-tr from-[#31afff] to-[#1677ff] cursor-pointer'
  237. >
  238. {item.owner_name}
  239. </Avatar>
  240. <span>{item.owner_name}</span>
  241. </div>
  242. )}
  243. {activeKey === 'recommend' ? (
  244. <div className='flex items-start gap-1'>
  245. <IconFont type='icon-hot' className='text-lg' />
  246. <span className='text-[#878c93]'>{item.hot_value}</span>
  247. </div>
  248. ) : (
  249. <div>{t('update') + '于' + moment(item?.updated_at).fromNow() + ' '}</div>
  250. )}
  251. </div>
  252. }
  253. scene={item?.team_context?.chat_scene || 'chat_agent'}
  254. />
  255. </div>
  256. );
  257. };
  258. useEffect(() => {
  259. // setPageNo('1');
  260. setApps({
  261. app_list: [],
  262. total_count: 0,
  263. });
  264. }, [activeKey]);
  265. useEffect(() => {
  266. getAppListFn();
  267. }, [activeKey, getAppListFn]);
  268. const [userInfo, setUserInfo] = useState<UserInfoResponse>();
  269. useEffect(() => {
  270. try {
  271. const user = JSON.parse(localStorage.getItem(STORAGE_USERINFO_KEY) ?? '');
  272. setUserInfo(user);
  273. } catch {
  274. return undefined;
  275. }
  276. }, []);
  277. return (
  278. <div
  279. className='flex flex-col h-full w-full backdrop-filter backdrop-blur bg-[#fff] bg-gradient-light px-2 '
  280. id='home-container'
  281. >
  282. <div className='mt-2 rounded-[10px] flex h-16 justify-between items-center px-2'>
  283. <Input
  284. variant='filled'
  285. prefix={<SearchOutlined />}
  286. placeholder={t('please_enter_the_keywords')}
  287. onChange={onSearch}
  288. onPressEnter={onSearch}
  289. allowClear
  290. className={cls(
  291. 'w-[400px] h-[40px] border-1 border-[#d1d1d1] backdrop-filter backdrop-blur-lg dark:border-[#6f7f95] dark:bg-[#6f7f95] dark:bg-opacity-60',
  292. )}
  293. />
  294. <span className='flex gap-2 items-center'>
  295. <Avatar className='bg-gradient-to-tr from-[#31afff] to-[#1677ff] cursor-pointer'>
  296. </Avatar>
  297. <span
  298. >
  299. admin
  300. </span>
  301. </span>
  302. </div>
  303. <ConfigProvider
  304. theme={{
  305. components: {
  306. Button: {
  307. defaultBorderColor: 'white',
  308. },
  309. Segmented: {
  310. itemSelectedBg: '#2867f5',
  311. itemSelectedColor: 'white',
  312. },
  313. },
  314. }}
  315. >
  316. {/* Apps list */}
  317. <div
  318. className='rounded-[10px] flex flex-col h-full mt-4 relative bg-slate-200 p-4 border-1 mb-2'
  319. // style={{
  320. // paddingBottom: apps.total_count > 12 ? 45 : 20,
  321. // }}
  322. >
  323. <div className='flex justify-between items-center'>
  324. <div className='flex items-center gap-4'>
  325. <Segmented
  326. className='h-10 backdrop-filter backdrop-blur-lg bg-white bg-opacity-30 border border-white rounded-lg shadow p-1 dark:border-[#6f7f95] dark:bg-[#6f7f95] dark:bg-opacity-60'
  327. options={items}
  328. onChange={key => setActiveKey(key as any)}
  329. value={activeKey}
  330. />
  331. </div>
  332. <div className='flex items-center gap-4'
  333. style={{ backgroundColor: '#7288FA!important' }}
  334. >
  335. <Button
  336. className='border-none text-white bg-button-gradient'
  337. onClick={() => {
  338. localStorage.removeItem('new_app_info');
  339. router.push('/construct/app?openModal=true');
  340. }}
  341. style={{ backgroundColor: '#fff!important'}}
  342. >
  343. 创建应用
  344. </Button>
  345. </div>
  346. </div>
  347. {loading && !apps.app_list.length ? (
  348. <Spin size='large' className='flex items-center justify-center h-full' spinning={loading} />
  349. ) : (
  350. <>
  351. <InfiniteLoader
  352. isRowLoaded={isRowLoaded}
  353. loadMoreRows={loadMoreRows}
  354. rowCount={apps.total_count}
  355. >
  356. {({ onRowsRendered, registerChild }) => (
  357. <AutoSizer>
  358. {({ width, height }) => (
  359. <Grid
  360. ref={registerChild}
  361. onSectionRendered={({ rowStartIndex, rowStopIndex }) => {
  362. const startIndex = rowStartIndex * columnCount;
  363. const stopIndex = rowStopIndex * columnCount + (columnCount - 1);
  364. onRowsRendered({
  365. startIndex,
  366. stopIndex,
  367. });
  368. }}
  369. cellRenderer={cellRenderer}
  370. columnWidth={width / 4}
  371. columnCount={4}
  372. height={height}
  373. rowHeight={200}
  374. rowCount={apps.total_count}
  375. width={width}
  376. />
  377. )}
  378. </AutoSizer>
  379. )}
  380. </InfiniteLoader>
  381. {loading && apps.app_list.length && (
  382. <Spin className='flex items-end justify-center h-full' spinning={loading} />
  383. )}
  384. </>
  385. )}
  386. {/* <TabContent apps={apps?.app_list || []} loading={loading} refresh={refresh} /> */}
  387. </div>
  388. </ConfigProvider>
  389. </div>
  390. );
  391. };
  392. export default Playground;