This commit is contained in:
2026-01-30 17:03:32 +08:00
parent 06a12b5052
commit f9adaeca4d
44 changed files with 10227 additions and 0 deletions

View File

@@ -0,0 +1,104 @@
import { useShallow } from 'zustand/shallow';
import { getCurrentContent, getFileUrl, useMenuStore } from './store/menu';
import { useEffect, useState } from 'react';
import { checkText } from './modules/get-content-type';
import { TextEditor } from './editor/text/TextEditor';
import { useEditStore } from './store/edit';
import { FileText, FileType } from 'lucide-react';
import { ImagePreview } from './preview/ImagePreview';
import { PdfPreview } from './preview/PdfPreview';
export const Content: React.FC = () => {
const { currentPath } = useMenuStore(
useShallow((state) => ({
currentPath: state.currentPath,
})),
);
const [content, setContent] = useState<string | null>(null);
const [fileUrl, setFileUrl] = useState<string | null>(null);
const { type, setType } = useEditStore(
useShallow((state) => ({
type: state.type,
setType: state.setType,
})),
);
useEffect(() => {
const fetchContent = async () => {
if (!currentPath) return;
const checkResult = checkText(currentPath);
if (checkResult.type === 'unsupported') {
setContent('This file type is not supported for viewing.');
setFileUrl(null);
setType('');
return;
}
if (checkResult.type === 'image' || checkResult.type === 'pdf') {
setContent(null);
const url = await getFileUrl(currentPath);
setFileUrl(url);
setType(checkResult.type);
return;
}
// text
setFileUrl(null);
setContent('Loading content...');
const textContent = await getCurrentContent(currentPath);
setContent(textContent || '');
setType('text');
};
fetchContent();
}, [currentPath]);
// 清理 URL
useEffect(() => {
return () => {
if (fileUrl) {
URL.revokeObjectURL(fileUrl);
}
};
}, [fileUrl]);
// 空状态
if (!currentPath) {
return (
<div className='h-full w-full flex items-center justify-center bg-white dark:bg-black'>
<div className='text-center text-gray-400'>
<FileText className='w-12 h-12 mx-auto mb-3 opacity-50' />
<p className='text-sm'></p>
</div>
</div>
);
}
return (
<div className='h-full w-full overflow-hidden bg-white dark:bg-black'>
<div className='flex flex-col w-full h-full relative'>
{type === 'text' && content && (
<div className='w-full h-full'>
<TextEditor filepath={currentPath!} content={content} />
</div>
)}
{type === 'image' && fileUrl && (
<ImagePreview src={fileUrl} alt={currentPath.split('/').pop()} />
)}
{type === 'pdf' && fileUrl && (
<PdfPreview src={fileUrl} fileName={currentPath.split('/').pop()} />
)}
{type === '' && content && (
<div className='h-full w-full flex items-center justify-center'>
<div className='text-center text-gray-500'>
<FileType className='w-12 h-12 mx-auto mb-3 opacity-50' />
<p className='text-sm'>{content}</p>
</div>
</div>
)}
</div>
</div>
);
};

View File

