tavern-harness 0.1.33 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +99 -0
- package/package.json +1 -1
- package/persistence-server.mjs +60 -1
- package/sandbox-server.mjs +11 -8
- package/src/App.tsx +1 -1
- package/src/components/CharactersView.tsx +1 -1
- package/src/components/ChatView.tsx +5 -3
- package/src/components/FileDisplayModal.tsx +105 -2
- package/src/components/SettingsView.tsx +194 -22
- package/src/components/Sidebar.tsx +26 -27
- package/src/components/WorkspaceFileManagerModal.tsx +2 -2
- package/src/components/shared.tsx +28 -9
- package/src/core/autoHideScrollbars.ts +191 -0
- package/src/core/browserPreferences.ts +6 -1
- package/src/core/i18n.ts +66 -3
- package/src/core/imageFilename.ts +21 -0
- package/src/core/imageGeneration.ts +32 -0
- package/src/core/prompts.ts +6 -1
- package/src/core/toolDefinitions.ts +21 -0
- package/src/core/tools/generatedSkillExecutor.ts +31 -2
- package/src/core/tools/toolExecutor.ts +104 -8
- package/src/db/database.ts +53 -12
- package/src/generated/changelog.json +140 -1
- package/src/main.tsx +3 -0
- package/src/store/store.ts +32 -17
- package/src/theme/chat.css +114 -54
- package/src/theme/global.css +122 -57
- package/src/theme/theme.ts +96 -43
- package/src/theme/views.css +110 -33
- package/src/types/models.ts +16 -1
- package/vite.config.ts +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -3,6 +3,103 @@
|
|
|
3
3
|
> 本文件由 `scripts/changelog.mjs` 从 `changelog/v*.md` 生成,请勿手动编辑。
|
|
4
4
|
> 版本对比链接见文末;源文件位于仓库 `changelog/` 目录。
|
|
5
5
|
|
|
6
|
+
## [0.2.1] - 2026-11-21
|
|
7
|
+
|
|
8
|
+
### 中文
|
|
9
|
+
|
|
10
|
+
#### 新增
|
|
11
|
+
|
|
12
|
+
- 新增内置「生成图片」技能:在设置中添加「百炼 Token Plan」生图供应商并选定默认模型(qwen-image-3.0-pro / qwen-image-2.0-pro / qwen-image-2.0 / wan2.7-image / wan2.7-image-pro)后,角色即可按提示词生成图片,图片保存到工作区 `images/` 目录并自动打开预览
|
|
13
|
+
- 角色创建与更新技能支持 `avatar_path`:酒馆助手可以从工作区的 PNG / JPEG / WebP / BMP / AVIF 图片生成或清空角色头像,保存前会校验图片真实格式并压缩到存储上限
|
|
14
|
+
- 对话中的图片附件改为缩略图卡片,点击即可放大查看
|
|
15
|
+
|
|
16
|
+
#### 改进
|
|
17
|
+
|
|
18
|
+
- 生成的图片文件名改为根据提示词或指定文件名生成的可读名称,并自动追加时间戳与正确的扩展名,不再是一串 `generated-数字`
|
|
19
|
+
|
|
20
|
+
#### 修复
|
|
21
|
+
|
|
22
|
+
- 修复图片预览弹窗缩放后无法平移、大图看不全的问题;图片现在按窗口自适应缩放,超出窗口时可在横向与纵向滚动,并保持居中
|
|
23
|
+
- 修复输入框内边距在不同屏幕宽度下不一致的问题
|
|
24
|
+
|
|
25
|
+
#### 内部
|
|
26
|
+
|
|
27
|
+
- 新增 `imageGeneration`、`imageFilename` 模块,并为生成图片文件名补充测试
|
|
28
|
+
- 持久化服务新增 `/image/generate` 端点,代理百炼 Token Plan 生图请求并下载结果;数据库升级至 v14,新增 `imageProviders` 表
|
|
29
|
+
- 沙箱服务新增二进制文件写入端点(上限 8MB),图片预览与 base64 写入端点纳入同源代理
|
|
30
|
+
|
|
31
|
+
### English
|
|
32
|
+
|
|
33
|
+
#### Added
|
|
34
|
+
|
|
35
|
+
- Built-in Generate Image skill: after adding a Bailian Token Plan image provider in Settings and choosing a default model (qwen-image-3.0-pro, qwen-image-2.0-pro, qwen-image-2.0, wan2.7-image, wan2.7-image-pro), characters can generate images from prompts; images are saved to the workspace `images/` folder and opened in a preview automatically
|
|
36
|
+
- Character create/update skills accept `avatar_path`: the Tavern Keeper can set or clear a character avatar from a PNG, JPEG, WebP, BMP, or AVIF file in the workspace, with real format validation and compression before saving
|
|
37
|
+
- Image attachments in conversations are now thumbnail cards that open a larger preview on click
|
|
38
|
+
|
|
39
|
+
#### Changed
|
|
40
|
+
|
|
41
|
+
- Generated images now get readable file names derived from the prompt or a requested filename, with a timestamp and the correct extension, instead of `generated-<number>`
|
|
42
|
+
|
|
43
|
+
#### Fixed
|
|
44
|
+
|
|
45
|
+
- Fixed the image preview being impossible to pan after zooming; images now fit the window, scroll horizontally and vertically when larger, and stay centered
|
|
46
|
+
- Fixed inconsistent composer padding across screen widths
|
|
47
|
+
|
|
48
|
+
#### Internal
|
|
49
|
+
|
|
50
|
+
- Added the `imageGeneration` and `imageFilename` modules, with tests for generated image filenames
|
|
51
|
+
- The persistence service gained an `/image/generate` endpoint that proxies Bailian Token Plan requests and downloads the result; the database moved to v14 with a new `imageProviders` table
|
|
52
|
+
- The sandbox service gained a binary file-write endpoint (8MB limit), and the preview/base64 write endpoints are covered by the same-origin proxy
|
|
53
|
+
|
|
54
|
+
## [0.2.0] - 2026-11-20
|
|
55
|
+
|
|
56
|
+
### 中文
|
|
57
|
+
|
|
58
|
+
#### 新增
|
|
59
|
+
|
|
60
|
+
- 设置页拆分为「API 配置 / 模型参数 / 通用设置」三个标签页,服务商、超参数和主题不再挤在同一个长页面里
|
|
61
|
+
- 新增「烛光琥珀 / 森野翡翠 / 暮色蔷薇 / 星夜靛蓝」四套配色方案,可在设置中随时切换,浅色与深色模式分别适配
|
|
62
|
+
- 对话标题栏和输入框改为悬浮玻璃卡片:内容从卡片背后滚动,输入框固定在底部;群聊时两者都会避开右侧成员栏
|
|
63
|
+
|
|
64
|
+
#### 改进
|
|
65
|
+
|
|
66
|
+
- 侧边栏与主区域改为各自独立的悬浮卡片,去掉渐变光晕、虚线纹理和多余投影,层级更干净
|
|
67
|
+
- 工具调用与思考卡片改用无边框色块表达状态,减少卡片套卡片的感觉
|
|
68
|
+
- 原生滚动条替换为滚动时出现、静止后淡出的悬浮细条,不再占用内容宽度
|
|
69
|
+
- Markdown 的标题、列表标记、代码块和表格跟随所选配色,并随浅色/深色模式自动调整
|
|
70
|
+
- 侧边栏宽度拖拽手柄更易识别,并支持触屏拖动
|
|
71
|
+
|
|
72
|
+
#### 修复
|
|
73
|
+
|
|
74
|
+
- 修复电脑休眠唤醒后持久化服务尚未就绪时,启动快照只重试一次就放弃、页面可能读不到数据的问题;启动阶段现在最多重试四次
|
|
75
|
+
- 修复设置页服务商名称过长时溢出卡片、挤压「文本服务 / 语音服务」标签的问题,名称过长时改为自动滚动显示
|
|
76
|
+
|
|
77
|
+
### English
|
|
78
|
+
|
|
79
|
+
#### Added
|
|
80
|
+
|
|
81
|
+
- Settings is split into API Configuration, Model Parameters, and General tabs, so providers, hyperparameters, and theme no longer share one long page
|
|
82
|
+
- Four color palettes — Candle Amber, Forest Jade, Twilight Rose, and Starlight Indigo — switchable at any time, each tuned for light and dark modes
|
|
83
|
+
- The conversation header and composer are now floating glass cards: content scrolls behind them, the composer stays pinned to the bottom, and both make room for the member panel in group chats
|
|
84
|
+
|
|
85
|
+
#### Changed
|
|
86
|
+
|
|
87
|
+
- The sidebar and main area are now separate floating cards; gradient glows, dashed textures, and excess shadows are gone for a cleaner hierarchy
|
|
88
|
+
- Tool call and reasoning cards use borderless color blocks to show state instead of nested outlines
|
|
89
|
+
- Native scrollbars are replaced by floating thin thumbs that appear while scrolling and fade when idle, without taking content width
|
|
90
|
+
- Markdown headings, list markers, code blocks, and tables follow the selected palette and adapt to light and dark modes
|
|
91
|
+
- The sidebar resize handle is easier to spot and now supports touch dragging
|
|
92
|
+
|
|
93
|
+
#### Fixed
|
|
94
|
+
|
|
95
|
+
- Fixed the startup snapshot giving up after one retry when the persistence service was still starting after sleep; startup now retries up to four times
|
|
96
|
+
- Fixed long provider names overflowing their cards and squeezing the text/voice service label; overflowing names now scroll automatically
|
|
97
|
+
|
|
98
|
+
#### Internal
|
|
99
|
+
|
|
100
|
+
- Added a global auto-hiding scrollbar module shared by all scroll containers
|
|
101
|
+
- Added test coverage for persistence startup retries
|
|
102
|
+
|
|
6
103
|
## [0.1.33] - 2026-11-18
|
|
7
104
|
|
|
8
105
|
### 中文
|
|
@@ -982,6 +1079,8 @@
|
|
|
982
1079
|
- Vite + React + Zustand + Dexie stack with browser-side local persistence
|
|
983
1080
|
|
|
984
1081
|
<!-- 链接定义 -->
|
|
1082
|
+
[0.2.1]: https://github.com/Rannichan/Tavern-Harness/compare/v0.2.0...v0.2.1
|
|
1083
|
+
[0.2.0]: https://github.com/Rannichan/Tavern-Harness/compare/v0.1.33...v0.2.0
|
|
985
1084
|
[0.1.33]: https://github.com/Rannichan/Tavern-Harness/compare/v0.1.32...v0.1.33
|
|
986
1085
|
[0.1.32]: https://github.com/Rannichan/Tavern-Harness/compare/v0.1.31...v0.1.32
|
|
987
1086
|
[0.1.31]: https://github.com/Rannichan/Tavern-Harness/compare/v0.1.30...v0.1.31
|
package/package.json
CHANGED
package/persistence-server.mjs
CHANGED
|
@@ -195,7 +195,7 @@ const listRecordsByJsonField = database.prepare(`
|
|
|
195
195
|
const listStartupRecords = database.prepare(`
|
|
196
196
|
SELECT collection, record_key, value_json, updated_at
|
|
197
197
|
FROM app_records
|
|
198
|
-
WHERE collection IN ('settings', 'providers', 'voiceProviders', 'npcs', 'sessions', 'worldBooks', 'tools', 'achievementUnlocks')
|
|
198
|
+
WHERE collection IN ('settings', 'providers', 'voiceProviders', 'imageProviders', 'npcs', 'sessions', 'worldBooks', 'tools', 'achievementUnlocks')
|
|
199
199
|
ORDER BY collection, record_key
|
|
200
200
|
`);
|
|
201
201
|
const deleteRecord = database.prepare('DELETE FROM app_records WHERE collection = ? AND record_key = ?');
|
|
@@ -290,6 +290,7 @@ const server = createServer(async (req, res) => {
|
|
|
290
290
|
settings: [],
|
|
291
291
|
providers: [],
|
|
292
292
|
voiceProviders: [],
|
|
293
|
+
imageProviders: [],
|
|
293
294
|
npcs: [],
|
|
294
295
|
sessions: [],
|
|
295
296
|
worldBooks: [],
|
|
@@ -306,6 +307,64 @@ const server = createServer(async (req, res) => {
|
|
|
306
307
|
json(res, 200, { ok: true, lock: lockState(clientId), collections });
|
|
307
308
|
return;
|
|
308
309
|
}
|
|
310
|
+
if (pathname === '/image/generate') {
|
|
311
|
+
const providerId = Number(body.providerId);
|
|
312
|
+
const prompt = typeof body.prompt === 'string' ? body.prompt.trim() : '';
|
|
313
|
+
const model = typeof body.model === 'string' ? body.model.trim() : '';
|
|
314
|
+
const size = typeof body.size === 'string' ? body.size.trim() : '1024*1024';
|
|
315
|
+
if (!Number.isInteger(providerId) || providerId <= 0 || !prompt || prompt.length > 10_000 || !model || !/^\d{2,5}\*\d{2,5}$/.test(size)) {
|
|
316
|
+
json(res, 400, { ok: false, message: 'Invalid image generation request' });
|
|
317
|
+
return;
|
|
318
|
+
}
|
|
319
|
+
const record = getRecord.get('imageProviders', String(providerId));
|
|
320
|
+
if (!record) {
|
|
321
|
+
json(res, 404, { ok: false, message: 'Image provider not found' });
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
const provider = JSON.parse(record.value_json);
|
|
325
|
+
const apiKey = typeof provider.apiKey === 'string' ? provider.apiKey.trim() : '';
|
|
326
|
+
if (!provider.isEnabled || provider.kind !== 'bailian-token-plan' || !apiKey) {
|
|
327
|
+
json(res, 400, { ok: false, message: 'Image provider is unavailable' });
|
|
328
|
+
return;
|
|
329
|
+
}
|
|
330
|
+
const upstream = await fetch('https://token-plan.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation', {
|
|
331
|
+
method: 'POST',
|
|
332
|
+
headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json' },
|
|
333
|
+
body: JSON.stringify({
|
|
334
|
+
model,
|
|
335
|
+
input: { messages: [{ role: 'user', content: [{ text: prompt }] }] },
|
|
336
|
+
parameters: { size },
|
|
337
|
+
}),
|
|
338
|
+
signal: AbortSignal.timeout(180_000),
|
|
339
|
+
});
|
|
340
|
+
const payload = await upstream.json().catch(() => null);
|
|
341
|
+
if (!upstream.ok) {
|
|
342
|
+
const upstreamMessage = payload?.message ?? payload?.error?.message ?? payload?.code;
|
|
343
|
+
json(res, upstream.status, { ok: false, message: upstreamMessage ? `Image service error: ${upstreamMessage}` : `Image service returned HTTP ${upstream.status}` });
|
|
344
|
+
return;
|
|
345
|
+
}
|
|
346
|
+
const imageUrl = payload?.output?.choices?.[0]?.message?.content?.[0]?.image;
|
|
347
|
+
if (typeof imageUrl !== 'string' || !/^https?:\/\//i.test(imageUrl)) {
|
|
348
|
+
json(res, 502, { ok: false, message: 'Image service did not return a valid image URL' });
|
|
349
|
+
return;
|
|
350
|
+
}
|
|
351
|
+
const imageResponse = await fetch(imageUrl, { signal: AbortSignal.timeout(120_000) });
|
|
352
|
+
if (!imageResponse.ok) {
|
|
353
|
+
imageResponse.body?.cancel();
|
|
354
|
+
json(res, 502, { ok: false, message: `Unable to download generated image (HTTP ${imageResponse.status})` });
|
|
355
|
+
return;
|
|
356
|
+
}
|
|
357
|
+
const image = Buffer.from(await imageResponse.arrayBuffer());
|
|
358
|
+
const mimeType = imageResponse.headers.get('content-type')?.split(';')[0] || 'image/png';
|
|
359
|
+
json(res, 200, {
|
|
360
|
+
ok: true,
|
|
361
|
+
dataUrl: `data:${mimeType};base64,${image.toString('base64')}`,
|
|
362
|
+
mimeType,
|
|
363
|
+
width: payload?.usage?.width ?? null,
|
|
364
|
+
height: payload?.usage?.height ?? null,
|
|
365
|
+
});
|
|
366
|
+
return;
|
|
367
|
+
}
|
|
309
368
|
if (pathname === '/voice/synthesize' || pathname === '/voice/preview') {
|
|
310
369
|
const voiceId = typeof body.voiceId === 'string' ? body.voiceId : '';
|
|
311
370
|
const text = typeof body.text === 'string' ? body.text.trim() : '';
|
package/sandbox-server.mjs
CHANGED
|
@@ -611,10 +611,10 @@ const server = createServer(async (req, res) => {
|
|
|
611
611
|
}
|
|
612
612
|
|
|
613
613
|
// ---- 真实文件工作区端点(file_read / file_write / file_delete / file_list) ----
|
|
614
|
-
if (req.url === '/file_read' || req.url === '/file_write' || req.url === '/file_delete' || req.url === '/file_list') {
|
|
614
|
+
if (req.url === '/file_read' || req.url === '/file_write' || req.url === '/file_write_base64' || req.url === '/file_delete' || req.url === '/file_list') {
|
|
615
615
|
let body = '';
|
|
616
616
|
for await (const chunk of req) body += chunk;
|
|
617
|
-
if (body.length > 512 * 1024) {
|
|
617
|
+
if (body.length > (req.url === '/file_write_base64' ? 12 * 1024 * 1024 : 512 * 1024)) {
|
|
618
618
|
res.writeHead(413);
|
|
619
619
|
res.end(JSON.stringify({ ok: false, message: 'body too large' }));
|
|
620
620
|
return;
|
|
@@ -640,10 +640,11 @@ const server = createServer(async (req, res) => {
|
|
|
640
640
|
const fp = resolve(base, rel);
|
|
641
641
|
const text = await readFileAsync(fp);
|
|
642
642
|
res.end(JSON.stringify({ ok: true, path: rel, content: text.slice(0, MAX_FILE_READ_CHARS) }));
|
|
643
|
-
} else if (req.url === '/file_write') {
|
|
643
|
+
} else if (req.url === '/file_write' || req.url === '/file_write_base64') {
|
|
644
644
|
const rawPath = String(payload?.path ?? '').replace(/\\/g, '/').trim();
|
|
645
645
|
if (!rawPath) throw new Error('Invalid path');
|
|
646
|
-
const
|
|
646
|
+
const binary = req.url === '/file_write_base64';
|
|
647
|
+
const mode = binary ? 'write' : payload?.mode === 'append' ? 'append' : 'write';
|
|
647
648
|
const content = String(payload?.content ?? '');
|
|
648
649
|
ensureSessionBase(base);
|
|
649
650
|
const rel = sanitizeWorkspaceRelativePath(rawPath);
|
|
@@ -655,16 +656,18 @@ const server = createServer(async (req, res) => {
|
|
|
655
656
|
mkdirSync(dirname(fp), { recursive: true });
|
|
656
657
|
assertInside(base, realpathSync(dirname(fp)));
|
|
657
658
|
if (existsSync(fp)) assertInside(base, realpathSync(fp));
|
|
658
|
-
|
|
659
|
-
|
|
659
|
+
const fileContent = binary ? Buffer.from(content, 'base64') : content;
|
|
660
|
+
const bytes = binary ? fileContent.length : Buffer.byteLength(content, 'utf8');
|
|
661
|
+
if (bytes > (binary ? 8 * 1024 * 1024 : MAX_FILE_WRITE_BYTES)) {
|
|
662
|
+
throw new Error(binary ? 'Binary file exceeds the 8MB limit' : `File exceeds the ${MAX_FILE_WRITE_BYTES / 1024}KB limit`);
|
|
660
663
|
}
|
|
661
664
|
if (mode === 'append') {
|
|
662
665
|
const existing = existsSync(fp) ? await readFilePromise(fp, 'utf8') : '';
|
|
663
666
|
await writeFilePromise(fp, existing + content, 'utf8');
|
|
664
667
|
} else {
|
|
665
|
-
await writeFilePromise(fp,
|
|
668
|
+
await writeFilePromise(fp, fileContent, binary ? undefined : 'utf8');
|
|
666
669
|
}
|
|
667
|
-
res.end(JSON.stringify({ ok: true, path: rel, mode, bytes
|
|
670
|
+
res.end(JSON.stringify({ ok: true, path: rel, mode, bytes }));
|
|
668
671
|
} else if (req.url === '/file_delete') {
|
|
669
672
|
const rawPath = String(payload?.path ?? '').replace(/\\/g, '/').trim();
|
|
670
673
|
if (!rawPath) throw new Error('Invalid path');
|
package/src/App.tsx
CHANGED
|
@@ -367,7 +367,7 @@ function SessionHeader({
|
|
|
367
367
|
}, [showMobileActions]);
|
|
368
368
|
|
|
369
369
|
return (
|
|
370
|
-
<div className=
|
|
370
|
+
<div className={`chat-header${session.mode === 'GROUP' ? ' chat-header-group' : ''}`}>
|
|
371
371
|
<SessionVisual mode={session.mode} npcName={npcRef?.name ?? undefined} hue={npcRef?.avatarColorOrdinal ?? 0} imageUrl={npcRef?.avatarDataUrl} members={session.mode === 'GROUP' ? groupMemberAvatars : undefined} size="lg" />
|
|
372
372
|
<div className="tinfo">
|
|
373
373
|
<div className="ttitle">{session.title}</div>
|
|
@@ -108,7 +108,7 @@ export const CharactersView = memo(function CharactersView({ active = true }: {
|
|
|
108
108
|
<h2 className="view-title">{t('workshop.title')}</h2>
|
|
109
109
|
<p className="view-sub">{t('workshop.sub')}</p>
|
|
110
110
|
</div>
|
|
111
|
-
<div className="side-nav" data-hscroll>
|
|
111
|
+
<div className="side-nav view-tabs" data-hscroll>
|
|
112
112
|
<button className={`nav-chip ${tab === 'characters' ? 'active' : ''}`} onClick={() => selectTab('characters')}>
|
|
113
113
|
{t('workshop.tabCharacters')}
|
|
114
114
|
</button>
|
|
@@ -559,7 +559,7 @@ function MessageBubble({
|
|
|
559
559
|
{msg.attachments.length > 0 && (
|
|
560
560
|
<div className="attachments">
|
|
561
561
|
{msg.attachments.map((a, i) => (
|
|
562
|
-
<AttachCard key={i} name={msg.attachmentInfos?.[i]?.displayName || attachmentName(a)} />
|
|
562
|
+
<AttachCard key={i} src={a} name={msg.attachmentInfos?.[i]?.displayName || attachmentName(a)} />
|
|
563
563
|
))}
|
|
564
564
|
</div>
|
|
565
565
|
)}
|
|
@@ -656,6 +656,7 @@ function MessageEditorModal({
|
|
|
656
656
|
{attachments.map((a, i) => (
|
|
657
657
|
<AttachCard
|
|
658
658
|
key={i}
|
|
659
|
+
src={a.dataUrl}
|
|
659
660
|
name={a.name}
|
|
660
661
|
onRemove={() => setAttachments(attachments.filter((_, j) => j !== i))}
|
|
661
662
|
/>
|
|
@@ -718,7 +719,7 @@ function UserBubble({ msg, session, userPersonaName, loopIndex }: { msg: ChatMes
|
|
|
718
719
|
{msg.attachments.length > 0 && (
|
|
719
720
|
<div className="attachments">
|
|
720
721
|
{msg.attachments.map((a, i) => (
|
|
721
|
-
<AttachCard key={i} name={msg.attachmentInfos?.[i]?.displayName || attachmentName(a)} />
|
|
722
|
+
<AttachCard key={i} src={a} name={msg.attachmentInfos?.[i]?.displayName || attachmentName(a)} />
|
|
722
723
|
))}
|
|
723
724
|
</div>
|
|
724
725
|
)}
|
|
@@ -988,12 +989,13 @@ export function ChatInput({ sessionId }: { sessionId: number }) {
|
|
|
988
989
|
};
|
|
989
990
|
|
|
990
991
|
return (
|
|
991
|
-
<div className=
|
|
992
|
+
<div className={`composer${session?.mode === 'GROUP' ? ' composer-group' : ''}`}>
|
|
992
993
|
{attachments.length > 0 && (
|
|
993
994
|
<div className="attach-preview">
|
|
994
995
|
{attachments.map((a, i) => (
|
|
995
996
|
<AttachCard
|
|
996
997
|
key={i}
|
|
998
|
+
src={a.dataUrl}
|
|
997
999
|
name={a.name}
|
|
998
1000
|
onRemove={() => setAttachments(attachments.filter((_, j) => j !== i))}
|
|
999
1001
|
/>
|
|
@@ -33,7 +33,7 @@ const PIP_RECT_STORAGE_KEY = 'tav-file-display-pip-rect';
|
|
|
33
33
|
const PREVIEW_ZOOMS_STORAGE_KEY = 'tav-file-display-preview-zooms';
|
|
34
34
|
const PIP_REFRESH_INTERVAL = 1000;
|
|
35
35
|
|
|
36
|
-
type PreviewZoomKind = 'html';
|
|
36
|
+
type PreviewZoomKind = 'html' | 'image';
|
|
37
37
|
|
|
38
38
|
interface PipRect {
|
|
39
39
|
x: number;
|
|
@@ -151,11 +151,20 @@ export function FileDisplayModal() {
|
|
|
151
151
|
const [workspaceDir, setWorkspaceDir] = useState<string | null>(null);
|
|
152
152
|
const [loadState, setLoadState] = useState<'loading' | 'ok' | 'error'>('loading');
|
|
153
153
|
const [htmlZoom, setHtmlZoom] = useState(1);
|
|
154
|
+
const [imageZoom, setImageZoom] = useState(1);
|
|
155
|
+
const [imageLoadVersion, setImageLoadVersion] = useState(0);
|
|
156
|
+
const [imageLayout, setImageLayout] = useState<{
|
|
157
|
+
width: number;
|
|
158
|
+
height: number;
|
|
159
|
+
overflowX: boolean;
|
|
160
|
+
overflowY: boolean;
|
|
161
|
+
} | null>(null);
|
|
154
162
|
const [htmlPreviewVersion, setHtmlPreviewVersion] = useState(0);
|
|
155
163
|
const [textWrap, setTextWrap] = useState(true);
|
|
156
164
|
const [isPictureInPicture, setIsPictureInPicture] = useState(true);
|
|
157
165
|
const [pipRect, setPipRect] = useState<PipRect>(createPipRect);
|
|
158
166
|
const contentRef = useRef<string | null>(null);
|
|
167
|
+
const imageViewportRef = useRef<HTMLDivElement | null>(null);
|
|
159
168
|
const wasDisplayOpenRef = useRef(false);
|
|
160
169
|
const pipGestureRef = useRef<
|
|
161
170
|
| { type: 'move'; pointerX: number; pointerY: number; startX: number; startY: number }
|
|
@@ -195,8 +204,51 @@ export function FileDisplayModal() {
|
|
|
195
204
|
setIsPictureInPicture(opensInPictureInPicture);
|
|
196
205
|
}
|
|
197
206
|
setHtmlZoom(active.kind === 'html' ? restorePreviewZoom('html', active.path, 1) : 1);
|
|
207
|
+
setImageZoom(active.kind === 'image' ? restorePreviewZoom('image', active.path, 1) : 1);
|
|
208
|
+
setImageLoadVersion(0);
|
|
209
|
+
setImageLayout(null);
|
|
198
210
|
}, [active]);
|
|
199
211
|
|
|
212
|
+
useLayoutEffect(() => {
|
|
213
|
+
if (!active || active.kind !== 'image' || loadState !== 'ok' || !workspaceDir) return;
|
|
214
|
+
const viewport = imageViewportRef.current;
|
|
215
|
+
const image = viewport?.querySelector('img');
|
|
216
|
+
if (!viewport || !image || !image.complete) return;
|
|
217
|
+
|
|
218
|
+
const updateImageViewport = () => {
|
|
219
|
+
const naturalWidth = image.naturalWidth;
|
|
220
|
+
const naturalHeight = image.naturalHeight;
|
|
221
|
+
if (!naturalWidth || !naturalHeight) return;
|
|
222
|
+
|
|
223
|
+
const fitScale = Math.min(1, viewport.clientWidth / naturalWidth, viewport.clientHeight / naturalHeight);
|
|
224
|
+
const width = naturalWidth * fitScale * imageZoom;
|
|
225
|
+
const height = naturalHeight * fitScale * imageZoom;
|
|
226
|
+
const nextLayout = {
|
|
227
|
+
width,
|
|
228
|
+
height,
|
|
229
|
+
overflowX: width > viewport.clientWidth,
|
|
230
|
+
overflowY: height > viewport.clientHeight,
|
|
231
|
+
};
|
|
232
|
+
setImageLayout((current) => current
|
|
233
|
+
&& current.width === nextLayout.width
|
|
234
|
+
&& current.height === nextLayout.height
|
|
235
|
+
&& current.overflowX === nextLayout.overflowX
|
|
236
|
+
&& current.overflowY === nextLayout.overflowY
|
|
237
|
+
? current
|
|
238
|
+
: nextLayout);
|
|
239
|
+
requestAnimationFrame(() => {
|
|
240
|
+
viewport.scrollLeft = Math.max(0, (width - viewport.clientWidth) / 2);
|
|
241
|
+
viewport.scrollTop = Math.max(0, (height - viewport.clientHeight) / 2);
|
|
242
|
+
});
|
|
243
|
+
};
|
|
244
|
+
|
|
245
|
+
updateImageViewport();
|
|
246
|
+
const resizeObserver = new ResizeObserver(updateImageViewport);
|
|
247
|
+
resizeObserver.observe(viewport);
|
|
248
|
+
resizeObserver.observe(image);
|
|
249
|
+
return () => resizeObserver.disconnect();
|
|
250
|
+
}, [active, imageLoadVersion, imageZoom, isPictureInPicture, loadState, workspaceDir]);
|
|
251
|
+
|
|
200
252
|
useEffect(() => {
|
|
201
253
|
if (!active || active.kind === 'unsupported' || !isPictureInPicture) return;
|
|
202
254
|
let cancelled = false;
|
|
@@ -374,6 +426,16 @@ export function FileDisplayModal() {
|
|
|
374
426
|
const htmlZoomIn = () => updateHtmlZoom((z) => Math.min(2, +(z + 0.1).toFixed(1)));
|
|
375
427
|
const htmlZoomOut = () => updateHtmlZoom((z) => Math.max(0.5, +(z - 0.1).toFixed(1)));
|
|
376
428
|
const resetHtmlZoom = () => updateHtmlZoom(() => 1);
|
|
429
|
+
const updateImageZoom = (update: (zoom: number) => number) => {
|
|
430
|
+
setImageZoom((zoom) => {
|
|
431
|
+
const nextZoom = update(zoom);
|
|
432
|
+
persistPreviewZoom('image', active.path, nextZoom);
|
|
433
|
+
return nextZoom;
|
|
434
|
+
});
|
|
435
|
+
};
|
|
436
|
+
const imageZoomIn = () => updateImageZoom((z) => Math.min(3, +(z + 0.1).toFixed(1)));
|
|
437
|
+
const imageZoomOut = () => updateImageZoom((z) => Math.max(0.2, +(z - 0.1).toFixed(1)));
|
|
438
|
+
const resetImageZoom = () => updateImageZoom(() => 1);
|
|
377
439
|
|
|
378
440
|
const renderBody = () => {
|
|
379
441
|
if (active.kind === 'unsupported') {
|
|
@@ -391,6 +453,47 @@ export function FileDisplayModal() {
|
|
|
391
453
|
return <div className="display-error">{t('display.fileError', { path: active.path })}</div>;
|
|
392
454
|
}
|
|
393
455
|
|
|
456
|
+
if (active.kind === 'image') {
|
|
457
|
+
if (!workspaceDir) return <div className="display-error">{t('display.fileError', { path: active.path })}</div>;
|
|
458
|
+
return (
|
|
459
|
+
<div className="display-image-wrap">
|
|
460
|
+
<div
|
|
461
|
+
ref={imageViewportRef}
|
|
462
|
+
className="display-image-viewport"
|
|
463
|
+
style={{
|
|
464
|
+
overflowX: imageLayout?.overflowX ? 'auto' : 'hidden',
|
|
465
|
+
overflowY: imageLayout?.overflowY ? 'auto' : 'hidden',
|
|
466
|
+
}}
|
|
467
|
+
>
|
|
468
|
+
<div
|
|
469
|
+
className="display-image-scroll-area"
|
|
470
|
+
style={imageLayout ? { width: imageLayout.width, height: imageLayout.height } : undefined}
|
|
471
|
+
>
|
|
472
|
+
<img
|
|
473
|
+
className="display-image"
|
|
474
|
+
src={previewUrl(active.path, workspaceDir)}
|
|
475
|
+
alt={title}
|
|
476
|
+
style={imageLayout
|
|
477
|
+
? { width: imageLayout.width, height: imageLayout.height, visibility: 'visible' }
|
|
478
|
+
: { visibility: 'hidden' }}
|
|
479
|
+
onLoad={() => setImageLoadVersion((version) => version + 1)}
|
|
480
|
+
/>
|
|
481
|
+
</div>
|
|
482
|
+
</div>
|
|
483
|
+
<div className="display-html-note display-image-note">
|
|
484
|
+
<span />
|
|
485
|
+
{!isPictureInPicture && (
|
|
486
|
+
<span className="display-html-zoom-group">
|
|
487
|
+
<button className="icon-btn" title={t('display.htmlZoomOut')} onClick={imageZoomOut}><Icon name="zoom-out" size={15} /></button>
|
|
488
|
+
<button className="icon-btn" title={t('display.resetHtmlZoom')} onClick={resetImageZoom}>{Math.round(imageZoom * 100)}%</button>
|
|
489
|
+
<button className="icon-btn" title={t('display.htmlZoomIn')} onClick={imageZoomIn}><Icon name="zoom-in" size={15} /></button>
|
|
490
|
+
</span>
|
|
491
|
+
)}
|
|
492
|
+
</div>
|
|
493
|
+
</div>
|
|
494
|
+
);
|
|
495
|
+
}
|
|
496
|
+
|
|
394
497
|
if (active.kind === 'html') {
|
|
395
498
|
if (!workspaceDir) return <div className="display-error">{t('display.fileError', { path: active.path })}</div>;
|
|
396
499
|
return (
|
|
@@ -548,7 +651,7 @@ export function parseStoredDisplayRef(json: string | null): DisplayFileRef | nul
|
|
|
548
651
|
if (!json) return null;
|
|
549
652
|
try {
|
|
550
653
|
const obj = JSON.parse(json) as Partial<DisplayFileRef>;
|
|
551
|
-
if (!obj || typeof obj.path !== 'string' || !['text', 'html', 'unsupported'].includes(obj.kind ?? '')) return null;
|
|
654
|
+
if (!obj || typeof obj.path !== 'string' || !['text', 'html', 'image', 'unsupported'].includes(obj.kind ?? '')) return null;
|
|
552
655
|
return {
|
|
553
656
|
path: obj.path,
|
|
554
657
|
kind: obj.kind as DisplayFileRef['kind'],
|