This commit is contained in:
676015863@qq.com committed 2026-07-29 11:02:21 +08:00
1 parent 5c809539d5
commit 9eebe059f4
1255 files changed
+90283 -9

No files matched your search

+90
View File
@@ -0,0 +1,90 @@
import { observer } from 'mobx-react';
import styles from './audio.module.less';
import { audios } from '@stores/audios';
import { useReducer, useRef, useState } from 'react';
import { Play, PauseOne } from '@icon-park/react';
import $ from 'jquery';
import { util } from '@utils/index';
import classNames from 'classnames';
export interface IProps {
item: any;
noName?: boolean;
}
function AudioItem(props: IProps) {
const [, forceUpdate] = useReducer(x => x + 1, 0);
const item = props.item;
const ref = useRef();
const [x, setX] = useState(0);
audios.progress;
const isActive = audios.selectedId === item.id;
const [name, ext] = item.name.split('.');
return (
<div
className={classNames(styles.item, styles.audioItem, 'audioSourceItem')}
ref={ref}
onClick={() => {
audios.setProgress(x);
}}
onMouseEnter={(e: any) => {
if (isActive) {
const offset = $(ref.current).offset();
const width = $(ref.current).width();
setX((e.pageX - offset.left) / width);
$(ref.current).on('mousemove', em => {
setX((em.pageX - offset.left) / width);
});
}
}}
onMouseLeave={e => {
if (isActive) {
$(ref.current).off('mousemove');
setX(0);
}
}}
>
<a
className={styles.btn}
onClick={e => {
e.stopPropagation();
audios.duration = item.attrs.duration;
if (audios.selectedId === item.id) {
if (!audios.selectedId) {
audios.selectedId = item.id;
audios.audioURL = item.urls.url;
audios.play();
} else {
audios.stop();
}
} else {
audios.pause();
audios.selectedId = item.id;
audios.audioURL = item.urls.url;
audios.play();
}
forceUpdate();
}}
>
{isActive ? (
<PauseOne theme="filled" size="30" fill="#8B20FB" />
) : (
<Play theme="filled" size="30" fill="#8B20FB" />
)}
</a>
<div className={styles.right}>
{!props.noName && (
<span className={styles.name}>
{name.length > 10 ? name.substr(0, 10) + '...' : name}
<em className={styles.ext}>{ext}</em>
</span>
)}
</div>
{isActive && <span className={styles.progress} style={{ width: `${audios.progress * 100}%` }}></span>}
{isActive && !!x && <span className={styles.line} style={{ left: x * 100 + '%' }}></span>}
</div>
);
}
export default observer(AudioItem);
+77
View File
@@ -0,0 +1,77 @@
.audioItem {
position: relative;
width: 100%;
height: 100%;
color: var(--theme-text);
font-size: 12px;
overflow: hidden;
text-align: center;
// display: flex;
// height: 54px;
.right {
position: relative;
z-index: 10;
:global {
.semi-slider-handle {
width: 10px;
height: 10px;
margin-top: 10px;
display: none;
}
.semi-slider-rail {
height: 3px;
}
.semi-slider-track {
height: 3px;
background: rgba(0, 255, 132, 1);
}
}
}
.btn {
display: inline-block;
margin-top: 20px;
margin-bottom: 5px;
position: relative;
z-index: 10;
}
.name,
.time {
display: block;
}
.time {
margin-top: 5px;
opacity: 0.5;
}
.ext {
display: inline-block;
padding: 1px 3px;
margin-left: 5px;
border-radius: 4px;
font-size: 12px;
color: #fff;
background: linear-gradient(30deg, #00e9fa 0%, #007bff 50%, #bb00fa 100%);
}
.progress {
position: absolute;
z-index: 0;
background: linear-gradient(90deg, rgba(0, 0, 0, 0), rgba(0, 255, 132, 0.3));
top: 0;
left: 0;
height: 100%;
width: 0;
}
.line {
width: 1px;
opacity: 0.8;
background-color: var(--theme-text);
position: absolute;
top: 0;
z-index: 30;
height: 100%;
pointer-events: none;
}
}
@@ -0,0 +1,18 @@
import styles from './styles.module.less';
export interface IProps {
title: string;
children?: JSX.Element;
}
function ContentUser(props: IProps) {
return (
<div className={styles.content}>
<div className={styles.title}>
<h1>{props.title}</h1>
</div>
<div className={styles.contents}>{props.children}</div>
</div>
);
}
export default ContentUser;
+3
View File
@@ -0,0 +1,3 @@
import ContentUser from './ContentUser';
export default ContentUser;
@@ -0,0 +1,20 @@
.content {
margin: 30px;
.title {
display: flex;
align-items: center;
justify-content: space-between;
color: var(--theme-text);
h1 {
font-size: 24px;
font-weight: bolder;
align-items: center;
}
}
.contents {
margin-top: 20px;
}
}
+688
View File
@@ -0,0 +1,688 @@
import styles from './content.module.less';
import { Button, Space, Toast, Upload, Pagination, Modal } from '@douyinfe/semi-ui';
import SourceList from './SourceList';
import { observer } from 'mobx-react';
import { layout } from '@stores/layout';
import { useReducer, useState, useRef, useCallback, useEffect, useImperativeHandle, forwardRef } from 'react';
import { userService } from '@server/user.service';
import Folders from './Folders';
import { pubsub } from '@utils/pubsub';
import { util } from '@utils/index';
import _remove from 'lodash/remove';
import { FailPicture, Right, Scissors, Upload as UploadIcon } from '@icon-park/react';
import { Link } from 'react-router-dom';
import SelectedSet from './SelectedSet';
import { user } from '@stores/user';
import { uploadInfo } from '@utils/uploadInfo.es.js';
import { language } from '@language/language';
import { config } from '@config/index';
import VideoSplit from './video-split/VideoSplit';
import PictureSplit from './picture-split/PictureSplit';
import {
isFSApiSupported,
getRootHandle,
getLocalCategoryList,
createLocalCategory,
} from '@services/localStorageService';
export interface IProps {
item: (a: any) => JSX.Element;
itemClassName: string;
itemWidth: number;
type: 'draft' | 'material'; // 类型
title: string | JSX.Element; // 标题
subTitle?: JSX.Element;
getListServer: (n: any) => Promise<[any, boolean]>; // 获取素材的回调
seekItemStatus?: (ids: string[]) => Promise<any>; // seekItemStatus的回调
categoryId: string;
contentHeight?: number; // 内容高度
categoryName: string;
catesCallback: (cates: any[]) => void;
moveCallBack: (cid: string, ids: string[]) => void; // 移动元素的回调
createUserMaterial?: (params: {
category_id?: string; // 直接创建到该分类下面
name: string;
urls: Record<string, any>;
attrs: Record<string, any>;
size?: number;
convert_status?: number;
}) => Promise<[any, boolean]>;
}
export interface UploadItem {
id: string;
status: 'ready' | 'uploadStart' | 'uploading' | 'decoding' | 'uploaded';
progress: number; // 当前进度
type?: string; // 文件类型
name?: string;
size?: number; // 文件大小
thumb?: string; // 缩图
naturalHeight?: number; // 图片真实尺寸
naturalWidth?: number;
duration?: number; // 时长
// 视频相关
rotate?: boolean; // 视频是否旋转了
hasAudioTrack?: boolean; // 视频是否有声音
videoWidth?: number; // 视频真实尺寸
videoHeight?: number;
wave?: string; // 音波json数据
frames?: string; // 1s单位的帧图
}
function Content(props: IProps, ref: any) {
const [, forceUpdate] = useReducer(x => x + 1, 0);
const [cates, setCates] = useState([]);
const [useLocal, setUseLocal] = useState(false);
const timer = useRef(null);
const totalRef = useRef(0);
const [showVideoSplit, setShowVideoSplit] = useState(false);
const [showImageSplit, setShowImageSplit] = useState(false);
const params = useRef({
page: 1,
page_size: 100,
keyword: '',
category_id: props.categoryId || '0',
});
// 使用ref存储items避免轮询时的闭包问题
const itemsRef = useRef<any[] | null>(null);
// 缓存info数据
const cacheInfoData = useRef<Record<string, UploadItem>>({});
// item中convert_status 状态(-1无需处理,0-待处理 1-处理中 2-处理成功 3-处理失败)
// 0,1 编码中
// 2 编码成功
// 3 编码失败
// 如果状态是0和1轮训,并且修改item.status.decoding,直到状态是2或3,修改item.status为uploaded或error。
const seekItemStatus = useCallback(
async ids => {
if (!itemsRef.current) {
return;
}
if (!props.seekItemStatus) {
return;
}
if (ids.length === 0) {
forceUpdate();
return;
}
const [res, err] = await props.seekItemStatus(ids);
if (err) {
return Toast.error(err);
}
// 更新itemsRef中的数据
const currentItems = itemsRef.current;
res.forEach(d => {
const item = currentItems.find(item => item.id === d.source_id);
if (item) {
item.convert_status = d.status;
}
});
// 同步更新state
itemsRef.current = [...currentItems];
forceUpdate();
// 继续轮询需要处理的项
const idArr = res
.map(d => {
if ([0, 1].includes(d.status)) {
return d.source_id;
}
return null;
})
.filter(d => d !== null);
if (idArr.length > 0) {
timer.current = setTimeout(() => {
seekItemStatus(idArr);
}, 1000);
} else {
timer.current = null;
}
},
[props.seekItemStatus],
);
// ref暴露getList方法
useImperativeHandle(ref, () => ({
getList,
}));
// 获取素材
const getList = async itemsArr => {
// 清理之前的轮询
if (timer.current) {
clearTimeout(timer.current);
timer.current = null;
}
const { list, total } = await getItems(props.type, params.current, props.getListServer);
totalRef.current = total;
console.log(list, total, 'list.length-------------------------');
// 同步更新ref和state
itemsRef.current = [...list];
forceUpdate();
// 开始轮询状态变化
const pendingIds = list
.map(d => {
if ([0, 1].includes(d.convert_status)) {
return d.id;
}
return null;
})
.filter(d => d !== null);
if (pendingIds.length > 0) {
seekItemStatus(pendingIds);
}
};
// 检测本地存储模式
useEffect(() => {
if (isFSApiSupported()) {
getRootHandle().then(handle => setUseLocal(!!handle));
}
}, []);
// 获取全部分类
const getCategoryList = useCallback(() => {
const t = props.type === 'draft' ? 'project' : 'material';
if (useLocal) {
getLocalCategoryList(t as 'project' | 'material').then(resp => {
const [res, err] = resp;
if (err) {
return Toast.error(err);
} else {
setCates(res.data);
props.catesCallback(res.data);
}
});
} else {
userService.getCategoryList({ type: t, page: 1, page_size: 100 }).then(resp => {
const [res, err] = resp;
if (err) {
return Toast.error(err);
} else {
setCates(res.data);
props.catesCallback(res.data);
}
});
}
}, [useLocal]);
useEffect(() => {
getCategoryList();
getList([]);
return () => {
layout.cancelSelected();
if (timer.current) {
clearTimeout(timer.current);
}
timer.current = null;
};
}, []);
// 显示上传中的信息
const uploadList = Object.values(cacheInfoData.current)
.map(d => {
return {
id: d.id,
name: d.name,
type: d.type,
urls: { thumb: d.thumb },
attrs: {
width: d.naturalWidth || d.videoWidth || 200,
height: d.naturalHeight || d.videoHeight || 180,
},
status: d.status,
progress: d.progress,
};
})
.filter(d => {
return d.status !== 'uploaded';
});
// console.log(layout.openSelectManage, items, cates, 'layout.openSelectManage, items, cates');
return (
<div className={styles.content}>
<div className={styles.title}>
<h1>
{props.title}
<Space className={styles.cates}>
<Link
to={
{
draft: `/workspace/draft/`,
material: `/workspace/material/`,
}[props.type]
}
>
{language.val('common_all')}
</Link>
{props.categoryName ? (
<>
<Right theme="outline" size="20" fill="var(--theme-icon)" />
<span style={{ opacity: 0.5 }}>{props.categoryName}</span>
</>
) : null}
</Space>
</h1>
{layout.openSelectManage && (cates?.length || itemsRef.current?.length) ? (
<SelectedSet
cates={cates}
total={totalRef.current}
items={itemsRef.current}
type={props.type}
moveCallBack={props.moveCallBack}
removeCallBack={(params: [any[]]) => {
const [_items] = params;
itemsRef.current = [..._items];
forceUpdate();
}}
/>
) : null}
<Space>
{props.type === 'material' && (
<>
<Button
icon={<FailPicture theme="outline" size="20" fill="#FFF" />}
size="large"
onClick={() => setShowImageSplit(true)}
>
<span style={{ color: 'var(--theme-text)' }}>图片分割</span>
</Button>
<Button
icon={<Scissors theme="outline" size="20" fill="#FFF" />}
size="large"
onClick={() => setShowVideoSplit(true)}
>
<span style={{ color: 'var(--theme-text)' }}>视频分割</span>
</Button>
</>
)}
{props.type === 'material' && (
<Upload // .aac, .wav, .mp3,
accept=".gif, .png, .jpeg, .jpg, .svg, .mp4, .avi, .mov"
action={'/api/v1/common/upload/form'}
uploadTrigger="auto"
headers={{
Authorization: user.getToken(),
}}
multiple={true}
showUploadList={false}
className={styles.btn1}
beforeUpload={async v => {
console.log(v.file, 'v.file');
const ftype = v.file.fileInstance.type.split('/')[0];
let thumb = ftype === 'image' ? v.file.url : '';
if (ftype === 'image') {
const base64 = (await util.blobURL2Data(v.file.url as any)) as string;
const thumbBase64 = (await util.resizeBase64Image(base64, 300)) as string;
const [res] = await userService.uploadBase64({
content: thumbBase64,
name: v.file.name,
file_type: 'image',
});
thumb = res.storage_path;
}
cacheInfoData.current[v.file.name] = {
id: v.file.uid,
progress: 0,
status: 'ready',
thumb,
type: v.file.fileInstance.type,
size: v.file.fileInstance.size,
name: v.file.name,
};
forceUpdate();
// console.log(
// v.file,
// 'v.file.?????',
// util.getFileTypeByURL('', v.file.name.split('.').pop().toLowerCase()),
// );
// 获取blob url
const info = await uploadInfo.getUploadBeforeData({
url: v.file.url,
type: util.getFileTypeByURL('', v.file.name.split('.').pop().toLowerCase()),
uploadBase64: userService.uploadBase64,
});
Object.assign(cacheInfoData.current[v.file.name], {
...info,
status: 'uploadStart',
progress: 0,
desc: '',
});
forceUpdate();
// 异步执行openaiImageDesc,不阻塞上传业务
if (['video', 'image'].includes(ftype)) {
(async () => {
try {
if (cacheInfoData.current[v.file.name]) {
//@ts-ignore
cacheInfoData.current[v.file.name].descWaiting = true;
}
let base64 = '';
if (ftype === 'video') {
const res = (await uploadInfo.decoderVideoDrawFrameImage({
url: v.file.url,
aspectRatio: info.videoWidth / info.videoHeight,
audioTrack: null,
videoRotation: info.rotate ? 90 : 0,
frameScale: 10,
duration: info.duration,
workerPath: '/assets/worker',
})) as any;
console.log(res, info, 'res--------->');
base64 = await util.blobUrlToBase64(res.url);
// base64 缩小5倍,frameScale刚好是2
const _img = await util.imgLazy(base64);
const base642 = await util.resizeBase64Image(base64, _img.naturalWidth / 5);
// 上传到资源服务器
const [res2] = await userService.uploadBase64({
content: base642,
name: util.randomID() + '.png',
file_type: 'image',
});
console.log(res2, 'res2');
// 更新cacheInfoData
cacheInfoData.current[v.file.name].frames = res2.storage_path;
} else {
base64 = util.reURL(thumb, config.resourcesHost);
}
const [res3] = await userService.openaiImageDesc([
{
role: 'user',
content: [
{
type: 'image_url',
image_url: util.reURL(base64, config.resourcesHost),
},
{
type: 'text',
text:
ftype === 'video'
? '这是一组1秒/帧的视频帧图,请一句话描述一下视频内容:视频展示了...'
: '这是一张图片,请一句话描述一下图片内容',
},
],
},
]);
if (cacheInfoData.current[v.file.name]) {
//@ts-ignore
cacheInfoData.current[v.file.name].desc = res3?.choices?.[0]?.message?.content || '';
// 描述生成完成,更新状态
//@ts-ignore
cacheInfoData.current[v.file.name].descWaiting = false;
forceUpdate();
}
} catch (error) {
console.error('openaiImageDesc执行失败:', error);
// 描述生成失败,更新状态
//@ts-ignore
cacheInfoData.current[v.file.name].descWaiting = false;
}
})();
}
return {
shouldUpload: true,
status: 'success',
};
}}
onProgress={(p, file, all) => {
cacheInfoData.current[file.name].status = 'uploading';
cacheInfoData.current[file.name].progress = p;
forceUpdate();
}}
onSuccess={async (res, file, all) => {
if (res.code !== 0) {
Toast.error(res.message);
cacheInfoData.current[file.name].status = 'uploaded';
forceUpdate();
return;
}
cacheInfoData.current[file.name].status = 'decoding';
forceUpdate();
// 等待描述生成完成
//@ts-ignore
while (cacheInfoData.current[file.name].descWaiting) {
await new Promise(resolve => setTimeout(resolve, 100));
}
const { name, thumb, progress, id, status, ...other } = cacheInfoData.current[file.name];
const attrs = {};
for (let key in other) {
if (key.split('')[0] !== '_') {
attrs[key] = other[key];
}
}
const url = res.data.storage_path;
// 保存到素材库
const [item, err] = await props.createUserMaterial({
category_id: props.categoryId || '0',
name: name,
urls: { url, thumb },
attrs,
convert_status: -1,
});
cacheInfoData.current[file.name].status = 'uploaded';
params.current.page = 1;
getList([]);
}}
onError={(...v) => console.log('error', v)}
>
<Button
iconPosition="left"
theme="solid"
type="primary"
block
icon={<UploadIcon theme="outline" size="20" fill="#FFF" />}
size="large"
>
{language.val('draft_upload_material')}
</Button>
</Upload>
)}
{!props.categoryName && (
<Button
onClick={async () => {
const type = {
draft: 'project',
material: 'material',
}[props.type] as 'project' | 'material';
const name = 'Untitled_' + util.randomID(4);
if (useLocal) {
const [res, err] = await createLocalCategory(type, name);
if (!err) {
getCategoryList();
Toast.success(language.val('common_create_success'));
pubsub.publish('updateFolders');
} else {
Toast.error(err);
}
} else {
const [res, err] = await userService.saveCategory({ type, name });
if (!err) {
getCategoryList();
Toast.success(language.val('common_create_success'));
pubsub.publish('updateFolders');
} else {
Toast.error(err);
}
}
}}
size="large"
theme="solid"
>
{language.val('draft_create_folder')}
</Button>
)}
<Button
disabled={cates?.length || itemsRef.current?.length ? false : true}
onClick={() => {
if (layout.openSelectManage) {
layout.cancelSelected();
} else {
layout.openSelectManage = true;
}
forceUpdate();
}}
size="large"
>
{layout.openSelectManage && (cates?.length || itemsRef.current?.length)
? language.val('draft_cancel')
: language.val('draft_batch_manage')}
</Button>
</Space>
</div>
{props.subTitle ? props.subTitle : null}
{!props.categoryId && (
<Folders
catesCallback={cs => {
setCates(cs);
props.catesCallback(cs);
}}
type={props.type}
/>
)}
<div className={styles.contents} style={{ height: props.contentHeight || 'auto' }}>
<SourceList
itemWidth={props.itemWidth}
item={props.item}
itemClassName={props.itemClassName}
items={[
...uploadList,
...(itemsRef.current || []).map(d => {
console.log(d);
if (d.convert_status === 0 || d.convert_status === 1) {
d.status = 'decoding';
} else if (d.convert_status === 2 || d.convert_status === -1) {
d.status = 'uploaded';
} else if (d.convert_status === 3) {
d.status = 'error';
}
return d;
}),
].map(d => {
return {
...d,
thumb: d.urls?.thumb || d.attrs?.thumb || d.thumb,
width: d.attrs?.width || d.attrs?.naturalWidth || d.attrs?.videoWidth || 200,
height: d.attrs?.height || d.attrs?.naturalHeight || d.attrs?.videoHeight || 180,
};
})}
type={props.type}
/>
</div>
{totalRef.current > 0 && (
<div className={styles.pagination}>
<Pagination
total={totalRef.current}
pageSize={params.current.page_size}
currentPage={params.current.page}
onChange={page => {
params.current.page = page;
getList([]);
window.scrollTo({ top: 0, behavior: 'smooth' });
}}
showSizeChanger={false}
/>
</div>
)}
<Modal
visible={showVideoSplit}
title="视频分割"
footer={null}
onCancel={() => setShowVideoSplit(false)}
onOk={() => setShowVideoSplit(false)}
width={1200}
>
{showVideoSplit && <VideoSplit />}
</Modal>
<Modal
visible={showImageSplit}
title="图片分割"
footer={null}
onCancel={() => setShowImageSplit(false)}
onOk={() => setShowImageSplit(false)}
width={1200}
>
{showImageSplit && <PictureSplit />}
</Modal>
</div>
);
}
/**
* 获取素材的列表Items数据
* @param type
* @param params
* @param items
* @returns
*/
export async function getItems(
type: 'draft' | 'material', // 类型
params: {
page: number;
page_size: number;
keyword: string;
category_id?: string;
project_id?: string;
},
apiServer: (n: any) => Promise<[any, boolean]>,
) {
const [res, err] = await apiServer({ ...params });
if (!err) {
const newData = res.data.map((d: any) => {
const item: any = { ...d, convert_status: d.convert_status ?? -1 };
if (type === 'draft') {
return { ...item, width: 200, height: 180 };
} else if (type === 'material') {
if (item.type === 'audio') {
return { ...item, width: 200, height: 80 };
} else {
return {
...item,
width: item.attrs.width || item.attrs.videoWidth || item.attrs.naturalWidth,
height: item.attrs.height || item.attrs.videoHeight || item.attrs.naturalHeight,
};
}
} else {
throw new Error('类型不支持', type);
}
});
// 分页模式下直接返回新数据,不合并
const list = newData;
return {
list,
total: res.total,
};
} else {
return {
list: [],
total: 0,
};
}
}
//@ts-ignore
export default observer(forwardRef(Content));
+129
View File
@@ -0,0 +1,129 @@
import { observer } from 'mobx-react';
import styles from './folders.module.less';
import { layout } from '@stores/layout';
import { FolderIcon } from './icon';
import { Button, Space, Checkbox, Toast } from '@douyinfe/semi-ui';
import { userService } from '@server/user.service';
import { useCallback, useEffect, useReducer, useRef, useState } from 'react';
import { pubsub } from '@utils/pubsub';
import { Link } from 'react-router-dom';
import classNames from 'classnames';
import { language } from '@language/language';
import {
isFSApiSupported,
getRootHandle,
getLocalCategoryList,
createLocalCategory,
updateLocalCategory,
} from '@services/localStorageService';
export interface IProps {
type: 'draft' | 'material'; // 类型
catesCallback: (cates: any[]) => void;
noCheckbox?: boolean;
onClick?: (item: any) => void;
}
function Folders(props: IProps) {
const [list, setList] = useState([]);
const [, forceUpdate] = useReducer(x => x + 1, 0);
const currentName = useRef<string>();
const getList = useCallback(() => {
const t = props.type === 'draft' ? 'project' : 'material';
getLocalCategoryList(t as 'project' | 'material').then(resp => {
const [res, err] = resp;
if (err) {
return Toast.error(err);
} else {
setList(res.data);
props.catesCallback(res.data);
}
});
}, []);
useEffect(() => {
pubsub.subscribe('updateFolders', () => {
getList();
});
getList();
return () => {
pubsub.unsubscribe('updateFolders');
};
}, []);
const checkboxStyle: any = {};
if (layout.openSelectManage) {
checkboxStyle.display = 'flex';
}
console.log('list', list);
return (
<div className={classNames(styles.folders, 'scroll')}>
{list.map(item => {
return (
<section key={item.id} className={styles.folderItem}>
{props.noCheckbox ? null : (
<Checkbox
style={checkboxStyle}
checked={!!layout.selects.find(d => d.id === item.id)}
onChange={e => {
layout.setSelected(
{
id: item.id,
type: 'folder',
},
e.target.checked,
);
}}
/>
)}
{props.onClick ? (
<a onClick={() => props.onClick(item)}>
<FolderIcon size={60} />
</a>
) : (
<Link
to={
{
draft: `/workspace/draft/${item.id}@${item.name}`,
material: `/workspace/material/${item.id}@${item.name}`,
}[props.type]
}
>
<FolderIcon size={60} />
</Link>
)}
<input
title={language.val('draft_name_input')}
value={item.name}
onFocus={e => {
currentName.current = e.target.value;
}}
onChange={e => {
item.name = e.target.value;
forceUpdate();
}}
onBlur={async e => {
if (item.name === currentName.current) {
return;
}
let [res, err] = await updateLocalCategory(item.id, { name: item.name });
if (!err) {
Toast.success(language.val('draft_name_success'));
}
getList();
}}
/>
</section>
);
})}
</div>
);
}
export default observer(Folders);
+174
View File
@@ -0,0 +1,174 @@
import styles from './content.module.less';
import { server as draftServer } from '@pages/workspace/draft/server';
import { server as materialServer } from '@pages/workspace/material/server';
import { Button, Space, Checkbox, Modal, Toast, Popover } from '@douyinfe/semi-ui';
import { observer } from 'mobx-react';
import { layout } from '@stores/layout';
import { userService } from '@server/user.service';
import { pubsub } from '@utils/pubsub';
import _remove from 'lodash/remove';
import { language, Intl } from '@language/index';
export interface IProps {
items: any[];
total: number;
type: 'draft' | 'material'; // 类型
cates: any[]; // 分类
removeCallBack: (params: [any[]]) => void; // 移除元素的回调
moveCallBack: (cid: string, ids: string[]) => void; // 移动元素的回调
}
// 选中元素的操作
function SelectedSet(props: IProps) {
const { items, cates, total, removeCallBack } = props;
// console.log(
// layout.selects.length,
// items,
// cates,
// (items || []).length + (cates || []).length,
// "layout.selects, items, cates"
// );
return (
<Space className={styles.selectedManager}>
<Checkbox
onChange={e => {
if (e.target.checked) {
//@ts-ignore
layout.selects = [
...(items || []).map(item => {
return {
type: 'item',
id: item.id,
};
}),
];
} else {
layout.selects = [];
}
}}
indeterminate={layout.selects.length > 0 && layout.selects.length < (items || []).length + (cates || []).length}
checked={layout.selects.length === (items || []).length + (cates.filter(d => d.type === 'folder') || []).length}
>
{language.val('common_all')}
</Checkbox>
<span>
<Intl name="draft_has_selected" data={{ num: layout.selects.length }} />
</span>
<Button
disabled={layout.selects.length === 0}
onClick={() => {
Modal.confirm({
title: language.val('draft_batch_modal_title'),
content: language.val('draft_batch_modal_content'),
onOk: async () => {
// 删除分类
const ids = layout.selects.filter(d => d.type === 'folder').map(d => d.id);
if (ids.length) {
const [res, err] = await userService.deleteCategory(ids);
if (err) {
Toast.error(err);
return;
}
pubsub.publish('updateFolders');
}
const deleteIds = [];
// 删除草稿
if (props.type === 'draft') {
const ids2 = layout.selects.filter(d => d.type === 'item').map(d => d.id);
if (ids2.length) {
deleteIds.push(...ids2);
for (const id of ids2) {
const [res2, err2] = await draftServer.deleteDraft(id);
if (err2) {
Toast.error(err2);
return;
}
}
}
}
// 删除素材
if (props.type === 'material') {
const ids2 = layout.selects.filter(d => d.type === 'item').map(d => d.id);
if (ids2.length) {
deleteIds.push(...ids2);
const [res2, err2] = await materialServer.deleteMaterial({
id: ids2,
});
if (err2) {
Toast.error(err2);
return;
}
}
}
// 如果分类和草稿(素材)都删除了,取消操作弹框
if (ids.length + deleteIds.length === cates?.length + items?.length) {
layout.openSelectManage = false;
}
if (deleteIds.length) {
//移除列表
_remove(items, d => deleteIds.includes(d.id));
removeCallBack([[...items]]);
}
layout.selects = [];
Toast.success(language.val('common_delete_success'));
},
});
}}
type="danger"
>
{language.val('common_delete')}
</Button>
<Button
disabled={
!(
layout.selects.filter(d => d.type === 'item').length !== 0 &&
layout.selects.filter(d => d.type === 'folder').length === 0
)
}
>
{' '}
<Popover
position="bottom"
content={
<ul className={styles.menus}>
{props.cates.map(d => {
return (
<li
onClick={() => {
props.moveCallBack(
d.id,
layout.selects.map(d => d.id),
);
layout.selects = [];
}}
key={d.id}
>
{d.name}
</li>
);
})}
</ul>
}
>
<span>{language.val('common_move')}</span>
</Popover>
</Button>
<Button
type="tertiary"
onClick={() => {
layout.cancelSelected();
}}
>
{language.val('common_cancel')}
</Button>
</Space>
);
}
export default observer(SelectedSet);
+147
View File
@@ -0,0 +1,147 @@
import { IconSpin } from '@douyinfe/semi-icons';
// import InfiniteScroll from 'react-infinite-scroll-component';
import styles from './sourceList.module.less';
import WaterFull from '@components/water-full';
import classNames from 'classnames';
import { Progress, Checkbox, Toast, Empty } from '@douyinfe/semi-ui';
import { userService } from '@server/user.service';
import { observer } from 'mobx-react';
import { layout } from '@stores/layout';
import { useReducer } from 'react';
import { language } from '@language/language';
import {
IllustrationConstruction,
IllustrationConstructionDark,
IllustrationNoResult,
IllustrationNoResultDark,
} from '@douyinfe/semi-illustrations';
import { Link } from 'react-router-dom';
export interface IProps {
items: any[];
itemWidth: number;
item: (a: any) => JSX.Element;
itemClassName: string;
type: 'draft' | 'material'; // 资源类型
selects?: any[];
setSelects?: (selects: any[]) => void;
propsCheckboxStyle?: React.CSSProperties;
}
export interface ChildProps {
children?: any;
className?: string;
item: any;
}
function SourceList(props: IProps) {
const { items, type, itemWidth, propsCheckboxStyle = {} } = props;
// console.log(items, hasMore, "items");
if (!items) {
return (
<div className={styles.loadingMore}>
<span>
<IconSpin spin style={{ color: '#fff' }} />
&nbsp;&nbsp;{language.val('loading_more')}
</span>
</div>
);
}
const checkboxStyle: any = {};
if (layout.openSelectManage) {
checkboxStyle.display = 'block';
}
layout.selects;
if (items.length === 0) {
if (type === 'draft') {
// 草稿/作品页
return (
<Empty
image={<IllustrationNoResult style={{ width: 150, height: 150 }} />}
darkModeImage={<IllustrationNoResultDark style={{ width: 150, height: 150 }} />}
title={'暂无作品'}
description="暂无任何作品,点击上方「创建项目」开始创作"
/>
);
}
// 素材页
return (
<Empty
image={<IllustrationNoResult style={{ width: 150, height: 150 }} />}
darkModeImage={<IllustrationNoResultDark style={{ width: 150, height: 150 }} />}
title={'暂无素材'}
description="暂无任何素材去选择"
/>
);
}
return (
// <InfiniteScroll
// dataLength={items.length || 0}
// hasMore={hasMore}
// next={next}
// loader={
// <>
// {hasMore && (
// <div className={styles.loadingMore}>
// <span>
// <IconSpin spin style={{ color: '#fff' }} />
// &nbsp;&nbsp;加载中...
// </span>
// </div>
// )}
// </>
// }
// scrollableTarget={scrollableTarget ? scrollableTarget : `sourceItemsScrollDOM_${props.type}`}
// endMessage={<p className={styles.noMoreTips}>{language.val('no_more_data')}</p>}
// >
<WaterFull
gap={16}
itemWidth={itemWidth}
itemHeight={['draft'].includes(type) ? 180 : 'count'}
list={items}
item={(item: any) => {
return (
<span data-type={item.type} className={classNames(styles.item, props.itemClassName)}>
{props.item(item)}
{item.id !== 'null' && (
<span className={styles.checkbox} style={{ ...checkboxStyle, ...propsCheckboxStyle }}>
{props.selects ? (
<Checkbox
checked={!!props.selects.find(d => d.id === item.id)}
onChange={e => {
if (e.target.checked) {
props.setSelects([...props.selects, { ...item }]);
} else {
props.setSelects([...props.selects.filter(d => d.id !== item.id)]);
}
}}
></Checkbox>
) : (
<Checkbox
checked={!!layout.selects.find(d => d.id === item.id)}
onChange={e => {
layout.setSelected(
{
id: item.material_id || item.id,
type: 'item',
},
e.target.checked,
);
}}
></Checkbox>
)}
</span>
)}
</span>
);
}}
/>
// </InfiniteScroll>
);
}
export default observer(SourceList);
+118
View File
@@ -0,0 +1,118 @@
.content {
// padding: 30px;
// min-height: 100vh;
.title {
display: flex;
align-items: center;
justify-content: space-between;
color: var(--theme-text);
h1 {
font-size: 24px;
font-weight: bolder;
align-items: center;
}
.cates {
align-items: center;
margin-left: 30px;
font-size: 18px;
color: var(--theme-text);
a {
color: var(--theme-main);
}
:global {
.i-icon {
opacity: 0.5;
position: relative;
top: 3px;
}
}
}
}
}
.contents {
margin-top: 20px;
// padding-top: 20px;
overflow: auto;
position: relative;
}
.selectedManager {
position: fixed;
left: 50%;
margin-left: -100px;
z-index: 100;
background-color: var(--theme-bg);
padding: 10px 20px;
border-radius: 4px;
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}
.menus {
padding: 15px 8px;
li {
display: flex;
align-items: center;
padding: 6px 16px;
cursor: pointer;
border-radius: 4px;
transition: 0.4s;
color: var(--theme-text);
:global {
.i-icon {
margin-right: 5px;
position: relative;
top: 3px;
}
}
&:hover {
background-color: var(--theme-input);
}
}
}
.pagination {
display: flex;
justify-content: center;
padding: 30px 0;
:global {
.semi-page-item {
background: rgba(255, 255, 255, 0.05);
border: 1px solid rgba(255, 255, 255, 0.1);
color: rgba(255, 255, 255, 0.6);
&:hover {
background: rgba(255, 255, 255, 0.1);
color: #fff;
}
&-active {
background: #0066ff;
border-color: #0066ff;
color: #fff;
}
}
.semi-page-prev,
.semi-page-next {
background: rgba(255, 255, 255, 0.05);
border: 1px solid rgba(255, 255, 255, 0.1);
color: rgba(255, 255, 255, 0.6);
&:hover {
background: rgba(255, 255, 255, 0.1);
color: #fff;
}
&.semi-page-item-disabled {
opacity: 0.3;
cursor: not-allowed;
}
}
}
}
@@ -0,0 +1,52 @@
.folders {
// margin: 20px 0;
margin-top: 20px;
max-height: 240px;
overflow-y: auto;
.folderItem {
display: inline-block;
text-align: center;
width: 120px;
height: 110px;
padding: 10px;
position: relative;
cursor: pointer;
:global {
.semi-checkbox {
position: absolute;
top: 5px;
right: 5px;
}
}
input {
display: block;
text-overflow: ellipsis;
text-align: center;
width: 100%;
overflow: hidden;
white-space: nowrap;
font-size: 12px;
background-color: transparent;
border: none;
border: 1px solid transparent;
border-radius: 2px;
color: var(--theme-text);
&:focus {
border: 1px solid #000;
}
}
:global {
.semi-checkbox {
display: none;
}
}
&:hover {
background-color: var(--theme-input);
:global {
.semi-checkbox {
display: flex;
}
}
}
}
}
+27
View File
@@ -0,0 +1,27 @@
export interface IconProps {
size: number;
color?: string;
}
export function FolderIcon(props: IconProps) {
return (
<svg
viewBox="0 0 1024 1024"
version="1.1"
xmlns="http://www.w3.org/2000/svg"
width={props.size}
height={props.size}
>
<path
d="M230.4 230.4m76.8 0l486.4 0q76.8 0 76.8 76.8l0 409.6q0 76.8-76.8 76.8l-486.4 0q-76.8 0-76.8-76.8l0-409.6q0-76.8 76.8-76.8Z"
fill="#FFA86A"
p-id="5062"
></path>
<path
d="M102.4 256a76.8 76.8 0 0 1 76.8-76.8h223.6672a76.8 76.8 0 0 1 73.856 55.7056L497.3568 307.2H844.8a76.8 76.8 0 0 1 76.8 76.8v409.6a76.8 76.8 0 0 1-76.8 76.8H179.2a76.8 76.8 0 0 1-76.8-76.8V256z"
fill="#FFD977"
p-id="5063"
></path>
</svg>
);
}
+3
View File
@@ -0,0 +1,3 @@
import Content from './Content';
export default Content;
@@ -0,0 +1,278 @@
import styles from './styles.module.less';
import { useCallback, useState } from 'react';
import { observer } from 'mobx-react';
import { Button, InputNumber, Space, Upload, Toast, Modal } from '@douyinfe/semi-ui';
import { language } from '@language/language';
import JSZip from 'jszip';
import ReactCrop, { type Crop, type PixelCrop } from 'react-image-crop';
import 'react-image-crop/dist/ReactCrop.css';
export interface IProps {}
/**
* AI 人像分割
* @param props
* @returns
*/
function PictureSplit(props: IProps) {
const [imgURL, setImgURL] = useState('');
const [key, setKey] = useState(1);
const [num, setNum] = useState({
x: 3,
y: 3,
padding: 0,
});
const [loading, setLoading] = useState(false);
const [crop, setCrop] = useState<Crop | null>(null);
const [showCrop, setShowCrop] = useState(false);
const [croppedImage, setCroppedImage] = useState('');
const getBase64 = file => {
return new Promise(resolve => {
var reader = new FileReader();
reader.onload = function (e) {
resolve(e.target.result);
};
reader.readAsDataURL(file);
});
};
const splitAndDownload = useCallback(async () => {
if (!imgURL) {
Toast.error('请先上传图片');
return;
}
setLoading(true);
try {
const img = new Image();
img.crossOrigin = 'anonymous';
await new Promise((resolve, reject) => {
img.onload = resolve;
img.onerror = reject;
img.src = imgURL;
});
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const scale = img.naturalWidth / 1000;
const padding = num.padding * scale;
const pieceWidth = Math.floor((img.width - padding * (num.x + 1)) / num.x);
const pieceHeight = Math.floor((img.height - padding * (num.y + 1)) / num.y);
canvas.width = pieceWidth;
canvas.height = pieceHeight;
const zip = new JSZip();
const imgFolder = zip.folder('split_images');
for (let row = 0; row < num.y; row++) {
for (let col = 0; col < num.x; col++) {
ctx.clearRect(0, 0, pieceWidth, pieceHeight);
const sx = padding + col * (pieceWidth + padding);
const sy = padding + row * (pieceHeight + padding);
ctx.drawImage(img, sx, sy, pieceWidth, pieceHeight, 0, 0, pieceWidth, pieceHeight);
const blob = await new Promise(resolve => {
canvas.toBlob(resolve, 'image/png');
});
const index = row * num.x + col + 1;
imgFolder.file(`image_${index}.png`, blob as Blob);
}
}
const content = await zip.generateAsync({ type: 'blob' });
const link = document.createElement('a');
link.href = URL.createObjectURL(content);
link.download = 'split_images.zip';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(link.href);
Toast.success('图片分割完成,已开始下载');
} catch (error) {
console.error('分割图片失败:', error);
Toast.error('分割图片失败');
} finally {
setLoading(false);
}
}, [imgURL, num.x, num.y, num.padding]);
const handleCropChange = useCallback((crop: any) => {
setCrop(crop);
}, []);
const handleCropComplete = useCallback(
async (crop: any) => {
if (!crop || !imgURL) return;
const img = new Image();
img.crossOrigin = 'anonymous';
await new Promise((resolve, reject) => {
img.onload = resolve;
img.onerror = reject;
img.src = imgURL;
});
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const scale = img.naturalWidth / 1000;
canvas.width = crop.width * scale;
canvas.height = crop.height * scale;
ctx.drawImage(
img,
crop.x * scale,
crop.y * scale,
crop.width * scale,
crop.height * scale,
0,
0,
crop.width * scale,
crop.height * scale,
);
canvas.toBlob(blob => {
if (blob) {
const url = URL.createObjectURL(blob);
setCroppedImage(url);
}
}, 'image/png');
},
[imgURL],
);
const downloadCroppedImage = useCallback(() => {
if (!croppedImage) {
Toast.error('请先完成裁剪');
return;
}
const link = document.createElement('a');
link.href = croppedImage;
link.download = 'cropped_image.png';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(croppedImage);
}, [croppedImage]);
return (
<div className={styles.body}>
<Upload
action="/"
accept=".gif, .png, .jpeg, .jpg"
showUploadList={false}
beforeUpload={obj => {
getBase64(obj.file.fileInstance).then(res => {
setKey(+new Date());
setImgURL(res as string);
});
return true;
}}
customRequest={() => {}}
draggable={true}
style={{ height: 200 }}
dragMainText={language.val('ai_upload_tip')}
dragSubText={language.val('ai_upload_sub_tip', {
format: 'PNG/GIF/JPG',
})}
></Upload>
<div className={styles.tools}>
<Space>
<InputNumber
style={{ width: 120 }}
value={num.x}
onChange={value => {
setNum({ ...num, x: Number(value) });
}}
min={1}
max={20}
step={1}
/>
<span style={{ color: 'var(--theme-text)' }}>x</span>
<InputNumber
style={{ width: 120 }}
value={num.y}
onChange={value => {
setNum({ ...num, y: Number(value) });
}}
min={1}
max={20}
step={1}
/>
<span style={{ color: 'var(--theme-text)' }}>padding:</span>
<InputNumber
style={{ width: 120 }}
value={num.padding}
onChange={value => {
setNum({ ...num, padding: Number(value) });
}}
min={0}
max={100}
step={1}
suffix="px"
/>
<Button onClick={splitAndDownload} loading={loading}>
分割图片
</Button>
<Button onClick={() => setShowCrop(true)} disabled={!imgURL}>
自由裁剪
</Button>
</Space>
</div>
{!!imgURL && (
<div className={styles.videoBox}>
{Array(num.x * num.y)
.fill(1)
.map((_, i) => {
const row = Math.floor(i / num.x);
const col = i % num.x;
const padding = num.padding;
return (
<span
className={styles.span}
style={{
width: `calc((100% - ${padding * (num.x + 1)}px) / ${num.x})`,
height: `calc((100% - ${padding * (num.y + 1)}px) / ${num.y})`,
top: `calc(${padding}px + ${row} * (100% - ${padding * (num.y + 1)}px) / ${num.y} + ${row} * ${padding}px)`,
left: `calc(${padding}px + ${col} * (100% - ${padding * (num.x + 1)}px) / ${num.x} + ${col} * ${padding}px)`,
}}
key={i}
>
{/* {i + 1} */}
</span>
);
})}
<img style={{ width: '100%' }} src={imgURL} alt="" />
</div>
)}
<Modal title="自由裁剪" visible={showCrop} onCancel={() => setShowCrop(false)} footer={null} width={1100}>
{imgURL && (
<div style={{ paddingBottom: 20, textAlign: 'center' }}>
<ReactCrop crop={crop} onChange={handleCropChange} onComplete={handleCropComplete} keepSelection>
<img style={{ width: 1000 }} src={imgURL} alt="" />
</ReactCrop>
{croppedImage && (
<Button onClick={downloadCroppedImage} style={{ marginTop: 10 }}>
下载裁剪图片
</Button>
)}
</div>
)}
</Modal>
</div>
);
}
export default observer(PictureSplit);
@@ -0,0 +1,52 @@
.body {
width: 1000px;
margin: 20px auto;
.title {
text-align: center;
color: var(--theme-text);
padding: 40px 20px 20px 20px;
p {
margin: 20px 0;
opacity: 0.5;
}
}
}
.tools {
margin: 20px 0;
}
.videoBox {
margin-top: 20px;
position: relative;
.span {
position: absolute;
border: 1px dashed #000;
}
}
:global {
.ReactCrop {
max-width: 100%;
img {
max-width: 100%;
}
}
}
.croppedPreview {
margin-top: 20px;
padding: 15px;
background: #fff;
border-radius: 4px;
h4 {
margin-bottom: 10px;
color: var(--theme-text);
}
img {
max-width: 100%;
max-height: 300px;
border: 1px solid #ddd;
}
}
@@ -0,0 +1,89 @@
.loadingMore,
.noMoreTips {
display: flex;
align-items: center;
justify-content: center;
padding: 20px;
font-size: 12px;
color: var(--theme-text);
path {
fill: #fff !important;
}
}
.loadingMore {
& > span {
display: flex;
align-items: center;
}
}
.item {
position: relative;
-webkit-user-drag: none;
img {
-webkit-user-drag: none;
}
.checkbox {
position: absolute;
z-index: 10;
top: 5px;
right: 5px;
background-color: #fff;
width: 16px;
height: 16px;
border-radius: 3px;
display: none;
:global {
.semi-checkbox {
top: -2px;
}
}
}
.save,
.add {
position: absolute;
z-index: 100;
bottom: 5px;
right: 5px;
background-color: var(--theme-main);
width: 16px;
height: 16px;
border-radius: 3px;
align-items: center;
justify-content: center;
display: none;
}
.save {
right: 25px;
background-color: rgb(255, 167, 58);
}
&:hover {
.save,
.add {
display: flex;
}
.checkbox {
display: block;
}
}
.progress {
font-size: 14px;
font-weight: bolder;
color: #fff;
position: absolute;
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
z-index: 100;
background-color: rgba(0, 0, 0, 0.5);
top: 0;
left: 0;
}
}
@@ -0,0 +1,297 @@
import React, { useCallback, useEffect, useRef, useState } from 'react';
import styles from './styles.module.less';
import { Upload, Button, Toast, Spin, Space, InputNumber } from '@douyinfe/semi-ui';
import JSZip from 'jszip';
import { util } from '@utils/index';
import { language } from '@language/language';
import { uploadInfo } from '@utils/uploadInfo.es.js';
import { userService } from '@server/user.service';
type Props = {};
const VideoSplit = (props: Props) => {
const [progress, setProgress] = useState(0);
const [url, setUrl] = useState('');
const [frameURL, setFrameURL] = useState('');
// const [stepFrameDraw, setStepFrameDraw] = useState(10);
const [duration, setDuration] = useState(0);
const [mouseX, setMouseX] = useState(-1);
const [markers, setMarkers] = useState<number[]>([]);
const [loading, setLoading] = useState(false);
const videoRef = useRef<HTMLVideoElement>(null);
const frameContainerRef = useRef<HTMLDivElement>(null);
const frameRef = useRef<HTMLImageElement>(null);
const [paddingTime, setPaddingTime] = useState(0);
const downCapture = async () => {
if (markers.length === 0) {
Toast.error('请先添加分割标记');
return;
}
console.log('markers', markers);
setProgress(0);
setLoading(true);
try {
// 使用ffmpeg对视频进行裁剪
const ffmpeg = (window as any)._ffmpegWASMInstance;
while (!ffmpeg.loaded) {
await util.sleep(1000);
}
// 开始
ffmpeg.on('progress', ({ progress }: any) => {
setProgress(progress);
});
await ffmpeg.writeFile('input.mp4', await util.fetchFile(url));
// 根据 markers 计算时间节点并排序
const times = markers
.map(n => {
const container = frameContainerRef.current;
if (!container) return 0;
const img = container.querySelector('img');
if (!img) return 0;
const imgWidth = img.scrollWidth;
const percent = Math.min(Math.max(n / imgWidth, 0), 1);
return percent * duration;
})
.sort((a, b) => a - b);
console.log('分割时间点:', times);
// 生成分割命令
const segments = [];
let startTime = 0;
for (let i = 0; i <= times.length; i++) {
const endTime = i < times.length ? times[i] : duration;
const segmentDuration = endTime - startTime;
if (segmentDuration > 0.1) {
// 过滤掉太短的片段
const outputFile = `segment_${i + 1}.mp4`;
segments.push(outputFile);
// 执行分割命令(使用copy参数快速分割,不重新编码)
await ffmpeg.exec([
'-ss',
(startTime + (i === 0 ? 0 : paddingTime / 2)).toFixed(2),
'-i',
'input.mp4',
'-t',
(endTime - startTime - (i === times.length - 1 ? 0 : paddingTime / 2)).toFixed(2),
'-c',
'copy',
'-y',
outputFile,
]);
startTime = endTime;
}
}
console.log('分割完成,生成的片段:', segments);
// 创建zip文件
const zip = new JSZip();
const videoFolder = zip.folder('video_segments');
// 读取所有分割后的片段并添加到zip
for (const segment of segments) {
const data = await ffmpeg.readFile(segment);
videoFolder.file(segment, data.buffer);
// 清理临时文件
ffmpeg.deleteFile(segment);
}
// 生成zip文件并下载
const content = await zip.generateAsync({ type: 'blob' });
const zipUrl = URL.createObjectURL(content);
const link = document.createElement('a');
link.href = zipUrl;
link.download = 'video_segments.zip';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(zipUrl);
// 清理临时文件
ffmpeg.deleteFile('input.mp4');
// 显示成功提示
Toast.success(`视频已分割为 ${segments.length} 个片段,已打包成zip文件`);
} catch (error) {
console.error('分割视频失败:', error);
Toast.error('分割视频失败');
} finally {
setLoading(false);
}
};
const drawFrameImage = async (url: string) => {
const info = await uploadInfo.getUploadBeforeData({
url,
type: 'video',
uploadBase64: null,
});
console.log('info1', info);
setDuration(info.duration);
const res = (await uploadInfo.decoderVideoDrawFrameImage({
url,
aspectRatio: info.videoWidth / info.videoHeight,
audioTrack: null,
drawRectangle: false,
stepFrameDraw: 10, // 每10帧绘制一次
videoRotation: info.rotate ? 90 : 0,
frameScale: 2,
duration: info.duration,
workerPath: '/assets/worker',
})) as any;
setFrameURL(res.url);
console.log(res, 'res--------->');
};
const handleMouseMove = (e: React.MouseEvent<HTMLDivElement>) => {
if (!frameContainerRef.current) return;
const container = frameContainerRef.current;
const rect = container.getBoundingClientRect();
const x = e.clientX - rect.left + container.scrollLeft;
// 获取图片实际宽度
const img = container.querySelector('img');
if (img) {
const imgWidth = img.scrollWidth;
// 限制x坐标在图片宽度范围内
const limitedX = Math.min(Math.max(x, 0), imgWidth);
setMouseX(limitedX);
// 计算当前时间点
if (videoRef.current && duration > 0) {
const percent = limitedX / imgWidth;
const currentTime = percent * duration;
videoRef.current.currentTime = currentTime;
}
}
};
const handleMouseLeave = () => {
setMouseX(-1);
};
const handleClick = (e: React.MouseEvent<HTMLDivElement>) => {
if (!frameContainerRef.current) return;
const container = frameContainerRef.current;
const rect = container.getBoundingClientRect();
const x = e.clientX - rect.left + container.scrollLeft;
// 获取图片实际宽度
const img = container.querySelector('img');
if (img) {
const imgWidth = img.scrollWidth;
// 限制x坐标在图片宽度范围内
const limitedX = Math.min(Math.max(x, 0), imgWidth);
setMarkers([...markers, limitedX]);
}
};
const removeMarker = (index: number) => {
setMarkers(markers.filter((_, i) => i !== index));
};
useEffect(() => {
if (url) {
drawFrameImage(url);
}
}, [url]);
return (
<Spin spinning={loading}>
<div className={styles.zip} style={{ height: 'auto' }}>
<Upload
action="/"
accept=".mp4"
showUploadList={false}
customRequest={() => {}}
beforeUpload={obj => {
setUrl(obj.file.url);
return true;
}}
draggable={true}
style={{ height: 200 }}
dragMainText={language.val('mp4_upload_tip', { format: 'MP4' })}
dragSubText={language.val('mp4_upload_sub_tip', { format: 'MP4' })}
></Upload>
{url && (
<div className={styles.videoBox}>
<video ref={videoRef} style={{ height: 400 }} src={url} controls></video>
</div>
)}
<div
className={styles.videoFrames}
ref={frameContainerRef}
onMouseMove={handleMouseMove}
onMouseLeave={handleMouseLeave}
onClick={handleClick}
>
<img ref={frameRef} src={frameURL} alt="" />
{/* 鼠标跟随竖线 */}
{mouseX >= 0 && <div className={styles.mouseLine} style={{ left: `${mouseX}px` }} />}
{/* 标记红线 */}
{markers.map((x, index) => (
<div key={index} className={styles.markerLine} style={{ left: `${x}px` }}>
<div
className={styles.markerDelete}
onClick={e => {
e.stopPropagation();
removeMarker(index);
}}
>
×
</div>
<div
className={styles.padding}
style={{ width: (frameRef.current.width * paddingTime) / duration + 'px' }}
></div>
</div>
))}
</div>
<div className={styles.markerBox}>
<div className={styles.markerTime}>
分割时间点:
{frameRef.current &&
duration &&
markers
.sort((a, b) => a - b)
.map(x => `${((x / frameRef.current.width) * duration).toFixed(2)}秒`)
.join('、')}
</div>
<Space>
<InputNumber
insetLabel="间隙"
value={paddingTime}
onChange={value => setPaddingTime(Number(value))}
min={0}
max={duration}
style={{ width: 160 }}
step={0.01}
suffix="秒"
/>
<Button onClick={downCapture} loading={loading}>
开始分割
</Button>
</Space>
</div>
</div>
</Spin>
);
};
export default VideoSplit;
@@ -0,0 +1,98 @@
.zip {
width: 1000px;
margin: 20px auto;
height: 600px;
a {
color: var(--theme-text);
}
.title {
text-align: center;
color: var(--theme-text);
padding: 40px 20px 20px 20px;
p {
margin: 20px 0;
opacity: 0.5;
}
}
}
.videoBox{
margin-top: 20px;
background-color: #000;
text-align: center;
}
.videoFrames{
margin-top: 20px;
position: relative;
cursor: pointer;
height: 80px;
overflow-x: auto;
overflow-y: hidden;
img{
height: 100%;
width: auto !important;
}
.mouseLine{
position: absolute;
top: 0;
bottom: 0;
width: 1px;
background-color: #007bff;
z-index: 10;
pointer-events: none;
}
.padding{
position: absolute;
height: 100%;
background-color: rgba(229, 255, 0, 0.63);
z-index: 10;
left: 50%;
transform: translateX(-50%);
pointer-events: none;
}
.markerLine{
position: absolute;
top: 0;
bottom: 0;
width: 1px;
background-color: #ff0000;
z-index: 5;
pointer-events: none;
.markerDelete{
position: absolute;
top: 20px;
left: -8px;
width: 16px;
height: 16px;
background-color: #ff0000;
color: white;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
font-size: 14px;
cursor: pointer;
z-index: 20;
pointer-events: auto;
&:hover{
background-color: #cc0000;
}
}
}
}
.markerBox{
margin-top: 20px;
display: flex;
justify-content: space-between;
}
.markerTime{
color: #fff;
}
@@ -0,0 +1,79 @@
import React, { useEffect, useState, useCallback } from 'react';
import { Button, Modal, Typography } from '@douyinfe/semi-ui';
import { FolderOpen } from '@icon-park/react';
import { initLocalFolder, getRootHandle, isFSApiSupported } from '@services/localStorageService';
interface FolderGuardProps {
children: React.ReactNode;
}
const FolderGuard: React.FC<FolderGuardProps> = ({ children }) => {
const supported = isFSApiSupported();
const [folderReady, setFolderReady] = useState(!supported);
const [folderLoading, setFolderLoading] = useState(false);
// 组件挂载时检查文件夹是否已初始化
useEffect(() => {
if (supported) {
getRootHandle().then(handle => {
if (handle) {
setFolderReady(true);
}
});
}
}, [supported]);
const handleInitFolder = useCallback(async () => {
setFolderLoading(true);
try {
const handle = await initLocalFolder();
if (handle) {
setFolderReady(true);
}
} finally {
setFolderLoading(false);
}
}, []);
// 不支持 FSApi,直接渲染子组件
if (!supported) {
return <>{children}</>;
}
// 文件夹未就绪,显示选择弹窗
if (!folderReady) {
return (
<Modal
visible={true}
closable={false}
maskClosable={false}
footer={null}
title={null}
style={{ maxWidth: 480 }}
bodyStyle={{ textAlign: 'center', padding: '40px 32px' }}
>
<FolderOpen size={64} fill="#1677ff" style={{ marginBottom: 24 }} />
<Typography.Title heading={4} style={{ marginBottom: 12 }}>
选择本地存储文件夹
</Typography.Title>
<Typography.Text type="tertiary" style={{ marginBottom: 24, display: 'block' }}>
请选择一个本地文件夹用于存放素材和项目数据,素材将不会上传到服务器
</Typography.Text>
<Button
theme="solid"
type="primary"
size="large"
loading={folderLoading}
onClick={handleInitFolder}
block
>
选择文件夹
</Button>
</Modal>
);
}
return <>{children}</>;
};
export default FolderGuard;
+77
View File
@@ -0,0 +1,77 @@
import { theme } from '@theme';
import styles from './footer.module.less';
import { Intl } from '@language/index';
export interface IProps {}
export default function Footer(props: IProps) {
return (
<div className={styles.footer}>
<div className={styles.divider}></div>
<div className={styles.footerInner}>
<section className={styles.item}>
<span className={styles.logo}></span>
<span className={styles.info}>
<Intl name="common_about_us_info" />
</span>
</section>
<section className={styles.item}>
<h3><Intl name="common_navigation" /></h3>
<ul className={styles.links}>
<li>
<a href="#">{<Intl name="common_home" />}</a>
</li>
<li>
<a href="#">{<Intl name="common_about_us" />}</a>
</li>
{/* <li>
<a href="#">VIP特权</a>
</li> */}
</ul>
</section>
<section className={styles.item}>
<h3><Intl name="common_support" /></h3>
<ul className={styles.links}>
<li>
<a href="#">{<Intl name="common_help_center" />}</a>
</li>
<li>
<a href="#">{<Intl name="common_privacy_policy" />}</a>
</li>
<li>
<a href="#">{<Intl name="common_service_agreement" />}</a>
</li>
<li>
<a href="#">{<Intl name="common_disclaimer" />}</a>
</li>
</ul>
</section>
<section className={styles.item}>
<h3><Intl name="common_contact_us" /></h3>
<div className={styles.contact}>
<p>
<Intl name="common_private_deployment_saas_consultation" />
<br />
<Intl name="common_phone" />: 13551301693
</p>
<span className={styles.span}>
<img src="/assets/images/qrcode.png" alt="" />
</span>
{/* <span className={styles.span}>
<i>董经理</i>
<em>13551301693</em>
</span> */}
</div>
</section>
</div>
<div className={styles.footerBottom}>
<span className={styles.copyRight}>
<Intl name="common_copyright" />
</span>
{/* <span className={styles.cookie}>
开启cookie提供更好的服务 <a>接受</a>
</span> */}
</div>
</div>
);
}
+201
View File
@@ -0,0 +1,201 @@
.footer {
padding-top: 20px;
.divider {
height: 3px;
background: linear-gradient(285.39deg, rgba(158, 128, 255, 0.4) -2.87%, rgba(194, 177, 248, 0) 27.22%),
linear-gradient(107.57deg, #78e4ef -0.21%, #fda8ff 98.69%);
}
.footerInner {
max-width: 1000px;
margin: 20px auto;
display: flex;
justify-content: space-between;
}
.footerBottom {
border-top: var(--theme-border);
margin: 20px auto;
max-width: 1000px;
display: flex;
justify-content: center;
font-size: 12px;
padding: 20px 0;
color: var(--theme-text);
.copyRight {
opacity: 0.5;
}
a {
color: var(--theme-main);
}
}
.item {
font-size: 14px;
width: 25%;
padding-right: 30px;
color: var(--theme-text);
span {
display: inline-block;
}
.logo {
display: block;
width: 160px;
height: 60px;
background-image: var(--theme-logoen);
margin-bottom: 30px;
}
.info {
font-size: 12px;
opacity: 0.6;
line-height: 20px;
width: 80%;
}
a {
color: var(--theme-text);
}
h3 {
line-height: 60px;
height: 60px;
font-size: 16px;
font-weight: bolder;
margin-bottom: 30px;
}
.links {
opacity: 0.5;
li {
margin-bottom: 15px;
}
}
.contact {
p {
display: block;
width: 100%;
}
.span {
margin-top: 10px;
display: block;
& > i {
display: inline-block;
width: 60px;
font-style: normal;
opacity: 0.5;
}
& > img {
width: 80px;
}
}
}
}
}
@media screen and (max-width: 1000px) {
.footer {
.footerInner {
flex-wrap: wrap; // 换行
padding: 0 20px;
}
.item {
width: 100%;
margin: 0 20px;
h3 {
margin-bottom: 0;
}
}
.links li {
display: inline-block;
margin-right: 20px;
}
}
}
// 小于768px时候(移动端)
@media screen and (max-width: 768px) {
.footer {
padding-top: 10px;
.divider {
height: 2px;
}
.footerInner {
margin: 10px auto;
padding: 0 15px;
}
.item {
width: 100%;
padding: 15px 0;
border-bottom: 1px solid var(--theme-border);
&:last-child {
border-bottom: none;
}
.logo {
width: 120px;
height: 45px;
margin-bottom: 15px;
}
.info {
width: 100%;
font-size: 11px;
}
h3 {
height: 40px;
line-height: 40px;
font-size: 14px;
margin-bottom: 10px;
}
.links {
li {
display: block;
margin-bottom: 8px;
font-size: 13px;
}
}
.contact {
p {
font-size: 12px;
}
.span {
margin-top: 15px;
img {
width: 100px;
}
}
}
}
.footerBottom {
margin: 10px auto;
padding: 15px 0;
font-size: 11px;
}
}
}
// 小于480px时候(小屏移动端)
@media screen and (max-width: 480px) {
.footer {
.footerInner {
padding: 0 10px;
}
.item {
padding: 12px 0;
.logo {
width: 100px;
height: 38px;
}
h3 {
font-size: 13px;
}
.links li {
font-size: 12px;
}
.contact {
p {
font-size: 11px;
}
.span img {
width: 80px;
}
}
}
.footerBottom {
font-size: 10px;
}
}
}
+3
View File
@@ -0,0 +1,3 @@
import Footer from './Footer';
export default Footer;
+205
View File
@@ -0,0 +1,205 @@
import React, { useReducer, useEffect, useState } from 'react';
import styles from './header.module.less';
import { NavLink, Link, withRouter } from 'react-router-dom';
import { observer } from 'mobx-react';
import { user } from '@stores/user';
import logoImg from '@images/logo2.png';
import { Button, Popover, Avatar, Space, Toast } from '@douyinfe/semi-ui';
import Login from '@components/login';
import User from './user/User';
import { config } from '@config/index';
import { theme, ThemeName } from '@theme';
import { layout } from '@stores/layout';
import { IconDuration, IconSun } from '@douyinfe/semi-icons';
import { getInitData } from '@config/initData';
import { server } from './server';
import { pubsub } from '@utils/pubsub';
import Intl from '@language/Intl';
import { language } from '@language/language';
import { AllApplication, Box, International } from '@icon-park/react';
import classNames from 'classnames';
import { reURL } from '@utils/util';
import VipRecharge from '@pages/editor/components/header/VipRecharge';
import CreditRecharge from '@pages/editor/components/header/CreditRecharge';
export interface IProps {
componentName?: string;
match?: any;
navs?: any[];
}
const Header = (props: IProps) => {
// const [, forceUpdate] = useReducer(x => x + 1, 0);
const [cid = '', cname = ''] = props.match.params.cid?.split('_') || [];
const [vipRechargeVisible, setVipRechargeVisible] = useState(false);
const [creditRechargeVisible, setCreditRechargeVisible] = useState(false);
// 创建视频
const createVideo = async () => {
if (!user.info) {
pubsub.publish('showLoginModal', true);
return;
}
const initData = getInitData();
if (cid) {
initData.category_id = cid;
}
const [res, err] = await server.createVideo(initData);
if (err) {
Toast.error(err);
return;
}
location.href = `${config.editorHost}/${res.id}`;
};
useEffect(() => {
const vipSub = pubsub.subscribe('showVipRecharge', () => {
setVipRechargeVisible(true);
});
const creditSub = pubsub.subscribe('showCreditRecharge', () => {
setCreditRechargeVisible(true);
});
return () => {
pubsub.unsubscribe('showVipRecharge');
pubsub.unsubscribe('showCreditRecharge');
};
}, []);
const languageType = language.getLanguage();
return (
<div className={styles.header}>
<div className={styles.logoNav}>
<Link to="/">
{/* <div
className={classNames({
[styles.logoen]: languageType === 'en-US',
[styles.logo]: languageType === 'zh-CN',
})}
></div>{' '} */}
<a className={styles.logoBrand}>
<div className={styles.logo}>✂</div>
无界云剪辑
</a>
</Link>
<div className={styles.nav}>
{/* <NavLink
to="/"
className={styles.text}
activeClassName={styles.active}
isActive={(match, location) => {
if (location.pathname === '/') {
return true;
}
}}
>
<Intl name="common_home" />
</NavLink> */}
{props.navs?.map((item, index) => (
<a key={index} href={item.to} className={styles.text}>
{item.name}
</a>
))}
{/* <NavLink to="/article/vip" className={styles.text} activeClassName={styles.active}>
会员中心
</NavLink> */}
{/* <NavLink to="/tools" className={styles.text} activeClassName={styles.active}>
<Intl name="common_tools" />
</NavLink> */}
{/* <NavLink to="/article/about" className={styles.text} activeClassName={styles.active}>
<Intl name="common_about_us" />
</NavLink> */}
{/* <a
href={languageType === 'en-US' ? '/docs/en' : '/docs'}
target="_blank"
className={styles.text}
>
<Intl name="common_tech_docs" />
</a> */}
</div>
</div>
<Space spacing={20}>
{/* <a
className={styles.space}
onClick={() => {
if (language.getLanguage() === 'en-US') {
language.setLanguage('zh-CN');
} else {
language.setLanguage('en-US');
}
}}
>
<Intl name="user_language" />
</a> */}
{!!user.info && (
<>
<Link to="/workspace/material" className={styles.space}>
{/* <Intl name="user_workspace" /> */}
<Box theme="outline" size="20" fill="var(--theme-icon)" />
素材
</Link>
<Link to="/workspace/draft" className={styles.space + ' ' + styles.active}>
{/* <Intl name="user_workspace" /> */}
<AllApplication theme="outline" size="20" fill="var(--theme-icon)" />
项目
</Link>
</>
)}
<a
href="https://github.com/mtsee/unicut"
target="_blank"
rel="noopener noreferrer"
className={styles.space}
style={{ display: 'inline-flex', alignItems: 'center', gap: '6px' }}
>
<svg width="24" height="24" fill="currentColor" viewBox="0 0 16 16">
<path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0 0 16 8c0-4.42-3.58-8-8-8z" />
</svg>
GitHub
</a>
<a
href="https://gitee.com/676015863/unicut"
target="_blank"
rel="noopener noreferrer"
className={styles.space}
style={{ display: 'inline-flex', alignItems: 'center', gap: '6px' }}
>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 90 90" version="1.1">
<g xmlns="http://www.w3.org/2000/svg" id="Group">
<circle id="Combined-Shape" fill="#C71D23" cx="44.8544363" cy="44.8544363" r="44.8544363" />
<path
d="M67.558546,39.8714292 L42.0857966,39.8714292 C40.8627004,39.8720094 39.8710953,40.8633548 39.8701949,42.0864508 L39.8687448,47.623783 C39.867826,48.8471055 40.8592652,49.8390642 42.0825879,49.8393845 C42.0827874,49.8393846 42.0829869,49.8393846 42.0831864,49.8387862 L57.5909484,49.838657 C58.8142711,49.8386283 59.8059783,50.830319 59.8059885,52.0536417 C59.8059885,52.0536479 59.8059885,52.053654 59.8059701,52.0536602 L59.8059701,52.6073539 L59.8059701,52.6073539 L59.8059701,53.161115 C59.8059701,56.8310831 56.8308731,59.80618 53.160905,59.80618 L32.1165505,59.80618 C30.8934034,59.806119 29.9018373,58.8145802 29.9017425,57.5914331 L29.9011625,36.5491188 C29.9008781,32.8791508 32.8758931,29.9039718 36.5458611,29.9038706 C36.5459222,29.9038706 36.5459833,29.9038706 36.5460443,29.9040538 L67.5523638,29.9040538 C68.77515,29.9026795 69.7666266,28.9118177 69.7687593,27.6890325 L69.7721938,22.1516997 C69.774326,20.928378 68.7832423,19.9360642 67.5599198,19.9353054 C67.5594619,19.9353051 67.5590039,19.935305 67.558546,19.9366784 L36.5479677,19.9366784 C27.3730474,19.9366784 19.935305,27.3744208 19.935305,36.549341 L19.935305,67.558546 C19.935305,68.7818687 20.927004,69.7735676 22.1503267,69.7735676 L54.8224984,69.7735676 C63.079746,69.7735676 69.7735676,63.079746 69.7735676,54.8224984 L69.7735676,42.0864509 C69.7735676,40.8631282 68.7818687,39.8714292 67.558546,39.8714292 Z"
id="G"
fill="#FFFFFF"
/>
</g>
</svg>
Gitee
</a>
{/* <a className={styles.createVideoBtn} onClick={createVideo}>
<Button theme="solid" type="primary" className={styles.create}>
<Intl name="common_create_video" />
</Button>
</a> */}
{user.info ? (
<Popover content={<User />} position="bottomRight" trigger="hover">
<Avatar src={reURL(user.info.avatar, config.resourcesHost)} size="small" color="blue" alt="Lisa LeBlanc">
{user.info.name.toUpperCase().split('')[0]}
</Avatar>
</Popover>
) : (
<Login>
<Button theme="solid" className={styles.loginBtn}>
<Intl name="header_login" />
</Button>
</Login>
)}
</Space>
<VipRecharge visible={vipRechargeVisible} onCancel={() => setVipRechargeVisible(false)} />
<CreditRecharge visible={creditRechargeVisible} onCancel={() => setCreditRechargeVisible(false)} />
</div>
);
};
export default withRouter(observer(Header));
+162
View File
@@ -0,0 +1,162 @@
.header {
position: fixed;
padding: 0 160px;
top: 0;
left: 0;
z-index: 900;
display: flex;
align-items: center;
justify-content: space-between;
width: 100%;
height: 60px;
// padding: 0 20px;
box-shadow: 0px 10px 10px rgba(0, 0, 0, 0.1);
background-color: var(--theme-bg4);
backdrop-filter: blur(20px);
.logoBrand {
display: flex;
align-items: center;
gap: 10px;
font-size: 18px;
font-weight: 700;
color: var(--theme-text);
text-decoration: none;
}
.logoBrand .logo {
width: 34px;
height: 34px;
border-radius: 10px;
background: linear-gradient(135deg, #7c3aed, #5a29c6);
display: flex;
align-items: center;
justify-content: center;
font-size: 16px;
}
// .logoNav {
// display: flex;
// .logo {
// display: inline-block;
// width: 160px;
// height: 60px;
// background-image: var(--theme-logo);
// background-repeat: no-repeat;
// background-size: 80%;
// background-position: center;
// }
// .logoen {
// display: inline-block;
// width: 160px;
// height: 60px;
// background-image: var(--theme-logoen);
// background-repeat: no-repeat;
// background-size: cover;
// }
// .nav {
// .text {
// display: inline-block;
// margin-left: 40px;
// height: 55px;
// line-height: 55px;
// font-family: Inter;
// font-size: 14px;
// font-weight: 500;
// color: var(--theme-text);
// }
// .active {
// border-bottom: solid 2px var(--theme-text-active);
// }
// }
// }
.space {
color: var(--theme-text);
background: var(--theme-bg);
padding: 5px 20px;
border-radius: 6px;
display: flex;
box-shadow: 0 0 2px rgba(139, 92, 246, 0.3);
align-items: center;
:global {
.i-icon {
margin-right: 10px;
display: inline-block;
height: 18px;
}
}
}
.active {
box-shadow: 0 4px 16px rgba(139, 92, 246, 0.3);
background: linear-gradient(135deg, #7c3aed, #551db6);
}
}
.create {
background: linear-gradient(45deg, #00e9fa 0%, rgb(32, 127, 251) 100%);
&:hover {
background: linear-gradient(60deg, #00e9fa 0%, rgb(32, 127, 251) 100%) !important;
}
}
.loginBtn {
background: linear-gradient(45deg, #00e9fa 0%, #8b20fb 51%, #bb00fa 100%);
&:hover {
background: linear-gradient(60deg, #00e9fa 0%, #8b20fb 51%, #bb00fa 100%) !important;
}
}
// 小于1000px时候
@media screen and (max-width: 1000px) {
.header {
padding: 0 15px;
}
.space {
display: none;
}
.createVideoBtn {
display: none;
}
.logoNav {
.logo {
margin-top: 10px;
width: 100px;
height: 35px;
}
.logoen {
margin-top: 10px;
width: 100px;
height: 35px;
}
.nav .text {
margin-left: 20px;
font-size: 13px;
}
}
}
// 小于768px时候(移动端)
@media screen and (max-width: 768px) {
.header {
height: 50px;
padding: 0 12px;
}
.logoNav {
.logo {
width: 80px;
height: 30px;
margin-top: 8px;
}
.logoen {
width: 80px;
height: 30px;
margin-top: 8px;
}
.nav {
display: none; // 移动端隐藏导航,可以改为汉堡菜单
}
}
.space {
display: none;
}
}
+3
View File
@@ -0,0 +1,3 @@
import Header from './Header';
export default Header;
+11
View File
@@ -0,0 +1,11 @@
import BasicService from '@server/BasicService';
class Server extends BasicService {
/**
* @desc 创建视频
*/
createVideo = async data => {
return await this.post('/user/apps/create', data);
};
}
export const server = new Server();
+139
View File
@@ -0,0 +1,139 @@
import styles from './user.module.less';
import { Avatar } from '@douyinfe/semi-ui';
import { VipOne, Workbench, Power, People, Theme, International } from '@icon-park/react';
import { observer } from 'mobx-react';
import { user } from '@stores/user';
import classNames from 'classnames';
import { theme, ThemeName } from '@theme';
import { layout } from '@stores/layout';
import { Link } from 'react-router-dom';
import { useReducer } from 'react';
import { language, Intl } from '@language/index';
import { reURL } from '@utils/util';
import { config } from '@config/index';
import { util } from '@utils/index';
import { pubsub } from '@utils/pubsub';
export interface IProps {}
function User(props: IProps) {
const [, forceUpdate] = useReducer(x => x + 1, 0);
const info = user.info;
const isVip = Number(info.vip_level || 0) > 0 && info.vip_expire && new Date(info.vip_expire).getTime() > Date.now();
const vipExpire = info.vip_expire ? util.formatDate(info.vip_expire, 'YYYY-MM-DD') : '未开通';
return (
<div className={styles.user}>
<div className={styles.photo}>
<Avatar src={reURL(info.avatar, config.resourcesHost)} size="medium" color="blue">
{info.name.toUpperCase().split('')[0]}
</Avatar>
<span className={styles.right}>
<h3>{info.name}</h3>
<p>
<em>
<Intl name="user_userid" />:
</em>
{info.id}
</p>
</span>
</div>
<div className={styles.menus}>
<ul>
<li
className={styles.vipMenu}
onClick={e => {
e.stopPropagation();
pubsub.publish('showVipRecharge');
}}
>
<span>
<VipOne theme="filled" size="16" fill="#ff7a1a" />
<span>{isVip ? '会员用户' : '开通会员'}</span>
</span>
<span className={styles.vipRight}>{isVip ? `有效期至 ${vipExpire}` : '普通用户'}</span>
</li>
<li
onClick={e => {
e.stopPropagation();
pubsub.publish('showCreditRecharge');
}}
>
<span>
<VipOne theme="filled" size="16" fill="var(--theme-icon)" />
<span>积分充值</span>
</span>
<span className={styles.right}>{user.info?.credits || 0}</span>
</li>
<Link to="/workspace/draft">
<li>
<span>
<Workbench theme="filled" size="16" fill="var(--theme-icon)" />
<span>
<Intl name="user_workspace" />
</span>
</span>
</li>
</Link>
<Link to="/user/account">
<li>
<span>
<People theme="filled" size="16" fill="var(--theme-icon)" />
<span>
<Intl name="user_profile" />
</span>
</span>
</li>
</Link>
<li
onClick={() => {
if (theme.getTheme() === 'dark') {
theme.setTheme(ThemeName.LIGHT);
} else {
theme.setTheme(ThemeName.DARK);
}
layout.themeUpdateKey = theme.getTheme();
}}
>
<span>
<Theme theme="filled" size="16" fill="var(--theme-icon)" />
<span>
<Intl name="user_theme" />
</span>
</span>
<span className={styles.right}>{layout.themeUpdateKey === 'dark' ? 'Black' : 'Light'}</span>
</li>
<li
onClick={() => {
if (language.getLanguage() === 'en-US') {
language.setLanguage('zh-CN');
} else {
language.setLanguage('en-US');
}
}}
>
<span>
<International theme="filled" size="16" fill="var(--theme-icon)" />
<span>
<Intl name="user_language" />
</span>
</span>
</li>
<li>
<span
onClick={() => {
user.logout();
}}
>
<Power theme="filled" size="16" fill="var(--theme-icon)" />
<span>
<Intl name="user_logout" />
</span>
</span>
</li>
</ul>
</div>
</div>
);
}
export default observer(User);
@@ -0,0 +1,99 @@
.user {
width: 300px;
padding: 20px;
background-color: var(--theme-bg);
border-radius: var(--semi-border-radius-small);
font-size: 14px;
color: var(--theme-text);
.photo {
display: flex;
align-items: center;
.right {
margin-left: 10px;
h3 {
font-weight: bolder;
margin-bottom: 6px;
}
p {
font-size: 13px;
opacity: 0.7;
}
}
}
.vipTips {
margin-top: 20px;
display: flex;
align-items: center;
background: rgba(255, 148, 49, 0.2);
padding: 10px;
border-radius: var(--semi-border-radius-small);
.right {
margin-left: 10px;
}
h3 {
font-weight: bolder;
margin-bottom: 6px;
color: #a1520a;
}
p {
span {
font-size: 13px;
opacity: 0.7;
}
}
a {
color: var(--theme-main);
font-weight: bolder;
margin-left: 5px;
}
}
.noVipTips {
background: rgba(0, 0, 0, 0.05);
h3 {
color: var(--theme-text);
}
}
.menus {
margin-top: 20px;
.right {
opacity: 0.5;
font-size: 12px;
}
.vipRight {
max-width: 145px;
opacity: 0.65;
font-size: 12px;
line-height: 18px;
text-align: right;
word-break: keep-all;
}
.vipMenu {
background: rgba(255, 148, 49, 0.12);
}
li {
display: flex;
align-items: center;
justify-content: space-between;
cursor: pointer;
padding: 10px 10px;
border-radius: var(--semi-border-radius-small);
transition: 0.3s;
:global {
.i-icon {
opacity: 0.7;
margin-right: 10px;
}
}
color: var(--theme-text);
&:hover {
background-color: rgba(0, 0, 0, 0.05);
}
}
}
}
+63
View File
@@ -0,0 +1,63 @@
import styles from './login-register.module.less';
import React, { useState, useEffect } from 'react';
import { Modal } from '@douyinfe/semi-ui';
import LoginRegisterBox from './loginRegisterBox/LoginRegisterBox';
import { pubsub } from '@utils/index';
import { Close } from '@icon-park/react';
import { language } from '@language/language';
import { stores } from '@stores/index';
function LoginRegister({ children }: any) {
const [visible, setVisible] = useState(false);
const showVisible = () => {
if (!stores.user.info) {
setVisible(true);
} else {
console.log(stores.user.info);
console.warn('已经登录过了');
// history.push(location.pathname);
}
};
useEffect(() => {
pubsub.subscribe('showLoginModal', (_eventName: string, mark: boolean) => {
if (mark !== undefined) {
setVisible(mark);
} else {
setVisible(true);
}
});
return () => {
pubsub.unsubscribe('showLoginModal');
};
}, []);
return (
<div className={styles.loginRegister}>
{children ? (
<span onClick={showVisible}>{children}</span>
) : (
<a onClick={showVisible} className={styles.loginRegisterBtn}>
{language.val('login_login0')}
</a>
)}
<Modal
className="loginRegisterModal"
style={{ padding: 0 }}
bodyStyle={{ padding: 0, margin: 0, border: 'none' }}
title={null}
width={836}
visible={visible}
zIndex={1000}
footer={null}
closeIcon={<Close />}
onCancel={() => setVisible(false)}
>
{visible && <LoginRegisterBox />}
</Modal>
</div>
);
}
export default LoginRegister;
+3
View File
@@ -0,0 +1,3 @@
import LoginRegister from './LoginRegister';
export default LoginRegister;
@@ -0,0 +1,27 @@
.loginRegister {
.loginRegisterBtn {
color: var(--theme-color1);
font-size: 14px;
}
}
:global {
.loginRegisterModal {
.semi-modal-content {
padding: 0 !important;
border: none !important;
}
.semi-modal-body-wrapper {
position: relative;
margin: 0 !important;
}
.semi-button.semi-button-with-icon-only.semi-button-size-small {
position: absolute;
right: 10px;
top: 10px;
svg {
font-size: 20px;
}
}
}
}
@@ -0,0 +1,175 @@
import styles from './styles.module.less';
import React, { useEffect, useState, useRef } from 'react';
import { Form, Input, Button, Row, Col, Divider, Toast } from '@douyinfe/semi-ui';
import { userService } from '@server/index';
import { pubsub } from '@utils/index';
import { config } from '@config/index';
import { language } from '@language/language';
import { stores } from '@stores/index';
function LoginEmail({ setShow }: any) {
const [captcha, setCaptcha] = useState({
key: '',
code: '',
});
const formRef = useRef<any>();
const formApiRef = useRef<any>();
const timer = useRef<any>();
const [time, setTime] = useState(60);
const onFinish = async (values: any) => {
// 1、登录成功后自动设置x-token
const [res, err] = await userService.login({
email: values.email,
code: values.emailCode,
type: 'email_code',
});
if (res) {
Toast.success(language.val('login_success'));
} else {
Toast.error(err);
}
if (err) {
// 切换验证码
getImageKey();
return;
}
// 2、获取用户详情,设置x-user-info
const [userRes, userError] = await userService.getUserDetail();
if (userRes) {
(window as any).RouterHistory.push(config.loginSuccessLink);
pubsub.publish('showLoginModal', false);
if (stores.editor.onLoginSuccess) {
userRes.token = res.token;
stores.editor.onLoginSuccess(userRes);
}
}
};
useEffect(() => {
getImageKey();
}, []);
const getImageKey = async () => {
const [res, err] = await userService.getCaptcha();
if (res) {
setCaptcha({
code: res.captcha_code,
key: res.captcha_key,
});
}
};
const getFormApi = formApi => {
formApiRef.current = formApi;
};
// 发送邮箱验证码
const sendEmailCode = async () => {
const { email, captchaCode } = formApiRef.current.getValues();
console.log('formApiRef.current', formApiRef.current.getValues());
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
Toast.error(language.val('login_email_error'));
return;
}
if (!captchaCode) {
Toast.error({ content: language.val('login_captcha_error'), duration: 10000 });
return;
}
// 发送验证码
const [res, err] = await userService.sendEmailCodeLogin({
email: email,
captchaCode: captchaCode,
captchaKey: captcha.key,
});
if (res) {
Toast.success(language.val('login_email_code_success'));
} else {
Toast.error(err);
}
let t = 60;
timer.current = setInterval(() => {
if (t - 1 === 0) {
clearInterval(timer.current);
setTime(60);
return;
}
t--;
setTime(t);
}, 1000);
};
useEffect(() => {
return () => {
if (timer.current) {
clearInterval(timer.current);
timer.current = null;
}
};
}, []);
return (
<div className={styles.loginMobile}>
<p className={styles.title}>
<span className={styles.text}>{language.val('login_email_login')}</span>
</p>
<Form name="basic" ref={formRef} getFormApi={getFormApi} onSubmit={onFinish}>
<Row gutter={8} className={styles.fromItem}>
<Col span={24}>
<Form.Input
noLabel
field="email"
rules={[
{ required: true, message: language.val('login_email_required') },
{ type: 'email', message: language.val('login_email_error') },
]}
placeholder={language.val('login_email_required')}
/>
</Col>
</Row>
<Row gutter={8} className={styles.fromItem}>
<Col span={16}>
<Form.Input
noLabel
field="captchaCode"
rules={[{ required: true, message: language.val('login_captcha_error') }]}
placeholder={language.val('login_captcha_error')}
/>
</Col>
<Col span={8}>
<img
onClick={getImageKey}
style={{ width: '100%', background: '#ccc', height: 32, display: 'flex', alignItems: 'center' }}
src={captcha.code}
alt=""
/>
</Col>
</Row>
<Row gutter={8} className={styles.fromItem}>
<Col span={16}>
<Form.Input
noLabel
field="emailCode"
rules={[{ required: true, message: language.val('login_email_code_required') }]}
placeholder={language.val('login_email_code_required')}
/>
</Col>
<Col span={8}>
<Button style={{ height: 35 }} block={true} onClick={sendEmailCode} disabled={time !== 60}>
{time === 60 ? language.val('login_code_send') : `${time}${language.val('login_code_send_tip')}`}
</Button>
</Col>
</Row>
<Row gutter={8} className={styles.fromBtnItem}>
<Col span={24}>
<Button type="primary" htmlType="submit" block={true}>
{language.val('login_login')}
</Button>
</Col>
</Row>
</Form>
</div>
);
}
export default LoginEmail;
+3
View File
@@ -0,0 +1,3 @@
import LoginEmail from './LoginEmail';
export default LoginEmail;
@@ -0,0 +1,19 @@
.loginMobile{
.title{
margin-bottom: 12px;
font-size: 22px;
}
.fromItem{
display: flex;
align-items: center;
:global{
.semi-form-field-error-message{
position: absolute;
bottom: -8px;
}
}
}
.fromBtnItem{
margin-top: 12px;
}
}
@@ -0,0 +1,176 @@
import styles from './login-mobile.module.less';
import React, { useEffect, useState, useRef } from 'react';
import { Form, Input, Button, Row, Col, Divider, Toast } from '@douyinfe/semi-ui';
import { userService } from '@server/index';
import { pubsub } from '@utils/index';
import { config } from '@config/index';
import { language } from '@language/language';
import { stores } from '@stores/index';
function LoginMobile({ setShow }: any) {
const [captcha, setCaptcha] = useState({
key: '',
code: '',
});
const formRef = useRef<any>();
const formApiRef = useRef<any>();
const timer = useRef<any>();
const [time, setTime] = useState(60);
const onFinish = async (values: any) => {
// 1、登录成功后自动设置x-token
// const res = await userService.login({ ...values, captchaKey: captcha.key });
const [res, err] = await userService.login({
mobile: values.telphone,
code: values.phoneCode,
type: 'mobile_code',
});
if (res) {
Toast.success(language.val('login_success'));
} else {
Toast.error(err);
}
if (err) {
// 切换验证码
getImageKey();
return;
}
// 2、获取用户详情,设置x-user-info
const [userRes, userError] = await userService.getUserDetail();
if (userRes) {
(window as any).RouterHistory.push(config.loginSuccessLink);
pubsub.publish('showLoginModal', false);
if (stores.editor.onLoginSuccess) {
userRes.token = res.token;
stores.editor.onLoginSuccess(userRes);
}
}
};
useEffect(() => {
getImageKey();
}, []);
const getImageKey = async () => {
const [res, err] = await userService.getCaptcha();
console.log(res);
if (res) {
setCaptcha({
code: res.captcha_code,
key: res.captcha_key,
});
}
};
const getFormApi = formApi => {
formApiRef.current = formApi;
};
// 发送手机验证码
const sendSMS = async () => {
console.log('formApiRef.current', formApiRef.current);
const { telphone, captchaCode } = formApiRef.current.getValues();
console.log('formApiRef.current', formApiRef.current.getValues());
if (!/^1\d{10}$/.test(telphone)) {
Toast.error(language.val('login_phone_format_error'));
return;
}
if (!captchaCode) {
Toast.error(language.val('login_captcha_error'));
return;
}
// 发送验证码
const [res, err] = await userService.getLoginSMS({
mobile: telphone,
captchaCode: captchaCode,
captchaKey: captcha.key,
});
if (res) {
Toast.success(language.val('login_phone_code_send_tip'));
} else {
Toast.error(err);
}
let t = 60;
timer.current = setInterval(() => {
if (t - 1 === 0) {
clearInterval(timer.current);
setTime(60);
return;
}
t--;
setTime(t);
}, 1000);
};
useEffect(() => {
return () => {
if (timer.current) {
clearInterval(timer.current);
timer.current = null;
}
};
}, []);
return (
<div className={styles.loginMobile}>
<p className={styles.title}>
<span className={styles.text}>{language.val('login_phone_login')}</span>
</p>
<Form name="basic" ref={formRef} getFormApi={getFormApi} onSubmit={onFinish}>
<Row gutter={8} className={styles.fromItem}>
<Col span={24}>
<Form.Input
noLabel
field="telphone"
rules={[{ required: true, message: language.val('login_phone_required') }]}
placeholder={language.val('login_phone_required')}
/>
</Col>
</Row>
<Row gutter={8} className={styles.fromItem}>
<Col span={16}>
<Form.Input
noLabel
field="captchaCode"
rules={[{ required: true, message: language.val('login_captcha_error') }]}
placeholder={language.val('login_captcha_error')}
/>
{/* <Input name="captchaCode" placeholder="请输入图形验证码" className={styles.codeNum}/> */}
</Col>
<Col span={8}>
<img
onClick={getImageKey}
style={{ width: '100%', background: '#ccc', height: 32, display: 'flex', alignItems: 'center' }}
src={captcha.code}
alt=""
/>
</Col>
</Row>
<Row gutter={8} className={styles.fromItem}>
<Col span={16}>
<Form.Input
noLabel
field="phoneCode"
rules={[{ required: true, message: language.val('login_phone_code_required') }]}
placeholder={language.val('login_phone_code')}
/>
</Col>
<Col span={8}>
<Button style={{ height: 35 }} block={true} onClick={sendSMS} disabled={time !== 60}>
{time === 60 ? language.val('login_code_send') : `${time}${language.val('login_code_send_tip')}`}
</Button>
</Col>
</Row>
<Row gutter={8} className={styles.fromBtnItem}>
<Col span={24}>
<Button type="primary" htmlType="submit" block={true}>
{language.val('login_login')}
</Button>
</Col>
</Row>
</Form>
</div>
);
}
export default LoginMobile;
@@ -0,0 +1,3 @@
import LoginMobile from './LoginMobile';
export default LoginMobile;
@@ -0,0 +1,19 @@
.loginMobile{
.title{
margin-bottom: 12px;
font-size: 22px;
}
.fromItem{
display: flex;
align-items: center;
:global{
.semi-form-field-error-message{
position: absolute;
bottom: -8px;
}
}
}
.fromBtnItem{
margin-top: 12px;
}
}
@@ -0,0 +1,86 @@
import styles from './login-qrcode.module.less';
import React, { Component } from 'react';
import { userService } from '@server/index';
import { pubsub } from '@utils/index';
import { config } from '@config/index';
import { Wechat, Phone } from '@icon-park/react';
import { language } from '@language/language';
import { stores } from '@stores/index';
interface IProps {}
interface IState {
url: string;
sn: string;
}
class LoginQrcode extends Component<IProps, IState> {
timer: any;
constructor(props: any) {
super(props);
this.state = {
url: '',
sn: '',
};
}
// 轮询监测登录状态
seekLogin = async (sn: string) => {
this.timer = setTimeout(async () => {
const [res] = await userService.seekWxLogin(sn);
if (!res) {
this.seekLogin(sn);
} else {
clearTimeout(this.timer);
// 获取到token了
userService._setRqHeaderToken(res.token);
// 2、获取用户详情,设置x-user-info
const [ress] = await userService.getUserDetail();
if (ress) {
// 登录成功回调
pubsub.publish('showLoginModal', false);
ress.token = res.token;
stores.editor.onLoginSuccess?.(ress);
// location.reload();
// (window as any).RouterHistory.push(config.loginSuccessLink);
}
}
}, 3000);
};
doQrcode = async () => {
const [res] = await userService.getWxQrcode();
this.setState({
url: res.url,
sn: res.sn,
});
// 轮询登录
this.seekLogin(res.sn);
};
componentDidMount() {
this.doQrcode();
}
componentWillUnmount() {
if (this.timer) {
clearTimeout(this.timer);
}
}
render() {
const { url } = this.state;
return (
<div className={styles.loginQrcode}>
<p className={styles.title}>
<Wechat theme="filled" size="28" fill="#4ab70f" />
<span className={styles.text}>{language.val('login_wechat_login')}</span>
</p>
<img style={{ width: 160 }} src={url || 'https://cdn.h5ds.com/static/images/qrcode-loading.png'} alt="" />
</div>
);
}
}
export default LoginQrcode;
@@ -0,0 +1,3 @@
import LoginQrcode from './LoginQrcode';
export default LoginQrcode;
@@ -0,0 +1,15 @@
.loginQrcode {
text-align: center;
padding: 20px;
.title {
display: flex;
align-items: center;
justify-content: center;
margin: 30px;
font-size: 18px;
.text{
margin-left: 5px;
}
}
}
@@ -0,0 +1,124 @@
import styles from './login-register-box.module.less';
import React, { useState, useEffect, useRef } from 'react';
import { config } from '@config/index';
import { Divider, Toast } from '@douyinfe/semi-ui';
import LoginQrcode from '../loginQrcode';
import LoginMobile from '../loginMobile';
import LoginEmail from '../loginEmail';
import { userService } from '@server/index';
import { Wechat, Phone, Check, MailPackage } from '@icon-park/react';
import { language } from '@language/language';
import classNames from 'classnames';
function LoginRegisterBox() {
const [show, setShow] = useState(language.getLanguage() === 'zh-CN' ? 'loginQrcode' : 'loginEmail');
// const showOAuthWindow = () => {
// let url = `${config.apiHost}/account/login/provider/qq?type=login`;
// window.open(url, '', 'width=500,height=500,channelmode=yes');
// };
const handlePostMessage = async (evt: any) => {
if (evt.data.msgType !== 'oauth-login') {
return;
}
const { provider, code } = evt.data;
if (provider) {
const hide = Toast.info(language.val('login_loading'));
await userService.oauthLogin(code);
Toast.close(hide);
(window as any).RouterHistory.push(location.pathname);
}
};
useEffect(() => {
window.addEventListener('message', handlePostMessage);
return () => {
window.removeEventListener('message', handlePostMessage);
};
});
return (
<div className={styles.loginRegisterBox}>
<div className={styles.loginRegisterInfo}>
<h1>{language.val('common_name')}</h1>
<p>
<Check theme="filled" size="16" fill="#98ff00" />
{language.val('login_switch_lens')}
</p>
<p>
<Check theme="filled" size="16" fill="#98ff00" />
{language.val('login_ai_subtitle')}
</p>
<p>
<Check theme="filled" size="16" fill="#98ff00" />
{language.val('login_ai_animation')}
</p>
<p>
<Check theme="filled" size="16" fill="#98ff00" />
{language.val('login_export_4k')}
</p>
<p>
<Check theme="filled" size="16" fill="#98ff00" />
{language.val('login_lut_filter')}
</p>
{/* <p>
<Check theme="filled" size="16" fill="#98ff00" />
{language.val('login_free_material')}
</p> */}
<p>
<Check theme="filled" size="16" fill="#98ff00" />
{language.val('login_exclusive_plugin')}
</p>
<p>
<Check theme="filled" size="16" fill="#98ff00" />
{language.val('login_no_download')}
</p>
<p>
<Check theme="filled" size="16" fill="#98ff00" />
{language.val('login_cloud_storage')}
</p>
</div>
<div className={styles.loginRegisterForm}>
<div className={styles.loginRegisterTabs}>
{show === 'loginQrcode' && <LoginQrcode />}
{show === 'loginMobile' && <LoginMobile setShow={setShow} />}
{show === 'loginEmail' && <LoginEmail setShow={setShow} />}
</div>
<Divider>{language.val('login_other_login')}</Divider>
<div className={styles.loginRegisterActions}>
<a
className={classNames(styles.item, {
[styles.active]: show === 'loginEmail',
})}
onClick={() => setShow('loginEmail')}
>
<MailPackage theme="filled" size="24" fill="#666" />
<span>{language.val('login_email_login')}</span>
</a>
<a
className={classNames(styles.item, {
[styles.active]: show === 'loginMobile',
})}
onClick={() => setShow('loginMobile')}
>
<Phone theme="filled" size="24" fill="#666" />
<span>{language.val('login_phone_login')}</span>
</a>
<a
className={classNames(styles.item, {
[styles.active]: show === 'loginQrcode',
})}
onClick={() => setShow('loginQrcode')}
>
<Wechat theme="filled" size="24" fill="#666" />
<span>{language.val('login_wechat_login')}</span>
</a>
</div>
</div>
</div>
);
}
export default LoginRegisterBox;
Whitespace-only changes.
@@ -0,0 +1,83 @@
.loginRegisterBox {
display: flex;
// padding-bottom: 20px;
.loginRegisterInfo {
width: 406px;
padding: 40px 60px;
background: linear-gradient(315deg, #7454ff 0%, #1261ff 100%);
img {
width: 100%;
}
h1 {
color: #ffff;
font-weight: bolder;
margin-bottom: 40px;
}
& > p {
color: #ffff;
background-color: rgba(255, 255, 255, 0.2);
margin-bottom: 10px;
padding: 10px;
border-radius: 100px;
font-size: 15px;
display: flex;
align-items: center;
:global {
.i-icon {
margin-right: 10px;
}
}
}
}
.loginRegisterForm {
width: 430px;
display: flex;
justify-content: center;
flex-direction: column;
}
.loginRegisterTabs {
margin: 0 50px 40px 50px;
.loginRegisterTitle {
font-size: 24px;
padding-top: 40px;
padding-bottom: 30px;
}
}
.loginRegisterActions {
text-align: center;
display: flex;
justify-content: center;
margin-top: 40px;
.item {
margin: 0 20px;
color: var(--theme-color1);
}
.active {
color: var(--theme-main);
path{
stroke: var(--theme-main);
}
}
.webfont {
font-size: 24px;
}
span {
display: block;
font-size: 12px;
}
}
.loginFooter {
padding-top: 20px;
}
}
@@ -0,0 +1,117 @@
import styles from './styles.module.less';
import { Form, Toast, Button } from '@douyinfe/semi-ui';
import { userService } from '@server/user.service';
import { useState, useEffect } from 'react';
import { pubsub, storage, crypto } from '@utils/index';
import { language } from '@language/language';
export interface IProps {}
export default function AccountLogin(props: IProps) {
const [captcha, setCaptcha] = useState({
key: '',
code: '',
});
const handleSubmit = async values => {
console.log(values);
const [res, err] = await userService.login({
account: values.account,
password: values.password,
captchaCode: values.code,
captchaKey: captcha.key,
});
if (values.rememberPassword) {
storage.local.set('account', crypto.encrypt(values.account));
storage.local.set('password', crypto.encrypt(values.password));
} else {
storage.local.remove('account');
storage.local.remove('password');
}
if (res) {
Toast.success(language.val('login_success'));
} else {
Toast.error(err);
}
if (err) {
// 切换验证码
getImageKey();
return;
}
// 2、获取用户详情,设置x-user-info
const [userRes, userError] = await userService.getUserDetail();
if (userRes) {
(window as any).RouterHistory.push('/workspace/draft');
pubsub.publish('showLoginModal', false);
}
};
useEffect(() => {
getImageKey();
}, []);
const getImageKey = async () => {
const [res, err] = await userService.getCaptcha();
if (res) {
setCaptcha({
code: res.captcha_code,
key: res.captcha_key,
});
}
};
return (
<div className={styles.forms}>
<Form
initValues={{
account: crypto.decrypt(storage.local.get('account')),
password: crypto.decrypt(storage.local.get('password')),
}}
onSubmit={values => handleSubmit(values)}
style={{ width: '100%' }}
>
{({ formState, values, formApi }) => (
<>
<Form.Input
field="account"
label={language.val('login_account')}
style={{ width: '100%' }}
placeholder={language.val('login_account_tip')}
></Form.Input>
<Form.Input
mode="password"
field="password"
label={language.val('login_password')}
style={{ width: '100%' }}
placeholder={language.val('login_password_tip')}
></Form.Input>
<div className={styles.formSpaceItem}>
<Form.Input
field="code"
label={language.val('login_code')}
style={{ width: 230 }}
placeholder={language.val('login_code_tip')}
></Form.Input>
<img className={styles.captcha} onClick={getImageKey} src={captcha.code} alt="" />
</div>
<div className={styles.formSpaceItem}>
<Form.Checkbox field="rememberPassword" noLabel>
{language.val('login_remember_password')}
</Form.Checkbox>
</div>
<Button
block
disabled={!values.account || !values.password || !values.code}
htmlType="submit"
type="primary"
>
{language.val('login_login')}
</Button>
</>
)}
</Form>
</div>
);
}
@@ -0,0 +1,3 @@
import AccountLogin from './AccountLogin';
export default AccountLogin;
@@ -0,0 +1,16 @@
.forms {
font-size: 14px;
}
.formSpaceItem {
display: flex;
justify-content: space-between;
align-items: center;
}
.captcha {
height: 30px;
position: relative;
top: 12px;
cursor: pointer;
}
+25
View File
@@ -0,0 +1,25 @@
import styles from './not-found.module.less';
import React, { Component } from 'react';
export default class NotFound extends Component {
toHome = () => {
location.href = '/';
}
render() {
return (
<div className={styles["not-found"]}>
<div className={styles["not-found-title"]}>404----</div>
<div className={styles["not-found-info"]}>Page Not Found</div>
<div className={styles["not-found-content"]}>
<p>对不起,没有找到您所需要的页面,可能是URL不确定,或者页面已被移除。</p>
<a type="primary" onClick={this.toHome}>
Back Home
</a>
</div>
</div>
);
}
}
+3
View File
@@ -0,0 +1,3 @@
import NotFound from './NotFound';
export default NotFound;
@@ -0,0 +1,29 @@
.not-found {
.not-found-title {
padding-top: 100px;
font-size: 40px;
font-weight: 700;
text-align: center;
line-height: 64px;
color: #838fa1;
}
.not-found-info {
line-height: 30px;
font-size: 21px;
padding-top: 20px;
text-align: center;
color: #dce2ec;
}
.not-found-content {
padding: 20px 0;
font-size: 16px;
text-align: center;
color: #96a2b4;
p {
padding-bottom: 30px;
}
}
}
@@ -0,0 +1,92 @@
import styles from './style.module.less';
import React, { useEffect, useRef, useReducer } from 'react';
import { pubsub } from '@utils/pubsub';
import { Progress } from '@douyinfe/semi-ui';
export interface ProgressData {
progress: number; // 手动传入进度:?: number | undefined
start: boolean; // 开始 ?: boolen
end: boolean; // 结束 ?:boolen
time: number; // 默认加载时间间隔
}
/**
* 用法:
* pubsub.publish('pageLoading', {
start: true
});
pubsub.publish('pageLoading', {
end: true
});
*/
export default function PageLoading() {
const [, forceUpdate] = useReducer(x => x + 1, 0);
const val = useRef<any>(null);
const reRender = useRef(0);
const timer = useRef<any>();
const autoLoading = (time = 50) => {
timer.current = setTimeout(() => {
val.current = val.current + (90 - val.current) / 10;
forceUpdate();
autoLoading();
}, time);
};
useEffect(() => {
/**
* data: {
* progress: undefined, // 手动传入进度:?: number | undefined
* start, // 开始 ?: boolen
* end, // 结束 ?:boolen
* time: 1000 // 默认加载时间间隔
* }
*/
pubsub.subscribe('pageLoading', (_eventName, data: ProgressData) => {
console.log('data--->', data);
if (timer.current) {
reRender.current++;
clearTimeout(timer.current);
timer.current = null;
}
if (data.progress !== undefined) {
val.current = data.progress;
forceUpdate();
} else if (data.start) {
val.current = 0;
forceUpdate();
autoLoading(data.time);
} else if (data.end) {
val.current = 100;
forceUpdate();
timer.current = setTimeout(() => {
val.current = null;
forceUpdate();
}, 400);
}
});
return () => {
clearTimeout(timer.current);
pubsub.unsubscribe('pageLoading');
};
}, []);
if (val.current === null) {
return null;
}
return (
<div className={styles.loading}>
<Progress
key={reRender.current}
showInfo={false}
strokeWidth={3}
percent={val.current}
// strokeColor="#FF7900"
// trailColor="#ffd7b4"
size="small"
/>
</div>
);
}
+3
View File
@@ -0,0 +1,3 @@
import PageLoading from './PageLoading';
export default PageLoading;
@@ -0,0 +1,10 @@
.loading {
position: fixed;
top: -1px;
width: 100%;
z-index: 9999;
line-height: 0;
:global(.ant-progress){
line-height: 0;
}
}
+17
View File
@@ -0,0 +1,17 @@
import styles from './styles.module.less';
export interface IProps {
title: string;
desc: string;
}
export default function SubHeader(props: IProps) {
return (
<div className={styles.bg}>
<span>
<h2>{props.title}</h2>
<p>{props.desc}</p>
</span>
</div>
);
}
View File
Whitespace-only changes.
@@ -0,0 +1,16 @@
.bg {
height: 240px;
margin-top: 60px;
background-image: url('/assets/images/userbg.png');
background-repeat: no-repeat;
display: flex;
justify-content: center;
align-items: center;
text-align: center;
color: #fff;
h2 {
font-weight: bolder;
margin-bottom: 20px;
font-size: 38px;
}
}
+95
View File
@@ -0,0 +1,95 @@
// import { util } from '@utils/index';
// import { useEffect, useState } from 'react';
import { useResizeDetector } from 'react-resize-detector';
import styles from './waterfull.module.less';
import IconSpin from '@douyinfe/semi-icons/lib/es/icons/IconSpin';
import classNames from 'classnames';
export interface IProps {
list?: any[];
itemWidth?: number;
style?: Record<string, any>;
item?: any;
sType?: string;
columns?: number;
itemClassName?: string;
itemHeight?: boolean; // 固定高度
}
// const defaultList = new Array(40).fill(1).map((d, i) => {
// return {
// width: util.randomNum(300, 500),
// height: util.randomNum(100, 600),
// };
// });
export default function WaterFall(props: IProps) {
const { width = 0, ref } = useResizeDetector();
const list = props.list;
const minHeight = 60;
return (
<div className={styles.list} style={{ ...(props.style || {}) }} ref={ref}>
{!list && <IconSpin spin />}
{list &&
(() => {
// 每个item的宽度,间隙默认是10px,反向计算出宽度
let itemWidth = props.itemWidth || 120;
const gap = 5;
let columns = props.columns ? props.columns : ~~(width / (itemWidth + gap));
if (!columns) {
columns = 1;
}
itemWidth = ~~((width - (columns - 1) * gap) / columns);
// 瀑布流算法,自动计算高度和坐标
const columItems: any[][] = [];
const totalHeight = new Array(columns).fill(0);
if (columns === 1) {
columItems.push(list);
} else {
list.forEach(elem => {
const min = Math.min(...totalHeight);
const index = totalHeight.findIndex(a => a === min);
// 最大高度不能超过宽度的2倍
let itemHeight = Math.min(itemWidth * (elem.height / elem.width), itemWidth * 2);
itemHeight = Math.max(itemHeight, minHeight);
totalHeight[index] += itemHeight + gap;
if (!columItems[index]) {
columItems[index] = [];
}
columItems[index].push(elem);
});
}
return columItems.map((items, i) => {
return (
<div
key={i}
className={styles.colums}
style={{ marginLeft: i !== 0 ? gap : 0, width: (width - (columns - 1) * gap) / columns }}
>
{items.map(d => {
let hei = Math.min(~~(itemWidth * (d.height / d.width)), itemWidth * 2);
return (
<div
key={d.id}
className={classNames(styles.itemWrap, props.itemClassName)}
style={{
width: itemWidth,
height: props.itemHeight ? 'auto' : Math.max(hei, 60),
marginBottom: gap,
}}
>
{props.item ? props.item(d) : null}
</div>
);
})}
</div>
);
});
})()}
</div>
);
}
+3
View File
@@ -0,0 +1,3 @@
import WaterFull from './WaterFull';
export default WaterFull;
@@ -0,0 +1,15 @@
.list {
margin: 0 10px 0 20px;
overflow-x: hidden;
.colums {
vertical-align: top;
display: inline-block;
}
.itemWrap {
background-color: var(--theme-wateritem);
border-radius: 3px;
overflow: hidden;
}
}