@@ -0,0 +1,80 @@
import CodeMirror from '@uiw/react-codemirror';
import { javascript } from '@codemirror/lang-javascript';
import { html } from '@codemirror/lang-html';
import { markdown } from '@codemirror/lang-markdown';
import { json } from '@codemirror/lang-json';
import { css } from '@codemirror/lang-css';
import { useMemo } from 'react';
type TextEditorProps = {
filepath: string;
content: string;
onChange?: (value: string) => void;
};
const getExtension = (filepath: string) => {
const ext = filepath.split('.').pop()?.toLowerCase();
switch (ext) {
case 'html':
case 'htm':
return [html()];
case 'md':
case 'markdown':
return [markdown()];
case 'js':
case 'jsx':
case 'ts':
case 'tsx':
return [javascript({ jsx: true, typescript: true })];
case 'json':
return [json()];
case 'css':
case 'scss':
case 'less':
return [css()];
default:
return [javascript()];
}
};
export const TextEditor = ({ filepath, content, onChange }: TextEditorProps) => {
const extensions = useMemo(() => getExtension(filepath), [filepath]);
return (
<div className='h-full overflow-y-auto overflow-x-hidden'>
<CodeMirror
value={content}
extensions={extensions}
onChange={onChange}
className='h-full text-sm'
height='100%'
basicSetup={{
lineNumbers: true,
highlightActiveLineGutter: true,
highlightSpecialChars: true,
history: true,
foldGutter: true,
drawSelection: true,
dropCursor: true,
allowMultipleSelections: true,
indentOnInput: true,
syntaxHighlighting: true,
bracketMatching: true,
closeBrackets: true,
autocompletion: true,
rectangularSelection: true,
crosshairCursor: true,
highlightActiveLine: true,
highlightSelectionMatches: true,
closeBracketsKeymap: true,
defaultKeymap: true,
searchKeymap: true,
historyKeymap: true,
foldKeymap: true,
completionKeymap: true,
lintKeymap: true,
}}
/>
</div>
);
};

View File

@@ -0,0 +1,50 @@
import Sidebar from './sidebar';
import { Content } from './content';
import { Panel, Group, Separator } from 'react-resizable-panels';
import { Toolbar } from './modules/Nav';
import { Toaster } from 'sonner';
const Provider = ({ children }: { children: React.ReactNode }) => {
return (
<>
{children}
<Toaster position="bottom-right" richColors />
</>
);
};
export const App = () => {
return (
<Provider>
<AIEditor />
</Provider>
);
};
export const SidebarApp = () => {
return (
<Provider>
<Sidebar />
</Provider>
);
};
export const AIEditor = () => {
return (
<div className='h-screen w-full flex flex-col bg-white dark:bg-black text-gray-900 dark:text-gray-100'>
<div className='h-16 shrink-0 text-xl font-bold border-b border-gray-200 dark:border-gray-800 p-3 flex gap-2 items-center bg-gray-50 dark:bg-gray-950'>
<span className='font-mono text-sm tracking-tight'>Codepod</span>
<Toolbar />
</div>
<div className='flex-1 min-h-0'>
<Group orientation="horizontal">
<Panel minSize={200} defaultSize={240} maxSize={400}>
<Sidebar />
</Panel>
<Separator className='bg-gray-200 dark:bg-gray-800 w-px' />
<Panel minSize={30}>
<Content />
</Panel>
</Group>
</div>
</div>
);
};

View File

@@ -0,0 +1,35 @@
import { Button } from '@/components/ui/button';
import { useMenuStore } from '../store/menu';
import { useShallow } from 'zustand/shallow';
import { useEditStore } from '../store/edit';
import { Save } from 'lucide-react';
export const Toolbar = () => {
const store = useMenuStore(
useShallow((state) => {
return {
onSaveText: state.onSaveText,
};
}),
);
const editStore = useEditStore(
useShallow((state) => {
return {
type: state.type,
setType: state.setType,
};
}),
);
return (
<div className='optrate-bar flex-1 flex justify-end items-center gap-2 h-full'>
<div className=''>
{editStore.type && (
<Button size={'sm'} variant='ghost' onClick={() => store.onSaveText()}>
<Save className='w-4 h-4' />
</Button>
)}
</div>
</div>
);
};

View File

@@ -0,0 +1,43 @@
export const checkText = (filepath: string) => {
const textExtensions = [
'.txt',
'.md',
'.json',
'.js',
'.ts',
'.html',
'.css',
'.xml',
'.csv',
'.tsx',
'.jsx',
'.mjs',
'.cjs',
'.vue',
'.yaml',
'.yml',
'.log',
'.conf',
'.env',
'.example', //
];
const imageExtensions = ['.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg', '.bmp', '.ico'];
const pdfExtensions = ['.pdf'];
const extension = filepath.split('.').pop()?.toLowerCase();
if (textExtensions.includes(`.${extension}`)) {
return { type: 'text' as const };
}
if (imageExtensions.includes(`.${extension}`)) {
return { type: 'image' as const };
}
if (pdfExtensions.includes(`.${extension}`)) {
return { type: 'pdf' as const };
}
return { type: 'unsupported' as const };
};

