241 lines
9.0 KiB
JavaScript
241 lines
9.0 KiB
JavaScript
'use strict';
|
||
window.AssistantAttachments = {
|
||
mount(root, { api, isActive, onChange, onError }) {
|
||
const button = root.querySelector('#assistant-attach'),
|
||
input = root.querySelector('#assistant-files'),
|
||
list = root.querySelector('#assistant-attachment-list'),
|
||
note = root.querySelector('#assistant-attachment-note'),
|
||
textTypes =
|
||
'.txt,.log,.csv,.md,.json,.yaml,.yml,.xml,.ini,.conf,.js,.ts,.cjs,.mjs,.py,.css,.html,.pdf';
|
||
let items = [],
|
||
generation = 0,
|
||
disabled = false,
|
||
disposed = false,
|
||
supportsVision = false;
|
||
const requests = new Set();
|
||
const alive = () => !disposed && isActive();
|
||
function icon(image) {
|
||
return (
|
||
'<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">' +
|
||
(image
|
||
? '<rect x="3" y="3" width="18" height="18" rx="3"/><circle cx="8" cy="8" r="1.5"/><path d="m4 17 5-5 4 4 3-3 5 5"/>'
|
||
: '<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><path d="M14 2v6h6M8 13h8M8 17h6"/>') +
|
||
'</svg>'
|
||
);
|
||
}
|
||
function preview(file) {
|
||
const dialog = document.createElement('dialog');
|
||
dialog.className = 'aw-settings-review aw-attachment-preview';
|
||
dialog.setAttribute('aria-label', '预览附件 ' + file.name);
|
||
dialog.innerHTML =
|
||
'<header><h2></h2></header><div class="aw-review-body"><p></p></div><footer><button type="button" class="btn">关闭</button></footer>';
|
||
dialog.querySelector('h2').textContent = file.name;
|
||
const body = dialog.querySelector('.aw-review-body');
|
||
if (file.kind === 'image') {
|
||
dialog.querySelector('p').textContent =
|
||
'图片 ' + file.width + '×' + file.height + ',点击发送才以图像内容交给当前视觉模型。';
|
||
const image = document.createElement('img');
|
||
image.src = file.previewImage;
|
||
image.alt = file.name;
|
||
image.className = 'aw-image-preview';
|
||
body.append(image);
|
||
} else {
|
||
dialog.querySelector('p').textContent =
|
||
'本机解析预览(最多前 2000 字),正文共 ' +
|
||
file.characters +
|
||
' 字。发送时才交给当前模型。';
|
||
const pre = document.createElement('pre');
|
||
pre.textContent = file.preview;
|
||
body.append(pre);
|
||
}
|
||
dialog.querySelector('button').onclick = () => dialog.close();
|
||
dialog.onclose = () => dialog.remove();
|
||
root.append(dialog);
|
||
dialog.showModal();
|
||
}
|
||
function draw() {
|
||
list.replaceChildren();
|
||
for (const item of items) {
|
||
const row = document.createElement('div');
|
||
row.className = 'aw-attachment';
|
||
const symbol = document.createElement('span');
|
||
symbol.className = 'aw-attachment-icon';
|
||
symbol.innerHTML = icon(item.kind === 'image');
|
||
row.append(symbol);
|
||
const info = document.createElement('div'),
|
||
name = document.createElement('strong'),
|
||
status = document.createElement('span');
|
||
name.textContent = item.name;
|
||
status.textContent = item.loading
|
||
? '正在本机处理…'
|
||
: item.kind === 'image'
|
||
? '图片 · ' +
|
||
item.width +
|
||
'×' +
|
||
item.height +
|
||
' · ' +
|
||
(item.size / 1024).toFixed(1) +
|
||
' KB'
|
||
: '已解析 · ' +
|
||
(item.size / 1024).toFixed(1) +
|
||
' KB · ' +
|
||
item.characters +
|
||
' 字' +
|
||
(item.kind === 'pdf' ? ' · PDF 文字' : '');
|
||
info.append(name, status);
|
||
row.append(info);
|
||
if (!item.loading) {
|
||
const view = document.createElement('button');
|
||
view.type = 'button';
|
||
view.className = 'btn btn-sm';
|
||
view.textContent = '预览';
|
||
view.setAttribute('aria-label', '预览附件 ' + item.name);
|
||
view.onclick = () => preview(item);
|
||
row.append(view);
|
||
}
|
||
const remove = document.createElement('button');
|
||
remove.type = 'button';
|
||
remove.className = 'btn btn-sm aw-remove-attachment';
|
||
remove.innerHTML =
|
||
'<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="m6 6 12 12M6 18 18 6"/></svg>';
|
||
remove.disabled = disabled;
|
||
remove.setAttribute('aria-label', '移除附件 ' + item.name);
|
||
remove.onclick = async () => {
|
||
remove.disabled = true;
|
||
try {
|
||
if (item.id) await api('/assistant/attachments/' + item.id + '/remove', {});
|
||
if (!alive()) return;
|
||
items = items.filter((f) => f !== item);
|
||
draw();
|
||
} catch (error) {
|
||
if (alive()) {
|
||
if (error.status === 404) {
|
||
items = items.filter((f) => f !== item);
|
||
draw();
|
||
} else {
|
||
remove.disabled = false;
|
||
onError(error);
|
||
}
|
||
}
|
||
}
|
||
};
|
||
row.append(remove);
|
||
list.append(row);
|
||
}
|
||
note.hidden = !items.length;
|
||
note.textContent = items.some((f) => f.kind === 'image')
|
||
? '图片将以图像内容发送给所选视觉模型,不会当作文本;文件内容不授予操作权限。'
|
||
: '文件在本机解析,点击发送才交给模型。最多 3 个、每个 2 MB、文字合计 40000 字;PDF 提取文字,扫描图片需先 OCR。';
|
||
button.disabled = disabled || items.length >= 3;
|
||
input.disabled = button.disabled;
|
||
input.accept = textTypes + (supportsVision ? ',.png,.jpg,.jpeg' : '');
|
||
button.title = supportsVision
|
||
? '添加文件或图片(PNG、JPEG)'
|
||
: '添加文本或 PDF;图片请选择视觉模型';
|
||
onChange();
|
||
}
|
||
const encode = (file) =>
|
||
new Promise((resolve, reject) => {
|
||
const reader = new FileReader();
|
||
reader.onload = () => resolve(String(reader.result).split(',')[1]);
|
||
reader.onerror = () => reject(Error('读取附件失败。'));
|
||
reader.readAsDataURL(file);
|
||
});
|
||
input.onchange = async () => {
|
||
const selected = [...input.files],
|
||
at = generation;
|
||
input.value = '';
|
||
for (const file of selected) {
|
||
if (!alive() || at !== generation) return;
|
||
if (items.length >= 3) {
|
||
onError(Error('每条消息最多添加 3 个附件。'));
|
||
break;
|
||
}
|
||
if (/\.(?:png|jpe?g)$/i.test(file.name) && !supportsVision) {
|
||
onError(Error('当前模型不支持图片,请先选择视觉模型。'));
|
||
continue;
|
||
}
|
||
if (!file.size || file.size > 2 * 1024 * 1024) {
|
||
onError(Error('附件为空或超过 2 MB。'));
|
||
continue;
|
||
}
|
||
const item = { name: file.name, loading: true },
|
||
controller = new AbortController();
|
||
requests.add(controller);
|
||
items.push(item);
|
||
draw();
|
||
try {
|
||
const data = await encode(file);
|
||
if (!alive() || at !== generation) return;
|
||
const result = await api(
|
||
'/assistant/attachments',
|
||
{ name: file.name, data },
|
||
{ signal: controller.signal },
|
||
);
|
||
if (!alive() || at !== generation || !items.includes(item)) {
|
||
void api('/assistant/attachments/' + result.id + '/remove', {}).catch(() => {});
|
||
continue;
|
||
}
|
||
Object.assign(item, result, { loading: false });
|
||
draw();
|
||
} catch (error) {
|
||
if (alive() && at === generation) {
|
||
items = items.filter((f) => f !== item);
|
||
draw();
|
||
if (error.name !== 'AbortError') onError(error);
|
||
}
|
||
} finally {
|
||
requests.delete(controller);
|
||
}
|
||
}
|
||
};
|
||
button.onclick = () => input.click();
|
||
return {
|
||
get pending() {
|
||
return items.some((f) => f.loading);
|
||
},
|
||
get ready() {
|
||
return items.filter((f) => !f.loading);
|
||
},
|
||
get incompatible() {
|
||
return !supportsVision && items.some((f) => f.kind === 'image');
|
||
},
|
||
setVisionSupport(value) {
|
||
if (supportsVision === value) return;
|
||
supportsVision = value;
|
||
draw();
|
||
},
|
||
snapshot() {
|
||
return items.filter((f) => !f.loading).map((f) => ({ ...f }));
|
||
},
|
||
restore(saved = []) {
|
||
generation++;
|
||
for (const r of requests) r.abort();
|
||
requests.clear();
|
||
items = saved.map((f) => ({ ...f, loading: false }));
|
||
draw();
|
||
},
|
||
clear() {
|
||
generation++;
|
||
items = [];
|
||
draw();
|
||
},
|
||
setDisabled(value) {
|
||
if (disabled === value) return;
|
||
disabled = value;
|
||
draw();
|
||
},
|
||
dispose() {
|
||
disposed = true;
|
||
generation++;
|
||
for (const r of requests) r.abort();
|
||
requests.clear();
|
||
items = [];
|
||
input.onchange = null;
|
||
button.onclick = null;
|
||
list.replaceChildren();
|
||
},
|
||
};
|
||
},
|
||
};
|