modified: frontend/src/pages/EndpointEditor.tsx

modified:   frontend/src/pages/Folders.tsx
This commit is contained in:
2026-03-13 18:23:21 +03:00
parent 727c6765f8
commit f0cbe99cb0
2 changed files with 183 additions and 37 deletions

View File

@@ -146,14 +146,23 @@ export default function EndpointEditor() {
} }
}, [storageKey, testParams, testResult]); }, [storageKey, testParams, testResult]);
const [saveAndStay, setSaveAndStay] = useState(false);
const saveMutation = useMutation({ const saveMutation = useMutation({
mutationFn: (data: any) => mutationFn: (data: any) =>
isEditing ? endpointsApi.update(id!, data) : endpointsApi.create(data), isEditing ? endpointsApi.update(id!, data) : endpointsApi.create(data),
onSuccess: () => { onSuccess: (response) => {
queryClient.invalidateQueries({ queryKey: ['endpoints'] }); queryClient.invalidateQueries({ queryKey: ['endpoints'] });
queryClient.invalidateQueries({ queryKey: ['endpoint', id] }); queryClient.invalidateQueries({ queryKey: ['endpoint', id] });
toast.success(isEditing ? 'Эндпоинт обновлен' : 'Эндпоинт создан'); toast.success(isEditing ? 'Эндпоинт обновлен' : 'Эндпоинт создан');
navigate(-1); if (saveAndStay) {
// При создании нового — переходим на страницу редактирования созданного
if (!isEditing && response.data?.id) {
navigate(`/endpoints/${response.data.id}`, { replace: true });
}
} else {
navigate(-1);
}
}, },
onError: () => toast.error('Не удалось сохранить эндпоинт'), onError: () => toast.error('Не удалось сохранить эндпоинт'),
}); });
@@ -832,8 +841,21 @@ export default function EndpointEditor() {
<button type="button" onClick={() => navigate(-1)} className="btn btn-secondary"> <button type="button" onClick={() => navigate(-1)} className="btn btn-secondary">
Отмена Отмена
</button> </button>
<button type="submit" disabled={saveMutation.isPending} className="btn btn-primary"> <button
{saveMutation.isPending ? 'Сохранение...' : 'Сохранить эндпоинт'} type="submit"
disabled={saveMutation.isPending}
className="btn btn-secondary"
onClick={() => setSaveAndStay(true)}
>
{saveMutation.isPending && saveAndStay ? 'Сохранение...' : 'Сохранить'}
</button>
<button
type="submit"
disabled={saveMutation.isPending}
className="btn btn-primary"
onClick={() => setSaveAndStay(false)}
>
{saveMutation.isPending && !saveAndStay ? 'Сохранение...' : 'Сохранить и выйти'}
</button> </button>
</div> </div>
</div> </div>

View File

@@ -1,9 +1,9 @@
import { useState } from 'react'; import { useState, useMemo } from 'react';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { foldersApi, endpointsApi } from '@/services/api'; import { foldersApi, endpointsApi } from '@/services/api';
import { Folder, Endpoint } from '@/types'; import { Folder, Endpoint } from '@/types';
import { Plus, Edit2, Trash2, Folder as FolderIcon, FolderOpen, FileCode, ChevronRight, ChevronDown } from 'lucide-react'; import { Plus, Edit2, Trash2, Folder as FolderIcon, FolderOpen, FileCode, ChevronRight, ChevronDown, Search, ChevronsDownUp, ChevronsUpDown } from 'lucide-react';
import toast from 'react-hot-toast'; import toast from 'react-hot-toast';
import Dialog from '@/components/Dialog'; import Dialog from '@/components/Dialog';
@@ -14,6 +14,7 @@ export default function Folders() {
const [editingFolder, setEditingFolder] = useState<Folder | null>(null); const [editingFolder, setEditingFolder] = useState<Folder | null>(null);
const [selectedFolderId, setSelectedFolderId] = useState<string | null>(null); const [selectedFolderId, setSelectedFolderId] = useState<string | null>(null);
const [expandedFolders, setExpandedFolders] = useState<Set<string>>(new Set()); const [expandedFolders, setExpandedFolders] = useState<Set<string>>(new Set());
const [searchQuery, setSearchQuery] = useState('');
const [dialog, setDialog] = useState<{ const [dialog, setDialog] = useState<{
isOpen: boolean; isOpen: boolean;
title: string; title: string;
@@ -111,6 +112,16 @@ export default function Folders() {
}); });
}; };
const getAllFolderIds = (nodes: any[]): string[] => {
const ids: string[] = [];
const collect = (ns: any[]) => ns.forEach(n => { ids.push(n.id); if (n.children?.length) collect(n.children); });
collect(nodes);
return ids;
};
const expandAll = () => setExpandedFolders(new Set(getAllFolderIds(tree)));
const collapseAll = () => setExpandedFolders(new Set());
// Построение дерева папок // Построение дерева папок
const buildTree = () => { const buildTree = () => {
if (!folders || !endpoints) return []; if (!folders || !endpoints) return [];
@@ -143,6 +154,33 @@ export default function Folders() {
const tree = buildTree(); const tree = buildTree();
// Поиск
const searchResults = useMemo(() => {
if (!searchQuery.trim()) return null;
const q = searchQuery.toLowerCase();
// Строим карту путей папок
const folderPathMap = new Map<string, string>();
const buildPaths = (nodes: any[], prefix = '') => {
nodes.forEach(n => {
const p = prefix ? `${prefix} / ${n.name}` : n.name;
folderPathMap.set(n.id, p);
if (n.children?.length) buildPaths(n.children, p);
});
};
buildPaths(tree);
const matchedEndpoints = (endpoints || []).filter(e =>
e.name.toLowerCase().includes(q) ||
e.path.toLowerCase().includes(q) ||
e.method.toLowerCase().includes(q)
).map(e => ({ ...e, folderPath: e.folder_id ? (folderPathMap.get(e.folder_id) || '') : '' }));
const matchedFolders = (folders || []).filter(f => f.name.toLowerCase().includes(q));
return { endpoints: matchedEndpoints, folders: matchedFolders, folderPathMap };
}, [searchQuery, endpoints, folders, tree]);
return ( return (
<div> <div>
<div className="flex items-center justify-between mb-6"> <div className="flex items-center justify-between mb-6">
@@ -169,40 +207,126 @@ export default function Folders() {
</div> </div>
) : ( ) : (
<div className="card p-6"> <div className="card p-6">
{/* Toolbar: search + expand/collapse */}
<div className="flex items-center gap-2 mb-4">
<div className="relative flex-1">
<Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />
<input
type="text"
placeholder="Поиск по имени, пути, методу..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="input w-full pl-9 text-sm"
/>
</div>
<button
onClick={expandAll}
className="btn btn-secondary flex items-center gap-1.5 text-sm py-1.5"
title="Раскрыть все"
>
<ChevronsUpDown size={16} />
Раскрыть все
</button>
<button
onClick={collapseAll}
className="btn btn-secondary flex items-center gap-1.5 text-sm py-1.5"
title="Свернуть все"
>
<ChevronsDownUp size={16} />
Свернуть все
</button>
</div>
<div className="space-y-1"> <div className="space-y-1">
{/* Корневые папки */} {searchResults ? (
{tree.map(folder => ( /* Результаты поиска */
<TreeNode <>
key={folder.id} {searchResults.endpoints.length === 0 && searchResults.folders.length === 0 ? (
folder={folder} <div className="text-center py-12 text-gray-500">
level={0} <p>Ничего не найдено по запросу «{searchQuery}»</p>
expandedFolders={expandedFolders} </div>
onToggle={toggleFolder} ) : (
onEditFolder={handleEditFolder} <>
onDeleteFolder={handleDeleteFolder} {searchResults.folders.map((folder: any) => (
onCreateSubfolder={handleCreateFolder} <div key={folder.id} className="flex items-center gap-2 px-3 py-2 rounded bg-yellow-50 border border-yellow-100">
onCreateEndpoint={handleCreateEndpoint} <FolderIcon size={16} className="text-yellow-600 flex-shrink-0" />
onEditEndpoint={handleEditEndpoint} <span className="text-sm font-medium text-gray-900">{folder.name}</span>
onDeleteEndpoint={handleDeleteEndpoint} <span className="text-xs text-gray-400">{searchResults.folderPathMap.get(folder.id)}</span>
/> <div className="flex gap-1 ml-auto">
))} <button onClick={() => handleEditFolder(folder)} className="p-1.5 hover:bg-gray-200 rounded" title="Редактировать">
<Edit2 size={14} className="text-gray-600" />
</button>
<button onClick={() => handleDeleteFolder(folder.id)} className="p-1.5 hover:bg-red-100 rounded" title="Удалить">
<Trash2 size={14} className="text-red-600" />
</button>
</div>
</div>
))}
{searchResults.endpoints.map((endpoint: any) => (
<div key={endpoint.id} className="flex items-center gap-2 px-3 py-2 rounded hover:bg-gray-50 border border-transparent">
<FileCode size={16} className="text-blue-600 flex-shrink-0" />
<div className="flex-1 min-w-0">
<span className="text-sm text-gray-900">{endpoint.name}</span>
{endpoint.folderPath && (
<span className="ml-2 text-xs text-gray-400">{endpoint.folderPath}</span>
)}
</div>
<span className={`text-xs px-2 py-0.5 rounded font-medium ${
endpoint.method === 'GET' ? 'bg-green-100 text-green-700' :
endpoint.method === 'POST' ? 'bg-blue-100 text-blue-700' :
endpoint.method === 'PUT' ? 'bg-yellow-100 text-yellow-700' :
'bg-red-100 text-red-700'
}`}>{endpoint.method}</span>
<code className="text-xs text-gray-600 hidden sm:block">{endpoint.path}</code>
<div className="flex gap-1">
<button onClick={() => handleEditEndpoint(endpoint)} className="p-1.5 hover:bg-gray-200 rounded" title="Редактировать">
<Edit2 size={14} className="text-gray-600" />
</button>
<button onClick={() => handleDeleteEndpoint(endpoint.id)} className="p-1.5 hover:bg-red-100 rounded" title="Удалить">
<Trash2 size={14} className="text-red-600" />
</button>
</div>
</div>
))}
</>
)}
</>
) : (
/* Обычное дерево */
<>
{tree.map(folder => (
<TreeNode
key={folder.id}
folder={folder}
level={0}
expandedFolders={expandedFolders}
onToggle={toggleFolder}
onEditFolder={handleEditFolder}
onDeleteFolder={handleDeleteFolder}
onCreateSubfolder={handleCreateFolder}
onCreateEndpoint={handleCreateEndpoint}
onEditEndpoint={handleEditEndpoint}
onDeleteEndpoint={handleDeleteEndpoint}
/>
))}
{/* Корневые эндпоинты (без папки) */} {rootEndpoints.map(endpoint => (
{rootEndpoints.map(endpoint => ( <EndpointNode
<EndpointNode key={endpoint.id}
key={endpoint.id} endpoint={endpoint}
endpoint={endpoint} level={0}
level={0} onEdit={handleEditEndpoint}
onEdit={handleEditEndpoint} onDelete={handleDeleteEndpoint}
onDelete={handleDeleteEndpoint} />
/> ))}
))}
{tree.length === 0 && rootEndpoints.length === 0 && ( {tree.length === 0 && rootEndpoints.length === 0 && (
<div className="text-center py-12 text-gray-500"> <div className="text-center py-12 text-gray-500">
<p>Нет папок и эндпоинтов.</p> <p>Нет папок и эндпоинтов.</p>
<p className="text-sm mt-2">Создайте первую папку или эндпоинт!</p> <p className="text-sm mt-2">Создайте первую папку или эндпоинт!</p>
</div> </div>
)}
</>
)} )}
</div> </div>
</div> </div>