View File

@@ -0,0 +1,18 @@
interface ImagePreviewProps {
src: string;
alt?: string;
}
export const ImagePreview: React.FC<ImagePreviewProps> = ({ src, alt }) => {
return (
<div className='h-full w-full flex items-center justify-center p-4 bg-gray-50 dark:bg-gray-900'>
<div className='relative max-w-full max-h-full'>
<img
src={src}
alt={alt || 'Image preview'}
className='max-w-full max-h-[calc(100vh-120px)] object-contain rounded-lg shadow-lg'
/>
</div>
</div>
);
};

View File

@@ -0,0 +1,19 @@
interface PdfPreviewProps {
src: string;
fileName?: string;
}
export const PdfPreview: React.FC<PdfPreviewProps> = ({ src, fileName }) => {
return (
<div className='h-full w-full flex flex-col bg-gray-50 dark:bg-gray-900'>
<div className='flex-1 w-full'>
<embed
src={src}
type='application/pdf'
className='w-full h-full'
title={fileName}
/>
</div>
</div>
);
};

View File

@@ -0,0 +1,455 @@
import React, { useState, useMemo, useEffect, useRef } from 'react';
import { File, Folder, ChevronRight, ChevronDown, Loader2, FilePlus, FolderPlus, Trash2, Rocket, Upload, Pencil } from 'lucide-react';
import { useMenuStore, init, queryResources } from './store/menu.ts';
import { toast } from 'sonner';
import type { MenuItem } from './store/menu.ts';
import { isSemVer } from './utils/version.ts';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import {
ContextMenu,
ContextMenuContent,
ContextMenuItem,
ContextMenuSeparator,
ContextMenuTrigger,
} from '@/components/ui/context-menu';
// 辅助函数:获取目录的直接子项
const getDirectChildren = (path: string, menu: MenuItem[]): MenuItem[] => {
const pathPrefix = path ? path + '/' : '';
return menu.filter((item) => {
if (!item.path.startsWith(pathPrefix)) return false;
if (item.path === path) return false;
const relativePath = item.path.slice(pathPrefix.length);
return !relativePath.includes('/');
});
};
interface DirectoryItemProps {
item: MenuItem;
level: number;
prefix?: string;
}
// 上传文件组件
const UploadFileItem: React.FC<{ parentPath: string }> = ({ parentPath }) => {
const fileInputRef = useRef<HTMLInputElement>(null);
const { refreshMenu } = useMenuStore();
const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
console.log('Selected file:', file);
if (!file) return;
const loadingToast = toast.loading('正在上传文件...');
const path = parentPath ? `${parentPath}/${file.name}` : file.name;
try {
const res = await queryResources.uploadFile(path, file);
toast.dismiss(loadingToast);
if (res.code === 200) {
toast.success('上传成功');
await refreshMenu();
} else {
toast.error(`上传失败: ${res.message}`);
}
} catch (error) {
toast.dismiss(loadingToast);
toast.error('上传失败');
}
// 重置 input
if (fileInputRef.current) {
fileInputRef.current.value = '';
}
};
return (
<>
<ContextMenuItem
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
fileInputRef.current?.click();
}}>
<Upload className='mr-2 h-4 w-4' />
</ContextMenuItem>
<input
type='file'
ref={fileInputRef}
className='hidden'
onChange={handleFileChange}
/>
</>
);
};
const ContextMenuDialogItem: React.FC<{
icon: React.ReactNode;
label: string;
title: string;
onConfirm: (name: string) => Promise<void>;
}> = ({ icon, label, title, onConfirm }) => {
const [open, setOpen] = useState(false);
const [inputValue, setInputValue] = useState('');
const handleOpen = (e: Event) => {
e.preventDefault();
e.stopPropagation();
setOpen(true);
};
const handleConfirm = async () => {
if (!inputValue.trim()) return;
await onConfirm(inputValue.trim());
setOpen(false);
setInputValue('');
};
return (
<>
<ContextMenuItem onSelect={handleOpen}>
{icon}
{label}
</ContextMenuItem>
<Dialog open={open} onOpenChange={(v) => { if (!v) setInputValue(''); setOpen(v); }}>
<DialogContent onCloseAutoFocus={(e) => e.preventDefault()}>
<DialogHeader>
<DialogTitle>{title}</DialogTitle>
</DialogHeader>
<Input
placeholder='请输入名称'
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
handleConfirm();
}
}}
autoFocus
/>
<DialogFooter>
<Button variant='outline' onClick={() => setOpen(false)}>
</Button>
<Button onClick={handleConfirm} disabled={!inputValue.trim()}>
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</>
);
};
// 重命名组件
const RenameItem: React.FC<{
path: string;
originalName: string;
onRename: (oldPath: string, newName: string) => Promise<void>;
}> = ({ path, originalName, onRename }) => {
const [open, setOpen] = useState(false);
const [inputValue, setInputValue] = useState(originalName);
const handleOpen = (e: Event) => {
e.preventDefault();
e.stopPropagation();
setOpen(true);
};
const handleConfirm = async () => {
const newName = inputValue.trim();
if (!newName || newName === originalName) {
setOpen(false);
return;
}
await onRename(path, newName);
setOpen(false);
setInputValue(originalName);
};
return (
<>
<ContextMenuItem onSelect={handleOpen}>
<Pencil className='mr-2 h-4 w-4' />
</ContextMenuItem>
<Dialog open={open} onOpenChange={(v) => { if (!v) setInputValue(originalName); setOpen(v); }}>
<DialogContent onCloseAutoFocus={(e) => e.preventDefault()}>
<DialogHeader>
<DialogTitle></DialogTitle>
</DialogHeader>
<Input
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
handleConfirm();
}
}}
autoFocus
/>
<DialogFooter>
<Button variant='outline' onClick={() => setOpen(false)}>
</Button>
<Button onClick={handleConfirm} disabled={!inputValue.trim() || inputValue.trim() === originalName}>
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</>
);
};
const DirectoryItem: React.FC<DirectoryItemProps> = ({ item, level, prefix }) => {
const [expanded, setExpanded] = useState(false);
const { menu, createFile, createDirectory, deleteItem, renameItem } = useMenuStore();
const children = useMemo(() => {
const children = getDirectChildren(item.path, menu);
return children.sort((a, b) => {
if (a.type === 'directory' && b.type === 'file') return -1;
if (a.type === 'file' && b.type === 'directory') return 1;
return a.path.localeCompare(b.path);
});
}, [menu, item.path]);
const directory = item.path.replace(prefix || '', '').replace(/\/$/, '') || '/';
const newPrefix = item.path + '/';
const handleDelete = async () => {
const path = item.type === 'directory' ? `${item.path}/` : item.path;
await deleteItem(path);
};
const handleRename = async (oldPath: string, newName: string) => {
const parts = oldPath.split('/');
parts.pop();
const parentPath = parts.join('/');
const newPath = parentPath ? `${parentPath}/${newName}/` : `${newName}/`;
await renameItem(oldPath + '/', newPath);
};
const handleDeploy = async () => {
console.log('Deploy app with version:', item.path);
toast.info('正在部署应用,部署功能尚未实现');
};
// 判断文件夹名是否为版本号格式 (如 v1.0.0, 1.0.0)
const isVersionNumber = isSemVer(directory);
return (
<div>
<ContextMenu>
<ContextMenuTrigger asChild>
<div
className='flex items-center cursor-pointer py-1.5 px-2 hover:bg-gray-100 dark:hover:bg-gray-900 rounded group transition-colors shrink-0'
style={{ paddingLeft: `${level * 12}px` }}
onClick={() => setExpanded(!expanded)}>
<div className='flex items-center shrink-0'>
{children.length > 0 ? (
expanded ? (
<ChevronDown className='w-4 h-4 text-gray-400' />
) : (
<ChevronRight className='w-4 h-4 text-gray-400' />
)
) : (
<div className='w-4 h-4' />
)}
</div>
<Folder className='w-4 h-4 ml-2 mr-1.5 text-gray-600 dark:text-gray-400 shrink-0' />
<span className='text-sm truncate text-gray-700 dark:text-gray-300 min-w-0 flex-1'>{directory}</span>
</div>
</ContextMenuTrigger>
<ContextMenuContent className='w-48 border-gray-200 dark:border-gray-700'>
{isVersionNumber && (
<>
<ContextMenuItem onClick={handleDeploy}>
<Rocket className='mr-2 h-4 w-4' />
</ContextMenuItem>
<ContextMenuSeparator />
</>
)}
<ContextMenuDialogItem
icon={<FilePlus className='mr-2 h-4 w-4' />}
label='新建文件'
title='新建文件'
onConfirm={async (name) => {
await createFile(item.path, name);
}}
/>
<ContextMenuDialogItem
icon={<FolderPlus className='mr-2 h-4 w-4' />}
label='新建文件夹'
title='新建文件夹'
onConfirm={async (name) => {
await createDirectory(item.path, name);
}}
/>
<UploadFileItem parentPath={item.path} />
<RenameItem path={item.path} originalName={directory} onRename={handleRename} />
<ContextMenuSeparator />
<ContextMenuItem onClick={handleDelete} className='text-red-600 focus:text-red-600'>
<Trash2 className='mr-2 h-4 w-4' />
</ContextMenuItem>
</ContextMenuContent>
</ContextMenu>
{expanded && children.length > 0 && (
<div className='ml-2'>
{children.map((child) =>
child.type === 'directory' ? (
<DirectoryItem key={child.path} item={child} prefix={newPrefix} level={level + 1} />
) : (
<FileItem key={child.path} item={child} prefix={newPrefix} level={level + 1} />
),
)}
</div>
)}
</div>
);
};
interface FileItemProps {
item: MenuItem;
level: number;
prefix?: string;
}
const FileItem: React.FC<FileItemProps> = ({ item, level }) => {
const { currentPath, setCurrentPath, deleteItem, renameItem } = useMenuStore();
const handleDelete = async () => {
await deleteItem(item.path);
};
const handleRename = async (oldPath: string, newName: string) => {
const parts = oldPath.split('/');
parts.pop();
const parentPath = parts.join('/');
const newPath = parentPath ? `${parentPath}/${newName}` : newName;
await renameItem(oldPath, newPath);
};
const fileName = item.path.split('/').pop() || '';
return (
<ContextMenu>
<ContextMenuTrigger asChild>
<div
className={`flex items-center cursor-pointer py-1.5 px-2 hover:bg-gray-100 dark:hover:bg-gray-900 rounded transition-colors shrink-0 ${currentPath === item.path ? 'bg-gray-100 dark:bg-gray-900' : ''
}`}
style={{ paddingLeft: `${level * 12}px` }}
onClick={() => setCurrentPath(item.path)}>
<div className='flex items-center shrink-0'>
<div className='w-4 h-4' />
</div>
<File className='w-4 h-4 ml-2 mr-1.5 text-gray-500 dark:text-gray-400 shrink-0' />
<span className='text-sm truncate text-gray-700 dark:text-gray-300 min-w-0 flex-1'>{fileName}</span>
</div>
</ContextMenuTrigger>
<ContextMenuContent className='w-48 border-gray-200 dark:border-gray-700'>
<RenameItem path={item.path} originalName={fileName} onRename={handleRename} />
<ContextMenuItem onClick={handleDelete} className='text-red-600 focus:text-red-600'>
<Trash2 className='mr-2 h-4 w-4' />
</ContextMenuItem>
</ContextMenuContent>
</ContextMenu>
);
};
export const getFolder = () => {
const url = new URL(window.location.href);
const searchParams = url.searchParams;
const folder = searchParams.get('folder') || '';
return folder;
};
const RootContextMenu: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const { createFile, createDirectory } = useMenuStore();
return (
<ContextMenu>
<ContextMenuTrigger asChild>{children}</ContextMenuTrigger>
<ContextMenuContent className='w-48 border-gray-200 dark:border-gray-700'>
<ContextMenuDialogItem
icon={<FilePlus className='mr-2 h-4 w-4' />}
label='新建文件'
title='新建文件'
onConfirm={async (name) => {
await createFile('', name);
}}
/>
<ContextMenuDialogItem
icon={<FolderPlus className='mr-2 h-4 w-4' />}
label='新建文件夹'
title='新建文件夹'
onConfirm={async (name) => {
await createDirectory('', name);
}}
/>
<UploadFileItem parentPath='' />
</ContextMenuContent>
</ContextMenu>
);
};
export const Sidebar: React.FC = () => {
const { menu, isLoading } = useMenuStore();
useEffect(() => {
const folder = getFolder();
init('', folder);
}, []);
const rootItems = useMemo(() => {
const _menu = menu.filter((item) => {
return !item.path.includes('/');
});
return _menu.sort((a, b) => {
if (a.type === 'directory' && b.type === 'file') return -1;
if (a.type === 'file' && b.type === 'directory') return 1;
return a.path.localeCompare(b.path);
});
}, [menu]);
return (
<div className='border-r border-gray-200 dark:border-gray-800 w-full min-h-screen bg-gray-50 dark:bg-black h-full'>
<div className='flex items-center justify-between mb-2 px-2 py-3 border-b border-gray-200 dark:border-gray-800'>
<h2 className='text-sm font-semibold text-gray-600 dark:text-gray-400 uppercase tracking-wider'></h2>
{isLoading && <Loader2 className='w-4 h-4 animate-spin text-gray-400' />}
</div>
<div className='overflow-y-auto scrollbar p-2' style={{ maxHeight: 'calc(100% - 68px)' }}>
{menu.length === 0 && !isLoading ? (
<div className='text-sm text-gray-400 px-2'></div>
) : (
<RootContextMenu>
<div className='space-y-0.5'>
{rootItems.map((item) =>
item.type === 'directory' ? (
<DirectoryItem key={item.path} item={item} level={1} />
) : (
<FileItem key={item.path} item={item} level={1} />
),
)}
</div>
</RootContextMenu>
)}
</div>
</div>
);
};
export default Sidebar;

