File size: 11,368 Bytes
ca51841
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
825c9b3
ca51841
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c43b369
 
ca51841
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
825c9b3
ca51841
 
 
 
 
 
 
825c9b3
ca51841
 
 
825c9b3
ca51841
 
 
 
825c9b3
 
 
 
 
 
 
ca51841
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
825c9b3
ca51841
 
 
 
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
340
341
342
343
344
345
import { renderMarkdown, attachCopyButtons } from '../markdown.js';
import { icon } from '../icons.js';

const MAX_VISIBLE = 50;

function escapeHtml(str) {
  return String(str)
    .replace(/&/g, '&')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;');
}

function getTextContent(message) {
  if (typeof message.content === 'string') return message.content;
  if (Array.isArray(message.content)) {
    const textParts = message.content.filter(p => p.type === 'text').map(p => p.text);
    return textParts.join('\n');
  }
  return '';
}

function getImageParts(message) {
  if (!Array.isArray(message.content)) return [];
  return message.content.filter(p => p.type === 'image_url');
}

function getVideoParts(message) {
  if (!Array.isArray(message.content)) return [];
  return message.content.filter(p => p.type === 'video_url');
}

function formatTime(iso) {
  try {
    return new Date(iso).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  } catch {
    return '';
  }
}

export class Chat {
  constructor() {
    this.el = null;
    this._messages = [];
    this._offset = 0; // how many messages we've hidden
    this._streamingEl = null;
    this._typingEl = null;
    this._errorEl = null;
  }

  render() {
    const el = document.createElement('div');
    el.className = 'flex flex-col h-full';
    el.innerHTML = `
      <div id="chat-messages" class="flex-1 overflow-y-auto py-6" role="log" aria-live="polite" aria-label="Chat messages">
        ${this._welcomeScreen()}
      </div>
    `;
    this.el = el;
    return this.el;
  }

  _welcomeScreen() {
    return `
      <div id="welcome-screen" class="flex h-full items-center justify-center px-6 py-16">
        <div class="w-full max-w-2xl text-center">
          <h2 class="text-3xl font-semibold tracking-tight text-[var(--c-tx)] md:text-4xl">需要我为你做些什么?</h2>
          <p class="mx-auto mt-4 max-w-xl text-sm leading-7 text-[var(--c-tx2)] md:text-[15px]">
            直接开始提问,或先在 Settings 中配置模型与上下文限制。
          </p>
        </div>
      </div>
    `;
  }

  loadConversation(conversation) {
    this._messages = conversation?.messages || [];
    this._streamingEl = null;
    this._typingEl = null;
    this._rerender();
  }

  _rerender() {
    const container = this.el.querySelector('#chat-messages');
    if (!container) return;

    container.innerHTML = '';

    if (this._messages.length === 0) {
      container.innerHTML = this._welcomeScreen();
      return;
    }

    const msgs = this._messages;
    const total = msgs.length;
    this._offset = Math.max(0, total - MAX_VISIBLE);
    const visible = msgs.slice(this._offset);

    if (this._offset > 0) {
      const loadMore = document.createElement('div');
      loadMore.className = 'max-w-4xl mx-auto w-full px-6 flex justify-center py-4';
      loadMore.innerHTML = `<button id="load-older-btn" class="text-[12px] text-[var(--c-tx3)] border border-[var(--c-bd)] rounded-full px-4 py-1.5 hover:text-[var(--c-tx2)] hover:border-[var(--c-bd-hi)] transition-all">Load ${this._offset} older messages</button>`;
      loadMore.querySelector('#load-older-btn').addEventListener('click', () => this._loadOlder(container));
      container.appendChild(loadMore);
    }

    visible.forEach(msg => {
      const el = this._buildMessageEl(msg);
      container.appendChild(el);
    });

    this._scrollToBottom();
  }

