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

4165 lines
204 KiB
JavaScript
Raw Normal View History

2026-10-26 17:57:34 +05:30
/**
* Phoenix App — Advanced Bulk API Tester
* Version: 3.0 (Aurum Edition)
*/
// ── Global Error & Promise Rejection Handlers ──
window.onerror = function(msg, url, lineNo, columnNo, error) {
const el = document.getElementById('error-display');
if (el) {
el.style.display = 'block';
el.innerHTML += '<div style="margin-bottom:6px;"><strong>⚠ Error:</strong> ' + msg + ' <span style="opacity:.7; font-size:11px;">(' + url + ':' + lineNo + ')</span></div>';
}
console.error('Phoenix Error:', msg, url, lineNo, columnNo, error);
return false;
};
window.onunhandledrejection = function(event) {
console.warn('Unhandled Promise Rejection:', event.reason);
};
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', 'activeCollectionId'];
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;
}
// Auto-save to localStorage only (no server call on every keypress)
return true;
}
}
target[prop] = value;
return true;
}
});
}
return this._proxyState;
},
debouncedSaveToCollection() {
if (this._autoSaveTimeout) clearTimeout(this._autoSaveTimeout);
this._autoSaveTimeout = setTimeout(() => {
this.saveToCollection();
}, 500);
},
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,
delay: 0,
repetitions: 10,
results: []
},
activeTab: 'params',
responseTab: 'response',
activeRequestId: reqData ? reqData.id : null,
activeCollectionId: reqData ? reqData.activeCollectionId : 'default',
isPreview: isPreview
};
},
fileStore: new Map(), // id -> FileList
dom: {},
_buildShell() {
// Write the complete, permanent DOM structure once.
// Individual regions are updated surgically after this — NEVER the whole mainPanel.
this.dom.sidebar.innerHTML = `
<div class="sidebar-head" id="ws-header-row">
<span class="sidebar-eyebrow"><i class="fa-solid fa-cube"></i> Workspace</span>
<button class="btn btn-ghost btn-sm" onclick="App.createSpace()" title="Create new workspace"><i class="fa-solid fa-plus"></i> New</button>
</div>
<div class="space-switcher-wrap">
<select id="ws-select" class="space-switcher-select" onchange="this.value ? App.openSpace(this.value) : App.showSpacesDashboard()"></select>
<i class="fa-solid fa-chevron-down" style="position:absolute;right:23px;top:19px;transform:translateY(-50%);color:var(--text-3);pointer-events:none;font-size:9px;"></i>
</div>
<div id="notif-banner" style="display:none;"></div>
<div id="collections-header" class="sidebar-collections-header">
<span id="collections-header-label" class="sidebar-section-label" onclick="App.toggleAllCollectionsView()" title="Toggle current workspace / all collections"><i class="fa-solid fa-layer-group"></i> Collections</span>
<button class="btn btn-ghost btn-sm" id="toggle-collapse-all-btn" style="height:25px;width:27px;padding:0;" onclick="App.toggleAllCollectionsCollapse()" title="Expand / collapse all collections"><i class="fa-solid fa-arrows-up-down"></i></button>
<button class="btn btn-ghost btn-sm" id="toggle-all-cols-btn" style="height:25px;width:27px;padding:0;" onclick="App.toggleAllCollectionsView()" title="Show all collections across all workspaces"><i class="fa-solid fa-globe"></i></button>
<button class="btn btn-ghost btn-sm" style="height:25px;width:27px;padding:0;" onclick="App.openImportFromDocModal()" title="Import API from Documentation"><i class="fa-solid fa-book-bookmark" style="color:var(--primary);"></i></button>
<button class="btn btn-ghost btn-sm" style="height:25px;width:27px;padding:0;" onclick="App.createCollection()" title="Create New Collection"><i class="fa-solid fa-plus"></i></button>
</div>
<div class="sidebar-search-container" id="search-wrap">
<i class="fa-solid fa-magnifying-glass" style="position:absolute;left:22px;top:17px;transform:translateY(-50%);color:var(--text-4);font-size:10px;pointer-events:none;z-index:1;"></i>
<input type="text" id="search-input" class="sidebar-search-input" placeholder="Search collections & endpoints…" value="" oninput="App.filterSidebarCollections(this.value)" style="padding-left:30px;padding-right:48px;">
<span class="search-kbd-badge" id="search-kbd-badge" style="position:absolute;right:22px;top:17px;transform:translateY(-50%);font-size:10px;font-family:var(--font-mono);font-weight:700;color:var(--text-4);background:rgba(255,255,255,0.06);border:1px solid rgba(255,255,255,0.08);padding:1px 5px;border-radius:4px;pointer-events:none;">⌘K</span>
<button id="search-clear-btn" class="search-clear-btn" style="display:none;top:17px;" onclick="document.getElementById('search-input').value=''; App.filterSidebarCollections('');" title="Clear search"><i class="fa-solid fa-xmark"></i></button>
</div>
<div class="history-list" id="collections-list"></div>
<div class="sidebar-footer">
<button class="btn btn-ghost sidebar-footer-btn" style="font-size:11px;" onclick="localStorage.removeItem('phoenix-state-v2');location.reload();">
<i class="fa-solid fa-rotate-right"></i> Reset App
</button>
</div>
`;
this.dom.mainPanel.innerHTML = `
<!-- DASHBOARD VIEW: shown when no space is active -->
<div id="dashboard-view" style="display:none;flex-direction:column;height:100%;overflow:auto;">
<div class="app-header" id="dash-header">
<div class="brand" onclick="App.showSpacesDashboard()" title="Phoenix Home">
<span class="brand-flame"><i class="fa-solid fa-fire"></i></span>
<span class="brand-text">PHOENIX</span>
</div>
<div style="flex:1;"></div>
<div style="font-family:var(--font-display);font-size:12.5px;color:var(--text-3);font-weight:600;letter-spacing:0.04em;">Workspace Dashboard</div>
<div style="flex:1;"></div>
<div></div>
</div>
<div class="spaces-dashboard">
<div class="spaces-dash-header">
<div class="spaces-dash-eyebrow"><i class="fa-solid fa-bolt"></i> Enterprise API Suite</div>
<h2>Workspaces<br><span class="grad">Command Center</span></h2>
<p>Select a workspace to access its collections, endpoints, and batch history. Every workspace keeps its own theme, collections and shared requests.</p>
</div>
<div class="spaces-grid" id="spaces-grid"></div>
</div>
</div>
<!-- WORKSPACE VIEW: shown when a space is active -->
<div id="workspace-view" style="display:flex;flex-direction:column;height:100%;overflow:hidden;">
<div class="app-header" id="app-header">
<div class="brand" onclick="App.showSpacesDashboard()" title="Back to Workspaces">
<span class="brand-flame"><i class="fa-solid fa-fire"></i></span>
<span class="brand-text">PHOENIX</span>
</div>
<div id="ws-badge" style="cursor:pointer;" onclick="App.showSpacesDashboard()"></div>
<select id="theme-select" class="theme-select" onchange="App.setSpaceTheme(this.value)" title="Workspace theme">
<option value="dark">Black Obsidian</option>
<option value="violet">Violet</option><option value="cobalt">Cobalt</option>
<option value="rose">Rose</option><option value="emerald">Emerald</option>
<option value="amber">Amber</option><option value="light">Light</option>
</select>
<button id="btnToggleLens" class="btn btn-ghost btn-sm lens-toggle-btn" onclick="App.togglePrecisionLens()" title="Toggle Kube.io Liquid Glass Lens" style="padding:4px 10px;height:32px;font-size:11.5px;font-weight:700;">
<i class="fa-solid fa-magnifying-glass"></i> Lens
</button>
<div class="input-group">
<select id="method-select" class="method-select" onchange="App._onMethodChange(this.value)">
<option>GET</option><option>POST</option><option>PUT</option><option>DELETE</option><option>PATCH</option>
</select>
<input type="text" id="url-input" class="url-input" placeholder="https://api.example.com/v1/resource" oninput="App._onUrlInput(this.value)">
</div>
<div id="action-btns" style="display:flex;gap:8px;align-items:center;"></div>
</div>
<div id="req-tab-strip" class="main-tab-strip"></div>
<div id="request-meta" class="request-meta-section" style="display:none;">
<div class="meta-row">
<i class="fa-solid fa-tag meta-icon" title="Request Name"></i>
<input type="text" id="req-name-input" class="req-name-input" placeholder="Request name…" onchange="App.updateActiveRequestName(this.value)">
<div class="meta-divider"></div>
<i class="fa-solid fa-align-left meta-icon" title="Request Description"></i>
<input type="text" id="req-desc-input" class="req-desc-input" placeholder="Add a description…" oninput="App.updateActiveRequestDescription(this.value)">
</div>
</div>
<div class="tabs" id="tabs-bar">
<div class="tab" id="ctab-params" onclick="App._switchContentTab('params')"><i class="fa-solid fa-sliders"></i> PARAMS</div>
<div class="tab" id="ctab-headers" onclick="App._switchContentTab('headers')"><i class="fa-solid fa-gears"></i> HEADERS</div>
<div class="tab" id="ctab-body" onclick="App._switchContentTab('body')"><i class="fa-solid fa-braille"></i> BODY</div>
<div class="tab" id="ctab-auth" onclick="App._switchContentTab('auth')"><i class="fa-solid fa-key"></i> AUTH</div>
<div style="flex:1;"></div>
<div id="bulk-controls" class="bulk-controls-wrap"></div>
</div>
<!-- ONLY this div gets innerHTML swapped for tab content (small, fast) -->
<div id="content-area" class="content-area"></div>
<div id="bottom-panel" class="bottom-results-panel">
<div class="results-resize-handle" onmousedown="App.startResultsResize(event)"></div>
<div class="panel-header">
<div class="panel-tabs-group">
<button id="ptab-response" class="panel-tab active" onclick="App._switchBottomTab('response')">
<i class="fa-solid fa-reply"></i> Response
</button>
<button id="ptab-results" class="panel-tab" onclick="App._switchBottomTab('results')">
<i class="fa-solid fa-list-check"></i> Batch Results
<span id="result-count-badge" class="result-count-badge" style="display:none;"></span>
</button>
<span id="stat-sep" style="display:none;width:1px;height:20px;background:var(--border-2);margin:0 6px;"></span>
<span id="stat-completed" class="stat-capsule" style="display:none;"></span>
<span id="stat-success" class="stat-capsule success" style="display:none;"></span>
<span id="stat-error" class="stat-capsule error" style="display:none;"></span>
</div>
<div id="bottom-right-actions" style="display:none;flex-wrap:nowrap;gap:6px;align-items:center;flex-shrink:0;"></div>
</div>
<div class="bottom-panel-body">
<div id="response-view" style="height:100%;display:flex;flex-direction:column;overflow:hidden;"></div>
<div id="results-view" style="height:100%;display:none;flex-direction:column;overflow:hidden;">
<div id="progress-track" class="progress-track" style="display:none;">
<div id="progress-bar-fill" class="progress-fill" style="width:0%;"></div>
</div>
<div id="main-results-grid" class="results-grid"></div>
</div>
</div>
</div>
</div>
`;
},
async init() {
this.loadState();
this.cacheDOM();
this._buildShell();
this._cacheShellDOM();
this.bindEvents();
// Bind URL/method input events on cached static elements
if (this.dom.urlInput) {
this.dom.urlInput.addEventListener('input', (e) => { this.state.url = e.target.value; this.saveState(); });
}
if (this.dom.methodInput) {
this.dom.methodInput.addEventListener('change', (e) => { this.state.method = e.target.value; this.saveState(); });
}
// Ensure active tab has at least one param and header row
if (!this.state.params || this.state.params.length === 0) this.addParam('params');
if (!this.state.headers || this.state.headers.length === 0) this.addParam('headers');
// Load spaces from the server to keep them synced
await this.loadSpacesFromServer();
// Ensure a workspace is active so collections are always visible
if (!this.state.activeSpaceId && this.state.spaces && this.state.spaces.length > 0) {
this.state.activeSpaceId = this.state.spaces[0].id;
}
// Apply saved sidebar width
const sidebarEl = document.getElementById('sidebar');
if (sidebarEl && this._stateData.sidebarWidth) {
sidebarEl.style.width = `${this._stateData.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.initPrecisionLens();
this._renderAll();
// Remove loader
const loader = document.getElementById('loading-overlay');
if (loader) loader.remove();
document.getElementById('app-root').style.visibility = 'visible';
},
// --- Tab Management ---
openNewTab() {
const newTab = this.createNewTab();
this.tabs.push(newTab);
this.activeTabIndex = this.tabs.length - 1;
if (!this.state.params || this.state.params.length === 0) this.addParam('params');
if (!this.state.headers || this.state.headers.length === 0) this.addParam('headers');
this.saveState();
this._renderAll();
},
switchTab(index) {
if (index < 0 || index >= this.tabs.length) return;
this.activeTabIndex = index;
this.saveState();
this._renderAll();
},
closeTab(index) {
if (this.tabs.length <= 1) {
// Can't close last tab; just reset it
this.tabs[0] = this.createNewTab();
this.activeTabIndex = 0;
this.saveState();
this._renderAll();
return;
}
this.tabs.splice(index, 1);
if (this.activeTabIndex >= this.tabs.length) {
this.activeTabIndex = this.tabs.length - 1;
}
this.saveState();
this._renderAll();
},
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 missing', this.dom);
alert('Critical Error: DOM missing. Refresh.');
}
},
// Re-cache after shell is built (called after _buildShell)
_cacheShellDOM() {
const d = this.dom;
d.dashboardView = document.getElementById('dashboard-view');
d.workspaceView = document.getElementById('workspace-view');
d.spacesGrid = document.getElementById('spaces-grid');
d.wsSelect = document.getElementById('ws-select');
d.notifBanner = document.getElementById('notif-banner');
d.collectionsHeader = document.getElementById('collections-header');
d.searchWrap = document.getElementById('search-wrap');
d.collectionsList = document.getElementById('collections-list');
d.wsBadge = document.getElementById('ws-badge');
d.themeSelect = document.getElementById('theme-select');
d.methodSelect = document.getElementById('method-select');
d.urlInput = document.getElementById('url-input');
d.actionBtns = document.getElementById('action-btns');
d.reqTabStrip = document.getElementById('req-tab-strip');
d.requestMeta = document.getElementById('request-meta');
d.reqNameInput = document.getElementById('req-name-input');
d.reqDescInput = document.getElementById('req-desc-input');
d.bulkControls = document.getElementById('bulk-controls');
d.contentArea = document.getElementById('content-area');
d.bottomPanel = document.getElementById('bottom-panel');
d.ptabResponse = document.getElementById('ptab-response');
d.ptabResults = document.getElementById('ptab-results');
d.resultBadge = document.getElementById('result-count-badge');
d.statSep = document.getElementById('stat-sep');
d.statCompleted = document.getElementById('stat-completed');
d.statSuccess = document.getElementById('stat-success');
d.statError = document.getElementById('stat-error');
d.bottomRightActions = document.getElementById('bottom-right-actions');
d.responseView = document.getElementById('response-view');
d.resultsView = document.getElementById('results-view');
d.progressTrack = document.getElementById('progress-track');
d.progressBar = document.getElementById('progress-bar-fill');
d.resultsGrid = document.getElementById('main-results-grid');
},
// --- State Management ---
loadState() {
try {
const raw = localStorage.getItem('phoenix-state-v2');
if (raw) {
const data = JSON.parse(raw);
// Restore _stateData (global state)
if (data.spaces !== undefined) this._stateData.spaces = data.spaces;
if (data.activeSpaceId !== undefined) this._stateData.activeSpaceId = data.activeSpaceId;
if (data.activeCollectionId !== undefined) this._stateData.activeCollectionId = data.activeCollectionId;
if (data.outputFolderPath !== undefined) this._stateData.outputFolderPath = data.outputFolderPath;
if (data.gridMaximized !== undefined) this._stateData.gridMaximized = data.gridMaximized;
if (data.resultsPanelHeight !== undefined) this._stateData.resultsPanelHeight = data.resultsPanelHeight;
if (data.sidebarWidth !== undefined) this._stateData.sidebarWidth = data.sidebarWidth;
if (data.searchQuery !== undefined) this._stateData.searchQuery = data.searchQuery;
// Restore tabs
if (data.tabs && data.tabs.length > 0) {
this.tabs = data.tabs.map(t => ({
...t,
params: t.params || [],
headers: t.headers || [],
bodyData: t.bodyData || [],
auth: t.auth || { type: 'none' },
bulk: { ...(t.bulk || {}), running: false, results: [] },
response: null
}));
this.activeTabIndex = Math.min(data.activeTabIndex || 0, this.tabs.length - 1);
} else {
// No saved tabs, create a blank one
this.tabs = [this.createNewTab()];
this.activeTabIndex = 0;
}
} else {
// Fresh start
this.tabs = [this.createNewTab()];
this.activeTabIndex = 0;
}
} catch (e) {
console.warn('Failed to load state', e);
this.tabs = [this.createNewTab()];
this.activeTabIndex = 0;
}
},
saveState() {
// Skip expensive localStorage serialization while bulk is actively running.
if (this.state.bulk && this.state.bulk.running) return;
if (this._saveStateTimeout) clearTimeout(this._saveStateTimeout);
this._saveStateTimeout = setTimeout(() => {
try {
const serializedTabs = this.tabs.map(t => ({
...t,
bulk: { ...t.bulk, running: false, results: [] },
response: null
}));
const persistentState = {
spaces: this._stateData.spaces,
activeSpaceId: this._stateData.activeSpaceId,
activeCollectionId: this._stateData.activeCollectionId,
outputFolderPath: this._stateData.outputFolderPath,
gridMaximized: this._stateData.gridMaximized,
resultsPanelHeight: this._stateData.resultsPanelHeight,
sidebarWidth: this._stateData.sidebarWidth,
searchQuery: this._stateData.searchQuery,
tabs: serializedTabs,
activeTabIndex: this.activeTabIndex
};
localStorage.setItem('phoenix-state-v2', JSON.stringify(persistentState));
} catch (e) {
console.warn('Failed to save state', e);
}
}, 300);
},
async loadLastRunFromServer() {
// Persistence disabled for performance — results are session-only.
},
async saveLastRunToServer() {
// Persistence disabled for performance — results are session-only.
},
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 || (space.collections = [])) : [];
},
getAllCollections() {
const all = [];
(this.state.spaces || []).forEach(space => {
(space.collections || []).forEach(col => {
all.push({
...col,
_spaceId: space.id,
_spaceName: space.name,
_isAllView: true
});
});
});
const meaningful = all.filter(c => (c.requests && c.requests.length > 0) || (c.id !== 'default' && c.name !== 'My Requests'));
return meaningful.length > 0 ? meaningful : all;
},
toggleAllCollectionsView() {
this.state.showAllCollections = !this.state.showAllCollections;
this._renderAll();
if (this.state.showAllCollections) {
this.toast("Showing all collections across all workspaces", "info");
} else {
this.toast("Showing current workspace collections", "info");
}
},
toggleAllCollectionsCollapse() {
this.state.collapsedCollections = this.state.collapsedCollections || {};
const query = (this.state.searchQuery || '').trim();
const cols = this.state.showAllCollections ? this.getAllCollections() : (this.collections || []);
const anyExpanded = cols.some(c => !this.state.collapsedCollections[c.id]);
if (anyExpanded) {
cols.forEach(c => { this.state.collapsedCollections[c.id] = true; });
this.toast("Collapsed all collections", "info");
} else {
this.state.collapsedCollections = {};
this.toast("Expanded all collections", "info");
}
this.saveState();
this.renderSidebar();
},
selectCollection(colId, spaceId) {
if (spaceId && spaceId !== this.state.activeSpaceId) {
this.state.activeSpaceId = spaceId;
} else if (!this.state.activeSpaceId) {
const found = this.findCollectionAcrossSpaces(colId);
if (found) this.state.activeSpaceId = found.space.id;
}
this.state.activeCollectionId = colId;
this.state.collapsedCollections = this.state.collapsedCollections || {};
// Toggle collapse state for the clicked collection
this.state.collapsedCollections[colId] = !this.state.collapsedCollections[colId];
this.saveState();
this._renderAll();
},
set collections(val) {
if (!this.state.activeSpaceId) {
if (this.state.spaces && this.state.spaces.length > 0) {
this.state.activeSpaceId = this.state.spaces[0].id;
}
}
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._debouncedSaveSpaces();
} else if (data.length === 0 && this.state.spaces && this.state.spaces.length > 0) {
await this._debouncedSaveSpaces();
} 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._renderAll();
},
showSpacesDashboard() {
this.state.activeSpaceId = null;
this.state.activeCollectionId = 'default';
this.state.activeRequestId = null;
this.saveState();
this._renderAll();
},
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._debouncedSaveSpaces();
this._renderAll();
}
},
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._debouncedSaveSpaces();
this._renderAll();
}
},
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._debouncedSaveSpaces();
this._renderAll();
}
},
async setSpaceTheme(themeId) {
const activeSpace = this.state.spaces.find(s => s.id === this.state.activeSpaceId);
if (activeSpace) {
activeSpace.theme = themeId;
this.saveState();
await this._debouncedSaveSpaces();
this._renderAll();
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._debouncedSaveSpaces();
this.toast(`Shared collection with ${targetSpace.name}!`);
this._renderAll();
} 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 btn-ghost btn-sm" style="width:30px;padding:0;" 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._debouncedSaveSpaces();
this.toast("Collection approved and added!");
this._renderAll();
}
},
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._debouncedSaveSpaces();
this.toast("Share request rejected");
this._renderAll();
}
},
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);
},
replaceResultCardInDOM(result) {
const newEl = this._buildCardElement(result);
document.querySelectorAll(`.result-card[data-index="${result.index}"]`).forEach(card => {
card.replaceWith(newEl.cloneNode(true));
});
},
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;
if (resultItem.blobUrl && resultItem.blobUrl !== res.blobUrl) {
URL.revokeObjectURL(resultItem.blobUrl);
}
resultItem.blobUrl = res.blobUrl;
resultItem.binaryData = null;
this.toast(`Request #${resultIndex} completed: ${res.status_code}`, isSuccess ? 'info' : 'error');
this.updateBulkProgressUI();
this.replaceResultCardInDOM(resultItem);
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();
this.replaceResultCardInDOM(resultItem);
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);
},
renderResultCard(result) {
const isImage = (result.contentType || '').toLowerCase().includes('image') && (result.blobUrl || 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 {
previewHTML = `<img src="${result.blobUrl || this.base64ToBlobUrl(result.binaryData, result.contentType)}" class="card-thumb" alt="${filename}" loading="lazy" decoding="async" />`;
} 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' : ''}" data-index="${result.index}" 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>
`;
},
_buildCardElement(result) {
const tmp = document.createElement('template');
tmp.innerHTML = this.renderResultCard(result).trim();
return tmp.content.firstElementChild;
},
appendResultCardToDOM(result) {
const newElement = this._buildCardElement(result);
const appendToGrid = (grid) => {
if (!grid) return;
const spinner = grid.querySelector('div[style*="fa-spinner"]');
if (spinner) spinner.remove();
grid.appendChild(newElement.cloneNode(true));
// Virtual DOM cap: keep only the most recent 200 cards in the DOM.
// Older results remain accessible in this.state.bulk.results but not rendered.
while (grid.children.length > 200) {
grid.removeChild(grid.firstElementChild);
}
};
appendToGrid(this.dom.resultsGrid || document.getElementById('main-results-grid'));
appendToGrid(document.querySelector('.fullscreen-results-grid'));
},
updateBulkProgressUI() {
// Direct DOM writes only — no re-render, no querySelectorAll, using cached refs
if (this._rafPending) return;
this._rafPending = true;
requestAnimationFrame(() => {
this._rafPending = false;
const bulk = this.state.bulk;
const pct = bulk.total > 0 ? (bulk.completed / bulk.total) * 100 : 0;
const color = bulk.error > 0 ? (bulk.success > 0 ? 'var(--warning)' : 'var(--danger)') : 'var(--success)';
const bar = this.dom.progressBar;
const track = this.dom.progressTrack;
if (bar) { bar.style.width = pct+'%'; bar.style.background = color; }
if (track && bulk.total > 0) track.style.display = '';
const sc = this.dom.statCompleted, ss = this.dom.statSuccess, se = this.dom.statError;
const sep = this.dom.statSep, badge = this.dom.resultBadge;
if (sc) { sc.style.display = ''; sc.textContent = `${bulk.completed}/${bulk.total}`; }
if (ss) { ss.style.display = ''; ss.textContent = `${bulk.success} ✓`; }
if (se) { se.style.display = ''; se.textContent = `${bulk.error} ✗`; }
if (sep) sep.style.display = '';
if (badge) { badge.style.display = ''; badge.textContent = bulk.results.length; }
// Also update fullscreen if open
document.querySelectorAll('.progress-fill').forEach(b => { b.style.width = pct+'%'; b.style.background = color; });
document.querySelectorAll('.stat-capsule.success').forEach(el => el.textContent = `${bulk.success} ✓`);
document.querySelectorAll('.stat-capsule.error').forEach(el => el.textContent = `${bulk.error} ✗`);
});
},
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 folderPath = this.state.outputFolderPath || 'None selected';
const contentHTML = `
<div class="fullscreen-results-header">
<div class="fullscreen-results-title">
<i class="fa-solid fa-square-poll-horizontal"></i>
<div>
<h2 style="margin:0; font-size:17px; font-weight:700; color:var(--text-1); font-family:var(--font-display);">Batch Processing Grid</h2>
<p style="margin:3px 0 0 0; font-size:11px; color:var(--text-3);">Real-time execution monitoring and visual results</p>
</div>
<div class="results-stats-row" style="margin-left:18px;">
<span class="stat-capsule">${bulk.completed} / ${bulk.total} Completed</span>
<span class="stat-capsule success">${bulk.success} Success</span>
<span class="stat-capsule error">${bulk.error} Failed</span>
</div>
</div>
<div style="display:flex; gap:10px; align-items:center; flex-wrap:wrap;">
<div class="folder-selector-container">
<span class="folder-path-display" title="${folderPath}">
<i class="fa-solid fa-folder-open"></i> ${folderPath}
</span>
<button class="btn btn-ghost" style="padding:0 12px; height:100%; border-radius:0; border:none; border-left:1px solid var(--border-2); 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 btn-sm" style="height:32px;" onclick="App.saveAllResults()" ${bulk.results.length === 0 ? 'disabled' : ''}>
<i class="fa-solid fa-file-zipper"></i> ZIP
</button>
<button class="btn btn-ghost btn-sm" style="height:32px;" onclick="App.downloadHistory()" ${bulk.results.length === 0 ? 'disabled' : ''}>
<i class="fa-solid fa-file-csv"></i> CSV
</button>
<button class="btn btn-ghost btn-sm" style="height:32px;" onclick="App.closeFullscreenResults()">
<i class="fa-solid fa-compress"></i> Close Fullscreen
</button>
</div>
</div>
<div class="progress-track" style="margin-bottom:0;">
<div class="progress-fill" style="width:${pct}%; background:${statusColor};"></div>
</div>
<div class="fullscreen-results-grid" id="fullscreen-results-inner"></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;
}
// Populate the fullscreen grid via DocumentFragment (no re-render of cards)
const fsGrid = document.getElementById('fullscreen-results-inner');
if (fsGrid) {
const frag = document.createDocumentFragment();
const shown = bulk.results.slice(-200);
if (shown.length === 0 && bulk.running) {
const ph = document.createElement('div');
ph.style.cssText = 'grid-column:1/-1;text-align:center;color:var(--text-muted);padding:80px;font-style:italic;';
ph.innerHTML = '<i class="fa-solid fa-spinner fa-spin" style="margin-right:10px;font-size:24px;"></i>Running…';
frag.appendChild(ph);
} else {
shown.forEach(r => frag.appendChild(this._buildCardElement(r)));
}
fsGrid.appendChild(frag);
}
},
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._renderAll();
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');
// Build file list from current in-memory blobUrls
const fileItems = [];
for (const r of this.state.bulk.results) {
const filename = this.getFinalFilename(r);
if (r.blobUrl) {
try {
const blob = await fetch(r.blobUrl).then(res => res.blob());
const ab = await blob.arrayBuffer();
const b64 = btoa(String.fromCharCode(...new Uint8Array(ab)));
fileItems.push({ filename, is_binary: true, binary_data: b64 });
} catch (e) { console.warn('blob fetch failed', r.index, e); }
} else if (r.fullContent) {
fileItems.push({ filename, is_binary: false, content: r.fullContent });
}
}
if (!fileItems.length) return this.toast('No data available to save', 'error');
const res = await fetch('/api/save_folder', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ path: this.state.outputFolderPath, results: fileItems })
});
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}`);
} 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 {
const filename = this.getFinalFilename(result);
let fileItem = null;
if (result.blobUrl) {
const blob = await fetch(result.blobUrl).then(r => r.blob());
const ab = await blob.arrayBuffer();
const b64 = btoa(String.fromCharCode(...new Uint8Array(ab)));
fileItem = { filename, is_binary: true, binary_data: b64 };
} else if (result.fullContent) {
fileItem = { filename, is_binary: false, content: result.fullContent };
}
if (!fileItem) return this.toast('No data for this result', 'error');
const res = await fetch('/api/save_folder', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ path: this.state.outputFolderPath, results: [fileItem] })
});
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 url;
let needsRevoke = false;
if (result.blobUrl) {
url = result.blobUrl;
} else if (result.fullContent) {
const blob = new Blob([result.fullContent], { type: result.contentType || 'text/plain' });
url = URL.createObjectURL(blob);
needsRevoke = true;
} else {
return this.toast('No content to download', 'error');
}
const a = document.createElement('a');
a.href = url;
a.download = finalFilename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
if (needsRevoke) {
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?")) {
// Revoke all blob URLs before clearing to free memory
this.state.bulk.results.forEach(r => { if (r.blobUrl) URL.revokeObjectURL(r.blobUrl); });
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._renderAll();
}
},
toggleGridMaximized() {
this.state.gridMaximized = !this.state.gridMaximized;
this._renderAll();
},
// --- 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._switchContentTab(this.state.activeTab);
this._updateBulkControls();
this._updateActionBtns();
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._switchContentTab(this.state.activeTab);
this._updateBulkControls();
this._updateActionBtns();
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();
if (field === 'type' || field === 'enabled') {
this._switchContentTab(this.state.activeTab);
this._updateBulkControls();
this._updateActionBtns();
}
}
},
// --- 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';
this._switchBottomTab('response');
this._updateResponseView();
try {
const start = Date.now();
const res = await this.executeRequest(0);
const latency = Date.now() - start;
res.latency = latency;
this.state.response = res;
if (res.blobUrl) this.state.response.blobUrl = res.blobUrl;
if (res.sentImageUrl) this.state.response.sentImageUrl = res.sentImageUrl;
if (res.sentImageName) this.state.response.sentImageName = res.sentImageName;
this.saveToCollection(res.status_code || 500);
} catch (e) {
this.state.response = { error: e.message };
}
this._updateResponseView();
this._updateActionBtns();
this.saveToCollection(this.state.response.status_code || 500);
this.saveState();
},
// --- 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, use the saved repetitions setting
if (total === 0) {
total = Math.max(1, parseInt(this.state.bulk.repetitions) || 10);
}
if (total <= 0) return this.toast('Invalid bulk count', 'error');
// Init Bulk State
if (!this.state.bulk.paused) {
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.bulk.nextIndex = 0;
this.state.responseTab = 'results';
} else {
this.state.bulk.total = total;
}
this.state.bulk.running = true;
this.state.bulk.paused = false;
// Surgical init: show results view, update action buttons — no full re-render
this._switchBottomTab('results');
this._updateActionBtns();
this._updateBottomStats();
this._updateBottomRightActions();
if (this.dom.progressTrack) this.dom.progressTrack.style.display = '';
// Clear grid for new run
if (this.dom.resultsGrid) this.dom.resultsGrid.innerHTML = '';
this.saveToCollection('BULK');
// Execution Queue
const concurrency = Math.max(1, Math.min(20, this.state.bulk.concurrency || 1));
let active = 0;
const worker = async () => {
while (this.state.bulk.nextIndex < this.state.bulk.total && this.state.bulk.running && this.state.bulk.currentRunId === currentRunId) {
const index = this.state.bulk.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;
}
const inputFilename = this.getInputFilename(index, fileIndex, listIndex);
try {
const res = await this.executeRequest(index, fileIndex, listIndex);
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]' : ''),
// Strip heavy data immediately — blobUrl is a cheap pointer
// fullContent and binaryData are NOT stored to avoid heap bloat
fullContent: null,
binaryData: null,
blobUrl: res.blobUrl,
sentImageUrl: res.sentImageUrl || null,
sentImageName: res.sentImageName || null,
contentType: res.content_type,
headers: res.headers,
inputFilename: inputFilename
});
const newResult = this.state.bulk.results[this.state.bulk.results.length - 1];
this.appendResultCardToDOM(newResult);
// Cap result memory: revoke blob URL of oldest item when trimming
if (this.state.bulk.results.length > 300) {
const dropped = this.state.bulk.results.shift();
if (dropped && dropped.blobUrl) URL.revokeObjectURL(dropped.blobUrl);
if (dropped && dropped.sentImageUrl) URL.revokeObjectURL(dropped.sentImageUrl);
}
} 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
});
const errResult = this.state.bulk.results[this.state.bulk.results.length - 1];
this.appendResultCardToDOM(errResult);
} finally {
active--;
this.state.bulk.completed++;
if (this.state.bulk.currentRunId === currentRunId) {
this.updateBulkProgressUI();
}
}
// Apply inter-request delay (only when concurrency = 1 or after each request)
const delayMs = parseInt(this.state.bulk.delay) || 0;
if (delayMs > 0 && this.state.bulk.running && this.state.bulk.currentRunId === currentRunId) {
await new Promise(r => setTimeout(r, delayMs));
}
}
if (active === 0 && this.state.bulk.nextIndex >= this.state.bulk.total && this.state.bulk.currentRunId === currentRunId) {
this.state.bulk.running = false;
this.state.bulk.paused = false;
this.state.bulk.results.sort((a, b) => a.index - b.index);
// Surgical completion: just update action buttons and stats
this._updateActionBtns();
this._updateBottomStats();
this._updateBottomRightActions();
this.toast('Bulk Operation Completed');
}
};
// Spawn workers
for (let i = 0; i < concurrency; i++) {
worker();
}
},
stopBulk() {
this.state.bulk.running = false;
this.state.bulk.paused = false;
this._updateActionBtns();
this._updateBottomRightActions();
},
pauseBulk() {
if (this.state.bulk.running) {
this.state.bulk.running = false;
this.state.bulk.paused = true;
this._updateActionBtns();
this.toast('Bulk Operation Paused', 'warning');
}
},
resumeBulk() {
if (this.state.bulk.paused) {
this.runBulk();
}
},
async getImageDimensions(file) {
return new Promise((resolve) => {
if (!file || !file.type.startsWith('image/')) return resolve({width: 0, height: 0});
const img = new Image();
const url = URL.createObjectURL(file);
img.onload = () => {
resolve({width: img.width, height: img.height});
URL.revokeObjectURL(url);
};
img.onerror = () => {
resolve({width: 0, height: 0});
URL.revokeObjectURL(url);
};
img.src = url;
});
},
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
let currentImageFile = null;
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');
const folderParam = this.state.bodyData.find(p => p.enabled && p.type === 'folder');
if (folderParam) {
const files = this.fileStore.get(folderParam.id);
if (files && files.length > 0) currentImageFile = files[fileIndex % files.length];
}
if (!currentImageFile) {
const fileParam = this.state.bodyData.find(p => p.enabled && p.type === 'file');
if (fileParam) {
const files = this.fileStore.get(fileParam.id);
if (files && files.length > 0) currentImageFile = files[0];
}
}
let imgDims = null;
const bodyParams = this.state.bodyData.filter(p => p.enabled && (p.type === 'file' || p.type === 'folder' || p.type === 'auto_width' || p.type === 'auto_height' || (p.key && p.key.trim())));
for (const p of bodyParams) {
if (p.type === 'file' || p.type === 'folder') {
const files = this.fileStore.get(p.id);
if (files && files.length > 0) {
if (p.type === 'folder') {
finalData.append(p.key, files[fileIndex % files.length]);
} else {
for (let f of files) finalData.append(p.key, f);
}
}
} else if (p.type === 'auto_width' || p.type === 'auto_height') {
if (!imgDims) imgDims = await this.getImageDimensions(currentImageFile);
finalData.append(p.key, p.type === 'auto_width' ? imgDims.width : imgDims.height);
} 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);
}
}
}
// Fallback detection of sent image from URL params or fileStore for Before / After comparison
if (!currentImageFile) {
const pFolder = this.state.params.find(p => p.enabled && p.type === 'folder');
if (pFolder) {
const files = this.fileStore.get(pFolder.id);
if (files && files.length > 0) currentImageFile = files[fileIndex % files.length];
}
}
if (!currentImageFile) {
const pFile = this.state.params.find(p => p.enabled && p.type === 'file');
if (pFile) {
const files = this.fileStore.get(pFile.id);
if (files && files.length > 0) currentImageFile = files[0];
}
}
if (!currentImageFile) {
for (const [id, files] of this.fileStore.entries()) {
if (files && files.length > 0) {
const f = files[fileIndex % files.length] || files[0];
if (f && (f.type?.startsWith('image/') || /\.(jpg|jpeg|png|webp|gif|bmp|svg|avif)$/i.test(f.name))) {
currentImageFile = f;
break;
}
}
}
}
const res = await fetch('/api/proxy-request', {
method: 'POST',
body: finalData
});
const data = await res.json();
if (data.binary_data) {
data.blobUrl = await this.base64ToBlobUrlAsync(data.binary_data, data.content_type);
// Immediately null out raw data to free the large string from JS heap.
// The blobUrl is a tiny reference to browser-managed memory.
data.binary_data = null;
}
if (currentImageFile) {
try {
data.sentImageUrl = URL.createObjectURL(currentImageFile);
data.sentImageName = currentImageFile.name;
data.sentImageSize = currentImageFile.size;
} catch(e) {}
}
data.latency = Date.now() - start;
return data;
},
saveToCollection(lastStatus) {
if (!this.state.url) return;
let targetColId = this.state.activeCollectionId || 'default';
let col = this.collections.find(c => c.id === targetColId);
if (!col) {
col = this.collections.find(c => c.id === 'default');
if(!col) {
col = { id: 'default', name: 'My Requests', requests: [] };
this.collections.push(col);
}
targetColId = col.id;
}
const existingIdx = col.requests.findIndex(r => r.id === this.state.activeRequestId || (r.url === this.state.url && r.method === this.state.method));
let existingReq = existingIdx >= 0 ? col.requests[existingIdx] : null;
const reqData = {
id: this.state.activeRequestId || Date.now().toString(),
name: (existingReq && existingReq.name) ? existingReq.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 !== undefined ? lastStatus : (existingReq ? existingReq.lastStatus : null),
lastTime: new Date().toLocaleTimeString(),
activeCollectionId: targetColId
};
if (existingIdx >= 0) {
// Update existing
reqData.id = existingReq.id; // preserve ID
col.requests[existingIdx] = reqData;
} else {
// Add new
col.requests.unshift(reqData);
}
this.state.activeRequestId = reqData.id;
this.saveState();
this._debouncedSaveSpaces();
},
_debouncedSaveSpaces() {
if (this._saveSpacesTimer) clearTimeout(this._saveSpacesTimer);
this._saveSpacesTimer = setTimeout(() => this.saveSpacesToServer(), 1000);
},
loadRequest(colId, reqId, spaceId) {
if (spaceId && spaceId !== this.state.activeSpaceId) {
this.state.activeSpaceId = spaceId;
} else if (!this.state.activeSpaceId) {
const found = this.findCollectionAcrossSpaces(colId);
if (found) this.state.activeSpaceId = found.space.id;
}
let col = this.collections.find(c => c.id === colId);
if (!col && spaceId) {
const sp = (this.state.spaces || []).find(s => s.id === spaceId);
if (sp) col = (sp.collections || []).find(c => c.id === colId);
}
if (!col) {
const found = this.findCollectionAcrossSpaces(colId);
if (found) {
col = found.collection;
this.state.activeSpaceId = found.space.id;
}
}
if (!col) return;
const req = (col.requests || []).find(r => r.id === reqId);
if(!req) return;
this.state.activeCollectionId = colId;
if (this.state.collapsedCollections) delete this.state.collapsedCollections[colId];
// Check if this request is already open in any tab
const existingTabIdx = this.tabs.findIndex(t => t.activeRequestId === reqId);
if (existingTabIdx >= 0) {
// Just switch to that tab
this.activeTabIndex = existingTabIdx;
this.saveState();
this._renderAll();
return;
}
// Postman behavior: if the current tab is a "preview" tab (untouched/empty), reuse it;
// otherwise open a new tab
const currTab = this.tabs[this.activeTabIndex];
const isUntouched = currTab && (
(!currTab.url || currTab.url === '') &&
(!currTab.activeRequestId) &&
(!currTab.response) &&
(currTab.name === 'Untitled Request' || !currTab.name)
);
const reqTabData = {
id: 'tab_' + Date.now() + Math.random().toString(36).substr(2, 9),
name: req.name || (req.url ? req.url.split('/').pop() || req.url : 'Request'),
method: req.method || 'GET',
url: req.url || '',
params: JSON.parse(JSON.stringify(req.params || [{ id: Date.now().toString(), key: '', value: '', type: 'text', enabled: true }])),
headers: JSON.parse(JSON.stringify(req.headers || [{ id: (Date.now()+1).toString(), key: '', value: '', type: 'text', enabled: true }])),
auth: JSON.parse(JSON.stringify(req.auth || {type:'none'})),
bodyType: req.bodyType || 'none',
bodyData: JSON.parse(JSON.stringify(req.bodyData || [])),
jsonBody: req.jsonBody || '',
response: null,
bulk: { strategy: 'consecutive', running: false, total: 0, completed: 0, success: 0, error: 0, concurrency: 1, results: [] },
activeTab: 'params',
responseTab: 'response',
activeRequestId: reqId,
activeCollectionId: colId,
isPreview: false
};
if (isUntouched) {
// Replace current blank tab
this.tabs[this.activeTabIndex] = reqTabData;
} else {
// Open brand new tab
this.tabs.push(reqTabData);
this.activeTabIndex = this.tabs.length - 1;
}
this.saveState();
this._renderAll();
},
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._debouncedSaveSpaces();
this._renderAll();
},
createCollection() {
this.openCreateCollectionModal();
},
openCreateCollectionModal() {
const existing = document.getElementById('create-col-modal');
if (existing) existing.remove();
const modal = document.createElement('div');
modal.className = 'premium-modal-overlay';
modal.id = 'create-col-modal';
modal.innerHTML = `
<div class="premium-modal-card" style="max-width:540px; width:100%;">
<div class="premium-modal-header">
<h3><i class="fa-solid fa-layer-group" style="color:var(--primary);"></i> Create New Collection</h3>
<button class="btn btn-ghost btn-sm" style="width:30px;padding:0;" onclick="this.closest('#create-col-modal').remove()"><i class="fa-solid fa-xmark"></i></button>
</div>
<div class="premium-modal-body" style="display:flex; flex-direction:column; gap:16px;">
<!-- Option 1: Import from API Documentation -->
<div style="background:var(--brand-grad-soft); border:1px solid var(--ph-alpha2); border-radius:var(--r-lg); padding:16px; cursor:pointer; transition:all 0.2s; display:flex; flex-direction:column; gap:8px;"
onclick="this.closest('#create-col-modal').remove(); App.openImportFromDocModal();"
onmouseover="this.style.borderColor='var(--ph)'; this.style.transform='translateY(-1px)';"
onmouseout="this.style.borderColor='var(--ph-alpha2)'; this.style.transform='none';">
<div style="display:flex; align-items:center; gap:12px;">
<div style="width:38px; height:38px; border-radius:var(--r-md); background:var(--ph-alpha); display:flex; align-items:center; justify-content:center; color:var(--ph); font-size:16px; flex-shrink:0;">
<i class="fa-solid fa-book-bookmark"></i>
</div>
<div style="flex:1;">
<div style="font-weight:700; font-size:14px; color:var(--text-1); display:flex; align-items:center; gap:8px;">
Import from Documentation
<span style="font-size:9px; background:var(--brand-grad); color:white; padding:2px 7px; border-radius:var(--r-2xs); font-weight:800; text-transform:uppercase; letter-spacing:0.05em;">Recommended</span>
</div>
<div style="font-size:11px; color:var(--text-3); margin-top:2px;">69 pre-configured Generative AI backend services</div>
</div>
<span class="btn btn-primary btn-sm" style="pointer-events:none;">
Browse APIs <i class="fa-solid fa-arrow-right" style="font-size:9px; margin-left:4px;"></i>
</span>
</div>
<div style="font-size:11.5px; color:var(--text-2); line-height:1.45; padding-left:50px;">
Select an API to automatically populate full URLs, multipart form fields, parameters, and preset values.
</div>
</div>
<div style="display:flex; align-items:center; gap:12px; margin:2px 0;">
<div style="flex:1; height:1px; background:var(--border-1);"></div>
<span style="font-size:10px; font-weight:700; text-transform:uppercase; letter-spacing:0.08em; color:var(--text-3);">or create blank collection</span>
<div style="flex:1; height:1px; background:var(--border-1);"></div>
</div>
<!-- Option 2: Blank Collection -->
<form onsubmit="event.preventDefault(); const val = document.getElementById('new-col-name-input').value.trim(); if(val){ App._createBlankCollection(val); this.closest('#create-col-modal').remove(); }">
<div style="margin-bottom:12px;">
<label style="display:block; font-size:11px; font-weight:600; color:var(--text-2); margin-bottom:6px;">Blank Collection Name</label>
<input type="text" id="new-col-name-input" class="cell-input" placeholder="e.g. My Custom Collection" style="width:100%; height:38px; padding:0 12px; background:var(--bg-input); border:1px solid var(--border-2); border-radius:var(--r-md); font-size:13px; color:var(--text-1);" autofocus>
</div>
<div style="display:flex; justify-content:flex-end; gap:8px;">
<button type="button" class="btn btn-ghost" onclick="this.closest('#create-col-modal').remove()">Cancel</button>
<button type="submit" class="btn" style="background:var(--bg-raised); border:1px solid var(--border-3); color:var(--text-1);">Create Blank</button>
</div>
</form>
</div>
</div>
`;
document.body.appendChild(modal);
setTimeout(() => {
const inp = document.getElementById('new-col-name-input');
if (inp) inp.focus();
}, 50);
},
_createBlankCollection(name) {
if (!name) return;
if (!this.state.activeSpaceId && this.state.spaces && this.state.spaces.length > 0) {
this.state.activeSpaceId = this.state.spaces[0].id;
}
let space = this.state.spaces.find(s => s.id === this.state.activeSpaceId);
if (!space) {
space = { id: 'space_' + Date.now(), name: 'My Workspace', collections: [] };
this.state.spaces.push(space);
this.state.activeSpaceId = space.id;
}
const id = 'col_' + Date.now();
const newCol = { id, name, requests: [] };
if (!space.collections) space.collections = [];
space.collections.push(newCol);
this.state.activeCollectionId = id;
this.saveState();
this.saveSpacesToServer();
this._renderAll();
this.toast(`Created collection "${name}"`, "success");
},
getAllCollectionsGrouped() {
const groups = [];
(this.state.spaces || []).forEach(s => {
const cols = s.collections || [];
if (cols.length > 0) {
groups.push({
spaceId: s.id,
spaceName: s.name,
isCurrent: s.id === this.state.activeSpaceId,
collections: cols
});
}
});
groups.sort((a, b) => (b.isCurrent ? 1 : 0) - (a.isCurrent ? 1 : 0));
return groups;
},
findCollectionAcrossSpaces(colId) {
if (!colId) return null;
for (const s of (this.state.spaces || [])) {
const col = (s.collections || []).find(c => c.id === colId);
if (col) return { space: s, collection: col };
}
return null;
},
async getDocsData() {
if (this._cachedDocsData) return this._cachedDocsData;
const urls = [
'/api/docs-data',
'/docs/data.json'
];
for (const url of urls) {
try {
const res = await fetch(url);
if (res.ok) {
const data = await res.json();
if (data && data.sections) {
this._cachedDocsData = data;
return data;
}
}
} catch(e) {}
}
return null;
},
async openImportFromDocModal(targetColId = null) {
this._importTargetColId = targetColId || null;
this._docModalSearch = '';
this._docModalActiveCategory = 'all';
const existing = document.getElementById('import-doc-modal');
if (existing) existing.remove();
const modal = document.createElement('div');
modal.className = 'premium-modal-overlay';
modal.id = 'import-doc-modal';
modal.innerHTML = `
<div class="premium-modal-card" style="max-width:880px; width:95%; height:86vh; display:flex; flex-direction:column; border:1px solid var(--border-3);">
<div class="premium-modal-header" style="flex-shrink:0;">
<div>
<h3 style="margin:0;"><i class="fa-solid fa-book-bookmark" style="color:var(--primary);"></i> Import from API Documentation</h3>
<p style="margin:3px 0 0; font-size:11.5px; color:var(--text-3);">Click an API to automatically create a collection and pre-fill URLs, parameters, multipart files, and presets.</p>
</div>
<button class="btn btn-ghost btn-sm" style="width:30px;padding:0;" onclick="this.closest('#import-doc-modal').remove()"><i class="fa-solid fa-xmark"></i></button>
</div>
<div style="padding:14px 22px 10px; border-bottom:1px solid var(--border-2); background:var(--bg-raised); display:flex; flex-direction:column; gap:10px; flex-shrink:0;">
<!-- Target Collection Bar -->
<div style="display:flex; align-items:center; justify-content:space-between; gap:12px; font-size:12px;">
<div style="display:flex; align-items:center; gap:8px; flex:1;">
<span style="color:var(--text-3); font-weight:700; text-transform:uppercase; font-size:10px; letter-spacing:0.06em; white-space:nowrap;">
<i class="fa-solid fa-folder-open" style="color:var(--warning); margin-right:4px;"></i> Destination:
</span>
<select id="doc-modal-dest-select" onchange="App._importTargetColId = this.value;" style="flex:1; max-width:520px; background:var(--bg-input); border:1px solid var(--border-2); border-radius:var(--r-xs); color:var(--text-1); font-size:12px; font-weight:600; padding:6px 10px; cursor:pointer;">
<option value="" ${!this._importTargetColId ? 'selected' : ''}>+ Create New Collection (Named after API)</option>
${this.getAllCollectionsGrouped().map(g => `
<optgroup label="${this.escapeHTML(g.spaceName)} (${g.collections.length} collections)">
${g.collections.map(c => `
<option value="${c.id}" ${this._importTargetColId === c.id ? 'selected' : ''}>
📁 ${this.escapeHTML(c.name)} (${c.requests ? c.requests.length : 0} reqs)
</option>
`).join('')}
</optgroup>
`).join('')}
</select>
</div>
<div id="doc-modal-count" style="font-size:11px; color:var(--text-3); white-space:nowrap;">Loading APIs…</div>
</div>
<!-- Search Input -->
<div style="position:relative;">
<i class="fa-solid fa-magnifying-glass" style="position:absolute; left:12px; top:50%; transform:translateY(-50%); color:var(--text-3); font-size:12px; pointer-events:none;"></i>
<input type="text" id="doc-api-search-input" placeholder="Search 69 APIs by name, endpoint path, parameters, presets..."
oninput="App._filterDocModal(this.value)"
style="width:100%; height:36px; padding:0 34px 0 34px; background:var(--bg-input); border:1px solid var(--border-2); border-radius:var(--r-md); color:var(--text-1); font-size:13px; font-family:var(--font-ui);" autofocus>
<button id="doc-api-search-clear" onclick="document.getElementById('doc-api-search-input').value=''; App._filterDocModal('');" style="display:none; position:absolute; right:10px; top:50%; transform:translateY(-50%); background:none; border:none; color:var(--text-3); cursor:pointer; font-size:12px;">
<i class="fa-solid fa-xmark"></i>
</button>
</div>
<!-- Category Pills -->
<div id="doc-modal-cats" style="display:flex; gap:6px; overflow-x:auto; padding-bottom:2px;" class="custom-scroll"></div>
</div>
<!-- API Cards List -->
<div class="premium-modal-body custom-scroll" id="doc-modal-list" style="padding:16px 22px; flex:1; overflow-y:auto; display:flex; flex-direction:column; gap:10px;">
<div style="text-align:center; padding:40px 20px; color:var(--text-3); font-size:13px;">
<i class="fa-solid fa-spinner fa-spin" style="margin-right:8px;"></i> Loading documentation APIs…
</div>
</div>
<div class="premium-modal-footer" style="padding:10px 22px; justify-content:space-between; align-items:center;">
<span style="font-size:11px; color:var(--text-3);"><i class="fa-solid fa-bolt" style="color:var(--primary); margin-right:4px;"></i> Clicking any API instantly creates the collection and fills all parameters, files & presets.</span>
<button class="btn btn-ghost" onclick="this.closest('#import-doc-modal').remove()">Close</button>
</div>
</div>
`;
document.body.appendChild(modal);
// Load docs data
const docsData = await this.getDocsData();
if (!docsData) {
const listEl = document.getElementById('doc-modal-list');
if (listEl) {
listEl.innerHTML = `<div style="text-align:center; padding:40px; color:var(--danger); font-size:13px;">Failed to load documentation APIs. Please try again.</div>`;
}
return;
}
// Build index of APIs
const allApis = [];
(docsData.sections || []).forEach(s => {
(s.eps || []).forEach(e => {
allApis.push({
...e,
secId: s.id,
secTitle: s.title,
secHue: s.hue
});
});
});
this._docModalApis = allApis;
this._docModalSections = docsData.sections || [];
this._renderDocModalCategories();
this._renderDocModalList();
setTimeout(() => {
const inp = document.getElementById('doc-api-search-input');
if (inp) inp.focus();
}, 50);
},
_renderDocModalCategories() {
const catsEl = document.getElementById('doc-modal-cats');
if (!catsEl || !this._docModalSections) return;
const totalCount = (this._docModalApis || []).length;
let html = `
<button class="doc-cat-pill ${this._docModalActiveCategory === 'all' ? 'active' : ''}" onclick="App._selectDocModalCategory('all')">
All (${totalCount})
</button>
`;
this._docModalSections.forEach(s => {
const count = (s.eps || []).length;
const isActive = this._docModalActiveCategory === s.id;
html += `
<button class="doc-cat-pill ${isActive ? 'active' : ''}" onclick="App._selectDocModalCategory('${s.id}')">
${this.escapeHTML(s.title)} (${count})
</button>
`;
});
catsEl.innerHTML = html;
},
_selectDocModalCategory(catId) {
this._docModalActiveCategory = catId;
this._renderDocModalCategories();
this._renderDocModalList();
},
_filterDocModal(query) {
this._docModalSearch = (query || '').toLowerCase().trim();
const clearBtn = document.getElementById('doc-api-search-clear');
if (clearBtn) clearBtn.style.display = this._docModalSearch ? 'block' : 'none';
this._renderDocModalList();
},
_renderDocModalList() {
const listEl = document.getElementById('doc-modal-list');
const countEl = document.getElementById('doc-modal-count');
if (!listEl || !this._docModalApis) return;
const q = this._docModalSearch || '';
const cat = this._docModalActiveCategory || 'all';
const filtered = this._docModalApis.filter(api => {
if (cat !== 'all' && api.secId !== cat) return false;
if (!q) return true;
const haystack = [
api.api_key || '',
api.title || '',
api.summary || '',
api.desc || '',
api.full_url || '',
api.path || '',
...(api.params || []).map(p => p.n || ''),
...(api.chips || []),
...(api.endpoints || []).map(sub => (sub.title || '') + ' ' + (sub.subpath || '') + ' ' + (sub.path || ''))
].join(' ').toLowerCase();
return haystack.includes(q);
});
if (countEl) {
countEl.textContent = `Showing ${filtered.length} of ${this._docModalApis.length} APIs`;
}
if (filtered.length === 0) {
listEl.innerHTML = `
<div style="text-align:center; padding:50px 20px; color:var(--text-3);">
<i class="fa-solid fa-magnifying-glass" style="font-size:24px; opacity:0.3; margin-bottom:10px; display:block;"></i>
No APIs found matching "<b>${this.escapeHTML(q)}</b>"
</div>
`;
return;
}
listEl.innerHTML = filtered.map(api => {
const subEps = (api.endpoints && api.endpoints.length) ? api.endpoints : [api];
const hasMultiple = subEps.length > 1;
const targetUrl = api.full_url || ('https://apigp0006.creinnovations.in' + (api.path || ''));
const cleanParams = (api.params || []).filter(p => p.n && p.n.trim());
const chips = api.chips || [];
return `
<div class="doc-import-card" onclick="App.importFromDoc('${api.id}', 0)">
<div style="display:flex; align-items:center; justify-content:space-between; gap:10px;">
<div style="display:flex; align-items:center; gap:8px; flex:1; min-width:0;">
<span class="method-badge m-${api.method === 'MULTI' ? 'POST' : api.method}">${api.method}</span>
<span style="font-family:var(--font-mono); font-weight:700; font-size:13px; color:var(--text-1); overflow:hidden; text-overflow:ellipsis; white-space:nowrap;" title="${this.escapeHTML(api.api_key || api.title)}">
${this.escapeHTML(api.api_key || api.title)}
</span>
<span style="font-size:10px; color:var(--text-3); background:var(--bg-input); padding:2px 7px; border-radius:4px; border:1px solid var(--border-1); white-space:nowrap;">
${this.escapeHTML(api.secTitle)}
</span>
</div>
<div style="display:flex; align-items:center; gap:6px; flex-shrink:0;">
${hasMultiple ? `<span style="font-size:10px; font-weight:600; color:var(--primary); background:var(--ph-alpha); padding:2px 8px; border-radius:4px;">${subEps.length} routes</span>` : ''}
${chips.length ? `<span style="font-size:10px; color:var(--text-2); background:var(--glass-2); padding:2px 8px; border-radius:4px;">${chips.length} presets</span>` : ''}
<button class="btn btn-sm btn-primary" onclick="event.stopPropagation(); App.importFromDoc('${api.id}', 0)" title="Import this API and pre-fill all fields">
<i class="fa-solid fa-bolt"></i> Import
</button>
</div>
</div>
<div style="font-family:var(--font-mono); font-size:11px; color:var(--text-3); overflow:hidden; text-overflow:ellipsis; white-space:nowrap;">
<i class="fa-solid fa-link" style="font-size:9.5px; margin-right:4px; opacity:0.6;"></i>${this.escapeHTML(targetUrl)}
</div>
<div style="font-size:12px; color:var(--text-2); line-height:1.4;">
${this.escapeHTML(api.summary || api.title)}
</div>
<!-- Parameter Badges Preview -->
<div style="display:flex; flex-wrap:wrap; gap:4px; align-items:center;">
<span style="font-size:9.5px; font-weight:700; text-transform:uppercase; letter-spacing:0.05em; color:var(--text-3); margin-right:4px;">Fields:</span>
${cleanParams.slice(0, 6).map(p => {
const isFile = /file|binary/i.test(p.ty);
const isPreset = chips.length && (/id$/i.test(p.n) || /preset/i.test(p.n));
const cls = isFile ? 'param-file' : (isPreset ? 'param-preset' : '');
return `
<span class="doc-param-chip ${cls}">
${isFile ? '<i class="fa-solid fa-file-image"></i>' : (isPreset ? '<i class="fa-solid fa-sliders"></i>' : '')}
${this.escapeHTML(p.n)}${p.rq ? ' *' : ''}
</span>
`;
}).join('')}
${cleanParams.length > 6 ? `<span style="font-size:10px; color:var(--text-3);">+${cleanParams.length - 6} more</span>` : ''}
</div>
<!-- Multi-endpoint routes if multiple -->
${hasMultiple ? `
<div style="margin-top:4px; padding-top:8px; border-top:1px solid var(--border-1);" onclick="event.stopPropagation();">
<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:4px;">
<span style="font-size:10px; font-weight:700; text-transform:uppercase; letter-spacing:0.05em; color:var(--text-3);">Available Endpoints:</span>
<button class="btn btn-ghost" style="height:20px; font-size:10px; padding:0 6px; color:var(--primary);" onclick="App.importFromDoc('${api.id}', null, null, null, true)">
<i class="fa-solid fa-layer-group"></i> Import All ${subEps.length} Routes
</button>
</div>
<div style="display:flex; flex-direction:column; gap:4px;">
${subEps.map((sub, sIdx) => `
<div class="doc-sub-route-item">
<div style="display:flex; align-items:center; gap:8px; min-width:0; flex:1;">
<span class="method-badge m-${sub.method}">${sub.method}</span>
<code style="font-family:var(--font-mono); font-size:11px; color:var(--text-1);">${this.escapeHTML(sub.subpath || sub.path)}</code>
<span style="font-size:11.5px; color:var(--text-2); overflow:hidden; text-overflow:ellipsis; white-space:nowrap;">${this.escapeHTML(sub.title)}</span>
</div>
<button class="btn btn-sm btn-ghost" style="font-size:10.5px; height:24px; padding:0 8px; color:var(--primary);" onclick="event.stopPropagation(); App.importFromDoc('${api.id}', ${sIdx});">
Import Route
</button>
</div>
`).join('')}
</div>
</div>
` : ''}
</div>
`;
}).join('');
},
async importFromDoc(apiId, subEpIdx = 0, targetColId = null, customColName = null, importAll = false) {
const api = (this._docModalApis || []).find(a => a.id === apiId);
if (!api) {
this.toast("API not found", "error");
return;
}
// Ensure active workspace
if (!this.state.activeSpaceId && this.state.spaces && this.state.spaces.length > 0) {
this.state.activeSpaceId = this.state.spaces[0].id;
}
let activeSpace = this.state.spaces.find(s => s.id === this.state.activeSpaceId);
if (!activeSpace) {
const newSpace = { id: 'workspace_' + Date.now(), name: 'Default Workspace', collections: [] };
this.state.spaces.push(newSpace);
this.state.activeSpaceId = newSpace.id;
activeSpace = newSpace;
}
// Determine destination collection:
const selDest = document.getElementById('doc-modal-dest-select');
let destinationId = targetColId || (selDest && selDest.value ? selDest.value : this._importTargetColId);
let col = null;
if (destinationId) {
const found = this.findCollectionAcrossSpaces(destinationId);
if (found) {
activeSpace = found.space;
this.state.activeSpaceId = activeSpace.id;
col = found.collection;
}
}
if (!col) {
// Create new collection
const colName = customColName || api.api_key || api.title || "Imported API";
const newColId = 'col_' + Date.now();
col = {
id: newColId,
name: colName,
requests: []
};
if (!activeSpace.collections) activeSpace.collections = [];
activeSpace.collections.push(col);
}
// Always activate and expand this collection in the sidebar!
this.state.activeCollectionId = col.id;
const subEndpoints = importAll
? (api.endpoints && api.endpoints.length ? api.endpoints : [api])
: (subEpIdx !== null && api.endpoints && api.endpoints[subEpIdx] ? [api.endpoints[subEpIdx]] : (api.endpoints && api.endpoints[0] ? [api.endpoints[0]] : [api]));
let lastCreatedReq = null;
subEndpoints.forEach((sub, sIdx) => {
const reqId = 'req_' + Date.now() + '_' + sIdx;
const targetUrl = sub.full_url || api.full_url || (sub.path ? ('https://apigp0006.creinnovations.in' + sub.path) : '');
const method = (sub.method === 'MULTI' ? 'POST' : (sub.method || api.method || 'POST')).toUpperCase();
const cleanParams = (sub.params || api.params || []).filter(p => p.n && p.n.trim());
const queryParams = cleanParams.filter(p => /query/i.test(p.lc));
const bodyParams = cleanParams.filter(p => !/query/i.test(p.lc));
// CRITICAL: Fill ONLY the field and type, DO NOT fill values!
const finalQueryParams = queryParams.length ? queryParams.map(p => ({
id: (Date.now() + Math.random()).toString(),
key: p.n,
value: '', // Strictly empty!
type: 'text',
enabled: true
})) : [{ id: (Date.now() + Math.random()).toString(), key: '', value: '', type: 'text', enabled: true }];
let bodyType = 'none';
let bodyData = [];
let jsonBody = '';
const isJson = bodyParams.some(p => /json|raw/i.test(p.lc) || /application\/json/i.test(p.lc));
if (isJson) {
bodyType = 'json';
jsonBody = ''; // Strictly empty!
} else if (bodyParams.length > 0 || method === 'POST') {
bodyType = 'form-data';
bodyData = bodyParams.map(p => {
const isFile = /file|binary/i.test(p.ty);
return {
id: (Date.now() + Math.random()).toString(),
key: p.n,
value: '', // Strictly empty! Just key and type!
type: isFile ? 'file' : 'text',
enabled: true
};
});
}
const newReq = {
id: reqId,
name: sub.title || api.title || api.api_key,
method: method,
url: targetUrl,
description: sub.desc || sub.summary || api.desc || api.summary || '',
params: finalQueryParams,
headers: [{ id: (Date.now() + Math.random()).toString(), key: '', value: '', type: 'text', enabled: true }],
auth: { type: 'none' },
bodyType: bodyType,
bodyData: bodyData,
jsonBody: jsonBody
};
col.requests.push(newReq);
lastCreatedReq = newReq;
});
if (lastCreatedReq) {
const reqTabData = {
id: 'tab_' + Date.now() + Math.random().toString(36).substr(2, 9),
name: lastCreatedReq.name,
method: lastCreatedReq.method,
url: lastCreatedReq.url,
params: JSON.parse(JSON.stringify(lastCreatedReq.params)),
headers: JSON.parse(JSON.stringify(lastCreatedReq.headers)),
auth: JSON.parse(JSON.stringify(lastCreatedReq.auth)),
bodyType: lastCreatedReq.bodyType,
bodyData: JSON.parse(JSON.stringify(lastCreatedReq.bodyData)),
jsonBody: lastCreatedReq.jsonBody,
response: null,
bulk: { strategy: 'consecutive', running: false, total: 0, completed: 0, success: 0, error: 0, concurrency: 1, results: [] },
activeTab: lastCreatedReq.bodyType === 'none' ? 'params' : 'body',
responseTab: 'response',
activeRequestId: lastCreatedReq.id,
activeCollectionId: col.id,
isPreview: false
};
const currTab = this.tabs[this.activeTabIndex];
const isUntouched = currTab && (!currTab.url && !currTab.activeRequestId && !currTab.response);
if (isUntouched) {
this.tabs[this.activeTabIndex] = reqTabData;
} else {
this.tabs.push(reqTabData);
this.activeTabIndex = this.tabs.length - 1;
}
this.state.activeRequestId = lastCreatedReq.id;
}
// Close modals
const modal = document.getElementById('import-doc-modal');
if (modal) modal.remove();
const createModal = document.getElementById('create-col-modal');
if (createModal) createModal.remove();
this.saveState();
await this.saveSpacesToServer();
this._renderAll();
const successMsg = importAll
? `Imported all ${subEndpoints.length} routes into "${col.name}"!`
: `Imported "${lastCreatedReq ? lastCreatedReq.name : 'API'}" into "${col.name}"!`;
this.toast(successMsg, "success");
},
renameCollection(colId, spaceId) {
if (spaceId && spaceId !== this.state.activeSpaceId) {
this.state.activeSpaceId = spaceId;
}
let col = this.collections.find(c => c.id === colId);
if (!col) {
const found = this.findCollectionAcrossSpaces(colId);
if (found) {
col = found.collection;
this.state.activeSpaceId = found.space.id;
}
}
if(!col) return;
const newName = prompt("Enter new collection name:", col.name);
if(newName && newName.trim()) {
col.name = newName.trim();
this.saveState();
this._debouncedSaveSpaces();
this._renderAll();
}
},
renameRequest(colId, reqId, spaceId) {
if (spaceId && spaceId !== this.state.activeSpaceId) {
this.state.activeSpaceId = spaceId;
}
let col = this.collections.find(c => c.id === colId);
if (!col) {
const found = this.findCollectionAcrossSpaces(colId);
if (found) {
col = found.collection;
this.state.activeSpaceId = found.space.id;
}
}
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._debouncedSaveSpaces();
this._renderAll();
}
},
deleteCollection(colId, spaceId) {
if (spaceId && spaceId !== this.state.activeSpaceId) {
this.state.activeSpaceId = spaceId;
}
if(confirm("Delete this collection and all its requests? This cannot be undone.")) {
const found = this.findCollectionAcrossSpaces(colId);
const targetSpace = (found && found.space) ? found.space : (this.state.spaces || []).find(s => s.id === this.state.activeSpaceId);
if (targetSpace) {
targetSpace.collections = (targetSpace.collections || []).filter(c => c.id !== colId);
if (targetSpace.collections.length === 0) {
targetSpace.collections = [{ id: 'default', name: 'My Requests', requests: [] }];
}
}
// Always keep at least one collection
if (this.collections.length === 0) {
this.collections = [{ id: 'default', name: 'My Requests', requests: [] }];
}
// If deleted collection was active, switch to first remaining
const stillExists = this.collections.some(c => c.id === this.state.activeCollectionId);
if (!stillExists) {
this.state.activeCollectionId = this.collections[0].id;
this.state.activeRequestId = null;
}
this.saveState();
this._debouncedSaveSpaces();
this._renderAll();
}
},
addRequestToCollection(colId, spaceId) {
if (spaceId && spaceId !== this.state.activeSpaceId) {
this.state.activeSpaceId = spaceId;
}
let col = this.collections.find(c => c.id === colId);
if (!col) {
const found = this.findCollectionAcrossSpaces(colId);
if (found) {
col = found.collection;
this.state.activeSpaceId = found.space.id;
}
}
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);
// Open this new request in a new tab
const reqTabData = {
id: 'tab_' + Date.now() + Math.random().toString(36).substr(2, 9),
name: 'New Request',
method: 'GET',
url: '',
params: JSON.parse(JSON.stringify(newReq.params)),
headers: JSON.parse(JSON.stringify(newReq.headers)),
auth: { type: 'none' },
bodyType: 'none',
bodyData: [],
jsonBody: '',
response: null,
bulk: { strategy: 'consecutive', running: false, total: 0, completed: 0, success: 0, error: 0, concurrency: 1, results: [] },
activeTab: 'params',
responseTab: 'response',
activeRequestId: reqId,
activeCollectionId: colId,
isPreview: false
};
this.tabs.push(reqTabData);
this.activeTabIndex = this.tabs.length - 1;
this.saveState();
this._debouncedSaveSpaces();
this._renderAll();
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._debouncedSaveSpaces();
this._renderAll();
}
},
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._debouncedSaveSpaces();
}
},
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}`;
let originalExt = '';
// Extract existing extension if present
const lastDot = name.lastIndexOf('.');
if (lastDot > 0 && (name.length - lastDot) <= 6) {
originalExt = name.substring(lastDot);
name = name.substring(0, lastDot);
}
// 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;
}
}
// Content sniffing for JSON if content type is missing or incorrect
if (!result.binaryData && result.fullContent) {
const trimmed = result.fullContent.trim();
if ((trimmed.startsWith('{') && trimmed.endsWith('}')) || (trimmed.startsWith('[') && trimmed.endsWith(']'))) {
try {
JSON.parse(trimmed); // Quick validation
return name + '.json';
} catch(e) {}
}
}
// If we still don't know the type, fallback to original extension if it existed
if (originalExt) return name + originalExt;
// Otherwise default based on data format
return result.binaryData ? name + '.bin' : name + '.txt';
},
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 — prefer blobUrl, fallback to fullContent
let data;
if (r.blobUrl) {
const blob = await fetch(r.blobUrl).then(res => res.blob());
data = await blob.arrayBuffer();
} 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 — prefer blobUrl (memory efficient), fallback to fullContent
let data;
if (result.blobUrl) {
const blob = await fetch(result.blobUrl).then(r => r.blob());
data = await blob.arrayBuffer();
zip.file(filename, data, { binary: true });
} else if (result.fullContent) {
data = result.fullContent;
zip.file(filename, data, { binary: false });
} else {
continue; // Skip empty results
}
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 {
this.toast('Generating ZIP, please wait...', 'info');
const blob = await zip.generateAsync({ type: 'blob' });
const url = URL.createObjectURL(blob);
const modal = document.createElement('div');
modal.className = 'premium-modal-overlay';
modal.style.zIndex = '9999';
modal.innerHTML = `
<div class="premium-modal-card" onclick="event.stopPropagation();" style="width:min(400px,90vw);text-align:center;padding:30px;">
<i class="fa-solid fa-file-zipper" style="font-size:48px;color:var(--primary);margin-bottom:20px;"></i>
<h3 style="margin:0 0 10px 0;color:var(--text-1);font-family:var(--font-display);">ZIP Ready!</h3>
<p style="margin:0 0 20px 0;color:var(--text-2);font-size:13px;">Successfully bundled ${savedCount} files.</p>
<a href="${url}" download="bulk_results_${new Date().toISOString().replace(/[:.]/g, '-')}.zip"
class="btn btn-primary" style="display:inline-block;text-decoration:none;padding:10px 20px;width:100%;box-sizing:border-box;"
onclick="setTimeout(() => { this.closest('.premium-modal-overlay').remove(); }, 100);">
<i class="fa-solid fa-download"></i> Click to Download ZIP
</a>
<button class="btn btn-ghost" style="margin-top:10px;width:100%;" onclick="this.closest('.premium-modal-overlay').remove()">Cancel</button>
</div>
`;
document.body.appendChild(modal);
// Note: intentionally not revoking the URL immediately so the manual click works!
} catch (e) {
this.toast('Error generating ZIP: ' + e.message, 'error');
}
},
// --- Rendering ---
// Debounced render — coalesces rapid successive calls (e.g., keystrokes)
// into a single animation frame to prevent jank.
scheduleRender() {
if (this._renderScheduled) return;
this._renderScheduled = true;
requestAnimationFrame(() => {
this._renderScheduled = false;
this._renderAll();
});
},
// ── Targeted update helpers ─────────────────────────────────────────────
_onMethodChange(val) { this.state.method = val; this.saveState(); this._updateActionBtns(); this._updateBulkControls(); },
_onUrlInput(val) { this.state.url = val; this.saveState(); },
_updateRootClasses() {
const root = document.getElementById('app-root');
if (!root) return;
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');
if (this.state.activeSpaceId) {
const sp = this.state.spaces.find(s => s.id === this.state.activeSpaceId);
const theme = sp && sp.theme ? sp.theme : 'dark';
root.classList.add(`theme-${theme}`);
document.body.className = `theme-${theme}`;
}
},
_updateWorkspaceSelect() {
const sel = this.dom.wsSelect;
if (!sel) return;
sel.innerHTML = `<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('');
},
_updateSidebarVisibility() {
const ch = this.dom.collectionsHeader || document.getElementById('collections-header');
const sw = this.dom.searchWrap || document.getElementById('search-wrap');
if (ch) ch.style.display = 'flex';
if (sw) sw.style.display = '';
const label = document.getElementById('collections-header-label');
const globeBtn = document.getElementById('toggle-all-cols-btn');
if (label) {
const hasOwnCollections = this.state.activeSpaceId && (this.collections || []).some(c => (c.requests && c.requests.length > 0) || (c.id !== 'default' && c.name !== 'My Requests'));
const isAll = this.state.showAllCollections || !hasOwnCollections;
if (isAll) {
label.innerHTML = `<i class="fa-solid fa-layer-group" style="color:var(--warning);font-size:9px;"></i> All Collections`;
label.title = "Showing all collections across workspaces. Click to toggle.";
if (globeBtn) {
globeBtn.style.color = 'var(--primary)';
globeBtn.style.background = 'var(--glass-2)';
}
} else {
label.innerHTML = `<i class="fa-solid fa-layer-group" style="color:var(--warning);font-size:9px;"></i> Collections`;
label.title = "Showing current workspace collections. Click to show all.";
if (globeBtn) {
globeBtn.style.color = '';
globeBtn.style.background = '';
}
}
}
},
_updateNotifBanner() {
const b = this.dom.notifBanner;
if (!b) return;
const sp = this.state.spaces.find(s => s.id === this.state.activeSpaceId);
const n = sp && sp.notifications && sp.notifications.length;
if (n) {
b.style.display = '';
b.className = 'notifications-banner';
b.innerHTML = `<i class="fa-solid fa-bell"></i><span>${n} pending share request${n > 1 ? 's' : ''}</span>`;
b.onclick = () => this.openNotificationsModal();
} else {
b.style.display = 'none';
}
},
_updateWorkspaceBadge() {
const badge = this.dom.wsBadge;
const ts = this.dom.themeSelect;
const sp = this.state.spaces.find(s => s.id === this.state.activeSpaceId);
if (sp && badge) {
badge.innerHTML = `<div class="ws-badge-pill" title="Switch workspace"><i class="fa-solid fa-cube"></i><span class="ws-badge-name">${this.escapeHTML(sp.name)}</span><i class="fa-solid fa-chevron-down" style="opacity:0.7;"></i></div>`;
}
if (ts && sp) ts.value = sp.theme || 'dark';
},
_updateUrlBar() {
const ms = this.dom.methodSelect;
const ui = this.dom.urlInput;
if (ms && document.activeElement !== ms) ms.value = this.state.method || 'POST';
if (ui && document.activeElement !== ui) ui.value = this.state.url || '';
if (ms) {
const mc = {GET:'var(--m-get)',POST:'var(--m-post)',PUT:'var(--m-put)',DELETE:'var(--m-delete)',PATCH:'var(--m-patch)'};
ms.style.color = mc[this.state.method] || 'var(--text-1)';
}
},
_updateActionBtns() {
const c = this.dom.actionBtns;
if (!c) return;
const bulk = this.state.bulk;
if (bulk.running) {
c.innerHTML = `
<button class="btn btn-warning" onclick="App.pauseBulk()" title="Pause Batch Execution">
<i class="fa-solid fa-pause"></i> PAUSE
</button>
<button class="btn btn-danger" onclick="App.stopBulk()" title="Stop Batch Execution">
<i class="fa-solid fa-stop"></i> STOP
</button>
`;
} else if (bulk.paused) {
c.innerHTML = `
<button class="btn btn-success" onclick="App.resumeBulk()" title="Resume Batch Execution">
<i class="fa-solid fa-play"></i> RESUME
</button>
<button class="btn btn-danger" onclick="App.stopBulk()" title="Stop Batch Execution">
<i class="fa-solid fa-stop"></i> STOP
</button>
`;
} else {
const method = (this.state.method || 'POST').toUpperCase();
const isMac = navigator.platform.toUpperCase().indexOf('MAC') >= 0;
const shortcutText = isMac ? '⌘↵' : 'Ctrl+↵';
const methodIcons = {
GET: 'fa-arrow-down-long',
POST: 'fa-paper-plane',
PUT: 'fa-arrows-rotate',
DELETE: 'fa-trash-can',
PATCH: 'fa-pen-to-square'
};
const icon = methodIcons[method] || 'fa-paper-plane';
c.innerHTML = `
<button class="btn btn-primary btn-main-action method-${method.toLowerCase()}" id="btn-main-action" onclick="App.executeMainAction()" title="Execute ${method} Request (${shortcutText})">
<i class="fa-solid ${icon}"></i>
<span class="btn-text">${method}</span>
<kbd class="kbd-pill">${shortcutText}</kbd>
</button>
`;
}
},
executeMainAction() {
if (!this.state.url) return this.toast('URL is required', 'error');
const bulk = this.state.bulk;
if (bulk && bulk.running) {
this.pauseBulk();
return;
}
if (bulk && bulk.paused) {
this.resumeBulk();
return;
}
// Animate press effect on button
const mainBtn = document.getElementById('btn-main-action') || document.getElementById('btn-run-batch');
if (mainBtn) {
mainBtn.classList.add('keyboard-trigger-active');
setTimeout(() => mainBtn.classList.remove('keyboard-trigger-active'), 250);
}
if (this.checkBulkStart()) {
this.runBulk();
} else {
this.sendRequest();
}
},
_updateReqTabStrip() {
const strip = this.dom.reqTabStrip;
if (!strip) return;
strip.innerHTML = this.tabs.map((tab, i) => {
const isActive = i === this.activeTabIndex;
const tabName = tab.name || (tab.url ? tab.url.split('/').pop() || 'Request' : 'Untitled');
const dn = tabName.length > 20 ? tabName.substring(0,20)+'…' : tabName;
const m = tab.method || 'GET';
return `<div class="main-tab ${isActive?'active':''}" onclick="App.switchTab(${i})" title="${this.escapeHTML(tab.name||tab.url||'Untitled')}"><span class="main-tab-method m-${m}">${m}</span><span class="main-tab-name">${this.escapeHTML(dn)}</span><button class="main-tab-close" onclick="event.stopPropagation();App.closeTab(${i})" title="Close tab">×</button></div>`;
}).join('') + `<button class="main-tab-add" onclick="App.openNewTab()" title="New tab"><i class="fa-solid fa-plus"></i></button>`;
},
_updateRequestMeta() {
const meta = this.dom.requestMeta;
if (!meta) return;
const sp = this.state.spaces.find(s => s.id === this.state.activeSpaceId);
const col = sp ? sp.collections.find(c => c.id === this.state.activeCollectionId) : null;
const req = col ? col.requests.find(r => r.id === this.state.activeRequestId) : null;
meta.style.display = req ? '' : 'none';
if (req) {
const ni = this.dom.reqNameInput, di = this.dom.reqDescInput;
if (ni && document.activeElement !== ni) ni.value = req.name || '';
if (di && document.activeElement !== di) di.value = req.description || '';
}
},
_updateBulkControls() {
const c = this.dom.bulkControls;
if (!c) return;
const isBulkStart = this.checkBulkStart();
c.innerHTML = `
${isBulkStart ? `<div class="bulk-control-group bulk-strategy-group"><span class="bulk-control-label">Strategy</span><label style="cursor:pointer;display:flex;align-items:center;gap:5px;font-size:11.5px;color:var(--text-2);"><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;display:flex;align-items:center;gap:5px;font-size:11.5px;color:var(--text-2);"><input type="radio" name="bulkStrategy" value="cartesian" ${this.state.bulk.strategy==='cartesian'?'checked':''} onchange="App.state.bulk.strategy='cartesian';App.saveState();"> All×All</label></div>` : ''}
<div class="bulk-control-group"><span class="bulk-control-label">Repeat</span><input type="number" min="1" max="9999" class="bulk-num-input" style="width:52px;" value="${this.state.bulk.repetitions||10}" onchange="App.state.bulk.repetitions=Math.max(1,parseInt(this.value)||1);App.saveState();"></div>
<div class="bulk-control-group"><span class="bulk-control-label">Delay</span><input type="number" min="0" max="60000" step="100" class="bulk-num-input" style="width:60px;" value="${this.state.bulk.delay||0}" onchange="App.state.bulk.delay=Math.max(0,parseInt(this.value)||0);App.saveState();"></div>
<div class="bulk-control-group"><span class="bulk-control-label">Workers</span><input type="number" min="1" max="20" class="bulk-num-input" style="width:44px;" value="${this.state.bulk.concurrency||1}" onchange="App.state.bulk.concurrency=Math.max(1,Math.min(20,parseInt(this.value)||1));App.saveState();"></div>
`;
},
_switchContentTab(tabName) {
this.state.activeTab = tabName;
['params','headers','body','auth'].forEach(t => {
const el = document.getElementById('ctab-'+t);
if (el) el.classList.toggle('active', t === tabName);
});
const ca = this.dom.contentArea;
if (!ca) return;
if (tabName === 'params') ca.innerHTML = this.renderTable(this.state.params, 'params');
else if (tabName === 'headers') ca.innerHTML = this.renderTable(this.state.headers, 'headers');
else if (tabName === 'body') ca.innerHTML = this.renderBodyTab();
else if (tabName === 'auth') ca.innerHTML = this.renderAuthTab();
this.saveState();
},
_switchBottomTab(tabName) {
this.state.responseTab = tabName;
const isResp = tabName === 'response';
const pr = this.dom.ptabResponse, prs = this.dom.ptabResults;
if (pr) pr.classList.toggle('active', isResp);
if (prs) prs.classList.toggle('active', !isResp);
const rv = this.dom.responseView, rsv = this.dom.resultsView;
if (rv) rv.style.display = isResp ? 'flex' : 'none';
if (rsv) rsv.style.display = !isResp ? 'flex' : 'none';
if (!isResp) this._updateBottomRightActions();
this.saveState();
},
_updateBottomStats() {
const bulk = this.state.bulk;
const has = bulk.results.length > 0;
const b = this.dom.resultBadge, sep = this.dom.statSep;
const sc = this.dom.statCompleted, ss = this.dom.statSuccess, se = this.dom.statError;
if (b) { b.textContent = bulk.results.length; b.style.display = has ? '' : 'none'; }
if (sep) sep.style.display = has ? '' : 'none';
if (sc) { sc.style.display = has ? '' : 'none'; sc.textContent = `${bulk.completed}/${bulk.total}`; }
if (ss) { ss.style.display = has ? '' : 'none'; ss.textContent = `${bulk.success} ✓`; }
if (se) { se.style.display = has ? '' : 'none'; se.textContent = `${bulk.error} ✗`; }
},
_updateBottomRightActions() {
const c = this.dom.bottomRightActions;
if (!c) return;
const bulk = this.state.bulk;
const isResults = (this.state.responseTab || 'response') === 'results';
if (isResults && bulk.results.length > 0) {
const fp = this.state.outputFolderPath || 'None selected';
c.style.display = 'flex';
c.innerHTML = `<div class="folder-selector-container"><span class="folder-path-display" title="${fp}"><i class="fa-solid fa-folder-open"></i> ${fp}</span><button class="btn btn-ghost" style="padding:0 11px;height:100%;border:none;border-radius:0;border-left:1px solid var(--border-2);font-size:10px;" onclick="App.browseServerFolder()">Browse</button><button class="btn btn-primary" style="padding:0 11px;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 btn-sm" style="height:30px;" onclick="App.saveAllResults()"><i class="fa-solid fa-file-zipper"></i> ZIP</button><button class="btn btn-ghost btn-sm" style="height:30px;" onclick="App.downloadHistory()"><i class="fa-solid fa-file-csv"></i> CSV</button><button class="btn btn-ghost btn-sm" style="height:30px;" onclick="App.openFullscreenResults()"><i class="fa-solid fa-maximize"></i> Expand</button><button class="btn btn-danger btn-sm" style="height:30px;" onclick="App.clearBulkResults()"><i class="fa-solid fa-trash"></i> Clear</button>`;
} else {
c.style.display = 'none';
}
},
_updateResponseView() {
const rv = this.dom.responseView;
if (!rv) return;
const resp = this.state.response;
if (!resp) {
rv.innerHTML = `<div class="empty-state"><i class="fa-solid fa-paper-plane"></i><span>Ready to send request. Click SEND or RUN BATCH.</span></div>`;
} else if (resp.status === 'Sending...') {
rv.innerHTML = `<div class="empty-state"><i class="fa-solid fa-spinner fa-spin"></i><span>Sending request...</span></div>`;
} else if (resp.error) {
rv.innerHTML = `<div style="padding:20px;color:var(--danger);font-family:var(--font-mono);font-size:12px;white-space:pre-wrap;overflow:auto;height:100%;">Error: ${this.escapeHTML(String(resp.error))}</div>`;
} else {
let content = resp.content;
try { if (content && !resp.blobUrl && content.trim().startsWith('{')) content = JSON.stringify(JSON.parse(content), null, 2); } catch(e){}
rv.innerHTML = `<div style="display:flex;align-items:center;gap:14px;padding:10px 20px;border-bottom:1px solid var(--border-1);font-size:11px;background:rgba(0,0,0,0.14);flex-shrink:0;"><span class="status-badge" style="background:${this.getStatusColor(resp.status_code)};color:#04121b;font-weight:800;padding:3px 9px;border-radius:var(--r-xs);font-family:var(--font-mono);">${resp.status_code}</span><span style="color:var(--text-2);font-family:var(--font-mono);">${resp.latency ? resp.latency+'ms' : ''}</span><span style="margin-left:auto;font-size:10.5px;color:var(--text-3);font-family:var(--font-mono);">${resp.content_type||''}</span></div><div style="flex:1;overflow:auto;padding:14px;background:var(--bg-input);">${resp.blobUrl ? `<div style="padding:20px;text-align:center;"><img src="${resp.blobUrl}" loading="lazy" decoding="async" style="max-width:100%;max-height:260px;border:1px solid var(--border-2);border-radius:var(--r-md);box-shadow:var(--sh-lg);" alt="Response"/></div>` : `<pre class="code-block" style="margin:0;">${this.escapeHTML(content)}</pre>`}</div>`;
}
},
_updateDashboard() {
const sg = this.dom.spacesGrid;
if (!sg) return;
const themeIcons = { violet: 'fa-gem', cobalt: 'fa-shield-halved', rose: 'fa-heart', emerald: 'fa-leaf', amber: 'fa-sun', light: 'fa-cloud-sun', dark: 'fa-moon' };
sg.innerHTML = this.state.spaces.map((s, idx) => {
const count = s.collections ? s.collections.length : 0;
const nc = s.notifications ? s.notifications.length : 0;
const theme = s.theme || 'violet';
const icon = themeIcons[theme] || 'fa-cubes';
return `<div class="space-card space-card-${theme}" style="animation-delay:${Math.min(idx*60,360)}ms" onclick="App.openSpace('${s.id}')"><div class="space-card-icon"><i class="fa-solid ${icon}"></i>${nc > 0 ? `<span class="space-card-notif-badge">${nc}</span>` : ''}</div><div class="space-card-info"><h3>${this.escapeHTML(s.name)}</h3><span>${count} Collection${count === 1 ? '' : 's'} · ${theme}</span></div><div class="space-card-actions" onclick="event.stopPropagation();"><button class="btn btn-ghost" style="color:var(--text-3);padding:4px 8px;height:28px;" onclick="App.renameSpace('${s.id}')" title="Rename workspace"><i class="fa-solid fa-pencil" style="font-size:11px;"></i></button>${this.state.spaces.length > 1 ? `<button class="btn btn-ghost" style="color:var(--danger);padding:4px 8px;height:28px;" onclick="App.deleteSpace('${s.id}')" title="Delete workspace"><i class="fa-solid fa-trash" style="font-size:11px;"></i></button>` : ''}</div></div>`;
}).join('') + `<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>`;
},
// ── THE NEW renderMain: 100% surgical, zero full-panel innerHTML ──────────
renderMain() {
if (!this.state.activeSpaceId) {
// Show dashboard view, hide workspace view
if (this.dom.dashboardView) this.dom.dashboardView.style.display = 'flex';
if (this.dom.workspaceView) this.dom.workspaceView.style.display = 'none';
this._updateDashboard();
return;
}
// Ensure workspace view is visible
if (this.dom.dashboardView) this.dom.dashboardView.style.display = 'none';
if (this.dom.workspaceView) this.dom.workspaceView.style.display = 'flex';
// Surgical updates — each touches only its own DOM node
this._updateWorkspaceBadge();
this._updateUrlBar();
this._updateReqTabStrip();
this._updateRequestMeta();
this._updateBulkControls();
this._updateActionBtns();
// Content tab (only the small content-area div gets innerHTML'd)
this._switchContentTab(this.state.activeTab);
// Bottom panel - switch tab view + update stats + actions
this._switchBottomTab(this.state.responseTab || 'response');
this._updateBottomStats();
this._updateResponseView();
// Bottom panel height
if (this.dom.bottomPanel) this.dom.bottomPanel.style.height = (this.state.resultsPanelHeight || 300) + 'px';
// Results grid: idempotent repopulate
this._repopulateResultsGrid();
},
_repopulateResultsGrid() {
const grid1 = this.dom.resultsGrid || document.getElementById('main-results-grid');
const grid2 = document.querySelector('.fullscreen-results-grid');
if (grid1) grid1.innerHTML = '';
if (grid2) grid2.innerHTML = '';
if (this.state.bulk.results && this.state.bulk.results.length > 0) {
this.state.bulk.results.forEach(r => this.appendResultCardToDOM(r));
} else if (grid1) {
grid1.innerHTML = `<div style="grid-column: 1 / -1; padding: 40px; text-align: center; color: var(--text-muted);"><i class="fa-solid fa-flask" style="font-size: 24px; margin-bottom: 15px; opacity: 0.5;"></i><br>Ready for bulk testing</div>`;
}
},
_renderAll() {
this._updateRootClasses();
this._updateWorkspaceSelect();
this._updateSidebarVisibility();
this._updateNotifBanner();
this.renderSidebar();
this.renderMain();
},
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 colsToRender = [];
let isShowingAll = false;
if (this.state.showAllCollections) {
colsToRender = this.getAllCollections();
isShowingAll = true;
} else if (this.state.activeSpaceId) {
const currentCols = this.collections || [];
const meaningful = currentCols.filter(c => (c.requests && c.requests.length > 0) || (c.id !== 'default' && c.name !== 'My Requests'));
if (meaningful.length > 0) {
colsToRender = currentCols.map(c => ({ ...c, _spaceId: this.state.activeSpaceId }));
} else {
// Nothing in current workspace sidebar -> Show all collections!
colsToRender = this.getAllCollections();
isShowingAll = true;
}
} else {
// No active workspace (dashboard) -> Show all collections!
colsToRender = this.getAllCollections();
isShowingAll = true;
}
// If user searched for something, and current space produced 0 matches, search all collections!
if (query && !isShowingAll) {
const hasMatch = colsToRender.some(col => {
if ((col.name || '').toLowerCase().includes(query)) return true;
return (col.requests || []).some(r =>
(r.name || '').toLowerCase().includes(query) ||
(r.url || '').toLowerCase().includes(query) ||
(r.description || '').toLowerCase().includes(query)
);
});
if (!hasMatch) {
colsToRender = this.getAllCollections();
isShowingAll = true;
}
}
let collectionsHTML = '';
colsToRender.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 nothing is searched, show every request in the collection (all expanded by default)
const isExplicitlyCollapsed = Boolean(this.state.collapsedCollections && this.state.collapsedCollections[col.id] === true);
const isExpanded = query ? true : !isExplicitlyCollapsed;
const reqCount = (col.requests || []).length;
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}', '${col._spaceId || ''}')">
<span class="method-badge m-${r.method}">${r.method}</span>
<div class="history-item-content">
<div class="history-item-name" title="${this.escapeHTML(r.name || 'Untitled')}">
${this.escapeHTML(r.name || 'Untitled')}
</div>
<div class="history-item-url" title="${this.escapeHTML(r.url || 'No URL')}">
${this.escapeHTML(r.url || 'No URL')}
</div>
</div>
<div class="history-item-actions" onclick="event.stopPropagation();">
<button class="col-action-btn" onclick="App.renameRequest('${col.id}', '${r.id}', '${col._spaceId || ''}');" title="Rename Request">
<i class="fa-solid fa-pencil"></i>
</button>
<button class="col-action-btn danger" onclick="App.deleteRequest('${col.id}', '${r.id}', '${col._spaceId || ''}');" title="Delete Request">
<i class="fa-solid fa-xmark"></i>
</button>
</div>
</div>
`).join('');
const spaceBadgeHTML = (isShowingAll && col._spaceName) ? `
<span class="collection-space-badge" title="Workspace: ${this.escapeHTML(col._spaceName)}">
${this.escapeHTML(col._spaceName)}
</span>
` : '';
collectionsHTML += `
<div class="collection-group ${isExpanded ? 'expanded' : ''} ${isColActive ? 'active-col' : ''}">
<div class="collection-header" onclick="App.selectCollection('${col.id}', '${col._spaceId || ''}');">
<i class="fa-solid fa-chevron-right col-chevron ${isExpanded ? 'rotated' : ''}"></i>
<i class="fa-solid ${isExpanded ? 'fa-folder-open' : 'fa-folder'} col-folder"></i>
<span class="col-title" title="${this.escapeHTML(col.name)}">${this.escapeHTML(col.name)}</span>
<span class="col-count-pill" title="${reqCount} requests">${reqCount}</span>
${spaceBadgeHTML}
<div class="col-actions-bar" onclick="event.stopPropagation();">
<button class="col-action-btn" onclick="App.addRequestToCollection('${col.id}', '${col._spaceId || ''}')" title="Add Request">
<i class="fa-solid fa-plus"></i>
</button>
<button class="col-action-btn" onclick="App.openImportFromDocModal('${col.id}', '${col._spaceId || ''}')" title="Import API from Docs">
<i class="fa-solid fa-book-bookmark"></i>
</button>
<button class="col-action-btn" onclick="App.shareCollection('${col.id}', '${col._spaceId || ''}')" title="Share Collection">
<i class="fa-solid fa-share-nodes"></i>
</button>
<button class="col-action-btn" onclick="App.renameCollection('${col.id}', '${col._spaceId || ''}')" title="Rename Collection">
<i class="fa-solid fa-pencil"></i>
</button>
<button class="col-action-btn danger" onclick="App.deleteCollection('${col.id}', '${col._spaceId || ''}')" title="Delete Collection">
<i class="fa-solid fa-trash"></i>
</button>
</div>
</div>
${isExpanded ? `<div class="collection-items">${reqsHTML || `
<div class="empty-collection-box">
<div class="empty-col-text">Empty Collection</div>
<div style="display:flex; gap:6px;">
<button class="btn btn-sm btn-primary" style="font-size:10px; padding:4px 8px; flex:1; justify-content:center; gap:4px;" onclick="event.stopPropagation(); App.openImportFromDocModal('${col.id}', '${col._spaceId || ''}')">
<i class="fa-solid fa-book-bookmark"></i> Docs
</button>
<button class="btn btn-sm btn-ghost" style="font-size:10px; padding:4px 8px; flex:1; justify-content:center; gap:4px;" onclick="event.stopPropagation(); App.addRequestToCollection('${col.id}', '${col._spaceId || ''}')">
<i class="fa-solid fa-plus"></i> Request
</button>
</div>
</div>
`}</div>` : ''}
</div>
`;
});
return collectionsHTML;
},
filterSidebarCollections(query) {
this.state.searchQuery = query;
const listEl = this.dom.collectionsList || document.getElementById('collections-list');
if (listEl) {
listEl.innerHTML = this.getCollectionsHTML();
}
// Also update clear button and shortcut hint badge visibility
const clearBtn = document.getElementById('search-clear-btn');
const kbdBadge = document.getElementById('search-kbd-badge');
if (clearBtn) clearBtn.style.display = query ? 'block' : 'none';
if (kbdBadge) kbdBadge.style.display = query ? 'none' : 'block';
},
renderSidebar() {
// Only update the collections list — never replace the whole sidebar
const cl = this.dom.collectionsList;
if (cl) cl.innerHTML = this.getCollectionsHTML() || `
<div style="padding:24px 14px;font-size:11px;color:var(--text-3);text-align:center;line-height:1.6;">
<i class="fa-solid fa-layer-group" style="font-size:24px; color:var(--text-3); opacity:0.35; margin-bottom:10px; display:block;"></i>
No collections in this workspace.<br>
<div style="display:flex; flex-direction:column; gap:8px; margin-top:14px;">
<button class="btn btn-primary" style="font-size:11px; justify-content:center; gap:6px;" onclick="App.openImportFromDocModal()">
<i class="fa-solid fa-book-bookmark"></i> Import from Docs
</button>
<button class="btn btn-ghost" style="font-size:11px; justify-content:center; gap:6px;" onclick="App.createCollection()">
<i class="fa-solid fa-plus"></i> Blank Collection
</button>
</div>
</div>`;
},
// --- Helpers ---
renderTable(items, section) {
if (!Array.isArray(items)) items = [];
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>
<option value="auto_width" ${item.type === 'auto_width' ? 'selected' : ''}>Auto (Image Width)</option>
<option value="auto_height" ${item.type === 'auto_height' ? 'selected' : ''}>Auto (Image Height)</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="document.getElementById('file_${item.id}').click()">${label}</button>
<input type="file" id="file_${item.id}" style="display:none" ${item.type === 'folder' ? 'webkitdirectory directory' : 'multiple'}
onchange="App.handleFileSelect(this, '${section}', '${item.id}')">
</div>
`;
}
if (item.type === 'auto_width' || item.type === 'auto_height') {
return `<input class="cell-input val-input" disabled style="opacity:0.7; font-style:italic;" value="Auto-calculated from image">`;
}
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 class="body-type-row" style="margin-bottom:16px;">
<label class="body-type-pill"><input type="radio" name="bodyType" value="none" ${this.state.bodyType === 'none' ? 'checked' : ''} onchange="App.state.bodyType='none'; App._switchContentTab(App.state.activeTab); App.saveState();"> None</label>
<label class="body-type-pill"><input type="radio" name="bodyType" value="form-data" ${this.state.bodyType === 'form-data' ? 'checked' : ''} onchange="App.state.bodyType='form-data'; App._switchContentTab(App.state.activeTab); App.saveState();"> Multipart Form</label>
<label class="body-type-pill"><input type="radio" name="bodyType" value="json" ${this.state.bodyType === 'json' ? 'checked' : ''} onchange="App.state.bodyType='json'; App._switchContentTab(App.state.activeTab); 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;
const inStyle = 'width:100%;padding:10px 12px;background:var(--bg-input);border:1px solid var(--border-2);border-radius:var(--r-md);color:var(--text-1);font-family:var(--font-mono);font-size:12px;transition:border-color 0.15s,box-shadow 0.15s;';
const labelStyle = 'display:block;margin-bottom:6px;font-size:9.5px;font-weight:700;text-transform:uppercase;letter-spacing:0.07em;color:var(--text-3);';
return `
<div style="padding:20px;max-width:420px;">
<label style="${labelStyle}">Authorization Type</label>
<select onchange="App.state.auth.type=this.value; App._switchContentTab(App.state.activeTab); App.saveState();"
style="${inStyle} font-size:13px;cursor:pointer;">
<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:18px;">
<label style="${labelStyle}">Token</label>
<input type="text" style="${inStyle}" value="${auth.token || ''}" oninput="App.state.auth.token=this.value; App.saveState();" placeholder="eyJhbGciOi…"
onfocus="this.style.borderColor='var(--ph)';this.style.boxShadow='0 0 0 3px var(--ph-alpha)'"
onblur="this.style.borderColor='var(--border-2)';this.style.boxShadow='none'">
</div>
` : ''}
${auth.type === 'basic' ? `
<div style="margin-top:18px;display:grid;gap:12px;">
<div>
<label style="${labelStyle}">Username</label>
<input type="text" style="${inStyle}" value="${auth.username || ''}" oninput="App.state.auth.username=this.value; App.saveState();"
onfocus="this.style.borderColor='var(--ph)';this.style.boxShadow='0 0 0 3px var(--ph-alpha)'"
onblur="this.style.borderColor='var(--border-2)';this.style.boxShadow='none'">
</div>
<div>
<label style="${labelStyle}">Password</label>
<input type="password" style="${inStyle}" value="${auth.password || ''}" oninput="App.state.auth.password=this.value; App.saveState();"
onfocus="this.style.borderColor='var(--ph)';this.style.boxShadow='0 0 0 3px var(--ph-alpha)'"
onblur="this.style.borderColor='var(--border-2)';this.style.boxShadow='none'">
</div>
</div>
` : ''}
${auth.type === 'apikey' ? `
<div style="margin-top:18px;display:grid;gap:12px;">
<div>
<label style="${labelStyle}">Header Name</label>
<input type="text" style="${inStyle}" value="${auth.key || ''}" oninput="App.state.auth.key=this.value; App.saveState();" placeholder="X-API-Key"
onfocus="this.style.borderColor='var(--ph)';this.style.boxShadow='0 0 0 3px var(--ph-alpha)'"
onblur="this.style.borderColor='var(--border-2)';this.style.boxShadow='none'">
</div>
<div>
<label style="${labelStyle}">Value</label>
<input type="text" style="${inStyle}" value="${auth.value || ''}" oninput="App.state.auth.value=this.value; App.saveState();"
onfocus="this.style.borderColor='var(--ph)';this.style.boxShadow='0 0 0 3px var(--ph-alpha)'"
onblur="this.style.borderColor='var(--border-2)';this.style.boxShadow='none'">
</div>
</div>
` : ''}
</div>
`;
},
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._switchContentTab(this.state.activeTab);
}
},
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 icons = { info: 'fa-circle-info', success: 'fa-circle-check', error: 'fa-circle-xmark', warning: 'fa-triangle-exclamation' };
const iconColors = { info: '#5ba0f5', success: '#0fcea0', error: '#ff4569', warning: '#f5a623' };
const icon = icons[type] || icons.info;
const color = iconColors[type] || iconColors.info;
const t = document.createElement('div');
t.className = `ph-toast-${type}`;
t.innerHTML = `<i class="fa-solid ${icon}" style="color:${color}; font-size:15px; flex-shrink:0; position:relative; z-index:1;"></i><span style="flex:1; position:relative; z-index:1;">${this.escapeHTML(msg)}</span>`;
t.style.animation = 'toastSlideIn 0.34s cubic-bezier(0.34,1.56,0.64,1) both';
this.dom.toast.appendChild(t);
const removeDelay = type === 'error' ? 4500 : 3000;
setTimeout(() => {
t.style.animation = 'toastFadeOut 0.2s ease forwards';
setTimeout(() => t.remove(), 200);
}, removeDelay);
},
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;');
},
base64ToUint8Array(base64Data) {
if (!base64Data) return new Uint8Array(0);
try {
const byteCharacters = atob(base64Data);
const data = new Uint8Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
data[i] = byteCharacters.charCodeAt(i);
}
return data;
} catch (e) {
console.error("Base64 to Uint8Array error", e);
return new Uint8Array(0);
}
},
async base64ToBlobUrlAsync(base64Data, contentType) {
if (!base64Data) return '';
try {
const res = await fetch(`data:${contentType || 'application/octet-stream'};base64,${base64Data}`);
const blob = await res.blob();
return URL.createObjectURL(blob);
} catch (e) {
console.error("Async Base64 decode error", e);
return '';
}
},
base64ToBlobUrl(base64Data, contentType) {
if (!base64Data) return '';
try {
const byteCharacters = atob(base64Data);
const byteArrays = [];
const sliceSize = 512;
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
const slice = byteCharacters.slice(offset, offset + sliceSize);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
const blob = new Blob(byteArrays, {type: contentType});
return URL.createObjectURL(blob);
} catch (e) {
console.error("Base64 decode error", e);
return '';
}
},
bindEvents() {
// Global keyboard shortcuts (capture: true ensures inputs/textareas do not swallow Ctrl+Enter)
window.addEventListener('keydown', (e) => {
const isEnter = e.key === 'Enter' || e.keyCode === 13;
if ((e.ctrlKey || e.metaKey) && isEnter) {
e.preventDefault();
e.stopPropagation();
this.executeMainAction();
}
// Ctrl/Cmd + K → focus sidebar search
if ((e.ctrlKey || e.metaKey) && (e.key === 'k' || e.key === 'K' || e.keyCode === 75)) {
e.preventDefault();
const si = document.getElementById('search-input');
if (si) {
si.focus();
si.select();
}
}
}, true);
},
// Helper to resolve original sent image for Before / After comparison
resolveOriginalImageForResult(result) {
if (!result) return null;
if (result.sentImageUrl) {
return {
url: result.sentImageUrl,
name: result.sentImageName || result.inputFilename || 'Original Input'
};
}
// Search in fileStore
const targetName = result.inputFilename;
const targetIndex = (result.index || 1) - 1;
for (const [id, files] of this.fileStore.entries()) {
if (!files || files.length === 0) continue;
// Match by filename
if (targetName) {
const foundByName = Array.from(files).find(f => f.name === targetName);
if (foundByName) {
const u = URL.createObjectURL(foundByName);
result.sentImageUrl = u;
result.sentImageName = foundByName.name;
return { url: u, name: foundByName.name };
}
}
// Match by index
const f = files[targetIndex % files.length];
if (f && (f.type?.startsWith('image/') || /\.(jpg|jpeg|png|webp|gif|bmp|svg|avif)$/i.test(f.name))) {
const u = URL.createObjectURL(f);
result.sentImageUrl = u;
result.sentImageName = f.name;
return { url: u, name: f.name };
}
}
// Check single response sentImageUrl
if (this.state.response && this.state.response.sentImageUrl) {
return {
url: this.state.response.sentImageUrl,
name: this.state.response.sentImageName || 'Original Input'
};
}
return null;
},
// Preview a result with Before / After Image Split Slider
previewResult(index) {
let result = this.state.bulk.results.find(r => r.index === index);
// Fallback for single response preview
if (!result && this.state.response && (index === 0 || index === 'single' || this.state.bulk.results.length === 0)) {
result = {
index: 1,
status: this.state.response.status_code || 200,
latency: this.state.response.latency || 0,
blobUrl: this.state.response.blobUrl,
sentImageUrl: this.state.response.sentImageUrl,
sentImageName: this.state.response.sentImageName,
contentType: this.state.response.content_type || 'image/png',
inputFilename: this.state.response.sentImageName || 'input.png',
fullContent: this.state.response.content
};
}
if (!result) return;
const isImage = (result.contentType || '').toLowerCase().includes('image') && (result.blobUrl || result.binaryData);
const finalFilename = this.getFinalFilename(result);
const beforeObj = isImage ? this.resolveOriginalImageForResult(result) : null;
const afterUrl = isImage ? (result.blobUrl || this.base64ToBlobUrl(result.binaryData, result.contentType)) : null;
// Remove any existing preview modal
const oldModal = document.querySelector('.premium-modal-overlay.result-preview-overlay');
if (oldModal) oldModal.remove();
const modal = document.createElement('div');
modal.className = 'premium-modal-overlay result-preview-overlay';
let bodyContentHTML = '';
if (isImage) {
if (beforeObj && beforeObj.url && afterUrl) {
bodyContentHTML = `
<div class="ba-comparator-wrap">
<div class="ba-toolbar">
<div class="ba-mode-tabs">
<button class="ba-mode-tab active" id="ba-tab-split" onclick="App.setBeforeAfterMode('split')">
<i class="fa-solid fa-arrows-split-up-and-left"></i> Split Slider
</button>
<button class="ba-mode-tab" id="ba-tab-side" onclick="App.setBeforeAfterMode('side')">
<i class="fa-solid fa-table-columns"></i> Side-by-Side
</button>
<button class="ba-mode-tab" id="ba-tab-blink" onclick="App.setBeforeAfterMode('blink')">
<i class="fa-solid fa-bolt"></i> Blink Diff
</button>
</div>
<div class="ba-stats-strip">
<span class="ba-pill before-pill" title="Input file: ${this.escapeHTML(beforeObj.name)}">
<i class="fa-solid fa-arrow-left"></i> Before: <b>${this.escapeHTML(beforeObj.name)}</b>
</span>
<span class="ba-pill split-ratio-badge" id="ba-split-badge">50%</span>
<span class="ba-pill after-pill" title="Output file: ${this.escapeHTML(finalFilename)}">
After: <b>${this.escapeHTML(finalFilename)}</b> <i class="fa-solid fa-arrow-right"></i>
</span>
</div>
</div>
<div class="ba-stage mode-split" id="ba-stage" onmousedown="App.startBaDrag(event)" ontouchstart="App.startBaTouch(event)">
<!-- BEFORE (Original) Layer -->
<div class="ba-layer ba-layer-before">
<img src="${beforeObj.url}" class="ba-img" id="ba-img-before" alt="Original Input" draggable="false" />
<div class="ba-floating-tag tag-before"><i class="fa-solid fa-arrow-left"></i> ORIGINAL INPUT</div>
</div>
<!-- AFTER (Result) Layer (Clipped to split position) -->
<div class="ba-layer ba-layer-after" id="ba-layer-after" style="clip-path: polygon(50% 0, 100% 0, 100% 100%, 50% 100%);">
<img src="${afterUrl}" class="ba-img" id="ba-img-after" alt="API Result" draggable="false" />
<div class="ba-floating-tag tag-after">PROCESSED OUTPUT <i class="fa-solid fa-arrow-right"></i></div>
</div>
<!-- DRAGGABLE DIVIDER -->
<div class="ba-divider" id="ba-divider" style="left: 50%;">
<div class="ba-handle">
<i class="fa-solid fa-caret-left"></i>
<i class="fa-solid fa-grip-lines-vertical handle-grip"></i>
<i class="fa-solid fa-caret-right"></i>
</div>
</div>
</div>
<!-- SLIDER CONTROLS BAR -->
<div class="ba-slider-bar" id="ba-slider-bar">
<button class="btn btn-ghost btn-xs" onclick="App.setBeforeAfterPos(0)">100% Original</button>
<button class="btn btn-ghost btn-xs" onclick="App.setBeforeAfterPos(25)">25%</button>
<input type="range" class="ba-range" id="ba-range-input" min="0" max="100" value="50" oninput="App.setBeforeAfterPos(this.value)">
<button class="btn btn-ghost btn-xs" onclick="App.setBeforeAfterPos(50)">50% Split</button>
<button class="btn btn-ghost btn-xs" onclick="App.setBeforeAfterPos(75)">75%</button>
<button class="btn btn-ghost btn-xs" onclick="App.setBeforeAfterPos(100)">100% Result</button>
</div>
</div>
`;
} else {
bodyContentHTML = `
<div style="display:flex;flex-direction:column;align-items:center;gap:16px;">
<img src="${afterUrl}" class="modal-zoom-image" alt="${this.escapeHTML(finalFilename)}" loading="lazy" decoding="async" />
<div class="ba-load-reference-card">
<div style="font-size:12px;color:var(--text-2);">Want to compare with the original input image?</div>
<button class="btn btn-ghost btn-sm" onclick="document.getElementById('ba-file-picker').click()">
<i class="fa-solid fa-arrow-right-arrow-left"></i> Select Original Image to Compare
</button>
<input type="file" id="ba-file-picker" accept="image/*" style="display:none;" onchange="App.attachBeforeImageToResult(event, ${result.index})">
</div>
</div>
`;
}
} else {
let prettyContent = result.fullContent || '';
try {
if (prettyContent.trim().startsWith('{')) {
prettyContent = JSON.stringify(JSON.parse(prettyContent), null, 2);
}
} catch(e) {}
bodyContentHTML = `<pre class="modal-zoom-code">${this.escapeHTML(prettyContent)}</pre>`;
}
modal.innerHTML = `
<div class="premium-modal-card ba-modal-card" onclick="event.stopPropagation();" style="width:min(960px, 94vw); max-height:92vh;">
<div class="premium-modal-header">
<div class="premium-modal-title">
<i class="fa-solid ${isImage ? 'fa-images' : 'fa-file-code'}" style="color:var(--accent);font-size:18px;"></i>
<div>
<span class="modal-title-filename" title="${this.escapeHTML(finalFilename)}">${this.escapeHTML(finalFilename)}</span>
<span class="modal-title-sub">Result #${result.index} ${isImage ? '· Interactive Comparison' : ''}</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" style="overflow-y:auto; padding:16px;">
${bodyContentHTML}
</div>
<div class="premium-modal-footer">
${(isImage && beforeObj && beforeObj.url) ? `
<button class="btn btn-ghost btn-sm" onclick="App.downloadBeforeImage('${encodeURIComponent(beforeObj.url)}', '${encodeURIComponent(beforeObj.name)}')">
<i class="fa-solid fa-download"></i> Original Image
</button>
` : ''}
<button class="btn btn-ghost btn-sm" onclick="App.downloadIndividualResult(${result.index})">
<i class="fa-solid fa-arrow-down"></i> Download Result
</button>
<button class="btn btn-primary btn-sm" 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();
const escHandler = (e) => {
if (e.key === 'Escape') {
modal.remove();
window.removeEventListener('keydown', escHandler);
}
};
window.addEventListener('keydown', escHandler);
},
setBeforeAfterPos(val) {
val = Math.max(0, Math.min(100, parseFloat(val) || 50));
const afterLayer = document.getElementById('ba-layer-after');
const divider = document.getElementById('ba-divider');
const range = document.getElementById('ba-range-input');
const badge = document.getElementById('ba-split-badge');
if (afterLayer) afterLayer.style.clipPath = `polygon(${val}% 0, 100% 0, 100% 100%, ${val}% 100%)`;
if (divider) divider.style.left = `${val}%`;
if (range && range.value != val) range.value = val;
if (badge) badge.textContent = `${Math.round(val)}%`;
},
setBeforeAfterMode(mode) {
const stage = document.getElementById('ba-stage');
const sliderBar = document.getElementById('ba-slider-bar');
const tabs = document.querySelectorAll('.ba-mode-tab');
tabs.forEach(t => t.classList.remove('active'));
const activeTab = document.getElementById(`ba-tab-${mode}`);
if (activeTab) activeTab.classList.add('active');
if (!stage) return;
stage.classList.remove('mode-split', 'mode-side', 'mode-blink');
stage.classList.add(`mode-${mode}`);
if (mode === 'split') {
if (sliderBar) sliderBar.style.display = 'flex';
this.setBeforeAfterPos(50);
} else if (mode === 'side') {
if (sliderBar) sliderBar.style.display = 'none';
} else if (mode === 'blink') {
if (sliderBar) sliderBar.style.display = 'none';
let isShowingAfter = true;
stage.onclick = () => {
isShowingAfter = !isShowingAfter;
const afterLayer = document.getElementById('ba-layer-after');
if (afterLayer) afterLayer.style.opacity = isShowingAfter ? '1' : '0';
const badge = document.getElementById('ba-split-badge');
if (badge) badge.textContent = isShowingAfter ? 'AFTER' : 'BEFORE';
};
}
},
startBaDrag(e) {
const stage = document.getElementById('ba-stage');
if (!stage || !stage.classList.contains('mode-split')) return;
e.preventDefault();
const updateFromMouse = (moveEv) => {
const rect = stage.getBoundingClientRect();
if (rect.width <= 0) return;
const x = moveEv.clientX - rect.left;
const pct = Math.max(0, Math.min(100, (x / rect.width) * 100));
this.setBeforeAfterPos(pct);
};
updateFromMouse(e);
const onMouseMove = (moveEv) => updateFromMouse(moveEv);
const onMouseUp = () => {
window.removeEventListener('mousemove', onMouseMove);
window.removeEventListener('mouseup', onMouseUp);
};
window.addEventListener('mousemove', onMouseMove);
window.addEventListener('mouseup', onMouseUp);
},
startBaTouch(e) {
const stage = document.getElementById('ba-stage');
if (!stage || !stage.classList.contains('mode-split')) return;
if (!e.touches || !e.touches[0]) return;
const updateFromTouch = (touchEv) => {
if (!touchEv.touches || !touchEv.touches[0]) return;
const rect = stage.getBoundingClientRect();
if (rect.width <= 0) return;
const x = touchEv.touches[0].clientX - rect.left;
const pct = Math.max(0, Math.min(100, (x / rect.width) * 100));
this.setBeforeAfterPos(pct);
};
updateFromTouch(e);
const onTouchMove = (moveEv) => updateFromTouch(moveEv);
const onTouchEnd = () => {
window.removeEventListener('touchmove', onTouchMove);
window.removeEventListener('touchend', onTouchEnd);
};
window.addEventListener('touchmove', onTouchMove, { passive: true });
window.addEventListener('touchend', onTouchEnd);
},
attachBeforeImageToResult(event, resultIndex) {
const file = event.target.files && event.target.files[0];
if (!file) return;
const result = this.state.bulk.results.find(r => r.index === resultIndex) || (this.state.response ? { index: 1, ...this.state.response } : null);
if (result) {
result.sentImageUrl = URL.createObjectURL(file);
result.sentImageName = file.name;
}
if (this.state.response) {
this.state.response.sentImageUrl = URL.createObjectURL(file);
this.state.response.sentImageName = file.name;
}
this.previewResult(resultIndex);
},
downloadBeforeImage(urlEnc, nameEnc) {
const url = decodeURIComponent(urlEnc);
const name = decodeURIComponent(nameEnc) || 'original-image.png';
const a = document.createElement('a');
a.href = url;
a.download = name;
document.body.appendChild(a);
a.click();
a.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._renderAll();
}
},
togglePrecisionLens() {
const lens = document.getElementById('kubePrecisionLens');
const btn = document.getElementById('btnToggleLens');
if (!lens) return;
const willOpen = lens.hidden;
lens.hidden = !willOpen;
if (btn) btn.classList.toggle('on', willOpen);
if (willOpen) {
this.toast('Liquid Glass Precision Lens active — drag to magnify & bend content!');
}
},
initPrecisionLens() {
const lens = document.getElementById('kubePrecisionLens');
const closeBtn = document.getElementById('btnCloseLens');
const toggleBtn = document.getElementById('btnToggleLens');
if (!lens) return;
if (closeBtn) {
closeBtn.onclick = (e) => {
e.stopPropagation();
lens.hidden = true;
if (toggleBtn) toggleBtn.classList.remove('on');
};
}
let isDragging = false;
let startX = 0, startY = 0;
let initialLeft = 360, initialTop = 180;
lens.addEventListener('pointerdown', (e) => {
if (e.target.closest('.kube-lens-close')) return;
isDragging = true;
lens.setPointerCapture(e.pointerId);
startX = e.clientX;
startY = e.clientY;
const rect = lens.getBoundingClientRect();
initialLeft = rect.left;
initialTop = rect.top;
lens.style.transition = 'none';
});
lens.addEventListener('pointermove', (e) => {
if (!isDragging) return;
const dx = e.clientX - startX;
const dy = e.clientY - startY;
const maxW = Math.max(window.innerWidth - 230, 0);
const maxH = Math.max(window.innerHeight - 160, 0);
const newLeft = Math.max(0, Math.min(maxW, initialLeft + dx));
const newTop = Math.max(0, Math.min(maxH, initialTop + dy));
lens.style.left = `${newLeft}px`;
lens.style.top = `${newTop}px`;
});
const stopDrag = (e) => {
if (!isDragging) return;
isDragging = false;
try { lens.releasePointerCapture(e.pointerId); } catch(_) {}
lens.style.transition = 'transform 0.15s ease-out, box-shadow 0.2s ease';
};
lens.addEventListener('pointerup', stopDrag);
lens.addEventListener('pointercancel', stopDrag);
}
};
document.addEventListener('DOMContentLoaded', () => App.init());