73 lines
2.3 KiB
JavaScript
73 lines
2.3 KiB
JavaScript
const SessionManager = {
|
||
sessions: [],
|
||
currentSessionId: null,
|
||
|
||
async loadSessions() {
|
||
try {
|
||
const res = await api.get('/sessions');
|
||
this.sessions = res.data || [];
|
||
this.renderSessionList();
|
||
} catch (err) {
|
||
console.error('加载会话失败:', err);
|
||
}
|
||
},
|
||
|
||
renderSessionList() {
|
||
const list = document.getElementById('sessionList');
|
||
if (!list) return;
|
||
|
||
list.innerHTML = this.sessions.map(s => `
|
||
<div class="session-item ${s.id === this.currentSessionId ? 'active' : ''}"
|
||
onclick="SessionManager.switchSession(${s.id})">
|
||
<span class="session-name">${this.escapeHtml(s.name)}</span>
|
||
<button class="session-delete" onclick="event.stopPropagation(); SessionManager.deleteSession(${s.id})" title="删除">×</button>
|
||
</div>
|
||
`).join('');
|
||
},
|
||
|
||
async createSession() {
|
||
try {
|
||
const res = await api.post('/sessions', {});
|
||
this.sessions.unshift(res.data);
|
||
this.currentSessionId = res.data.id;
|
||
this.renderSessionList();
|
||
ChatManager.clearMessages();
|
||
return res.data;
|
||
} catch (err) {
|
||
console.error('创建会话失败:', err);
|
||
}
|
||
},
|
||
|
||
async switchSession(id) {
|
||
this.currentSessionId = id;
|
||
this.renderSessionList();
|
||
await ChatManager.loadMessages(id);
|
||
},
|
||
|
||
async deleteSession(id) {
|
||
if (!confirm('确定要删除这个会话吗?')) return;
|
||
try {
|
||
await api.delete('/sessions/' + id);
|
||
this.sessions = this.sessions.filter(s => s.id !== id);
|
||
Storage.clearCachedMessages(id);
|
||
|
||
if (this.currentSessionId === id) {
|
||
this.currentSessionId = null;
|
||
ChatManager.clearMessages();
|
||
if (this.sessions.length > 0) {
|
||
await this.switchSession(this.sessions[0].id);
|
||
}
|
||
}
|
||
this.renderSessionList();
|
||
} catch (err) {
|
||
alert('删除会话失败: ' + err.message);
|
||
}
|
||
},
|
||
|
||
escapeHtml(text) {
|
||
const div = document.createElement('div');
|
||
div.textContent = text;
|
||
return div.innerHTML;
|
||
}
|
||
};
|