  _loadOlder(container) {
    const loadMoreDiv = container.querySelector('#load-older-btn')?.parentElement;
    const msgs = this._messages;
    const newOffset = Math.max(0, this._offset - MAX_VISIBLE);
    const olderMsgs = msgs.slice(newOffset, this._offset);
    this._offset = newOffset;

    const fragment = document.createDocumentFragment();
    if (newOffset > 0) {
      const newLoadMore = document.createElement('div');
      newLoadMore.className = 'max-w-4xl mx-auto w-full px-6 flex justify-center py-4';
      newLoadMore.innerHTML = `<button id="load-older-btn" class="text-[12px] text-[var(--c-tx3)] border border-[var(--c-bd)] rounded-full px-4 py-1.5 hover:text-[var(--c-tx2)] hover:border-[var(--c-bd-hi)] transition-all">Load ${newOffset} older messages</button>`;
      newLoadMore.querySelector('#load-older-btn').addEventListener('click', () => this._loadOlder(container));
      fragment.appendChild(newLoadMore);
    }

    olderMsgs.forEach(msg => {
      fragment.appendChild(this._buildMessageEl(msg));
    });

    if (loadMoreDiv) {
      container.insertBefore(fragment, loadMoreDiv);
      loadMoreDiv.remove();
    } else {
      container.insertBefore(fragment, container.firstChild);
    }
  }

  _buildMessageEl(msg) {
    const isUser = msg.role === 'user';
    const text = getTextContent(msg);
    const images = getImageParts(msg);
    const videos = getVideoParts(msg);
    const time = formatTime(msg.timestamp);

    const wrapper = document.createElement('div');
    wrapper.className = 'message-enter max-w-4xl mx-auto w-full px-6 mb-4';
    wrapper.dataset.msgId = msg.timestamp || Math.random();

    if (isUser) {
      const imageHtml = images.map(img => `
        <img src="${img.image_url?.url || ''}" alt="Attached image" class="max-w-xs max-h-48 rounded-xl border border-[var(--c-bd)] object-cover mb-2" />
      `).join('');

      const videoHtml = videos.map(vid => `
        <video src="${escapeHtml(vid.video_url?.url || '')}" controls muted playsinline
          class="max-w-xs max-h-48 rounded-xl border border-[var(--c-bd)] bg-black mb-2"></video>
      `).join('');

      wrapper.innerHTML = `
        <div class="flex justify-end">
          <div class="max-w-[65%]">
            ${imageHtml}
            ${videoHtml}
            <div class="user-bubble px-4 py-3 text-[13.5px] text-[var(--c-utx)] whitespace-pre-wrap break-words leading-relaxed">${escapeHtml(text)}</div>
            ${time ? `<div class="text-[11px] text-[var(--c-tx3)] mt-1.5 text-right">${time}</div>` : ''}
          </div>
        </div>
      `;
    } else {
      const msgDiv = document.createElement('div');
      msgDiv.className = 'w-full';

      const bubble = document.createElement('div');
      bubble.className = 'text-[13.5px] prose-dark leading-relaxed';
      bubble.innerHTML = renderMarkdown(text);
      attachCopyButtons(bubble);

      msgDiv.appendChild(bubble);

      if (time) {
        const timeEl = document.createElement('div');
        timeEl.className = 'text-[11px] text-[var(--c-tx3)] mt-2';
        timeEl.textContent = time;
        msgDiv.appendChild(timeEl);
      }

      wrapper.appendChild(msgDiv);
    }

    return wrapper;
  }

  appendUserMessage(message) {
    this._messages.push(message);
    const container = this.el.querySelector('#chat-messages');

    // Remove welcome screen if present
    const welcome = container.querySelector('#welcome-screen');
    if (welcome) welcome.remove();

    const el = this._buildMessageEl(message);
    container.appendChild(el);
    this._scrollToBottom();
  }

  showTypingIndicator() {
    const container = this.el.querySelector('#chat-messages');
    this.hideTypingIndicator();

    this._typingEl = document.createElement('div');
    this._typingEl.className = 'max-w-4xl mx-auto w-full px-6 mb-4';
    this._typingEl.innerHTML = `
      <div class="flex justify-start">
        <div class="flex items-center gap-1.5 py-3 px-1">
          <span class="typing-dot"></span>
          <span class="typing-dot"></span>
          <span class="typing-dot"></span>
        </div>
      </div>
    `;
    container.appendChild(this._typingEl);
    this._scrollToBottom();
  }

