forked from lich0821/ccNexus
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathendpoints.js
More file actions
339 lines (297 loc) · 14.6 KB
/
endpoints.js
File metadata and controls
339 lines (297 loc) · 14.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
import { t } from '../i18n/index.js';
import { formatTokens, maskApiKey } from '../utils/format.js';
import { getEndpointStats } from './stats.js';
import { toggleEndpoint } from './config.js';
let currentTestButton = null;
let currentTestButtonOriginalText = '';
let currentTestIndex = -1;
let endpointPanelExpanded = true;
let currentTransformerFilter = 'claude';
function copyToClipboard(text, button) {
navigator.clipboard.writeText(text).then(() => {
const originalHTML = button.innerHTML;
button.innerHTML = '<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" width="1em" height="1em"><path d="M20 6L9 17l-5-5" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';
setTimeout(() => { button.innerHTML = originalHTML; }, 1000);
});
}
export function getTestState() {
return { currentTestButton, currentTestIndex };
}
export function clearTestState() {
if (currentTestButton) {
currentTestButton.disabled = false;
currentTestButton.innerHTML = currentTestButtonOriginalText;
currentTestButton = null;
currentTestButtonOriginalText = '';
currentTestIndex = -1;
}
}
export function setTestState(button, index) {
currentTestButton = button;
currentTestButtonOriginalText = button.innerHTML;
currentTestIndex = index;
}
export async function renderEndpoints(endpoints) {
const container = document.getElementById('endpointList');
const filterTabs = document.getElementById('endpointFilterTabs');
if (filterTabs) {
filterTabs.querySelectorAll('.endpoint-filter-btn').forEach((btn) => {
const isActive = btn.dataset.transformer === currentTransformerFilter;
btn.classList.toggle('active', isActive);
btn.classList.toggle('btn-primary', isActive);
btn.classList.toggle('btn-secondary', !isActive);
});
}
// Get current endpoint
let currentEndpointName = '';
try {
currentEndpointName = await window.go.main.App.GetCurrentEndpoint();
} catch (error) {
console.error('Failed to get current endpoint:', error);
}
if (endpoints.length === 0) {
container.innerHTML = `
<div class="empty-state">
<p>${t('endpoints.noEndpoints')}</p>
</div>
`;
return;
}
container.innerHTML = '';
const endpointStats = getEndpointStats();
// Display endpoints in config file order (no sorting by enabled status)
const sortedEndpoints = endpoints
.map((ep, index) => {
const stats = endpointStats[ep.name] || { requests: 0, errors: 0, inputTokens: 0, outputTokens: 0 };
const enabled = ep.enabled !== undefined ? ep.enabled : true;
return { endpoint: ep, originalIndex: index, stats, enabled };
})
.filter(({ endpoint: ep }) => {
const transformer = ep.transformer || 'claude';
return transformer === currentTransformerFilter;
});
sortedEndpoints.forEach(({ endpoint: ep, originalIndex: index, stats }) => {
const totalTokens = stats.inputTokens + stats.outputTokens;
const enabled = ep.enabled !== undefined ? ep.enabled : true;
const transformer = ep.transformer || 'claude';
const model = ep.model || '';
const isCurrentEndpoint = ep.name === currentEndpointName;
const item = document.createElement('div');
item.className = 'endpoint-item';
item.draggable = true;
item.dataset.name = ep.name;
item.dataset.index = index;
item.innerHTML = `
<div class="endpoint-info">
<h3>
${ep.name}
${enabled ? '✅' : '❌'}
${isCurrentEndpoint ? '<span class="current-badge">' + t('endpoints.current') + '</span>' : ''}
${enabled && !isCurrentEndpoint ? '<button class="btn btn-switch" data-action="switch" data-name="' + ep.name + '">' + t('endpoints.switchTo') + '</button>' : ''}
</h3>
<p style="display: flex; align-items: center; gap: 8px; min-width: 0;"><span style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">🌐 ${ep.apiUrl}</span> <button class="copy-btn" data-copy="${ep.apiUrl}" aria-label="${t('endpoints.copy')}" title="${t('endpoints.copy')}"><svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" width="1em" height="1em"><path d="M7 4c0-1.1.9-2 2-2h11a2 2 0 0 1 2 2v11a2 2 0 0 1-2 2h-1V8c0-2-1-3-3-3H7V4Z" fill="currentColor"></path><path d="M5 7a2 2 0 0 0-2 2v10c0 1.1.9 2 2 2h10a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2H5Z" fill="currentColor"></path></svg></button></p>
<p style="display: flex; align-items: center; gap: 8px; min-width: 0;"><span style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">🔑 ${maskApiKey(ep.apiKey)}</span> <button class="copy-btn" data-copy="${ep.apiKey}" aria-label="${t('endpoints.copy')}" title="${t('endpoints.copy')}"><svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" width="1em" height="1em"><path d="M7 4c0-1.1.9-2 2-2h11a2 2 0 0 1 2 2v11a2 2 0 0 1-2 2h-1V8c0-2-1-3-3-3H7V4Z" fill="currentColor"></path><path d="M5 7a2 2 0 0 0-2 2v10c0 1.1.9 2 2 2h10a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2H5Z" fill="currentColor"></path></svg></button></p>
<p style="color: #666; font-size: 14px; margin-top: 5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">🔄 ${t('endpoints.transformer')}: ${transformer}${model ? ` (${model})` : ''}</p>
<p style="color: #666; font-size: 14px; margin-top: 3px;">📊 ${t('endpoints.requests')}: ${stats.requests} | ${t('endpoints.errors')}: ${stats.errors}</p>
<p style="color: #666; font-size: 14px; margin-top: 3px;">🎯 ${t('endpoints.tokens')}: ${formatTokens(totalTokens)} (${t('statistics.in')}: ${formatTokens(stats.inputTokens)}, ${t('statistics.out')}: ${formatTokens(stats.outputTokens)})</p>
${ep.remark ? `<p style="color: #888; font-size: 13px; margin-top: 5px; font-style: italic;" title="${ep.remark}">💬 ${ep.remark.length > 20 ? ep.remark.substring(0, 20) + '...' : ep.remark}</p>` : ''}
</div>
<div class="endpoint-actions">
<label class="toggle-switch">
<input type="checkbox" data-index="${index}" ${enabled ? 'checked' : ''}>
<span class="toggle-slider"></span>
</label>
<button class="btn-card btn-secondary" data-action="test" data-index="${index}">${t('endpoints.test')}</button>
<button class="btn-card btn-secondary" data-action="edit" data-index="${index}">${t('endpoints.edit')}</button>
<button class="btn-card btn-danger" data-action="delete" data-index="${index}">${t('endpoints.delete')}</button>
</div>
`;
const testBtn = item.querySelector('[data-action="test"]');
const editBtn = item.querySelector('[data-action="edit"]');
const deleteBtn = item.querySelector('[data-action="delete"]');
const toggleSwitch = item.querySelector('input[type="checkbox"]');
const copyBtns = item.querySelectorAll('.copy-btn');
if (currentTestIndex === index) {
testBtn.disabled = true;
testBtn.innerHTML = '⏳';
currentTestButton = testBtn;
}
testBtn.addEventListener('click', () => {
const idx = parseInt(testBtn.getAttribute('data-index'));
window.testEndpoint(idx, testBtn);
});
editBtn.addEventListener('click', () => {
const idx = parseInt(editBtn.getAttribute('data-index'));
window.editEndpoint(idx);
});
deleteBtn.addEventListener('click', () => {
const idx = parseInt(deleteBtn.getAttribute('data-index'));
window.deleteEndpoint(idx);
});
toggleSwitch.addEventListener('change', async (e) => {
const idx = parseInt(e.target.getAttribute('data-index'));
const newEnabled = e.target.checked;
try {
await toggleEndpoint(idx, newEnabled);
window.loadConfig();
} catch (error) {
console.error('Failed to toggle endpoint:', error);
alert('Failed to toggle endpoint: ' + error);
e.target.checked = !newEnabled;
}
});
copyBtns.forEach(btn => {
btn.addEventListener('click', () => {
copyToClipboard(btn.getAttribute('data-copy'), btn);
});
});
// Add switch button event listener
const switchBtn = item.querySelector('[data-action="switch"]');
if (switchBtn) {
switchBtn.addEventListener('click', async () => {
const name = switchBtn.getAttribute('data-name');
try {
switchBtn.disabled = true;
switchBtn.innerHTML = '⏳';
await window.go.main.App.SwitchToEndpoint(name);
window.loadConfig(); // Refresh display
} catch (error) {
console.error('Failed to switch endpoint:', error);
alert(t('endpoints.switchFailed') + ': ' + error);
} finally {
if (switchBtn) {
switchBtn.disabled = false;
switchBtn.innerHTML = t('endpoints.switchTo');
}
}
});
}
// Add drag and drop event listeners
setupDragAndDrop(item, container);
container.appendChild(item);
});
}
export function toggleEndpointPanel() {
const panel = document.getElementById('endpointPanel');
const icon = document.getElementById('endpointToggleIcon');
const text = document.getElementById('endpointToggleText');
endpointPanelExpanded = !endpointPanelExpanded;
if (endpointPanelExpanded) {
panel.style.display = 'block';
icon.textContent = '🔼';
text.textContent = t('endpoints.collapse');
} else {
panel.style.display = 'none';
icon.textContent = '🔽';
text.textContent = t('endpoints.expand');
}
}
export function setTransformerFilter(transformer) {
currentTransformerFilter = transformer || 'claude';
window.loadConfig(); // re-render with new filter
}
// Drag and drop state
let draggedElement = null;
let draggedOverElement = null;
let draggedOriginalName = null;
let autoScrollInterval = null;
// Auto scroll when dragging near edges
function autoScroll(e) {
const scrollContainer = document.querySelector('.container');
const scrollThreshold = 80;
const scrollSpeed = 10;
const rect = scrollContainer.getBoundingClientRect();
const distanceFromTop = e.clientY - rect.top;
const distanceFromBottom = rect.bottom - e.clientY;
if (distanceFromTop < scrollThreshold) {
scrollContainer.scrollTop -= scrollSpeed;
} else if (distanceFromBottom < scrollThreshold) {
scrollContainer.scrollTop += scrollSpeed;
}
}
// Setup drag and drop for an endpoint item
function setupDragAndDrop(item, container) {
item.addEventListener('dragstart', (e) => {
draggedElement = item;
draggedOriginalName = item.dataset.name;
item.classList.add('dragging');
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text/html', item.innerHTML);
// Start auto-scroll interval
autoScrollInterval = setInterval(() => {
if (window.lastDragEvent) {
autoScroll(window.lastDragEvent);
}
}, 50);
});
item.addEventListener('dragend', (e) => {
item.classList.remove('dragging');
const allItems = container.querySelectorAll('.endpoint-item');
allItems.forEach(i => i.classList.remove('drag-over'));
draggedElement = null;
draggedOverElement = null;
draggedOriginalName = null;
// Clear auto-scroll
if (autoScrollInterval) {
clearInterval(autoScrollInterval);
autoScrollInterval = null;
}
window.lastDragEvent = null;
});
item.addEventListener('dragover', (e) => {
e.preventDefault();
e.dataTransfer.dropEffect = 'move';
window.lastDragEvent = e; // Store for auto-scroll
if (draggedElement && draggedElement !== item) {
if (draggedOverElement && draggedOverElement !== item) {
draggedOverElement.classList.remove('drag-over');
}
item.classList.add('drag-over');
draggedOverElement = item;
}
});
item.addEventListener('dragleave', (e) => {
// Only remove if we're actually leaving the element
if (!item.contains(e.relatedTarget)) {
item.classList.remove('drag-over');
if (draggedOverElement === item) {
draggedOverElement = null;
}
}
});
item.addEventListener('drop', async (e) => {
e.preventDefault();
e.stopPropagation();
if (draggedElement && draggedElement !== item) {
// Use dataset.name to identify positions, not DOM order
const draggedName = draggedElement.dataset.name;
const targetName = item.dataset.name;
// Get all items and build current order by name
const allItems = Array.from(container.querySelectorAll('.endpoint-item'));
const currentOrder = allItems.map(el => el.dataset.name);
// Find positions by name (stable, not affected by scrolling)
const fromIndex = currentOrder.indexOf(draggedName);
const toIndex = currentOrder.indexOf(targetName);
// Calculate new order
const newOrder = [...currentOrder];
newOrder.splice(fromIndex, 1);
newOrder.splice(toIndex, 0, draggedName);
// Compare arrays: if order hasn't changed, don't do anything
const orderChanged = !currentOrder.every((name, idx) => name === newOrder[idx]);
if (!orderChanged) {
item.classList.remove('drag-over');
return;
}
// Save to backend
try {
await window.go.main.App.ReorderEndpoints(newOrder);
window.loadConfig();
} catch (error) {
console.error('Failed to reorder endpoints:', error);
alert(t('endpoints.reorderFailed') + ': ' + error);
window.loadConfig();
}
}
item.classList.remove('drag-over');
});
}