dsh-document-reader 0.0.0-stage → 1.0.2
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/LICENSE +21 -0
- package/README.md +84 -2
- package/client.js +3652 -0
- package/client.pdfjs.js +21278 -0
- package/client.vendor.js +41 -0
- package/cordis.patch.yml +10 -0
- package/icon.svg +11 -0
- package/index.js +1418 -0
- package/locale/en.json +41 -0
- package/locale/zh.json +41 -0
- package/package.json +50 -3
package/client.js
ADDED
|
@@ -0,0 +1,3652 @@
|
|
|
1
|
+
// Client half of the DSH doc-reader plugin (v2).
|
|
2
|
+
// Registers the "doc-reader" main panel and its sidebar entry; renders local
|
|
3
|
+
// PDF / DOCX / Markdown / text / image files fetched from the Host routes.
|
|
4
|
+
//
|
|
5
|
+
// v2 adds (see docs/对照分析.md):
|
|
6
|
+
// - PDF continuous scroll + lazy page rendering + text-layer search + fit-width
|
|
7
|
+
// - DOCX full render options + page synthesis + style.zoom + page controls
|
|
8
|
+
// - Markdown: breaks, slug TOC, external-link guard, intra-doc links
|
|
9
|
+
// - MD/text in-document search with n/m navigation
|
|
10
|
+
// - Image: 100% reset / fit-width / rotation-aware fit / stage sizing
|
|
11
|
+
// - Structured per-kind position restore, rename, reveal, settings overlay
|
|
12
|
+
window.__ModuleLoader__.load({
|
|
13
|
+
id: 'dsh-document-reader',
|
|
14
|
+
factory(require) {
|
|
15
|
+
const React = require('react');
|
|
16
|
+
const { useState, useEffect, useRef, useCallback, useMemo } = React;
|
|
17
|
+
const h = React.createElement;
|
|
18
|
+
// Bump on every client release. Shown in ⚙ settings, set as data-attr on the
|
|
19
|
+
// panel root and logged at load — a stale cached bundle (the webview can serve
|
|
20
|
+
// an old client.js across refreshes) is then distinguishable from a code bug
|
|
21
|
+
// in one glance instead of a blind debugging round.
|
|
22
|
+
const CLIENT_VERSION = '1.0.2';
|
|
23
|
+
try { console.info(`[doc-reader] client v${CLIENT_VERSION}`); } catch { /* console unavailable */ }
|
|
24
|
+
|
|
25
|
+
const ROUTE = '/doc-reader/dsh-document-reader';
|
|
26
|
+
const FILE_URL = (path) => `${ROUTE}/file/${encodeURIComponent(path)}`;
|
|
27
|
+
const LIST_URL = (dir) => `${ROUTE}/list${dir ? `?path=${encodeURIComponent(dir)}` : ''}`;
|
|
28
|
+
const RENAME_URL = `${ROUTE}/rename`;
|
|
29
|
+
const REVEAL_URL = (path) => `${ROUTE}/reveal?path=${encodeURIComponent(path)}`;
|
|
30
|
+
const ACTIVE_URL = `${ROUTE}/active`;
|
|
31
|
+
const CONFIG_URL = `${ROUTE}/config`;
|
|
32
|
+
const TRANSLATE_URL = `${ROUTE}/translate`;
|
|
33
|
+
const EVENTS_URL = (path) => `${ROUTE}/events${path ? `?path=${encodeURIComponent(path)}` : ''}`;
|
|
34
|
+
|
|
35
|
+
const MD_EXT = ['md', 'markdown'];
|
|
36
|
+
const TXT_EXT = ['txt', 'log', 'json', 'yaml', 'yml', 'csv', 'tsv', 'xml', 'ini', 'conf', 'toml'];
|
|
37
|
+
const IMG_EXT = ['png', 'jpg', 'jpeg', 'gif', 'webp', 'svg', 'bmp', 'ico', 'avif', 'jfif'];
|
|
38
|
+
const OFFICE_EXT = ['pptx', 'xlsx', 'ppt', 'xls', 'doc'];
|
|
39
|
+
const kindOf = (path) => {
|
|
40
|
+
const name = path.slice(path.lastIndexOf('/') + 1);
|
|
41
|
+
const dot = name.lastIndexOf('.');
|
|
42
|
+
if (dot <= 0) return null; // no extension, or a dotfile like ".md" (Host extname treats those as extensionless)
|
|
43
|
+
const ext = name.slice(dot + 1).toLowerCase();
|
|
44
|
+
if (MD_EXT.includes(ext)) return 'markdown';
|
|
45
|
+
if (TXT_EXT.includes(ext)) return 'text';
|
|
46
|
+
if (IMG_EXT.includes(ext)) return 'image';
|
|
47
|
+
if (OFFICE_EXT.includes(ext)) return 'office';
|
|
48
|
+
if (ext === 'pdf') return 'pdf';
|
|
49
|
+
if (ext === 'docx') return 'docx';
|
|
50
|
+
if (ext === 'epub') return 'epub';
|
|
51
|
+
if (ext === 'html' || ext === 'htm') return 'html';
|
|
52
|
+
return null;
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
// ---------- persistence ----------
|
|
56
|
+
const LS = {
|
|
57
|
+
recent: 'dsh-doc-reader:recent',
|
|
58
|
+
settings: 'dsh-doc-reader:settings',
|
|
59
|
+
pos: (path) => `dsh-doc-reader:pos:${path}`,
|
|
60
|
+
draft: (path) => `dsh-doc-reader:draft:${path}`,
|
|
61
|
+
};
|
|
62
|
+
function readJson(key, fallback) {
|
|
63
|
+
try { return JSON.parse(localStorage.getItem(key)) ?? fallback; } catch { return fallback; }
|
|
64
|
+
}
|
|
65
|
+
function writeJson(key, value) {
|
|
66
|
+
try { localStorage.setItem(key, JSON.stringify(value)); } catch { /* full */ }
|
|
67
|
+
}
|
|
68
|
+
const DEFAULT_SETTINGS = { fontSize: 15, lineHeight: 1.7, recentLimit: 20, pdfTextLayer: true, docxBreakPages: true, lang: 'auto', translateTarget: 'zh-Hans', translateEngine: 'bing', translateProvider: '', translateModel: '', translateGoogleEndpoint: '' };
|
|
69
|
+
const getSettings = () => ({ ...DEFAULT_SETTINGS, ...readJson(LS.settings, {}) });
|
|
70
|
+
const getPos = (path) => readJson(LS.pos(path), null);
|
|
71
|
+
const savePos = (path, pos) => writeJson(LS.pos(path), pos);
|
|
72
|
+
const removePos = (path) => { try { localStorage.removeItem(LS.pos(path)); } catch { /* storage disabled */ } };
|
|
73
|
+
const removeDraft = (path) => { try { localStorage.removeItem(LS.draft(path)); } catch { /* storage disabled */ } };
|
|
74
|
+
function pushRecent(path, limit) {
|
|
75
|
+
const kind = kindOf(path);
|
|
76
|
+
const prev = readJson(LS.recent, []);
|
|
77
|
+
const next = [{ path, kind, at: Date.now() }, ...prev.filter((e) => e.path !== path)]
|
|
78
|
+
.slice(0, Math.max(5, Math.min(200, limit)));
|
|
79
|
+
// drop the position record of entries evicted from the recent list
|
|
80
|
+
for (const e of prev) if (!next.some((n) => n.path === e.path)) { removePos(e.path); removeDraft(e.path); }
|
|
81
|
+
writeJson(LS.recent, next);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// ---------- lazy vendor chunks ----------
|
|
85
|
+
// A rejected promise must NOT stay cached: one transient failure would
|
|
86
|
+
// otherwise permanently break every md/docx/pdf open until page reload.
|
|
87
|
+
let vendorPromise;
|
|
88
|
+
function loadVendor() {
|
|
89
|
+
vendorPromise ??= require.async('./client.vendor.js').catch((error) => { vendorPromise = null; throw error; });
|
|
90
|
+
return vendorPromise;
|
|
91
|
+
}
|
|
92
|
+
let pdfjsPromise;
|
|
93
|
+
function loadPdfjs() {
|
|
94
|
+
pdfjsPromise ??= require.async('./client.pdfjs.js').then((m) => {
|
|
95
|
+
const lib = m.pdfjsLib;
|
|
96
|
+
if (!lib.GlobalWorkerOptions.workerSrc && m.workerText) {
|
|
97
|
+
lib.GlobalWorkerOptions.workerSrc = URL.createObjectURL(new Blob([m.workerText], { type: 'text/javascript' }));
|
|
98
|
+
}
|
|
99
|
+
return lib;
|
|
100
|
+
}).catch((error) => { pdfjsPromise = null; throw error; });
|
|
101
|
+
return pdfjsPromise;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Decode text bytes: strict UTF-8 first, then common CJK legacy
|
|
105
|
+
* encodings (TextDecoder ships them in Chromium), else lenient UTF-8.
|
|
106
|
+
* A leading BOM is stripped. */
|
|
107
|
+
function decodeText(buf) {
|
|
108
|
+
const bytes = buf instanceof Uint8Array ? buf : new Uint8Array(buf);
|
|
109
|
+
const utf8Strict = () => new TextDecoder('utf-8', { fatal: true, ignoreBOM: false }).decode(bytes);
|
|
110
|
+
for (const attempt of [utf8Strict, () => new TextDecoder('gbk').decode(bytes), () => new TextDecoder('big5').decode(bytes), () => new TextDecoder('shift_jis').decode(bytes)]) {
|
|
111
|
+
try {
|
|
112
|
+
const out = attempt();
|
|
113
|
+
if (typeof out === 'string') return out.replace(/^\uFEFF/u, '');
|
|
114
|
+
} catch { /* try next encoding */ }
|
|
115
|
+
}
|
|
116
|
+
return new TextDecoder('utf-8').decode(bytes).replace(/^\uFEFF/u, '');
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
async function fetchFile(path, as, signal) {
|
|
120
|
+
const res = await fetch(FILE_URL(path), { signal });
|
|
121
|
+
if (!res.ok) {
|
|
122
|
+
const detail = await res.json().catch(() => ({ error: res.statusText }));
|
|
123
|
+
throw new Error(detail.error || `${res.status}`);
|
|
124
|
+
}
|
|
125
|
+
if (as === 'text') return decodeText(await res.arrayBuffer());
|
|
126
|
+
return res.arrayBuffer();
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const joinDir = (base, src) => {
|
|
130
|
+
const clean = src.split('?')[0].split('#')[0];
|
|
131
|
+
if (/^https?:/iu.test(clean) || clean.startsWith('data:') || clean.startsWith('mailto:')) return null;
|
|
132
|
+
if (clean.startsWith('/')) return clean;
|
|
133
|
+
const parts = base.split('/');
|
|
134
|
+
for (const seg of clean.split('/')) {
|
|
135
|
+
if (seg === '' || seg === '.') continue;
|
|
136
|
+
if (seg === '..') parts.pop();
|
|
137
|
+
else parts.push(seg);
|
|
138
|
+
}
|
|
139
|
+
return parts.join('/') || '/';
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
/** VSCode-extension-style heading slug: strip punctuation, spaces to '-', dedupe. */
|
|
143
|
+
function slugify(text, occurrences) {
|
|
144
|
+
const base = text.trim().toLowerCase()
|
|
145
|
+
.replace(/[`~!@#$%^&*()+={}\[\]|\\:;"'<>,.?/]/g, '')
|
|
146
|
+
.replace(/\s+/g, '-')
|
|
147
|
+
.replace(/-+/g, '-')
|
|
148
|
+
.replace(/^-|-$/g, '') || 'section';
|
|
149
|
+
const count = occurrences.get(base) ?? 0;
|
|
150
|
+
occurrences.set(base, count + 1);
|
|
151
|
+
return count === 0 ? base : `${base}-${count}`;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const clamp = (value, min, max) => Math.max(min, Math.min(max, value));
|
|
155
|
+
|
|
156
|
+
// ---------- styles ----------
|
|
157
|
+
const CSS = `
|
|
158
|
+
.dr-panel{display:flex;flex-direction:column;height:100%;min-height:0;background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);font-family:var(--dsw-font,inherit)}
|
|
159
|
+
.dr-toolbar{display:flex;align-items:center;gap:8px;padding:7px 12px;border-bottom:.5px solid var(--dsw-alias-border-l2);flex:none;flex-wrap:wrap}
|
|
160
|
+
.dr-logo{display:flex;align-items:center;gap:6px;font-size:13px;font-weight:600;white-space:nowrap}
|
|
161
|
+
.dr-logo svg{width:16px;height:16px}
|
|
162
|
+
.dr-rename{display:flex;align-items:center;gap:4px;font-size:13px;font-weight:600;min-width:0;max-width:34%}
|
|
163
|
+
.dr-rename-btn{display:inline-flex;align-items:center;gap:5px;background:none;border:none;padding:3px 6px;border-radius:6px;color:var(--dsw-alias-label-primary);cursor:pointer;font:inherit;max-width:100%;position:relative;z-index:1}
|
|
164
|
+
.dr-rename-btn:hover,.dr-rename-btn:focus-visible{background:var(--dsw-alias-interactive-bg-hover)}
|
|
165
|
+
.dr-rename-btn svg{width:12px;height:12px;opacity:.45;flex:none;transition:opacity .12s}
|
|
166
|
+
.dr-rename-btn:hover svg{opacity:.9}
|
|
167
|
+
.dr-rename-name{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
|
168
|
+
.dr-rename-input{font:inherit;font-size:13px;font-weight:600;color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-layer-2);border:.5px solid var(--dsw-alias-border-l3);border-radius:6px;padding:3px 8px;min-width:120px;outline:none;width:100%}
|
|
169
|
+
.dr-path{flex:1;min-width:160px;box-sizing:border-box;height:30px;padding:0 10px;font-size:12px;font-family:var(--dsw-font-mono,monospace);color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-layer-2);border:.5px solid var(--dsw-alias-border-l2);border-radius:var(--dsw-radius-sm,6px);outline:none}
|
|
170
|
+
.dr-path:focus{border-color:var(--dsw-alias-border-l3)}
|
|
171
|
+
.dr-path::placeholder{color:var(--dsw-alias-label-tertiary)}
|
|
172
|
+
.dr-btn{height:28px;padding:0 10px;font-size:12px;color:var(--dsw-alias-label-secondary);background:transparent;border:.5px solid var(--dsw-alias-border-l2);border-radius:var(--dsw-radius-sm,6px);cursor:pointer;display:inline-flex;align-items:center;gap:5px;white-space:nowrap;font-family:inherit}
|
|
173
|
+
.dr-btn:hover{color:var(--dsw-alias-label-primary);background:var(--dsw-alias-interactive-bg-hover)}
|
|
174
|
+
.dr-btn[aria-pressed="true"]{color:var(--dsw-alias-label-primary);background:var(--dsw-alias-interactive-bg-hover)}
|
|
175
|
+
.dr-btn:disabled{opacity:.45;cursor:default}
|
|
176
|
+
.dr-btn--icon{width:28px;padding:0;justify-content:center}
|
|
177
|
+
.dr-selbar{position:fixed;transform:translate(-50%,-100%);margin-top:-6px;display:inline-flex;align-items:center;gap:1px;height:28px;padding:2px;border-radius:8px;border:.5px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-3);box-shadow:0 2px 10px rgba(0,0,0,.18);z-index:70}
|
|
178
|
+
.dr-selbar button{width:26px;height:24px;display:inline-flex;align-items:center;justify-content:center;background:none;border:none;border-radius:6px;color:var(--dsw-alias-label-secondary);cursor:pointer;padding:0}
|
|
179
|
+
.dr-selbar button:hover{color:var(--dsw-alias-label-primary);background:var(--dsw-alias-interactive-bg-hover)}
|
|
180
|
+
.dr-selbar svg{width:13px;height:13px}
|
|
181
|
+
.dr-ctxmenu{position:fixed;min-width:168px;padding:4px;border-radius:8px;border:.5px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-3);box-shadow:0 6px 24px rgba(0,0,0,.22);z-index:75;display:flex;flex-direction:column}
|
|
182
|
+
.dr-ctxmenu button{display:flex;align-items:center;gap:8px;padding:6px 10px;border:none;background:none;color:var(--dsw-alias-label-primary);font-size:12px;text-align:left;cursor:pointer;border-radius:5px;font-family:inherit}
|
|
183
|
+
.dr-ctxmenu button:hover{background:var(--dsw-alias-interactive-bg-hover)}
|
|
184
|
+
.dr-ctxmenu button:disabled{opacity:.4;cursor:default}
|
|
185
|
+
.dr-external{display:flex;align-items:center;gap:8px;padding:5px 12px;border-bottom:.5px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-2);flex:none;font-size:12px}
|
|
186
|
+
.dr-external-msg{flex:1;min-width:0;color:var(--dsw-alias-label-primary)}
|
|
187
|
+
.dr-body{flex:1;min-height:0;display:flex}
|
|
188
|
+
.dr-side{width:260px;flex:none;min-height:0;min-width:0;display:flex;flex-direction:column;border-right:.5px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-1);overflow:hidden}
|
|
189
|
+
.dr-side-hidden{display:none}
|
|
190
|
+
.dr-side-tabs{display:flex;gap:2px;padding:6px 8px 0;flex:none}
|
|
191
|
+
.dr-side-tab{flex:1;height:26px;font-size:12px;color:var(--dsw-alias-label-secondary);background:transparent;border:none;border-bottom:1.5px solid transparent;cursor:pointer;font-family:inherit}
|
|
192
|
+
.dr-side-tab[aria-selected="true"]{color:var(--dsw-alias-label-primary);border-bottom-color:var(--dsw-alias-label-primary)}
|
|
193
|
+
.dr-side-scroll{flex:1;min-height:0;overflow-x:hidden;overflow-y:auto;padding:4px 0 12px;--dsh-scrollbar-thumb:var(--dsw-alias-scrollbar-bg-l2)}
|
|
194
|
+
.dr-crumbs{display:flex;flex-wrap:wrap;gap:2px;padding:6px 10px 2px;font-size:11px;color:var(--dsw-alias-label-tertiary);flex:none}
|
|
195
|
+
.dr-crumb{background:none;border:none;padding:2px 4px;font-size:11px;color:var(--dsw-alias-label-secondary);cursor:pointer;font-family:inherit;border-radius:4px}
|
|
196
|
+
.dr-crumb:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}
|
|
197
|
+
.dr-row{display:flex;width:100%;max-width:100%;box-sizing:border-box;align-items:center;gap:7px;padding:5px 10px;font-size:12px;color:var(--dsw-alias-label-primary);background:none;border:none;cursor:pointer;text-align:left;font-family:inherit;position:relative;overflow:hidden}
|
|
198
|
+
.dr-row:hover{background:var(--dsw-alias-interactive-bg-hover)}
|
|
199
|
+
.dr-row svg{width:14px;height:14px;flex:none;opacity:.75}
|
|
200
|
+
.dr-row>span{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
|
201
|
+
.dr-row:hover>span{padding-right:6px}
|
|
202
|
+
.dr-row small{margin-left:auto;color:var(--dsw-alias-label-tertiary);font-size:10px;flex:none;white-space:nowrap;padding-left:6px}
|
|
203
|
+
.dr-row:hover>small{visibility:hidden}
|
|
204
|
+
.dr-toc-expand{position:absolute;top:8px;left:8px;z-index:5;width:22px;height:22px;border:.5px solid var(--dsw-alias-border-l2);border-radius:6px;background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-tertiary);cursor:pointer;font-size:12px;display:flex;align-items:center;justify-content:center;padding:0;box-shadow:0 1px 4px rgba(0,0,0,.12)}
|
|
205
|
+
.dr-toc-expand:hover{color:var(--dsw-alias-label-primary);background:var(--dsw-alias-interactive-bg-hover)}
|
|
206
|
+
.dr-browse{width:min(560px,86vw);height:min(520px,80vh);background:var(--dsw-alias-bg-layer-1);border:.5px solid var(--dsw-alias-border-l3);border-radius:10px;display:flex;flex-direction:column;box-shadow:0 12px 40px rgba(0,0,0,.3);overflow:hidden}
|
|
207
|
+
.dr-browse header{display:flex;align-items:center;gap:8px;padding:10px 14px;border-bottom:.5px solid var(--dsw-alias-border-l2);font-size:13px;font-weight:600;flex:none}
|
|
208
|
+
.dr-browse .dr-crumbs{padding:8px 12px 4px}
|
|
209
|
+
.dr-browse .dr-side-scroll{flex:1;min-height:0;padding:4px 0 8px}
|
|
210
|
+
.dr-browse footer{display:flex;justify-content:flex-end;gap:8px;padding:8px 12px;border-top:.5px solid var(--dsw-alias-border-l2);flex:none}
|
|
211
|
+
.dr-side-head{padding:6px 10px;flex:none;display:flex;align-items:center;justify-content:space-between;gap:8px}
|
|
212
|
+
.dr-side-title{font-size:12px;font-weight:600;color:var(--dsw-alias-label-primary)}
|
|
213
|
+
.dr-row-actions{position:absolute;right:2px;top:50%;transform:translateY(-50%);display:none;gap:1px;background:var(--dsw-alias-bg-layer-3);border:.5px solid var(--dsw-alias-border-l2);padding:1px 2px;border-radius:6px;z-index:2}
|
|
214
|
+
.dr-row:hover .dr-row-actions{display:inline-flex}
|
|
215
|
+
.dr-row:hover>small{display:none}
|
|
216
|
+
.dr-row-actions button{background:none;border:none;padding:2px 6px;color:var(--dsw-alias-label-secondary);cursor:pointer;font-size:12px;border-radius:4px;display:inline-flex;align-items:center;line-height:1;min-width:22px;justify-content:center}
|
|
217
|
+
.dr-row-actions button:hover{color:var(--dsw-alias-label-primary);background:var(--dsw-alias-interactive-bg-hover)}
|
|
218
|
+
.dr-tip{position:fixed;transform:translate(-50%,-100%);margin-top:-6px;background:var(--dsw-alias-tooltip-bg,#2c2c2e);color:var(--dsw-alias-tooltip-label,#fff);border:none;border-radius:7px;padding:4px 9px;font-size:12px;line-height:18px;white-space:nowrap;pointer-events:none;/* max int: the tooltip lives at document.body but nothing in the app may stack above it (app bubbles sit at 100, toasts 1100) */z-index:2147483647;box-shadow:0 4px 16px rgba(0,0,0,.28)}
|
|
219
|
+
.dr-tip--below{transform:translate(-50%,0)!important;margin-top:0!important}
|
|
220
|
+
.dr-tip--side-l{transform:translate(-100%,-50%)!important;margin-top:0!important}
|
|
221
|
+
.dr-tip--side-r{transform:translate(0,-50%)!important;margin-top:0!important}
|
|
222
|
+
.dr-empty-side{padding:16px 12px;font-size:12px;color:var(--dsw-alias-label-tertiary);line-height:1.6}
|
|
223
|
+
.dr-content{flex:1;min-width:0;min-height:0;position:relative;display:flex;flex-direction:column}
|
|
224
|
+
.dr-viewbar{display:flex;align-items:center;gap:6px;padding:5px 12px;border-bottom:.5px solid var(--dsw-alias-border-l1);flex:none;flex-wrap:wrap;min-height:34px}
|
|
225
|
+
.dr-viewbar input[type="search"]{width:150px;height:24px;padding:0 8px;font-size:12px;font-family:inherit;color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-layer-2);border:.5px solid var(--dsw-alias-border-l2);border-radius:6px;outline:none}
|
|
226
|
+
.dr-count{font-size:11px;color:var(--dsw-alias-label-tertiary);min-width:34px;text-align:center}
|
|
227
|
+
.dr-badge{font-size:11px;color:var(--dsw-alias-label-tertiary);min-width:40px;text-align:center}
|
|
228
|
+
.dr-stage{flex:1;min-height:0;display:flex;position:relative}
|
|
229
|
+
.dr-scroll{flex:1;min-width:0;min-height:0;overflow:auto;position:relative;--dsh-scrollbar-thumb:var(--dsw-alias-scrollbar-bg-l2)}
|
|
230
|
+
.dr-toc{width:200px;flex:none;border-right:.5px solid var(--dsw-alias-border-l1);overflow:auto;font-size:12px;padding:8px 6px}
|
|
231
|
+
.dr-toc-title{font-size:11px;color:var(--dsw-alias-label-tertiary);padding:0 8px 6px}
|
|
232
|
+
.dr-toc button{display:block;width:100%;text-align:left;background:none;border:none;color:var(--dsw-alias-label-secondary);cursor:pointer;padding:3px 8px;font-size:12px;font-family:inherit;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;border-radius:4px}
|
|
233
|
+
.dr-toc button:hover{color:var(--dsw-alias-label-primary);background:var(--dsw-alias-interactive-bg-hover)}
|
|
234
|
+
.dr-toc button.active{color:var(--dsw-alias-label-primary);background:var(--dsw-alias-interactive-bg-hover)}
|
|
235
|
+
.dr-status{flex:none;display:flex;align-items:center;padding:3px 12px;min-height:22px;font-size:11px;color:var(--dsw-alias-label-tertiary);border-top:.5px solid var(--dsw-alias-border-l1)}
|
|
236
|
+
.dr-error{margin:auto;padding:24px;font-size:13px;color:var(--dsw-alias-label-secondary);text-align:center;line-height:1.8}
|
|
237
|
+
.dr-empty{margin:auto;padding:24px;display:flex;flex-direction:column;align-items:center;gap:12px;color:var(--dsw-alias-label-tertiary);font-size:13px;text-align:center}
|
|
238
|
+
.dr-empty svg{width:44px;height:44px;opacity:.5}
|
|
239
|
+
.dr-load{margin:auto;font-size:12px;color:var(--dsw-alias-label-tertiary)}
|
|
240
|
+
.dr-md{flex:1;min-width:0;padding:16px 26px 60px;font-size:15px;line-height:var(--dr-line-height,1.7);white-space:normal;overflow-wrap:break-word}
|
|
241
|
+
.dr-md h1,.dr-md h2,.dr-md h3,.dr-md h4,.dr-md h5,.dr-md h6{line-height:1.35;margin:1.2em 0 .5em}
|
|
242
|
+
.dr-md h1{font-size:1.55em}.dr-md h2{font-size:1.3em}.dr-md h3{font-size:1.12em}.dr-md h4{font-size:1em}
|
|
243
|
+
.dr-md p{margin:.65em 0}
|
|
244
|
+
.dr-md pre{background:var(--dsw-alias-bg-layer-2);border:.5px solid var(--dsw-alias-border-l1);border-radius:8px;padding:12px;overflow:auto;font-family:var(--dsw-font-mono,monospace);font-size:12.5px;line-height:1.6}
|
|
245
|
+
.dr-md code{font-family:var(--dsw-font-mono,monospace);font-size:.92em;background:var(--dsw-alias-bg-layer-2);padding:1px 5px;border-radius:4px}
|
|
246
|
+
.dr-md pre code{background:none;padding:0}
|
|
247
|
+
.dr-md blockquote{margin:.8em 0;padding:2px 14px;border-left:3px solid var(--dsw-alias-border-l3);color:var(--dsw-alias-label-secondary)}
|
|
248
|
+
.dr-md img{max-width:100%;border-radius:6px}
|
|
249
|
+
.dr-md table{border-collapse:collapse;margin:.8em 0}
|
|
250
|
+
.dr-md th,.dr-md td{border:.5px solid var(--dsw-alias-border-l2);padding:5px 10px;font-size:.95em}
|
|
251
|
+
.dr-md th{background:var(--dsw-alias-bg-layer-2)}
|
|
252
|
+
.dr-md a{color:var(--dsw-alias-label-accent,var(--dsw-alias-label-primary));cursor:pointer}
|
|
253
|
+
.dr-md hr{border:none;border-top:.5px solid var(--dsw-alias-border-l2);margin:1.6em 0}
|
|
254
|
+
.dr-text{padding:14px 18px 60px;font-family:var(--dsw-font-mono,monospace);white-space:pre-wrap;word-break:break-word;line-height:var(--dr-line-height,1.7)}
|
|
255
|
+
mark.dr-mark{background:color-mix(in srgb,var(--dsw-alias-label-accent,#e6b800) 38%,transparent);color:inherit;border-radius:2px;padding:0 1px}
|
|
256
|
+
mark.dr-mark.active{background:var(--dsw-alias-label-accent,#e6b800);color:#20222a}
|
|
257
|
+
.dr-pdf-doc{display:flex;flex-direction:column;align-items:center;gap:14px;padding:18px 8px 44px}
|
|
258
|
+
.dr-pdf-shell{position:relative;background:#fff;box-shadow:0 4px 18px rgba(0,0,0,.28);border-radius:2px;min-height:40px;min-width:40px}
|
|
259
|
+
.dr-pdf-shell canvas{display:block;border-radius:2px}
|
|
260
|
+
.dr-pdf-shell[data-error]::after{content:attr(data-error);position:absolute;inset:0;display:flex;align-items:center;justify-content:center;font-size:12px;color:#b44;background:#fff;padding:12px;text-align:center}
|
|
261
|
+
.dr-docx-scroll{padding:18px 8px 44px}
|
|
262
|
+
.dr-docx-scroll .docx-wrapper{background:transparent;box-shadow:none;padding:0}
|
|
263
|
+
.dr-docx-inner{background:#fff;box-shadow:0 4px 18px rgba(0,0,0,.28);border-radius:2px;width:max-content;min-width:600px}
|
|
264
|
+
.dr-docx-anchor{position:absolute}
|
|
265
|
+
.dr-image-host{display:flex;min-height:100%;padding:24px;box-sizing:border-box}
|
|
266
|
+
.dr-image-stage{position:relative;padding:14px;border:.5px solid var(--dsw-alias-border-l2);border-radius:6px;background:var(--dsw-alias-bg-layer-2);flex:none;margin:auto}
|
|
267
|
+
.dr-image-stage img{display:block;transform-origin:0 0;user-select:none;-webkit-user-drag:none}
|
|
268
|
+
.dr-editor-shell{display:flex;height:100%;min-height:0;font-family:var(--dsw-font-mono,monospace);font-size:13px;line-height:1.7}
|
|
269
|
+
.dr-editor-lines{flex:none;width:46px;margin:0;padding:12px 8px 40px 0;text-align:right;color:var(--dsw-alias-label-tertiary);background:var(--dsw-alias-bg-layer-2);border-right:.5px solid var(--dsw-alias-border-l1);overflow:hidden;white-space:pre;user-select:none}
|
|
270
|
+
.dr-editor{flex:1;min-width:0;height:100%;box-sizing:border-box;margin:0;padding:12px 16px 40px;border:none;outline:none;resize:none;background:transparent;color:var(--dsw-alias-label-primary);font:inherit;white-space:pre-wrap;word-break:break-word;overflow:auto;--dsh-scrollbar-thumb:var(--dsw-alias-scrollbar-bg-l2}
|
|
271
|
+
.dr-editor:disabled{opacity:.6}
|
|
272
|
+
.dr-toc-head{display:flex;align-items:center;justify-content:space-between;padding:0 4px 6px 8px}
|
|
273
|
+
.dr-toc-collapse{background:none;border:none;color:var(--dsw-alias-label-tertiary);cursor:pointer;padding:2px 6px;border-radius:4px;font-size:12px;display:inline-flex;align-items:center}
|
|
274
|
+
.dr-toc-collapse:hover{color:var(--dsw-alias-label-primary);background:var(--dsw-alias-interactive-bg-hover)}
|
|
275
|
+
.dr-overlay{position:fixed;inset:0;background:rgba(0,0,0,.32);display:flex;align-items:center;justify-content:center;z-index:60}
|
|
276
|
+
.dr-settings{width:340px;background:var(--dsw-alias-bg-layer-1);border:.5px solid var(--dsw-alias-border-l3);border-radius:10px;padding:18px;display:flex;flex-direction:column;gap:14px;box-shadow:0 12px 40px rgba(0,0,0,.3)}
|
|
277
|
+
.dr-settings-title{margin:0;font-size:14px;font-weight:600}
|
|
278
|
+
.dr-set-row{display:grid;grid-template-columns:1fr auto;align-items:center;gap:10px;font-size:12.5px;color:var(--dsw-alias-label-primary)}
|
|
279
|
+
.dr-set-row>span:first-child{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
|
280
|
+
.dr-set-row input[type="number"]{grid-column:2;width:76px;height:26px;box-sizing:border-box;padding:0 8px;font-size:12px;font-family:inherit;color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-layer-2);border:.5px solid var(--dsw-alias-border-l2);border-radius:6px;outline:none;text-align:right;-moz-appearance:textfield;appearance:textfield}
|
|
281
|
+
.dr-set-row input[type="number"]::-webkit-outer-spin-button,.dr-set-row input[type="number"]::-webkit-inner-spin-button{-webkit-appearance:none;margin:0}
|
|
282
|
+
.dr-set-row input[type="number"]:focus{border-color:var(--dsw-alias-border-l3)}
|
|
283
|
+
.dr-set-row .dr-switch{grid-column:2;display:flex;align-items:center}
|
|
284
|
+
.dr-set-row input[type="checkbox"]{width:15px;height:15px;margin:0;accent-color:var(--dsw-alias-label-primary)}
|
|
285
|
+
.dr-settings-actions{display:flex;justify-content:flex-end;gap:8px}
|
|
286
|
+
`;
|
|
287
|
+
|
|
288
|
+
// ---------- icons ----------
|
|
289
|
+
const Glyph = {
|
|
290
|
+
file: (s) => h('svg', { viewBox: '0 0 16 16', width: s, height: s, 'aria-hidden': true },
|
|
291
|
+
h('path', { fill: 'currentColor', d: 'M4 1.5A1.5 1.5 0 0 0 2.5 3v10A1.5 1.5 0 0 0 4 14.5h8A1.5 1.5 0 0 0 13.5 13V5.207L9.793 1.5H4Zm5.5.707L12.793 5.5H9.5V2.207Z' })),
|
|
292
|
+
dir: (s) => h('svg', { viewBox: '0 0 16 16', width: s, height: s, 'aria-hidden': true },
|
|
293
|
+
h('path', { fill: 'currentColor', d: 'M1.5 3A1.5 1.5 0 0 1 3 1.5h3.086a1.5 1.5 0 0 1 1.06.44l.915.914a.5.5 0 0 0 .353.146H13A1.5 1.5 0 0 1 14.5 4.5v8A1.5 1.5 0 0 1 13 14H3a1.5 1.5 0 0 1-1.5-1.5V3Z' })),
|
|
294
|
+
pencil: () => h('svg', { viewBox: '0 0 16 16', 'aria-hidden': true, fill: 'none', stroke: 'currentColor', strokeWidth: 1.3, strokeLinecap: 'round', strokeLinejoin: 'round' },
|
|
295
|
+
h('path', { d: 'm11.8 2.7 1.5 1.5a1.2 1.2 0 0 1 0 1.7L6.2 13H3v-3.2l7.1-7.1a1.2 1.2 0 0 1 1.7 0Z' }),
|
|
296
|
+
h('path', { d: 'm9.6 3.9 2.5 2.5' })),
|
|
297
|
+
quote: (s) => h('svg', { viewBox: '0 0 16 16', width: s, height: s, 'aria-hidden': true, fill: 'currentColor' },
|
|
298
|
+
h('path', { d: 'M4 3h2.2v7.5a2.5 2.5 0 0 1-2.5 2.5H3V11h.7a.7.7 0 0 0 .7-.7V3Zm5.8 0H12v7.5a2.5 2.5 0 0 1-2.5 2.5H8.8V11h.7a.7.7 0 0 0 .7-.7V3Z' })),
|
|
299
|
+
copy: (s) => h('svg', { viewBox: '0 0 16 16', width: s, height: s, 'aria-hidden': true, fill: 'none', stroke: 'currentColor', strokeWidth: 1.3, strokeLinejoin: 'round' },
|
|
300
|
+
h('rect', { x: 5.5, y: 5.5, width: 8, height: 8, rx: 1.5 }),
|
|
301
|
+
h('path', { d: 'M10.5 3.5v-.5A1.5 1.5 0 0 0 9 .5H3.5A1.5 1.5 0 0 0 2 2v6a1.5 1.5 0 0 0 1.5 1.5H4', transform: 'translate(0 1)' })),
|
|
302
|
+
search: (s) => h('svg', { viewBox: '0 0 16 16', width: s, height: s, 'aria-hidden': true, fill: 'none', stroke: 'currentColor', strokeWidth: 1.4, strokeLinecap: 'round' },
|
|
303
|
+
h('circle', { cx: 7, cy: 7, r: 4.2 }),
|
|
304
|
+
h('line', { x1: 10.2, y1: 10.2, x2: 14, y2: 14 })),
|
|
305
|
+
translateG: (s) => h('svg', { viewBox: '0 0 16 16', width: s, height: s, 'aria-hidden': true },
|
|
306
|
+
h('text', { x: 1.5, y: 12, fontSize: 9, fontWeight: 700, fill: 'currentColor', fontFamily: 'Georgia, serif' }, 'A'),
|
|
307
|
+
h('text', { x: 8.5, y: 12, fontSize: 9, fontWeight: 700, fill: 'currentColor', fontFamily: 'inherit' }, '文')),
|
|
308
|
+
sliders: (s) => h('svg', { viewBox: '0 0 24 24', width: s, height: s, 'aria-hidden': true, fill: 'none', stroke: 'currentColor', strokeWidth: 2, strokeLinecap: 'round' },
|
|
309
|
+
h('line', { x1: 4, y1: 21, x2: 4, y2: 14 }), h('line', { x1: 4, y1: 10, x2: 4, y2: 3 }),
|
|
310
|
+
h('line', { x1: 12, y1: 21, x2: 12, y2: 12 }), h('line', { x1: 12, y1: 8, x2: 12, y2: 3 }),
|
|
311
|
+
h('line', { x1: 20, y1: 21, x2: 20, y2: 16 }), h('line', { x1: 20, y1: 12, x2: 20, y2: 3 }),
|
|
312
|
+
h('line', { x1: 1, y1: 14, x2: 7, y2: 14 }), h('line', { x1: 9, y1: 8, x2: 15, y2: 8 }),
|
|
313
|
+
h('line', { x1: 17, y1: 16, x2: 23, y2: 16 })),
|
|
314
|
+
folder: (s) => h('svg', { viewBox: '0 0 16 16', width: s, height: s, 'aria-hidden': true }, h('path', { fill: 'currentColor', d: 'M1.5 3A1.5 1.5 0 0 1 3 1.5h3.086a1.5 1.5 0 0 1 1.06.44l.915.914a.5.5 0 0 0 .353.146H13A1.5 1.5 0 0 1 14.5 4.5v8A1.5 1.5 0 0 1 13 14H3a1.5 1.5 0 0 1-1.5-1.5V3Z' })),
|
|
315
|
+
sidebar: (s) => h('svg', { viewBox: '0 0 16 16', width: s, height: s, 'aria-hidden': true, fill: 'none', stroke: 'currentColor', strokeWidth: 1.3 }, h('rect', { x: 1.8, y: 2.5, width: 12.4, height: 11, rx: 1.6 }), h('line', { x1: 5.6, y1: 2.5, x2: 5.6, y2: 13.5 })) ,
|
|
316
|
+
logo: (s) => h('svg', { viewBox: '0 0 64 64', width: s, height: s, 'aria-hidden': true },
|
|
317
|
+
h('rect', { x: 6, y: 10, width: 40, height: 44, rx: 4, fill: '#4a8fd4' }),
|
|
318
|
+
h('rect', { x: 12, y: 16, width: 30, height: 36, rx: 2, fill: '#f4f8fc' }),
|
|
319
|
+
h('rect', { x: 17, y: 22, width: 20, height: 2.6, rx: 1.3, fill: '#9db8d2' }),
|
|
320
|
+
h('rect', { x: 17, y: 29, width: 20, height: 2.6, rx: 1.3, fill: '#9db8d2' }),
|
|
321
|
+
h('rect', { x: 17, y: 36, width: 12, height: 2.6, rx: 1.3, fill: '#9db8d2' }),
|
|
322
|
+
h('path', { d: 'M14 10c4-3 9-3 13 0v44c-4-3-9-3-13 0z', fill: '#3a76b0', opacity: .9 }),
|
|
323
|
+
h('circle', { cx: 46, cy: 42, r: 11, fill: '#fff', stroke: '#2f5f8f', 'stroke-width': 3 }),
|
|
324
|
+
h('line', { x1: 54, y1: 50, x2: 60, y2: 56, stroke: '#2f5f8f', 'stroke-width': 4, 'stroke-linecap': 'round' }),
|
|
325
|
+
h('circle', { cx: 46, cy: 42, r: 6, fill: 'none', stroke: '#4a8fd4', 'stroke-width': 2.4 })),
|
|
326
|
+
};
|
|
327
|
+
const kindGlyph = (kind, s = 14) => {
|
|
328
|
+
if (kind === 'pdf') return h('svg', { viewBox: '0 0 16 16', width: s, height: s, 'aria-hidden': true }, h('path', { fill: '#c0504d', d: 'M4 1.5A1.5 1.5 0 0 0 2.5 3v10A1.5 1.5 0 0 0 4 14.5h8A1.5 1.5 0 0 0 13.5 13V5.2L9.8 1.5H4Zm6 .7L12.8 5.5H10V2.2ZM5.6 8.2h1c.2 1.4.5 2.4.9 3 .2-1.2.3-2.4.4-3.7l1.2-.1c-.1 1.9-.4 3.5-.8 4.9-.3 1.1-.9 1.8-1.7 2.1l-.7-1c.5-.2.9-.6 1.1-1.1-.5-.8-.9-2-1.2-3.4l-.2-.7Z' }));
|
|
329
|
+
if (kind === 'markdown') return h('svg', { viewBox: '0 0 16 16', width: s, height: s, 'aria-hidden': true }, h('path', { fill: '#4a7db5', d: 'M2.5 4h11A1.5 1.5 0 0 1 15 5.5v5A1.5 1.5 0 0 1 13.5 12h-11A1.5 1.5 0 0 1 1 10.5v-5A1.5 1.5 0 0 1 2.5 4Zm1.2 6h1.4V7.2l1.3 1.6 1.3-1.6V10h1.4V6H8.1L6.4 8 4.7 6H3.7v4Zm7.5 0h1.5V6h-1.5L10 7.5 10.7 8.6 11.2 8v2Z' }));
|
|
330
|
+
if (kind === 'docx') return h('svg', { viewBox: '0 0 16 16', width: s, height: s, 'aria-hidden': true }, h('path', { fill: '#3a6ea5', d: 'M9 1H3.5A1.5 1.5 0 0 0 2 2.5v11A1.5 1.5 0 0 0 3.5 15h9a1.5 1.5 0 0 0 1.5-1.5V6L9 1Zm0 1.7L12.4 6H9V2.7ZM5.2 11.8c.8-.5 1.3-1.2 1.7-2.2.2.9.5 1.7.9 2.3l-.9.6c-.2-.4-.4-.9-.6-1.5-.3.6-.6 1.1-1 1.5l-.9-.4.8-1.9H4.4v-.9h1.7L5.2 7l.8-.3.4 1.2h.8l.4-1.2.8.3-.4 1.2h1.4v.9H8.7l.7 1.8c.3-.5.5-1 .7-1.6l.9.5c-.3.7-.6 1.3-1 1.8.4.3.8.5 1.3.6l-.5 1c-.7-.2-1.3-.5-1.8-1-.5.4-1.1.7-1.8.9l-.4-.9Z' }));
|
|
331
|
+
if (kind === 'image') return h('svg', { viewBox: '0 0 16 16', width: s, height: s, 'aria-hidden': true }, h('path', { fill: '#5b8c5a', d: 'M2.5 3h11A1.5 1.5 0 0 1 15 4.5v7a1.5 1.5 0 0 1-1.5 1.5h-11A1.5 1.5 0 0 1 1 11.5v-7A1.5 1.5 0 0 1 2.5 3Zm0 1.5v5.1l2.6-2.6 2 2L9.8 6l3.7 3.7v-5a.1.1 0 0 0-.1-.2H2.6a.1.1 0 0 0-.1.2ZM5.5 6a1 1 0 1 0 0-2 1 1 0 0 0 0 2Z' }));
|
|
332
|
+
if (kind === 'office') return h('svg', { viewBox: '0 0 16 16', width: s, height: s, 'aria-hidden': true },
|
|
333
|
+
h('rect', { fill: '#d9730d', rx: 2.5, x: 1, y: 1, width: 14, height: 14 }),
|
|
334
|
+
h('path', { fill: '#fff', d: 'M3.5 5.5h4.4v1.2H6.6v4.3H5V6.7H3.5v-1.2Zm5.6 0h1.5l1 1.9 1-1.9H14l-1.7 3 1.8 3.4h-1.6l-1.1-2-1.1 2H7.9L9.7 8.6 8 5.5Z' }));
|
|
335
|
+
return Glyph.file(s);
|
|
336
|
+
};
|
|
337
|
+
|
|
338
|
+
// ---------- shared bits ----------
|
|
339
|
+
const Btn = ({ title, onClick, disabled, pressed, children, icon, instantTip, ...rest }) => h('button', {
|
|
340
|
+
className: `dr-btn${icon ? ' dr-btn--icon' : ''}`,
|
|
341
|
+
title: instantTip ? undefined : title, // instant tooltip replaces the delayed native one
|
|
342
|
+
'aria-label': title, 'aria-pressed': pressed,
|
|
343
|
+
...rest, onClick, disabled,
|
|
344
|
+
}, children);
|
|
345
|
+
|
|
346
|
+
/** Instant hover tooltip (shared). Native `title` has a ~1s browser delay,
|
|
347
|
+
* which reads as "broken" on small icon buttons — render a fixed-position
|
|
348
|
+
* div instead, styled with the platform's dark tooltip tokens (same look
|
|
349
|
+
* as the app's own bubbles: high contrast, reads as a floating overlay).
|
|
350
|
+
* The div is appended directly to document.body (imperative DOM, no
|
|
351
|
+
* react-dom dependency) at max z-index: app-shell ancestors of the panel
|
|
352
|
+
* (transforms/containment in the layout) turn `position:fixed` into
|
|
353
|
+
* container-relative coordinates and stack it under sibling layers — at
|
|
354
|
+
* body level it is true-viewport and above every in-panel layer.
|
|
355
|
+
* `anchor`: 'above' (default) | 'below' (selection bar over document
|
|
356
|
+
* content) | 'left' | 'right' (beside the button, vertically centered —
|
|
357
|
+
* the pattern the platform's own side-panel toggles use; the toolbar's
|
|
358
|
+
* right-side icons anchor left, the left-most rename button anchors
|
|
359
|
+
* right). After mounting, the bubble is clamped into the viewport, and
|
|
360
|
+
* above-placement is pushed down when there is no headroom. mouseover/out
|
|
361
|
+
* (bubbling) delegate reliably everywhere; the relatedTarget guard skips
|
|
362
|
+
* moves between the button and its own svg glyph so the tooltip never
|
|
363
|
+
* flickers. */
|
|
364
|
+
function useTip(anchor = 'above') {
|
|
365
|
+
const [tip, setTip] = useState(null); // { text, x, y } viewport coords
|
|
366
|
+
// `xFrom` (optional, side anchors): (el) => element whose edge replaces
|
|
367
|
+
// the hovered element's for the X coordinate — the toolbar's right-side
|
|
368
|
+
// icons pass the path input so ALL their bubbles share ONE fixed slot:
|
|
369
|
+
// the bubble's right border sits EXACTLY on the input's right border,
|
|
370
|
+
// whichever of the three icons is hovered. A detached/zero-size anchor
|
|
371
|
+
// (mid-remount hover) falls back to an 8px gap beside the hovered
|
|
372
|
+
// element, and callers back the ref with a live DOM re-query.
|
|
373
|
+
const place = (el, text, xFrom) => {
|
|
374
|
+
const r = el.getBoundingClientRect();
|
|
375
|
+
let xr = null;
|
|
376
|
+
try { const t = xFrom?.(el); const tr = t?.getBoundingClientRect?.(); if (tr && tr.width > 0) xr = tr; } catch { /* anchor unavailable */ }
|
|
377
|
+
const x = anchor === 'left' ? (xr ? xr.right : r.left - 8) : anchor === 'right' ? (xr ? xr.left : r.right + 8) : r.left + r.width / 2;
|
|
378
|
+
const y = (anchor === 'left' || anchor === 'right') ? r.top + r.height / 2 : anchor === 'below' ? r.bottom + 6 : r.top;
|
|
379
|
+
// dedupe: mouseover re-fires when the cursor crosses the button's
|
|
380
|
+
// own svg glyph (bubbling) — an unchanged {text,x,y} must not
|
|
381
|
+
// re-render, or the tooltip element is destroyed and recreated on
|
|
382
|
+
// every internal move (DOM churn + visible flicker).
|
|
383
|
+
setTip((prev) => (prev && prev.text === text && prev.x === x && prev.y === y) ? prev : { text, x, y });
|
|
384
|
+
};
|
|
385
|
+
const hoverProps = (text, xFrom) => ({
|
|
386
|
+
onMouseOver: (ev) => place(ev.currentTarget, text, xFrom),
|
|
387
|
+
onMouseOut: (ev) => { if (!ev.currentTarget.contains(ev.relatedTarget)) setTip(null); },
|
|
388
|
+
onFocus: (ev) => place(ev.currentTarget, text, xFrom),
|
|
389
|
+
onBlur: () => setTip(null),
|
|
390
|
+
});
|
|
391
|
+
useEffect(() => {
|
|
392
|
+
if (!tip) return undefined;
|
|
393
|
+
const variant = { below: 'dr-tip--below', left: 'dr-tip--side-l', right: 'dr-tip--side-r' }[anchor] ?? '';
|
|
394
|
+
const el = document.createElement('div');
|
|
395
|
+
el.className = `dr-tip${variant ? ` ${variant}` : ''}`;
|
|
396
|
+
el.style.left = `${tip.x}px`;
|
|
397
|
+
el.style.top = `${tip.y}px`;
|
|
398
|
+
el.textContent = tip.text;
|
|
399
|
+
document.body.appendChild(el);
|
|
400
|
+
// clamp into the viewport AFTER mounting (needs real metrics).
|
|
401
|
+
// anchor-aware: for side-l `x` is the bubble's RIGHT edge (the
|
|
402
|
+
// shared slot line) — only the LEFT edge may need protecting, so
|
|
403
|
+
// max-x is vw-4, NOT vw-w-4 (the old form pulled long-label
|
|
404
|
+
// bubbles off the slot line whenever the panel sat near the
|
|
405
|
+
// window's right edge, breaking the right-border alignment).
|
|
406
|
+
// side-r's x is the LEFT edge; centered anchors are midpoints.
|
|
407
|
+
const w = el.offsetWidth, hh = el.offsetHeight;
|
|
408
|
+
const vw = document.documentElement?.clientWidth || window.innerWidth || 0;
|
|
409
|
+
if (w && vw) {
|
|
410
|
+
const minX = anchor === 'left' ? w + 4 : anchor === 'right' ? 4 : w / 2 + 4;
|
|
411
|
+
const maxX = Math.max(minX, anchor === 'left' ? vw - 4 : anchor === 'right' ? vw - w - 4 : vw - w / 2 - 4);
|
|
412
|
+
const x = Math.min(Math.max(tip.x, minX), maxX);
|
|
413
|
+
if (x !== tip.x) el.style.left = `${x}px`;
|
|
414
|
+
}
|
|
415
|
+
if (anchor === 'above' && hh && tip.y - hh - 6 < 4) el.style.top = `${hh + 10}px`;
|
|
416
|
+
return () => { el.remove(); };
|
|
417
|
+
}, [tip, anchor]);
|
|
418
|
+
return { hoverProps, hide: () => setTip(null), node: null };
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
function ViewBar({ children }) {
|
|
422
|
+
return h('div', { className: 'dr-viewbar' }, children);
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/** Scroll-position persistence for a scroll container, per path.
|
|
426
|
+
* `enabled` must be false while the scroll container is not mounted
|
|
427
|
+
* (loading / edit mode): the container only appears after async content
|
|
428
|
+
* is ready, so a mount-time-only effect would bind to nothing. */
|
|
429
|
+
function useScrollRestore(path, scrollRef, extra, enabled = true) {
|
|
430
|
+
const extraRef = useRef(extra);
|
|
431
|
+
extraRef.current = extra;
|
|
432
|
+
useEffect(() => {
|
|
433
|
+
if (!enabled) return undefined;
|
|
434
|
+
const el = scrollRef.current;
|
|
435
|
+
if (!el) return undefined;
|
|
436
|
+
const saved = getPos(path);
|
|
437
|
+
if (saved && typeof saved.scrollTop === 'number') {
|
|
438
|
+
requestAnimationFrame(() => { el.scrollTop = saved.scrollTop; });
|
|
439
|
+
}
|
|
440
|
+
let timer;
|
|
441
|
+
const onScroll = () => {
|
|
442
|
+
clearTimeout(timer);
|
|
443
|
+
timer = setTimeout(() => savePos(path, { ...extraRef.current(), scrollTop: Math.round(el.scrollTop) }), 300);
|
|
444
|
+
};
|
|
445
|
+
el.addEventListener('scroll', onScroll, { passive: true });
|
|
446
|
+
return () => {
|
|
447
|
+
clearTimeout(timer);
|
|
448
|
+
el.removeEventListener('scroll', onScroll);
|
|
449
|
+
// flush the very last position instead of losing the final <300ms —
|
|
450
|
+
// but never persist a zero from an already-emptied container
|
|
451
|
+
if (el.scrollHeight > el.clientHeight + 50) {
|
|
452
|
+
savePos(path, { ...extraRef.current(), scrollTop: Math.round(el.scrollTop) });
|
|
453
|
+
}
|
|
454
|
+
};
|
|
455
|
+
}, [path, enabled]);
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
// ---------- DOM search (markdown / text) ----------
|
|
459
|
+
const MAX_MARKS = 5000;
|
|
460
|
+
/**
|
|
461
|
+
* Installs a TreeWalker highlighter over `contentRef`.
|
|
462
|
+
* Returns { run(query, dir), clear() } operating on the live DOM.
|
|
463
|
+
* Callbacks are kept in refs so `run`/`clear` identities are stable —
|
|
464
|
+
* otherwise a parent re-render re-runs the cleanup and wipes highlights.
|
|
465
|
+
*/
|
|
466
|
+
function useDomSearch(contentRef, onCount, onStatus, t) {
|
|
467
|
+
const marksRef = useRef([]);
|
|
468
|
+
const indexRef = useRef(-1);
|
|
469
|
+
const activeRef = useRef(null);
|
|
470
|
+
const onCountRef = useRef(onCount);
|
|
471
|
+
onCountRef.current = onCount;
|
|
472
|
+
const onStatusRef = useRef(onStatus);
|
|
473
|
+
onStatusRef.current = onStatus;
|
|
474
|
+
const tRef = useRef(t);
|
|
475
|
+
tRef.current = t;
|
|
476
|
+
const setActive = (mark) => {
|
|
477
|
+
if (activeRef.current && activeRef.current.parentNode) activeRef.current.classList.remove('active');
|
|
478
|
+
activeRef.current = mark;
|
|
479
|
+
mark.classList.add('active');
|
|
480
|
+
mark.scrollIntoView({ block: 'center', behavior: 'smooth' });
|
|
481
|
+
};
|
|
482
|
+
const clear = useCallback(() => {
|
|
483
|
+
for (const mark of marksRef.current) {
|
|
484
|
+
const parent = mark.parentNode;
|
|
485
|
+
if (!parent) continue;
|
|
486
|
+
parent.replaceChild(document.createTextNode(mark.textContent || ''), mark);
|
|
487
|
+
parent.normalize();
|
|
488
|
+
}
|
|
489
|
+
marksRef.current = [];
|
|
490
|
+
indexRef.current = -1;
|
|
491
|
+
activeRef.current = null;
|
|
492
|
+
onCountRef.current?.(0, -1);
|
|
493
|
+
}, []);
|
|
494
|
+
const run = useCallback((query, dir) => {
|
|
495
|
+
const root = contentRef.current;
|
|
496
|
+
if (!root) return;
|
|
497
|
+
if (marksRef.current.length || indexRef.current >= 0) clear();
|
|
498
|
+
const needle = query.trim();
|
|
499
|
+
if (!needle) return;
|
|
500
|
+
const matcher = new RegExp(needle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi');
|
|
501
|
+
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {
|
|
502
|
+
acceptNode(node) {
|
|
503
|
+
if (!node.nodeValue || !node.nodeValue.trim()) return NodeFilter.FILTER_REJECT;
|
|
504
|
+
const parent = node.parentElement;
|
|
505
|
+
if (!parent || parent.closest('mark.dr-mark,style,script,noscript')) return NodeFilter.FILTER_REJECT;
|
|
506
|
+
return NodeFilter.FILTER_ACCEPT;
|
|
507
|
+
},
|
|
508
|
+
});
|
|
509
|
+
const nodes = [];
|
|
510
|
+
while (walker.nextNode()) nodes.push(walker.currentNode);
|
|
511
|
+
matcher.lastIndex = 0;
|
|
512
|
+
let truncated = false;
|
|
513
|
+
for (const node of nodes) {
|
|
514
|
+
if (truncated) break;
|
|
515
|
+
const value = node.nodeValue;
|
|
516
|
+
if (!value || !matcher.test(value)) continue;
|
|
517
|
+
matcher.lastIndex = 0;
|
|
518
|
+
const fragment = document.createDocumentFragment();
|
|
519
|
+
let last = 0;
|
|
520
|
+
let match;
|
|
521
|
+
while ((match = matcher.exec(value)) !== null) {
|
|
522
|
+
if (marksRef.current.length >= MAX_MARKS) { truncated = true; break; }
|
|
523
|
+
if (match.index > last) fragment.appendChild(document.createTextNode(value.slice(last, match.index)));
|
|
524
|
+
const mark = document.createElement('mark');
|
|
525
|
+
mark.className = 'dr-mark';
|
|
526
|
+
mark.textContent = value.slice(match.index, match.index + match[0].length);
|
|
527
|
+
fragment.appendChild(mark);
|
|
528
|
+
marksRef.current.push(mark);
|
|
529
|
+
last = match.index + match[0].length;
|
|
530
|
+
}
|
|
531
|
+
if (last < value.length) fragment.appendChild(document.createTextNode(value.slice(last)));
|
|
532
|
+
node.parentNode.replaceChild(fragment, node);
|
|
533
|
+
}
|
|
534
|
+
if (truncated) onStatusRef.current?.(tRef.current('panel.searchTruncated'));
|
|
535
|
+
if (marksRef.current.length === 0) { onCountRef.current?.(0, -1); return; }
|
|
536
|
+
const total = marksRef.current.length;
|
|
537
|
+
const focus = (index) => {
|
|
538
|
+
const normalized = ((index % total) + total) % total;
|
|
539
|
+
indexRef.current = normalized;
|
|
540
|
+
setActive(marksRef.current[normalized]);
|
|
541
|
+
onCountRef.current?.(total, normalized);
|
|
542
|
+
};
|
|
543
|
+
focus(dir < 0 ? total - 1 : 0);
|
|
544
|
+
}, []);
|
|
545
|
+
useEffect(() => clear, [clear]);
|
|
546
|
+
return {
|
|
547
|
+
run,
|
|
548
|
+
clear,
|
|
549
|
+
navigate: (dir) => {
|
|
550
|
+
if (marksRef.current.length === 0) return;
|
|
551
|
+
const total = marksRef.current.length;
|
|
552
|
+
const next = indexRef.current < 0 ? 0 : indexRef.current + dir;
|
|
553
|
+
const normalized = ((next % total) + total) % total;
|
|
554
|
+
indexRef.current = normalized;
|
|
555
|
+
setActive(marksRef.current[normalized]);
|
|
556
|
+
onCountRef.current?.(total, normalized);
|
|
557
|
+
},
|
|
558
|
+
};
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
function SearchControls({ t, query, setQuery, count, index, onEnter, onPrev, onNext, disabled }) {
|
|
562
|
+
return h(React.Fragment, null,
|
|
563
|
+
h('input', {
|
|
564
|
+
type: 'search', value: query, placeholder: t('panel.search'), disabled,
|
|
565
|
+
onChange: (e) => setQuery(e.target.value),
|
|
566
|
+
onKeyDown: (e) => { if (e.key === 'Enter' && !e.isComposing && e.keyCode !== 229) { e.preventDefault(); onEnter(e.shiftKey ? -1 : 1); } },
|
|
567
|
+
}),
|
|
568
|
+
h(Btn, { title: t('panel.searchPrev'), onClick: onPrev, disabled: disabled || count === 0 }, '‹'),
|
|
569
|
+
h(Btn, { title: t('panel.searchNext'), onClick: onNext, disabled: disabled || count === 0 }, '›'),
|
|
570
|
+
h('span', { className: 'dr-count' }, count > 0 ? `${index + 1}/${count}` : (query ? '0/0' : '')));
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
// ---------- Markdown ----------
|
|
574
|
+
const MD_PLAIN_THRESHOLD = 4 * 1024 * 1024;
|
|
575
|
+
// one shared markdown-it instance; per-document state travels via env
|
|
576
|
+
/** Visual Y of `offset` inside a textarea: mirror its styles in an
|
|
577
|
+
* offscreen div and measure a marker (soft-wrap accurate). Returns null
|
|
578
|
+
* when the prefix is too large to mirror. */
|
|
579
|
+
function measureTextareaTop(el, text, offset) {
|
|
580
|
+
if (offset > 256 * 1024) return null;
|
|
581
|
+
const doc = el.ownerDocument;
|
|
582
|
+
const mirror = doc.createElement('div');
|
|
583
|
+
const cs = getComputedStyle(el);
|
|
584
|
+
for (const prop of ['fontFamily', 'fontSize', 'fontWeight', 'lineHeight', 'letterSpacing', 'paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft', 'boxSizing', 'whiteSpace', 'wordWrap', 'overflowWrap', 'wordBreak', 'tabSize', 'width']) {
|
|
585
|
+
mirror.style[prop] = cs[prop];
|
|
586
|
+
}
|
|
587
|
+
mirror.style.position = 'absolute';
|
|
588
|
+
mirror.style.visibility = 'hidden';
|
|
589
|
+
mirror.style.left = '-9999px';
|
|
590
|
+
mirror.style.top = '0';
|
|
591
|
+
mirror.textContent = text.slice(0, offset);
|
|
592
|
+
const mark = doc.createElement('span');
|
|
593
|
+
mark.textContent = '\u200b';
|
|
594
|
+
mirror.appendChild(mark);
|
|
595
|
+
doc.body.appendChild(mirror);
|
|
596
|
+
const top = mark.offsetTop;
|
|
597
|
+
mirror.remove();
|
|
598
|
+
return Number.isFinite(top) ? top : null;
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
/** Heading outline straight from the draft text (edit mode): one line per
|
|
602
|
+
* heading, carrying its character offset for editor jump targets. */
|
|
603
|
+
function extractDraftOutline(text) {
|
|
604
|
+
if (!text) return [];
|
|
605
|
+
const items = [];
|
|
606
|
+
let offset = 0;
|
|
607
|
+
for (const line of text.split('\n')) {
|
|
608
|
+
const match = /^(#{1,6})\s+(.*)$/u.exec(line);
|
|
609
|
+
if (match) items.push({ level: match[1].length, text: match[2].trim(), id: `ln-${offset}`, lineOffset: offset });
|
|
610
|
+
offset += line.length + 1;
|
|
611
|
+
if (items.length >= 300) break; // cap pathological documents
|
|
612
|
+
}
|
|
613
|
+
return items;
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
|
|
617
|
+
let mdPromise = null;
|
|
618
|
+
function getMarkdownIt() {
|
|
619
|
+
mdPromise ??= loadVendor().then((vendor) => {
|
|
620
|
+
const md = new vendor.MarkdownIt({ html: false, linkify: false, typographer: false, breaks: true });
|
|
621
|
+
const defaultImage = md.renderer.rules.image;
|
|
622
|
+
md.renderer.rules.image = (tokens, idx, options, env, self) => {
|
|
623
|
+
const token = tokens[idx];
|
|
624
|
+
const srcAttr = token.attrGet('src');
|
|
625
|
+
if (srcAttr && env?.dir) {
|
|
626
|
+
const resolved = joinDir(env.dir, srcAttr);
|
|
627
|
+
if (resolved && kindOf(resolved) === 'image') {
|
|
628
|
+
token.attrSet('src', FILE_URL(resolved));
|
|
629
|
+
token.attrSet('loading', 'lazy');
|
|
630
|
+
token.attrSet('decoding', 'async');
|
|
631
|
+
} else {
|
|
632
|
+
// remote/unsupported src: never let the document make network requests
|
|
633
|
+
token.attrSet('src', 'data:image/gif;base64,R0lGODlhAQABAAAAACw=');
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
return defaultImage(tokens, idx, options, env, self);
|
|
637
|
+
};
|
|
638
|
+
md.renderer.rules.heading_open = (tokens, idx, options, env, self) => {
|
|
639
|
+
const level = Number.parseInt(tokens[idx].tag.slice(1), 10);
|
|
640
|
+
const headingText = (tokens[idx + 1]?.content ?? '').trim();
|
|
641
|
+
const id = slugify(headingText, env?.occurrences ?? new Map());
|
|
642
|
+
tokens[idx].attrSet('id', id);
|
|
643
|
+
if (level >= 1 && level <= 6) env?.outline?.push({ level, text: headingText, id });
|
|
644
|
+
return self.renderToken(tokens, idx, options);
|
|
645
|
+
};
|
|
646
|
+
return md;
|
|
647
|
+
}).catch((error) => { mdPromise = null; throw error; });
|
|
648
|
+
return mdPromise;
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
function MarkdownView({ path, settings, t, onStatus, onSidebar, onOpen, sidebar, onEditingChange }) {
|
|
652
|
+
const [state, setState] = useState({ status: 'loading' });
|
|
653
|
+
const [fontSize, setFontSize] = useState(() => {
|
|
654
|
+
const pos = getPos(path);
|
|
655
|
+
return (pos && pos.kind === 'markdown' && typeof pos.fontSize === 'number') ? pos.fontSize : settings.fontSize;
|
|
656
|
+
});
|
|
657
|
+
const [query, setQuery] = useState('');
|
|
658
|
+
const [count, setCount] = useState(0);
|
|
659
|
+
const [index, setIndex] = useState(-1);
|
|
660
|
+
const [renderError, setRenderError] = useState(null);
|
|
661
|
+
const bodyRef = useRef(null);
|
|
662
|
+
const scrollRef = useRef(null);
|
|
663
|
+
const search = useDomSearch(bodyRef, (total, idx) => { setCount(total); setIndex(idx); }, onStatus, t);
|
|
664
|
+
const dir = useMemo(() => path.slice(0, path.lastIndexOf('/')) || '/', [path]);
|
|
665
|
+
const text = state.status === 'ready' ? state.text : null;
|
|
666
|
+
|
|
667
|
+
useEffect(() => { let alive = true; setState({ status: 'loading' });
|
|
668
|
+
const controller = new AbortController();
|
|
669
|
+
fetchFile(path, 'text', controller.signal)
|
|
670
|
+
.then((src) => { if (alive) setState({ status: 'ready', text: src }); })
|
|
671
|
+
.catch((e) => { if (alive && e?.name !== 'AbortError') setState({ status: 'error', message: e.message }); });
|
|
672
|
+
return () => { alive = false; controller.abort(); };
|
|
673
|
+
}, [path]);
|
|
674
|
+
|
|
675
|
+
// render markdown (reruns after edits save new text)
|
|
676
|
+
const rendered = useMemo(() => {
|
|
677
|
+
if (text === null) return null;
|
|
678
|
+
// giant markdown: markdown-it must parse the whole document; degrade to
|
|
679
|
+
// chunked plain text instead of a multi-second freeze + million-node DOM
|
|
680
|
+
if (text.length > MD_PLAIN_THRESHOLD) return Promise.resolve({ html: null, outline: [], plain: true });
|
|
681
|
+
return getMarkdownIt().then((md) => {
|
|
682
|
+
const outline = [];
|
|
683
|
+
const occurrences = new Map();
|
|
684
|
+
const html = md.render(text, { dir, outline, occurrences });
|
|
685
|
+
return { html, outline };
|
|
686
|
+
});
|
|
687
|
+
}, [text, dir]);
|
|
688
|
+
const [renderedState, setRenderedState] = useState(null);
|
|
689
|
+
useEffect(() => {
|
|
690
|
+
if (rendered === null) { setRenderedState(null); return; }
|
|
691
|
+
let alive = true;
|
|
692
|
+
rendered.then((r) => { if (alive) { setRenderedState(r); setRenderError(null); } })
|
|
693
|
+
.catch((e) => { if (alive) setRenderError(e?.message ?? String(e)); });
|
|
694
|
+
return () => { alive = false; };
|
|
695
|
+
}, [rendered]);
|
|
696
|
+
|
|
697
|
+
const outlineModel = useCallback((outline) => ({
|
|
698
|
+
kind: 'outline',
|
|
699
|
+
items: outline,
|
|
700
|
+
go: (id) => bodyRef.current?.querySelector(`[id="${CSS.escape(id)}"], a[name="${CSS.escape(id)}"]`)?.scrollIntoView({ behavior: 'smooth', block: 'start' }),
|
|
701
|
+
}), []);
|
|
702
|
+
useEffect(() => {
|
|
703
|
+
if (renderedState) onSidebar(renderedState.outline.length > 0 ? outlineModel(renderedState.outline) : null);
|
|
704
|
+
return () => onSidebar(null);
|
|
705
|
+
}, [renderedState]);
|
|
706
|
+
|
|
707
|
+
// link guards: external -> new window; .md relative -> open; anchors -> scroll
|
|
708
|
+
useEffect(() => {
|
|
709
|
+
const root = bodyRef.current;
|
|
710
|
+
if (!root || !renderedState) return;
|
|
711
|
+
const onClick = (event) => {
|
|
712
|
+
const anchor = event.target.closest('a[href]');
|
|
713
|
+
if (!anchor) return;
|
|
714
|
+
const href = anchor.getAttribute('href') || '';
|
|
715
|
+
if (/^javascript:/iu.test(href)) { event.preventDefault(); return; }
|
|
716
|
+
if (/^https?:/iu.test(href)) { event.preventDefault(); window.open(href, '_blank', 'noopener,noreferrer'); return; }
|
|
717
|
+
if (href.startsWith('#')) {
|
|
718
|
+
event.preventDefault();
|
|
719
|
+
let id = href.slice(1);
|
|
720
|
+
try { id = decodeURIComponent(id); } catch { /* keep raw */ }
|
|
721
|
+
root.querySelector(`[id="${CSS.escape(id)}"], a[name="${CSS.escape(id)}"]`)?.scrollIntoView({ behavior: 'smooth', block: 'start' });
|
|
722
|
+
return;
|
|
723
|
+
}
|
|
724
|
+
const resolved = joinDir(dir, href);
|
|
725
|
+
if (resolved && kindOf(resolved)) {
|
|
726
|
+
event.preventDefault();
|
|
727
|
+
onOpen(resolved);
|
|
728
|
+
}
|
|
729
|
+
};
|
|
730
|
+
root.addEventListener('click', onClick);
|
|
731
|
+
return () => root.removeEventListener('click', onClick);
|
|
732
|
+
}, [renderedState, dir]);
|
|
733
|
+
|
|
734
|
+
const editor = useEditMode({
|
|
735
|
+
path,
|
|
736
|
+
currentText: text ?? '',
|
|
737
|
+
onSaved: (next) => setState({ status: 'ready', text: next }),
|
|
738
|
+
t, onStatus,
|
|
739
|
+
});
|
|
740
|
+
// lift the editing flag to the panel: an external-change event must not
|
|
741
|
+
// clobber an active editor, it shows a conflict bar instead
|
|
742
|
+
useEffect(() => {
|
|
743
|
+
onEditingChange?.(editor.editing);
|
|
744
|
+
return () => onEditingChange?.(false);
|
|
745
|
+
}, [editor.editing, onEditingChange]);
|
|
746
|
+
const [editorQuery, setEditorQuery] = useState('');
|
|
747
|
+
const editorSearch = useEditorSearch(editor.editing ? editor.draft : '');
|
|
748
|
+
// edit mode: live outline from the debounced draft, same sidebar as preview
|
|
749
|
+
const [outlineDraft, setOutlineDraft] = useState(null);
|
|
750
|
+
useEffect(() => {
|
|
751
|
+
if (!editor.editing) { setOutlineDraft(null); return undefined; }
|
|
752
|
+
const timer = setTimeout(() => setOutlineDraft(editor.draft), 300);
|
|
753
|
+
return () => clearTimeout(timer);
|
|
754
|
+
}, [editor.editing, editor.draft]);
|
|
755
|
+
const draftOutline = useMemo(() => (editor.editing && outlineDraft !== null ? extractDraftOutline(outlineDraft) : null), [editor.editing, outlineDraft]);
|
|
756
|
+
const gotoDraftHeading = (item) => {
|
|
757
|
+
const el = editorSearch.areaRef.current;
|
|
758
|
+
if (!el || typeof item.lineOffset !== 'number') return;
|
|
759
|
+
el.focus();
|
|
760
|
+
el.setSelectionRange(item.lineOffset, item.lineOffset);
|
|
761
|
+
const top = measureTextareaTop(el, editor.draft, item.lineOffset);
|
|
762
|
+
if (top !== null) el.scrollTop = Math.max(0, Math.round(top - el.clientHeight / 2));
|
|
763
|
+
else {
|
|
764
|
+
const line = (editor.draft.slice(0, item.lineOffset).match(/\n/g) ?? []).length;
|
|
765
|
+
const lineH = parseFloat(getComputedStyle(el).lineHeight) || 22;
|
|
766
|
+
el.scrollTop = Math.max(0, Math.round(line * lineH - el.clientHeight / 2));
|
|
767
|
+
}
|
|
768
|
+
};
|
|
769
|
+
useEffect(() => {
|
|
770
|
+
if (editor.editing) {
|
|
771
|
+
// during the debounce window the draft outline is not ready yet —
|
|
772
|
+
// keep the preview outline mounted instead of flashing empty
|
|
773
|
+
if (draftOutline === null) return;
|
|
774
|
+
onSidebar(draftOutline.length > 0
|
|
775
|
+
? { kind: 'outline', items: draftOutline, go: (id) => gotoDraftHeading(draftOutline.find((x) => x.id === id)) }
|
|
776
|
+
: null);
|
|
777
|
+
} else if (renderedState) onSidebar(renderedState.outline.length > 0 ? outlineModel(renderedState.outline) : null);
|
|
778
|
+
}, [editor.editing, draftOutline, renderedState]);
|
|
779
|
+
|
|
780
|
+
// bind scroll persistence only once the scroll container actually
|
|
781
|
+
// exists (it mounts with the rendered content, after async fetch)
|
|
782
|
+
const mdChunks = useMemo(() => (renderedState?.plain ? splitTextChunks(text ?? '') : null), [renderedState, text]);
|
|
783
|
+
const mdReady = state.status === 'ready' && !!renderedState && !editor.editing;
|
|
784
|
+
useScrollRestore(path, scrollRef, () => ({ kind: 'markdown', fontSize }), mdReady);
|
|
785
|
+
|
|
786
|
+
if (state.status === 'error') return h('div', { className: 'dr-error' }, `${t('panel.error')}: ${state.message}`);
|
|
787
|
+
if (renderError) return h('div', { className: 'dr-error' }, `${t('panel.error')}: ${renderError} — ${t('panel.retryHint')}`);
|
|
788
|
+
if (state.status !== 'ready' || !renderedState) return h('div', { className: 'dr-load' }, t('panel.loading'));
|
|
789
|
+
return h(React.Fragment, null,
|
|
790
|
+
h(ViewBar, null,
|
|
791
|
+
editor.editing
|
|
792
|
+
? h(React.Fragment, null,
|
|
793
|
+
h(SearchControls, { t, query: editorQuery, setQuery: setEditorQuery, count: editorSearch.count, index: editorSearch.index,
|
|
794
|
+
onEnter: (dirn) => (editorQuery.trim() ? editorSearch.run(editorQuery, dirn) : undefined),
|
|
795
|
+
onPrev: () => editorSearch.navigate(-1), onNext: () => editorSearch.navigate(1) }),
|
|
796
|
+
h('span', { style: { flex: 1 } }),
|
|
797
|
+
h(EditControls, { t, editing: true, dirty: editor.dirty, busy: editor.busy, onEnter: editor.enter, onExit: editor.exit, onSave: editor.save }))
|
|
798
|
+
: h(React.Fragment, null,
|
|
799
|
+
h(SearchControls, { t, query, setQuery, count, index,
|
|
800
|
+
onEnter: (dirn) => (query.trim() ? search.run(query, dirn) : search.clear()),
|
|
801
|
+
onPrev: () => search.navigate(-1), onNext: () => search.navigate(1) }),
|
|
802
|
+
h('span', { style: { flex: 1 } }),
|
|
803
|
+
h(Btn, { title: t('panel.fontSmaller'), onClick: () => setFontSize((s) => Math.max(10, s - 1)) }, 'A−'),
|
|
804
|
+
h('span', { className: 'dr-badge' }, `${fontSize}px`),
|
|
805
|
+
h(Btn, { title: t('panel.fontBigger'), onClick: () => setFontSize((s) => Math.min(40, s + 1)) }, 'A+'),
|
|
806
|
+
h(Btn, { title: t('panel.fontReset'), onClick: () => setFontSize(settings.fontSize) }, 'A'),
|
|
807
|
+
renderedState.plain && h('span', { className: 'dr-badge', title: t('panel.mdPlainMode') }, t('panel.mdPlainMode')),
|
|
808
|
+
h(EditControls, { t, editing: false, dirty: false, busy: false, onEnter: editor.enter, onExit: editor.exit, onSave: editor.save }))),
|
|
809
|
+
h('div', { className: 'dr-stage', style: { '--dr-line-height': settings.lineHeight } },
|
|
810
|
+
sidebar,
|
|
811
|
+
editor.editing
|
|
812
|
+
? h('div', { className: 'dr-scroll' },
|
|
813
|
+
h(EditorPane, { value: editor.draft, onChange: editor.setDraft, onSave: editor.save, busy: editor.busy, label: path, areaRef: editorSearch.areaRef }))
|
|
814
|
+
: h('div', { className: 'dr-scroll', ref: scrollRef },
|
|
815
|
+
renderedState.plain
|
|
816
|
+
? h('pre', { className: 'dr-text', ref: bodyRef, style: { fontSize: `${fontSize}px` } },
|
|
817
|
+
(mdChunks
|
|
818
|
+
? mdChunks.map((chunk, i) => h('div', { key: i, style: { contentVisibility: 'auto', containIntrinsicSize: 'auto 1200px' } }, chunk))
|
|
819
|
+
: text))
|
|
820
|
+
: h('article', {
|
|
821
|
+
className: 'dr-md', ref: bodyRef, style: { fontSize: `${fontSize}px` },
|
|
822
|
+
dangerouslySetInnerHTML: { __html: renderedState.html },
|
|
823
|
+
}))),
|
|
824
|
+
h(SaveFontSize, { path, kind: 'markdown', fontSize }));
|
|
825
|
+
}
|
|
826
|
+
// persist font size with the scroll position
|
|
827
|
+
function SaveFontSize({ path, kind, fontSize }) {
|
|
828
|
+
useEffect(() => {
|
|
829
|
+
const saved = getPos(path);
|
|
830
|
+
if (saved && saved.kind === kind && saved.fontSize !== fontSize) savePos(path, { ...saved, fontSize });
|
|
831
|
+
}, [fontSize]);
|
|
832
|
+
return null;
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
// ---------- Text ----------
|
|
836
|
+
// Large plain-text files render in line-aligned chunks with
|
|
837
|
+
// content-visibility:auto — the DOM stays complete (search/highlight
|
|
838
|
+
// unaffected) but layout work happens only near the viewport.
|
|
839
|
+
const TEXT_CHUNK_THRESHOLD = 512 * 1024;
|
|
840
|
+
const TEXT_CHUNK_SIZE = 96 * 1024;
|
|
841
|
+
function splitTextChunks(text) {
|
|
842
|
+
if (text.length <= TEXT_CHUNK_THRESHOLD) return null;
|
|
843
|
+
const chunks = [];
|
|
844
|
+
let start = 0;
|
|
845
|
+
while (start < text.length) {
|
|
846
|
+
let end = Math.min(text.length, start + TEXT_CHUNK_SIZE);
|
|
847
|
+
if (end < text.length) {
|
|
848
|
+
const nl = text.lastIndexOf('\n', end);
|
|
849
|
+
if (nl > start + TEXT_CHUNK_SIZE / 2) end = nl + 1;
|
|
850
|
+
}
|
|
851
|
+
chunks.push(text.slice(start, end));
|
|
852
|
+
start = end;
|
|
853
|
+
}
|
|
854
|
+
return chunks;
|
|
855
|
+
}
|
|
856
|
+
|
|
857
|
+
function TextView({ path, settings, t, onStatus, onSidebar, sidebar, onEditingChange }) {
|
|
858
|
+
const [state, setState] = useState({ status: 'loading' });
|
|
859
|
+
const [fontSize, setFontSize] = useState(() => {
|
|
860
|
+
const pos = getPos(path);
|
|
861
|
+
return (pos && pos.kind === 'text' && typeof pos.fontSize === 'number') ? pos.fontSize : settings.fontSize;
|
|
862
|
+
});
|
|
863
|
+
const [query, setQuery] = useState('');
|
|
864
|
+
const [count, setCount] = useState(0);
|
|
865
|
+
const [index, setIndex] = useState(-1);
|
|
866
|
+
const bodyRef = useRef(null);
|
|
867
|
+
const scrollRef = useRef(null);
|
|
868
|
+
const search = useDomSearch(bodyRef, (total, idx) => { setCount(total); setIndex(idx); }, onStatus, t);
|
|
869
|
+
useEffect(() => { let alive = true; setState({ status: 'loading' }); onSidebar(null);
|
|
870
|
+
const controller = new AbortController();
|
|
871
|
+
fetchFile(path, 'text', controller.signal).then((text) => alive && setState({ status: 'ready', text }))
|
|
872
|
+
.catch((e) => { if (alive && e?.name !== 'AbortError') setState({ status: 'error', message: e.message }); });
|
|
873
|
+
return () => { alive = false; controller.abort(); };
|
|
874
|
+
}, [path]);
|
|
875
|
+
const textChunks = useMemo(() => (state.status === 'ready' ? splitTextChunks(state.text) : null), [state]);
|
|
876
|
+
const editor = useEditMode({
|
|
877
|
+
path,
|
|
878
|
+
currentText: state.status === 'ready' ? state.text : '',
|
|
879
|
+
onSaved: (text) => setState({ status: 'ready', text }),
|
|
880
|
+
t, onStatus,
|
|
881
|
+
});
|
|
882
|
+
useEffect(() => {
|
|
883
|
+
onEditingChange?.(editor.editing);
|
|
884
|
+
return () => onEditingChange?.(false);
|
|
885
|
+
}, [editor.editing, onEditingChange]);
|
|
886
|
+
const [editorQuery, setEditorQuery] = useState('');
|
|
887
|
+
const editorSearch = useEditorSearch(editor.editing ? editor.draft : '');
|
|
888
|
+
useScrollRestore(path, scrollRef, () => ({ kind: 'text', fontSize }), state.status === 'ready' && !editor.editing);
|
|
889
|
+
if (state.status === 'error') return h('div', { className: 'dr-error' }, `${t('panel.error')}: ${state.message}`);
|
|
890
|
+
if (state.status !== 'ready') return h('div', { className: 'dr-load' }, t('panel.loading'));
|
|
891
|
+
return h(React.Fragment, null,
|
|
892
|
+
h(ViewBar, null,
|
|
893
|
+
editor.editing
|
|
894
|
+
? h(React.Fragment, null,
|
|
895
|
+
h(SearchControls, { t, query: editorQuery, setQuery: setEditorQuery, count: editorSearch.count, index: editorSearch.index,
|
|
896
|
+
onEnter: (dirn) => (editorQuery.trim() ? editorSearch.run(editorQuery, dirn) : undefined),
|
|
897
|
+
onPrev: () => editorSearch.navigate(-1), onNext: () => editorSearch.navigate(1) }),
|
|
898
|
+
h('span', { style: { flex: 1 } }),
|
|
899
|
+
h(EditControls, { t, editing: true, dirty: editor.dirty, busy: editor.busy, onEnter: editor.enter, onExit: editor.exit, onSave: editor.save }))
|
|
900
|
+
: h(React.Fragment, null,
|
|
901
|
+
h(SearchControls, { t, query, setQuery, count, index,
|
|
902
|
+
onEnter: () => (query.trim() ? search.run(query, 1) : search.clear()),
|
|
903
|
+
onPrev: () => search.navigate(-1), onNext: () => search.navigate(1) }),
|
|
904
|
+
h('span', { style: { flex: 1 } }),
|
|
905
|
+
h(Btn, { title: t('panel.fontSmaller'), onClick: () => setFontSize((s) => Math.max(10, s - 1)) }, 'A−'),
|
|
906
|
+
h('span', { className: 'dr-badge' }, `${fontSize}px`),
|
|
907
|
+
h(Btn, { title: t('panel.fontBigger'), onClick: () => setFontSize((s) => Math.min(40, s + 1)) }, 'A+'),
|
|
908
|
+
h(Btn, { title: t('panel.fontReset'), onClick: () => setFontSize(settings.fontSize) }, 'A'),
|
|
909
|
+
h(EditControls, { t, editing: false, dirty: false, busy: false, onEnter: editor.enter, onExit: editor.exit, onSave: editor.save }))),
|
|
910
|
+
h('div', { className: 'dr-stage', style: { '--dr-line-height': settings.lineHeight } },
|
|
911
|
+
sidebar,
|
|
912
|
+
editor.editing
|
|
913
|
+
? h('div', { className: 'dr-scroll' },
|
|
914
|
+
h(EditorPane, { value: editor.draft, onChange: editor.setDraft, onSave: editor.save, busy: editor.busy, label: path, areaRef: editorSearch.areaRef }))
|
|
915
|
+
: h('div', { className: 'dr-scroll', ref: scrollRef },
|
|
916
|
+
h('pre', { className: 'dr-text', ref: bodyRef, style: { fontSize: `${fontSize}px` } },
|
|
917
|
+
textChunks
|
|
918
|
+
? textChunks.map((chunk, i) => h('div', { key: i, style: { contentVisibility: 'auto', containIntrinsicSize: 'auto 1200px' } }, chunk))
|
|
919
|
+
: state.text))),
|
|
920
|
+
h(SaveFontSize, { path, kind: 'text', fontSize }));
|
|
921
|
+
}
|
|
922
|
+
|
|
923
|
+
// ---------- PDF (continuous scroll) ----------
|
|
924
|
+
function PdfView({ path, settings, t, onStatus, onSidebar, sidebar }) {
|
|
925
|
+
const [docState, setDocState] = useState(null); // { doc, numPages }
|
|
926
|
+
const [error, setError] = useState(null);
|
|
927
|
+
const [scale, setScale] = useState(null);
|
|
928
|
+
const [page, setPage] = useState(1);
|
|
929
|
+
const [query, setQuery] = useState('');
|
|
930
|
+
const [matches, setMatches] = useState(null); // null=idle []=none [{page,index}]
|
|
931
|
+
const [matchIndex, setMatchIndex] = useState(-1);
|
|
932
|
+
const scrollRef = useRef(null);
|
|
933
|
+
const docRef = useRef(null);
|
|
934
|
+
const shellsRef = useRef(new Map());
|
|
935
|
+
const renderRef = useRef(new Map());
|
|
936
|
+
const observerRef = useRef(null);
|
|
937
|
+
const textCacheRef = useRef(new Map());
|
|
938
|
+
const searchTokenRef = useRef(0);
|
|
939
|
+
const scaleRef = useRef(null);
|
|
940
|
+
scaleRef.current = scale;
|
|
941
|
+
const pageRef = useRef(1);
|
|
942
|
+
pageRef.current = page;
|
|
943
|
+
const basePageHRef = useRef(0);
|
|
944
|
+
|
|
945
|
+
// load document
|
|
946
|
+
useEffect(() => {
|
|
947
|
+
let alive = true; setDocState(null); setError(null); setScale(null); setPage(1); setMatches(null); setMatchIndex(-1);
|
|
948
|
+
onSidebar(null);
|
|
949
|
+
docRef.current?.destroy(); docRef.current = null;
|
|
950
|
+
shellsRef.current.clear(); renderRef.current.clear(); textCacheRef.current.clear(); observerRef.current?.disconnect(); observerRef.current = null;
|
|
951
|
+
searchTokenRef.current += 1; // kill any in-flight full-text search of the old document
|
|
952
|
+
const controller = new AbortController();
|
|
953
|
+
(async () => {
|
|
954
|
+
try {
|
|
955
|
+
const [lib, buf] = await Promise.all([loadPdfjs(), fetchFile(path, undefined, controller.signal)]);
|
|
956
|
+
if (!alive) return;
|
|
957
|
+
const doc = await lib.getDocument({ data: new Uint8Array(buf) }).promise;
|
|
958
|
+
if (!alive) { doc.destroy(); return; }
|
|
959
|
+
docRef.current = doc;
|
|
960
|
+
setDocState({ doc, numPages: doc.numPages });
|
|
961
|
+
onSidebar({ kind: 'pages', docKind: 'pdf', numPages: doc.numPages });
|
|
962
|
+
} catch (e) { if (alive && e?.name !== 'AbortError') setError(e.message); }
|
|
963
|
+
})();
|
|
964
|
+
return () => { alive = false; controller.abort(); docRef.current?.destroy(); docRef.current = null; observerRef.current?.disconnect(); onSidebar(null); };
|
|
965
|
+
}, [path]);
|
|
966
|
+
|
|
967
|
+
// fit-width default scale + position restore, once doc ready
|
|
968
|
+
useEffect(() => {
|
|
969
|
+
if (!docState || scale !== null) return undefined;
|
|
970
|
+
let alive = true;
|
|
971
|
+
(async () => {
|
|
972
|
+
try {
|
|
973
|
+
const first = await docState.doc.getPage(1);
|
|
974
|
+
if (!alive) return;
|
|
975
|
+
const viewport = first.getViewport({ scale: 1 });
|
|
976
|
+
basePageHRef.current = viewport.height;
|
|
977
|
+
const width = viewport.width;
|
|
978
|
+
const el = scrollRef.current;
|
|
979
|
+
const available = el ? el.clientWidth - 36 : 800;
|
|
980
|
+
const saved = getPos(path);
|
|
981
|
+
const fit = clamp(Number((Math.min(1, available / Math.max(width, 1)).toFixed(3))), 0.5, 4);
|
|
982
|
+
setScale(saved?.kind === 'pdf' && Number.isFinite(saved.scale) ? clamp(saved.scale, 0.5, 4) : fit);
|
|
983
|
+
if (saved?.kind === 'pdf' && Number.isFinite(saved.page)) setPage(clamp(Math.round(saved.page), 1, docState.numPages));
|
|
984
|
+
} catch { /* doc destroyed mid-load */ }
|
|
985
|
+
})();
|
|
986
|
+
return () => { alive = false; };
|
|
987
|
+
}, [docState]);
|
|
988
|
+
|
|
989
|
+
// command a page render into its shell
|
|
990
|
+
const renderPage = useCallback(async (pageNumber) => {
|
|
991
|
+
const doc = docRef.current;
|
|
992
|
+
const shell = shellsRef.current.get(pageNumber);
|
|
993
|
+
const target = scaleRef.current; // capture: scale may change mid-render
|
|
994
|
+
if (!doc || !shell || target === null) return;
|
|
995
|
+
const rs = renderRef.current.get(pageNumber) ?? { rendering: false, renderedScale: 0 };
|
|
996
|
+
if (rs.rendering || rs.renderedScale === target) return;
|
|
997
|
+
rs.rendering = true;
|
|
998
|
+
renderRef.current.set(pageNumber, rs);
|
|
999
|
+
let ok = false;
|
|
1000
|
+
try {
|
|
1001
|
+
const pg = await doc.getPage(pageNumber);
|
|
1002
|
+
if (!docRef.current || !shellsRef.current.get(pageNumber)) return;
|
|
1003
|
+
const viewport = pg.getViewport({ scale: target });
|
|
1004
|
+
let canvas = shell.querySelector('canvas');
|
|
1005
|
+
if (!canvas) { canvas = document.createElement('canvas'); shell.appendChild(canvas); }
|
|
1006
|
+
const dpr = window.devicePixelRatio || 1;
|
|
1007
|
+
canvas.width = Math.floor(viewport.width * dpr);
|
|
1008
|
+
canvas.height = Math.floor(viewport.height * dpr);
|
|
1009
|
+
canvas.style.width = `${Math.floor(viewport.width)}px`;
|
|
1010
|
+
canvas.style.height = `${Math.floor(viewport.height)}px`;
|
|
1011
|
+
// pin the shell height so recycling the canvas cannot shift layout
|
|
1012
|
+
shell.style.height = `${Math.floor(viewport.height)}px`;
|
|
1013
|
+
shell.dataset.h = '1';
|
|
1014
|
+
const context = canvas.getContext('2d', { alpha: false });
|
|
1015
|
+
context.setTransform(dpr, 0, 0, dpr, 0, 0);
|
|
1016
|
+
await pg.render({ canvasContext: context, viewport }).promise;
|
|
1017
|
+
if (!docRef.current) return;
|
|
1018
|
+
ok = true;
|
|
1019
|
+
} catch (e) {
|
|
1020
|
+
shell.setAttribute('data-error', t('panel.pdfRenderFailed'));
|
|
1021
|
+
const bad = shell.querySelector('canvas');
|
|
1022
|
+
if (bad) { bad.width = 1; bad.height = 1; bad.remove(); } // failed renders must not hold bitmaps
|
|
1023
|
+
} finally {
|
|
1024
|
+
const rs3 = renderRef.current.get(pageNumber);
|
|
1025
|
+
if (rs3) { rs3.rendering = false; rs3.renderedScale = ok ? target : 0; }
|
|
1026
|
+
if (ok && scaleRef.current !== target) void renderPage(pageNumber); // zoom moved on: re-render at the new scale
|
|
1027
|
+
}
|
|
1028
|
+
}, []);
|
|
1029
|
+
|
|
1030
|
+
// release the bitmap of pages far outside the viewport (canvas LRU)
|
|
1031
|
+
const prunePage = useCallback((pageNumber) => {
|
|
1032
|
+
const rs = renderRef.current.get(pageNumber);
|
|
1033
|
+
if (!rs || rs.rendering || rs.renderedScale === 0) return;
|
|
1034
|
+
const shell = shellsRef.current.get(pageNumber);
|
|
1035
|
+
const canvas = shell?.querySelector('canvas');
|
|
1036
|
+
if (canvas) { canvas.width = 1; canvas.height = 1; canvas.remove(); }
|
|
1037
|
+
rs.renderedScale = 0;
|
|
1038
|
+
// unpin the height and re-estimate at the CURRENT scale so the scrollbar
|
|
1039
|
+
// does not jump when the page re-renders after a zoom change
|
|
1040
|
+
if (shell && scaleRef.current !== null && basePageHRef.current > 0) {
|
|
1041
|
+
delete shell.dataset.h;
|
|
1042
|
+
shell.style.height = `${Math.round(basePageHRef.current * scaleRef.current)}px`;
|
|
1043
|
+
}
|
|
1044
|
+
}, []);
|
|
1045
|
+
|
|
1046
|
+
const renderVisible = useCallback(() => {
|
|
1047
|
+
const el = scrollRef.current;
|
|
1048
|
+
if (!el) return;
|
|
1049
|
+
const top = el.scrollTop - 900;
|
|
1050
|
+
const bottom = el.scrollTop + el.clientHeight + 900;
|
|
1051
|
+
const current = pageRef.current;
|
|
1052
|
+
const keep = Math.max(4, Math.round(12 / Math.max(0.75, scaleRef.current ?? 1))); // high zoom = heavy bitmaps: keep fewer
|
|
1053
|
+
for (const [num, shell] of shellsRef.current.entries()) {
|
|
1054
|
+
const shellTop = shell.offsetTop;
|
|
1055
|
+
const near = shellTop + shell.offsetHeight >= top && shellTop <= bottom;
|
|
1056
|
+
if (near) void renderPage(num);
|
|
1057
|
+
else if (Math.abs(num - current) > keep) prunePage(num);
|
|
1058
|
+
}
|
|
1059
|
+
}, [renderPage, prunePage]);
|
|
1060
|
+
|
|
1061
|
+
// observer + shells after doc ready
|
|
1062
|
+
useEffect(() => {
|
|
1063
|
+
if (!docState || !scrollRef.current) return;
|
|
1064
|
+
const observer = new IntersectionObserver((entries) => {
|
|
1065
|
+
for (const entry of entries) {
|
|
1066
|
+
if (!entry.isIntersecting) continue;
|
|
1067
|
+
const num = Number(entry.target.dataset.page || '0');
|
|
1068
|
+
if (num > 0) void renderPage(num);
|
|
1069
|
+
}
|
|
1070
|
+
}, { root: scrollRef.current, rootMargin: '900px 0px', threshold: 0.01 });
|
|
1071
|
+
observerRef.current = observer;
|
|
1072
|
+
for (const shell of shellsRef.current.values()) observer.observe(shell);
|
|
1073
|
+
// after shells mount: jump to restored page
|
|
1074
|
+
const target = page;
|
|
1075
|
+
requestAnimationFrame(() => {
|
|
1076
|
+
scrollToPage(target, 'auto');
|
|
1077
|
+
renderVisible();
|
|
1078
|
+
});
|
|
1079
|
+
return () => { observer.disconnect(); observerRef.current = null; };
|
|
1080
|
+
}, [docState]);
|
|
1081
|
+
|
|
1082
|
+
// scale change: invalidate rendered pages, keep page anchored
|
|
1083
|
+
useEffect(() => {
|
|
1084
|
+
if (scale === null || !docState) return;
|
|
1085
|
+
for (const rs of renderRef.current.values()) rs.renderedScale = 0;
|
|
1086
|
+
// pre-size not-yet-rendered shells with the page-1 estimate so the
|
|
1087
|
+
// scrollbar does not jump as pages render in
|
|
1088
|
+
if (basePageHRef.current > 0) {
|
|
1089
|
+
for (const shell of shellsRef.current.values()) {
|
|
1090
|
+
if (!shell.dataset.h) shell.style.height = `${Math.round(basePageHRef.current * scale)}px`;
|
|
1091
|
+
}
|
|
1092
|
+
}
|
|
1093
|
+
requestAnimationFrame(() => { scrollToPage(pageRef.current, 'auto'); renderVisible(); });
|
|
1094
|
+
}, [scale]);
|
|
1095
|
+
|
|
1096
|
+
const scrollToPage = useCallback((pageNumber, behavior = 'smooth') => {
|
|
1097
|
+
const shell = shellsRef.current.get(clamp(pageNumber, 1, docRef.current?.numPages ?? 1));
|
|
1098
|
+
if (!shell) return;
|
|
1099
|
+
setPage(clamp(pageNumber, 1, docRef.current.numPages));
|
|
1100
|
+
shell.scrollIntoView({ behavior, block: 'start' });
|
|
1101
|
+
void renderPage(clamp(pageNumber, 1, docRef.current.numPages));
|
|
1102
|
+
}, [renderPage]);
|
|
1103
|
+
|
|
1104
|
+
// viewport page tracking + position save + status
|
|
1105
|
+
useEffect(() => {
|
|
1106
|
+
const el = scrollRef.current;
|
|
1107
|
+
if (!el || !docState) return;
|
|
1108
|
+
let raf = 0;
|
|
1109
|
+
let timer;
|
|
1110
|
+
let closest = 1; // declared here: the debounce timer below must see it
|
|
1111
|
+
const onScroll = () => {
|
|
1112
|
+
if (raf) return;
|
|
1113
|
+
raf = requestAnimationFrame(() => {
|
|
1114
|
+
raf = 0;
|
|
1115
|
+
const mid = el.scrollTop + el.clientHeight / 2;
|
|
1116
|
+
closest = 1;
|
|
1117
|
+
let best = Infinity;
|
|
1118
|
+
for (const [num, shell] of shellsRef.current.entries()) {
|
|
1119
|
+
const center = shell.offsetTop + shell.offsetHeight / 2;
|
|
1120
|
+
const distance = Math.abs(center - mid);
|
|
1121
|
+
if (distance < best) { best = distance; closest = num; }
|
|
1122
|
+
}
|
|
1123
|
+
setPage((prev) => (closest !== prev ? closest : prev));
|
|
1124
|
+
renderVisible();
|
|
1125
|
+
});
|
|
1126
|
+
clearTimeout(timer);
|
|
1127
|
+
timer = setTimeout(() => {
|
|
1128
|
+
if (docRef.current && scaleRef.current !== null) {
|
|
1129
|
+
savePos(path, { kind: 'pdf', page: closest, scale: scaleRef.current });
|
|
1130
|
+
}
|
|
1131
|
+
onStatus(`${t('panel.page')} ${closest}/${docRef.current?.numPages} • ${Math.round(scaleRef.current * 100)}%`);
|
|
1132
|
+
}, 300);
|
|
1133
|
+
};
|
|
1134
|
+
el.addEventListener('scroll', onScroll, { passive: true });
|
|
1135
|
+
return () => {
|
|
1136
|
+
el.removeEventListener('scroll', onScroll);
|
|
1137
|
+
clearTimeout(timer);
|
|
1138
|
+
if (raf) cancelAnimationFrame(raf);
|
|
1139
|
+
if (scaleRef.current !== null && shellsRef.current.size > 0) {
|
|
1140
|
+
// docRef is already null after the load effect's cleanup — but the
|
|
1141
|
+
// document was real when this listener was bound, so flush anyway
|
|
1142
|
+
savePos(path, { kind: 'pdf', page: closest, scale: scaleRef.current });
|
|
1143
|
+
}
|
|
1144
|
+
};
|
|
1145
|
+
}, [docState]);
|
|
1146
|
+
|
|
1147
|
+
// ctrl/cmd wheel zoom (throttled)
|
|
1148
|
+
useEffect(() => {
|
|
1149
|
+
const el = scrollRef.current;
|
|
1150
|
+
if (!el || !docState) return;
|
|
1151
|
+
let last = 0;
|
|
1152
|
+
const onWheel = (event) => {
|
|
1153
|
+
if (!(event.ctrlKey || event.metaKey)) return;
|
|
1154
|
+
event.preventDefault();
|
|
1155
|
+
const now = Date.now();
|
|
1156
|
+
if (now - last < 60) return;
|
|
1157
|
+
last = now;
|
|
1158
|
+
setScale((s) => (s === null ? s : clamp(Number((s + (event.deltaY < 0 ? 0.1 : -0.1)).toFixed(2)), 0.5, 4)));
|
|
1159
|
+
};
|
|
1160
|
+
el.addEventListener('wheel', onWheel, { passive: false });
|
|
1161
|
+
return () => el.removeEventListener('wheel', onWheel);
|
|
1162
|
+
}, [docState]);
|
|
1163
|
+
|
|
1164
|
+
// sidebar thumbnails navigate
|
|
1165
|
+
useEffect(() => {
|
|
1166
|
+
if (!docState) return;
|
|
1167
|
+
onSidebar({ kind: 'pages', docKind: 'pdf', numPages: docState.numPages, currentPage: page, go: (n) => scrollToPage(n, 'smooth') });
|
|
1168
|
+
}, [page, scrollToPage]);
|
|
1169
|
+
|
|
1170
|
+
// PDF text search
|
|
1171
|
+
const runSearch = useCallback(async (direction) => {
|
|
1172
|
+
const doc = docRef.current;
|
|
1173
|
+
const needle = query.trim().toLowerCase();
|
|
1174
|
+
const scan = async () => {
|
|
1175
|
+
if (!doc) return;
|
|
1176
|
+
if (!needle) { setMatches(null); setMatchIndex(-1); return; }
|
|
1177
|
+
if (!settings.pdfTextLayer) { onStatus(t('panel.pdfSearchDisabled')); return; }
|
|
1178
|
+
let current = matches;
|
|
1179
|
+
if (searchDirtyRef.current || !Array.isArray(current)) {
|
|
1180
|
+
const token = ++searchTokenRef.current;
|
|
1181
|
+
onStatus(t('panel.searching'));
|
|
1182
|
+
const found = [];
|
|
1183
|
+
for (let p = 1; p <= doc.numPages; p += 1) {
|
|
1184
|
+
if (searchTokenRef.current !== token) return;
|
|
1185
|
+
let text = textCacheRef.current.get(p);
|
|
1186
|
+
if (text === undefined) {
|
|
1187
|
+
const pg = await doc.getPage(p);
|
|
1188
|
+
const content = await pg.getTextContent();
|
|
1189
|
+
text = content.items.map((item) => (typeof item.str === 'string' ? item.str : '')).join(' ');
|
|
1190
|
+
if (searchTokenRef.current !== token) return; // check BEFORE caching: never pollute a new document
|
|
1191
|
+
textCacheRef.current.set(p, text);
|
|
1192
|
+
if (textCacheRef.current.size > 500) { // bound the cache: big books would otherwise hold tens of MB
|
|
1193
|
+
const keys = [...textCacheRef.current.keys()].slice(0, 250);
|
|
1194
|
+
for (const k of keys) textCacheRef.current.delete(k);
|
|
1195
|
+
}
|
|
1196
|
+
}
|
|
1197
|
+
if (searchTokenRef.current !== token) return;
|
|
1198
|
+
let from = 0;
|
|
1199
|
+
const lowered = text.toLowerCase();
|
|
1200
|
+
while (from < lowered.length) {
|
|
1201
|
+
const at = lowered.indexOf(needle, from);
|
|
1202
|
+
if (at < 0) break;
|
|
1203
|
+
found.push({ page: p, index: at });
|
|
1204
|
+
from = at + needle.length;
|
|
1205
|
+
}
|
|
1206
|
+
}
|
|
1207
|
+
if (searchTokenRef.current !== token) return;
|
|
1208
|
+
current = found;
|
|
1209
|
+
setMatches(found);
|
|
1210
|
+
setMatchIndex(-1);
|
|
1211
|
+
searchDirtyRef.current = false;
|
|
1212
|
+
if (found.length === 0) { onStatus(t('panel.noMatches')); return; }
|
|
1213
|
+
}
|
|
1214
|
+
if (!current || current.length === 0) { onStatus(t('panel.noMatches')); return; }
|
|
1215
|
+
const next = matchIndex < 0 ? 0 : matchIndex + direction;
|
|
1216
|
+
const normalized = ((next % current.length) + current.length) % current.length;
|
|
1217
|
+
setMatchIndex(normalized);
|
|
1218
|
+
scrollToPage(current[normalized].page, 'smooth');
|
|
1219
|
+
onStatus(`${normalized + 1}/${current.length} • ${t('panel.page')} ${current[normalized].page}`);
|
|
1220
|
+
};
|
|
1221
|
+
try { await scan(); } catch { /* doc destroyed mid-scan */ }
|
|
1222
|
+
}, [query, matches, matchIndex, scrollToPage, settings.pdfTextLayer]);
|
|
1223
|
+
const searchDirtyRef = useRef(true);
|
|
1224
|
+
useEffect(() => {
|
|
1225
|
+
searchTokenRef.current += 1; // new query or new document cancels the in-flight scan
|
|
1226
|
+
searchDirtyRef.current = true;
|
|
1227
|
+
setMatches(null);
|
|
1228
|
+
setMatchIndex(-1);
|
|
1229
|
+
}, [query, path]);
|
|
1230
|
+
|
|
1231
|
+
if (error) return h('div', { className: 'dr-error' }, `${t('panel.error')}: ${error}`);
|
|
1232
|
+
if (!docState) return h('div', { className: 'dr-load' }, t('panel.loadingPdf'));
|
|
1233
|
+
return h(React.Fragment, null,
|
|
1234
|
+
h(ViewBar, null,
|
|
1235
|
+
h(SearchControls, { t, query, setQuery, count: matches?.length ?? 0, index: matchIndex, disabled: !settings.pdfTextLayer,
|
|
1236
|
+
onEnter: (dirn) => void runSearch(dirn), onPrev: () => void runSearch(-1), onNext: () => void runSearch(1) }),
|
|
1237
|
+
h('span', { style: { flex: 1 } }),
|
|
1238
|
+
h('span', { className: 'dr-badge' }, `${page}/${docState.numPages}`),
|
|
1239
|
+
h(Btn, { title: t('panel.prevPage'), onClick: () => scrollToPage(page - 1), disabled: page <= 1 }, '‹'),
|
|
1240
|
+
h(Btn, { title: t('panel.nextPage'), onClick: () => scrollToPage(page + 1), disabled: page >= docState.numPages }, '›'),
|
|
1241
|
+
h(Btn, { title: t('panel.zoomOut'), onClick: () => setScale((s) => clamp(Number(((s ?? 1) - 0.1).toFixed(2)), 0.5, 4)) }, '−'),
|
|
1242
|
+
h('span', { className: 'dr-badge' }, scale === null ? '' : `${Math.round(scale * 100)}%`),
|
|
1243
|
+
h(Btn, { title: t('panel.zoomIn'), onClick: () => setScale((s) => clamp(Number(((s ?? 1) + 0.1).toFixed(2)), 0.5, 4)) }, '+'),
|
|
1244
|
+
h(Btn, { title: t('panel.zoomReset'), onClick: () => setScale(1) }, '100%')),
|
|
1245
|
+
h('div', { className: 'dr-stage' },
|
|
1246
|
+
sidebar,
|
|
1247
|
+
h('div', { className: 'dr-scroll', ref: scrollRef },
|
|
1248
|
+
h('div', { className: 'dr-pdf-doc' },
|
|
1249
|
+
Array.from({ length: docState.numPages }, (_, i) => h('div', {
|
|
1250
|
+
key: i + 1, className: 'dr-pdf-shell', 'data-page': `${i + 1}`,
|
|
1251
|
+
ref: (el) => { if (el) shellsRef.current.set(i + 1, el); else shellsRef.current.delete(i + 1); },
|
|
1252
|
+
}))))));
|
|
1253
|
+
}
|
|
1254
|
+
|
|
1255
|
+
// ---------- DOCX ----------
|
|
1256
|
+
function DocxView({ path, settings, t, onStatus, onSidebar, sidebar }) {
|
|
1257
|
+
const [error, setError] = useState(null);
|
|
1258
|
+
const [ready, setReady] = useState(false);
|
|
1259
|
+
const [zoom, setZoom] = useState(null);
|
|
1260
|
+
const [page, setPage] = useState(1);
|
|
1261
|
+
const [pageCount, setPageCount] = useState(1);
|
|
1262
|
+
const scrollRef = useRef(null);
|
|
1263
|
+
const rootRef = useRef(null); // .dr-docx-inner
|
|
1264
|
+
const pagesRef = useRef([]); // page elements / anchors
|
|
1265
|
+
const metaPagesRef = useRef(null);
|
|
1266
|
+
const zoomRef = useRef(null);
|
|
1267
|
+
zoomRef.current = zoom;
|
|
1268
|
+
const pageRef = useRef(1);
|
|
1269
|
+
pageRef.current = page;
|
|
1270
|
+
|
|
1271
|
+
const scrollToPage = useCallback((pageNumber, behavior = 'smooth') => {
|
|
1272
|
+
const pages = pagesRef.current;
|
|
1273
|
+
if (pages.length === 0) return;
|
|
1274
|
+
const normalized = clamp(pageNumber, 1, pages.length);
|
|
1275
|
+
setPage(normalized);
|
|
1276
|
+
pagesRef.current[normalized - 1]?.scrollIntoView({ behavior, block: 'start' });
|
|
1277
|
+
}, []);
|
|
1278
|
+
|
|
1279
|
+
// render + page synthesis
|
|
1280
|
+
useEffect(() => {
|
|
1281
|
+
let alive = true; setError(null); setReady(false); setZoom(null); setPage(1); setPageCount(1); onSidebar(null);
|
|
1282
|
+
restoredRef.current = false;
|
|
1283
|
+
pagesRef.current = []; metaPagesRef.current = null;
|
|
1284
|
+
const controller = new AbortController();
|
|
1285
|
+
(async () => {
|
|
1286
|
+
try {
|
|
1287
|
+
const [vendor, buf] = await Promise.all([loadVendor(), fetchFile(path, undefined, controller.signal)]);
|
|
1288
|
+
if (!alive || !rootRef.current) return;
|
|
1289
|
+
if (buf.byteLength > 100 * 1024 * 1024) throw new Error(t('panel.docxTooLarge'));
|
|
1290
|
+
rootRef.current.innerHTML = '';
|
|
1291
|
+
// metadata page count from docProps/app.xml (VSCode-extension behaviour)
|
|
1292
|
+
try {
|
|
1293
|
+
const zip = await vendor.JSZip.loadAsync(buf);
|
|
1294
|
+
const appXml = zip.file('docProps/app.xml');
|
|
1295
|
+
if (appXml) {
|
|
1296
|
+
const xml = await appXml.async('string');
|
|
1297
|
+
const parsed = new DOMParser().parseFromString(xml, 'application/xml');
|
|
1298
|
+
const pagesNode = Array.from(parsed.getElementsByTagName('*')).find((n) => n.localName === 'Pages');
|
|
1299
|
+
const value = Number.parseInt(pagesNode?.textContent?.trim() ?? '', 10);
|
|
1300
|
+
if (Number.isFinite(value) && value > 0 && value <= 5000) metaPagesRef.current = value;
|
|
1301
|
+
}
|
|
1302
|
+
} catch { /* metadata optional */ }
|
|
1303
|
+
if (!alive) return;
|
|
1304
|
+
await vendor.loadDocx().renderAsync(buf, rootRef.current, null, {
|
|
1305
|
+
inWrapper: true, ignoreWidth: false, ignoreHeight: false,
|
|
1306
|
+
breakPages: settings.docxBreakPages,
|
|
1307
|
+
renderHeaders: true, renderFooters: true, renderFootnotes: true, renderEndnotes: true,
|
|
1308
|
+
ignoreLastRenderedPageBreak: false, useBase64URL: true,
|
|
1309
|
+
experimental: true, renderChanges: true, renderComments: true, renderAltChunks: true,
|
|
1310
|
+
});
|
|
1311
|
+
if (!alive) return;
|
|
1312
|
+
// page synthesis: sections when paginated, else virtual anchors by height
|
|
1313
|
+
const wrapper = rootRef.current.querySelector('.docx-wrapper');
|
|
1314
|
+
const sections = wrapper ? Array.from(wrapper.querySelectorAll(':scope > section.docx')) : [];
|
|
1315
|
+
const buildPages = () => {
|
|
1316
|
+
if (sections.length > 1) {
|
|
1317
|
+
sections.forEach((s, i) => s.setAttribute('data-page', `${i + 1}`));
|
|
1318
|
+
return sections;
|
|
1319
|
+
}
|
|
1320
|
+
const single = sections[0] ?? wrapper;
|
|
1321
|
+
if (!single) return [rootRef.current];
|
|
1322
|
+
const styles = getComputedStyle(single);
|
|
1323
|
+
const width = Number.parseFloat(styles.width) || single.clientWidth || 794;
|
|
1324
|
+
const minHeight = Number.parseFloat(styles.minHeight);
|
|
1325
|
+
const declared = Number.parseFloat(styles.height);
|
|
1326
|
+
const pageHeight = (Number.isFinite(minHeight) && minHeight > 0 ? minHeight
|
|
1327
|
+
: Number.isFinite(declared) && declared > 0 ? declared : width * 1.414) || width * 1.414;
|
|
1328
|
+
const childMax = Array.from(single.children).reduce((max, child) => Math.max(max, child.offsetTop + child.offsetHeight), 0);
|
|
1329
|
+
const totalHeight = Math.max(single.scrollHeight, single.offsetHeight, childMax, pageHeight);
|
|
1330
|
+
const estimated = pageHeight > 0 ? Math.max(1, Math.ceil(totalHeight / pageHeight)) : 1;
|
|
1331
|
+
const meta = metaPagesRef.current && metaPagesRef.current > 1 ? Math.round(metaPagesRef.current) : 1;
|
|
1332
|
+
const target = Math.max(estimated, meta);
|
|
1333
|
+
single.style.position = 'relative';
|
|
1334
|
+
single.querySelectorAll(':scope > .dr-docx-anchor').forEach((a) => a.remove());
|
|
1335
|
+
if (target <= 1) { single.setAttribute('data-page', '1'); return [single]; }
|
|
1336
|
+
const anchors = [];
|
|
1337
|
+
const maxTop = Math.max(0, totalHeight - 1);
|
|
1338
|
+
for (let i = 0; i < target; i += 1) {
|
|
1339
|
+
const anchor = document.createElement('div');
|
|
1340
|
+
anchor.className = 'dr-docx-anchor';
|
|
1341
|
+
anchor.setAttribute('data-page', `${i + 1}`);
|
|
1342
|
+
anchor.style.top = `${Math.round(maxTop * (target <= 1 ? 0 : i / (target - 1)))}px`;
|
|
1343
|
+
single.appendChild(anchor);
|
|
1344
|
+
anchors.push(anchor);
|
|
1345
|
+
}
|
|
1346
|
+
return anchors;
|
|
1347
|
+
};
|
|
1348
|
+
pagesRef.current = buildPages();
|
|
1349
|
+
setPageCount(Math.max(pagesRef.current.length, 1));
|
|
1350
|
+
// default fit-width zoom
|
|
1351
|
+
const firstPage = wrapper?.querySelector(':scope > section.docx');
|
|
1352
|
+
const pageWidth = firstPage?.offsetWidth ?? 794;
|
|
1353
|
+
const available = scrollRef.current ? scrollRef.current.clientWidth - 36 : 800;
|
|
1354
|
+
const fit = clamp(Number((Math.min(1, available / Math.max(pageWidth, 1)).toFixed(3))), 0.5, 3);
|
|
1355
|
+
const saved = getPos(path);
|
|
1356
|
+
setZoom(saved?.kind === 'docx' && Number.isFinite(saved.scale) ? clamp(saved.scale, 0.5, 3) : fit);
|
|
1357
|
+
setReady(true);
|
|
1358
|
+
onStatus(t('panel.docxRendered'));
|
|
1359
|
+
// second layout pass
|
|
1360
|
+
requestAnimationFrame(() => requestAnimationFrame(() => {
|
|
1361
|
+
if (!alive) return;
|
|
1362
|
+
pagesRef.current = buildPages();
|
|
1363
|
+
setPageCount(Math.max(pagesRef.current.length, 1));
|
|
1364
|
+
}));
|
|
1365
|
+
} catch (e) { if (alive && e?.name !== 'AbortError') setError(e.message); }
|
|
1366
|
+
})();
|
|
1367
|
+
return () => { alive = false; controller.abort(); if (rootRef.current) rootRef.current.innerHTML = ''; onSidebar(null); };
|
|
1368
|
+
}, [path, settings.docxBreakPages]);
|
|
1369
|
+
|
|
1370
|
+
// apply zoom via CSS zoom; restore the saved scroll position only once after first render
|
|
1371
|
+
const restoredRef = useRef(false);
|
|
1372
|
+
useEffect(() => {
|
|
1373
|
+
const inner = rootRef.current;
|
|
1374
|
+
if (!inner || zoom === null) return;
|
|
1375
|
+
inner.style.zoom = `${zoom}`;
|
|
1376
|
+
if (restoredRef.current) return;
|
|
1377
|
+
restoredRef.current = true;
|
|
1378
|
+
const saved = getPos(path);
|
|
1379
|
+
if (saved?.kind === 'docx' && typeof saved.scrollTop === 'number') {
|
|
1380
|
+
requestAnimationFrame(() => { if (scrollRef.current) scrollRef.current.scrollTop = saved.scrollTop; });
|
|
1381
|
+
}
|
|
1382
|
+
}, [zoom, ready]);
|
|
1383
|
+
|
|
1384
|
+
// viewport page tracking + save
|
|
1385
|
+
useEffect(() => {
|
|
1386
|
+
const el = scrollRef.current;
|
|
1387
|
+
if (!el || !ready) return;
|
|
1388
|
+
let raf = 0; let timer;
|
|
1389
|
+
const onScroll = () => {
|
|
1390
|
+
if (raf) return;
|
|
1391
|
+
raf = requestAnimationFrame(() => {
|
|
1392
|
+
raf = 0;
|
|
1393
|
+
const top = el.getBoundingClientRect().top + 12;
|
|
1394
|
+
let active = 1; let nearest = 1; let nearestDistance = Infinity;
|
|
1395
|
+
pagesRef.current.forEach((pel, i) => {
|
|
1396
|
+
const num = Number.parseInt(pel.getAttribute('data-page') || `${i + 1}`, 10) || i + 1;
|
|
1397
|
+
const distance = pel.getBoundingClientRect().top - top;
|
|
1398
|
+
if (distance <= 0) active = num;
|
|
1399
|
+
if (Math.abs(distance) < nearestDistance) { nearestDistance = Math.abs(distance); nearest = num; }
|
|
1400
|
+
});
|
|
1401
|
+
const next = active || nearest;
|
|
1402
|
+
setPage((prev) => (next !== prev ? next : prev));
|
|
1403
|
+
});
|
|
1404
|
+
clearTimeout(timer);
|
|
1405
|
+
timer = setTimeout(() => {
|
|
1406
|
+
savePos(path, { kind: 'docx', scrollTop: Math.round(el.scrollTop), scale: zoomRef.current ?? 1 });
|
|
1407
|
+
onStatus(`${t('panel.page')} ${pageRef.current}/${pagesRef.current.length} • ${Math.round((zoomRef.current ?? 1) * 100)}%`);
|
|
1408
|
+
}, 300);
|
|
1409
|
+
};
|
|
1410
|
+
el.addEventListener('scroll', onScroll, { passive: true });
|
|
1411
|
+
return () => { el.removeEventListener('scroll', onScroll); clearTimeout(timer); if (raf) cancelAnimationFrame(raf); };
|
|
1412
|
+
}, [ready]);
|
|
1413
|
+
|
|
1414
|
+
// ctrl/cmd wheel zoom
|
|
1415
|
+
useEffect(() => {
|
|
1416
|
+
const el = scrollRef.current;
|
|
1417
|
+
if (!el || !ready) return;
|
|
1418
|
+
let last = 0;
|
|
1419
|
+
const onWheel = (event) => {
|
|
1420
|
+
if (!(event.ctrlKey || event.metaKey)) return;
|
|
1421
|
+
event.preventDefault();
|
|
1422
|
+
const now = Date.now();
|
|
1423
|
+
if (now - last < 60) return;
|
|
1424
|
+
last = now;
|
|
1425
|
+
setZoom((z) => (z === null ? z : clamp(Number((z + (event.deltaY < 0 ? 0.1 : -0.1)).toFixed(2)), 0.5, 3)));
|
|
1426
|
+
};
|
|
1427
|
+
el.addEventListener('wheel', onWheel, { passive: false });
|
|
1428
|
+
return () => el.removeEventListener('wheel', onWheel);
|
|
1429
|
+
}, [ready]);
|
|
1430
|
+
|
|
1431
|
+
// sidebar pages
|
|
1432
|
+
useEffect(() => {
|
|
1433
|
+
if (!ready) return;
|
|
1434
|
+
onSidebar({ kind: 'pages', docKind: 'docx', numPages: pageCount, currentPage: page, go: (n) => scrollToPage(n, 'smooth') });
|
|
1435
|
+
}, [ready, page, pageCount, scrollToPage]);
|
|
1436
|
+
|
|
1437
|
+
if (error) return h('div', { className: 'dr-error' }, `${t('panel.error')}: ${error}`);
|
|
1438
|
+
return h(React.Fragment, null,
|
|
1439
|
+
h(ViewBar, null,
|
|
1440
|
+
h('span', { className: 'dr-badge' }, `${page}/${pageCount}`),
|
|
1441
|
+
h(Btn, { title: t('panel.prevPage'), onClick: () => scrollToPage(page - 1), disabled: page <= 1 }, '‹'),
|
|
1442
|
+
h(Btn, { title: t('panel.nextPage'), onClick: () => scrollToPage(page + 1), disabled: page >= pageCount }, '›'),
|
|
1443
|
+
h('span', { style: { flex: 1 } }),
|
|
1444
|
+
h(Btn, { title: t('panel.zoomOut'), onClick: () => setZoom((z) => clamp(Number(((z ?? 1) - 0.1).toFixed(2)), 0.5, 3)) }, '−'),
|
|
1445
|
+
h('span', { className: 'dr-badge' }, zoom === null ? '' : `${Math.round(zoom * 100)}%`),
|
|
1446
|
+
h(Btn, { title: t('panel.zoomIn'), onClick: () => setZoom((z) => clamp(Number(((z ?? 1) + 0.1).toFixed(2)), 0.5, 3)) }, '+'),
|
|
1447
|
+
h(Btn, { title: t('panel.zoomReset'), onClick: () => setZoom(1) }, '100%')),
|
|
1448
|
+
h('div', { className: 'dr-stage' },
|
|
1449
|
+
sidebar,
|
|
1450
|
+
h('div', { className: 'dr-scroll dr-docx-scroll', ref: scrollRef },
|
|
1451
|
+
h('div', { className: 'dr-docx-inner', ref: rootRef }),
|
|
1452
|
+
!ready && !error && h('div', { className: 'dr-load' }, t('panel.loading')))));
|
|
1453
|
+
}
|
|
1454
|
+
|
|
1455
|
+
// ---------- Image ----------
|
|
1456
|
+
function ImageView({ path, t, onStatus, onSidebar }) {
|
|
1457
|
+
const [error, setError] = useState(null);
|
|
1458
|
+
const [natural, setNatural] = useState(null); // {width,height}
|
|
1459
|
+
const [scale, setScale] = useState(1);
|
|
1460
|
+
const [rotation, setRotation] = useState(0);
|
|
1461
|
+
const [fitMode, setFitMode] = useState('window'); // null | 'window' | 'width'
|
|
1462
|
+
const stageRef = useRef(null);
|
|
1463
|
+
const scrollRef = useRef(null);
|
|
1464
|
+
const [viewportTick, setViewportTick] = useState(0);
|
|
1465
|
+
const pendingScrollRef = useRef(null);
|
|
1466
|
+
const [downsampled, setDownsampled] = useState(null); // blob URL for huge images
|
|
1467
|
+
const downsampledRef = useRef(null);
|
|
1468
|
+
const dsTokenRef = useRef(0); // invalidates in-flight downsampling on file switch
|
|
1469
|
+
useEffect(() => () => { if (downsampledRef.current) URL.revokeObjectURL(downsampledRef.current); }, []);
|
|
1470
|
+
useEffect(() => {
|
|
1471
|
+
let raf = 0;
|
|
1472
|
+
const onResize = () => {
|
|
1473
|
+
if (raf) return;
|
|
1474
|
+
raf = requestAnimationFrame(() => { raf = 0; setViewportTick((v) => v + 1); });
|
|
1475
|
+
};
|
|
1476
|
+
window.addEventListener('resize', onResize);
|
|
1477
|
+
return () => { window.removeEventListener('resize', onResize); if (raf) cancelAnimationFrame(raf); };
|
|
1478
|
+
}, []);
|
|
1479
|
+
|
|
1480
|
+
// restore (also resets stale state when switching image -> image)
|
|
1481
|
+
useEffect(() => {
|
|
1482
|
+
setError(null);
|
|
1483
|
+
setNatural(null);
|
|
1484
|
+
pendingScrollRef.current = null;
|
|
1485
|
+
dsTokenRef.current += 1;
|
|
1486
|
+
if (downsampledRef.current) { URL.revokeObjectURL(downsampledRef.current); downsampledRef.current = null; }
|
|
1487
|
+
setDownsampled(null);
|
|
1488
|
+
const saved = getPos(path);
|
|
1489
|
+
if (saved?.kind === 'image') {
|
|
1490
|
+
setScale(Number.isFinite(saved.scale) ? clamp(saved.scale, 0.1, 8) : 1);
|
|
1491
|
+
setRotation(Number.isFinite(saved.rotation) ? ((Math.round(saved.rotation) % 360) + 360) % 360 : 0);
|
|
1492
|
+
setFitMode(saved.fitMode === 'width' || saved.fitMode === 'window' ? saved.fitMode : 'window');
|
|
1493
|
+
if (typeof saved.scrollTop === 'number') pendingScrollRef.current = saved.scrollTop;
|
|
1494
|
+
} else {
|
|
1495
|
+
setScale(1); setRotation(0); setFitMode('window');
|
|
1496
|
+
}
|
|
1497
|
+
onSidebar(null);
|
|
1498
|
+
}, [path]);
|
|
1499
|
+
|
|
1500
|
+
// save (debounced on any transform change OR plain scrolling)
|
|
1501
|
+
useEffect(() => {
|
|
1502
|
+
if (!natural) return undefined;
|
|
1503
|
+
let timer;
|
|
1504
|
+
const save = () => {
|
|
1505
|
+
timer = setTimeout(() => {
|
|
1506
|
+
savePos(path, { kind: 'image', scale, rotation, fitMode, scrollTop: Math.round(scrollRef.current?.scrollTop ?? 0) });
|
|
1507
|
+
}, 300);
|
|
1508
|
+
};
|
|
1509
|
+
const el = scrollRef.current;
|
|
1510
|
+
el?.addEventListener('scroll', save, { passive: true });
|
|
1511
|
+
save();
|
|
1512
|
+
return () => { el?.removeEventListener('scroll', save); clearTimeout(timer); };
|
|
1513
|
+
}, [natural, scale, rotation, fitMode]);
|
|
1514
|
+
|
|
1515
|
+
// effective scale under fit modes (rotation-aware)
|
|
1516
|
+
const effective = useMemo(() => {
|
|
1517
|
+
if (!natural) return 1;
|
|
1518
|
+
if (!fitMode) return scale;
|
|
1519
|
+
const swapped = rotation % 180 !== 0;
|
|
1520
|
+
const w = swapped ? natural.height : natural.width;
|
|
1521
|
+
const hSwapped = swapped ? natural.width : natural.height;
|
|
1522
|
+
const el = scrollRef.current;
|
|
1523
|
+
const viewportWidth = Math.max((el?.clientWidth ?? 800) - 76, 1);
|
|
1524
|
+
const viewportHeight = Math.max((el?.clientHeight ?? 600) - 76, 1);
|
|
1525
|
+
if (fitMode === 'width') return clamp(viewportWidth / Math.max(w, 1), 0.1, 8);
|
|
1526
|
+
return clamp(Math.min(viewportWidth / Math.max(w, 1), viewportHeight / Math.max(hSwapped, 1)), 0.1, 8);
|
|
1527
|
+
}, [natural, fitMode, rotation, scale, viewportTick]);
|
|
1528
|
+
|
|
1529
|
+
// stage sizing so transform overflow scrolls correctly
|
|
1530
|
+
const stageSize = useMemo(() => {
|
|
1531
|
+
if (!natural) return null;
|
|
1532
|
+
const swapped = rotation % 180 !== 0;
|
|
1533
|
+
const w = (swapped ? natural.height : natural.width) * effective;
|
|
1534
|
+
const h = (swapped ? natural.width : natural.height) * effective;
|
|
1535
|
+
return { width: Math.ceil(w), height: Math.ceil(h) };
|
|
1536
|
+
}, [natural, rotation, effective]);
|
|
1537
|
+
|
|
1538
|
+
// The <img> keeps its NATURAL layout size and is scaled/rotated purely
|
|
1539
|
+
// visually, so the transform must anchor at the img's TOP-LEFT and
|
|
1540
|
+
// compensate rotation with a display-unit translate — anything else
|
|
1541
|
+
// (e.g. origin center) draws the picture around the layout box's
|
|
1542
|
+
// center, thousands of px right of the stage for large images
|
|
1543
|
+
// (invisible until scrolled: the "empty stage + h-scrollbar" bug).
|
|
1544
|
+
const imgTransform = useMemo(() => {
|
|
1545
|
+
if (!natural) return 'none';
|
|
1546
|
+
const s = effective;
|
|
1547
|
+
const px = (v) => `${Math.round(v * 100) / 100}px`;
|
|
1548
|
+
const w = natural.width * s, h = natural.height * s;
|
|
1549
|
+
if (rotation === 90) return `translate(${px(h)}, 0px) rotate(90deg) scale(${s})`;
|
|
1550
|
+
if (rotation === 180) return `translate(${px(w)}, ${px(h)}) rotate(180deg) scale(${s})`;
|
|
1551
|
+
if (rotation === 270) return `translate(0px, ${px(w)}) rotate(270deg) scale(${s})`;
|
|
1552
|
+
return `scale(${s})`;
|
|
1553
|
+
}, [natural, rotation, effective]);
|
|
1554
|
+
|
|
1555
|
+
// ctrl wheel zoom
|
|
1556
|
+
useEffect(() => {
|
|
1557
|
+
const el = scrollRef.current;
|
|
1558
|
+
if (!el) return;
|
|
1559
|
+
let last = 0;
|
|
1560
|
+
const onWheel = (event) => {
|
|
1561
|
+
if (!(event.ctrlKey || event.metaKey)) return;
|
|
1562
|
+
event.preventDefault();
|
|
1563
|
+
const now = Date.now();
|
|
1564
|
+
if (now - last < 60) return;
|
|
1565
|
+
last = now;
|
|
1566
|
+
setFitMode(null);
|
|
1567
|
+
setScale((s) => clamp(Number((s + (event.deltaY < 0 ? 0.1 : -0.1)).toFixed(2)), 0.1, 8));
|
|
1568
|
+
};
|
|
1569
|
+
el.addEventListener('wheel', onWheel, { passive: false });
|
|
1570
|
+
return () => el.removeEventListener('wheel', onWheel);
|
|
1571
|
+
}, []);
|
|
1572
|
+
|
|
1573
|
+
const reset = () => { setScale(1); setRotation(0); setFitMode(null); };
|
|
1574
|
+
const isDefault = fitMode === null && rotation === 0 && Math.abs(scale - 1) < 0.001;
|
|
1575
|
+
|
|
1576
|
+
if (error) return h('div', { className: 'dr-error' }, `${t('panel.error')}: ${error}`);
|
|
1577
|
+
return h(React.Fragment, null,
|
|
1578
|
+
h(ViewBar, null,
|
|
1579
|
+
h(Btn, { title: t('panel.zoomOut'), onClick: () => { setFitMode(null); setScale((s) => clamp(Number((s - 0.1).toFixed(2)), 0.1, 8)); }, disabled: !natural || effective <= 0.1 + 1e-9 }, '−'),
|
|
1580
|
+
h('span', { className: 'dr-badge' }, `${Math.round(effective * 100)}%`),
|
|
1581
|
+
h(Btn, { title: t('panel.zoomIn'), onClick: () => { setFitMode(null); setScale((s) => clamp(Number((s + 0.1).toFixed(2)), 0.1, 8)); }, disabled: !natural || effective >= 8 - 1e-9 }, '+'),
|
|
1582
|
+
h(Btn, { title: t('panel.zoomReset'), onClick: reset, disabled: !natural || isDefault }, '100%'),
|
|
1583
|
+
h(Btn, { title: t('panel.rotateLeft'), onClick: () => setRotation((r) => (r + 270) % 360), disabled: !natural }, '↺'),
|
|
1584
|
+
h(Btn, { title: t('panel.rotateRight'), onClick: () => setRotation((r) => (r + 90) % 360), disabled: !natural }, '↻'),
|
|
1585
|
+
h(Btn, { title: t('panel.fitWindow'), onClick: () => setFitMode('window'), pressed: fitMode === 'window', disabled: !natural }, t('panel.fitWindow')),
|
|
1586
|
+
h(Btn, { title: t('panel.fitWidth'), onClick: () => setFitMode('width'), pressed: fitMode === 'width', disabled: !natural }, t('panel.fitWidth'))),
|
|
1587
|
+
h('div', { className: 'dr-stage' },
|
|
1588
|
+
h('div', { className: 'dr-scroll', ref: scrollRef },
|
|
1589
|
+
h('div', { className: 'dr-image-host' },
|
|
1590
|
+
h('div', { className: 'dr-image-stage', ref: stageRef, style: stageSize ? { width: `${stageSize.width + 29}px`, height: `${stageSize.height + 29}px` } : undefined },
|
|
1591
|
+
h('img', {
|
|
1592
|
+
src: downsampled ?? FILE_URL(path), alt: path, decoding: 'async',
|
|
1593
|
+
onLoad: async (e) => {
|
|
1594
|
+
const img = e.currentTarget;
|
|
1595
|
+
const width = img.naturalWidth;
|
|
1596
|
+
const height = img.naturalHeight;
|
|
1597
|
+
// giant bitmaps (>8192px) can request GB-scale decode memory: downsample once
|
|
1598
|
+
if ((width > 8192 || height > 8192) && !downsampledRef.current) {
|
|
1599
|
+
const token = dsTokenRef.current;
|
|
1600
|
+
try {
|
|
1601
|
+
const ratio = Math.min(1, 8192 / Math.max(width, height));
|
|
1602
|
+
const bmp = await createImageBitmap(img, { resizeWidth: Math.max(1, Math.round(width * ratio)), resizeHeight: Math.max(1, Math.round(height * ratio)), resizeQuality: 'good' });
|
|
1603
|
+
const canvas = document.createElement('canvas');
|
|
1604
|
+
canvas.width = bmp.width; canvas.height = bmp.height;
|
|
1605
|
+
canvas.getContext('2d').drawImage(bmp, 0, 0);
|
|
1606
|
+
bmp.close?.();
|
|
1607
|
+
const blob = await new Promise((resolve) => canvas.toBlob(resolve, 'image/png'));
|
|
1608
|
+
if (blob) {
|
|
1609
|
+
const url = URL.createObjectURL(blob);
|
|
1610
|
+
if (token !== dsTokenRef.current) { URL.revokeObjectURL(url); return; } // stale: user moved on
|
|
1611
|
+
downsampledRef.current = url;
|
|
1612
|
+
setDownsampled(url); // reloads <img> at display size; onLoad fires again
|
|
1613
|
+
return;
|
|
1614
|
+
}
|
|
1615
|
+
} catch { /* keep the original image */ }
|
|
1616
|
+
}
|
|
1617
|
+
setNatural({ width: img.naturalWidth, height: img.naturalHeight });
|
|
1618
|
+
// restore the scroll offset only now that layout has real height
|
|
1619
|
+
const pending = pendingScrollRef.current;
|
|
1620
|
+
if (pending !== null) {
|
|
1621
|
+
pendingScrollRef.current = null;
|
|
1622
|
+
requestAnimationFrame(() => { if (scrollRef.current) scrollRef.current.scrollTop = pending; });
|
|
1623
|
+
}
|
|
1624
|
+
},
|
|
1625
|
+
onError: () => setError('image failed to load'),
|
|
1626
|
+
style: {
|
|
1627
|
+
width: natural ? `${natural.width}px` : undefined,
|
|
1628
|
+
height: natural ? `${natural.height}px` : undefined,
|
|
1629
|
+
transform: imgTransform,
|
|
1630
|
+
opacity: natural ? 1 : 0,
|
|
1631
|
+
},
|
|
1632
|
+
}))))));
|
|
1633
|
+
}
|
|
1634
|
+
|
|
1635
|
+
// ---------- sanitized HTML / EPUB rendering ----------
|
|
1636
|
+
// URL parsers strip NUL..space and DEL before scheme detection, so a raw
|
|
1637
|
+
// /^javascript:/ test misses "java\tscript:" — normalize first, then decide
|
|
1638
|
+
// by scheme instead of by deny-list.
|
|
1639
|
+
function docUrlKind(value) {
|
|
1640
|
+
const norm = (value || '').replace(/[\x00-\x20\x7f]/gu, '');
|
|
1641
|
+
if (!norm) return 'none';
|
|
1642
|
+
if (norm.startsWith('#')) return 'anchor';
|
|
1643
|
+
if (/^[a-z][a-z0-9+.\-]*:/iu.test(norm)) {
|
|
1644
|
+
if (/^data:image\//iu.test(norm)) return 'inline-image';
|
|
1645
|
+
try {
|
|
1646
|
+
const { protocol } = new URL(norm);
|
|
1647
|
+
if (protocol === 'http:' || protocol === 'https:') return 'external';
|
|
1648
|
+
if (protocol === 'blob:') return 'asset'; // page-local blob we created ourselves
|
|
1649
|
+
return 'blocked';
|
|
1650
|
+
} catch {
|
|
1651
|
+
return 'blocked';
|
|
1652
|
+
}
|
|
1653
|
+
}
|
|
1654
|
+
return 'relative';
|
|
1655
|
+
}
|
|
1656
|
+
|
|
1657
|
+
const SANITIZE_REMOVE = 'script,iframe,object,embed,link,meta,base,form,video,audio,source,track,picture,style';
|
|
1658
|
+
/** Strip executable content and any remote-request surface from a fragment:
|
|
1659
|
+
* dangerous elements, on* handlers, non-http(s) absolute URLs, srcset/poster
|
|
1660
|
+
* beacons. Also descends into <template> content. */
|
|
1661
|
+
function sanitizeFragment(root) {
|
|
1662
|
+
root.querySelectorAll(SANITIZE_REMOVE).forEach((el) => el.remove());
|
|
1663
|
+
const clean = (scope) => {
|
|
1664
|
+
for (const el of scope.querySelectorAll('*')) {
|
|
1665
|
+
for (const attr of [...el.attributes]) {
|
|
1666
|
+
const name = attr.name.toLowerCase();
|
|
1667
|
+
const value = attr.value;
|
|
1668
|
+
if (name.startsWith('on')) { el.removeAttribute(attr.name); continue; }
|
|
1669
|
+
if (name === 'srcset' || name === 'poster' || name === 'loading') { el.removeAttribute(attr.name); continue; }
|
|
1670
|
+
if (name === 'href' || name === 'src' || name === 'xlink:href') {
|
|
1671
|
+
const kind = docUrlKind(value);
|
|
1672
|
+
if (kind === 'blocked' || kind === 'none') el.removeAttribute(attr.name);
|
|
1673
|
+
}
|
|
1674
|
+
}
|
|
1675
|
+
if ((el.localName || el.tagName || '').toLowerCase() === 'a') {
|
|
1676
|
+
el.setAttribute('target', '_blank');
|
|
1677
|
+
el.setAttribute('rel', 'noopener noreferrer');
|
|
1678
|
+
}
|
|
1679
|
+
}
|
|
1680
|
+
for (const tpl of scope.querySelectorAll('template')) clean(tpl.content);
|
|
1681
|
+
};
|
|
1682
|
+
clean(root);
|
|
1683
|
+
}
|
|
1684
|
+
|
|
1685
|
+
/**
|
|
1686
|
+
* Whitelisted click guard for sanitized containers: external -> system
|
|
1687
|
+
* browser, anchors -> smooth scroll, supported relative docs -> open in the
|
|
1688
|
+
* reader, everything else blocked (never falls through to default nav).
|
|
1689
|
+
*/
|
|
1690
|
+
function useGuardedLinks(ref, enabled, opts = {}) {
|
|
1691
|
+
const { onOpen, dir } = opts;
|
|
1692
|
+
const onOpenRef = useRef(onOpen);
|
|
1693
|
+
onOpenRef.current = onOpen;
|
|
1694
|
+
useEffect(() => {
|
|
1695
|
+
const root = ref.current;
|
|
1696
|
+
if (!root || !enabled) return undefined;
|
|
1697
|
+
const onClick = (event) => {
|
|
1698
|
+
const anchor = event.target.closest('a[href]');
|
|
1699
|
+
if (!anchor) return;
|
|
1700
|
+
const href = anchor.getAttribute('href') || '';
|
|
1701
|
+
const kind = docUrlKind(href);
|
|
1702
|
+
event.preventDefault(); // navigation is opt-in only
|
|
1703
|
+
if (kind === 'external') { window.open(href, '_blank', 'noopener,noreferrer'); return; }
|
|
1704
|
+
if (kind === 'anchor') {
|
|
1705
|
+
let id = href.slice(1);
|
|
1706
|
+
try { id = decodeURIComponent(id); } catch { /* keep raw */ }
|
|
1707
|
+
root.querySelector(`[id="${CSS.escape(id)}"], a[name="${CSS.escape(id)}"]`)?.scrollIntoView({ behavior: 'smooth', block: 'start' });
|
|
1708
|
+
return;
|
|
1709
|
+
}
|
|
1710
|
+
if (kind === 'relative' && onOpenRef.current && dir) {
|
|
1711
|
+
const resolved = joinDir(dir, href);
|
|
1712
|
+
if (resolved && kindOf(resolved)) { onOpenRef.current(resolved); return; }
|
|
1713
|
+
}
|
|
1714
|
+
};
|
|
1715
|
+
root.addEventListener('click', onClick);
|
|
1716
|
+
return () => root.removeEventListener('click', onClick);
|
|
1717
|
+
}, [enabled, dir]);
|
|
1718
|
+
}
|
|
1719
|
+
|
|
1720
|
+
function FontControls({ t, fontSize, setFontSize, settings }) {
|
|
1721
|
+
return h(React.Fragment, null,
|
|
1722
|
+
h(Btn, { title: t('panel.fontSmaller'), onClick: () => setFontSize((s) => Math.max(10, s - 1)) }, 'A−'),
|
|
1723
|
+
h('span', { className: 'dr-badge' }, `${fontSize}px`),
|
|
1724
|
+
h(Btn, { title: t('panel.fontBigger'), onClick: () => setFontSize((s) => Math.min(40, s + 1)) }, 'A+'),
|
|
1725
|
+
h(Btn, { title: t('panel.fontReset'), onClick: () => setFontSize(settings.fontSize) }, 'A'));
|
|
1726
|
+
}
|
|
1727
|
+
|
|
1728
|
+
/** Local .html/.htm file: parsed, sanitized, images routed through the file endpoint. */
|
|
1729
|
+
function HtmlView({ path, settings, t, onStatus, onSidebar, sidebar }) {
|
|
1730
|
+
const [state, setState] = useState({ status: 'loading' });
|
|
1731
|
+
const [fontSize, setFontSize] = useState(() => {
|
|
1732
|
+
const pos = getPos(path);
|
|
1733
|
+
return (pos && pos.kind === 'html' && typeof pos.fontSize === 'number') ? pos.fontSize : settings.fontSize;
|
|
1734
|
+
});
|
|
1735
|
+
const [query, setQuery] = useState('');
|
|
1736
|
+
const [count, setCount] = useState(0);
|
|
1737
|
+
const [index, setIndex] = useState(-1);
|
|
1738
|
+
const bodyRef = useRef(null);
|
|
1739
|
+
const scrollRef = useRef(null);
|
|
1740
|
+
const search = useDomSearch(bodyRef, (total, idx) => { setCount(total); setIndex(idx); }, onStatus, t);
|
|
1741
|
+
const dir = useMemo(() => path.slice(0, path.lastIndexOf('/')) || '/', [path]);
|
|
1742
|
+
useScrollRestore(path, scrollRef, () => ({ kind: 'html', fontSize }), state.status === 'ready');
|
|
1743
|
+
useGuardedLinks(bodyRef, state.status === 'ready');
|
|
1744
|
+
useEffect(() => {
|
|
1745
|
+
let alive = true; setState({ status: 'loading' }); onSidebar(null);
|
|
1746
|
+
const controller = new AbortController();
|
|
1747
|
+
fetchFile(path, 'text', controller.signal).then((html) => {
|
|
1748
|
+
if (!alive) return;
|
|
1749
|
+
const doc = new DOMParser().parseFromString(html, 'text/html');
|
|
1750
|
+
const body = doc.body;
|
|
1751
|
+
for (const img of [...body.querySelectorAll('img[data-src]')]) {
|
|
1752
|
+
img.setAttribute('src', img.getAttribute('data-src') || '');
|
|
1753
|
+
img.removeAttribute('data-src');
|
|
1754
|
+
}
|
|
1755
|
+
for (const img of [...body.querySelectorAll('img[src]')]) {
|
|
1756
|
+
const raw = img.getAttribute('src') || '';
|
|
1757
|
+
const kind = docUrlKind(raw);
|
|
1758
|
+
const resolved = kind === 'relative' ? joinDir(dir, raw) : null;
|
|
1759
|
+
if (resolved && kindOf(resolved) === 'image') { img.setAttribute('src', FILE_URL(resolved)); img.setAttribute('loading', 'lazy'); }
|
|
1760
|
+
else if (kind === 'inline-image') { img.setAttribute('loading', 'lazy'); } // keep data:image/*
|
|
1761
|
+
else img.removeAttribute('src');
|
|
1762
|
+
}
|
|
1763
|
+
body.querySelectorAll('[srcset]').forEach((el) => el.removeAttribute('srcset'));
|
|
1764
|
+
sanitizeFragment(body);
|
|
1765
|
+
setState({ status: 'ready', html: body.innerHTML });
|
|
1766
|
+
}).catch((e) => { if (alive && e?.name !== 'AbortError') setState({ status: 'error', message: e.message }); });
|
|
1767
|
+
return () => { alive = false; controller.abort(); };
|
|
1768
|
+
}, [path]);
|
|
1769
|
+
if (state.status === 'error') return h('div', { className: 'dr-error' }, `${t('panel.error')}: ${state.message}`);
|
|
1770
|
+
if (state.status !== 'ready') return h('div', { className: 'dr-load' }, t('panel.loading'));
|
|
1771
|
+
return h(React.Fragment, null,
|
|
1772
|
+
h(ViewBar, null,
|
|
1773
|
+
h(SearchControls, { t, query, setQuery, count, index,
|
|
1774
|
+
onEnter: (dirn) => (query.trim() ? search.run(query, dirn) : search.clear()),
|
|
1775
|
+
onPrev: () => search.navigate(-1), onNext: () => search.navigate(1) }),
|
|
1776
|
+
h('span', { style: { flex: 1 } }),
|
|
1777
|
+
h(FontControls, { t, fontSize, setFontSize, settings })),
|
|
1778
|
+
h('div', { className: 'dr-stage', style: { '--dr-line-height': settings.lineHeight } },
|
|
1779
|
+
sidebar,
|
|
1780
|
+
h('div', { className: 'dr-scroll', ref: scrollRef },
|
|
1781
|
+
h('article', { className: 'dr-md', ref: bodyRef, style: { fontSize: `${fontSize}px` }, dangerouslySetInnerHTML: { __html: state.html } })),
|
|
1782
|
+
h(SaveFontSize, { path, kind: 'html', fontSize })));
|
|
1783
|
+
}
|
|
1784
|
+
|
|
1785
|
+
const resolveZipPath = (baseDir, ref) => {
|
|
1786
|
+
const clean = (ref || '').split('?')[0].split('#')[0];
|
|
1787
|
+
if (!clean) return null;
|
|
1788
|
+
let decoded = clean;
|
|
1789
|
+
try { decoded = decodeURIComponent(clean); } catch { /* keep raw */ }
|
|
1790
|
+
const parts = baseDir ? baseDir.split('/') : [];
|
|
1791
|
+
for (const seg of decoded.split('/')) {
|
|
1792
|
+
if (seg === '' || seg === '.') continue;
|
|
1793
|
+
if (seg === '..') parts.pop();
|
|
1794
|
+
else parts.push(seg);
|
|
1795
|
+
}
|
|
1796
|
+
return parts.join('/');
|
|
1797
|
+
};
|
|
1798
|
+
|
|
1799
|
+
const EPUB_MAX_CHAPTER_BYTES = 20 * 1024 * 1024;
|
|
1800
|
+
const EPUB_MAX_IMAGE_BYTES = 50 * 1024 * 1024;
|
|
1801
|
+
|
|
1802
|
+
/** Case-tolerant zip lookup: zip entries are case-sensitive but Windows-made
|
|
1803
|
+
* epubs frequently disagree with the OPF about it. */
|
|
1804
|
+
function zipEntry(book, name) {
|
|
1805
|
+
if (!name) return null;
|
|
1806
|
+
const hit = book.zip.file(name);
|
|
1807
|
+
if (hit) return hit;
|
|
1808
|
+
if (!book.lowerMap) {
|
|
1809
|
+
book.lowerMap = new Map();
|
|
1810
|
+
book.zip.forEach((relPath, file) => { if (!book.lowerMap.has(relPath.toLowerCase())) book.lowerMap.set(relPath.toLowerCase(), file); });
|
|
1811
|
+
}
|
|
1812
|
+
return book.lowerMap.get(name.toLowerCase()) ?? null;
|
|
1813
|
+
}
|
|
1814
|
+
|
|
1815
|
+
async function parseEpub(vendor, buf) {
|
|
1816
|
+
const zip = await vendor.JSZip.loadAsync(buf);
|
|
1817
|
+
const book = { zip, opfDir: '', spine: [], titles: [], spinePaths: [] };
|
|
1818
|
+
const containerRaw = decodeText(await zipEntry(book, 'META-INF/container.xml')?.async('uint8array').then((b) => b ?? new Uint8Array()));
|
|
1819
|
+
const container = new DOMParser().parseFromString(containerRaw ?? '', 'application/xml');
|
|
1820
|
+
let opfPath = [...container.getElementsByTagName('*')].find((n) => n.localName === 'rootfile')?.getAttribute('full-path') ?? '';
|
|
1821
|
+
try { opfPath = decodeURIComponent(opfPath); } catch { /* keep raw */ }
|
|
1822
|
+
opfPath = opfPath.replace(/^\/+/u, '');
|
|
1823
|
+
const opfEntry = zipEntry(book, opfPath);
|
|
1824
|
+
if (!opfPath || !opfEntry) throw new Error('epub: missing OPF');
|
|
1825
|
+
book.opfDir = opfPath.includes('/') ? opfPath.slice(0, opfPath.lastIndexOf('/')) : '';
|
|
1826
|
+
const opf = new DOMParser().parseFromString(decodeText(await opfEntry.async('uint8array')), 'application/xml');
|
|
1827
|
+
const manifest = new Map();
|
|
1828
|
+
for (const item of opf.getElementsByTagName('*')) {
|
|
1829
|
+
if (item.localName !== 'item') continue;
|
|
1830
|
+
manifest.set(item.getAttribute('id'), {
|
|
1831
|
+
href: item.getAttribute('href') || '',
|
|
1832
|
+
type: item.getAttribute('media-type') || '',
|
|
1833
|
+
properties: item.getAttribute('properties') || '',
|
|
1834
|
+
});
|
|
1835
|
+
}
|
|
1836
|
+
book.spine = [...opf.getElementsByTagName('*')].filter((n) => n.localName === 'itemref')
|
|
1837
|
+
.map((n) => manifest.get(n.getAttribute('idref')))
|
|
1838
|
+
.filter((it) => it && /x?html/i.test(it.type));
|
|
1839
|
+
if (book.spine.length === 0) throw new Error('epub: empty spine');
|
|
1840
|
+
// materialize resolved paths once (TOC matching is O(n+m) this way)
|
|
1841
|
+
book.spinePaths = book.spine.map((it) => resolveZipPath(book.opfDir, it.href));
|
|
1842
|
+
// chapter titles: EPUB3 nav document, else NCX navLabel>text, else positional
|
|
1843
|
+
book.titles = new Array(book.spine.length).fill('');
|
|
1844
|
+
const tocItem = [...manifest.values()].find((it) => it.properties.split(' ').includes('nav'))
|
|
1845
|
+
?? [...manifest.values()].find((it) => it.type === 'application/x-dtbncx+xml');
|
|
1846
|
+
if (tocItem) {
|
|
1847
|
+
const tocPath = resolveZipPath(book.opfDir, tocItem.href);
|
|
1848
|
+
const tocEntry = zipEntry(book, tocPath);
|
|
1849
|
+
if (tocEntry) {
|
|
1850
|
+
const tocDoc = new DOMParser().parseFromString(decodeText(await tocEntry.async('uint8array')), 'application/xml');
|
|
1851
|
+
const entries = tocItem.type === 'application/x-dtbncx+xml'
|
|
1852
|
+
? [...tocDoc.getElementsByTagName('*')].filter((n) => n.localName === 'navPoint').map((n) => {
|
|
1853
|
+
const labelNode = [...n.getElementsByTagName('*')].find((a) => a.localName === 'navLabel');
|
|
1854
|
+
const textNode = labelNode ? [...labelNode.getElementsByTagName('*')].find((a) => a.localName === 'text') : null;
|
|
1855
|
+
const srcNode = [...n.getElementsByTagName('*')].find((a) => a.localName === 'content');
|
|
1856
|
+
return { href: srcNode?.getAttribute('src') || '', text: (textNode?.textContent || '').trim() };
|
|
1857
|
+
})
|
|
1858
|
+
: [...tocDoc.getElementsByTagName('*')].filter((n) => n.localName === 'a' && n.getAttribute('href'))
|
|
1859
|
+
.map((n) => ({ href: n.getAttribute('href'), text: (n.textContent || '').trim() }));
|
|
1860
|
+
const tocDir = tocPath.includes('/') ? tocPath.slice(0, tocPath.lastIndexOf('/')) : '';
|
|
1861
|
+
for (const entry of entries) {
|
|
1862
|
+
const target = resolveZipPath(tocDir, entry.href);
|
|
1863
|
+
const idx = book.spinePaths.indexOf(target);
|
|
1864
|
+
if (idx >= 0 && !book.titles[idx]) book.titles[idx] = entry.text;
|
|
1865
|
+
}
|
|
1866
|
+
}
|
|
1867
|
+
}
|
|
1868
|
+
book.titles = book.titles.map((title, i) => title || `${i + 1}`);
|
|
1869
|
+
return book;
|
|
1870
|
+
}
|
|
1871
|
+
|
|
1872
|
+
/** Render one chapter. Returns { html, urls }; the CALLER owns the blob URLs. */
|
|
1873
|
+
const EPUB_MAX_CSS_BYTES = 512 * 1024;
|
|
1874
|
+
const CSS_MIME = { '.css': 'text/css', '.woff2': 'font/woff2', '.woff': 'font/woff', '.ttf': 'font/ttf', '.otf': 'font/otf', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.svg': 'image/svg+xml' };
|
|
1875
|
+
|
|
1876
|
+
/** Prefix every plain rule with the chapter scope so book styles can never
|
|
1877
|
+
* leak into the reader chrome; @media recurses, @import is dropped,
|
|
1878
|
+
* font-face/keyframes pass through untouched. */
|
|
1879
|
+
function scopeEpubCss(css, scope) {
|
|
1880
|
+
// blockless at-statements (@import/@charset) have no '{' — strip them up
|
|
1881
|
+
// front or the parser would glue them onto the next rule's block
|
|
1882
|
+
css = css.replace(/@(?:import|charset)[^;{}]*;?/giu, '');
|
|
1883
|
+
let out = '';
|
|
1884
|
+
let i = 0;
|
|
1885
|
+
const n = css.length;
|
|
1886
|
+
while (i < n) {
|
|
1887
|
+
const brace = css.indexOf('{', i);
|
|
1888
|
+
if (brace < 0) { out += css.slice(i); break; }
|
|
1889
|
+
const sel = css.slice(i, brace);
|
|
1890
|
+
let depth = 1;
|
|
1891
|
+
let j = brace + 1;
|
|
1892
|
+
while (j < n && depth > 0) {
|
|
1893
|
+
if (css[j] === '{') depth += 1;
|
|
1894
|
+
else if (css[j] === '}') depth -= 1;
|
|
1895
|
+
j += 1;
|
|
1896
|
+
}
|
|
1897
|
+
const block = css.slice(brace + 1, j - 1);
|
|
1898
|
+
const trimmed = sel.trim();
|
|
1899
|
+
if (trimmed.startsWith('@')) {
|
|
1900
|
+
const at = trimmed.replace(/^(@[\w-]+).*$/su, '$1').toLowerCase();
|
|
1901
|
+
if (at === '@import') { /* dropped: no nested fetching */ }
|
|
1902
|
+
else if (at === '@media' || at === '@supports') out += `${sel}{${scopeEpubCss(block, scope)}}`;
|
|
1903
|
+
else out += `${sel}{${block}}`;
|
|
1904
|
+
} else if (trimmed) {
|
|
1905
|
+
const scoped = trimmed.split(',').map((part) => {
|
|
1906
|
+
const p = part.trim();
|
|
1907
|
+
if (!p) return p;
|
|
1908
|
+
if (/^(body|html)$/iu.test(p)) return `.${scope}`;
|
|
1909
|
+
if (/^(body|html)([ .#:[])/iu.test(p)) return `.${scope}${p.replace(/^(body|html)/iu, '')}`;
|
|
1910
|
+
return `.${scope} ${p}`;
|
|
1911
|
+
}).filter(Boolean).join(', ');
|
|
1912
|
+
if (scoped) out += `${scoped}{${block}}`;
|
|
1913
|
+
}
|
|
1914
|
+
i = j;
|
|
1915
|
+
}
|
|
1916
|
+
return out;
|
|
1917
|
+
}
|
|
1918
|
+
|
|
1919
|
+
/** Rewrite url(...) references in chapter CSS to blob URLs from the zip
|
|
1920
|
+
* (embedded fonts and decorative images); collected into `urls` for the
|
|
1921
|
+
* caller's revoke lifecycle. */
|
|
1922
|
+
async function rewriteEpubCssUrls(cssText, book, chapterDir, urls) {
|
|
1923
|
+
const seen = new Map();
|
|
1924
|
+
const jobs = [];
|
|
1925
|
+
for (const m of cssText.matchAll(/url\(\s*(['"]?)([^'")]+)\1\s*\)/gu)) {
|
|
1926
|
+
const raw = m[2];
|
|
1927
|
+
if (!raw || /^(data:|https?:|blob:|#)/iu.test(raw)) continue;
|
|
1928
|
+
const clean = raw.split('?')[0].split('#')[0];
|
|
1929
|
+
const target = clean ? resolveZipPath(chapterDir, clean) : null;
|
|
1930
|
+
if (!target || seen.has(target)) continue;
|
|
1931
|
+
const entry = zipEntry(book, target);
|
|
1932
|
+
if (!entry || (entry._data?.uncompressedSize ?? 0) > EPUB_MAX_IMAGE_BYTES) { seen.set(target, null); continue; }
|
|
1933
|
+
seen.set(target, null);
|
|
1934
|
+
jobs.push(entry.async('uint8array').then((u8) => {
|
|
1935
|
+
const ext = target.slice(target.lastIndexOf('.')).toLowerCase();
|
|
1936
|
+
const blob = new Blob([u8], { type: CSS_MIME[ext] ?? 'application/octet-stream' });
|
|
1937
|
+
const url = URL.createObjectURL(blob);
|
|
1938
|
+
urls.push(url);
|
|
1939
|
+
cssText = cssText.split(m[0]).join(`url(${url})`);
|
|
1940
|
+
}).catch(() => {}));
|
|
1941
|
+
}
|
|
1942
|
+
await Promise.all(jobs);
|
|
1943
|
+
return cssText;
|
|
1944
|
+
}
|
|
1945
|
+
|
|
1946
|
+
/** Cheap whole-book hit scan: which spine chapters contain the query. */
|
|
1947
|
+
async function epubChapterHas(book, needle) {
|
|
1948
|
+
const lower = needle.toLowerCase();
|
|
1949
|
+
const flags = [];
|
|
1950
|
+
for (let i = 0; i < book.spinePaths.length; i++) {
|
|
1951
|
+
const entry = zipEntry(book, book.spinePaths[i]);
|
|
1952
|
+
let has = false;
|
|
1953
|
+
if (entry && (entry._data?.uncompressedSize ?? 0) <= EPUB_MAX_CHAPTER_BYTES) {
|
|
1954
|
+
try { has = decodeText(await entry.async('uint8array')).toLowerCase().includes(lower); } catch { has = false; }
|
|
1955
|
+
}
|
|
1956
|
+
flags.push(has);
|
|
1957
|
+
}
|
|
1958
|
+
return flags;
|
|
1959
|
+
}
|
|
1960
|
+
|
|
1961
|
+
async function renderEpubChapter(book, index) {
|
|
1962
|
+
const chapterPath = book.spinePaths[index];
|
|
1963
|
+
const entry = zipEntry(book, chapterPath);
|
|
1964
|
+
if (!entry) throw new Error(`epub: chapter ${index + 1} missing`);
|
|
1965
|
+
const rawSize = entry._data?.uncompressedSize ?? 0;
|
|
1966
|
+
if (rawSize > EPUB_MAX_CHAPTER_BYTES) throw new Error(`epub: chapter ${index + 1} too large`);
|
|
1967
|
+
const raw = decodeText(await entry.async('uint8array'));
|
|
1968
|
+
// XHTML is strict; real-world books often have one unclosed tag — fall back
|
|
1969
|
+
let doc = new DOMParser().parseFromString(raw, 'application/xhtml+xml');
|
|
1970
|
+
let body = doc.getElementsByTagName('body')[0] ?? doc.body;
|
|
1971
|
+
if (!body) { // malformed OR fragment-only chapter: the HTML parser synthesizes <body>
|
|
1972
|
+
doc = new DOMParser().parseFromString(raw, 'text/html');
|
|
1973
|
+
body = doc.getElementsByTagName('body')[0] ?? doc.body;
|
|
1974
|
+
}
|
|
1975
|
+
if (!body) throw new Error(`epub: chapter ${index + 1} has no body`);
|
|
1976
|
+
const chapterDir = chapterPath.includes('/') ? chapterPath.slice(0, chapterPath.lastIndexOf('/')) : '';
|
|
1977
|
+
const urls = [];
|
|
1978
|
+
// chapter stylesheets: <link rel=stylesheet> from the zip + inline <style>,
|
|
1979
|
+
// scoped to the chapter container and with url() assets inlined as blobs
|
|
1980
|
+
let css = '';
|
|
1981
|
+
const head = doc.getElementsByTagName('head')[0];
|
|
1982
|
+
const cssParts = [];
|
|
1983
|
+
if (head) {
|
|
1984
|
+
for (const link of [...head.querySelectorAll('link[href]')]) {
|
|
1985
|
+
const rel = (link.getAttribute('rel') || '').split(/\s+/u).map((r) => r.toLowerCase());
|
|
1986
|
+
if (!rel.includes('stylesheet')) continue;
|
|
1987
|
+
const target = resolveZipPath(chapterDir, link.getAttribute('href') || '');
|
|
1988
|
+
const cssEntry = target ? zipEntry(book, target) : null;
|
|
1989
|
+
if (!cssEntry || (cssEntry._data?.uncompressedSize ?? 0) > EPUB_MAX_CSS_BYTES) continue;
|
|
1990
|
+
cssParts.push(decodeText(await cssEntry.async('uint8array')));
|
|
1991
|
+
}
|
|
1992
|
+
for (const style of [...head.querySelectorAll('style')]) cssParts.push(style.textContent || '');
|
|
1993
|
+
}
|
|
1994
|
+
if (cssParts.length) {
|
|
1995
|
+
let joined = cssParts.join('\n\n').slice(0, 2 * EPUB_MAX_CSS_BYTES);
|
|
1996
|
+
joined = await rewriteEpubCssUrls(joined, book, chapterDir, urls);
|
|
1997
|
+
css = scopeEpubCss(joined, 'dr-epub-ch').replace(/<\/style/giu, '<\\/style');
|
|
1998
|
+
}
|
|
1999
|
+
// normalize data-src lazy-loading so those images enter the rewrite path
|
|
2000
|
+
for (const img of [...body.querySelectorAll('img[data-src], image[data-src]')]) {
|
|
2001
|
+
img.setAttribute('src', img.getAttribute('data-src') || '');
|
|
2002
|
+
img.removeAttribute('data-src');
|
|
2003
|
+
}
|
|
2004
|
+
for (const img of [...body.querySelectorAll('img[src], image[href], image[xlink\\:href]')]) {
|
|
2005
|
+
const attr = img.hasAttribute('src') ? 'src' : (img.hasAttribute('href') ? 'href' : 'xlink:href');
|
|
2006
|
+
const kind = docUrlKind(img.getAttribute(attr) || '');
|
|
2007
|
+
if (kind !== 'relative') continue; // inline/remote handled by sanitize
|
|
2008
|
+
const target = resolveZipPath(chapterDir, img.getAttribute(attr) || '');
|
|
2009
|
+
const imgEntry = target ? zipEntry(book, target) : null;
|
|
2010
|
+
if (imgEntry) {
|
|
2011
|
+
if ((imgEntry._data?.uncompressedSize ?? 0) > EPUB_MAX_IMAGE_BYTES) { img.removeAttribute(attr); continue; }
|
|
2012
|
+
const blob = await imgEntry.async('blob');
|
|
2013
|
+
const url = URL.createObjectURL(blob);
|
|
2014
|
+
urls.push(url);
|
|
2015
|
+
img.setAttribute('src', url); // normalize xlink:href -> src for the HTML context
|
|
2016
|
+
img.removeAttribute('xlink:href');
|
|
2017
|
+
img.removeAttribute('href');
|
|
2018
|
+
} else img.removeAttribute(attr);
|
|
2019
|
+
}
|
|
2020
|
+
sanitizeFragment(body);
|
|
2021
|
+
return { html: body.innerHTML, urls, css };
|
|
2022
|
+
}
|
|
2023
|
+
|
|
2024
|
+
function EpubView({ path, settings, t, onStatus, onSidebar, sidebar, onOpen }) {
|
|
2025
|
+
const [fatal, setFatal] = useState(null); // whole book unreadable
|
|
2026
|
+
const [chapterError, setChapterError] = useState(null); // this chapter only
|
|
2027
|
+
const [book, setBook] = useState(null);
|
|
2028
|
+
const [chapter, setChapter] = useState(() => {
|
|
2029
|
+
const pos = getPos(path);
|
|
2030
|
+
return pos?.kind === 'epub' && Number.isInteger(pos.chapter) && pos.chapter >= 0 ? pos.chapter : 0;
|
|
2031
|
+
});
|
|
2032
|
+
const [html, setHtml] = useState(null);
|
|
2033
|
+
const [fontSize, setFontSize] = useState(() => {
|
|
2034
|
+
const pos = getPos(path);
|
|
2035
|
+
return (pos && pos.kind === 'epub' && typeof pos.fontSize === 'number') ? pos.fontSize : settings.fontSize;
|
|
2036
|
+
});
|
|
2037
|
+
const [query, setQuery] = useState('');
|
|
2038
|
+
const [count, setCount] = useState(0);
|
|
2039
|
+
const [index, setIndex] = useState(-1);
|
|
2040
|
+
const [css, setCss] = useState('');
|
|
2041
|
+
const bodyRef = useRef(null);
|
|
2042
|
+
const bookRef = useRef(null);
|
|
2043
|
+
bookRef.current = book;
|
|
2044
|
+
const countRef = useRef(0);
|
|
2045
|
+
const hitIndexRef = useRef(-1);
|
|
2046
|
+
const pendingSearchRef = useRef(null); // { query, dirn } to run after a chapter hop
|
|
2047
|
+
const scrollRef = useRef(null);
|
|
2048
|
+
const blobUrlsRef = useRef([]);
|
|
2049
|
+
const chapterRef = useRef(chapter);
|
|
2050
|
+
chapterRef.current = chapter;
|
|
2051
|
+
const search = useDomSearch(bodyRef, (total, idx) => { countRef.current = total; hitIndexRef.current = idx; setCount(total); setIndex(idx); }, onStatus, t);
|
|
2052
|
+
useGuardedLinks(bodyRef, !!html, { onOpen, dir: '' });
|
|
2053
|
+
useScrollRestore(path, scrollRef, () => ({ kind: 'epub', fontSize, chapter: chapterRef.current }), !!html);
|
|
2054
|
+
|
|
2055
|
+
// load book structure
|
|
2056
|
+
useEffect(() => {
|
|
2057
|
+
let alive = true; setFatal(null); setBook(null); setChapter(0); setHtml(null); setChapterError(null); onSidebar(null);
|
|
2058
|
+
blobUrlsRef.current = [];
|
|
2059
|
+
const controller = new AbortController();
|
|
2060
|
+
Promise.all([loadVendor(), fetchFile(path, undefined, controller.signal)])
|
|
2061
|
+
.then(async ([vendor, buf]) => {
|
|
2062
|
+
const parsed = await parseEpub(vendor, buf);
|
|
2063
|
+
if (alive) setBook(parsed);
|
|
2064
|
+
})
|
|
2065
|
+
.catch((e) => { if (alive && e?.name !== 'AbortError') setFatal(e.message); });
|
|
2066
|
+
return () => { alive = false; controller.abort(); onSidebar(null); };
|
|
2067
|
+
}, [path]);
|
|
2068
|
+
|
|
2069
|
+
// render the current chapter
|
|
2070
|
+
useEffect(() => {
|
|
2071
|
+
if (!book) return undefined;
|
|
2072
|
+
let alive = true;
|
|
2073
|
+
const prevUrls = blobUrlsRef.current;
|
|
2074
|
+
blobUrlsRef.current = [];
|
|
2075
|
+
setChapterError(null);
|
|
2076
|
+
setHtml(null);
|
|
2077
|
+
setCount(0);
|
|
2078
|
+
setIndex(-1);
|
|
2079
|
+
renderEpubChapter(book, chapter)
|
|
2080
|
+
.then(({ html: out, urls, css: chapterCss }) => {
|
|
2081
|
+
if (!alive) { for (const u of urls) URL.revokeObjectURL(u); return; }
|
|
2082
|
+
for (const u of prevUrls) URL.revokeObjectURL(u); // old chapter's images die only once replaced
|
|
2083
|
+
blobUrlsRef.current = urls;
|
|
2084
|
+
setCss(chapterCss || '');
|
|
2085
|
+
setHtml(out);
|
|
2086
|
+
})
|
|
2087
|
+
.catch((e) => { if (alive) setChapterError(e?.message ?? String(e)); });
|
|
2088
|
+
return () => { alive = false; };
|
|
2089
|
+
}, [book, chapter]);
|
|
2090
|
+
|
|
2091
|
+
// revoke everything on unmount / path switch
|
|
2092
|
+
useEffect(() => () => {
|
|
2093
|
+
for (const u of blobUrlsRef.current) URL.revokeObjectURL(u);
|
|
2094
|
+
blobUrlsRef.current = [];
|
|
2095
|
+
}, []);
|
|
2096
|
+
|
|
2097
|
+
// a chapter hop for whole-book search lands here: run the query in the
|
|
2098
|
+
// freshly rendered chapter once its DOM exists
|
|
2099
|
+
useEffect(() => {
|
|
2100
|
+
const pending = pendingSearchRef.current;
|
|
2101
|
+
if (!html || !pending) return;
|
|
2102
|
+
pendingSearchRef.current = null;
|
|
2103
|
+
search.run(pending.query, pending.dirn);
|
|
2104
|
+
if (countRef.current > 0 && bookRef.current) {
|
|
2105
|
+
const title = bookRef.current.titles?.[chapterRef.current] || String(chapterRef.current + 1);
|
|
2106
|
+
onStatus(`${t('panel.searchJumped')}: ${title} · ${countRef.current}`);
|
|
2107
|
+
}
|
|
2108
|
+
}, [html]);
|
|
2109
|
+
|
|
2110
|
+
// whole-book search: a miss or a boundary in this chapter hops to the next
|
|
2111
|
+
// chapter that contains the query
|
|
2112
|
+
const runSearch = async (dirn) => {
|
|
2113
|
+
const q = query.trim();
|
|
2114
|
+
if (!q) { search.clear(); countRef.current = 0; return; }
|
|
2115
|
+
search.run(q, dirn);
|
|
2116
|
+
if (countRef.current > 0) return;
|
|
2117
|
+
if (!bookRef.current) return;
|
|
2118
|
+
const flags = await epubChapterHas(bookRef.current, q);
|
|
2119
|
+
const n = flags.length;
|
|
2120
|
+
let next = -1;
|
|
2121
|
+
for (let step = 1; step <= n; step++) { const i = (chapterRef.current + step) % n; if (flags[i]) { next = i; break; } }
|
|
2122
|
+
if (next >= 0) { pendingSearchRef.current = { query: q, dirn }; setChapter(next); }
|
|
2123
|
+
};
|
|
2124
|
+
const navSearch = async (dir) => {
|
|
2125
|
+
if (countRef.current === 0) return;
|
|
2126
|
+
if (dir > 0 && hitIndexRef.current < countRef.current - 1) return search.navigate(1);
|
|
2127
|
+
if (dir < 0 && hitIndexRef.current > 0) return search.navigate(-1);
|
|
2128
|
+
const q = query.trim();
|
|
2129
|
+
if (!q || !bookRef.current) return search.navigate(dir);
|
|
2130
|
+
const flags = await epubChapterHas(bookRef.current, q);
|
|
2131
|
+
const n = flags.length;
|
|
2132
|
+
let next = -1;
|
|
2133
|
+
for (let step = 1; step <= n; step++) { const i = ((chapterRef.current + dir * step) % n + n) % n; if (flags[i]) { next = i; break; } }
|
|
2134
|
+
if (next >= 0 && next !== chapterRef.current) { pendingSearchRef.current = { query: q, dirn: dir }; setChapter(next); }
|
|
2135
|
+
else search.navigate(dir); // wrap inside this chapter
|
|
2136
|
+
};
|
|
2137
|
+
|
|
2138
|
+
// chapter sidebar
|
|
2139
|
+
useEffect(() => {
|
|
2140
|
+
if (!book) return undefined;
|
|
2141
|
+
onSidebar({
|
|
2142
|
+
kind: 'outline',
|
|
2143
|
+
items: book.titles.map((title, i) => ({ level: 1, text: `${i + 1}. ${title}`, id: `ch-${i}` })),
|
|
2144
|
+
go: (id) => { const i = Number(String(id).slice(3)); if (Number.isInteger(i) && i >= 0 && i < book.spine.length) setChapter(i); },
|
|
2145
|
+
});
|
|
2146
|
+
return () => onSidebar(null);
|
|
2147
|
+
}, [book]);
|
|
2148
|
+
|
|
2149
|
+
if (fatal) return h('div', { className: 'dr-error' }, `${t('panel.error')}: ${fatal}`);
|
|
2150
|
+
if (!book) return h('div', { className: 'dr-load' }, t('panel.loading'));
|
|
2151
|
+
return h(React.Fragment, null,
|
|
2152
|
+
h(ViewBar, null,
|
|
2153
|
+
h(SearchControls, { t, query, setQuery, count, index,
|
|
2154
|
+
onEnter: (dirn) => { void runSearch(dirn); },
|
|
2155
|
+
onPrev: () => { void navSearch(-1); }, onNext: () => { void navSearch(1); } }),
|
|
2156
|
+
h('span', { style: { flex: 1 } }),
|
|
2157
|
+
h('span', { className: 'dr-badge' }, `${chapter + 1}/${book.spine.length}`),
|
|
2158
|
+
h(Btn, { title: t('panel.prevPage'), onClick: () => setChapter((c) => Math.max(0, c - 1)), disabled: chapter <= 0 }, '‹'),
|
|
2159
|
+
h(Btn, { title: t('panel.nextPage'), onClick: () => setChapter((c) => Math.min(book.spine.length - 1, c + 1)), disabled: chapter >= book.spine.length - 1 }, '›'),
|
|
2160
|
+
h(FontControls, { t, fontSize, setFontSize, settings })),
|
|
2161
|
+
h('div', { className: 'dr-stage', style: { '--dr-line-height': settings.lineHeight } },
|
|
2162
|
+
sidebar,
|
|
2163
|
+
h('div', { className: 'dr-scroll', ref: scrollRef },
|
|
2164
|
+
chapterError
|
|
2165
|
+
? h('div', { className: 'dr-error' }, `${t('panel.error')}: ${chapterError}`)
|
|
2166
|
+
: html
|
|
2167
|
+
? h('article', { className: `dr-md dr-epub-ch`, ref: bodyRef, style: { fontSize: `${fontSize}px` }, dangerouslySetInnerHTML: { __html: (css ? `<style>${css}</style>` : '') + html } })
|
|
2168
|
+
: h('div', { className: 'dr-load' }, t('panel.loading')))),
|
|
2169
|
+
h(SaveFontSize, { path, kind: 'epub', fontSize }));
|
|
2170
|
+
}
|
|
2171
|
+
|
|
2172
|
+
// ---------- content sidebar (outline / page list) ----------
|
|
2173
|
+
/** Virtualized page-number list: only the visible window of buttons is
|
|
2174
|
+
* mounted, so a 2000-page PDF re-renders ~30 rows on page change. */
|
|
2175
|
+
function PageList({ model, t }) {
|
|
2176
|
+
const ROW = 26;
|
|
2177
|
+
const scrollRef = useRef(null);
|
|
2178
|
+
const [scrollTop, setScrollTop] = useState(0);
|
|
2179
|
+
const [viewportH, setViewportH] = useState(400);
|
|
2180
|
+
useEffect(() => {
|
|
2181
|
+
const el = scrollRef.current;
|
|
2182
|
+
if (el) setViewportH(el.clientHeight || 400);
|
|
2183
|
+
}, []);
|
|
2184
|
+
useEffect(() => {
|
|
2185
|
+
const el = scrollRef.current;
|
|
2186
|
+
if (el && model.currentPage > 0) {
|
|
2187
|
+
const target = (model.currentPage - 1) * ROW;
|
|
2188
|
+
if (target < el.scrollTop || target > el.scrollTop + el.clientHeight - ROW) {
|
|
2189
|
+
el.scrollTop = Math.max(0, target - el.clientHeight / 2);
|
|
2190
|
+
}
|
|
2191
|
+
}
|
|
2192
|
+
}, [model.currentPage]);
|
|
2193
|
+
const total = model.numPages;
|
|
2194
|
+
const first = Math.max(0, Math.floor(scrollTop / ROW) - 5);
|
|
2195
|
+
const last = Math.min(total, first + Math.ceil(viewportH / ROW) + 10);
|
|
2196
|
+
const btnStyle = (active) => ({ position: 'absolute', left: 0, right: 0, textAlign: 'left', background: active ? 'var(--dsw-alias-interactive-bg-hover)' : 'none', border: 'none', color: active ? 'var(--dsw-alias-label-primary)' : 'var(--dsw-alias-label-secondary)', cursor: 'pointer', padding: '3px 8px', fontSize: '12px', fontFamily: 'inherit', lineHeight: 1.6, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', borderRadius: '4px' });
|
|
2197
|
+
return h('div', {
|
|
2198
|
+
ref: scrollRef,
|
|
2199
|
+
onScroll: (e) => setScrollTop(e.currentTarget.scrollTop),
|
|
2200
|
+
style: { flex: '1 1 0', minHeight: 0, overflowY: 'auto', position: 'relative' },
|
|
2201
|
+
},
|
|
2202
|
+
h('div', { style: { height: `${total * ROW}px`, position: 'relative' } },
|
|
2203
|
+
Array.from({ length: last - first }, (_, i) => {
|
|
2204
|
+
const num = first + i + 1;
|
|
2205
|
+
return h('button', {
|
|
2206
|
+
key: num, style: { ...btnStyle(model.currentPage === num), top: `${(num - 1) * ROW}px`, height: `${ROW - 3}px` },
|
|
2207
|
+
onClick: () => model.go?.(num),
|
|
2208
|
+
}, `${t('panel.page')} ${num}`);
|
|
2209
|
+
})));
|
|
2210
|
+
}
|
|
2211
|
+
|
|
2212
|
+
function ContentSidebar({ model, t, onCollapse }) {
|
|
2213
|
+
const [width, setWidth] = useState(() => {
|
|
2214
|
+
const saved = readJson(LS.tocWidth, 200);
|
|
2215
|
+
return Number.isFinite(saved) ? clamp(saved, 160, 480) : 200;
|
|
2216
|
+
});
|
|
2217
|
+
const widthRef = useRef(width);
|
|
2218
|
+
widthRef.current = width;
|
|
2219
|
+
const dragCleanupRef = useRef(null);
|
|
2220
|
+
const onHandleDown = (e) => {
|
|
2221
|
+
if (e.button !== 0) return;
|
|
2222
|
+
e.preventDefault();
|
|
2223
|
+
const startX = e.clientX;
|
|
2224
|
+
const startW = widthRef.current;
|
|
2225
|
+
const onMove = (ev) => { const w = clamp(startW + ev.clientX - startX, 160, 480); widthRef.current = w; setWidth(w); };
|
|
2226
|
+
const stop = () => {
|
|
2227
|
+
window.removeEventListener('mousemove', onMove);
|
|
2228
|
+
window.removeEventListener('mouseup', onUp);
|
|
2229
|
+
dragCleanupRef.current = null;
|
|
2230
|
+
writeJson(LS.tocWidth, widthRef.current);
|
|
2231
|
+
};
|
|
2232
|
+
dragCleanupRef.current = stop;
|
|
2233
|
+
window.addEventListener('mousemove', onMove);
|
|
2234
|
+
window.addEventListener('mouseup', onUp);
|
|
2235
|
+
};
|
|
2236
|
+
useEffect(() => () => { dragCleanupRef.current?.(); }, []);
|
|
2237
|
+
if (!model) return null;
|
|
2238
|
+
return h('aside', {
|
|
2239
|
+
'aria-label': t('panel.outline'),
|
|
2240
|
+
style: { width: `${width}px`, flex: 'none', minWidth: 0, boxSizing: 'border-box', display: 'flex', flexDirection: 'column', fontSize: '12px', background: 'var(--dsw-alias-bg-layer-1)', borderRight: '.5px solid var(--dsw-alias-border-l1)', position: 'relative' },
|
|
2241
|
+
},
|
|
2242
|
+
h('div', {
|
|
2243
|
+
'aria-label': t('panel.resizeSidebar'), title: t('panel.resizeSidebar'),
|
|
2244
|
+
onMouseDown: onHandleDown,
|
|
2245
|
+
style: { position: 'absolute', top: 0, bottom: 0, right: 0, width: '5px', cursor: 'col-resize', zIndex: 5 },
|
|
2246
|
+
}),
|
|
2247
|
+
h('div', { style: { position: 'relative', display: 'flex', alignItems: 'center', padding: '8px 6px 6px 6px', width: '100%', boxSizing: 'border-box', flex: 'none' } },
|
|
2248
|
+
h('span', { style: { fontSize: '11px', color: 'var(--dsw-alias-label-tertiary)', whiteSpace: 'nowrap', flex: 'none', paddingRight: '28px' } },
|
|
2249
|
+
model.kind === 'outline' ? t('panel.outline') : t('panel.pages')),
|
|
2250
|
+
onCollapse && h('button', {
|
|
2251
|
+
style: { position: 'absolute', right: '2px', top: '50%', transform: 'translateY(-50%)', background: 'none', border: 'none', color: 'var(--dsw-alias-label-tertiary)', cursor: 'pointer', padding: '2px 8px', borderRadius: '4px', fontSize: '13px', lineHeight: 1, display: 'inline-flex', alignItems: 'center' },
|
|
2252
|
+
title: t('panel.collapseSidebar'), onClick: onCollapse,
|
|
2253
|
+
}, '‹')),
|
|
2254
|
+
model.kind === 'outline'
|
|
2255
|
+
? h('div', { style: { flex: '1 1 0', minHeight: 0, overflowY: 'auto', padding: '0 0 12px' } },
|
|
2256
|
+
model.items.map((item, i) => h('button', {
|
|
2257
|
+
key: `${item.id}-${i}`, title: item.text,
|
|
2258
|
+
style: { display: 'block', width: '100%', textAlign: 'left', background: 'none', border: 'none', color: 'var(--dsw-alias-label-secondary)', cursor: 'pointer', padding: '3px 8px', fontSize: '12px', fontFamily: 'inherit', lineHeight: 1.6, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', borderRadius: '4px', paddingLeft: `${6 + (item.level - 1) * 10}px` },
|
|
2259
|
+
onClick: () => (model.go
|
|
2260
|
+
? model.go(item.id)
|
|
2261
|
+
: document.getElementById(item.id)?.scrollIntoView({ behavior: 'smooth', block: 'start' })),
|
|
2262
|
+
}, item.text || '(?)')))
|
|
2263
|
+
: h(PageList, { model, t }));
|
|
2264
|
+
}
|
|
2265
|
+
|
|
2266
|
+
// ---------- file browser / recent ----------
|
|
2267
|
+
function FileBrowser({ onOpen, t, version }) {
|
|
2268
|
+
const [dir, setDir] = useState(null);
|
|
2269
|
+
const [listing, setListing] = useState(null);
|
|
2270
|
+
const [err, setErr] = useState(null);
|
|
2271
|
+
useEffect(() => { let alive = true; setErr(null);
|
|
2272
|
+
const controller = new AbortController();
|
|
2273
|
+
fetch(LIST_URL(dir ?? ''), { signal: controller.signal })
|
|
2274
|
+
.then((r) => (r.ok ? r.json() : r.json().then((j) => Promise.reject(new Error(j.error)))))
|
|
2275
|
+
.then((data) => { if (alive) setListing(data); })
|
|
2276
|
+
.catch((e) => { if (alive && e.name !== 'AbortError') setErr(e.message); });
|
|
2277
|
+
return () => { alive = false; controller.abort(); };
|
|
2278
|
+
}, [dir, version]);
|
|
2279
|
+
const crumbs = useMemo(() => {
|
|
2280
|
+
if (!listing) return [];
|
|
2281
|
+
const parts = listing.path.split('/').filter(Boolean);
|
|
2282
|
+
return [{ name: '/', path: '/' }, ...parts.map((name, i) => ({ name, path: '/' + parts.slice(0, i + 1).join('/') }))];
|
|
2283
|
+
}, [listing]);
|
|
2284
|
+
const parent = listing && listing.path !== '/' ? (listing.path.replace(/\/[^/]+\/?$/u, '') || '/') : null;
|
|
2285
|
+
return h('div', { style: { display: 'flex', flexDirection: 'column', minHeight: 0, flex: 1 } },
|
|
2286
|
+
h('div', { className: 'dr-crumbs' },
|
|
2287
|
+
crumbs.map((c, i) => h(React.Fragment, { key: c.path },
|
|
2288
|
+
i > 0 && '› ',
|
|
2289
|
+
h('button', { className: 'dr-crumb', onClick: () => setDir(c.path) }, c.name))),
|
|
2290
|
+
err && h('span', { style: { color: 'var(--dsw-alias-label-primary)' } }, `⚠ ${err}`)),
|
|
2291
|
+
h('div', { className: 'dr-side-scroll' },
|
|
2292
|
+
parent && h('button', { className: 'dr-row', onClick: () => setDir(parent) },
|
|
2293
|
+
h('span', null, '↩ '), h('span', null, '..')),
|
|
2294
|
+
(listing?.entries ?? []).map((entry) => h('button', {
|
|
2295
|
+
key: entry.path, className: 'dr-row',
|
|
2296
|
+
onClick: () => (entry.directory ? setDir(entry.path) : onOpen(entry.path)),
|
|
2297
|
+
title: entry.path,
|
|
2298
|
+
},
|
|
2299
|
+
entry.directory ? Glyph.dir(14) : kindGlyph(kindOf(entry.path), 14),
|
|
2300
|
+
h('span', null, entry.name),
|
|
2301
|
+
!entry.directory && h('small', null, entry.size > 1048576 ? `${(entry.size / 1048576).toFixed(1)}M` : `${Math.max(1, Math.round(entry.size / 1024))}K`))),
|
|
2302
|
+
listing?.truncated && h('div', { className: 'dr-empty-side' }, t('panel.listTruncated')),
|
|
2303
|
+
err === null && listing !== null && listing.entries.length === 0 && h('div', { className: 'dr-empty-side' }, t('panel.emptyDir')),
|
|
2304
|
+
err === null && listing === null && h('div', { className: 'dr-empty-side' }, t('panel.loading'))));
|
|
2305
|
+
}
|
|
2306
|
+
|
|
2307
|
+
// shared date formatter (avoids re-creating per row per render)
|
|
2308
|
+
const recentDateFmt = new Intl.DateTimeFormat(undefined, { year: 'numeric', month: '2-digit', day: '2-digit' });
|
|
2309
|
+
const RECENT_CHECK_TTL = 24 * 60 * 60 * 1000;
|
|
2310
|
+
|
|
2311
|
+
/** Corrupt entries (non-array storage, missing path/at) must never crash
|
|
2312
|
+
* the render — normalize on every read. */
|
|
2313
|
+
function readRecentSafe() {
|
|
2314
|
+
const raw = readJson(LS.recent, []);
|
|
2315
|
+
if (!Array.isArray(raw)) return [];
|
|
2316
|
+
return raw.filter((e) => e && typeof e.path === 'string' && Number.isFinite(e.at));
|
|
2317
|
+
}
|
|
2318
|
+
|
|
2319
|
+
function RecentList({ onOpen, onFlash, settings, version, t }) {
|
|
2320
|
+
const [recent, setRecent] = useState(() => readRecentSafe());
|
|
2321
|
+
useEffect(() => {
|
|
2322
|
+
const list = readRecentSafe();
|
|
2323
|
+
setRecent(list);
|
|
2324
|
+
// prune entries whose file no longer exists (rename leftovers etc.);
|
|
2325
|
+
// re-check at most once a day per entry to avoid HEAD storms
|
|
2326
|
+
let alive = true;
|
|
2327
|
+
const stale = list.filter((e) => !e.checked || Date.now() - e.checked > RECENT_CHECK_TTL);
|
|
2328
|
+
if (stale.length === 0) return () => { alive = false; };
|
|
2329
|
+
Promise.all(stale.map(async (e) => {
|
|
2330
|
+
try { const r = await fetch(FILE_URL(e.path), { method: 'HEAD' }); return r.ok; }
|
|
2331
|
+
catch { return false; }
|
|
2332
|
+
})).then((results) => {
|
|
2333
|
+
if (!alive) return;
|
|
2334
|
+
const alivePaths = new Set(stale.filter((_, i) => results[i]).map((e) => e.path));
|
|
2335
|
+
const deadPaths = new Set(stale.filter((_, i) => !results[i]).map((e) => e.path));
|
|
2336
|
+
// re-read: the user may have edited the list while we probed;
|
|
2337
|
+
// remove only confirmed-dead entries, keep everything else
|
|
2338
|
+
const fresh = readRecentSafe();
|
|
2339
|
+
const next = fresh
|
|
2340
|
+
.filter((e) => !deadPaths.has(e.path))
|
|
2341
|
+
.map((e) => (alivePaths.has(e.path) ? { ...e, checked: Date.now() } : e));
|
|
2342
|
+
for (const dead of deadPaths) { removePos(dead); removeDraft(dead); }
|
|
2343
|
+
writeJson(LS.recent, next);
|
|
2344
|
+
setRecent(next);
|
|
2345
|
+
});
|
|
2346
|
+
return () => { alive = false; };
|
|
2347
|
+
}, [version]);
|
|
2348
|
+
const refresh = () => setRecent(readJson(LS.recent, []));
|
|
2349
|
+
const remove = (path) => {
|
|
2350
|
+
writeJson(LS.recent, readJson(LS.recent, []).filter((e) => e.path !== path));
|
|
2351
|
+
removePos(path);
|
|
2352
|
+
refresh();
|
|
2353
|
+
};
|
|
2354
|
+
const reveal = async (path) => {
|
|
2355
|
+
const res = await fetch(REVEAL_URL(path));
|
|
2356
|
+
if (!res.ok) {
|
|
2357
|
+
const detail = await res.json().catch(() => ({ error: res.statusText }));
|
|
2358
|
+
onFlash(detail.error || 'reveal failed');
|
|
2359
|
+
}
|
|
2360
|
+
};
|
|
2361
|
+
// instant hover tooltip: native `title` has a ~1s browser delay, which
|
|
2362
|
+
// reads as "broken" on 22px action buttons — see useTip for details.
|
|
2363
|
+
const { hoverProps, hide: hideTip } = useTip();
|
|
2364
|
+
return h('div', { className: 'dr-side-scroll' },
|
|
2365
|
+
recent.length === 0 && h('div', { className: 'dr-empty-side' }, t('panel.recentEmpty')),
|
|
2366
|
+
recent.slice(0, settings.recentLimit).map((e) => h('div', {
|
|
2367
|
+
key: e.path, className: 'dr-row', title: e.path,
|
|
2368
|
+
onClick: () => onOpen(e.path), role: 'button', tabIndex: 0,
|
|
2369
|
+
onKeyDown: (ev) => { if (ev.key === 'Enter') onOpen(e.path); },
|
|
2370
|
+
},
|
|
2371
|
+
kindGlyph(e.kind ?? kindOf(e.path), 14),
|
|
2372
|
+
h('span', null, e.path.slice(e.path.lastIndexOf('/') + 1)),
|
|
2373
|
+
h('small', null, recentDateFmt.format(new Date(e.at))),
|
|
2374
|
+
h('span', { className: 'dr-row-actions' },
|
|
2375
|
+
h('button', {
|
|
2376
|
+
'aria-label': t('panel.revealInFinder'), 'data-action': 'reveal',
|
|
2377
|
+
onClick: (ev) => { ev.stopPropagation(); hideTip(); void reveal(e.path); },
|
|
2378
|
+
...hoverProps(t('panel.revealInFinder')),
|
|
2379
|
+
}, Glyph.folder(12)),
|
|
2380
|
+
h('button', {
|
|
2381
|
+
'aria-label': t('panel.removeRecent'), 'data-action': 'remove',
|
|
2382
|
+
onClick: (ev) => { ev.stopPropagation(); hideTip(); remove(e.path); },
|
|
2383
|
+
...hoverProps(t('panel.removeRecent')),
|
|
2384
|
+
}, '✕')))),
|
|
2385
|
+
recent.length > 0 && h('button', {
|
|
2386
|
+
className: 'dr-row', style: { color: 'var(--dsw-alias-label-tertiary)' },
|
|
2387
|
+
onClick: () => { writeJson(LS.recent, []); refresh(); },
|
|
2388
|
+
}, h('span', null, '🗑 '), h('span', null, t('panel.clearRecent'))));
|
|
2389
|
+
}
|
|
2390
|
+
|
|
2391
|
+
/** Modal directory browser: reuse FileBrowser inside an overlay dialog. */
|
|
2392
|
+
function BrowseOverlay({ t, version, onOpen, onClose }) {
|
|
2393
|
+
useEffect(() => {
|
|
2394
|
+
const onKey = (e) => { if (e.key === 'Escape') onClose(); };
|
|
2395
|
+
window.addEventListener('keydown', onKey);
|
|
2396
|
+
return () => window.removeEventListener('keydown', onKey);
|
|
2397
|
+
}, [onClose]);
|
|
2398
|
+
return h('div', { style: { position: 'fixed', inset: 0, background: 'rgba(0,0,0,.32)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 60 }, onClick: (e) => { if (e.target === e.currentTarget) onClose(); } },
|
|
2399
|
+
h('div', { style: { width: 'min(560px,86vw)', height: 'min(520px,80vh)', background: 'var(--dsw-alias-bg-layer-1)', border: '.5px solid var(--dsw-alias-border-l3)', borderRadius: '10px', display: 'flex', flexDirection: 'column', boxShadow: '0 12px 40px rgba(0,0,0,.3)', overflow: 'hidden' }, role: 'dialog', 'aria-label': t('panel.browse') },
|
|
2400
|
+
h('div', { style: { display: 'flex', alignItems: 'center', gap: '8px', padding: '10px 14px', borderBottom: '.5px solid var(--dsw-alias-border-l2)', fontSize: '13px', fontWeight: 600, flex: 'none' } }, Glyph.folder(15), ' ', t('panel.browse')),
|
|
2401
|
+
h(FileBrowser, { onOpen, t, version }),
|
|
2402
|
+
h('div', { style: { display: 'flex', justifyContent: 'flex-end', gap: '8px', padding: '8px 12px', borderTop: '.5px solid var(--dsw-alias-border-l2)', flex: 'none' } },
|
|
2403
|
+
h(Btn, { title: t('panel.close'), onClick: onClose }, t('panel.close')))));
|
|
2404
|
+
}
|
|
2405
|
+
|
|
2406
|
+
// ---------- editor pane (text / markdown edit mode) ----------
|
|
2407
|
+
function EditorPane({ value, onChange, onSave, busy, label, areaRef: externalRef }) {
|
|
2408
|
+
const localRef = useRef(null);
|
|
2409
|
+
const areaRef = externalRef ?? localRef;
|
|
2410
|
+
const linesRef = useRef(null);
|
|
2411
|
+
const saveRef = useRef(onSave);
|
|
2412
|
+
saveRef.current = onSave;
|
|
2413
|
+
useEffect(() => {
|
|
2414
|
+
const onKey = (e) => {
|
|
2415
|
+
if ((e.ctrlKey || e.metaKey) && !e.altKey && e.key.toLowerCase() === 's') {
|
|
2416
|
+
e.preventDefault();
|
|
2417
|
+
saveRef.current?.();
|
|
2418
|
+
}
|
|
2419
|
+
};
|
|
2420
|
+
window.addEventListener('keydown', onKey);
|
|
2421
|
+
return () => window.removeEventListener('keydown', onKey);
|
|
2422
|
+
}, []);
|
|
2423
|
+
useEffect(() => {
|
|
2424
|
+
const el = areaRef.current;
|
|
2425
|
+
if (el) { el.focus(); const end = el.value.length; el.setSelectionRange(end, end); }
|
|
2426
|
+
}, []);
|
|
2427
|
+
const lineCount = useMemo(() => (value ? value.split('\n').length : 1), [value]);
|
|
2428
|
+
const numbers = useMemo(() => Array.from({ length: lineCount }, (_, i) => i + 1).join('\n'), [lineCount]);
|
|
2429
|
+
return h('div', { className: 'dr-editor-shell' },
|
|
2430
|
+
h('pre', { ref: linesRef, className: 'dr-editor-lines', 'aria-hidden': true }, numbers),
|
|
2431
|
+
h('textarea', {
|
|
2432
|
+
ref: areaRef, className: 'dr-editor', value, spellCheck: false, disabled: busy,
|
|
2433
|
+
'aria-label': label,
|
|
2434
|
+
onChange: (e) => onChange(e.target.value),
|
|
2435
|
+
onScroll: () => { if (linesRef.current && areaRef.current) linesRef.current.scrollTop = areaRef.current.scrollTop; },
|
|
2436
|
+
}));
|
|
2437
|
+
}
|
|
2438
|
+
|
|
2439
|
+
/** In-editor find: textarea has no live highlight, so matches are
|
|
2440
|
+
* selected and scrolled into view instead. */
|
|
2441
|
+
function useEditorSearch(text) {
|
|
2442
|
+
const areaRef = useRef(null);
|
|
2443
|
+
const [count, setCount] = useState(0);
|
|
2444
|
+
const [index, setIndex] = useState(-1);
|
|
2445
|
+
const indexRef = useRef(-1);
|
|
2446
|
+
const positionsRef = useRef([]);
|
|
2447
|
+
const needleRef = useRef('');
|
|
2448
|
+
const textRef = useRef(text);
|
|
2449
|
+
if (textRef.current !== text) { // draft edited after a search: offsets are stale
|
|
2450
|
+
textRef.current = text;
|
|
2451
|
+
positionsRef.current = [];
|
|
2452
|
+
needleRef.current = '';
|
|
2453
|
+
indexRef.current = -1;
|
|
2454
|
+
if (count !== 0) { setCount(0); setIndex(-1); }
|
|
2455
|
+
}
|
|
2456
|
+
const measureTop = (el, at) => measureTextareaTop(el, text, at);
|
|
2457
|
+
const focusMatch = (i) => {
|
|
2458
|
+
const el = areaRef.current;
|
|
2459
|
+
const positions = positionsRef.current;
|
|
2460
|
+
if (!el || !positions.length) return;
|
|
2461
|
+
const total = positions.length;
|
|
2462
|
+
const normalized = ((i % total) + total) % total;
|
|
2463
|
+
const at = positions[normalized];
|
|
2464
|
+
const len = needleRef.current.length;
|
|
2465
|
+
el.focus();
|
|
2466
|
+
el.setSelectionRange(at, at + len);
|
|
2467
|
+
const measured = measureTop(el, at);
|
|
2468
|
+
if (measured !== null) el.scrollTop = Math.max(0, Math.round(measured - el.clientHeight / 2));
|
|
2469
|
+
else {
|
|
2470
|
+
const line = (text.slice(0, at).match(/\n/g) ?? []).length;
|
|
2471
|
+
const style = getComputedStyle(el);
|
|
2472
|
+
const lineH = parseFloat(style.lineHeight) || 22;
|
|
2473
|
+
el.scrollTop = Math.max(0, Math.round(line * lineH - el.clientHeight / 2));
|
|
2474
|
+
}
|
|
2475
|
+
indexRef.current = normalized;
|
|
2476
|
+
setIndex(normalized);
|
|
2477
|
+
};
|
|
2478
|
+
const run = (query, dir) => {
|
|
2479
|
+
const needle = query.trim().toLowerCase();
|
|
2480
|
+
if (!needle || !text) { positionsRef.current = []; setCount(0); setIndex(-1); indexRef.current = -1; return; }
|
|
2481
|
+
const hay = text.toLowerCase();
|
|
2482
|
+
const positions = [];
|
|
2483
|
+
let at = hay.indexOf(needle);
|
|
2484
|
+
while (at >= 0 && positions.length < 5000) { positions.push(at); at = hay.indexOf(needle, at + needle.length); }
|
|
2485
|
+
positionsRef.current = positions;
|
|
2486
|
+
needleRef.current = needle;
|
|
2487
|
+
setCount(positions.length);
|
|
2488
|
+
focusMatch(dir < 0 ? positions.length - 1 : 0);
|
|
2489
|
+
};
|
|
2490
|
+
const navigate = (dir) => focusMatch((indexRef.current < 0 ? 0 : indexRef.current + dir));
|
|
2491
|
+
return { areaRef, count, index, run, navigate };
|
|
2492
|
+
}
|
|
2493
|
+
|
|
2494
|
+
/** Shared edit-mode state machine for text/markdown viewers. */
|
|
2495
|
+
function useEditMode({ path, currentText, onSaved, t, onStatus }) {
|
|
2496
|
+
const [editing, setEditing] = useState(false);
|
|
2497
|
+
const [draft, setDraft] = useState('');
|
|
2498
|
+
const [busy, setBusy] = useState(false);
|
|
2499
|
+
const baseRef = useRef('');
|
|
2500
|
+
const lastPathRef = useRef(path);
|
|
2501
|
+
const dirty = editing && draft !== baseRef.current;
|
|
2502
|
+
const enter = useCallback(() => {
|
|
2503
|
+
baseRef.current = currentText ?? '';
|
|
2504
|
+
// restore an unsaved draft stashed when the file was switched away
|
|
2505
|
+
const stashed = readJson(LS.draft(path), null);
|
|
2506
|
+
setDraft(typeof stashed === 'string' && stashed ? stashed : baseRef.current);
|
|
2507
|
+
setEditing(true);
|
|
2508
|
+
onStatus(typeof stashed === 'string' && stashed ? t('panel.draftRestored') : t('panel.editModeHint'));
|
|
2509
|
+
}, [currentText, path, onStatus, t]);
|
|
2510
|
+
const exit = useCallback(() => {
|
|
2511
|
+
if (busy) return;
|
|
2512
|
+
if (draft !== baseRef.current && !window.confirm(t('panel.unsavedConfirm'))) return;
|
|
2513
|
+
removeDraft(path); // leaving on purpose: drop the stash
|
|
2514
|
+
setEditing(false);
|
|
2515
|
+
onStatus('');
|
|
2516
|
+
}, [busy, draft, path, onStatus, t]);
|
|
2517
|
+
const save = useCallback(async () => {
|
|
2518
|
+
if (!editing || busy) return;
|
|
2519
|
+
if (draft === baseRef.current) { onStatus(t('panel.noChanges')); return; }
|
|
2520
|
+
setBusy(true);
|
|
2521
|
+
try {
|
|
2522
|
+
const res = await fetch(`${ROUTE}/save`, {
|
|
2523
|
+
method: 'POST',
|
|
2524
|
+
headers: { 'content-type': 'application/json' },
|
|
2525
|
+
body: JSON.stringify({ path, baseContent: baseRef.current, content: draft }),
|
|
2526
|
+
});
|
|
2527
|
+
const data = await res.json().catch(() => ({}));
|
|
2528
|
+
if (!res.ok) throw Object.assign(new Error(data.error || `${res.status}`), { status: res.status });
|
|
2529
|
+
baseRef.current = draft;
|
|
2530
|
+
removeDraft(path);
|
|
2531
|
+
onStatus(t('panel.saved'));
|
|
2532
|
+
onSaved(draft);
|
|
2533
|
+
} catch (e) {
|
|
2534
|
+
if (e.status === 409) {
|
|
2535
|
+
// the file changed on disk: rebase onto the fresh content but
|
|
2536
|
+
// KEEP the user's draft — saving again overwrites the disk copy
|
|
2537
|
+
const fresh = await fetchFile(path, 'text').catch(() => null);
|
|
2538
|
+
if (fresh !== null) baseRef.current = fresh;
|
|
2539
|
+
onStatus(t('panel.saveConflictRebased'));
|
|
2540
|
+
} else {
|
|
2541
|
+
onStatus(`${t('panel.saveFailed')}: ${e.message}`);
|
|
2542
|
+
}
|
|
2543
|
+
} finally {
|
|
2544
|
+
setBusy(false);
|
|
2545
|
+
}
|
|
2546
|
+
}, [editing, busy, draft, path, onSaved, onStatus, t]);
|
|
2547
|
+
// switching documents under the editor: stash the unsaved draft keyed
|
|
2548
|
+
// by the OLD path (localStorage quota permitting) instead of losing it
|
|
2549
|
+
useEffect(() => {
|
|
2550
|
+
const prev = lastPathRef.current;
|
|
2551
|
+
lastPathRef.current = path;
|
|
2552
|
+
if (prev !== path && editing && draft !== baseRef.current) {
|
|
2553
|
+
writeJson(LS.draft(prev), draft);
|
|
2554
|
+
}
|
|
2555
|
+
setEditing(false);
|
|
2556
|
+
setBusy(false);
|
|
2557
|
+
}, [path]);
|
|
2558
|
+
return { editing, draft, busy, dirty, enter, exit, save, setDraft };
|
|
2559
|
+
}
|
|
2560
|
+
|
|
2561
|
+
function EditControls({ t, editing, dirty, busy, onEnter, onExit, onSave }) {
|
|
2562
|
+
return h(React.Fragment, null,
|
|
2563
|
+
h(Btn, { title: editing ? t('panel.exitEdit') : t('panel.editDocument'), pressed: editing, onClick: editing ? onExit : onEnter, disabled: busy }, Glyph.pencil(), editing ? t('panel.exitEdit') : t('panel.editDocument')),
|
|
2564
|
+
editing && h(Btn, { title: t('panel.save'), onClick: onSave, disabled: busy || !dirty }, t('panel.save')));
|
|
2565
|
+
}
|
|
2566
|
+
|
|
2567
|
+
// ---------- settings overlay ----------
|
|
2568
|
+
/** Floating selection action bar: quote / copy / search-in-doc / translate,
|
|
2569
|
+
* shown as soon as text is selected (icon buttons + instant tooltips). */
|
|
2570
|
+
function SelectionBar({ at, t, onQuote, onCopy, onSearch, onTranslate }) {
|
|
2571
|
+
const { hoverProps, hide: hideTip } = useTip('below'); // tooltip lives at document.body
|
|
2572
|
+
const grab = () => {
|
|
2573
|
+
try { return String(window.getSelection()?.toString() ?? ''); } catch { return ''; }
|
|
2574
|
+
};
|
|
2575
|
+
const btn = (key, glyph, label, run) => h('button', {
|
|
2576
|
+
type: 'button', 'aria-label': label, 'data-selbar-action': key,
|
|
2577
|
+
onMouseDown: (e) => { e.preventDefault(); }, // keep the selection alive
|
|
2578
|
+
onClick: () => { const text = grab(); hideTip(); if (text.trim()) run(text); },
|
|
2579
|
+
...hoverProps(label),
|
|
2580
|
+
}, glyph(13));
|
|
2581
|
+
return h('div', { className: 'dr-selbar', style: { left: at.x, top: at.y }, 'data-doc-reader-selbar': '1' },
|
|
2582
|
+
btn('quote', Glyph.quote, t('panel.quoteToChat'), onQuote),
|
|
2583
|
+
btn('copy', Glyph.copy, t('panel.menuCopy'), (text) => { try { navigator.clipboard.writeText(text).catch(() => { /* denied */ }); } catch { /* denied */ } onCopy(); }),
|
|
2584
|
+
btn('search', Glyph.search, t('panel.menuSearchInDoc'), onSearch),
|
|
2585
|
+
btn('translate', Glyph.translateG, t('panel.translate'), onTranslate));
|
|
2586
|
+
}
|
|
2587
|
+
|
|
2588
|
+
/** Translation result dialog: plain translated text with copy. */
|
|
2589
|
+
function TranslateOverlay({ state, onClose, t, engineLabel, onRetry }) {
|
|
2590
|
+
const [copied, setCopied] = useState(false);
|
|
2591
|
+
useEffect(() => {
|
|
2592
|
+
const onKey = (e) => { if (e.key === 'Escape') onClose(); };
|
|
2593
|
+
window.addEventListener('keydown', onKey);
|
|
2594
|
+
return () => { window.removeEventListener('keydown', onKey); };
|
|
2595
|
+
}, [onClose]);
|
|
2596
|
+
return h('div', { style: { position: 'fixed', inset: 0, background: 'rgba(0,0,0,.32)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 60 }, onClick: (e) => { if (e.target === e.currentTarget) onClose(); } },
|
|
2597
|
+
h('div', { style: { width: 'min(520px, 86vw)', maxHeight: '72vh', boxSizing: 'border-box', background: 'var(--dsw-alias-bg-layer-1)', border: '.5px solid var(--dsw-alias-border-l3)', borderRadius: '10px', padding: '16px', display: 'flex', flexDirection: 'column', gap: '12px', boxShadow: '0 12px 40px rgba(0,0,0,.3)' }, role: 'dialog', 'aria-label': t('panel.translateTitle') },
|
|
2598
|
+
h('div', { style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', fontSize: '13px', fontWeight: 600 } },
|
|
2599
|
+
`${t('panel.translateTitle')}${engineLabel ? ` · ${engineLabel}` : ''}`,
|
|
2600
|
+
h(Btn, { title: t('panel.close'), onClick: onClose }, t('panel.close'))),
|
|
2601
|
+
state.status === 'loading'
|
|
2602
|
+
? h('div', { className: 'dr-load' }, t('panel.translating'))
|
|
2603
|
+
: state.status === 'error'
|
|
2604
|
+
? h(React.Fragment, null,
|
|
2605
|
+
h('div', { className: 'dr-error', 'data-doc-reader-translate-error': '1' }, `${t('panel.translationFailed')}: ${state.error}`),
|
|
2606
|
+
h('div', { style: { display: 'flex', justifyContent: 'flex-end' } },
|
|
2607
|
+
h(Btn, { title: t('panel.retry'), 'data-doc-reader-translate-retry': '1', onClick: () => { onRetry?.(); } }, t('panel.retry'))))
|
|
2608
|
+
: h(React.Fragment, null,
|
|
2609
|
+
state.source ? h('div', { 'data-doc-reader-translate-source': '1', style: { flex: '0 0 auto', maxHeight: '34%', minHeight: 0, overflow: 'auto', whiteSpace: 'pre-wrap', fontSize: '12px', lineHeight: 1.6, color: 'var(--dsw-alias-label-secondary)', fontFamily: 'var(--dsw-font-mono, monospace)', borderBottom: '.5px solid var(--dsw-alias-border-l2)', paddingBottom: '8px' } }, state.source) : null,
|
|
2610
|
+
h('pre', { 'data-doc-reader-translate': '1', style: { margin: 0, flex: 1, minHeight: 0, overflow: 'auto', whiteSpace: 'pre-wrap', fontSize: '13px', lineHeight: 1.7, color: 'var(--dsw-alias-label-primary)', fontFamily: 'inherit' } }, state.text),
|
|
2611
|
+
h('div', { style: { display: 'flex', justifyContent: 'flex-end' } },
|
|
2612
|
+
h(Btn, { title: t('panel.translateCopy'), 'data-doc-reader-translate-copy': '1', onClick: () => {
|
|
2613
|
+
try { navigator.clipboard.writeText(state.text ?? '').catch(() => { /* clipboard denied */ }); } catch { /* clipboard denied */ }
|
|
2614
|
+
setCopied(true);
|
|
2615
|
+
setTimeout(() => setCopied(false), 1600);
|
|
2616
|
+
} }, copied ? t('panel.copied') : t('panel.translateCopy'))))));
|
|
2617
|
+
}
|
|
2618
|
+
|
|
2619
|
+
function SettingsOverlay({ settings, setSettings, onClose, t }) {
|
|
2620
|
+
const [draft, setDraft] = useState(settings);
|
|
2621
|
+
const [dshCatalog, setDshCatalog] = useState(null); // { providers: [{ name, models }] }
|
|
2622
|
+
useEffect(() => {
|
|
2623
|
+
if (draft.translateEngine !== 'dsh' || dshCatalog) return undefined;
|
|
2624
|
+
let alive = true;
|
|
2625
|
+
fetch(`${ROUTE}/translate-models`).then((r) => r.json()).then((c) => { if (alive && c && Array.isArray(c.providers)) setDshCatalog(c); }).catch(() => {});
|
|
2626
|
+
return () => { alive = false; };
|
|
2627
|
+
}, [draft.translateEngine, dshCatalog]);
|
|
2628
|
+
const commit = () => { setSettings(draft); writeJson(LS.settings, draft); onClose(); };
|
|
2629
|
+
const overlayStyle = { position: 'fixed', inset: 0, background: 'rgba(0,0,0,.32)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 60 };
|
|
2630
|
+
const cardStyle = { width: '340px', boxSizing: 'border-box', background: 'var(--dsw-alias-bg-layer-1)', border: '.5px solid var(--dsw-alias-border-l3)', borderRadius: '10px', padding: '18px', display: 'flex', flexDirection: 'column', gap: '14px', boxShadow: '0 12px 40px rgba(0,0,0,.3)' };
|
|
2631
|
+
const rowStyle = { display: 'grid', gridTemplateColumns: '1fr auto', alignItems: 'center', gap: '10px', fontSize: '12.5px', color: 'var(--dsw-alias-label-primary)' };
|
|
2632
|
+
const numStyle = { width: '76px', height: '26px', boxSizing: 'border-box', padding: '0 8px', fontSize: '12px', font: '12px inherit', color: 'var(--dsw-alias-label-primary)', background: 'var(--dsw-alias-bg-layer-2)', border: '.5px solid var(--dsw-alias-border-l2)', borderRadius: '6px', outline: 'none', textAlign: 'right' };
|
|
2633
|
+
const checkStyle = { width: '15px', height: '15px', margin: 0, accentColor: 'var(--dsw-alias-label-primary)' };
|
|
2634
|
+
return h('div', { style: overlayStyle, onClick: (e) => { if (e.target === e.currentTarget) onClose(); } },
|
|
2635
|
+
h('div', { style: cardStyle, role: 'dialog', 'aria-label': t('panel.settings') },
|
|
2636
|
+
h('div', { style: { margin: 0, fontSize: '14px', fontWeight: 600, display: 'flex', alignItems: 'baseline', gap: '8px' } },
|
|
2637
|
+
t('panel.settings'),
|
|
2638
|
+
h('span', { 'data-doc-reader-client-version': '1', style: { fontSize: '11px', fontWeight: 400, color: 'var(--dsw-alias-label-tertiary)' } }, `v${CLIENT_VERSION}`)),
|
|
2639
|
+
h('div', { style: rowStyle }, h('span', null, t('panel.setFontSize')),
|
|
2640
|
+
h('input', { type: 'number', min: 10, max: 28, value: draft.fontSize, style: numStyle,
|
|
2641
|
+
onChange: (e) => setDraft({ ...draft, fontSize: clamp(Number(e.target.value) || 14, 10, 28) }) })),
|
|
2642
|
+
h('div', { style: rowStyle }, h('span', null, t('panel.setLineHeight')),
|
|
2643
|
+
h('input', { type: 'number', min: 1.2, max: 2.4, step: 0.1, value: draft.lineHeight, style: numStyle,
|
|
2644
|
+
onChange: (e) => setDraft({ ...draft, lineHeight: clamp(Number(e.target.value) || 1.7, 1.2, 2.4) }) })),
|
|
2645
|
+
h('div', { style: rowStyle }, h('span', null, t('panel.setRecentLimit')),
|
|
2646
|
+
h('input', { type: 'number', min: 5, max: 200, value: draft.recentLimit, style: numStyle,
|
|
2647
|
+
onChange: (e) => setDraft({ ...draft, recentLimit: clamp(Number(e.target.value) || 20, 5, 200) }) })),
|
|
2648
|
+
h('div', { style: rowStyle }, h('span', null, t('panel.setPdfTextLayer')),
|
|
2649
|
+
h('input', { type: 'checkbox', checked: draft.pdfTextLayer, style: checkStyle,
|
|
2650
|
+
onChange: (e) => setDraft({ ...draft, pdfTextLayer: e.target.checked }) })),
|
|
2651
|
+
h('div', { style: rowStyle }, h('span', null, t('panel.setDocxBreakPages')),
|
|
2652
|
+
h('input', { type: 'checkbox', checked: draft.docxBreakPages, style: checkStyle,
|
|
2653
|
+
onChange: (e) => setDraft({ ...draft, docxBreakPages: e.target.checked }) })),
|
|
2654
|
+
h('div', { style: rowStyle }, h('span', null, t('panel.setLanguage')),
|
|
2655
|
+
h('select', {
|
|
2656
|
+
value: draft.lang ?? 'auto',
|
|
2657
|
+
onChange: (e) => setDraft({ ...draft, lang: e.target.value }),
|
|
2658
|
+
style: { gridColumn: 2, width: '150px', height: '26px', boxSizing: 'border-box', fontSize: '12px', fontFamily: 'inherit', color: 'var(--dsw-alias-label-primary)', background: 'var(--dsw-alias-bg-layer-2)', border: '.5px solid var(--dsw-alias-border-l2)', borderRadius: '6px', outline: 'none', textAlign: 'center' },
|
|
2659
|
+
},
|
|
2660
|
+
h('option', { value: 'auto' }, t('panel.langAuto')),
|
|
2661
|
+
h('option', { value: 'zh' }, '简体中文'),
|
|
2662
|
+
h('option', { value: 'zh-tw' }, '繁體中文'),
|
|
2663
|
+
h('option', { value: 'en' }, 'English'))),
|
|
2664
|
+
h('div', { style: rowStyle }, h('span', null, t('panel.translateTarget')),
|
|
2665
|
+
h('select', {
|
|
2666
|
+
value: draft.translateTarget ?? 'zh-Hans',
|
|
2667
|
+
onChange: (e) => setDraft({ ...draft, translateTarget: e.target.value }),
|
|
2668
|
+
style: { gridColumn: 2, width: '150px', height: '26px', boxSizing: 'border-box', fontSize: '12px', fontFamily: 'inherit', color: 'var(--dsw-alias-label-primary)', background: 'var(--dsw-alias-bg-layer-2)', border: '.5px solid var(--dsw-alias-border-l2)', borderRadius: '6px', outline: 'none', textAlign: 'center' },
|
|
2669
|
+
},
|
|
2670
|
+
h('option', { value: 'zh-Hans' }, '简体中文'),
|
|
2671
|
+
h('option', { value: 'zh-Hant' }, '繁體中文'),
|
|
2672
|
+
h('option', { value: 'en' }, 'English'),
|
|
2673
|
+
h('option', { value: 'ja' }, '日本語'),
|
|
2674
|
+
h('option', { value: 'ko' }, '한국어'),
|
|
2675
|
+
h('option', { value: 'fr' }, 'Français'),
|
|
2676
|
+
h('option', { value: 'de' }, 'Deutsch'),
|
|
2677
|
+
h('option', { value: 'es' }, 'Español'))),
|
|
2678
|
+
h('div', { style: rowStyle }, h('span', null, t('panel.translateEngine')),
|
|
2679
|
+
h('select', {
|
|
2680
|
+
value: draft.translateEngine ?? 'bing',
|
|
2681
|
+
onChange: (e) => setDraft({ ...draft, translateEngine: e.target.value }),
|
|
2682
|
+
style: { gridColumn: 2, width: '150px', height: '26px', boxSizing: 'border-box', fontSize: '12px', fontFamily: 'inherit', color: 'var(--dsw-alias-label-primary)', background: 'var(--dsw-alias-bg-layer-2)', border: '.5px solid var(--dsw-alias-border-l2)', borderRadius: '6px', outline: 'none', textAlign: 'center' },
|
|
2683
|
+
},
|
|
2684
|
+
h('option', { value: 'bing' }, t('panel.translateEngineBing')),
|
|
2685
|
+
h('option', { value: 'google' }, t('panel.translateEngineGoogle')),
|
|
2686
|
+
h('option', { value: 'dsh' }, t('panel.translateEngineDsh')))),
|
|
2687
|
+
draft.translateEngine === 'google' ? h('div', { style: { ...rowStyle, gridTemplateColumns: '1fr' } },
|
|
2688
|
+
h('div', { style: { display: 'flex', flexDirection: 'column', gap: '4px' } },
|
|
2689
|
+
h('span', null, t('panel.translateGoogleEndpointLabel')),
|
|
2690
|
+
h('input', {
|
|
2691
|
+
type: 'text', value: draft.translateGoogleEndpoint ?? '', placeholder: t('panel.translateGoogleEndpointHint'),
|
|
2692
|
+
onChange: (e) => setDraft({ ...draft, translateGoogleEndpoint: e.target.value }),
|
|
2693
|
+
style: { width: '100%', height: '26px', boxSizing: 'border-box', fontSize: '12px', fontFamily: 'var(--dsw-font-mono, monospace)', color: 'var(--dsw-alias-label-primary)', background: 'var(--dsw-alias-bg-layer-2)', border: '.5px solid var(--dsw-alias-border-l2)', borderRadius: '6px', padding: '0 8px', outline: 'none' },
|
|
2694
|
+
}))) : null,
|
|
2695
|
+
draft.translateEngine === 'dsh' ? h('div', { style: rowStyle }, h('span', null, t('panel.translateModelLabel')),
|
|
2696
|
+
h('select', {
|
|
2697
|
+
value: `${draft.translateProvider || ''}::${draft.translateModel || ''}`,
|
|
2698
|
+
onChange: (e) => { const [provider, model] = String(e.target.value).split('::'); setDraft({ ...draft, translateProvider: provider, translateModel: model }); },
|
|
2699
|
+
style: { gridColumn: 2, width: '190px', height: '26px', boxSizing: 'border-box', fontSize: '12px', fontFamily: 'inherit', color: 'var(--dsw-alias-label-primary)', background: 'var(--dsw-alias-bg-layer-2)', border: '.5px solid var(--dsw-alias-border-l2)', borderRadius: '6px', outline: 'none', textAlign: 'center' },
|
|
2700
|
+
},
|
|
2701
|
+
(dshCatalog?.providers ?? []).flatMap((p) => (p.models.length ? p.models : [null]).map((m) => h('option', { key: `${p.name}::${m ?? ''}`, value: `${p.name}::${m ?? ''}` }, m ? `${p.name} · ${m}` : p.name))))) : null,
|
|
2702
|
+
h('div', { style: { display: 'flex', justifyContent: 'flex-end', gap: '8px' } },
|
|
2703
|
+
h(Btn, { title: t('panel.close'), onClick: onClose }, t('panel.cancel')),
|
|
2704
|
+
h(Btn, { title: t('panel.save'), onClick: commit }, t('panel.save')))));
|
|
2705
|
+
}
|
|
2706
|
+
|
|
2707
|
+
/** Controlled rename input: focuses and selects on mount; Enter commits, Escape cancels. */
|
|
2708
|
+
function RenameInput({ value, stem, onChange, onCommit, onCancel }) {
|
|
2709
|
+
const ref = useRef(null);
|
|
2710
|
+
useEffect(() => {
|
|
2711
|
+
const el = ref.current;
|
|
2712
|
+
if (!el) return;
|
|
2713
|
+
el.focus();
|
|
2714
|
+
el.select();
|
|
2715
|
+
}, []);
|
|
2716
|
+
return h('input', {
|
|
2717
|
+
ref,
|
|
2718
|
+
className: 'dr-rename-input', value, spellCheck: false,
|
|
2719
|
+
onChange: (e) => onChange(e.target.value),
|
|
2720
|
+
onBlur: onCommit,
|
|
2721
|
+
onKeyDown: (e) => {
|
|
2722
|
+
if (e.isComposing || e.keyCode === 229) return; // let IME confirm first
|
|
2723
|
+
if (e.key === 'Enter') { e.preventDefault(); e.currentTarget.blur(); }
|
|
2724
|
+
if (e.key === 'Escape') { e.preventDefault(); onCancel(); }
|
|
2725
|
+
},
|
|
2726
|
+
});
|
|
2727
|
+
}
|
|
2728
|
+
|
|
2729
|
+
// ---------- main panel ----------
|
|
2730
|
+
/** Panel-local translation: honor the language setting when it is not
|
|
2731
|
+
* "follow DSH" — registered slots (sidebar label etc.) keep following
|
|
2732
|
+
* the global locale since they are snapshotted at registration. */
|
|
2733
|
+
function makePanelT(base, lang) {
|
|
2734
|
+
if (!lang || lang === 'auto' || !LOCALES[lang]) return base;
|
|
2735
|
+
const dict = LOCALES[lang];
|
|
2736
|
+
return (key) => dict[key] ?? base(key);
|
|
2737
|
+
}
|
|
2738
|
+
|
|
2739
|
+
function makeReaderPanel(t) {
|
|
2740
|
+
return function ReaderPanel() {
|
|
2741
|
+
const [path, setPath] = useState(null);
|
|
2742
|
+
const [draft, setDraft] = useState('');
|
|
2743
|
+
const [showSide, setShowSide] = useState(true);
|
|
2744
|
+
const [showBrowse, setShowBrowse] = useState(false);
|
|
2745
|
+
const [settings, setSettings] = useState(getSettings);
|
|
2746
|
+
const localT = useMemo(() => makePanelT(t, settings.lang), [settings.lang]);
|
|
2747
|
+
const [showSettings, setShowSettings] = useState(false);
|
|
2748
|
+
const [sidebarModel, setSidebarModel] = useState(null);
|
|
2749
|
+
const [contentSideVisible, setContentSideVisible] = useState(true);
|
|
2750
|
+
const [sidebarVisible, setSidebarVisible] = useState(true);
|
|
2751
|
+
const [status, setStatus] = useState('');
|
|
2752
|
+
const [recentVersion, setRecentVersion] = useState(0);
|
|
2753
|
+
const [renaming, setRenaming] = useState(null); // { pending }
|
|
2754
|
+
const flashTimerRef = useRef(null);
|
|
2755
|
+
const flash = useCallback((message) => {
|
|
2756
|
+
setStatus(message);
|
|
2757
|
+
clearTimeout(flashTimerRef.current);
|
|
2758
|
+
if (message && message !== LOCALES.zh['panel.loading']) {
|
|
2759
|
+
flashTimerRef.current = setTimeout(() => setStatus(''), 3200);
|
|
2760
|
+
}
|
|
2761
|
+
}, []);
|
|
2762
|
+
useEffect(() => () => clearTimeout(flashTimerRef.current), []);
|
|
2763
|
+
|
|
2764
|
+
const openSeqRef = useRef(0);
|
|
2765
|
+
const pathRef = useRef(null);
|
|
2766
|
+
pathRef.current = path;
|
|
2767
|
+
const lastOpenPathRef = useRef(null);
|
|
2768
|
+
const open = useCallback(async (p) => {
|
|
2769
|
+
if (!kindOf(p)) { flash(`${localT('panel.error')}: ${localT('panel.unsupported')}`); return; }
|
|
2770
|
+
// verify the file exists before touching the recent list so dead
|
|
2771
|
+
// entries (e.g. pre-rename leftovers) cannot resurrect themselves
|
|
2772
|
+
const seq = ++openSeqRef.current; // a newer open() must win over a slower older probe
|
|
2773
|
+
try {
|
|
2774
|
+
const probe = await fetch(FILE_URL(p), { method: 'HEAD' });
|
|
2775
|
+
if (seq !== openSeqRef.current) return;
|
|
2776
|
+
if (!probe.ok) {
|
|
2777
|
+
const detail = await probe.json().catch(() => ({}));
|
|
2778
|
+
flash(`${localT('panel.error')}: ${detail.error || localT('panel.notFound')}`);
|
|
2779
|
+
return;
|
|
2780
|
+
}
|
|
2781
|
+
} catch (e) {
|
|
2782
|
+
if (seq !== openSeqRef.current) return;
|
|
2783
|
+
flash(`${localT('panel.error')}: ${e.message}`);
|
|
2784
|
+
return;
|
|
2785
|
+
}
|
|
2786
|
+
pushRecent(p, getSettings().recentLimit);
|
|
2787
|
+
setRecentVersion((v) => v + 1);
|
|
2788
|
+
lastOpenPathRef.current = p;
|
|
2789
|
+
setPath(p);
|
|
2790
|
+
setDraft(p);
|
|
2791
|
+
setSidebarModel(null);
|
|
2792
|
+
}, [flash]);
|
|
2793
|
+
|
|
2794
|
+
// consume handoff requests from other panels ("open in reader")
|
|
2795
|
+
const openRef = useRef(open);
|
|
2796
|
+
openRef.current = open;
|
|
2797
|
+
useEffect(() => {
|
|
2798
|
+
notifyReaderOpen = () => {
|
|
2799
|
+
const p = pendingReaderOpen;
|
|
2800
|
+
pendingReaderOpen = null;
|
|
2801
|
+
if (p) void openRef.current(p);
|
|
2802
|
+
};
|
|
2803
|
+
notifyReaderOpen(); // pick up a request that arrived before mount
|
|
2804
|
+
return () => { notifyReaderOpen = () => {}; };
|
|
2805
|
+
}, []);
|
|
2806
|
+
|
|
2807
|
+
// global shortcut (Cmd/Ctrl+Shift+O): focus + select the path input
|
|
2808
|
+
useEffect(() => {
|
|
2809
|
+
const focusPath = () => {
|
|
2810
|
+
focusPathRequested = false;
|
|
2811
|
+
const input = document.querySelector('.dr-panel .dr-path');
|
|
2812
|
+
if (input) { try { input.focus(); input.select?.(); } catch { /* detached */ } }
|
|
2813
|
+
};
|
|
2814
|
+
window.addEventListener('doc-reader:focus-path', focusPath);
|
|
2815
|
+
if (focusPathRequested) setTimeout(focusPath, 60); // mounted after the shortcut fired
|
|
2816
|
+
return () => { window.removeEventListener('doc-reader:focus-path', focusPath); };
|
|
2817
|
+
}, []);
|
|
2818
|
+
|
|
2819
|
+
// ---------- live integration with the host ----------
|
|
2820
|
+
// report the opened document (agent chat context + /doc recent list)
|
|
2821
|
+
useEffect(() => {
|
|
2822
|
+
if (typeof path !== 'string') return undefined;
|
|
2823
|
+
void fetch(ACTIVE_URL, {
|
|
2824
|
+
method: 'POST', headers: { 'content-type': 'application/json' },
|
|
2825
|
+
body: JSON.stringify({ path }),
|
|
2826
|
+
}).catch(() => { /* host offline: reader keeps working */ });
|
|
2827
|
+
return undefined;
|
|
2828
|
+
}, [path]);
|
|
2829
|
+
|
|
2830
|
+
// SSE: external disk changes auto-reload (or show a conflict bar while
|
|
2831
|
+
// editing); {type:'open'} broadcasts come from the /doc slash command
|
|
2832
|
+
const [reloadKey, setReloadKey] = useState(0);
|
|
2833
|
+
const [externalChange, setExternalChange] = useState(null); // { path }
|
|
2834
|
+
const editingRef = useRef(false);
|
|
2835
|
+
const onEditingChange = useCallback((flag) => { editingRef.current = !!flag; }, []);
|
|
2836
|
+
useEffect(() => {
|
|
2837
|
+
if (typeof EventSource !== 'function') return undefined; // tests/older hosts
|
|
2838
|
+
const es = new EventSource(EVENTS_URL(typeof path === 'string' ? path : null));
|
|
2839
|
+
es.onmessage = (event) => {
|
|
2840
|
+
let ev;
|
|
2841
|
+
try { ev = JSON.parse(event.data); } catch { return; }
|
|
2842
|
+
if (!ev || typeof ev.type !== 'string') return;
|
|
2843
|
+
if (ev.type === 'open' && typeof ev.path === 'string' && ev.path !== pathRef.current) {
|
|
2844
|
+
void openRef.current(ev.path);
|
|
2845
|
+
} else if (ev.type === 'change' && ev.path === pathRef.current) {
|
|
2846
|
+
if (editingRef.current) setExternalChange({ path: ev.path, at: Date.now() });
|
|
2847
|
+
else {
|
|
2848
|
+
setExternalChange(null);
|
|
2849
|
+
setReloadKey((k) => k + 1);
|
|
2850
|
+
flash(localT('panel.reloadedFromDisk'));
|
|
2851
|
+
}
|
|
2852
|
+
}
|
|
2853
|
+
};
|
|
2854
|
+
return () => { es.close(); };
|
|
2855
|
+
}, [path, localT, flash]);
|
|
2856
|
+
const reloadFromDisk = () => {
|
|
2857
|
+
if (typeof path === 'string') removeDraft(path); // reload means: discard my draft
|
|
2858
|
+
setExternalChange(null);
|
|
2859
|
+
setReloadKey((k) => k + 1);
|
|
2860
|
+
};
|
|
2861
|
+
|
|
2862
|
+
// ---------- selection → "quote to chat" floating button ----------
|
|
2863
|
+
// Mirrors the transcript quote action: pick text in the rendered
|
|
2864
|
+
// document, get one button, click to drop a blockquote into the
|
|
2865
|
+
// conversation composer (clipboard fallback when no composer).
|
|
2866
|
+
const contentRef = useRef(null);
|
|
2867
|
+
const [quoteAt, setQuoteAt] = useState(null); // { x, y }
|
|
2868
|
+
useEffect(() => {
|
|
2869
|
+
if (typeof document === 'undefined' || typeof document.addEventListener !== 'function') return undefined;
|
|
2870
|
+
let timer = null;
|
|
2871
|
+
const update = () => {
|
|
2872
|
+
if (timer) clearTimeout(timer);
|
|
2873
|
+
timer = setTimeout(() => {
|
|
2874
|
+
timer = null;
|
|
2875
|
+
const content = contentRef.current;
|
|
2876
|
+
if (!content || editingRef.current) { setQuoteAt(null); return; }
|
|
2877
|
+
let sel = null;
|
|
2878
|
+
try { sel = window.getSelection(); } catch { sel = null; }
|
|
2879
|
+
const text = sel ? String(sel.toString() ?? '') : '';
|
|
2880
|
+
if (!sel || sel.isCollapsed || !text.trim() || text.trim().length > 4000) { setQuoteAt(null); return; }
|
|
2881
|
+
const node = sel.anchorNode;
|
|
2882
|
+
const el = node ? (node.nodeType === 1 ? node : node.parentNode) : null;
|
|
2883
|
+
if (!el || !content.contains(el)) { setQuoteAt(null); return; }
|
|
2884
|
+
// Range.getBoundingClientRect is missing on some hosts (jsdom);
|
|
2885
|
+
// fall back to the anchor element's box, then to 0,0
|
|
2886
|
+
let rect = null;
|
|
2887
|
+
try {
|
|
2888
|
+
const range = sel.rangeCount > 0 ? sel.getRangeAt(0) : null;
|
|
2889
|
+
if (range && typeof range.getBoundingClientRect === 'function') rect = range.getBoundingClientRect();
|
|
2890
|
+
else if (el && typeof el.getBoundingClientRect === 'function') rect = el.getBoundingClientRect();
|
|
2891
|
+
} catch { rect = null; }
|
|
2892
|
+
if (!rect) { setQuoteAt(null); return; }
|
|
2893
|
+
setQuoteAt({ x: Math.round(rect.left + rect.width / 2), y: Math.round(rect.top) });
|
|
2894
|
+
}, 120);
|
|
2895
|
+
};
|
|
2896
|
+
document.addEventListener('selectionchange', update);
|
|
2897
|
+
return () => { document.removeEventListener('selectionchange', update); if (timer) clearTimeout(timer); };
|
|
2898
|
+
}, []);
|
|
2899
|
+
const quoteNow = async () => {
|
|
2900
|
+
let sel = null;
|
|
2901
|
+
try { sel = window.getSelection(); } catch { sel = null; }
|
|
2902
|
+
const text = sel ? String(sel.toString() ?? '') : '';
|
|
2903
|
+
setQuoteAt(null);
|
|
2904
|
+
if (!text.trim() || typeof path !== 'string') return;
|
|
2905
|
+
const outcome = await quoteSelectionToChat(displayName, text);
|
|
2906
|
+
try { sel?.removeAllRanges?.(); } catch { /* fine */ }
|
|
2907
|
+
flash(outcome === 'chat' ? localT('panel.quotedToChat') : outcome === 'copied' ? localT('panel.quoteCopied') : localT('panel.quoteFailed'));
|
|
2908
|
+
};
|
|
2909
|
+
|
|
2910
|
+
// ---------- content context menu ----------
|
|
2911
|
+
const [ctxMenu, setCtxMenu] = useState(null); // { x, y, selection }
|
|
2912
|
+
const openContextMenu = (e) => {
|
|
2913
|
+
if (editingRef.current) return; // keep the native menu while editing
|
|
2914
|
+
let sel = null;
|
|
2915
|
+
try { sel = window.getSelection(); } catch { sel = null; }
|
|
2916
|
+
const selection = (sel ? String(sel.toString() ?? '') : '').trim().slice(0, 2000);
|
|
2917
|
+
e.preventDefault();
|
|
2918
|
+
const x = Math.min(e.clientX, (typeof window !== 'undefined' && window.innerWidth ? window.innerWidth - 190 : e.clientX));
|
|
2919
|
+
setCtxMenu({ x, y: e.clientY, selection });
|
|
2920
|
+
};
|
|
2921
|
+
useEffect(() => {
|
|
2922
|
+
if (!ctxMenu) return undefined;
|
|
2923
|
+
const onDown = (e) => { if (!e.target?.closest?.('.dr-ctxmenu')) setCtxMenu(null); };
|
|
2924
|
+
const close = () => setCtxMenu(null);
|
|
2925
|
+
window.addEventListener('mousedown', onDown);
|
|
2926
|
+
window.addEventListener('resize', close);
|
|
2927
|
+
return () => { window.removeEventListener('mousedown', onDown); window.removeEventListener('resize', close); };
|
|
2928
|
+
}, [ctxMenu]);
|
|
2929
|
+
// selection translation via the optional Host translator bridge
|
|
2930
|
+
const [translateState, setTranslateState] = useState(null); // { status, text?, error? }
|
|
2931
|
+
const lastTranslateTextRef = useRef('');
|
|
2932
|
+
const runTranslate = (text) => {
|
|
2933
|
+
lastTranslateTextRef.current = text;
|
|
2934
|
+
setTranslateState({ status: 'loading' });
|
|
2935
|
+
const s = getSettings();
|
|
2936
|
+
fetch(TRANSLATE_URL, {
|
|
2937
|
+
method: 'POST', headers: { 'content-type': 'application/json' },
|
|
2938
|
+
body: JSON.stringify({
|
|
2939
|
+
text, targetLanguage: s.translateTarget || 'zh-Hans',
|
|
2940
|
+
...(s.translateEngine === 'dsh' ? { engine: 'dsh', provider: s.translateProvider || undefined, model: s.translateModel || undefined } : {}),
|
|
2941
|
+
...(s.translateEngine === 'google' ? { engine: 'google', endpoint: s.translateGoogleEndpoint || undefined } : {}),
|
|
2942
|
+
}),
|
|
2943
|
+
})
|
|
2944
|
+
.then(async (res) => { const d = await res.json().catch(() => ({})); if (!res.ok) throw new Error(d.error || `${res.status}`); return d; })
|
|
2945
|
+
.then((d) => setTranslateState({ status: 'ready', text: String(d.text ?? ''), source: text, engineLabel: d.engine === 'dsh' ? (getSettings().translateModel || 'DSH') : d.engine === 'google' ? 'Google' : undefined }))
|
|
2946
|
+
.catch((e) => setTranslateState({ status: 'error', error: e.message }));
|
|
2947
|
+
};
|
|
2948
|
+
const searchInDoc = (term) => {
|
|
2949
|
+
const input = contentRef.current?.querySelector('.dr-viewbar input[type="search"], .dr-viewbar input[type="text"]');
|
|
2950
|
+
if (!input) { flash(localT('panel.searchUnavailable')); return; }
|
|
2951
|
+
try {
|
|
2952
|
+
const setter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set;
|
|
2953
|
+
setter.call(input, term);
|
|
2954
|
+
input.dispatchEvent(new window.Event('input', { bubbles: true }));
|
|
2955
|
+
input.dispatchEvent(new window.KeyboardEvent('keydown', { key: 'Enter', bubbles: true }));
|
|
2956
|
+
input.focus?.();
|
|
2957
|
+
} catch { flash(localT('panel.searchUnavailable')); }
|
|
2958
|
+
};
|
|
2959
|
+
|
|
2960
|
+
const renameFile = useCallback(async (from, name) => {
|
|
2961
|
+
if (!name || !name.trim()) return;
|
|
2962
|
+
setRenaming({ pending: true });
|
|
2963
|
+
try {
|
|
2964
|
+
const res = await fetch(RENAME_URL, {
|
|
2965
|
+
method: 'POST',
|
|
2966
|
+
headers: { 'content-type': 'application/json' },
|
|
2967
|
+
body: JSON.stringify({ path: from, name: name.trim() }),
|
|
2968
|
+
});
|
|
2969
|
+
const data = await res.json().catch(() => ({}));
|
|
2970
|
+
if (!res.ok) throw new Error(data.error || `${res.status}`);
|
|
2971
|
+
// migrate recent + position to the new path
|
|
2972
|
+
const recent = readJson(LS.recent, []).map((e) => (e.path === from ? { ...e, path: data.path, kind: kindOf(data.path) } : e));
|
|
2973
|
+
writeJson(LS.recent, recent);
|
|
2974
|
+
try {
|
|
2975
|
+
const saved = localStorage.getItem(LS.pos(from));
|
|
2976
|
+
if (saved) { localStorage.setItem(LS.pos(data.path), saved); localStorage.removeItem(LS.pos(from)); }
|
|
2977
|
+
const draft = localStorage.getItem(LS.draft(from));
|
|
2978
|
+
if (draft) { localStorage.setItem(LS.draft(data.path), draft); localStorage.removeItem(LS.draft(from)); }
|
|
2979
|
+
} catch { /* storage disabled — rename itself already succeeded */ }
|
|
2980
|
+
setRecentVersion((v) => v + 1);
|
|
2981
|
+
flash(`${localT('panel.renameDone')}: ${data.path.slice(data.path.lastIndexOf('/') + 1)}`);
|
|
2982
|
+
if (pathRef.current === from && lastOpenPathRef.current === from) open(data.path); // never override a newer explicit open
|
|
2983
|
+
} catch (e) {
|
|
2984
|
+
flash(`${localT('panel.renameFailed')}: ${e.message}`);
|
|
2985
|
+
} finally {
|
|
2986
|
+
setRenaming(null);
|
|
2987
|
+
}
|
|
2988
|
+
}, [flash, open]);
|
|
2989
|
+
|
|
2990
|
+
const kind = typeof path === 'string' ? kindOf(path) : null;
|
|
2991
|
+
const displayName = typeof path === 'string' ? path.slice(path.lastIndexOf('/') + 1) : '';
|
|
2992
|
+
const stem = displayName.includes('.') ? displayName.slice(0, displayName.lastIndexOf('.')) : displayName;
|
|
2993
|
+
|
|
2994
|
+
// title rename UI
|
|
2995
|
+
const [renameDraft, setRenameDraft] = useState('');
|
|
2996
|
+
const [renameActive, setRenameActive] = useState(false);
|
|
2997
|
+
const renameCancelledRef = useRef(false);
|
|
2998
|
+
// toolbar hover explanations are dark side-anchored bubbles (the
|
|
2999
|
+
// platform's own sidebar-toggle pattern), vertically centered on
|
|
3000
|
+
// the hovered button. The right-side icons share ONE fixed hint
|
|
3001
|
+
// slot: every bubble's right border sits EXACTLY on the path
|
|
3002
|
+
// input's right border (product requirement — confirmed), so the
|
|
3003
|
+
// position never depends on which icon is hovered. The anchor
|
|
3004
|
+
// reads the input ref, backed by a live DOM re-query so a
|
|
3005
|
+
// mid-remount hover can never degrade to button-hugging. The
|
|
3006
|
+
// left-most rename button anchors to its RIGHT, 8px past it.
|
|
3007
|
+
const pathInputRef = useRef(null);
|
|
3008
|
+
const { hoverProps: sideHover } = useTip('left');
|
|
3009
|
+
const { hoverProps: renameHover } = useTip('right');
|
|
3010
|
+
const iconHint = (text) => sideHover(text, (el) => pathInputRef.current ?? el?.closest?.('.dr-toolbar')?.querySelector('.dr-path'));
|
|
3011
|
+
|
|
3012
|
+
const startRename = () => {
|
|
3013
|
+
if (typeof path !== 'string' || renaming?.pending) return;
|
|
3014
|
+
renameCancelledRef.current = false; // stale cancel flag would swallow the next commit
|
|
3015
|
+
setRenameDraft(stem);
|
|
3016
|
+
setRenameActive(true);
|
|
3017
|
+
flash(localT('panel.renamePrompt'));
|
|
3018
|
+
};
|
|
3019
|
+
|
|
3020
|
+
const viewProps = {
|
|
3021
|
+
path, settings, t: localT, onStatus: flash, onSidebar: setSidebarModel, onOpen: open,
|
|
3022
|
+
sidebar: sidebarModel
|
|
3023
|
+
? (contentSideVisible
|
|
3024
|
+
? h(ContentSidebar, { model: sidebarModel, t, onCollapse: () => setContentSideVisible(false) })
|
|
3025
|
+
: h('button', { className: 'dr-toc-expand', title: localT('panel.outline'), 'aria-label': localT('panel.outline'), onClick: () => setContentSideVisible(true) }, '›'))
|
|
3026
|
+
: null,
|
|
3027
|
+
};
|
|
3028
|
+
return h('div', { className: 'dr-panel', 'data-doc-reader-version': CLIENT_VERSION },
|
|
3029
|
+
h('style', null, CSS),
|
|
3030
|
+
h('div', { className: 'dr-toolbar' },
|
|
3031
|
+
h('span', { className: 'dr-logo' }, Glyph.logo(16), localT('panel.title')),
|
|
3032
|
+
typeof path === 'string' && h('span', { className: 'dr-rename' },
|
|
3033
|
+
renameActive
|
|
3034
|
+
? h(RenameInput, {
|
|
3035
|
+
value: renameDraft, stem,
|
|
3036
|
+
onChange: (v) => setRenameDraft(v),
|
|
3037
|
+
onCommit: () => {
|
|
3038
|
+
setRenameActive(false);
|
|
3039
|
+
if (renameCancelledRef.current) { renameCancelledRef.current = false; return; }
|
|
3040
|
+
if (renameDraft.trim() && renameDraft.trim() !== stem) void renameFile(path, renameDraft);
|
|
3041
|
+
},
|
|
3042
|
+
onCancel: () => { renameCancelledRef.current = true; setRenameActive(false); },
|
|
3043
|
+
})
|
|
3044
|
+
: h('button', {
|
|
3045
|
+
className: 'dr-rename-btn', 'aria-label': localT('panel.renameFile'),
|
|
3046
|
+
onClick: startRename,
|
|
3047
|
+
onDoubleClick: startRename,
|
|
3048
|
+
...renameHover(localT('panel.renameFile')),
|
|
3049
|
+
}, h('span', { className: 'dr-rename-name' }, displayName), Glyph.pencil())),
|
|
3050
|
+
h('input', {
|
|
3051
|
+
className: 'dr-path', ref: pathInputRef, value: draft, placeholder: localT('panel.placeholder'), spellCheck: false,
|
|
3052
|
+
onChange: (e) => setDraft(e.target.value),
|
|
3053
|
+
onKeyDown: (e) => { if (e.key === 'Enter' && !e.isComposing && e.keyCode !== 229) open(draft.trim()); },
|
|
3054
|
+
}),
|
|
3055
|
+
h(Btn, {
|
|
3056
|
+
title: localT('panel.copyPath'), icon: true, instantTip: true,
|
|
3057
|
+
'data-doc-reader-copy-path': '1', disabled: typeof path !== 'string',
|
|
3058
|
+
onClick: () => {
|
|
3059
|
+
if (typeof path !== 'string') return;
|
|
3060
|
+
// copy the OPEN file's path, not the (possibly edited) input draft
|
|
3061
|
+
try { navigator.clipboard.writeText(path).catch(() => { /* clipboard denied */ }); flash(localT('panel.copied')); } catch { /* clipboard denied */ }
|
|
3062
|
+
},
|
|
3063
|
+
...iconHint(localT('panel.copyPath')),
|
|
3064
|
+
}, Glyph.copy(14)),
|
|
3065
|
+
h(Btn, { title: localT('panel.toggleSide'), icon: true, instantTip: true, onClick: () => setShowSide((v) => !v), pressed: showSide, ...iconHint(localT('panel.toggleSide')) }, Glyph.sidebar(14)),
|
|
3066
|
+
h(Btn, { title: localT('panel.settings'), icon: true, instantTip: true, onClick: () => setShowSettings(true), ...iconHint(localT('panel.settings')) }, Glyph.sliders(14))),
|
|
3067
|
+
externalChange && h('div', { className: 'dr-external', role: 'alert' },
|
|
3068
|
+
h('span', { className: 'dr-external-msg' }, localT('panel.externalChanged')),
|
|
3069
|
+
h('button', { className: 'dr-btn', onClick: reloadFromDisk }, localT('panel.reloadNow')),
|
|
3070
|
+
h('button', { className: 'dr-btn', onClick: () => setExternalChange(null) }, localT('panel.keepEditing'))),
|
|
3071
|
+
h('div', { className: 'dr-body' },
|
|
3072
|
+
h('div', { className: showSide ? 'dr-side' : 'dr-side-hidden' },
|
|
3073
|
+
h('div', { className: 'dr-side-head' },
|
|
3074
|
+
h('span', { className: 'dr-side-title' }, localT('panel.recent')),
|
|
3075
|
+
h(Btn, { title: localT('panel.browse'), onClick: () => setShowBrowse(true) }, Glyph.folder(13), ' ', localT('panel.browse'))),
|
|
3076
|
+
h(RecentList, { onOpen: open, onFlash: flash, settings, version: recentVersion, t })),
|
|
3077
|
+
h('div', { className: 'dr-content', ref: contentRef, onContextMenu: openContextMenu },
|
|
3078
|
+
path === null
|
|
3079
|
+
? h('div', { className: 'dr-empty' }, Glyph.logo(44), h('span', null, localT('panel.dropHint')))
|
|
3080
|
+
: h(View, { ...viewProps, onEditingChange, key: `${path}#${reloadKey}` }))),
|
|
3081
|
+
quoteAt && typeof path === 'string' && h(SelectionBar, {
|
|
3082
|
+
at: quoteAt, t: localT,
|
|
3083
|
+
onQuote: () => { void quoteNow(); },
|
|
3084
|
+
onCopy: () => { flash(localT('panel.copied')); },
|
|
3085
|
+
onSearch: (text) => { searchInDoc(text); },
|
|
3086
|
+
onTranslate: (text) => { runTranslate(text); },
|
|
3087
|
+
}),
|
|
3088
|
+
ctxMenu && h('div', { className: 'dr-ctxmenu', style: { left: ctxMenu.x, top: ctxMenu.y }, 'data-doc-reader-menu': '1' },
|
|
3089
|
+
ctxMenu.selection ? h('button', {
|
|
3090
|
+
onClick: () => { const s = ctxMenu.selection; setCtxMenu(null); void quoteSelectionToChat(displayName, s).then((r) => { flash(r === 'chat' ? localT('panel.quotedToChat') : r === 'copied' ? localT('panel.quoteCopied') : localT('panel.quoteFailed')); }); },
|
|
3091
|
+
}, localT('panel.quoteToChat')) : null,
|
|
3092
|
+
ctxMenu.selection ? h('button', {
|
|
3093
|
+
onClick: () => { const s = ctxMenu.selection; setCtxMenu(null); try { navigator.clipboard.writeText(s).catch(() => { /* clipboard denied */ }); flash(localT('panel.copied')); } catch { /* clipboard denied */ } },
|
|
3094
|
+
}, localT('panel.menuCopy')) : null,
|
|
3095
|
+
ctxMenu.selection ? h('button', {
|
|
3096
|
+
onClick: () => { const s = ctxMenu.selection; setCtxMenu(null); searchInDoc(s); },
|
|
3097
|
+
}, localT('panel.menuSearchInDoc')) : null,
|
|
3098
|
+
ctxMenu.selection ? h('button', {
|
|
3099
|
+
onClick: () => { const s = ctxMenu.selection; setCtxMenu(null); runTranslate(s); },
|
|
3100
|
+
}, localT('panel.translate')) : null,
|
|
3101
|
+
typeof path === 'string' ? h('button', {
|
|
3102
|
+
onClick: () => { setCtxMenu(null); void fetch(REVEAL_URL(path)).catch(() => {}); },
|
|
3103
|
+
}, localT('panel.revealInFinder')) : null),
|
|
3104
|
+
typeof path === 'string' && h('div', { className: 'dr-status', 'aria-live': 'polite' }, status),
|
|
3105
|
+
translateState && h(TranslateOverlay, { state: translateState, onClose: () => setTranslateState(null), t: localT, engineLabel: translateState.engineLabel, onRetry: () => { if (lastTranslateTextRef.current) runTranslate(lastTranslateTextRef.current); } }),
|
|
3106
|
+
showSettings && h(SettingsOverlay, { settings, setSettings, onClose: () => setShowSettings(false), t: localT }),
|
|
3107
|
+
showBrowse && h(BrowseOverlay, {
|
|
3108
|
+
t, version: recentVersion,
|
|
3109
|
+
onOpen: (p) => { setShowBrowse(false); void open(p); },
|
|
3110
|
+
onClose: () => setShowBrowse(false),
|
|
3111
|
+
}));
|
|
3112
|
+
};
|
|
3113
|
+
}
|
|
3114
|
+
|
|
3115
|
+
/** Office deck/spreadsheet: Host converts to PDF via the official
|
|
3116
|
+
* libreoffice-kit, then rendering reuses the battle-tested PdfView. */
|
|
3117
|
+
function OfficeView(props) {
|
|
3118
|
+
const { path, t } = props;
|
|
3119
|
+
const [state, setState] = useState({ status: 'loading' });
|
|
3120
|
+
useEffect(() => {
|
|
3121
|
+
let alive = true;
|
|
3122
|
+
const controller = new AbortController();
|
|
3123
|
+
setState({ status: 'loading' });
|
|
3124
|
+
fetch(`${ROUTE}/convert?path=${encodeURIComponent(path)}`, { signal: controller.signal })
|
|
3125
|
+
.then(async (res) => {
|
|
3126
|
+
const data = await res.json().catch(() => ({}));
|
|
3127
|
+
if (!res.ok) throw new Error(data.error || `${res.status}`);
|
|
3128
|
+
return data;
|
|
3129
|
+
})
|
|
3130
|
+
.then((data) => { if (alive && typeof data.pdfPath === 'string') setState({ status: 'ready', pdfPath: data.pdfPath }); })
|
|
3131
|
+
.catch((e) => { if (alive && e?.name !== 'AbortError') setState({ status: 'error', message: e.message }); });
|
|
3132
|
+
return () => { alive = false; controller.abort(); };
|
|
3133
|
+
}, [path]);
|
|
3134
|
+
if (state.status === 'error') return h('div', { className: 'dr-error' }, `${t('panel.error')}: ${state.message}`);
|
|
3135
|
+
if (state.status !== 'ready') return h('div', { className: 'dr-load' }, t('panel.converting'));
|
|
3136
|
+
return h(PdfView, { ...props, path: state.pdfPath });
|
|
3137
|
+
}
|
|
3138
|
+
|
|
3139
|
+
function View(props) {
|
|
3140
|
+
const kind = kindOf(props.path);
|
|
3141
|
+
if (kind === 'office') return h(OfficeView, props);
|
|
3142
|
+
if (kind === 'markdown') return h(MarkdownView, props);
|
|
3143
|
+
if (kind === 'text') return h(TextView, props);
|
|
3144
|
+
if (kind === 'image') return h(ImageView, props);
|
|
3145
|
+
if (kind === 'pdf') return h(PdfView, props);
|
|
3146
|
+
if (kind === 'docx') return h(DocxView, props);
|
|
3147
|
+
if (kind === 'epub') return h(EpubView, props);
|
|
3148
|
+
if (kind === 'html') return h(HtmlView, props);
|
|
3149
|
+
return h('div', { className: 'dr-error' }, props.t('panel.unsupported'));
|
|
3150
|
+
}
|
|
3151
|
+
|
|
3152
|
+
function PanelIcon({ size }) {
|
|
3153
|
+
return Glyph.logo(size ?? 18);
|
|
3154
|
+
}
|
|
3155
|
+
|
|
3156
|
+
// ---------- embedded dictionaries ----------
|
|
3157
|
+
const STRINGS = {
|
|
3158
|
+
en: {
|
|
3159
|
+
meta: { title: 'Doc reader', description: 'Read local PDF, DOCX, Markdown, text, and image files in a dedicated panel.' },
|
|
3160
|
+
panel: {
|
|
3161
|
+
title: 'Reader', toggleSide: 'Toggle recent-files sidebar', placeholder: 'Type an absolute local file path and press Enter…',
|
|
3162
|
+
open: 'Open', browse: 'Open file', recent: 'Recent files', recentEmpty: 'No files opened yet',
|
|
3163
|
+
clearRecent: 'Clear recent files', removeRecent: 'Remove from recent', revealInFinder: 'Reveal in file manager',
|
|
3164
|
+
error: 'Cannot open', unsupported: 'Unsupported file type', notFound: 'File not found',
|
|
3165
|
+
loading: 'Loading…', loadingPdf: 'Loading PDF…', emptyDir: 'No readable files in this folder',
|
|
3166
|
+
outline: 'Outline', pages: 'Pages', page: 'Page',
|
|
3167
|
+
search: 'Search', searchPrev: 'Previous match', searchNext: 'Next match', searching: 'Searching…', noMatches: 'No matches',
|
|
3168
|
+
searchTruncated: 'Too many matches — highlighting the first 5000 only',
|
|
3169
|
+
retryHint: 'close and reopen the file to retry',
|
|
3170
|
+
searchPrevShort: 'Prev', fontSmaller: 'Smaller font', fontBigger: 'Larger font', fontReset: 'Reset font size',
|
|
3171
|
+
prevPage: 'Previous page', nextPage: 'Next page',
|
|
3172
|
+
zoomIn: 'Zoom in', zoomOut: 'Zoom out', zoomReset: 'Reset zoom (100%)',
|
|
3173
|
+
rotateLeft: 'Rotate left 90°', rotateRight: 'Rotate right 90°', fitWindow: 'Fit window', fitWidth: 'Fit width',
|
|
3174
|
+
pdfRenderFailed: 'Page failed to render', pdfSearchDisabled: 'PDF text search is off (Settings)',
|
|
3175
|
+
docxTooLarge: 'DOCX too large to render (>100MB)', docxRendered: 'DOCX rendered', dropHint: 'Paste a supported file path above to open it',
|
|
3176
|
+
renameFile: 'Rename file', renamePrompt: 'Type a new name, then press Enter', renameDone: 'Renamed', renameFailed: 'Rename failed',
|
|
3177
|
+
editDocument: 'Edit', exitEdit: 'Exit edit', saved: 'Saved', saveFailed: 'Save failed', setLanguage: 'Language', langAuto: 'Follow DSH', noChanges: 'No changes to save', unsavedConfirm: 'Discard unsaved changes?', draftRestored: 'Unsaved draft restored', saveConflictRebased: 'File changed on disk — rebased. Save again to overwrite, or exit to discard.', resizeSidebar: 'Drag to resize sidebar', openInReader: 'Open in reader', commandSearch: 'Search', commandRecent: 'Recent docs', listTruncated: 'List truncated at 2000 entries', mdPlainMode: 'Large document — plain text mode', editModeHint: 'Editing — Ctrl/Cmd+S to save', collapseSidebar: 'Collapse sidebar', settings: 'Reader settings', setFontSize: 'Base font size (10–28)', setLineHeight: 'Line height (1.2–2.4)',
|
|
3178
|
+
setRecentLimit: 'Recent files limit (5–200)', setPdfTextLayer: 'PDF text-layer search',
|
|
3179
|
+
setDocxBreakPages: 'DOCX page breaks', save: 'Save', cancel: 'Cancel', close: 'Close',
|
|
3180
|
+
reloadedFromDisk: 'Reloaded — file changed on disk', externalChanged: 'This file changed on disk while you are editing it', reloadNow: 'Reload from disk', keepEditing: 'Keep editing',
|
|
3181
|
+
rowConfig: 'Reader settings', cfgCtxInject: 'Inject active document outline into chat context', cfgCtxInjectHint: 'Lets the assistant see which document you are reading', cfgAutoReload: 'Auto-reload on external changes', cfgAutoReloadHint: 'Reload the reader when the file changes on disk', cfgTool: 'doc_reader agent tool', cfgToolHint: 'Let the assistant read local documents in chat', cfgCommand: '/doc slash command', cfgCommandHint: 'Open recent documents from the chat box', cfgOutlineCount: 'Outline entries injected', translate: 'Translate', translating: 'Translating…', translationFailed: 'Translation failed', translateTitle: 'Translation', translateTarget: 'Translate into', retry: 'Retry', copied: 'Copied ✓', translateEngine: 'Translation engine', translateEngineBing: 'Bing (free, anonymous)', translateEngineGoogle: 'Google (free, anonymous)', translateEngineDsh: 'DSH model (configured provider)', translateModelLabel: 'Model', translateGoogleEndpointLabel: 'Google-compatible endpoint', translateGoogleEndpointHint: 'default: translate.googleapis.com — any reverse proxy works', translateCopy: 'Copy',
|
|
3182
|
+
quoteToChat: 'Quote to chat', quotedToChat: 'Quoted into the chat input', quoteCopied: 'Quote copied — paste it into the chat', quoteFailed: 'Could not quote — copy manually', menuCopy: 'Copy', menuSearchInDoc: 'Search in document', copied: 'Copied', copyPath: 'Copy file path', searchUnavailable: 'Search is not available in this view', atDocs: 'Recent documents', searchJumped: 'Searched in chapter', shortcutOpen: 'Open the doc reader and focus its path box', converting: 'Converting document…',
|
|
3183
|
+
},
|
|
3184
|
+
},
|
|
3185
|
+
zh: {
|
|
3186
|
+
meta: { title: '文档阅读器', description: '在独立面板中阅读本地 PDF、DOCX、Markdown、文本与图片文件。' },
|
|
3187
|
+
panel: {
|
|
3188
|
+
title: '阅读器', toggleSide: '展开/收起最近文件侧栏', placeholder: '输入本地文件绝对路径后回车…',
|
|
3189
|
+
open: '打开', browse: '打开文件', recent: '最近文件', recentEmpty: '还没有打开过文件', openInReader: '在阅读器打开', commandSearch: '搜索', commandRecent: '最近文档',
|
|
3190
|
+
clearRecent: '清空最近文件', removeRecent: '从最近文件删除', revealInFinder: '在文件管理器中显示',
|
|
3191
|
+
error: '无法打开', unsupported: '不支持的文件类型', notFound: '文件不存在',
|
|
3192
|
+
loading: '加载中…', loadingPdf: '正在加载 PDF…', emptyDir: '此目录下没有可读文件',
|
|
3193
|
+
outline: '大纲', pages: '页面', page: '页',
|
|
3194
|
+
search: '搜索', searchPrev: '上一个', searchNext: '下一个', searching: '搜索中…', noMatches: '未找到匹配项',
|
|
3195
|
+
searchTruncated: '匹配过多,仅高亮前 5000 处',
|
|
3196
|
+
retryHint: '关闭后重新打开该文件即可重试',
|
|
3197
|
+
searchPrevShort: '上一个', fontSmaller: '缩小字号', fontBigger: '放大字号', fontReset: '重置字号',
|
|
3198
|
+
prevPage: '上一页', nextPage: '下一页',
|
|
3199
|
+
zoomIn: '放大', zoomOut: '缩小', zoomReset: '恢复 100%',
|
|
3200
|
+
rotateLeft: '左转 90°', rotateRight: '右转 90°', fitWindow: '适应窗口', fitWidth: '适应宽度',
|
|
3201
|
+
pdfRenderFailed: '页面渲染失败', pdfSearchDisabled: 'PDF 文本搜索已关闭(见设置)',
|
|
3202
|
+
docxTooLarge: 'DOCX 过大(>100MB),无法渲染', docxRendered: 'DOCX 渲染完成', dropHint: '把支持的文件路径粘贴到上方打开',
|
|
3203
|
+
renameFile: '重命名文件', renamePrompt: '输入新名称后回车确认', renameDone: '已重命名', renameFailed: '重命名失败',
|
|
3204
|
+
editDocument: '编辑', exitEdit: '退出编辑', saved: '已保存', saveFailed: '保存失败', setLanguage: '语言', langAuto: '跟随 DSH', noChanges: '没有可保存的更改', unsavedConfirm: '放弃未保存的更改?', draftRestored: '已恢复上次未保存的草稿', saveConflictRebased: '文件在磁盘上已变化,已用磁盘版本作为基线;再次保存将覆盖,退出编辑则放弃', resizeSidebar: '拖动调整侧栏宽度', openInReader: '用阅读器打开', listTruncated: '条目过多,仅显示前 2000 项', mdPlainMode: '大文档——纯文本模式', editModeHint: '编辑中 — Ctrl/Cmd+S 保存', collapseSidebar: '收起侧栏', settings: '阅读器设置', setFontSize: '基准字号(10–28)', setLineHeight: '行高(1.2–2.4)',
|
|
3205
|
+
setRecentLimit: '最近文件上限(5–200)', setPdfTextLayer: 'PDF 文本层搜索',
|
|
3206
|
+
setDocxBreakPages: 'DOCX 分页渲染', save: '保存', cancel: '取消', close: '关闭',
|
|
3207
|
+
reloadedFromDisk: '文件在磁盘上已变更,已自动重载', externalChanged: '编辑中的文件已在磁盘上被修改', reloadNow: '重载磁盘版本', keepEditing: '继续编辑',
|
|
3208
|
+
rowConfig: '阅读器设置', cfgCtxInject: '把当前文档大纲注入对话上下文', cfgCtxInjectHint: '让助手知道你正在阅读的文档', cfgAutoReload: '外部修改自动刷新', cfgAutoReloadHint: '文件在磁盘上变化时自动重载阅读器', cfgTool: 'doc_reader 对话工具', cfgToolHint: '让助手在对话中读取本地文档', cfgCommand: '/doc 斜杠命令', cfgCommandHint: '在输入框快速打开最近文档', cfgOutlineCount: '注入的大纲条数', translate: '翻译', translating: '翻译中…', translationFailed: '翻译失败', translateTitle: '翻译结果', translateTarget: '翻译目标语言', retry: '重试', copied: '已复制 ✓', translateEngine: '翻译引擎', translateEngineBing: '必应(免费匿名)', translateEngineGoogle: 'Google(免费匿名)', translateEngineDsh: 'DSH 模型(已配置的服务商)', translateModelLabel: '模型', translateGoogleEndpointLabel: 'Google 兼容端点', translateGoogleEndpointHint: '默认 translate.googleapis.com,可填自建反代', translateCopy: '复制',
|
|
3209
|
+
quoteToChat: '引用到对话', quotedToChat: '已引用到对话输入框', quoteCopied: '引用已复制,粘贴到对话输入框即可', quoteFailed: '引用失败,请手动复制', menuCopy: '复制', menuSearchInDoc: '在文档中搜索', copied: '已复制', copyPath: '复制文件路径', searchUnavailable: '当前视图不支持搜索', atDocs: '最近文档', searchJumped: '已跳转搜索', shortcutOpen: '打开文档阅读器并聚焦路径输入', converting: '正在转换文档…',
|
|
3210
|
+
},
|
|
3211
|
+
},
|
|
3212
|
+
'zh-tw': {
|
|
3213
|
+
meta: { title: '文件閱讀器', description: '在獨立面板中閱讀本地 PDF、DOCX、Markdown、文字與圖片文件。' },
|
|
3214
|
+
panel: {
|
|
3215
|
+
title: '閱讀器', toggleSide: '展開/收合最近文件側欄', placeholder: '輸入本地文件絕對路徑後按 Enter…',
|
|
3216
|
+
open: '開啟', browse: '開啟文件', recent: '最近文件', recentEmpty: '尚未開啟過文件', openInReader: '在閱讀器開啟', commandSearch: '搜尋', commandRecent: '最近文件',
|
|
3217
|
+
clearRecent: '清空最近文件', removeRecent: '從最近文件刪除', revealInFinder: '在檔案管理器中顯示',
|
|
3218
|
+
error: '無法開啟', unsupported: '不支援的文件類型', notFound: '文件不存在',
|
|
3219
|
+
loading: '載入中…', loadingPdf: '正在載入 PDF…', emptyDir: '此目錄下沒有可讀文件',
|
|
3220
|
+
outline: '大綱', pages: '頁面', page: '頁',
|
|
3221
|
+
search: '搜尋', searchPrev: '上一個', searchNext: '下一個', searching: '搜尋中…', noMatches: '未找到符合項',
|
|
3222
|
+
searchTruncated: '匹配過多,僅高亮前 5000 處',
|
|
3223
|
+
retryHint: '關閉後重新開啟該檔案即可重試',
|
|
3224
|
+
searchPrevShort: '上一個', fontSmaller: '縮小字號', fontBigger: '放大字號', fontReset: '重設字號',
|
|
3225
|
+
prevPage: '上一頁', nextPage: '下一頁',
|
|
3226
|
+
zoomIn: '放大', zoomOut: '縮小', zoomReset: '恢復 100%',
|
|
3227
|
+
rotateLeft: '左轉 90°', rotateRight: '右轉 90°', fitWindow: '適應視窗', fitWidth: '適應寬度',
|
|
3228
|
+
pdfRenderFailed: '頁面渲染失敗', pdfSearchDisabled: 'PDF 文字搜尋已關閉(見設定)',
|
|
3229
|
+
docxTooLarge: 'DOCX 過大(>100MB),無法渲染', docxRendered: 'DOCX 渲染完成', dropHint: '把支援的文件路徑貼到上方開啟',
|
|
3230
|
+
renameFile: '重新命名文件', renamePrompt: '輸入新名稱後按 Enter 確認', renameDone: '已重新命名', renameFailed: '重新命名失敗',
|
|
3231
|
+
editDocument: '編輯', exitEdit: '退出編輯', saved: '已儲存', saveFailed: '儲存失敗', setLanguage: '語言', langAuto: '跟隨 DSH', noChanges: '沒有可儲存的變更', unsavedConfirm: '放棄未儲存的變更?', draftRestored: '已恢復上次未儲存的草稿', saveConflictRebased: '檔案在磁碟上已變化,已用磁碟版本作為基線;再次儲存將覆蓋,退出編輯則放棄', resizeSidebar: '拖動調整側欄寬度', openInReader: '用閱讀器開啟', listTruncated: '條目過多,僅顯示前 2000 項', mdPlainMode: '大文件——純文字模式', editModeHint: '編輯中 — Ctrl/Cmd+S 儲存', collapseSidebar: '收起側欄', settings: '閱讀器設定', setFontSize: '基準字號(10–28)', setLineHeight: '行高(1.2–2.4)',
|
|
3232
|
+
setRecentLimit: '最近文件上限(5–200)', setPdfTextLayer: 'PDF 文字層搜尋',
|
|
3233
|
+
setDocxBreakPages: 'DOCX 分頁渲染', save: '儲存', cancel: '取消', close: '關閉',
|
|
3234
|
+
reloadedFromDisk: '檔案在磁碟上已變更,已自動重新載入', externalChanged: '編輯中的檔案已在磁碟上被修改', reloadNow: '重新載入磁碟版本', keepEditing: '繼續編輯',
|
|
3235
|
+
rowConfig: '閱讀器設定', cfgCtxInject: '把目前文件大綱注入對話上下文', cfgCtxInjectHint: '讓助手知道你正在閱讀的文件', cfgAutoReload: '外部修改自動重新載入', cfgAutoReloadHint: '檔案在磁碟上變化時自動重新載入閱讀器', cfgTool: 'doc_reader 對話工具', cfgToolHint: '讓助手在對話中讀取本機文件', cfgCommand: '/doc 斜線命令', cfgCommandHint: '在輸入框快速開啟最近文件', cfgOutlineCount: '注入的大綱條數', translate: '翻譯', translating: '翻譯中…', translationFailed: '翻譯失敗', translateTitle: '翻譯結果', translateTarget: '翻譯目標語言', retry: '重試', copied: '已複製 ✓', translateEngine: '翻譯引擎', translateEngineBing: '必應(免費匿名)', translateEngineGoogle: 'Google(免費匿名)', translateEngineDsh: 'DSH 模型(已設定的服務商)', translateModelLabel: '模型', translateGoogleEndpointLabel: 'Google 相容端點', translateGoogleEndpointHint: '預設 translate.googleapis.com,可填自建反向代理', translateCopy: '複製',
|
|
3236
|
+
quoteToChat: '引用到對話', quotedToChat: '已引用到對話輸入框', quoteCopied: '引用已複製,貼到對話輸入框即可', quoteFailed: '引用失敗,請手動複製', menuCopy: '複製', menuSearchInDoc: '在文件中搜尋', copied: '已複製', copyPath: '複製文件路徑', searchUnavailable: '目前檢視不支援搜尋', atDocs: '最近文件', searchJumped: '已跳轉搜尋', shortcutOpen: '開啟文件閱讀器並聚焦路徑輸入', converting: '正在轉換文件…',
|
|
3237
|
+
},
|
|
3238
|
+
},
|
|
3239
|
+
};
|
|
3240
|
+
// locale dictionaries are FLAT dot-path maps (official client plugins use
|
|
3241
|
+
// `{"browser.home": "…"}`, not nested objects) — flatten ours at build time.
|
|
3242
|
+
function flattenDict(prefix, obj, out) {
|
|
3243
|
+
for (const [key, value] of Object.entries(obj)) {
|
|
3244
|
+
if (value && typeof value === 'object') flattenDict(`${prefix}${key}.`, value, out);
|
|
3245
|
+
else out[`${prefix}${key}`] = String(value);
|
|
3246
|
+
}
|
|
3247
|
+
return out;
|
|
3248
|
+
}
|
|
3249
|
+
const LOCALES = Object.fromEntries(['de', 'en', 'es', 'fr', 'ja', 'pt', 'ru', 'zh', 'zh-tw'].map(
|
|
3250
|
+
(id) => [id, flattenDict('', STRINGS[id] ?? STRINGS.en, {})],
|
|
3251
|
+
));
|
|
3252
|
+
|
|
3253
|
+
// ---------- cross-slot handoff: "open in reader" from other panels ----------
|
|
3254
|
+
// The reader panel owns its open state; handoff buttons elsewhere (document
|
|
3255
|
+
// preview, unpreviewable files) park the requested path here. The panel
|
|
3256
|
+
// consumes it on mount or via the listener when already mounted.
|
|
3257
|
+
let pendingReaderOpen = null;
|
|
3258
|
+
let notifyReaderOpen = () => {};
|
|
3259
|
+
const requestReaderOpen = (path) => {
|
|
3260
|
+
pendingReaderOpen = path;
|
|
3261
|
+
notifyReaderOpen();
|
|
3262
|
+
};
|
|
3263
|
+
function makeReaderHandoff(t, activatePanel) {
|
|
3264
|
+
return function ReaderHandoffAction(props) {
|
|
3265
|
+
const path = props.absolutePath;
|
|
3266
|
+
if (typeof path !== 'string' || !kindOf(path)) return null;
|
|
3267
|
+
return h('button', {
|
|
3268
|
+
type: 'button',
|
|
3269
|
+
title: t('panel.openInReader'),
|
|
3270
|
+
'aria-label': t('panel.openInReader'),
|
|
3271
|
+
onClick: () => { activatePanel(); requestReaderOpen(path); },
|
|
3272
|
+
style: {
|
|
3273
|
+
width: '28px', height: '28px', flex: 'none', display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
|
|
3274
|
+
background: 'transparent', border: 'none', borderRadius: 'var(--dsw-radius-sm)',
|
|
3275
|
+
color: 'var(--dsw-alias-label-secondary)', cursor: 'pointer', padding: 0,
|
|
3276
|
+
},
|
|
3277
|
+
onMouseEnter: (e) => { e.currentTarget.style.background = 'var(--dsw-alias-interactive-bg-hover)'; e.currentTarget.style.color = 'var(--dsw-alias-label-primary)'; },
|
|
3278
|
+
onMouseLeave: (e) => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'var(--dsw-alias-label-secondary)'; },
|
|
3279
|
+
}, Glyph.logo(15));
|
|
3280
|
+
};
|
|
3281
|
+
}
|
|
3282
|
+
|
|
3283
|
+
// ---------- global shortcut focus request ----------
|
|
3284
|
+
// The Cmd/Ctrl+Shift+O shortcut activates the panel and asks it to focus
|
|
3285
|
+
// the path input. A flag survives the case where the panel mounts only
|
|
3286
|
+
// after selectPanel (the event would fire before any listener exists).
|
|
3287
|
+
let focusPathRequested = false;
|
|
3288
|
+
|
|
3289
|
+
// ---------- tool.call.toolview: doc_reader tool result card ----------
|
|
3290
|
+
// Renders inside the chat flow, OUTSIDE the reader panel: the panel
|
|
3291
|
+
// stylesheet does not reach it, so every style is inline and the card
|
|
3292
|
+
// reads only theme tokens (weread-plugin pattern, defensively propped).
|
|
3293
|
+
function makeToolCard(t, activatePanel) {
|
|
3294
|
+
const S = {
|
|
3295
|
+
wrapper: { border: '.5px solid var(--dsw-alias-border-l1)', borderRadius: 8, padding: '8px 10px', fontSize: 12, maxWidth: 460, margin: '4px 0', background: 'var(--dsw-alias-bg-layer-2)' },
|
|
3296
|
+
head: { display: 'flex', alignItems: 'center', gap: 6, fontWeight: 600, minWidth: 0 },
|
|
3297
|
+
file: { fontWeight: 400, color: 'var(--dsw-alias-label-tertiary)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', flex: 1, minWidth: 0 },
|
|
3298
|
+
pre: { margin: '6px 0 0', whiteSpace: 'pre-wrap', maxHeight: 180, overflow: 'auto', color: 'var(--dsw-alias-label-secondary)', fontSize: 11, lineHeight: 1.5 },
|
|
3299
|
+
btn: { marginTop: 8, height: 24, padding: '0 10px', fontSize: 11, color: 'var(--dsw-alias-label-secondary)', background: 'transparent', border: '.5px solid var(--dsw-alias-border-l2)', borderRadius: 6, cursor: 'pointer' },
|
|
3300
|
+
};
|
|
3301
|
+
return function DocReaderToolView(props) {
|
|
3302
|
+
try {
|
|
3303
|
+
const p = props ?? {};
|
|
3304
|
+
const call = p.call ?? p.toolCall ?? p.entry?.call ?? p.node?.call ?? p;
|
|
3305
|
+
const name = call?.name ?? p.name ?? '';
|
|
3306
|
+
if (name && name !== 'doc_reader') return null;
|
|
3307
|
+
const args = call?.arguments ?? call?.args ?? call?.input ?? p.args ?? {};
|
|
3308
|
+
const rawResult = call?.result ?? p.result ?? p.output ?? null;
|
|
3309
|
+
const text = typeof rawResult === 'string' ? rawResult
|
|
3310
|
+
: rawResult?.text ?? rawResult?.content ?? rawResult?.value ?? (rawResult ? JSON.stringify(rawResult) : '');
|
|
3311
|
+
const action = String(args?.action ?? '');
|
|
3312
|
+
const path = typeof args?.path === 'string' ? args.path : '';
|
|
3313
|
+
const file = path ? path.slice(path.lastIndexOf('/') + 1) : '';
|
|
3314
|
+
if (!action && !text) return null;
|
|
3315
|
+
return h('div', { style: S.wrapper, 'data-doc-reader-tool': action || 'result' },
|
|
3316
|
+
h('div', { style: S.head },
|
|
3317
|
+
Glyph.logo(12), ` ${t('panel.title')} · ${action || 'result'}`,
|
|
3318
|
+
file && h('span', { title: path, style: S.file }, file)),
|
|
3319
|
+
text ? h('pre', { style: S.pre }, String(text).slice(0, 1200)) : null,
|
|
3320
|
+
path && kindOf(path) ? h('button', {
|
|
3321
|
+
type: 'button', style: S.btn,
|
|
3322
|
+
onClick: () => { activatePanel(); requestReaderOpen(path); },
|
|
3323
|
+
}, t('panel.openInReader')) : null);
|
|
3324
|
+
} catch { return null; }
|
|
3325
|
+
};
|
|
3326
|
+
}
|
|
3327
|
+
|
|
3328
|
+
// ---------- conversation.chat.commandview: /doc slash-command card ----------
|
|
3329
|
+
// v0.6.0:与微读插件同款醒目卡片(左侧强调边 + 底色);结果文本里的绝对
|
|
3330
|
+
// 路径渲染为可点击——点击即激活阅读器面板并打开该文档。
|
|
3331
|
+
function makeCommandCard(t, activatePanel) {
|
|
3332
|
+
const S = {
|
|
3333
|
+
card: {
|
|
3334
|
+
margin: '6px 0', padding: '10px 12px', borderRadius: 10,
|
|
3335
|
+
border: '1px solid rgba(120,150,235,.35)',
|
|
3336
|
+
borderLeft: '3px solid rgba(90,130,230,.85)',
|
|
3337
|
+
background: 'rgba(120,150,235,.07)',
|
|
3338
|
+
},
|
|
3339
|
+
cardError: {
|
|
3340
|
+
margin: '6px 0', padding: '10px 12px', borderRadius: 10,
|
|
3341
|
+
border: '1px solid rgba(220,60,60,.45)',
|
|
3342
|
+
borderLeft: '3px solid rgba(220,60,60,.8)',
|
|
3343
|
+
background: 'rgba(220,60,60,.06)',
|
|
3344
|
+
},
|
|
3345
|
+
head: { fontWeight: 600, fontSize: '12.5px', display: 'flex', alignItems: 'center', gap: 6 },
|
|
3346
|
+
pre: {
|
|
3347
|
+
margin: '6px 0 0', padding: 0, fontFamily: 'inherit', fontSize: '12.5px', lineHeight: 1.65,
|
|
3348
|
+
whiteSpace: 'pre-wrap', wordBreak: 'break-word', color: 'inherit',
|
|
3349
|
+
},
|
|
3350
|
+
link: {
|
|
3351
|
+
color: 'var(--dsw-alias-accent, #4c7cf5)', textDecoration: 'underline',
|
|
3352
|
+
textDecorationStyle: 'dotted', cursor: 'pointer', wordBreak: 'break-all',
|
|
3353
|
+
},
|
|
3354
|
+
};
|
|
3355
|
+
const PATH_RE = /(\/(?:Users|private|tmp|var|opt|home)\/[^\s,。;;))」』"'`《》]+)/g;
|
|
3356
|
+
const openInReader = (file) => { activatePanel(); requestReaderOpen(file); };
|
|
3357
|
+
const renderTextWithPaths = (text) => {
|
|
3358
|
+
const parts = String(text).split(PATH_RE);
|
|
3359
|
+
return parts.map((seg, i) => (i % 2 === 1
|
|
3360
|
+
? h('span', { key: i, style: S.link, title: t('panel.openInReader') + ': ' + seg, onClick: () => openInReader(seg) }, seg)
|
|
3361
|
+
: seg));
|
|
3362
|
+
};
|
|
3363
|
+
return function DocCommandView(props) {
|
|
3364
|
+
try {
|
|
3365
|
+
const p = props ?? {};
|
|
3366
|
+
let cmd = p.command ?? p.entry?.command;
|
|
3367
|
+
if (!cmd && p.node && typeof p.node === 'object') cmd = p.node.command ?? (p.node.kind === 'command' ? p.node : undefined);
|
|
3368
|
+
if (!cmd) cmd = p;
|
|
3369
|
+
const name = String(cmd?.name ?? p.name ?? '');
|
|
3370
|
+
if (name !== 'doc') return null;
|
|
3371
|
+
const args = String(cmd?.args ?? cmd?.rawInput ?? p.args ?? '').trim();
|
|
3372
|
+
const outcome = cmd?.outcome ?? null;
|
|
3373
|
+
const text = String(outcome?.text ?? cmd?.text ?? cmd?.result ?? p.text ?? '');
|
|
3374
|
+
const failed = outcome?.kind === 'error';
|
|
3375
|
+
return h('div', { style: failed ? S.cardError : S.card },
|
|
3376
|
+
h('div', { style: S.head },
|
|
3377
|
+
Glyph.logo(12), ` ${t('panel.title')} · ${args ? `${t('panel.commandSearch') ?? '搜索'}「${args}」` : (t('panel.commandRecent') ?? '最近文档')}`,
|
|
3378
|
+
failed ? h('span', { style: { color: 'rgba(220,60,60,.9)', fontWeight: 600 } }, ' · 失败') : null),
|
|
3379
|
+
text ? h('pre', { style: S.pre }, renderTextWithPaths(text.slice(0, 1200))) : null);
|
|
3380
|
+
} catch { return null; }
|
|
3381
|
+
};
|
|
3382
|
+
}
|
|
3383
|
+
|
|
3384
|
+
// ---------- plugins.row.config: standard settings row ----------
|
|
3385
|
+
// Reads/writes the plugin-owned config endpoint; switches apply instantly
|
|
3386
|
+
// (no plugin restart). Also outside the panel: inline styles + tokens only.
|
|
3387
|
+
function makeRowConfig(t) {
|
|
3388
|
+
const S = {
|
|
3389
|
+
wrap: { display: 'flex', flexDirection: 'column', gap: 12, padding: '2px 0', fontSize: 12, color: 'var(--dsw-alias-label-primary)' },
|
|
3390
|
+
block: { display: 'flex', flexDirection: 'column', gap: 4 },
|
|
3391
|
+
row: { display: 'flex', alignItems: 'center', gap: 10 },
|
|
3392
|
+
label: { flex: 1, minWidth: 0 },
|
|
3393
|
+
hint: { color: 'var(--dsw-alias-label-tertiary)', fontSize: 11 },
|
|
3394
|
+
muted: { color: 'var(--dsw-alias-label-tertiary)', fontSize: 12, padding: '2px 0' },
|
|
3395
|
+
switchBase: { width: 34, height: 20, borderRadius: 10, border: 'none', cursor: 'pointer', position: 'relative', flex: 'none', padding: 0, transition: 'background .15s' },
|
|
3396
|
+
knob: { position: 'absolute', top: 2, width: 16, height: 16, borderRadius: '50%', background: '#fff', transition: 'left .15s', boxShadow: '0 1px 2px rgba(0,0,0,.25)' },
|
|
3397
|
+
input: { width: 64, height: 24, fontSize: 12, color: 'var(--dsw-alias-label-primary)', background: 'var(--dsw-alias-bg-layer-2)', border: '.5px solid var(--dsw-alias-border-l2)', borderRadius: 6, padding: '0 6px', outline: 'none' },
|
|
3398
|
+
};
|
|
3399
|
+
const TOGGLES = [
|
|
3400
|
+
['ctxInjectEnabled', 'cfgCtxInject', 'cfgCtxInjectHint'],
|
|
3401
|
+
['autoReloadEnabled', 'cfgAutoReload', 'cfgAutoReloadHint'],
|
|
3402
|
+
['toolEnabled', 'cfgTool', 'cfgToolHint'],
|
|
3403
|
+
['commandEnabled', 'cfgCommand', 'cfgCommandHint'],
|
|
3404
|
+
];
|
|
3405
|
+
return function DocReaderRowConfig() {
|
|
3406
|
+
const [cfg, setCfg] = useState(null);
|
|
3407
|
+
const [failed, setFailed] = useState(false);
|
|
3408
|
+
useEffect(() => {
|
|
3409
|
+
let alive = true;
|
|
3410
|
+
fetch(CONFIG_URL)
|
|
3411
|
+
.then((r) => r.json())
|
|
3412
|
+
.then((c) => { if (alive && c && typeof c === 'object') setCfg(c); else if (alive) setFailed(true); })
|
|
3413
|
+
.catch(() => { if (alive) setFailed(true); });
|
|
3414
|
+
return () => { alive = false; };
|
|
3415
|
+
}, []);
|
|
3416
|
+
const save = (key, value) => {
|
|
3417
|
+
fetch(CONFIG_URL, {
|
|
3418
|
+
method: 'POST', headers: { 'content-type': 'application/json' },
|
|
3419
|
+
body: JSON.stringify({ [key]: value }),
|
|
3420
|
+
}).then((r) => (r.ok ? r.json() : null)).then((next) => { if (next && typeof next === 'object') setCfg(next); }).catch(() => { /* keep previous */ });
|
|
3421
|
+
};
|
|
3422
|
+
if (failed) return h('div', { style: S.muted }, `${t('panel.title')}: unavailable`);
|
|
3423
|
+
if (!cfg) return h('div', { style: S.muted }, t('panel.loading'));
|
|
3424
|
+
return h('div', { style: S.wrap, 'data-doc-reader-config': '1' },
|
|
3425
|
+
TOGGLES.map(([key, labelKey, hintKey]) => h('div', { key, style: S.block },
|
|
3426
|
+
h('div', { style: S.row },
|
|
3427
|
+
h('span', { style: S.label }, t(`panel.${labelKey}`)),
|
|
3428
|
+
h('button', {
|
|
3429
|
+
type: 'button', role: 'switch', 'aria-checked': String(cfg[key] === true),
|
|
3430
|
+
style: { ...S.switchBase, background: cfg[key] ? 'var(--dsw-alias-brand-primary)' : 'var(--dsw-alias-border-l2)' },
|
|
3431
|
+
onClick: () => save(key, !(cfg[key] === true)),
|
|
3432
|
+
}, h('span', { style: { ...S.knob, left: cfg[key] ? 16 : 2 } }))),
|
|
3433
|
+
h('div', { style: S.hint }, t(`panel.${hintKey}`)))),
|
|
3434
|
+
h('div', { style: S.row },
|
|
3435
|
+
h('span', { style: S.label }, t('panel.cfgOutlineCount')),
|
|
3436
|
+
h('input', {
|
|
3437
|
+
type: 'number', min: 1, max: 100, defaultValue: cfg.ctxOutlineCount, style: S.input, 'aria-label': t('panel.cfgOutlineCount'),
|
|
3438
|
+
onBlur: (e) => {
|
|
3439
|
+
const v = Math.max(1, Math.min(100, Math.round(Number(e.target.value)) || 30));
|
|
3440
|
+
e.target.value = String(v);
|
|
3441
|
+
if (v !== cfg.ctxOutlineCount) save('ctxOutlineCount', v);
|
|
3442
|
+
},
|
|
3443
|
+
})));
|
|
3444
|
+
};
|
|
3445
|
+
}
|
|
3446
|
+
|
|
3447
|
+
// ---------- quote bridge: reader selection → conversation composer ----------
|
|
3448
|
+
// `inputActions.insertQuote` is a Session-scoped standard prop; the reader
|
|
3449
|
+
// panel is global. A null-rendering bridge component parked in the
|
|
3450
|
+
// composer dock captures the actions object for the panel to call.
|
|
3451
|
+
const quoteBridge = { actions: null };
|
|
3452
|
+
function findInputActions(props) {
|
|
3453
|
+
if (!props || typeof props !== 'object') return null;
|
|
3454
|
+
for (const value of Object.values(props)) {
|
|
3455
|
+
if (value && typeof value === 'object' && typeof value.insertQuote === 'function') return value;
|
|
3456
|
+
}
|
|
3457
|
+
for (const value of Object.values(props)) {
|
|
3458
|
+
if (value && typeof value === 'object') {
|
|
3459
|
+
for (const inner of Object.values(value)) {
|
|
3460
|
+
if (inner && typeof inner === 'object' && typeof inner.insertQuote === 'function') return inner;
|
|
3461
|
+
}
|
|
3462
|
+
}
|
|
3463
|
+
}
|
|
3464
|
+
return null;
|
|
3465
|
+
}
|
|
3466
|
+
function makeQuoteBridge() {
|
|
3467
|
+
return function DocReaderQuoteBridge(props) {
|
|
3468
|
+
const found = findInputActions(props);
|
|
3469
|
+
useEffect(() => {
|
|
3470
|
+
quoteBridge.actions = found;
|
|
3471
|
+
return () => { if (quoteBridge.actions === found) quoteBridge.actions = null; };
|
|
3472
|
+
}, [found]);
|
|
3473
|
+
return null;
|
|
3474
|
+
};
|
|
3475
|
+
}
|
|
3476
|
+
/** Quote a selection into the chat composer; returns 'chat' | 'copied' | null. */
|
|
3477
|
+
async function quoteSelectionToChat(displayName, text) {
|
|
3478
|
+
const trimmed = String(text ?? '').trim();
|
|
3479
|
+
if (!trimmed) return null;
|
|
3480
|
+
const quoted = trimmed.split('\n').map((line) => `> ${line}`).join('\n');
|
|
3481
|
+
const withSource = `> 《${displayName}》\n${quoted}`.slice(0, 8000);
|
|
3482
|
+
const actions = quoteBridge.actions;
|
|
3483
|
+
if (actions) {
|
|
3484
|
+
try {
|
|
3485
|
+
if (actions.insertQuote(withSource)) return 'chat';
|
|
3486
|
+
} catch { /* fall back to the clipboard */ }
|
|
3487
|
+
}
|
|
3488
|
+
try {
|
|
3489
|
+
await navigator.clipboard.writeText(withSource);
|
|
3490
|
+
return 'copied';
|
|
3491
|
+
} catch {
|
|
3492
|
+
return null;
|
|
3493
|
+
}
|
|
3494
|
+
}
|
|
3495
|
+
|
|
3496
|
+
// ---------- input-trigger source: "@doc" recent-documents references ----------
|
|
3497
|
+
// Same registration contract the official ui-reference source uses
|
|
3498
|
+
// (ctx.get('inputTriggers').registerSource). Candidates come straight from
|
|
3499
|
+
// the reader's recent list in localStorage — no Host round-trip.
|
|
3500
|
+
function makeDocSource(t, activatePanel) {
|
|
3501
|
+
return {
|
|
3502
|
+
trigger: '@',
|
|
3503
|
+
name: 'doc-reader',
|
|
3504
|
+
async candidates(_session, req) {
|
|
3505
|
+
const query = String(req?.query ?? '').toLowerCase();
|
|
3506
|
+
const recent = readJson(LS.recent, []);
|
|
3507
|
+
return recent.slice(0, 12)
|
|
3508
|
+
.filter((e) => !query || e.path.toLowerCase().includes(query))
|
|
3509
|
+
.map((e) => {
|
|
3510
|
+
const name = e.path.slice(e.path.lastIndexOf('/') + 1);
|
|
3511
|
+
const slash = e.path.lastIndexOf('/');
|
|
3512
|
+
const parent = slash > 0 ? e.path.slice(0, slash) : '';
|
|
3513
|
+
return {
|
|
3514
|
+
name,
|
|
3515
|
+
description: parent || undefined,
|
|
3516
|
+
icon: 'file',
|
|
3517
|
+
section: t('panel.atDocs'),
|
|
3518
|
+
value: JSON.stringify({ path: e.path }),
|
|
3519
|
+
};
|
|
3520
|
+
});
|
|
3521
|
+
},
|
|
3522
|
+
onPick({ candidate }) {
|
|
3523
|
+
try {
|
|
3524
|
+
const value = JSON.parse(candidate?.value);
|
|
3525
|
+
if (value && typeof value.path === 'string' && value.path.startsWith('/')) {
|
|
3526
|
+
const base = value.path.slice(value.path.lastIndexOf('/') + 1);
|
|
3527
|
+
return {
|
|
3528
|
+
insert: {
|
|
3529
|
+
source: 'doc-reader',
|
|
3530
|
+
ref: value.path,
|
|
3531
|
+
label: base,
|
|
3532
|
+
appearance: 'file',
|
|
3533
|
+
clipboardText: value.path,
|
|
3534
|
+
},
|
|
3535
|
+
};
|
|
3536
|
+
}
|
|
3537
|
+
} catch { /* malformed value should not happen; ignore */ }
|
|
3538
|
+
return undefined;
|
|
3539
|
+
},
|
|
3540
|
+
openReference(_session, { ref }) {
|
|
3541
|
+
if (typeof ref === 'string' && ref.startsWith('/') && kindOf(ref)) {
|
|
3542
|
+
activatePanel();
|
|
3543
|
+
requestReaderOpen(ref);
|
|
3544
|
+
return true;
|
|
3545
|
+
}
|
|
3546
|
+
return false;
|
|
3547
|
+
},
|
|
3548
|
+
codec: { clipboardText: (ref) => ref, serialize: async (ref) => ref },
|
|
3549
|
+
};
|
|
3550
|
+
}
|
|
3551
|
+
|
|
3552
|
+
return {
|
|
3553
|
+
inject: ['slots', 'locale', 'layout'],
|
|
3554
|
+
apply(ctx) {
|
|
3555
|
+
ctx.effect(() => {
|
|
3556
|
+
const disposers = Object.entries(LOCALES)
|
|
3557
|
+
.map(([locale, dict]) => ctx.locale.register('doc-reader', locale, dict));
|
|
3558
|
+
return () => { for (const dispose of disposers.reverse()) dispose(); };
|
|
3559
|
+
}, 'dsh-doc-reader: locale');
|
|
3560
|
+
const t = ctx.locale.bind('doc-reader');
|
|
3561
|
+
ctx.effect(() => ctx.slots.inject('main', () => ctx.slots.register(
|
|
3562
|
+
{ name: 'main', key: 'doc-reader' },
|
|
3563
|
+
makeReaderPanel(t),
|
|
3564
|
+
)), 'dsh-doc-reader: main panel');
|
|
3565
|
+
ctx.effect(() => ctx.slots.inject('sidebar.panellist', () => ctx.slots.register(
|
|
3566
|
+
{ name: 'sidebar.panellist', id: 'doc-reader', order: 60, label: t('panel.title') },
|
|
3567
|
+
PanelIcon,
|
|
3568
|
+
)), 'dsh-doc-reader: sidebar entry');
|
|
3569
|
+
// "open in reader" from the document-preview panel and from
|
|
3570
|
+
// files the built-in preview cannot render (both pass {absolutePath})
|
|
3571
|
+
const activateReader = () => { try { ctx.layout?.selectPanel('doc-reader'); } catch { /* panel already active or layout absent */ } };
|
|
3572
|
+
const handoff = makeReaderHandoff(t, activateReader);
|
|
3573
|
+
ctx.effect(() => ctx.slots.inject('sidebar.right.tab.document.actions', () => ctx.slots.register(
|
|
3574
|
+
{ name: 'sidebar.right.tab.document.actions', id: 'dsh-doc-reader', locale: 'doc-reader' },
|
|
3575
|
+
handoff,
|
|
3576
|
+
)), 'dsh-doc-reader: document preview handoff');
|
|
3577
|
+
ctx.effect(() => ctx.slots.inject('sidebar.right.tab.document.unpreviewable', () => ctx.slots.register(
|
|
3578
|
+
{ name: 'sidebar.right.tab.document.unpreviewable', id: 'dsh-doc-reader', locale: 'doc-reader' },
|
|
3579
|
+
handoff,
|
|
3580
|
+
)), 'dsh-doc-reader: unpreviewable handoff');
|
|
3581
|
+
// agent tool result card in the chat flow ("open in reader" bridge)
|
|
3582
|
+
ctx.effect(() => ctx.slots.inject('tool.call.toolview', () => ctx.slots.register(
|
|
3583
|
+
{ name: 'tool.call.toolview', key: 'doc_reader' },
|
|
3584
|
+
makeToolCard(t, activateReader),
|
|
3585
|
+
)), 'dsh-doc-reader: tool result card');
|
|
3586
|
+
// v0.6.0:/doc 斜杠命令反馈卡片(与微读插件同款样式,路径可点击)
|
|
3587
|
+
ctx.effect(() => ctx.slots.inject('conversation.chat.commandview', () => ctx.slots.register(
|
|
3588
|
+
{ name: 'conversation.chat.commandview', key: 'doc' },
|
|
3589
|
+
makeCommandCard(t, activateReader),
|
|
3590
|
+
)), 'dsh-doc-reader: /doc command card');
|
|
3591
|
+
// v0.6.0:跨插件打开桥——其他插件(如微读命令卡片)派发 cancelable 的
|
|
3592
|
+
// dsh:open-in-reader 事件;本插件在时 preventDefault 接管并在面板打开,
|
|
3593
|
+
// 不在时事件无人处理,派发方自行回退(如系统默认应用打开)。
|
|
3594
|
+
ctx.effect(() => {
|
|
3595
|
+
const onOpenInReader = (ev) => {
|
|
3596
|
+
const target = typeof ev?.detail?.path === 'string' ? ev.detail.path.trim() : '';
|
|
3597
|
+
if (!target) return;
|
|
3598
|
+
ev.preventDefault();
|
|
3599
|
+
activateReader();
|
|
3600
|
+
requestReaderOpen(target);
|
|
3601
|
+
};
|
|
3602
|
+
window.addEventListener('dsh:open-in-reader', onOpenInReader);
|
|
3603
|
+
return () => { window.removeEventListener('dsh:open-in-reader', onOpenInReader); };
|
|
3604
|
+
}, 'dsh-doc-reader: open-in-reader bridge');
|
|
3605
|
+
// standard settings row on the plugin manager row
|
|
3606
|
+
ctx.effect(() => ctx.slots.inject('plugins.row.config', () => ctx.slots.register(
|
|
3607
|
+
{ name: 'plugins.row.config', key: 'dsh-document-reader#dsh-doc-reader', label: () => t('panel.rowConfig') },
|
|
3608
|
+
makeRowConfig(t),
|
|
3609
|
+
)), 'dsh-doc-reader: row config');
|
|
3610
|
+
// global shortcut: activate the reader and focus its path input
|
|
3611
|
+
try {
|
|
3612
|
+
ctx.effect(() => ctx.shortcuts.register({
|
|
3613
|
+
id: 'doc-reader.open',
|
|
3614
|
+
label: () => t('panel.shortcutOpen'),
|
|
3615
|
+
aliases: ['doc reader', 'open in reader'],
|
|
3616
|
+
defaults: {
|
|
3617
|
+
'desktop:macos': { code: 'KeyO', modifiers: ['primary', 'shift'] },
|
|
3618
|
+
'desktop:windows': { code: 'KeyO', modifiers: ['primary', 'shift'] },
|
|
3619
|
+
'desktop:linux': { code: 'KeyO', modifiers: ['primary', 'shift'] },
|
|
3620
|
+
'web:macos': { code: 'KeyO', modifiers: ['primary', 'shift'] },
|
|
3621
|
+
'web:windows': { code: 'KeyO', modifiers: ['primary', 'shift'] },
|
|
3622
|
+
'web:linux': { code: 'KeyO', modifiers: ['primary', 'shift'] },
|
|
3623
|
+
},
|
|
3624
|
+
resolve: () => ({
|
|
3625
|
+
status: 'handled',
|
|
3626
|
+
run: () => {
|
|
3627
|
+
focusPathRequested = true;
|
|
3628
|
+
try { ctx.layout?.selectPanel('doc-reader'); } catch { /* already active */ }
|
|
3629
|
+
try { window.dispatchEvent(new (window.CustomEvent ?? window.Event)('doc-reader:focus-path')); } catch { /* no window */ }
|
|
3630
|
+
},
|
|
3631
|
+
}),
|
|
3632
|
+
}), 'dsh-doc-reader: open shortcut');
|
|
3633
|
+
} catch (error) {
|
|
3634
|
+
ctx.logger?.warn?.(`doc-reader shortcut registration failed: ${error?.message ?? error}`);
|
|
3635
|
+
}
|
|
3636
|
+
// quote bridge: capture Session inputActions from the composer dock so the
|
|
3637
|
+
// global reader panel can insert a blockquote into the chat draft
|
|
3638
|
+
ctx.effect(() => ctx.slots.inject('conversation.composer.dock', () => ctx.slots.register(
|
|
3639
|
+
{ name: 'conversation.composer.dock', id: 'doc-reader-bridge', order: 99 },
|
|
3640
|
+
makeQuoteBridge(),
|
|
3641
|
+
)), 'dsh-doc-reader: quote bridge');
|
|
3642
|
+
// "@doc" reference source in the composer trigger menu (recent documents)
|
|
3643
|
+
try {
|
|
3644
|
+
const inputTriggers = ctx.get('inputTriggers');
|
|
3645
|
+
ctx.effect(() => inputTriggers.registerSource(makeDocSource(t, activateReader)), 'dsh-doc-reader: @doc source');
|
|
3646
|
+
} catch (error) {
|
|
3647
|
+
ctx.logger?.warn?.(`doc-reader inputTriggers unavailable: ${error?.message ?? error}`);
|
|
3648
|
+
}
|
|
3649
|
+
},
|
|
3650
|
+
};
|
|
3651
|
+
},
|
|
3652
|
+
});
|