  hideTypingIndicator() {
    if (this._typingEl) {
      this._typingEl.remove();
      this._typingEl = null;
    }
  }

  startAssistantMessage() {
    this.hideTypingIndicator();
    const container = this.el.querySelector('#chat-messages');

    const wrapper = document.createElement('div');
    wrapper.className = 'message-enter max-w-4xl mx-auto w-full px-6 mb-4';

    const msgDiv = document.createElement('div');
    msgDiv.className = 'w-full';

    const bubble = document.createElement('div');
    bubble.className = 'text-[13.5px] prose-dark leading-relaxed';
    bubble.innerHTML = '<span class="streaming-cursor opacity-60">▋</span>';

    msgDiv.appendChild(bubble);
    wrapper.appendChild(msgDiv);
    container.appendChild(wrapper);
    this._scrollToBottom();
    this._streamingEl = bubble;
    this._streamingText = '';
    return bubble;
  }

  appendToAssistantMessage(chunk) {
    if (!this._streamingEl) return;
    this._streamingText = (this._streamingText || '') + chunk;
    // Re-render markdown during streaming for better UX
    this._streamingEl.innerHTML = renderMarkdown(this._streamingText) + '<span class="streaming-cursor opacity-60 animate-pulse">▋</span>';
    this._scrollToBottom();
  }

  finalizeAssistantMessage(fullText) {
    if (!this._streamingEl) return;
    this._streamingEl.innerHTML = renderMarkdown(fullText);
    attachCopyButtons(this._streamingEl);
    this._streamingEl = null;
    this._streamingText = '';
    this._messages.push({
      role: 'assistant',
      content: fullText,
      timestamp: new Date().toISOString(),
    });
    this._scrollToBottom();
  }

  showError(message) {
    const container = this.el.querySelector('#chat-messages');
    this.hideTypingIndicator();
    if (this._streamingEl) {
      this._streamingEl.innerHTML = `<span class="text-red-600 dark:text-red-400">${escapeHtml(message)}</span>`;
      this._streamingEl = null;
      this._streamingText = '';
      return;
    }
    const errEl = document.createElement('div');
    errEl.className = 'max-w-4xl mx-auto w-full px-6 mb-4 message-enter';
    errEl.innerHTML = `
      <div class="bg-red-50 dark:bg-red-950/40 border border-red-200 dark:border-red-900/40 rounded-xl px-4 py-3 text-[13px] text-red-700 dark:text-red-400 flex items-center gap-2">
        ${icon('x')} ${escapeHtml(message)}
      </div>
    `;
    this._errorEl = errEl;
    container.appendChild(errEl);
    this._scrollToBottom();
  }

  clearError() {
    if (this._errorEl) {
      this._errorEl.remove();
      this._errorEl = null;
    }
  }

  showSystemMessage(text) {
    const container = this.el.querySelector('#chat-messages');
    if (!container) return;
    const welcome = container.querySelector('#welcome-screen');
    if (welcome) welcome.remove();
    const el = document.createElement('div');
    el.className = 'max-w-4xl mx-auto w-full px-6 my-3 message-enter flex justify-center';
    el.innerHTML = `
      <div class="text-[11px] text-[var(--c-tx3)] border border-[var(--c-bd)] rounded-full px-3 py-1 bg-[var(--c-ho)] select-none">
        ${escapeHtml(text)}
      </div>
    `;
    container.appendChild(el);
    this._scrollToBottom();
  }

  _scrollToBottom() {
    const container = this.el.querySelector('#chat-messages');
    if (container) {
      requestAnimationFrame(() => {
        container.scrollTop = container.scrollHeight;
      });
    }
  }

  clear() {
    this._messages = [];
    this._streamingEl = null;
    this._streamingText = '';
    this._typingEl = null;
    this._errorEl = null;
    const container = this.el.querySelector('#chat-messages');
    if (container) container.innerHTML = this._welcomeScreen();
  }
}