Files
Unified_Dashboard_Suite_Go/web/bulk-api-tester/static/js/app.js.bak2
T

2489 lines
120 KiB
Plaintext
Raw Normal View History

/**
* Phoenix App - Advanced Bulk API Tester
* Version: 2.0 (Agentic Edition)
*/
const App = {
_stateData: {
spaces: [],
activeSpaceId: null,
activeCollectionId: 'default',
outputFolderPath: '',
gridMaximized: false,
resultsPanelHeight: 300,
sidebarWidth: 270,
searchQuery: ''
},
tabs: [],
activeTabIndex: 0,
get state() {
if (!this._proxyState) {
const props = ['name', 'method', 'url', 'params', 'headers', 'auth', 'bodyType', 'bodyData', 'jsonBody', 'response', 'bulk', 'activeTab', 'responseTab', 'activeRequestId', 'isPreview'];
this._proxyState = new Proxy(this._stateData, {
get(target, prop) {
if (props.includes(prop)) {
if (App.tabs && App.tabs[App.activeTabIndex]) {
return App.tabs[App.activeTabIndex][prop];
}
}
return target[prop];
},
set(target, prop, value) {
if (props.includes(prop)) {
if (App.tabs && App.tabs[App.activeTabIndex]) {
App.tabs[App.activeTabIndex][prop] = value;
if (prop !== 'activeTab' && prop !== 'responseTab' && prop !== 'activeRequestId') {
App.tabs[App.activeTabIndex].isPreview = false;
}
return true;
}
}
target[prop] = value;
return true;
}
});
}
return this._proxyState;
},
createNewTab(reqData, isPreview = false) {
return {
id: 'tab_' + Date.now() + Math.random().toString(36).substr(2, 9),
name: reqData ? reqData.name : 'Untitled Request',
method: reqData ? reqData.method : 'POST',
url: reqData ? reqData.url : '',
params: reqData ? JSON.parse(JSON.stringify(reqData.params || [])) : [],
headers: reqData ? JSON.parse(JSON.stringify(reqData.headers || [])) : [],
auth: reqData ? JSON.parse(JSON.stringify(reqData.auth || {type:'none'})) : {type:'none'},
bodyType: reqData ? reqData.bodyType : 'none',
bodyData: reqData ? JSON.parse(JSON.stringify(reqData.bodyData || [])) : [],
jsonBody: reqData ? reqData.jsonBody : '',
response: null,
bulk: reqData && reqData.bulk ? JSON.parse(JSON.stringify(reqData.bulk)) : {
strategy: 'consecutive',
running: false,
total: 0,
completed: 0,
success: 0,
error: 0,
concurrency: 1,
results: []
},
activeTab: 'params',
responseTab: 'response',
activeRequestId: reqData ? reqData.id : null,
isPreview: isPreview
};
},
fileStore: new Map(), // id -> FileList
dom: {},
async init() {
this.loadState();
this.cacheDOM();
this.bindEvents();
if (this.state.params.length === 0) this.addParam('params');
if (this.state.headers.length === 0) this.addParam('headers');
// Load spaces from the server to keep them synced
await this.loadSpacesFromServer();
// Load the last run results/response from the server
await this.loadLastRunFromServer();
// Apply saved sidebar width
const sidebarEl = document.getElementById('sidebar');
if (sidebarEl && this.state.sidebarWidth) {
sidebarEl.style.width = `${this.state.sidebarWidth}px`;
}
// Attach event listener for horizontal sidebar dragging
const handle = document.getElementById('sidebar-resize-handle');
if (handle) {
handle.addEventListener('mousedown', (e) => this.startSidebarResize(e));
}
this.render();
// Remove loader
const loader = document.getElementById('loading-overlay');
if (loader) loader.remove();
document.getElementById('app-root').style.visibility = 'visible';
},
cacheDOM() {
this.dom = {
mainPanel: document.getElementById('main-panel'),
sidebar: document.getElementById('sidebar'),
toast: document.getElementById('toast-container')
};
if (!this.dom.sidebar || !this.dom.mainPanel) {
console.error('Critical: DOM elements not found', this.dom);
alert('Critical Error: Application DOM structure is missing. Please refresh.');
}
},
// --- State Management ---
loadState() {
try {
const raw = localStorage.getItem('phoenix-state-v2');
if (raw) {
const data = JSON.parse(raw);
this.state = { ...this.state, ...data };
// Keep volatile fields clean on reload, loaded separately from server
this.state.bulk.running = false;
this.state.bulk.results = [];
this.state.response = null;
}
} catch (e) {
console.warn('Failed to load state', e);
}
},
saveState() {
try {
const { bulk, response, ...persistent } = this.state;
const persistentState = {
...persistent,
bulk: { ...this.state.bulk, running: false, results: [] }
};
localStorage.setItem('phoenix-state-v2', JSON.stringify(persistentState));
} catch (e) {
console.warn('Failed to save state', e);
}
},
async loadLastRunFromServer() {
try {
const res = await fetch('/api/last-run');
if (res.ok) {
const data = await res.json();
if (data) {
if (data.bulk) {
this.state.bulk = { ...this.state.bulk, ...data.bulk, running: false };
}
if (data.response !== undefined) {
this.state.response = data.response;
}
if (data.responseTab) {
this.state.responseTab = data.responseTab;
}
}
}
} catch (e) {
console.error('Failed to load last run from server', e);
}
},
async saveLastRunToServer() {
try {
const payload = {
bulk: { ...this.state.bulk, running: false },
response: this.state.response,
responseTab: this.state.responseTab
};
await fetch('/api/last-run', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
} catch (e) {
console.error('Failed to save last run to server', e);
}
},
saveLastRunToServerThrottled() {
if (this._saveThrottleTimeout) return;
this._saveThrottleTimeout = setTimeout(async () => {
this._saveThrottleTimeout = null;
await this.saveLastRunToServer();
}, 1000);
},
get collections() {
if (!this.state.activeSpaceId) return [];
const space = this.state.spaces.find(s => s.id === this.state.activeSpaceId);
return space ? space.collections : [];
},
set collections(val) {
if (!this.state.activeSpaceId) return;
const space = this.state.spaces.find(s => s.id === this.state.activeSpaceId);
if (space) {
space.collections = val;
}
},
get notifications() {
if (!this.state.activeSpaceId) return [];
const space = this.state.spaces.find(s => s.id === this.state.activeSpaceId);
return space ? (space.notifications || []) : [];
},
set notifications(val) {
if (!this.state.activeSpaceId) return;
const space = this.state.spaces.find(s => s.id === this.state.activeSpaceId);
if (space) {
space.notifications = val;
}
},
async loadSpacesFromServer() {
try {
const res = await fetch('/api/spaces');
const data = await res.json();
if (Array.isArray(data)) {
// Check if server returned empty or only the default empty spaces
const serverIsEmpty = data.length === 0 || (
data.length === 2 &&
data[0].id === 'personal' && data[0].collections.length === 1 && (!data[0].collections[0].requests || data[0].collections[0].requests.length === 0) &&
data[1].id === 'team' && data[1].collections.length === 1 && (!data[1].collections[0].requests || data[1].collections[0].requests.length === 0)
);
// Check if client had non-empty legacy collections in localStorage
const clientHasLegacyCollections = this.state.collections && (
this.state.collections.length > 1 ||
(this.state.collections[0] && this.state.collections[0].requests && this.state.collections[0].requests.length > 0)
);
if (serverIsEmpty && clientHasLegacyCollections) {
console.log('Migrating local client collections to spaces...');
this.state.spaces = [
{
id: 'personal',
name: 'Personal Space',
collections: JSON.parse(JSON.stringify(this.state.collections))
},
{
id: 'team',
name: 'Team Space',
collections: JSON.parse(JSON.stringify(this.state.collections))
}
];
delete this.state.collections;
await this.saveSpacesToServer();
} else if (data.length === 0 && this.state.spaces && this.state.spaces.length > 0) {
await this.saveSpacesToServer();
} else if (data.length > 0) {
this.state.spaces = data;
}
// Validate activeSpaceId
if (this.state.activeSpaceId) {
const spaceExists = this.state.spaces.some(s => s.id === this.state.activeSpaceId);
if (!spaceExists) {
this.state.activeSpaceId = null;
this.state.activeCollectionId = 'default';
this.state.activeRequestId = null;
}
}
}
} catch (e) {
console.error('Failed to load spaces from server:', e);
}
},
async saveSpacesToServer() {
try {
await fetch('/api/spaces', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(this.state.spaces)
});
} catch (e) {
console.error('Failed to sync spaces with server:', e);
}
},
openSpace(spaceId) {
this.state.activeSpaceId = spaceId;
this.state.activeCollectionId = 'default';
this.state.activeRequestId = null;
this.saveState();
this.render();
},
showSpacesDashboard() {
this.state.activeSpaceId = null;
this.state.activeCollectionId = 'default';
this.state.activeRequestId = null;
this.saveState();
this.render();
},
async createSpace() {
const name = prompt("Enter space name:");
if (name && name.trim()) {
const id = 'space_' + Date.now();
this.state.spaces.push({
id: id,
name: name.trim(),
collections: [{ id: 'default', name: 'My Requests', requests: [] }]
});
this.state.activeSpaceId = id;
this.saveState();
await this.saveSpacesToServer();
this.render();
}
},
async deleteSpace(spaceId) {
if (this.state.spaces.length <= 1) {
return this.toast("Cannot delete the last remaining space", "error");
}
if (confirm("Are you sure you want to delete this space? All collections and requests inside it will be permanently lost.")) {
this.state.spaces = this.state.spaces.filter(s => s.id !== spaceId);
if (this.state.activeSpaceId === spaceId) {
this.state.activeSpaceId = null;
this.state.activeCollectionId = 'default';
this.state.activeRequestId = null;
}
this.saveState();
await this.saveSpacesToServer();
this.render();
}
},
renameSpace(spaceId) {
const space = this.state.spaces.find(s => s.id === spaceId);
if (!space) return;
const newName = prompt("Enter new workspace name:", space.name);
if (newName && newName.trim()) {
space.name = newName.trim();
this.saveState();
this.saveSpacesToServer();
this.render();
}
},
async setSpaceTheme(themeId) {
const activeSpace = this.state.spaces.find(s => s.id === this.state.activeSpaceId);
if (activeSpace) {
activeSpace.theme = themeId;
this.saveState();
await this.saveSpacesToServer();
this.render();
this.toast(`Applied ${themeId} theme to ${activeSpace.name}`);
}
},
async shareCollection(colId) {
const otherSpaces = this.state.spaces.filter(s => s.id !== this.state.activeSpaceId);
if (otherSpaces.length === 0) {
return this.toast("No other spaces to share with", "warning");
}
const activeSpace = this.state.spaces.find(s => s.id === this.state.activeSpaceId);
const collection = this.collections.find(c => c.id === colId);
if (!collection) return;
const spacesList = otherSpaces.map((s, idx) => `${idx + 1}. ${s.name}`).join('\n');
const choice = prompt(`Select workspace to share "${collection.name}" with (enter number):\n${spacesList}`);
if (choice) {
const idx = parseInt(choice) - 1;
if (idx >= 0 && idx < otherSpaces.length) {
const targetSpace = otherSpaces[idx];
targetSpace.notifications = targetSpace.notifications || [];
const alreadyShared = targetSpace.notifications.some(n => n.collection.id === colId && n.fromSpaceId === this.state.activeSpaceId);
if (alreadyShared) {
return this.toast("Already shared with this space, pending approval", "warning");
}
targetSpace.notifications.push({
id: 'share_' + Date.now(),
fromSpaceId: this.state.activeSpaceId,
fromSpaceName: activeSpace ? activeSpace.name : 'Unknown Space',
collection: JSON.parse(JSON.stringify(collection))
});
this.saveState();
await this.saveSpacesToServer();
this.toast(`Shared collection with ${targetSpace.name}!`);
this.render();
} else {
this.toast("Invalid selection", "error");
}
}
},
openNotificationsModal() {
const activeSpace = this.state.spaces.find(s => s.id === this.state.activeSpaceId);
if (!activeSpace || !activeSpace.notifications || activeSpace.notifications.length === 0) return;
const modal = document.createElement('div');
modal.className = 'premium-modal-overlay';
modal.id = 'notifications-modal';
const listHTML = activeSpace.notifications.map(n => `
<div class="notif-item">
<div class="notif-details">
<i class="fa-solid fa-folder-open notif-icon"></i>
<div>
<div class="notif-title"><strong>${this.escapeHTML(n.fromSpaceName)}</strong> shared collection:</div>
<div class="notif-col-name">${this.escapeHTML(n.collection.name)}</div>
<small class="notif-col-meta">${n.collection.requests ? n.collection.requests.length : 0} Requests</small>
</div>
</div>
<div class="notif-actions">
<button class="btn btn-success" onclick="App.approveShare('${n.id}'); this.closest('#notifications-modal').remove();">
<i class="fa-solid fa-check"></i> Approve
</button>
<button class="btn btn-danger" onclick="App.rejectShare('${n.id}'); this.closest('#notifications-modal').remove();">
<i class="fa-solid fa-xmark"></i> Reject
</button>
</div>
</div>
`).join('');
modal.innerHTML = `
<div class="premium-modal-card" style="max-width:500px; width:100%; border:1px solid var(--border);">
<div class="premium-modal-header">
<h3><i class="fa-solid fa-bell" style="color:var(--primary);"></i> Share Requests</h3>
<button class="btn-ghost" onclick="this.closest('#notifications-modal').remove()"><i class="fa-solid fa-xmark"></i></button>
</div>
<div class="premium-modal-body" style="display:flex; flex-direction:column; gap:16px;">
${listHTML}
</div>
<div class="premium-modal-footer">
<button class="btn btn-ghost" onclick="this.closest('#notifications-modal').remove()">Close</button>
</div>
</div>
`;
document.body.appendChild(modal);
modal.onclick = (e) => { if (e.target === modal) modal.remove(); };
},
async approveShare(notifId) {
const activeSpace = this.state.spaces.find(s => s.id === this.state.activeSpaceId);
if (!activeSpace || !activeSpace.notifications) return;
const idx = activeSpace.notifications.findIndex(n => n.id === notifId);
if (idx >= 0) {
const notif = activeSpace.notifications[idx];
const collection = notif.collection;
let newName = collection.name;
let counter = 1;
while (activeSpace.collections.some(c => c.name === newName)) {
newName = `${collection.name} (${counter++})`;
}
collection.name = newName;
collection.id = 'col_' + Date.now();
activeSpace.collections.push(collection);
activeSpace.notifications.splice(idx, 1);
this.saveState();
await this.saveSpacesToServer();
this.toast("Collection approved and added!");
this.render();
}
},
async rejectShare(notifId) {
const activeSpace = this.state.spaces.find(s => s.id === this.state.activeSpaceId);
if (!activeSpace || !activeSpace.notifications) return;
const idx = activeSpace.notifications.findIndex(n => n.id === notifId);
if (idx >= 0) {
activeSpace.notifications.splice(idx, 1);
this.saveState();
await this.saveSpacesToServer();
this.toast("Share request rejected");
this.render();
}
},
startSidebarResize(e) {
e.preventDefault();
document.body.classList.add('resizing');
const startX = e.clientX;
const startWidth = this.state.sidebarWidth || 270;
const handle = document.getElementById('sidebar-resize-handle');
if (handle) handle.classList.add('active');
const doDrag = (moveEvent) => {
const deltaX = moveEvent.clientX - startX;
const newWidth = Math.max(180, Math.min(600, startWidth + deltaX));
this.state.sidebarWidth = newWidth;
const sidebarEl = document.getElementById('sidebar');
if (sidebarEl) {
sidebarEl.style.width = `${newWidth}px`;
}
};
const stopDrag = () => {
document.body.classList.remove('resizing');
document.removeEventListener('mousemove', doDrag);
document.removeEventListener('mouseup', stopDrag);
if (handle) handle.classList.remove('active');
this.saveState();
};
document.addEventListener('mousemove', doDrag);
document.addEventListener('mouseup', stopDrag);
},
async resendBulkRequest(resultIndex) {
const index = resultIndex - 1; // 0-based index
const bulk = this.state.bulk;
const resultItem = bulk.results.find(r => r.index === resultIndex);
if (!resultItem) return;
this.toast(`Re-sending request #${resultIndex}...`, 'info');
// Recalculate maxFiles and maxList to determine fileIndex and listIndex 1-to-1
let maxFiles = 0;
let maxList = 0;
const folders = [
...this.state.params.filter(p => p.type === 'folder' && p.enabled && p.key && p.key.trim()),
...(this.state.bodyType === 'form-data' ? this.state.bodyData.filter(p => p.type === 'folder' && p.enabled && p.key && p.key.trim()) : [])
];
if (folders.length > 0) {
for (const f of folders) {
const files = this.fileStore.get(f.id);
if (files && files.length > maxFiles) maxFiles = files.length;
}
}
const allLists = [
...this.state.params.filter(p => p.type === 'list' && p.enabled && p.key && p.key.trim()),
...(this.state.bodyType === 'form-data' ? this.state.bodyData.filter(p => p.type === 'list' && p.enabled && p.key && p.key.trim()) : []),
...this.state.headers.filter(h => h.type === 'list' && h.enabled && h.key && h.key.trim())
];
if (allLists.length > 0) {
for (const listParam of allLists) {
const val = listParam.value || '';
const arr = val.split(/[\n,]+/).map(s => s.trim()).filter(s => s);
if (arr.length > maxList) maxList = arr.length;
}
}
let fileIndex = index;
let listIndex = index;
if (bulk.strategy === 'cartesian' && maxFiles > 0 && maxList > 0) {
fileIndex = Math.floor(index / maxList);
listIndex = index % maxList;
}
try {
const res = await this.executeRequest(index, fileIndex, listIndex);
const isSuccess = res.status_code >= 200 && res.status_code < 300;
// Adjust stats counters
const wasSuccess = resultItem.status >= 200 && resultItem.status < 300;
if (wasSuccess && !isSuccess) {
bulk.success--;
bulk.error++;
} else if (!wasSuccess && isSuccess) {
bulk.success++;
bulk.error--;
}
// Update item details
resultItem.status = res.status_code;
resultItem.latency = res.latency || 0;
resultItem.data = res.content ? res.content.substring(0, 100) : (res.binary_data ? '[Binary]' : '');
resultItem.fullContent = res.content;
resultItem.binaryData = res.binary_data;
resultItem.contentType = res.content_type;
resultItem.headers = res.headers;
this.toast(`Request #${resultIndex} completed: ${res.status_code}`, isSuccess ? 'info' : 'error');
this.updateBulkProgressUI();
await this.saveLastRunToServer();
} catch (e) {
const wasSuccess = resultItem.status >= 200 && resultItem.status < 300;
if (wasSuccess) {
bulk.success--;
bulk.error++;
}
resultItem.status = 'ERR';
resultItem.latency = 0;
resultItem.data = e.message;
this.toast(`Request #${resultIndex} failed: ${e.message}`, 'error');
this.updateBulkProgressUI();
await this.saveLastRunToServer();
}
},
startResultsResize(e) {
e.preventDefault();
document.body.classList.add('resizing');
const startY = e.clientY;
const startHeight = this.state.resultsPanelHeight || 300;
const doDrag = (moveEvent) => {
const deltaY = startY - moveEvent.clientY;
const newHeight = Math.max(120, Math.min(800, startHeight + deltaY));
this.state.resultsPanelHeight = newHeight;
const panel = document.querySelector('.bottom-results-panel');
if (panel) {
panel.style.height = `${newHeight}px`;
}
};
const stopDrag = () => {
document.body.classList.remove('resizing');
document.removeEventListener('mousemove', doDrag);
document.removeEventListener('mouseup', stopDrag);
this.saveState();
};
document.addEventListener('mousemove', doDrag);
document.addEventListener('mouseup', stopDrag);
},
updateBulkProgressUI() {
const bulk = this.state.bulk;
const pct = bulk.total > 0 ? (bulk.completed / bulk.total) * 100 : 0;
const statusColor = bulk.error > 0 ? (bulk.success > 0 ? 'var(--warning)' : 'var(--danger)') : 'var(--success)';
const bar = document.getElementById('progress-bar-fill');
if (bar) {
bar.style.width = `${pct}%`;
bar.style.background = statusColor;
}
const text = document.getElementById('progress-text');
if (text) {
text.innerText = `${bulk.completed} / ${bulk.total} Completed`;
}
// Update stats
const successStat = document.querySelector('.stat-capsule.success');
if (successStat) {
successStat.innerText = `${bulk.success} Success`;
}
const errorStat = document.querySelector('.stat-capsule.error');
if (errorStat) {
errorStat.innerText = `${bulk.error} Failed`;
}
// Update the grid
const grid = document.querySelector('.results-grid');
if (grid) {
const cardsHTML = bulk.results.map(r => this.renderResultCard(r)).join('');
grid.innerHTML = cardsHTML || `<div style="grid-column: 1/-1; text-align: center; color: var(--text-muted); padding: 40px; font-style: italic;"><i class="fa-solid fa-spinner fa-spin" style="margin-right:10px;"></i>Executing batch requests, processing results...</div>`;
}
// Update the fullscreen grid overlay if active
if (document.getElementById('fullscreen-results-overlay')) {
this.openFullscreenResults();
}
// Enable/disable buttons based on results
const saveFolderBtn = document.querySelector('[onclick="App.saveToServerFolder()"]');
if (saveFolderBtn) {
saveFolderBtn.disabled = bulk.results.length === 0;
}
const zipBtn = document.querySelector('[onclick="App.saveAllResults()"]');
if (zipBtn) {
zipBtn.disabled = bulk.results.length === 0;
}
const csvBtn = document.querySelector('[onclick="App.downloadHistory()"]');
if (csvBtn) {
csvBtn.disabled = bulk.results.length === 0;
}
// Throttle state saves to the server to ensure perfect persistence during refreshes
this.saveLastRunToServerThrottled();
},
openFullscreenResults() {
const bulk = this.state.bulk;
if (bulk.results.length === 0 && !bulk.running) {
return this.toast("No results to view in fullscreen", "warning");
}
let modal = document.getElementById('fullscreen-results-overlay');
const pct = bulk.total > 0 ? (bulk.completed / bulk.total) * 100 : 0;
const statusColor = bulk.error > 0 ? (bulk.success > 0 ? 'var(--warning)' : 'var(--danger)') : 'var(--success)';
const cardsHTML = bulk.results.map(r => this.renderResultCard(r)).join('');
const folderPath = this.state.outputFolderPath || 'None selected';
const contentHTML = `
<div class="fullscreen-results-header">
<div style="display:flex; align-items:center; gap:16px;">
<i class="fa-solid fa-square-poll-horizontal" style="color:var(--primary); font-size:24px;"></i>
<div style="text-align:left;">
<h2 style="margin:0; font-size:18px; font-weight:700; color:var(--text-main);">Fullscreen Batch Processing Grid</h2>
<p style="margin:4px 0 0 0; font-size:12px; color:var(--text-muted);">Real-time execution monitoring and visual results</p>
</div>
<div class="results-stats-row" style="margin-left:20px;">
<span class="stat-capsule" style="font-size:11px; padding:4px 14px;">${bulk.completed} / ${bulk.total} Completed</span>
<span class="stat-capsule success" style="font-size:11px; padding:4px 14px;">${bulk.success} Success</span>
<span class="stat-capsule error" style="font-size:11px; padding:4px 14px;">${bulk.error} Failed</span>
</div>
</div>
<div style="display:flex; gap:12px; align-items:center;">
<div class="folder-selector-container">
<span class="folder-path-display" title="${folderPath}">
<i class="fa-solid fa-folder-open" style="margin-right:6px; color:var(--warning)"></i> ${folderPath}
</span>
<button class="btn btn-ghost" style="padding:0 12px; height:100%; border-radius:0; border-left:1px solid #3f3f46; font-size:11px;" onclick="App.browseServerFolder()">
Browse Folder
</button>
<button class="btn btn-primary" style="padding:0 12px; height:100%; border-radius:0;" onclick="App.saveToServerFolder()" ${bulk.results.length === 0 ? 'disabled' : ''}>
<i class="fa-solid fa-cloud-arrow-up"></i> Save all to folder
</button>
</div>
<button class="btn btn-ghost" style="border:1px solid var(--border); height:34px; font-size:12px;" onclick="App.saveAllResults()" ${bulk.results.length === 0 ? 'disabled' : ''}>
<i class="fa-solid fa-file-zipper"></i> ZIP
</button>
<button class="btn btn-ghost" style="border:1px solid var(--border); height:34px; font-size:12px;" onclick="App.downloadHistory()" ${bulk.results.length === 0 ? 'disabled' : ''}>
<i class="fa-solid fa-file-csv"></i> CSV
</button>
<button class="btn btn-ghost btn-danger" style="height:34px; font-size:12px; color:white;" onclick="App.closeFullscreenResults()">
<i class="fa-solid fa-compress"></i> Close Fullscreen
</button>
</div>
</div>
<div class="progress-track" style="margin-bottom:20px; height:4px; border-radius:2px; background:rgba(255,255,255,0.05); overflow:hidden;">
<div class="progress-fill" style="width:${pct}%; background:${statusColor}; height:100%; transition: width 0.3s ease;"></div>
</div>
<div class="fullscreen-results-grid">
${cardsHTML || `<div style="grid-column: 1/-1; text-align: center; color: var(--text-muted); padding: 80px; font-style: italic;"><i class="fa-solid fa-spinner fa-spin" style="margin-right:10px; font-size:24px;"></i>Executing batch requests, processing results...</div>`}
</div>
`;
if (!modal) {
modal = document.createElement('div');
modal.className = 'fullscreen-results-overlay';
modal.id = 'fullscreen-results-overlay';
modal.innerHTML = contentHTML;
document.body.appendChild(modal);
} else {
modal.innerHTML = contentHTML;
}
},
closeFullscreenResults() {
const modal = document.getElementById('fullscreen-results-overlay');
if (modal) {
modal.remove();
}
},
async browseServerFolder() {
try {
const res = await fetch('/api/browse_folder', {
method: 'POST'
});
const data = await res.json();
if (data.success) {
this.state.outputFolderPath = data.path;
this.saveState();
this.render();
this.toast(`Folder selected: ${data.path}`);
} else {
this.toast(data.error || 'Failed to browse folder', 'error');
}
} catch (e) {
this.toast(`Error browsing folder: ${e.message}`, 'error');
}
},
async saveToServerFolder() {
if (!this.state.bulk.results.length) return this.toast('No results to save', 'error');
if (!this.state.outputFolderPath) {
this.toast('Please select an output folder first', 'error');
await this.browseServerFolder();
if (!this.state.outputFolderPath) return;
}
try {
this.toast('Saving files to server folder...', 'info');
// First ensure the latest run is persisted on the server
await this.saveLastRunToServer();
// Ask the server to save from its own copy (avoids sending huge binary payloads)
const res = await fetch('/api/save_folder_from_lastrun', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ path: this.state.outputFolderPath })
});
const data = await res.json();
if (data.success) {
const errMsg = data.errors && data.errors.length > 0 ? ` (${data.errors.length} errors)` : '';
this.toast(`Saved ${data.count} files to ${this.state.outputFolderPath}${errMsg}`);
if (data.errors && data.errors.length > 0) {
console.warn('Save errors:', data.errors);
}
} else {
this.toast(`Failed to save: ${data.error}`, 'error');
}
} catch (e) {
this.toast(`Error saving to folder: ${e.message}`, 'error');
}
},
async saveIndividualToServerFolder(index) {
const result = this.state.bulk.results.find(r => r.index === index);
if (!result) return;
if (!this.state.outputFolderPath) {
this.toast('Please select an output folder first', 'error');
await this.browseServerFolder();
if (!this.state.outputFolderPath) return;
}
try {
// Ensure server has latest run data
await this.saveLastRunToServer();
const res = await fetch('/api/save_folder_from_lastrun', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
path: this.state.outputFolderPath,
indices: [index]
})
});
const data = await res.json();
if (data.success && data.count > 0) {
this.toast(`Saved file #${index} to server folder`);
} else {
this.toast(`Failed to save: ${data.error || (data.errors && data.errors[0]) || 'Unknown error'}`, 'error');
}
} catch (e) {
this.toast(`Error saving file: ${e.message}`, 'error');
}
},
downloadIndividualResult(index) {
const result = this.state.bulk.results.find(r => r.index === index);
if (!result) return;
try {
const finalFilename = this.getFinalFilename(result);
let blob;
if (result.binaryData) {
const bytes = new Uint8Array(result.binaryData.match(/.{1,2}/g).map(byte => parseInt(byte, 16)));
blob = new Blob([bytes], { type: result.contentType || 'application/octet-stream' });
} else if (result.fullContent) {
blob = new Blob([result.fullContent], { type: result.contentType || 'text/plain' });
} else {
return this.toast('No content to download', 'error');
}
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = finalFilename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
this.toast(`Downloaded "${finalFilename}"`);
} catch (e) {
this.toast(`Download failed: ${e.message}`, 'error');
}
},
clearBulkResults() {
if (confirm("Are you sure you want to clear all batch results?")) {
this.state.bulk.results = [];
this.state.bulk.completed = 0;
this.state.bulk.success = 0;
this.state.bulk.error = 0;
this.state.bulk.total = 0;
this.state.bulk.running = false;
this.saveState();
this.saveLastRunToServer();
this.render();
}
},
toggleGridMaximized() {
this.state.gridMaximized = !this.state.gridMaximized;
this.render();
},
// --- Actions ---
addParam(section) {
const item = { id: Date.now().toString() + Math.random(), key: '', value: '', type: 'text', enabled: true };
if (section === 'params') this.state.params.push(item);
if (section === 'headers') this.state.headers.push(item);
if (section === 'body') this.state.bodyData.push(item);
this.render();
this.saveState();
},
removeParam(section, id) {
if (section === 'params') this.state.params = this.state.params.filter(p => p.id !== id);
if (section === 'headers') this.state.headers = this.state.headers.filter(p => p.id !== id);
if (section === 'body') this.state.bodyData = this.state.bodyData.filter(p => p.id !== id);
this.render();
this.saveState();
},
updateParam(section, id, field, value) {
const list = section === 'params' ? this.state.params : (section === 'headers' ? this.state.headers : this.state.bodyData);
const item = list.find(p => p.id === id);
if (item) {
item[field] = value;
this.saveState();
// Re-render if type changes to show/hide file input
if (field === 'type' || field === 'enabled') this.render();
}
},
// --- Request Execution ---
async sendRequest() {
if (!this.state.url) return this.toast('URL is required', 'error');
// Reset bulk results upon sending another single request
this.state.bulk.results = [];
this.state.bulk.completed = 0;
this.state.bulk.success = 0;
this.state.bulk.error = 0;
this.state.bulk.total = 0;
this.state.response = { status: 'Sending...', headers: {} };
this.state.responseTab = 'response'; // Switch view
this.render();
this.saveLastRunToServerThrottled();
try {
const start = Date.now();
const res = await this.executeRequest(0);
const latency = Date.now() - start;
res.latency = latency;
this.state.response = res;
this.saveToCollection(res.status_code || 500);
} catch (e) {
this.state.response = { error: e.message };
}
this.render();
this.saveState();
await this.saveLastRunToServer();
},
// --- Bulk Execution ---
async runBulk() {
if (!this.state.url) return this.toast('URL is required', 'error');
// Calculate total items based on folders or lists
let maxFiles = 0;
let maxList = 0;
const currentRunId = Date.now();
this.state.bulk.currentRunId = currentRunId;
// Check folders first - only those that will actually be used
const folders = [
...this.state.params.filter(p => p.type === 'folder' && p.enabled && p.key && p.key.trim()),
...(this.state.bodyType === 'form-data' ? this.state.bodyData.filter(p => p.type === 'folder' && p.enabled && p.key && p.key.trim()) : [])
];
if (folders.length > 0) {
// Find max file count
for (const f of folders) {
const files = this.fileStore.get(f.id);
if (files && files.length > maxFiles) maxFiles = files.length;
}
}
// Check lists (params, body, headers) - only those with keys
const allLists = [
...this.state.params.filter(p => p.type === 'list' && p.enabled && p.key && p.key.trim()),
...(this.state.bodyType === 'form-data' ? this.state.bodyData.filter(p => p.type === 'list' && p.enabled && p.key && p.key.trim()) : []),
...this.state.headers.filter(h => h.type === 'list' && h.enabled && h.key && h.key.trim())
];
if (allLists.length > 0) {
// Find the longest list
for (const listParam of allLists) {
const val = listParam.value || '';
const arr = val.split(/[\n,]+/).map(s => s.trim()).filter(s => s);
if (arr.length > maxList) maxList = arr.length;
}
}
let total = 0;
if (this.state.bulk.strategy === 'cartesian' && maxFiles > 0 && maxList > 0) {
total = maxFiles * maxList;
} else {
total = Math.max(maxFiles, maxList);
}
// If still no total, ask user
if (total === 0) {
const p = prompt('Enter number of repetitions:', '10');
total = parseInt(p) || 0;
}
if (total <= 0) return this.toast('Invalid bulk count', 'error');
// Init Bulk State
this.state.bulk.running = true;
this.state.bulk.total = total;
this.state.bulk.completed = 0;
this.state.bulk.success = 0;
this.state.bulk.error = 0;
this.state.bulk.results = [];
this.state.responseTab = 'results';
this.saveToCollection('BULK');
this.render();
// Execution Queue
const concurrency = Math.max(1, Math.min(20, this.state.bulk.concurrency || 1));
let active = 0;
let nextIndex = 0;
const worker = async () => {
while (nextIndex < total && this.state.bulk.running && this.state.bulk.currentRunId === currentRunId) {
const index = nextIndex++;
active++;
let fileIndex = index;
let listIndex = index;
if (this.state.bulk.strategy === 'cartesian' && maxFiles > 0 && maxList > 0) {
fileIndex = Math.floor(index / maxList);
listIndex = index % maxList;
}
// Determine input filename for this index
const inputFilename = this.getInputFilename(index, fileIndex, listIndex);
try {
const res = await this.executeRequest(index, fileIndex, listIndex);
// Safety: if run was stopped or restarted, discard
if (this.state.bulk.currentRunId !== currentRunId) return;
const isSuccess = res.status_code >= 200 && res.status_code < 300;
if (isSuccess) this.state.bulk.success++; else this.state.bulk.error++;
this.state.bulk.results.push({
index: index + 1,
status: res.status_code,
latency: res.latency || 0,
data: res.content ? res.content.substring(0, 100) : (res.binary_data ? '[Binary]' : ''),
fullContent: res.content,
binaryData: res.binary_data,
contentType: res.content_type,
headers: res.headers,
inputFilename: inputFilename
});
// Sort by index to maintain perfect sequence in UI and saved folders
this.state.bulk.results.sort((a, b) => a.index - b.index);
// Limit result history to last 1000 to prevent memory issues
if (this.state.bulk.results.length > 1000) this.state.bulk.results.shift();
} catch (e) {
if (this.state.bulk.currentRunId !== currentRunId) return;
this.state.bulk.error++;
this.state.bulk.results.push({
index: index + 1,
status: 'ERR',
latency: 0,
data: e.message,
inputFilename: inputFilename
});
this.state.bulk.results.sort((a, b) => a.index - b.index);
} finally {
active--;
this.state.bulk.completed++;
// Update the UI completely in real-time
if (this.state.bulk.currentRunId === currentRunId) {
this.updateBulkProgressUI();
}
}
}
if (active === 0 && nextIndex >= total && this.state.bulk.currentRunId === currentRunId) {
this.state.bulk.running = false;
this.render(); // Final render
this.toast('Bulk Operation Completed');
await this.saveLastRunToServer();
}
};
// Spawn workers
for (let i = 0; i < concurrency; i++) {
worker();
}
},
stopBulk() {
this.state.bulk.running = false;
this.render();
},
async executeRequest(index, fileIndex = index, listIndex = index) {
const start = Date.now();
// Headers
const headers = {};
this.state.headers.filter(h => h.enabled && h.key && h.key.trim()).forEach(h => {
// Handle list replacement in headers too
let val = h.value;
if (h.type === 'list') {
const arr = val.split(/[\n,]+/).map(s => s.trim()).filter(s => s);
if (arr.length > 0) val = arr[listIndex % arr.length];
}
headers[h.key.trim()] = val;
});
// Auth
const auth = this.state.auth;
if (auth.type === 'bearer') headers['Authorization'] = `Bearer ${auth.token}`;
else if (auth.type === 'basic') headers['Authorization'] = 'Basic ' + btoa(`${auth.username}:${auth.password}`);
else if (auth.type === 'apikey') headers[auth.key] = auth.value;
// URL Params
const urlObj = new URL(this.state.url);
this.state.params.filter(p => p.enabled && p.key && p.key.trim()).forEach(p => {
let val = p.value;
// List handling
if (p.type === 'list') {
// Try splitting by newline first if present, else comma
const arr = val.split(/[\n,]+/).map(s => s.trim()).filter(s => s);
if (arr.length > 0) val = arr[listIndex % arr.length];
}
// File logic not applicable for URL params usually, skipping
urlObj.searchParams.append(p.key, val);
});
// Payload Construction
const finalData = new FormData();
finalData.append('method', this.state.method);
finalData.append('url', urlObj.toString());
finalData.append('headers', JSON.stringify(headers));
// Add auth config for server-side handling if needed (e.g. Basic Auth via requests arg)
if (auth.type === 'basic') finalData.append('auth', JSON.stringify({ type: 'basic', username: auth.username, password: auth.password }));
// Body
if (this.state.bodyType === 'json') {
finalData.append('body_type', 'json');
finalData.append('body', this.state.jsonBody);
} else if (this.state.bodyType === 'form-data') {
finalData.append('body_type', 'form-data');
this.state.bodyData.filter(p => p.enabled && (p.type === 'file' || p.type === 'folder' || (p.key && p.key.trim()))).forEach(p => {
if (p.type === 'file' || p.type === 'folder') {
const files = this.fileStore.get(p.id);
if (files && files.length > 0) {
if (p.type === 'folder') {
// Folder iteration
finalData.append(p.key, files[fileIndex % files.length]);
} else {
// Single file input: send all files attached? or iterate?
// If it's a "File" type but multiple files selected, usually implies multi-upload.
// If bulk mode, maybe we want to iterate?
// Current logic: Send ALL files in the input for this request.
for (let f of files) finalData.append(p.key, f);
}
}
} else {
let val = p.value;
if (p.type === 'list') {
const arr = val.split(/[\n,]+/).map(s => s.trim()).filter(s => s);
if (arr.length > 0) val = arr[listIndex % arr.length];
}
finalData.append(p.key, val);
}
});
}
const res = await fetch('/api/proxy-request', {
method: 'POST',
body: finalData
});
const data = await res.json();
data.latency = Date.now() - start;
return data;
},
saveToCollection(lastStatus) {
if (!this.state.url) return;
// Find or create default collection
let col = this.collections.find(c => c.id === this.state.activeCollectionId);
if (!col) {
col = this.collections.find(c => c.id === 'default');
if(!col) {
col = { id: 'default', name: 'My Requests', requests: [] };
this.collections.push(col);
}
this.state.activeCollectionId = col.id;
}
// Deep copy current request data
const reqData = {
id: this.state.activeRequestId || Date.now().toString(),
name: this.state.url.split('?')[0].split('/').pop() || 'Root URL',
method: this.state.method,
url: this.state.url,
params: JSON.parse(JSON.stringify(this.state.params)),
headers: JSON.parse(JSON.stringify(this.state.headers)),
auth: JSON.parse(JSON.stringify(this.state.auth)),
bodyType: this.state.bodyType,
bodyData: JSON.parse(JSON.stringify(this.state.bodyData)),
jsonBody: this.state.jsonBody,
lastStatus: lastStatus,
lastTime: new Date().toLocaleTimeString()
};
const existingIdx = col.requests.findIndex(r => r.id === reqData.id || (r.url === reqData.url && r.method === reqData.method));
if (existingIdx >= 0) {
// Update existing
reqData.id = col.requests[existingIdx].id; // preserve ID
reqData.name = col.requests[existingIdx].name; // preserve custom name
col.requests[existingIdx] = reqData;
} else {
// Add new
col.requests.unshift(reqData);
}
this.state.activeRequestId = reqData.id;
this.saveState();
this.saveSpacesToServer();
},
loadRequest(colId, reqId) {
const col = this.collections.find(c => c.id === colId);
if(!col) return;
const req = col.requests.find(r => r.id === reqId);
if(!req) return;
this.state.activeCollectionId = colId;
this.state.activeRequestId = reqId;
this.state.method = req.method;
this.state.url = req.url;
this.state.params = JSON.parse(JSON.stringify(req.params || []));
this.state.headers = JSON.parse(JSON.stringify(req.headers || []));
this.state.auth = JSON.parse(JSON.stringify(req.auth || {type:'none'}));
this.state.bodyType = req.bodyType || 'none';
this.state.bodyData = JSON.parse(JSON.stringify(req.bodyData || []));
this.state.jsonBody = req.jsonBody || '';
this.state.response = null;
this.render();
},
deleteRequest(colId, reqId) {
const col = this.collections.find(c => c.id === colId);
if(col) col.requests = col.requests.filter(r => r.id !== reqId);
if(this.state.activeRequestId === reqId) this.state.activeRequestId = null;
this.saveState();
this.saveSpacesToServer();
this.render();
},
createCollection() {
const name = prompt("Collection Name:");
if(name) {
const id = 'col_' + Date.now();
this.collections.push({ id, name, requests: [] });
this.state.activeCollectionId = id;
this.saveState();
this.saveSpacesToServer();
this.render();
}
},
renameCollection(colId) {
if(colId === 'default') return this.toast("Cannot rename default collection", "error");
const col = this.collections.find(c => c.id === colId);
if(!col) return;
const newName = prompt("Enter new collection name:", col.name);
if(newName && newName.trim()) {
col.name = newName.trim();
this.saveState();
this.saveSpacesToServer();
this.render();
}
},
renameRequest(colId, reqId) {
const col = this.collections.find(c => c.id === colId);
if(!col) return;
const req = col.requests.find(r => r.id === reqId);
if(!req) return;
const newName = prompt("Enter new request name:", req.name);
if(newName && newName.trim()) {
req.name = newName.trim();
this.saveState();
this.saveSpacesToServer();
this.render();
}
},
deleteCollection(colId) {
if(colId === 'default') return this.toast("Cannot delete default collection", "error");
if(confirm("Delete this collection entirely?")) {
this.collections = this.collections.filter(c => c.id !== colId);
if(this.state.activeCollectionId === colId) this.state.activeCollectionId = 'default';
this.saveState();
this.saveSpacesToServer();
this.render();
}
},
addRequestToCollection(colId) {
const col = this.collections.find(c => c.id === colId);
if (!col) return;
const reqId = 'req_' + Date.now();
const newReq = {
id: reqId,
name: 'New Request',
method: 'GET',
url: '',
description: '',
params: [{ id: Date.now().toString() + Math.random(), key: '', value: '', type: 'text', enabled: true }],
headers: [{ id: Date.now().toString() + Math.random(), key: '', value: '', type: 'text', enabled: true }],
auth: { type: 'none' },
bodyType: 'none',
bodyData: [],
jsonBody: ''
};
col.requests.push(newReq);
// Auto-select this request
this.state.activeCollectionId = colId;
this.state.activeRequestId = reqId;
this.state.method = newReq.method;
this.state.url = newReq.url;
this.state.params = newReq.params;
this.state.headers = newReq.headers;
this.state.auth = newReq.auth;
this.state.bodyType = newReq.bodyType;
this.state.bodyData = newReq.bodyData;
this.state.jsonBody = newReq.jsonBody;
this.state.response = null;
this.saveState();
this.saveSpacesToServer();
this.render();
this.toast("Added new request to collection");
},
updateActiveRequestName(name) {
const activeSpace = this.state.spaces.find(s => s.id === this.state.activeSpaceId);
const col = activeSpace ? activeSpace.collections.find(c => c.id === this.state.activeCollectionId) : null;
const activeReq = col ? col.requests.find(r => r.id === this.state.activeRequestId) : null;
if (activeReq) {
activeReq.name = name.trim() || 'Untitled Request';
this.saveState();
this.saveSpacesToServer();
this.render();
}
},
updateActiveRequestDescription(desc) {
const activeSpace = this.state.spaces.find(s => s.id === this.state.activeSpaceId);
const col = activeSpace ? activeSpace.collections.find(c => c.id === this.state.activeCollectionId) : null;
const activeReq = col ? col.requests.find(r => r.id === this.state.activeRequestId) : null;
if (activeReq) {
activeReq.description = desc;
this.saveState();
this.saveSpacesToServer();
}
},
downloadHistory() {
if (!this.state.bulk.results.length) return;
const csvContent = "data:text/csv;charset=utf-8,"
+ "Index,Status,Latency (ms),Snippet\n"
+ this.state.bulk.results.map(r => `${r.index},${r.status},${r.latency},"${(r.data || '').replace(/"/g, '""').replace(/\n/g, ' ')}"`).join("\n");
const encodedUri = encodeURI(csvContent);
const link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", `bulk_results_${new Date().toISOString()}.csv`);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
},
// Get the input filename for a given bulk index
getInputFilename(index, fileIndex = index, listIndex = index) {
// Build list of active params that could provide a name
const activeParams = [
...this.state.params.filter(p => p.enabled && p.key && p.key.trim()),
...(this.state.bodyType === 'form-data' ? this.state.bodyData.filter(p => p.enabled && p.key && p.key.trim()) : [])
];
let folderName = null;
// Priority 1: Folder type (usually high-intent for naming)
const folderParam = activeParams.find(p => p.type === 'folder');
if (folderParam) {
const files = this.fileStore.get(folderParam.id);
if (files && files.length > 0) {
const file = files[fileIndex % files.length];
folderName = file.webkitRelativePath || file.name;
}
}
let listName = null;
// Priority 2: List in Body (user's specific request context)
if (this.state.bodyType === 'form-data') {
const bodyList = this.state.bodyData.find(p => p.type === 'list' && p.enabled && p.key && p.key.trim());
if (bodyList) {
const arr = bodyList.value.split(/[\n,]+/).map(s => s.trim()).filter(s => s);
if (arr.length > 0) listName = arr[listIndex % arr.length];
}
}
// Priority 3: Any other list
if (!listName) {
const listParam = activeParams.find(p => p.type === 'list');
if (listParam) {
const val = listParam.value || '';
const arr = val.split(/[\n,]+/).map(s => s.trim()).filter(s => s);
if (arr.length > 0) listName = arr[listIndex % arr.length];
}
}
if (folderName && listName) {
// Strip extension from folderName, add listName, re-add extension
let base = folderName;
let ext = '';
const lastDot = folderName.lastIndexOf('.');
if (lastDot !== -1 && lastDot > 0 && folderName.length - lastDot <= 6) {
base = folderName.substring(0, lastDot);
ext = folderName.substring(lastDot);
}
// Replace any invalid characters in listName just in case, though usually fine
const safeListName = listName.replace(/[\/\\]/g, '_');
return `${base}_${safeListName}${ext}`;
} else if (folderName) {
return folderName;
} else if (listName) {
return listName;
}
return `result_${index + 1}`;
},
// Get the final filename with appropriate extension if missing
getFinalFilename(result) {
let name = result.inputFilename || `result_${result.index}`;
// Check if name already has a likely extension (last dot within 5 chars of end)
const parts = name.split('.');
const hasExt = parts.length > 1 && parts[parts.length-1].length <= 5;
if (hasExt) return name;
// Map common content types
const ct = (result.contentType || '').toLowerCase();
if (ct.includes('image/png')) return name + '.png';
if (ct.includes('image/jpeg') || ct.includes('image/jpg')) return name + '.jpg';
if (ct.includes('image/gif')) return name + '.gif';
if (ct.includes('image/webp')) return name + '.webp';
if (ct.includes('image/svg')) return name + '.svg';
if (ct.includes('application/pdf')) return name + '.pdf';
if (ct.includes('application/json')) return name + '.json';
if (ct.includes('application/xml') || ct.includes('text/xml')) return name + '.xml';
if (ct.includes('text/html')) return name + '.html';
if (ct.includes('text/csv')) return name + '.csv';
if (ct.includes('text/css')) return name + '.css';
if (ct.includes('text/plain')) return name + '.txt';
if (ct.includes('application/zip')) return name + '.zip';
// Fallback for other binary types: try to extract subtype
if (result.binaryData && ct.includes('/')) {
const subtype = ct.split('/')[1].split(';')[0]; // handle "type/subtype;charset=..."
if (subtype && subtype.length <= 4 && /^[a-z0-9]+$/.test(subtype)) {
return name + '.' + subtype;
}
}
return name;
},
async saveAsFolder() {
if (!this.state.bulk.results.length) return this.toast('No results to save', 'error');
try {
if (!window.showDirectoryPicker) {
return this.toast('Your browser does not support native folder saving. Please use the ZIP button instead.', 'error');
}
this.toast('Select a folder to save files...', 'info');
const dirHandle = await window.showDirectoryPicker({
mode: 'readwrite'
});
let savedCount = 0;
let errors = 0;
const usedNames = new Set();
for (const r of this.state.bulk.results) {
try {
let filename = this.getFinalFilename(r);
let base = filename;
let ext = '';
const lastDot = filename.lastIndexOf('.');
if (lastDot !== -1 && lastDot > 0) {
base = filename.substring(0, lastDot);
ext = filename.substring(lastDot);
}
let counter = 1;
while (usedNames.has(filename)) {
filename = `${base}_${counter}${ext}`;
counter++;
}
usedNames.add(filename);
// Get the content as binary data
let data;
if (r.binaryData) {
// Convert hex string to Uint8Array
data = new Uint8Array(r.binaryData.match(/.{1,2}/g).map(byte => parseInt(byte, 16)));
} else if (r.fullContent) {
data = r.fullContent;
} else {
continue; // Skip empty results
}
// Create file and write content
const fileHandle = await dirHandle.getFileHandle(filename, { create: true });
const writable = await fileHandle.createWritable();
await writable.write(data);
await writable.close();
savedCount++;
} catch (e) {
console.error('Error saving file', r.index, e);
errors++;
}
}
if (errors > 0) {
this.toast(`Saved ${savedCount} files. Failed to save ${errors} files.`, 'warning');
} else {
this.toast(`Successfully saved ${savedCount} files to the selected folder.`);
}
} catch (e) {
console.error(e);
if (e.name === 'AbortError') {
this.toast('Folder selection cancelled.', 'info');
} else {
this.toast('Failed to save to folder: ' + e.message, 'error');
}
}
},
async saveAllResults() {
if (!this.state.bulk.results.length) return this.toast('No results to save', 'error');
if (typeof JSZip === 'undefined') return this.toast('JSZip library not loaded. Please refresh.', 'error');
this.toast('Building ZIP file...', 'info');
const zip = new JSZip();
let savedCount = 0;
const usedNames = new Set();
for (const result of this.state.bulk.results) {
try {
// Use the tracked input filename + auto extension
let filename = this.getFinalFilename(result);
let base = filename;
let ext = '';
const lastDot = filename.lastIndexOf('.');
if (lastDot !== -1 && lastDot > 0) {
base = filename.substring(0, lastDot);
ext = filename.substring(lastDot);
}
let counter = 1;
while (usedNames.has(filename)) {
filename = `${base}_${counter}${ext}`;
counter++;
}
usedNames.add(filename);
// Get the content as binary data
let data;
if (result.binaryData) {
// Convert hex string to Uint8Array
data = new Uint8Array(result.binaryData.match(/.{1,2}/g).map(byte => parseInt(byte, 16)));
} else if (result.fullContent) {
data = result.fullContent;
} else {
continue; // Skip empty results
}
// Add to ZIP (JSZip handles folder creation from path automatically)
zip.file(filename, data, { binary: !!result.binaryData });
savedCount++;
} catch (e) {
console.error('Error adding result to ZIP', result.index, e);
}
}
if (savedCount === 0) return this.toast('No valid results to save', 'error');
// Generate and download ZIP
try {
const blob = await zip.generateAsync({ type: 'blob' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `bulk_results_${new Date().toISOString().replace(/[:.]/g, '-')}.zip`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
this.toast(`ZIP saved with ${savedCount} files`, 'info');
} catch (e) {
this.toast('Error generating ZIP: ' + e.message, 'error');
}
},
// --- Rendering ---
render() {
const root = document.getElementById('app-root');
if (root) {
// Reset base class first to prevent layout/theme clashing
root.className = 'workspace';
if (this.state.bulk.results.length > 0 || this.state.bulk.running) {
root.classList.add('bulk-active');
}
if (this.state.gridMaximized || !this.state.activeSpaceId) {
root.classList.add('grid-maximized');
}
// Add theme class for active space
if (this.state.activeSpaceId) {
const activeSpace = this.state.spaces.find(s => s.id === this.state.activeSpaceId);
const theme = activeSpace && activeSpace.theme ? activeSpace.theme : 'violet';
root.classList.add(`theme-${theme}`);
}
}
this.renderSidebar();
this.renderMain();
this.renderResponse();
},
renderProgress() {
// Optimized partial render for progress bar
const bar = document.getElementById('progress-bar-fill');
const text = document.getElementById('progress-text');
if (bar && text) {
const pct = (this.state.bulk.completed / this.state.bulk.total) * 100;
bar.style.width = `${pct}%`;
text.innerText = `${this.state.bulk.completed} / ${this.state.bulk.total}`;
}
},
getCollectionsHTML() {
const query = (this.state.searchQuery || '').toLowerCase().trim();
let collectionsHTML = '';
this.collections.forEach(col => {
const isColActive = this.state.activeCollectionId === col.id;
// Filter requests
const filteredRequests = col.requests.filter(r => {
if (!query) return true;
return (
(r.name || '').toLowerCase().includes(query) ||
(r.url || '').toLowerCase().includes(query) ||
(r.description || '').toLowerCase().includes(query)
);
});
// Decide if the collection itself matches
const colMatches = (col.name || '').toLowerCase().includes(query);
// If neither collection matches nor has matching requests, skip rendering it
if (query && !colMatches && filteredRequests.length === 0) {
return;
}
// If there's a query and we have matches, auto-expand the collection
const isExpanded = query ? true : isColActive;
const reqsHTML = (query && colMatches ? col.requests : filteredRequests).map(r => `
<div class="history-item ${this.state.activeRequestId === r.id ? 'active-request' : ''}" onclick="App.loadRequest('${col.id}', '${r.id}')">
<span class="method-badge m-${r.method}">${r.method}</span>
<div style="flex:1; overflow:hidden;">
<div style="white-space:nowrap; overflow:hidden; text-overflow:ellipsis; font-size:12px; color:var(--text-main); font-weight:500;" title="${this.escapeHTML(r.name || '')}">
${this.escapeHTML(r.name || '')}
</div>
<div style="font-size:10px; color:var(--text-muted); text-overflow:ellipsis; overflow:hidden; white-space:nowrap;" title="${this.escapeHTML(r.url || 'No URL')}">
${this.escapeHTML(r.url || 'No URL')}
</div>
</div>
<button class="btn-ghost" style="padding:4px;" onclick="event.stopPropagation(); App.renameRequest('${col.id}', '${r.id}');" title="Rename">
<i class="fa-solid fa-pencil" style="font-size:10px;"></i>
</button>
<button class="btn-ghost" style="padding:4px 6px; font-size:14px; opacity: 0.5;" onclick="event.stopPropagation(); App.deleteRequest('${col.id}', '${r.id}');" title="Delete">
<i class="fa-solid fa-xmark"></i>
</button>
</div>
`).join('');
collectionsHTML += `
<div class="collection-group ${isExpanded ? 'expanded' : ''}">
<div class="collection-header" onclick="App.state.activeCollectionId = '${col.id}'; App.render();">
<i class="fa-solid ${isExpanded ? 'fa-folder-open' : 'fa-folder'}" style="color:var(--warning)"></i>
<span style="flex:1; margin-left:8px; font-weight:600; font-size:12px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;" title="${this.escapeHTML(col.name)}">${this.escapeHTML(col.name)}</span>
<button class="btn-ghost" style="padding:2px; margin-right:4px;" onclick="event.stopPropagation(); App.shareCollection('${col.id}')" title="Share Collection">
<i class="fa-solid fa-share-nodes" style="font-size:10px;"></i>
</button>
<button class="btn-ghost" style="padding:2px; margin-right:4px;" onclick="event.stopPropagation(); App.addRequestToCollection('${col.id}')" title="Add Request">
<i class="fa-solid fa-circle-plus" style="font-size:10px; color:var(--primary);"></i>
</button>
${col.id !== 'default' ? `
<button class="btn-ghost" style="padding:2px; margin-right:4px;" onclick="event.stopPropagation(); App.renameCollection('${col.id}')" title="Rename Collection">
<i class="fa-solid fa-pencil" style="font-size:10px;"></i>
</button>
<button class="btn-ghost" style="padding:2px 6px;" onclick="event.stopPropagation(); App.deleteCollection('${col.id}')" title="Delete Collection">
<i class="fa-solid fa-trash" style="font-size:10px;"></i>
</button>
` : ''}
</div>
${isExpanded ? `<div class="collection-items">${reqsHTML || '<div style="padding:10px 20px; color:var(--text-muted); font-size:11px; font-style:italic;">Empty Collection</div>'}</div>` : ''}
</div>
`;
});
return collectionsHTML;
},
filterSidebarCollections(query) {
this.state.searchQuery = query;
const listEl = document.getElementById('sidebar-collections-list');
if (listEl) {
listEl.innerHTML = this.getCollectionsHTML();
}
// Also update clear button visibility
const clearBtn = document.getElementById('search-clear-btn');
if (clearBtn) {
clearBtn.style.display = query ? 'block' : 'none';
}
},
renderSidebar() {
const collectionsHTML = this.getCollectionsHTML();
const activeSpace = this.state.spaces.find(s => s.id === this.state.activeSpaceId);
let notificationsBannerHTML = '';
if (activeSpace && activeSpace.notifications && activeSpace.notifications.length > 0) {
notificationsBannerHTML = `
<div class="notifications-banner" onclick="App.openNotificationsModal()">
<i class="fa-solid fa-bell"></i>
<span>You have ${activeSpace.notifications.length} pending share request${activeSpace.notifications.length > 1 ? 's' : ''}</span>
</div>
`;
}
const spaceOptionsHTML = `
<option value="" ${!this.state.activeSpaceId ? 'selected' : ''}>Workspaces Dashboard</option>
${this.state.spaces.map(s => `
<option value="${s.id}" ${s.id === this.state.activeSpaceId ? 'selected' : ''}>
${this.escapeHTML(s.name)}
</option>
`).join('')}
`;
const sidebarHeaderHTML = `
<div class="sidebar-header" style="display:flex; flex-direction:column; padding: 16px 20px; border-bottom: 1px solid var(--border); flex-shrink:0; gap: 8px;">
<div style="display:flex; justify-content:space-between; align-items:center; width:100%;">
<div style="display:flex; align-items:center; gap:8px; font-weight:700; font-size:11px; color:var(--text-muted); letter-spacing:0.05em; text-transform:uppercase;">
<i class="fa-solid fa-cube" style="color:var(--primary)"></i> Workspace
</div>
<button class="btn-ghost" style="padding:2px 6px; font-size:10px; border-radius:4px; display:flex; align-items:center; gap:4px;" onclick="App.createSpace()" title="Create New Workspace">
<i class="fa-solid fa-plus"></i> New
</button>
</div>
<div style="position:relative; width:100%;">
<select class="space-switcher-select" onchange="this.value ? App.openSpace(this.value) : App.showSpacesDashboard()" style="width:100%; padding:8px 12px; padding-right:30px; background:var(--input-bg); border:1px solid var(--border); border-radius:var(--radius-md); color:var(--text-main); font-size:13px; font-weight:600; cursor:pointer; -webkit-appearance:none; -moz-appearance:none; appearance:none;">
${spaceOptionsHTML}
</select>
<i class="fa-solid fa-chevron-down" style="position:absolute; right:12px; top:50%; transform:translateY(-50%); color:var(--text-muted); pointer-events:none; font-size:10px;"></i>
</div>
</div>
`;
this.dom.sidebar.innerHTML = `
${sidebarHeaderHTML}
${activeSpace ? `
${notificationsBannerHTML}
<div class="sidebar-header" style="display:flex; justify-content:space-between; align-items:center; margin-top: 5px; padding: 12px 20px 8px 20px;">
<div style="font-size:10px; font-weight:700; color:var(--text-muted);"><i class="fa-solid fa-folder-open" style="margin-right:6px; color:var(--warning)"></i> COLLECTIONS</div>
<button class="btn-ghost" onclick="App.createCollection()" title="New Collection"><i class="fa-solid fa-plus"></i></button>
</div>
<div class="sidebar-search-container" style="padding: 0 10px 10px 10px; flex-shrink: 0;">
<div style="position:relative; display:flex; align-items:center;">
<i class="fa-solid fa-magnifying-glass" style="position:absolute; left:10px; color:var(--text-muted); font-size:11px;"></i>
<input type="text" class="sidebar-search-input" placeholder="Search collections/requests..." value="${this.state.searchQuery || ''}" oninput="App.filterSidebarCollections(this.value)" style="width:100%; padding:6px 10px 6px 28px; background:var(--input-bg); border:1px solid var(--border); border-radius:var(--radius-sm); color:var(--text-main); font-size:11px;">
<i id="search-clear-btn" class="fa-solid fa-xmark" onclick="App.filterSidebarCollections(''); document.querySelector('.sidebar-search-input').value='';" style="position:absolute; right:10px; color:var(--text-muted); font-size:11px; cursor:pointer; display: ${this.state.searchQuery ? 'block' : 'none'};"></i>
</div>
</div>
<div class="history-list" id="sidebar-collections-list" style="padding:10px; flex:1; overflow-y:auto;">
${collectionsHTML}
</div>
` : `
<div style="padding: 20px 16px; font-size:11px; color:var(--text-muted); text-align:center; font-style:italic; flex:1;">
Select a workspace from the dashboard to view collections
</div>
`}
<div style="padding:10px; border-top:1px solid var(--border); flex-shrink:0;">
<button class="btn btn-ghost" style="width:100%" onclick="localStorage.removeItem('phoenix-state-v2'); location.reload();">
<i class="fa-solid fa-rotate-right"></i> Reset App
</button>
</div>
`;
},
renderMain() {
if (!this.state.activeSpaceId) {
// Render Spaces Dashboard Grid View
const spacesCardsHTML = this.state.spaces.map(s => {
const count = s.collections ? s.collections.length : 0;
const notifCount = s.notifications ? s.notifications.length : 0;
const theme = s.theme || 'violet';
return `
<div class="space-card space-card-${theme}" onclick="App.openSpace('${s.id}')">
<div class="space-card-icon">
<i class="fa-solid fa-cubes"></i>
${notifCount > 0 ? `<span class="space-card-notif-badge">${notifCount}</span>` : ''}
</div>
<div class="space-card-info">
<h3>${this.escapeHTML(s.name)}</h3>
<span>${count} Collections</span>
</div>
<div class="space-card-actions" onclick="event.stopPropagation();">
<button class="btn btn-ghost" style="color:var(--text-muted); padding:4px;" onclick="App.renameSpace('${s.id}')" title="Rename Space">
<i class="fa-solid fa-pencil" style="font-size:12px;"></i>
</button>
${this.state.spaces.length > 1 ? `
<button class="btn btn-ghost" style="color:var(--danger); padding:4px;" onclick="App.deleteSpace('${s.id}')" title="Delete Space">
<i class="fa-solid fa-trash" style="font-size:12px;"></i>
</button>
` : ''}
</div>
</div>
`;
}).join('');
const dashboardHTML = `
<div class="spaces-dashboard">
<div class="spaces-dash-header">
<h2>Workspaces</h2>
<p>Select a workspace to access its collections, endpoints, and history.</p>
</div>
<div class="spaces-grid">
${spacesCardsHTML}
<div class="space-card create-space-card" onclick="App.createSpace()">
<div class="space-card-icon"><i class="fa-solid fa-circle-plus"></i></div>
<div class="space-card-info">
<h3>Create New Space</h3>
<span>Add a clean workspace</span>
</div>
</div>
</div>
</div>
`;
const headerHTML = `
<div class="app-header">
<div class="brand" style="cursor:pointer;" onclick="App.showSpacesDashboard()"><i class="fa-solid fa-fire"></i> PHOENIX</div>
<div style="font-size:13px; color:var(--text-muted); font-weight:600;">
Workspace Dashboard
</div>
<div></div>
</div>
`;
this.dom.mainPanel.innerHTML = headerHTML + dashboardHTML;
return;
}
const isBulkStart = this.checkBulkStart();
const bulk = this.state.bulk;
const activeSpace = this.state.spaces.find(s => s.id === this.state.activeSpaceId);
// Header with Active Space name/switcher
const headerHTML = `
<div class="app-header">
<div class="brand" style="cursor:pointer;" onclick="App.showSpacesDashboard()" title="Back to Spaces Dashboard">
<i class="fa-solid fa-fire"></i> PHOENIX
</div>
<div style="display:flex; align-items:center; gap:8px; background:rgba(255,255,255,0.05); padding:6px 12px; border-radius:4px; font-size:12px; font-weight:600; color:var(--primary); cursor:pointer;" onclick="App.showSpacesDashboard()" title="Switch Space">
<i class="fa-solid fa-cube"></i> ${this.escapeHTML(activeSpace ? activeSpace.name : '')}
<i class="fa-solid fa-chevron-down" style="font-size:9px; opacity:0.7; margin-left:4px;"></i>
</div>
<!-- Space Theme Selector -->
<div style="display:flex; align-items:center; margin-left: -10px;">
<select class="theme-select" onchange="App.setSpaceTheme(this.value)" style="background:rgba(255,255,255,0.05); border:1px solid var(--border); color:var(--text-main); font-size:11px; padding:5px 8px; border-radius:4px; cursor:pointer;" title="Change Workspace Theme">
${[
{ id: 'violet', label: '💜 Violet Theme' },
{ id: 'cobalt', label: '💙 Cobalt Theme' },
{ id: 'rose', label: '💖 Rose Theme' },
{ id: 'emerald', label: '💚 Emerald Theme' },
{ id: 'amber', label: '💛 Amber Theme' },
{ id: 'light', label: '⚪ Light Theme' },
{ id: 'dark', label: '⚫ Dark Theme' }
].map(t => `<option value="${t.id}" ${activeSpace && activeSpace.theme === t.id ? 'selected' : ''}>${t.label}</option>`).join('')}
</select>
</div>
<div class="input-group" style="flex:1; max-width:550px; margin:0 20px;">
<select class="method-select" onchange="App.state.method = this.value; App.saveState();">
${['GET','POST','PUT','DELETE','PATCH'].map(m => `<option value="${m}" ${this.state.method===m?'selected':''}>${m}</option>`).join('')}
</select>
<input type="text" class="url-input" value="${this.state.url}"
oninput="App.state.url = this.value; App.saveState();" placeholder="https://api.example.com/v1/resource">
</div>
<div style="display:flex; gap:10px; align-items:center;">
${bulk.running
? `<button class="btn btn-danger" onclick="App.stopBulk()"><i class="fa-solid fa-stop"></i> STOP</button>`
: `<button class="btn btn-primary" onclick="${isBulkStart ? 'App.runBulk()' : 'App.sendRequest()'}">
<i class="fa-solid ${isBulkStart ? 'fa-layer-group' : 'fa-paper-plane'}"></i> ${isBulkStart ? 'RUN BATCH' : 'SEND'}
</button>`
}
</div>
</div>
`;
// Request Name & Description Details Section
const col = activeSpace ? activeSpace.collections.find(c => c.id === this.state.activeCollectionId) : null;
const activeReq = col ? col.requests.find(r => r.id === this.state.activeRequestId) : null;
const requestMetaHTML = activeReq ? `
<div class="request-meta-section" style="padding: 10px 24px; border-bottom: 1px solid var(--border); display: flex; flex-direction: column; gap: 8px; background: var(--bg-sidebar);">
<div style="display:flex; align-items:center; gap:10px;">
<span style="font-size: 11px; color: var(--text-muted); font-weight: 600; text-transform: uppercase; width: 90px; text-align: left;">Request Name:</span>
<input type="text" style="background:transparent; border:none; border-bottom:1px solid transparent; color:var(--text-main); font-weight:600; font-size:13px; padding:2px 4px; flex:1;" value="${this.escapeHTML(activeReq.name || '')}" onchange="App.updateActiveRequestName(this.value)" placeholder="Enter request name...">
</div>
<div style="display:flex; align-items:center; gap:10px;">
<span style="font-size: 11px; color: var(--text-muted); font-weight: 600; text-transform: uppercase; width: 90px; text-align: left;">Description:</span>
<input type="text" style="background:transparent; border:none; border-bottom: 1px dashed var(--border); color:var(--text-muted); font-size:12px; padding:2px 4px; flex:1;" value="${this.escapeHTML(activeReq.description || '')}" oninput="App.updateActiveRequestDescription(this.value)" placeholder="Add a description for this request...">
</div>
</div>
` : '';
// Tabs
const tabsHTML = `
<div class="tabs">
${['params', 'headers', 'body', 'auth'].map(t => `
<div class="tab ${this.state.activeTab === t ? 'active' : ''}" onclick="App.state.activeTab = '${t}'; App.render()">${t.toUpperCase()}</div>
`).join('')}
<div style="flex:1"></div>
${isBulkStart ? `
<div style="display:flex; align-items:center; font-size:11px; color:#888; padding-right:10px; gap:15px;">
<div style="display:flex; align-items:center; gap:5px;">
<span style="margin-right:5px;">Strategy:</span>
<label style="cursor:pointer;"><input type="radio" name="bulkStrategy" value="consecutive" ${this.state.bulk.strategy === 'consecutive' || !this.state.bulk.strategy ? 'checked' : ''} onchange="App.state.bulk.strategy='consecutive'; App.saveState();"> Consecutive</label>
<label style="cursor:pointer; margin-left:5px;"><input type="radio" name="bulkStrategy" value="cartesian" ${this.state.bulk.strategy === 'cartesian' ? 'checked' : ''} onchange="App.state.bulk.strategy='cartesian'; App.saveState();"> Cartesian (All x All)</label>
</div>
<div style="display:flex; align-items:center; border-left:1px solid #444; padding-left:15px;">
<span style="margin-right:5px;">Concurrency:</span>
<input type="number" min="1" max="20" style="width:40px; background:#222; border:1px solid #444; color:white; padding:2px;"
value="${this.state.bulk.concurrency}" onchange="App.state.bulk.concurrency = parseInt(this.value); App.saveState();">
</div>
</div>
` : ''}
</div>
`;
// Content
let contentHTML = '';
if (this.state.activeTab === 'params') contentHTML = this.renderTable(this.state.params, 'params');
else if (this.state.activeTab === 'headers') contentHTML = this.renderTable(this.state.headers, 'headers');
else if (this.state.activeTab === 'body') contentHTML = this.renderBodyTab();
else if (this.state.activeTab === 'auth') contentHTML = this.renderAuthTab();
// Bottom Results & Response Panel (Always Rendered)
const pct = bulk.total > 0 ? (bulk.completed / bulk.total) * 100 : 0;
const statusColor = bulk.error > 0 ? (bulk.success > 0 ? 'var(--warning)' : 'var(--danger)') : 'var(--success)';
const cardsHTML = bulk.results.map(r => this.renderResultCard(r)).join('');
const folderPath = this.state.outputFolderPath || 'None selected';
const activeBottomTab = this.state.responseTab || 'response';
let bottomTabContentHTML = '';
if (activeBottomTab === 'response') {
const resp = this.state.response;
if (!resp) {
bottomTabContentHTML = `<div class="empty-state" style="padding: 40px; text-align: center; color: var(--text-muted); font-style: italic; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 10px; height: 100%; min-height: 150px;"><i class="fa-solid fa-paper-plane" style="font-size: 24px; color: var(--primary);"></i><span>Ready to send request. Click SEND to execute a single request, or RUN BATCH for bulk.</span></div>`;
} else if (resp.status === 'Sending...') {
bottomTabContentHTML = `<div class="empty-state" style="padding: 40px; text-align: center; color: var(--text-muted); font-style: italic; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 10px; height: 100%; min-height: 150px;"><i class="fa-solid fa-spinner fa-spin" style="font-size: 24px; color: var(--primary);"></i><span>Sending request...</span></div>`;
} else if (resp.error) {
bottomTabContentHTML = `<div class="error-state" style="padding: 20px; color: var(--danger); font-family: var(--font-code); font-size: 12px; white-space: pre-wrap; overflow: auto; height: 100%; max-height: 100%;">Error: ${resp.error}</div>`;
} else {
let content = resp.content;
try {
if (content && !resp.binary_data && content.trim().startsWith('{')) {
content = JSON.stringify(JSON.parse(content), null, 2);
}
} catch(e){}
bottomTabContentHTML = `
<div class="response-meta" style="display: flex; align-items: center; gap: 15px; padding: 10px 20px; border-bottom: 1px solid var(--border); font-size: 11px; background: rgba(0,0,0,0.1); flex-shrink: 0;">
<span class="status-badge" style="background:${this.getStatusColor(resp.status_code)}; color:black; font-weight:700; padding:3px 8px; border-radius:4px;">${resp.status_code}</span>
<span style="color: var(--text-muted); font-weight: 500;">${resp.latency ? resp.latency + ' ms' : ''}</span>
<span style="margin-left:auto; font-size:11px; color: var(--text-muted); font-weight: 500;">${resp.content_type || 'Unknown Type'}</span>
</div>
<div style="flex: 1; overflow: auto; padding: 15px; background: var(--input-bg);">
${resp.binary_data
? `<div style="padding:20px; text-align:center;">
<img src="data:${resp.content_type};base64,${this.hexToBase64(resp.binary_data)}"
style="max-width:100%; max-height:260px; border:1px solid var(--border); border-radius: 4px;" alt="Binary Content" />
</div>`
: `<pre class="code-block" style="margin: 0; font-family: var(--font-code); font-size: 12px; color: var(--text-main); white-space: pre-wrap; word-break: break-all;">${this.escapeHTML(content)}</pre>`
}
</div>
`;
}
} else {
if (bulk.results.length === 0) {
bottomTabContentHTML = `
<div class="empty-state" style="padding: 40px; text-align: center; color: var(--text-muted); font-style: italic; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 10px; height: 100%; min-height: 150px;">
<i class="fa-solid fa-list-check" style="font-size: 24px; color: var(--primary);"></i>
<span>No batch results yet. Run a batch to see results in a grid.</span>
</div>
`;
} else {
bottomTabContentHTML = `
<div class="progress-track" style="height:4px; width: 100%; flex-shrink: 0; background: rgba(0,0,0,0.1);">
<div id="progress-bar-fill" class="progress-fill" style="width:${pct}%; background:${statusColor}; height: 100%;"></div>
</div>
<div class="results-grid">
${cardsHTML}
</div>
`;
}
}
bottomPanelHTML = `
<div class="bottom-results-panel" style="height: ${this.state.resultsPanelHeight || 300}px; display: flex; flex-direction: column; background: var(--bg-panel); border-top: 1px solid var(--border); overflow: hidden; position: relative; flex-shrink: 0;">
<div class="results-resize-handle" onmousedown="App.startResultsResize(event)" style="height: 6px; cursor: ns-resize; background: transparent; position: absolute; top: 0; left: 0; right: 0; z-index: 100;">
</div>
<div class="results-header-bar" style="display: flex; align-items: center; justify-content: space-between; padding: 8px 20px; border-bottom: 1px solid var(--border); background: var(--bg-header); flex-shrink: 0; flex-wrap: nowrap; gap: 12px; height: 48px;">
<div class="results-title-group" style="display: flex; align-items: center; gap: 15px;">
<div class="bottom-panel-tabs" style="display: flex; gap: 4px; background: rgba(0,0,0,0.15); padding: 3px; border-radius: var(--radius-sm); border: 1px solid var(--border);">
<button class="bottom-tab ${activeBottomTab === 'response' ? 'active' : ''}" onclick="App.state.responseTab = 'response'; App.render();" style="border: none; background: ${activeBottomTab === 'response' ? 'var(--primary)' : 'transparent'}; color: ${activeBottomTab === 'response' ? '#ffffff' : 'var(--text-muted)'}; padding: 6px 14px; border-radius: var(--radius-sm); font-weight: 600; font-size: 11px; cursor: pointer; transition: all 0.2s; display: flex; align-items: center; gap: 6px;">
<i class="fa-solid fa-reply"></i> Response
</button>
<button class="bottom-tab ${activeBottomTab === 'results' ? 'active' : ''}" onclick="App.state.responseTab = 'results'; App.render();" style="border: none; background: ${activeBottomTab === 'results' ? 'var(--primary)' : 'transparent'}; color: ${activeBottomTab === 'results' ? '#ffffff' : 'var(--text-muted)'}; padding: 6px 14px; border-radius: var(--radius-sm); font-weight: 600; font-size: 11px; cursor: pointer; transition: all 0.2s; display: flex; align-items: center; gap: 6px;">
<i class="fa-solid fa-list-check"></i> Batch Results ${bulk.results.length > 0 ? `<span style="background:rgba(255,255,255,0.2); padding: 1px 6px; border-radius: 10px; font-size: 9px;">${bulk.results.length}</span>` : ''}
</button>
</div>
${bulk.results.length > 0 ? `
<div class="results-stats-row" style="display: flex; gap: 8px; align-items: center; font-size: 11px;">
<span class="stat-capsule" style="background: rgba(255,255,255,0.04); border: 1px solid var(--border); color: var(--text-main); padding: 3px 10px; border-radius: 20px; font-weight: 500;">${bulk.completed} / ${bulk.total} Completed</span>
<span class="stat-capsule success" style="background: rgba(16, 185, 129, 0.08); border: 1px solid rgba(16, 185, 129, 0.2); color: var(--success); padding: 3px 10px; border-radius: 20px; font-weight: 500;">${bulk.success} Success</span>
<span class="stat-capsule error" style="background: rgba(244, 63, 94, 0.08); border: 1px solid rgba(244, 63, 94, 0.2); color: var(--danger); padding: 3px 10px; border-radius: 20px; font-weight: 500;">${bulk.error} Failed</span>
</div>
` : ''}
</div>
${activeBottomTab === 'results' && bulk.results.length > 0 ? `
<div class="results-actions-group" style="display: flex; gap: 8px; align-items: center; flex-shrink: 0;">
<div class="folder-selector-container" style="display: flex; align-items: center; background: rgba(0,0,0,0.15); border: 1px solid var(--border); border-radius: var(--radius-sm); overflow: hidden; height: 28px;">
<span class="folder-path-display" title="${folderPath}" style="padding: 0 10px; font-size: 10px; color: var(--text-muted); max-width: 140px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
<i class="fa-solid fa-folder-open" style="margin-right:4px; color:var(--warning)"></i> ${folderPath}
</span>
<button class="btn btn-ghost" style="padding:0 8px; height:100%; border:none; border-radius:0; border-left:1px solid var(--border); font-size:10px; background: rgba(255,255,255,0.02); color: var(--text-main);" onclick="App.browseServerFolder()">
Browse
</button>
<button class="btn btn-primary" style="padding:0 10px; height:100%; border:none; border-radius:0; font-size:10px;" onclick="App.saveToServerFolder()">
<i class="fa-solid fa-cloud-arrow-up"></i> Save
</button>
</div>
<button class="btn btn-ghost" style="border:1px solid var(--border); height:28px; font-size:10px; padding: 0 10px; color: var(--text-main);" onclick="App.saveAllResults()" title="Export results ZIP">
<i class="fa-solid fa-file-zipper"></i> ZIP
</button>
<button class="btn btn-ghost" style="border:1px solid var(--border); height:28px; font-size:10px; padding: 0 10px; color: var(--text-main);" onclick="App.downloadHistory()" title="Export CSV">
<i class="fa-solid fa-file-csv"></i> CSV
</button>
<button class="btn btn-ghost" style="border:1px solid var(--border); height:28px; font-size:10px; padding: 0 10px; color: var(--text-main);" onclick="App.openFullscreenResults()">
<i class="fa-solid fa-maximize"></i> Fullscreen
</button>
<button class="btn btn-ghost btn-danger" style="height:28px; font-size:10px; color:white; padding: 0 10px;" onclick="App.clearBulkResults()">
<i class="fa-solid fa-trash"></i> Clear
</button>
</div>
` : ''}
</div>
<div class="bottom-panel-body" style="flex: 1; display: flex; flex-direction: column; overflow: hidden;">
${bottomTabContentHTML}
</div>
</div>
`;
this.dom.mainPanel.innerHTML = headerHTML + requestMetaHTML + tabsHTML + `<div class="content-area">${contentHTML}</div>` + bottomPanelHTML;
},
renderResultCard(result) {
const isImage = (result.contentType || '').toLowerCase().includes('image') && result.binaryData;
const isSuccess = result.status >= 200 && result.status < 300;
const statusClass = isSuccess ? 'status-success' : 'status-error';
const filename = result.inputFilename || `result_${result.index}`;
const finalFilename = this.getFinalFilename(result);
let previewHTML = '';
if (isImage) {
try {
const base64Data = this.hexToBase64(result.binaryData);
previewHTML = `<img src="data:${result.contentType};base64,${base64Data}" class="card-thumb" alt="${filename}" loading="lazy" />`;
} catch (e) {
previewHTML = `<div class="card-icon-fallback"><i class="fa-solid fa-triangle-exclamation"></i><span>Decode error</span></div>`;
}
} else {
let icon = 'fa-file-lines';
let typeLabel = 'TXT';
const ct = (result.contentType || '').toLowerCase();
if (ct.includes('application/json')) { icon = 'fa-file-code'; typeLabel = 'JSON'; }
else if (ct.includes('text/html')) { icon = 'fa-file-code'; typeLabel = 'HTML'; }
else if (result.status === 'ERR') { icon = 'fa-circle-xmark'; typeLabel = 'ERROR'; }
previewHTML = `
<div class="card-text-fallback">
<i class="fa-solid ${icon} fallback-icon"></i>
<span class="fallback-type">${typeLabel}</span>
<p class="fallback-snippet">${this.escapeHTML(result.data || '')}</p>
</div>`;
}
const footerHTML = isImage
? `<div class="card-tiny-footer">
<span class="tiny-status ${isSuccess ? '' : 'err'}"></span>
<span>#${result.index}</span>
<span style="margin-left:auto;font-size:9px;opacity:0.55;">${result.latency}ms</span>
</div>`
: `<div class="card-info-area">
<div class="card-meta-row">
<span class="card-index">#${result.index}</span>
<span class="card-status-badge ${statusClass}">${result.status}</span>
<span class="card-latency">${result.latency}ms</span>
</div>
<div class="card-filename" title="${finalFilename}">${finalFilename}</div>
</div>`;
return `
<div class="result-card ${statusClass} ${isImage ? 'is-image' : ''}" onclick="App.previewResult(${result.index})">
<div class="card-preview-area">
${previewHTML}
<div class="card-action-overlay">
${!isImage ? `
<button class="action-overlay-btn" onclick="event.stopPropagation(); App.previewResult(${result.index})" title="Full Preview">
<i class="fa-solid fa-eye"></i>
</button>` : ''}
<button class="action-overlay-btn" onclick="event.stopPropagation(); App.resendBulkRequest(${result.index})" title="Resend">
<i class="fa-solid fa-rotate-right"></i>
</button>
<button class="action-overlay-btn" onclick="event.stopPropagation(); App.downloadIndividualResult(${result.index})" title="Download">
<i class="fa-solid fa-arrow-down"></i>
</button>
<button class="action-overlay-btn" onclick="event.stopPropagation(); App.saveIndividualToServerFolder(${result.index})" title="Save to Folder">
<i class="fa-solid fa-folder-plus"></i>
</button>
</div>
</div>
${footerHTML}
</div>
`;
},
renderResponse() {
// No-op: Single response and bulk results have been consolidated into renderMain()'s bottom panel.
},
renderTable(items, section) {
return `
<table class="data-table">
<thead><tr><th style="width:30px"></th><th style="width:200px">Key</th><th>Value</th><th class="action-col"></th></tr></thead>
<tbody>
${items.map(item => `
<tr data-id="${item.id}" data-section="${section}">
<td><input type="checkbox" ${item.enabled ? 'checked' : ''} onchange="App.updateParam('${section}', '${item.id}', 'enabled', this.checked)"></td>
<td><input class="cell-input key-input" value="${item.key}" placeholder="Key" oninput="App.updateParam('${section}', '${item.id}', 'key', this.value)"></td>
<td style="display:flex; align-items:center;">
<select class="type-select" onchange="App.updateParam('${section}', '${item.id}', 'type', this.value)">
<option value="text" ${item.type === 'text' ? 'selected' : ''}>Text</option>
<option value="list" ${item.type === 'list' ? 'selected' : ''}>List</option>
<option value="file" ${item.type === 'file' ? 'selected' : ''}>File</option>
<option value="folder" ${item.type === 'folder' ? 'selected' : ''}>Folder</option>
</select>
${this.renderValueInput(item, section)}
</td>
<td class="action-col"><button class="btn-ghost" onclick="App.removeParam('${section}', '${item.id}')">×</button></td>
</tr>
`).join('')}
</tbody>
</table>
<button class="btn btn-ghost" style="margin:10px;" onclick="App.addParam('${section}')">+ Add Parameter</button>
`;
},
renderValueInput(item, section) {
if (item.type === 'file' || item.type === 'folder') {
const files = this.fileStore.get(item.id);
const label = files ? (item.type === 'folder' ? `${files.length} Files Selected` : `${files.length} Files`) : 'Select...';
return `
<div style="flex:1; position:relative;">
<button class="btn-ghost file-trigger" onclick="this.nextElementSibling.click()">${label}</button>
<input type="file" hidden ${item.type === 'folder' ? 'webkitdirectory directory' : 'multiple'}
onchange="App.handleFileSelect(this, '${section}', '${item.id}')">
</div>
`;
}
return `<input class="cell-input val-input" value="${item.value}" placeholder="${item.type === 'list' ? 'Values (comma or newline separated)' : 'Value'}" oninput="App.updateParam('${section}', '${item.id}', 'value', this.value)">`;
},
renderBodyTab() {
return `
<div style="padding:16px;">
<div style="margin-bottom:16px; display:flex; gap:10px;">
<label><input type="radio" name="bodyType" value="none" ${this.state.bodyType === 'none' ? 'checked' : ''} onchange="App.state.bodyType='none'; App.render(); App.saveState();"> None</label>
<label><input type="radio" name="bodyType" value="form-data" ${this.state.bodyType === 'form-data' ? 'checked' : ''} onchange="App.state.bodyType='form-data'; App.render(); App.saveState();"> Multipart Form</label>
<label><input type="radio" name="bodyType" value="json" ${this.state.bodyType === 'json' ? 'checked' : ''} onchange="App.state.bodyType='json'; App.render(); App.saveState();"> Raw JSON</label>
</div>
${this.state.bodyType === 'form-data' ? this.renderTable(this.state.bodyData, 'body') : ''}
${this.state.bodyType === 'json' ? `<textarea class="code-editor" placeholder="{ ... }" oninput="App.state.jsonBody=this.value; App.saveState();">${this.state.jsonBody}</textarea>` : ''}
</div>
`;
},
renderAuthTab() {
const auth = this.state.auth;
return `
<div style="padding:20px; max-width:400px;">
<label style="display:block; margin-bottom:8px; color:#888;">Authorization Type</label>
<select id="authType" onchange="App.state.auth.type=this.value; App.render(); App.saveState();" style="width:100%; padding:10px; background:#222; color:white; border:1px solid #444; border-radius:4px;">
<option value="none" ${auth.type === 'none' ? 'selected' : ''}>None</option>
<option value="bearer" ${auth.type === 'bearer' ? 'selected' : ''}>Bearer Token</option>
<option value="basic" ${auth.type === 'basic' ? 'selected' : ''}>Basic Auth (User/Pass)</option>
<option value="apikey" ${auth.type === 'apikey' ? 'selected' : ''}>API Key (Header)</option>
</select>
${auth.type === 'bearer' ? `
<div style="margin-top:16px;">
<label>Token</label>
<input type="text" class="cell-input" style="border:1px solid #333; border-radius:4px; margin-top:5px;" value="${auth.token || ''}" oninput="App.state.auth.token=this.value; App.saveState();">
</div>
` : ''}
${auth.type === 'basic' ? `
<div style="margin-top:16px; display:grid; gap:10px;">
<div><label>Username</label><input type="text" class="cell-input" style="border:1px solid #333; margin-top:5px;" value="${auth.username || ''}" oninput="App.state.auth.username=this.value; App.saveState();"></div>
<div><label>Password</label><input type="password" class="cell-input" style="border:1px solid #333; margin-top:5px;" value="${auth.password || ''}" oninput="App.state.auth.password=this.value; App.saveState();"></div>
</div>
` : ''}
${auth.type === 'apikey' ? `
<div style="margin-top:16px; display:grid; gap:10px;">
<div><label>Key Name</label><input type="text" class="cell-input" style="border:1px solid #333; margin-top:5px;" value="${auth.key || ''}" oninput="App.state.auth.key=this.value; App.saveState();"></div>
<div><label>Value</label><input type="text" class="cell-input" style="border:1px solid #333; margin-top:5px;" value="${auth.value || ''}" oninput="App.state.auth.value=this.value; App.saveState();"></div>
</div>
` : ''}
</div>
`;
},
// --- Helpers ---
handleFileSelect(input, section, id) {
if (input.files.length > 0) {
// Convert FileList to Array and sort by path to ensure strict processing sequence (natural sorting)
let filesArr = Array.from(input.files);
filesArr.sort((a, b) => {
const pA = a.webkitRelativePath || a.name;
const pB = b.webkitRelativePath || b.name;
return pA.localeCompare(pB, undefined, { numeric: true, sensitivity: 'base' });
});
this.fileStore.set(id, filesArr);
this.render(); // update label
}
},
checkBulkStart() {
const hasKeyedFolder = this.state.params.some(p => p.type === 'folder' && p.enabled && p.key && p.key.trim())
|| (this.state.bodyType === 'form-data' && this.state.bodyData.some(p => p.type === 'folder' && p.enabled && p.key && p.key.trim()));
const hasKeyedList = this.state.params.some(p => p.type === 'list' && p.enabled && p.key && p.key.trim())
|| (this.state.bodyType === 'form-data' && this.state.bodyData.some(p => p.type === 'list' && p.enabled && p.key && p.key.trim()))
|| this.state.headers.some(h => h.type === 'list' && h.enabled && h.key && h.key.trim());
return hasKeyedFolder || hasKeyedList;
},
getStatusColor(code) {
if (code >= 200 && code < 300) return 'var(--success)';
if (code >= 300 && code < 400) return 'var(--warning)';
if (code >= 400 || code === 'ERR') return 'var(--danger)';
return 'var(--text-muted)';
},
toast(msg, type = 'info') {
const t = document.createElement('div');
t.innerText = msg;
t.style.cssText = `
background: ${type === 'error' ? '#EF4444' : '#333'};
color: white; padding: 10px 20px; border-radius: 6px; margin-top: 10px;
box-shadow: 0 4px 12px rgba(0,0,0,0.5); font-size: 13px;
`;
this.dom.toast.appendChild(t);
setTimeout(() => t.remove(), 3000);
},
escapeHTML(str) {
if (!str) return '';
if (typeof str !== 'string') return String(str);
return str.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#039;');
},
hexToBase64(hexString) {
if (!hexString) return '';
// Strip any whitespace or non-hex chars
hexString = hexString.replace(/[^0-9a-fA-F]/g, '');
const len = hexString.length;
const bytes = new Uint8Array(len / 2);
for (let i = 0; i < len; i += 2) {
bytes[i / 2] = parseInt(hexString.substr(i, 2), 16);
}
let binary = '';
const chunk = 8192;
for (let i = 0; i < bytes.length; i += chunk) {
const subarr = bytes.subarray(i, i + chunk);
binary += String.fromCharCode.apply(null, subarr);
}
return btoa(binary);
},
bindEvents() {
// Most events are inline (onclick, onchange) for simplicity in this structure
},
// Preview a result
previewResult(index) {
const result = this.state.bulk.results.find(r => r.index === index);
if (!result) return;
const isImage = (result.contentType || '').toLowerCase().includes('image') && result.binaryData;
const finalFilename = this.getFinalFilename(result);
let contentHTML = '';
if (isImage) {
try {
const base64Data = this.hexToBase64(result.binaryData);
contentHTML = `<img src="data:${result.contentType};base64,${base64Data}" class="modal-zoom-image" alt="${finalFilename}" />`;
} catch (e) {
contentHTML = `<div class="modal-error-fallback"><i class="fa-solid fa-triangle-exclamation"></i><span>Failed to decode image preview</span></div>`;
}
} else {
let prettyContent = result.fullContent || '';
try {
if (prettyContent.trim().startsWith('{')) {
prettyContent = JSON.stringify(JSON.parse(prettyContent), null, 2);
}
} catch(e) {}
contentHTML = `<pre class="modal-zoom-code">${this.escapeHTML(prettyContent)}</pre>`;
}
const modal = document.createElement('div');
modal.className = 'premium-modal-overlay';
modal.innerHTML = `
<div class="premium-modal-card" onclick="event.stopPropagation();">
<div class="premium-modal-header">
<div class="premium-modal-title">
<i class="fa-solid ${isImage ? 'fa-image' : 'fa-file-code'}" style="color:var(--primary);"></i>
<div>
<span class="modal-title-filename" title="${finalFilename}">${finalFilename}</span>
<span class="modal-title-sub">Result #${result.index}</span>
</div>
</div>
<div style="display:flex; align-items:center; gap:8px;">
<span class="stat-capsule ${result.status >= 200 && result.status < 300 ? 'success' : 'error'}">${result.status}</span>
<span class="stat-capsule">${result.latency}ms</span>
<button class="modal-close-btn" onclick="this.closest('.premium-modal-overlay').remove()">✕</button>
</div>
</div>
<div class="premium-modal-body">
${contentHTML}
</div>
<div class="premium-modal-footer">
<button class="btn btn-ghost" style="border:1px solid var(--border)" onclick="App.downloadIndividualResult(${result.index})">
<i class="fa-solid fa-arrow-down"></i> Download File
</button>
<button class="btn btn-primary" onclick="App.saveIndividualToServerFolder(${result.index})">
<i class="fa-solid fa-folder-plus"></i> Save to server folder
</button>
</div>
</div>
`;
document.body.appendChild(modal);
modal.onclick = () => modal.remove();
},
// For manual clicking from history
loadHistoryItem(id) {
const item = this.state.history.find(h => h.id === id);
if (item) {
this.state.method = item.method;
this.state.url = item.url;
this.saveState();
this.render();
}
}
};
document.addEventListener('DOMContentLoaded', () => App.init());