View File

@@ -0,0 +1,26 @@
import { create } from 'zustand';
import { Chain } from '@kevisual/codemirror/utils';
export const chain = new Chain();
interface EditState {
type: string;
value: string;
isEditing: boolean;
setType: (type: string) => void;
setValue: (value: string) => void;
setEditing: (status: boolean) => void;
}
export const useEditStore = create<EditState>((set) => ({
type: '',
value: '',
isEditing: false,
setType: (type) => set({ type }),
setValue: (value) => {
set({ value });
chain.setContent(value);
},
setEditing: (isEditing) => set({ isEditing }),
}));

View File

@@ -0,0 +1,288 @@
import { create } from 'zustand';
import { query } from '@/modules/query';
import { QueryLoginBrowser } from '@kevisual/api/login';
import { QueryResources } from '@kevisual/api/resources';
import { toast } from 'sonner';
import { Chain } from '@kevisual/codemirror/utils';
export const chain = new Chain();
export const queryLogin = new QueryLoginBrowser({ query });
export const queryResources = new QueryResources({
prefix: '/root/resources/',
});
export type MenuItem = {
type: 'file' | 'directory';
name?: string; // type === 'file'
prefix?: string; // type === 'directory'
etag?: string;
lastModified?: string; // ISO date string
size: number;
url: string;
path: string; // a/b/file.md
pathname: string;
};
export type Menu = MenuItem[];
// 右键菜单状态类型
export interface ContextMenuState {
visible: boolean;
x: number;
y: number;
item: MenuItem | null;
parentPath: string | null;
}
interface MenuState {
menu: Menu;
currentPath: string | null;
isLoading: boolean;
contextMenu: ContextMenuState;
setMenu: (menu: Menu) => void;
setCurrentPath: (path: string | null) => void;
setLoading: (status: boolean) => void;
setContextMenu: (state: Partial<ContextMenuState> | null) => void;
onSaveText: () => Promise<any>;
createFile: (parentPath: string, name: string) => Promise<boolean>;
createDirectory: (parentPath: string, name: string) => Promise<boolean>;
deleteItem: (path: string) => Promise<boolean>;
renameItem: (oldPath: string, newPath: string) => Promise<boolean>;
refreshMenu: () => Promise<void>;
}
export const useMenuStore = create<MenuState>((set, get) => ({
menu: [],
currentPath: null,
isLoading: false,
contextMenu: {
visible: false,
x: 0,
y: 0,
item: null,
parentPath: null,
},
setMenu: (menu) => set({ menu }),
setCurrentPath: (currentPath) => set({ currentPath }),
setLoading: (isLoading) => set({ isLoading }),
setContextMenu: (state) => {
if (state === null) {
set({
contextMenu: { visible: false, x: 0, y: 0, item: null, parentPath: null },
});
} else {
set((prev) => ({
contextMenu: { ...prev.contextMenu, ...state },
}));
}
},
onSaveText: async () => {
const { currentPath } = get();
const content = chain.getContent();
console.log('path', currentPath);
console.log('Saving content:', content);
const res = await postContent(currentPath!, content);
},
createFile: async (parentPath: string, name: string) => {
const path = parentPath ? `${parentPath}/${name}` : name;
const loadingToast = toast.loading('正在创建文件...');
const res = await queryResources.uploadFile(path, '');
toast.dismiss(loadingToast);
if (res.code === 200) {
toast.success('文件创建成功');
await get().refreshMenu();
return true;
} else {
toast.error(`创建文件失败: ${res.message}`);
return false;
}
},
createDirectory: async (parentPath: string, name: string) => {
const path = parentPath ? `${parentPath}/${name}` : name;
const loadingToast = toast.loading('正在创建文件夹...');
const res = await queryResources.createFolder(path);
toast.dismiss(loadingToast);
if (res.code === 200) {
toast.success('文件夹创建成功');
await get().refreshMenu();
return true;
} else {
toast.error(`创建文件夹失败: ${res.message}`);
return false;
}
},
renameItem: async (oldPath: string, newPath: string) => {
const loadingToast = toast.loading('正在重命名...');
const res = await queryResources.rename(oldPath, newPath);
toast.dismiss(loadingToast);
if (res.code === 200) {
toast.success('重命名成功');
const { currentPath } = get();
if (currentPath === oldPath) {
const parts = oldPath.split('/');
parts.pop();
const newCurrentPath = parts.length > 0 ? `${parts.join('/')}/${newPath}` : newPath;
set({ currentPath: newCurrentPath });
}
await get().refreshMenu();
return true;
} else {
toast.error(`重命名失败: ${res.message}`);
return false;
}
},
deleteItem: async (path: string) => {
const loadingToast = toast.loading('正在删除...');
const res = await queryResources.deleteFile(path);
toast.dismiss(loadingToast);
if (res.code === 200) {
toast.success('删除成功');
const { currentPath } = get();
if (currentPath === path) {
set({ currentPath: null });
}
await get().refreshMenu();
return true;
} else {
toast.error(`删除失败: ${res.message}`);
return false;
}
},
refreshMenu: async () => {
const { setMenu, setLoading } = useMenuStore.getState();
setLoading(true);
try {
const res = await queryResources.getList('', { recursive: true });
if (res.code === 200) {
const menu = res.data!.map((item: any) => ({
...item,
type: item.prefix ? 'directory' : 'file',
}));
// 添加缺失的目录项
const obj: Record<string, any> = {};
menu.forEach((item) => {
if (item.type === 'file') {
const parts = item.path.split('/');
const dirParts = parts.slice(0, -1);
for (let i = 0; i < dirParts.length; i++) {
const dir = dirParts.slice(0, i + 1).join('/');
if (!dir) continue;
obj[dir] = obj[dir] || { type: 'directory', path: dir };
}
}
});
Object.keys(obj).forEach((key) => {
if (!menu.find((m) => m.path === key)) {
menu.push(obj[key]);
}
});
setMenu(menu);
}
} finally {
setLoading(false);
}
},
}));
class Status {
isInitialized = false;
username = '';
}
const status = new Status();
export const init = async (resource: string = '', prefix: string = '') => {
console.log('init menu', resource, prefix);
const { setMenu, setCurrentPath, setLoading } = useMenuStore.getState();
let me = await queryLogin.checkLocalUser();
const isInitialized = status.isInitialized;
if (!isInitialized && me) {
status.isInitialized = true;
status.username = me.username!;
queryResources.setUsername(status.username);
}
let recursive = true;
const data = {};
if (recursive) {
data['recursive'] = recursive;
}
if (prefix) {
queryResources.setPrefix(prefix);
}
console.log('queryResources', queryResources.prefix);
const res = await queryResources.getList(resource, data);
// @ts-ignore
if (res?.status === 404) {
toast.error('资源不存在,请检查路径是否正确');
return;
}
if (res.code === 200) {
const menu = res.data!.map((item: any) => {
if (item.prefix) {
item.type = 'directory';
} else {
item.type = 'file';
}
return item;
});
console.log('init menu', menu);
if (recursive) {
const obj: Record<string, any> = {};
menu.forEach((item) => {
const parts = item.path.split('/');
const dirParts = parts.slice(0, -1);
for (let i = 0; i < dirParts.length; i++) {
const dir = dirParts.slice(0, i + 1).join('/');
if (!dir) continue; // skip root
obj[dir] = obj[dir] || { type: 'directory', path: dir };
}
});
Object.keys(obj).forEach((key) => {
const item = obj[key];
menu.push(item);
});
}
setMenu(menu);
setCurrentPath('');
}
};
export const getCurrentContent = async (currentPath: string): Promise<string | null> => {
if (!currentPath) return null;
const loadingToast = toast.loading('正在加载文件内容...');
const res = await queryResources.fetchFile(currentPath);
toast.dismiss(loadingToast);
if (res.code === 200) {
return res.data || '';
} else {
console.error('Error fetching content:', res.message);
toast.error(`获取内容失败: ${res.message}`);
return null;
}
};
export const postContent = async (currentPath: string, content: string): Promise<boolean> => {
if (!currentPath) return false;
const loadingToast = toast.loading('正在保存...');
const res = await queryResources.uploadFile(currentPath, content);
toast.dismiss(loadingToast);
console.log('postContent', res);
if (res.code === 200) {
toast.success('内容保存成功');
return true;
} else {
console.error('Error saving content:', res.message);
toast.error(`保存内容失败: ${res.message}`);
return false;
}
};
export const getFileUrl = async (currentPath: string): Promise<string> => {
if (!currentPath) return '';
const res = await queryResources.fetchFile(currentPath);
if (res instanceof Response && res.ok) {
return URL.createObjectURL(await res.blob());
}
return '';
};

View File

@@ -0,0 +1,13 @@
// 简单实用的版本
export function isSemVer(version) {
if (typeof version !== 'string') return false;
// 移除可能的 v 前缀
if (version.toLowerCase().startsWith('v')) {
version = version.slice(1);
}
// 完整的 SemVer 格式验证
const semverRegex = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/;
return semverRegex.test(version);
}