@spzxg/cli-ui 0.6.18 → 0.6.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +8 -2
- package/README.md +3 -3
- package/dist/{cli-ui-embed-Dsw7A8BQ.js → cli-ui-embed-BIeQkXIU.js} +16955 -16434
- package/dist/{cli-ui-index-CHFgaDHY.js → cli-ui-index-BOCFJA87.js} +2 -2
- package/dist/{cli-ui-jszip.min-Dw9DMuD5.js → cli-ui-jszip.min-DeMMXc2T.js} +2 -2
- package/dist/{cli-ui-jszip.min-DDRprLiN.js → cli-ui-jszip.min-cpxytNM4.js} +1 -1
- package/dist/{cli-ui-xlsx-BUG2_Azh.js → cli-ui-xlsx-BLe37Dql.js} +1 -1
- package/dist/cli-ui.js +1 -1
- package/package.json +1 -1
- package/src/board/CliBoard.tsx +11 -2
- package/src/board/FileViewer.tsx +131 -20
- package/src/board/frameQuote.ts +42 -8
- package/src/board/htmlWorkspace.ts +499 -0
- package/src/board/previewCache.ts +137 -0
- package/src/chat/CliChat.tsx +14 -4
- package/src/chat/Composer.tsx +1 -1
- package/src/core/config.ts +1 -1
- package/src/index.ts +1 -0
- package/src/operator/node/Chat.tsx +6 -1
- package/src/operator/node/Composer.tsx +2 -2
- package/src/operator/node/SessionRail.tsx +11 -7
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { g as ms, a as vs } from "./cli-ui-embed-
|
|
2
|
-
import { r as ys } from "./cli-ui-jszip.min-
|
|
1
|
+
import { g as ms, a as vs } from "./cli-ui-embed-BIeQkXIU.js";
|
|
2
|
+
import { r as ys } from "./cli-ui-jszip.min-cpxytNM4.js";
|
|
3
3
|
function gs(e, t) {
|
|
4
4
|
for (var n = 0; n < t.length; n++) {
|
|
5
5
|
const r = t[n];
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { a } from "./cli-ui-embed-
|
|
2
|
-
import { r as p } from "./cli-ui-jszip.min-
|
|
1
|
+
import { a } from "./cli-ui-embed-BIeQkXIU.js";
|
|
2
|
+
import { r as p } from "./cli-ui-jszip.min-cpxytNM4.js";
|
|
3
3
|
function f(t, n) {
|
|
4
4
|
for (var o = 0; o < n.length; o++) {
|
|
5
5
|
const e = n[o];
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { c as bt } from "./cli-ui-embed-
|
|
1
|
+
import { c as bt } from "./cli-ui-embed-BIeQkXIU.js";
|
|
2
2
|
function vt(yt) {
|
|
3
3
|
throw new Error('Could not dynamically require "' + yt + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');
|
|
4
4
|
}
|
|
@@ -28,7 +28,7 @@ function v(e) {
|
|
|
28
28
|
}
|
|
29
29
|
async function R(e) {
|
|
30
30
|
var E;
|
|
31
|
-
const t = await import("./cli-ui-jszip.min-
|
|
31
|
+
const t = await import("./cli-ui-jszip.min-DeMMXc2T.js").then((s) => s.j), o = await (t.default ?? t).loadAsync(e), m = async (s) => {
|
|
32
32
|
const a = o.file(s);
|
|
33
33
|
return a ? a.async("string") : null;
|
|
34
34
|
}, S = await m("xl/workbook.xml");
|
package/dist/cli-ui.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { C as a, b as i, d as r, e as t, f as o, h as C, i as l, j as n, k as m, m as d, l as u, n as w, o as B, p as f } from "./cli-ui-embed-
|
|
1
|
+
import { C as a, b as i, d as r, e as t, f as o, h as C, i as l, j as n, k as m, m as d, l as u, n as w, o as B, p as f } from "./cli-ui-embed-BIeQkXIU.js";
|
|
2
2
|
export {
|
|
3
3
|
a as CliBoard,
|
|
4
4
|
i as CliBrowserView,
|
package/package.json
CHANGED
package/src/board/CliBoard.tsx
CHANGED
|
@@ -330,6 +330,11 @@ function BoardInner({ jobId: jobIdProp, taskId: taskIdProp, tabs, availableTabs,
|
|
|
330
330
|
|
|
331
331
|
const activeRef = useRef(activeTab);
|
|
332
332
|
activeRef.current = activeTab;
|
|
333
|
+
const closedVersions = useRef(new Map<string, number>());
|
|
334
|
+
useEffect(() => { closedVersions.current.clear(); }, [jobId]);
|
|
335
|
+
const rememberClosedVersion = (closed: OpenFile) => {
|
|
336
|
+
closedVersions.current.set(closed.path, Math.max(closedVersions.current.get(closed.path) ?? -1, closed.version));
|
|
337
|
+
};
|
|
333
338
|
/** 打开文件:已经开着就切过去(并重读),否则新开一个页签;超过 MAX_FILE_TABS 关掉最早的(不关正在看的)。 */
|
|
334
339
|
const openPath = useCallback((path: string, entry?: Partial<FileEntry>) => {
|
|
335
340
|
const requested = path.replace(/^\.\//, "").replace(/\/+$/, "");
|
|
@@ -339,10 +344,12 @@ function BoardInner({ jobId: jobIdProp, taskId: taskIdProp, tabs, availableTabs,
|
|
|
339
344
|
setFiles((list) => {
|
|
340
345
|
const have = list.find((f) => f.path === clean);
|
|
341
346
|
if (have) return list.map((f) => (f.path === clean ? { ...f, name: entry?.name ?? f.name, size: entry?.size ?? f.size, mtime: entry?.mtime ?? f.mtime, version: f.version + 1 } : f));
|
|
342
|
-
const
|
|
347
|
+
const priorClosed = closedVersions.current.get(clean);
|
|
348
|
+
const next = [...list, { path: clean, name: entry?.name, size: entry?.size, mtime: entry?.mtime, version: priorClosed !== undefined ? priorClosed + 1 : 0, ...(resolvedFrom ? { resolvedFrom } : {}) }];
|
|
343
349
|
while (next.length > MAX_FILE_TABS) {
|
|
344
350
|
const i = next.findIndex((f) => fileTabId(f.path) !== activeRef.current && f.path !== clean);
|
|
345
|
-
next.splice(i >= 0 ? i : 0, 1);
|
|
351
|
+
const [evicted] = next.splice(i >= 0 ? i : 0, 1);
|
|
352
|
+
if (evicted) rememberClosedVersion(evicted);
|
|
346
353
|
}
|
|
347
354
|
return next;
|
|
348
355
|
});
|
|
@@ -381,6 +388,7 @@ function BoardInner({ jobId: jobIdProp, taskId: taskIdProp, tabs, availableTabs,
|
|
|
381
388
|
setFiles((list) => {
|
|
382
389
|
const i = list.findIndex((f) => f.path === path);
|
|
383
390
|
if (i < 0) return list;
|
|
391
|
+
rememberClosedVersion(list[i]);
|
|
384
392
|
const next = list.filter((f) => f.path !== path);
|
|
385
393
|
if (activeRef.current === fileTabId(path)) setTab(next.length ? fileTabId(next[Math.min(i, next.length - 1)].path) : "files");
|
|
386
394
|
return next;
|
|
@@ -458,6 +466,7 @@ function BoardInner({ jobId: jobIdProp, taskId: taskIdProp, tabs, availableTabs,
|
|
|
458
466
|
displayName={file.name}
|
|
459
467
|
size={file.size}
|
|
460
468
|
mtime={file.mtime}
|
|
469
|
+
workspaceRoot={info?.workspaceRoot}
|
|
461
470
|
version={file.version + manual} reloadKey={file.reloadKey}
|
|
462
471
|
actions={allFileActions}
|
|
463
472
|
onOpenPath={(p) => openPath(p)}
|
package/src/board/FileViewer.tsx
CHANGED
|
@@ -23,6 +23,8 @@ import { bridgeDoc, frameToken, type FrameSelMessage } from "./frameQuote";
|
|
|
23
23
|
import { syncFile } from "./fileSync";
|
|
24
24
|
import { retainFileScope } from "./fileScope";
|
|
25
25
|
import { isTaskUploadPath } from "../core/documentUpload";
|
|
26
|
+
import { deleteCachedPreview, getCachedPreview, setCachedPreview } from "./previewCache";
|
|
27
|
+
import { prepareWorkspaceHtml, readWorkspaceAsset, resolveWorkspaceAssetPath } from "./htmlWorkspace";
|
|
26
28
|
|
|
27
29
|
export { downloadFile };
|
|
28
30
|
|
|
@@ -132,6 +134,8 @@ export interface FileViewerProps {
|
|
|
132
134
|
/** 文件信息(列表里已有的话省一次请求)。 */
|
|
133
135
|
size?: number;
|
|
134
136
|
mtime?: number;
|
|
137
|
+
/** 工作区根目录(用于 HTML 根相对资源解析与越界边界保护)。 */
|
|
138
|
+
workspaceRoot?: string;
|
|
135
139
|
/** 变了就重新读(看板在文件更新时递增)。 */
|
|
136
140
|
version?: number;
|
|
137
141
|
/** 明确的文件变更事件使内容重新读取,不能只按末尾重叠判断为追加。 */
|
|
@@ -168,10 +172,17 @@ export function FileViewer(props:FileViewerProps) {
|
|
|
168
172
|
let id=viewerBackendIds.get(props.backend);if(id===undefined){id=nextViewerBackendId++;viewerBackendIds.set(props.backend,id);}
|
|
169
173
|
return <FileViewerInner key={JSON.stringify([id,props.jobId,props.path])} {...props}/>;
|
|
170
174
|
}
|
|
171
|
-
function
|
|
175
|
+
function cacheMetaMatches(cached: { mtime?: number; size?: number }, mtime?: number, size?: number): boolean {
|
|
176
|
+
if (mtime !== undefined && cached.mtime !== undefined && cached.mtime !== mtime) return false;
|
|
177
|
+
if (size !== undefined && cached.size !== undefined && cached.size !== size) return false;
|
|
178
|
+
return true;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function FileViewerInner({ backend, jobId, path, displayName, size, mtime, workspaceRoot, version = 0, reloadKey, onOpenPath, onClose, lead, onBack, actions = [], bare, toolbarHost, onQuoteText, resolveMissing, onResolved, resolvedFrom }: FileViewerProps) {
|
|
172
182
|
const name = displayName || path.split("/").pop() || path;
|
|
173
183
|
const kind: PreviewKind = previewKind(path);
|
|
174
|
-
const
|
|
184
|
+
const initialCached = useMemo(() => getCachedPreview(backend, jobId, path), [backend, jobId, path]);
|
|
185
|
+
const [loaded, setLoaded] = useState<Loaded | null>(() => initialCached?.kind === "text" ? { kind: "text", ...initialCached.loaded } : null);
|
|
175
186
|
const [error, setError] = useState<string | null>(null);
|
|
176
187
|
const [downloadError, setDownloadError] = useState<string | null>(null);
|
|
177
188
|
const [copied, setCopied] = useState(false);
|
|
@@ -185,20 +196,23 @@ function FileViewerInner({ backend, jobId, path, displayName, size, mtime, versi
|
|
|
185
196
|
const [htmlPresentation, setHtmlPresentation] = useState<"reading" | "original">("original");
|
|
186
197
|
const htmlReading = kind === "html" && mode === "preview" && htmlPresentation === "reading";
|
|
187
198
|
// 超大文本:看开头还是看末尾(日志看末尾)。
|
|
188
|
-
const [tail, setTail] = useState(false);
|
|
199
|
+
const [tail, setTail] = useState(() => initialCached?.kind === "text" ? initialCached.tail : false);
|
|
189
200
|
const progressiveText = kind === "csv" || !!backend.fileSync && (kind === "text" || kind === "code");
|
|
190
|
-
const [textLimit, setTextLimit] = useState(kind === "html" || progressiveText || backend.fileSync && kind === "markdown" ? MARKDOWN_STEP : TEXT_MAX);
|
|
201
|
+
const [textLimit, setTextLimit] = useState(() => initialCached?.kind === "text" ? initialCached.textLimit : (kind === "html" || progressiveText || backend.fileSync && kind === "markdown" ? MARKDOWN_STEP : TEXT_MAX));
|
|
191
202
|
const [syncing, setSyncing] = useState(false);
|
|
192
203
|
const [parsing, setParsing] = useState(false);
|
|
193
204
|
const [cancelled, setCancelled] = useState(false);
|
|
194
205
|
const sourceBusy = useCallback((value: boolean) => { setSyncing(value); if (value) setCancelled(false); }, []);
|
|
195
206
|
const readingBusy = useCallback((value: boolean) => { setParsing(value); if (value) setCancelled(false); }, []);
|
|
196
|
-
const revisionRef = useRef<string | undefined>(undefined);
|
|
207
|
+
const revisionRef = useRef<string | undefined>(initialCached?.kind === "text" ? initialCached.loaded.revision : initialCached?.kind === "html" ? initialCached.revision : undefined);
|
|
208
|
+
const openPathRef = useRef(onOpenPath);
|
|
209
|
+
openPathRef.current = onOpenPath;
|
|
197
210
|
const fileReadAbort = useRef<AbortController | null>(null);
|
|
198
211
|
const readingAbort = useRef<AbortController | null>(null);
|
|
199
212
|
const cancelRead = () => { fileReadAbort.current?.abort(); readingAbort.current?.abort(); setSyncing(false); setParsing(false); setCancelled(true); };
|
|
200
213
|
useEffect(() => retainFileScope(backend, jobId, { paths: [path], dirs: [], onDenied: message => {
|
|
201
214
|
fileReadAbort.current?.abort(); readingAbort.current?.abort(); revisionRef.current = undefined;
|
|
215
|
+
deleteCachedPreview(backend, jobId, path);
|
|
202
216
|
setLoaded(null); setHtmlDoc(null); setSyncing(false); setParsing(false); setError(message || "文件访问受限,请检查任务文件目录或访问权限");
|
|
203
217
|
} }), [backend, jobId, path]);
|
|
204
218
|
// 放大:盖住页面看(看板窄的时候看报告、表格、图片)。Esc 还原。
|
|
@@ -224,7 +238,7 @@ function FileViewerInner({ backend, jobId, path, displayName, size, mtime, versi
|
|
|
224
238
|
// 这个预览的口令:iframe 里的选区桥报上来的消息只认它(见 frameQuote.ts)。
|
|
225
239
|
const token = useMemo(frameToken, []);
|
|
226
240
|
const links = useFileLinks(backend, jobId, path, version, attempt, reloadKey, !!backend.fileSync && isTaskUploadPath(path));
|
|
227
|
-
const knownSize = size ?? (loaded?.kind === "text" ? loaded.size : undefined);
|
|
241
|
+
const knownSize = size ?? (loaded?.kind === "text" ? loaded.size : initialCached?.kind === "html" ? initialCached.size : undefined);
|
|
228
242
|
// 读大文件时的进度(已收到的字节数)。
|
|
229
243
|
const [progress, setProgress] = useState(0);
|
|
230
244
|
// HTML 默认原样预览,完整重组后插选区桥;加载或排版较慢时可切分段阅读。
|
|
@@ -233,8 +247,14 @@ function FileViewerInner({ backend, jobId, path, displayName, size, mtime, versi
|
|
|
233
247
|
const linksRef = useRef(links);
|
|
234
248
|
linksRef.current = links;
|
|
235
249
|
const htmlTooBig = size !== undefined && size > HTML_QUOTE_MAX;
|
|
236
|
-
const htmlBridge = (!!backend.fileSync || !!onQuoteText) && kind === "html" && mode === "preview" && !htmlReading && !links.pending && !htmlTooBig;
|
|
237
|
-
const [htmlDoc, setHtmlDoc] = useState<{ srcDoc: string; token: string; revision?: string } | "fallback" | "toobig" | null>(
|
|
250
|
+
const htmlBridge = (!!backend.fileSync || !!onQuoteText || links.blob) && kind === "html" && mode === "preview" && !htmlReading && !links.pending && !htmlTooBig;
|
|
251
|
+
const [htmlDoc, setHtmlDoc] = useState<{ srcDoc: string; token: string; revision?: string; preparedHtml?: string } | "fallback" | "toobig" | null>(() => {
|
|
252
|
+
if (initialCached?.kind !== "html" || htmlTooBig || kind !== "html") return null;
|
|
253
|
+
const bridgeToken = frameToken();
|
|
254
|
+
const url = links.url?.(path);
|
|
255
|
+
const base = url ? new URL(url, window.location.href).href : undefined;
|
|
256
|
+
return { srcDoc: bridgeDoc(initialCached.preparedHtml, { token: bridgeToken, base, allowScripts: true }), token: bridgeToken, revision: initialCached.revision, preparedHtml: initialCached.preparedHtml };
|
|
257
|
+
});
|
|
238
258
|
useEffect(() => { if (htmlReading || mode === "source") setHtmlDoc(null); }, [htmlReading, mode]);
|
|
239
259
|
const [frameState, setFrameState] = useState<"rendering" | "slow" | "ready">("rendering");
|
|
240
260
|
// 走 srcdoc 时不用再按地址取(中枢太旧时那是又整个读一遍)。
|
|
@@ -242,6 +262,18 @@ function FileViewerInner({ backend, jobId, path, displayName, size, mtime, versi
|
|
|
242
262
|
const src = useFileSrc(backend, jobId, path, needsSrc && !bridged && !(kind === "html" && mode === "source"), version, knownSize, links, attempt);
|
|
243
263
|
useEffect(() => {
|
|
244
264
|
if (!htmlBridge) return;
|
|
265
|
+
const cached = getCachedPreview(backend, jobId, path);
|
|
266
|
+
if (attempt === 0 && cached?.kind === "html" && cached.version === version && cached.reloadKey === reloadKey && cacheMetaMatches(cached, mtime, size)) {
|
|
267
|
+
revisionRef.current = cached.revision;
|
|
268
|
+
const url = linksRef.current.url?.(path);
|
|
269
|
+
const base = url ? new URL(url, window.location.href).href : undefined;
|
|
270
|
+
setHtmlDoc(previous => {
|
|
271
|
+
if (previous && typeof previous === "object" && previous.revision === cached.revision && previous.preparedHtml === cached.preparedHtml) return previous;
|
|
272
|
+
const bridgeToken = frameToken();
|
|
273
|
+
return { srcDoc: bridgeDoc(cached.preparedHtml, { token: bridgeToken, base, allowScripts: true }), token: bridgeToken, revision: cached.revision, preparedHtml: cached.preparedHtml };
|
|
274
|
+
});
|
|
275
|
+
return;
|
|
276
|
+
}
|
|
245
277
|
const ctl = new AbortController();
|
|
246
278
|
fileReadAbort.current = ctl;
|
|
247
279
|
setError(null); setCancelled(false); setSyncing(true); setProgress(0);
|
|
@@ -251,27 +283,66 @@ function FileViewerInner({ backend, jobId, path, displayName, size, mtime, versi
|
|
|
251
283
|
const result = await syncFile(transport, jobId, path, options);
|
|
252
284
|
return { text: result.text ?? decodeText(result.bytes).text, revision: result.revision, size: result.size };
|
|
253
285
|
})()
|
|
254
|
-
: readBoundedBuffer(backend, jobId, path, HTML_QUOTE_MAX, { signal: ctl.signal, onBytes: setProgress }).then(buffer => ({ text: decodeText(new Uint8Array(buffer)).text, revision: undefined }));
|
|
255
|
-
loading.then(result => {
|
|
286
|
+
: readBoundedBuffer(backend, jobId, path, HTML_QUOTE_MAX, { signal: ctl.signal, onBytes: setProgress }).then(buffer => ({ text: decodeText(new Uint8Array(buffer)).text, revision: undefined, size: buffer.byteLength }));
|
|
287
|
+
loading.then(async result => {
|
|
256
288
|
if (ctl.signal.aborted) return;
|
|
289
|
+
const latestCached = getCachedPreview(backend, jobId, path);
|
|
290
|
+
let preparedHtml: string;
|
|
291
|
+
let blobUrls: string[];
|
|
292
|
+
if (attempt === 0 && result.revision && latestCached?.kind === "html" && latestCached.revision === result.revision) {
|
|
293
|
+
preparedHtml = latestCached.preparedHtml;
|
|
294
|
+
blobUrls = latestCached.blobUrls;
|
|
295
|
+
} else {
|
|
296
|
+
const prepared = await prepareWorkspaceHtml({
|
|
297
|
+
html: result.text,
|
|
298
|
+
htmlPath: path,
|
|
299
|
+
backend,
|
|
300
|
+
jobId,
|
|
301
|
+
workspaceRoot,
|
|
302
|
+
signal: ctl.signal,
|
|
303
|
+
fresh: attempt > 0,
|
|
304
|
+
});
|
|
305
|
+
preparedHtml = prepared.html;
|
|
306
|
+
blobUrls = prepared.blobUrls;
|
|
307
|
+
}
|
|
308
|
+
if (ctl.signal.aborted) {
|
|
309
|
+
for (const u of blobUrls) { try { URL.revokeObjectURL(u); } catch { /* ignore */ } }
|
|
310
|
+
return;
|
|
311
|
+
}
|
|
312
|
+
setCachedPreview(backend, jobId, path, {
|
|
313
|
+
kind: "html",
|
|
314
|
+
text: result.text,
|
|
315
|
+
preparedHtml,
|
|
316
|
+
blobUrls,
|
|
317
|
+
revision: result.revision,
|
|
318
|
+
size: result.size,
|
|
319
|
+
mtime,
|
|
320
|
+
version,
|
|
321
|
+
reloadKey,
|
|
322
|
+
chars: result.text.length + (preparedHtml === result.text ? 0 : preparedHtml.length),
|
|
323
|
+
});
|
|
257
324
|
const url = linksRef.current.url?.(path);
|
|
258
325
|
const base = url ? new URL(url, window.location.href).href : undefined;
|
|
259
326
|
revisionRef.current = result.revision;
|
|
260
327
|
setHtmlDoc(previous => {
|
|
261
|
-
if (result.revision && previous && typeof previous === "object" && previous.revision === result.revision) return previous;
|
|
328
|
+
if (result.revision && previous && typeof previous === "object" && previous.revision === result.revision && previous.preparedHtml === preparedHtml) return previous;
|
|
262
329
|
const bridgeToken = frameToken();
|
|
263
|
-
return { srcDoc: bridgeDoc(
|
|
330
|
+
return { srcDoc: bridgeDoc(preparedHtml, { token: bridgeToken, base, allowScripts: true }), token: bridgeToken, revision: result.revision, preparedHtml };
|
|
264
331
|
});
|
|
265
|
-
}
|
|
332
|
+
}).catch((error: unknown) => {
|
|
266
333
|
if (ctl.signal.aborted) return;
|
|
267
334
|
if (backend.fileSync) {
|
|
268
|
-
if ([401, 403, 404].includes((error as { status?: number }).status ?? 0)) {
|
|
335
|
+
if ([401, 403, 404].includes((error as { status?: number }).status ?? 0)) {
|
|
336
|
+
deleteCachedPreview(backend, jobId, path);
|
|
337
|
+
setHtmlDoc(null);
|
|
338
|
+
revisionRef.current = undefined;
|
|
339
|
+
}
|
|
269
340
|
setError(error instanceof Error ? error.message : String(error));
|
|
270
341
|
} else if (error instanceof FileReadLimitError) setHtmlDoc("toobig");
|
|
271
342
|
else setHtmlDoc("fallback");
|
|
272
343
|
}).finally(() => { if (!ctl.signal.aborted) setSyncing(false); });
|
|
273
344
|
return () => ctl.abort();
|
|
274
|
-
}, [htmlBridge, backend, jobId, path, version, reloadKey, attempt, htmlPresentation]);
|
|
345
|
+
}, [htmlBridge, backend, jobId, path, workspaceRoot, mtime, size, version, reloadKey, attempt, htmlPresentation]);
|
|
275
346
|
const activeToken = htmlDoc && typeof htmlDoc === "object" ? htmlDoc.token : token;
|
|
276
347
|
useEffect(() => {
|
|
277
348
|
if (!bridged || !htmlDoc || typeof htmlDoc !== "object") return;
|
|
@@ -297,12 +368,41 @@ function FileViewerInner({ backend, jobId, path, displayName, size, mtime, versi
|
|
|
297
368
|
useEffect(() => { setSel(null); }, [htmlDoc, loaded, mode]);
|
|
298
369
|
const sourceRevision = useCallback((revision: string | undefined) => { revisionRef.current = revision; setSel(null); }, []);
|
|
299
370
|
useEffect(() => {
|
|
371
|
+
let disposed = false;
|
|
300
372
|
const onMessage = (e: MessageEvent) => {
|
|
301
373
|
const frame = frameRef.current;
|
|
302
374
|
const root = rootRef.current;
|
|
303
375
|
const data = e.data as FrameSelMessage | null;
|
|
304
376
|
if (!frame || !root || e.source !== frame.contentWindow || !data || data.cliUiSel !== activeToken) return;
|
|
305
377
|
if (data.ready) { setFrameState("ready"); return; }
|
|
378
|
+
if (typeof data.assetReq === "string" && typeof data.relUrl === "string") {
|
|
379
|
+
const sourceWin = frame.contentWindow;
|
|
380
|
+
const reqId = data.assetReq;
|
|
381
|
+
const relUrl = data.relUrl;
|
|
382
|
+
const target = resolveWorkspaceAssetPath(path, relUrl, workspaceRoot);
|
|
383
|
+
if (!target) {
|
|
384
|
+
sourceWin?.postMessage({ cliUiAsset: activeToken, assetReq: reqId, relUrl, ok: false, error: "路径无效" }, "*");
|
|
385
|
+
return;
|
|
386
|
+
}
|
|
387
|
+
void readWorkspaceAsset(backend, jobId, target).then(
|
|
388
|
+
asset => {
|
|
389
|
+
if (!disposed && sourceWin === frameRef.current?.contentWindow) {
|
|
390
|
+
sourceWin?.postMessage({ cliUiAsset: activeToken, assetReq: reqId, relUrl, ok: true, bytes: asset.bytes, mime: asset.mime }, "*");
|
|
391
|
+
}
|
|
392
|
+
},
|
|
393
|
+
err => {
|
|
394
|
+
if (!disposed && sourceWin === frameRef.current?.contentWindow) {
|
|
395
|
+
sourceWin?.postMessage({ cliUiAsset: activeToken, assetReq: reqId, relUrl, ok: false, error: err instanceof Error ? err.message : String(err) }, "*");
|
|
396
|
+
}
|
|
397
|
+
},
|
|
398
|
+
);
|
|
399
|
+
return;
|
|
400
|
+
}
|
|
401
|
+
if (typeof data.openPath === "string") {
|
|
402
|
+
const target = resolveWorkspaceAssetPath(path, data.openPath, workspaceRoot);
|
|
403
|
+
if (target && openPathRef.current) openPathRef.current(target);
|
|
404
|
+
return;
|
|
405
|
+
}
|
|
306
406
|
if (data.scroll) frameScroll.current = { top: Math.max(0, data.top ?? 0), left: Math.max(0, data.left ?? 0) };
|
|
307
407
|
if (!onQuoteText) return;
|
|
308
408
|
const text = data.scroll ? "" : (data.text ?? "").trim();
|
|
@@ -313,8 +413,8 @@ function FileViewerInner({ backend, jobId, path, displayName, size, mtime, versi
|
|
|
313
413
|
setSel({ text, frame: true, revision: revisionRef.current, x: Math.min(Math.max(8, fr.left - box.left + r.left + r.width / 2), box.width - 8), y: Math.max(40, fr.top - box.top + r.top) });
|
|
314
414
|
};
|
|
315
415
|
window.addEventListener("message", onMessage);
|
|
316
|
-
return () => window.removeEventListener("message", onMessage);
|
|
317
|
-
}, [onQuoteText, activeToken]);
|
|
416
|
+
return () => { disposed = true; window.removeEventListener("message", onMessage); };
|
|
417
|
+
}, [backend, jobId, path, workspaceRoot, onQuoteText, activeToken]);
|
|
318
418
|
useEffect(() => {
|
|
319
419
|
if (!onQuoteText) return;
|
|
320
420
|
const read = () => {
|
|
@@ -404,13 +504,19 @@ function FileViewerInner({ backend, jobId, path, displayName, size, mtime, versi
|
|
|
404
504
|
if (alive) setLoaded({ kind: "docx", html: out.value });
|
|
405
505
|
}).catch((e: unknown) => { if (alive) setError(e instanceof Error ? e.message : String(e)); });
|
|
406
506
|
} else {
|
|
507
|
+
const max = htmlReading || progressiveText || backend.fileSync && kind === "markdown" ? textLimit : TEXT_MAX;
|
|
508
|
+
const cached = getCachedPreview(backend, jobId, path);
|
|
509
|
+
if (attempt === 0 && cached?.kind === "text" && cached.version === version && cached.reloadKey === reloadKey && cached.tail === tail && (cached.textLimit >= max || !cached.loaded.truncated) && cacheMetaMatches(cached, mtime, size)) {
|
|
510
|
+
revisionRef.current = cached.loaded.revision;
|
|
511
|
+
setLoaded(previous => previous?.kind === "text" && previous.revision === cached.loaded.revision && previous.text === cached.loaded.text ? previous : { kind: "text", ...cached.loaded });
|
|
512
|
+
return () => { alive = false; ctl.abort(); };
|
|
513
|
+
}
|
|
407
514
|
// A refresh verifies the immutable revision and reuses matching blocks.
|
|
408
515
|
const key = `${path}|${tail}|${attempt}|${reloadKey??""}`;
|
|
409
516
|
const prev = loadedRef.current?.kind === "text" && textKey.current === key ? loadedRef.current : null;
|
|
410
517
|
textKey.current = key;
|
|
411
518
|
if (!prev) setProgress(0);
|
|
412
519
|
setSyncing(true);
|
|
413
|
-
const max = htmlReading || progressiveText || backend.fileSync && kind === "markdown" ? textLimit : TEXT_MAX;
|
|
414
520
|
const full = () => loadText(backend, jobId, path, { max, tail, preview: true, fresh: attempt > 0, signal: ctl.signal, onBytes: (n) => { if (alive && !prev) setProgress(n); } });
|
|
415
521
|
(prev ? refreshText(backend, jobId, path, prev, max, { signal: ctl.signal, preview: true, fresh: attempt > 0 }).then((r) => r ?? full()) : full()).then(
|
|
416
522
|
(r) => {
|
|
@@ -418,16 +524,21 @@ function FileViewerInner({ backend, jobId, path, displayName, size, mtime, versi
|
|
|
418
524
|
const box = bodyRef.current;
|
|
419
525
|
stick.current = tail || (!!box && box.scrollHeight > box.clientHeight && box.scrollHeight - box.scrollTop - box.clientHeight < 40);
|
|
420
526
|
revisionRef.current = r.revision;
|
|
527
|
+
setCachedPreview(backend, jobId, path, { kind: "text", loaded: r, tail, textLimit: max, size: r.size, mtime, version, reloadKey, chars: r.text.length });
|
|
421
528
|
setLoaded({ kind: "text", ...r });
|
|
422
529
|
},
|
|
423
530
|
(e: unknown) => { if (alive && !ctl.signal.aborted) {
|
|
424
|
-
if ([401, 403, 404].includes((e as { status?: number }).status ?? 0)) {
|
|
531
|
+
if ([401, 403, 404].includes((e as { status?: number }).status ?? 0)) {
|
|
532
|
+
deleteCachedPreview(backend, jobId, path);
|
|
533
|
+
setLoaded(null);
|
|
534
|
+
revisionRef.current = undefined;
|
|
535
|
+
}
|
|
425
536
|
setError(e instanceof Error ? e.message : String(e));
|
|
426
537
|
} },
|
|
427
538
|
).finally(() => { if (alive) setSyncing(false); });
|
|
428
539
|
}
|
|
429
540
|
return () => { alive = false; ctl.abort(); };
|
|
430
|
-
}, [backend, jobId, path, kind, needsSrc, version, reloadKey, tail, attempt, textLimit, htmlReading]); // eslint-disable-line react-hooks/exhaustive-deps
|
|
541
|
+
}, [backend, jobId, path, kind, needsSrc, mtime, size, version, reloadKey, tail, attempt, textLimit, htmlReading]); // eslint-disable-line react-hooks/exhaustive-deps
|
|
431
542
|
useLayoutEffect(() => {
|
|
432
543
|
const box = bodyRef.current;
|
|
433
544
|
if (box && stick.current && loaded?.kind === "text") box.scrollTop = box.scrollHeight;
|
package/src/board/frameQuote.ts
CHANGED
|
@@ -6,14 +6,46 @@
|
|
|
6
6
|
// · 相对路径的样式 / 图片按文件原地址解析(<base>),文档里的 #锚点 在页内滚动(不然会按 <base> 整页跳走)。
|
|
7
7
|
|
|
8
8
|
/** iframe → 宿主:选区(text 为空 = 取消了选择)或滚动了(收起按钮)。 */
|
|
9
|
-
export interface FrameSelMessage {
|
|
9
|
+
export interface FrameSelMessage {
|
|
10
|
+
cliUiSel: string;
|
|
11
|
+
text?: string;
|
|
12
|
+
rect?: { left: number; top: number; width: number } | null;
|
|
13
|
+
scroll?: boolean;
|
|
14
|
+
top?: number;
|
|
15
|
+
left?: number;
|
|
16
|
+
ready?: boolean;
|
|
17
|
+
openPath?: string;
|
|
18
|
+
assetReq?: string;
|
|
19
|
+
relUrl?: string;
|
|
20
|
+
}
|
|
10
21
|
|
|
11
22
|
const randomId = () => Math.random().toString(36).slice(2, 12) + Math.random().toString(36).slice(2, 12);
|
|
12
23
|
|
|
13
24
|
/** 每个预览一个口令 / nonce。 */
|
|
14
25
|
export const frameToken = randomId;
|
|
15
26
|
|
|
16
|
-
function
|
|
27
|
+
function runtimeAssetBridge() {
|
|
28
|
+
return `if(typeof History!=="undefined"&&History.prototype){["replaceState","pushState"].forEach(function(fn){var orig=History.prototype[fn];if(typeof orig==="function")History.prototype[fn]=function(){try{return orig.apply(this,arguments)}catch(e){}}})}
|
|
29
|
+
(function(){function memStore(){var d=Object.create(null);return{get length(){return Object.keys(d).length},key:function(i){return Object.keys(d)[i]||null},getItem:function(k){return Object.prototype.hasOwnProperty.call(d,String(k))?d[String(k)]:null},setItem:function(k,v){d[String(k)]=String(v)},removeItem:function(k){delete d[String(k)]},clear:function(){d=Object.create(null)}}}["localStorage","sessionStorage"].forEach(function(k){try{var st=window[k];if(!st)throw 1;st.getItem("__cli_ui_probe__")}catch(e){try{Object.defineProperty(window,k,{configurable:true,value:memStore()})}catch(e2){}}})})();
|
|
30
|
+
var pending=new Map(),blobs=new Map(),seq=0,ext=/^(?:[a-z][a-z0-9+.-]*:|\\/\\/|#)/i;
|
|
31
|
+
function isRel(u){return typeof u==="string"&&!!u.trim()&&!ext.test(u.trim())}
|
|
32
|
+
function askAsset(u){var k=u.trim();if(blobs.has(k))return blobs.get(k);var p=new Promise(function(res,rej){var id="r"+(++seq);var tm=setTimeout(function(){pending.delete(id);rej(new Error("资源加载超时"))},30000);pending.set(id,{res:res,rej:rej,tm:tm});post({assetReq:id,relUrl:k})});blobs.set(k,p);return p}
|
|
33
|
+
addEventListener("message",function(e){if(e.source!==parent||!e.data||e.data.cliUiAsset!==t)return;var w=pending.get(e.data.assetReq);if(!w)return;pending.delete(e.data.assetReq);clearTimeout(w.tm);if(e.data.ok&&e.data.bytes){var b=new Blob([e.data.bytes],{type:e.data.mime||"application/octet-stream"});w.res({url:URL.createObjectURL(b),bytes:e.data.bytes,mime:e.data.mime||"application/octet-stream"})}else{blobs.delete(e.data.relUrl);w.rej(new Error(e.data.error||"资源不存在"))}});
|
|
34
|
+
function patchNode(n){if(!n||n.nodeType!==1)return false;var tag=n.tagName;
|
|
35
|
+
if(tag==="SCRIPT"){var s=n.getAttribute("src");if(isRel(s)&&!n.dataset.cliBridged){n.dataset.cliBridged="1";n.removeAttribute("src");askAsset(s).then(function(r){var sc=document.createElement("script");sc.dataset.cliBridged="1";if(n.type)sc.type=n.type;sc.src=r.url;sc.onload=function(){n.dispatchEvent(new Event("load"))};sc.onerror=function(){n.dispatchEvent(new Event("error"))};(n.parentNode||document.head).appendChild(sc)},function(){n.dispatchEvent(new Event("error"))});return true}}
|
|
36
|
+
if(tag==="LINK"&&String(n.rel||n.getAttribute("rel")||"").toLowerCase().indexOf("stylesheet")>=0){var h=n.getAttribute("href");if(isRel(h)&&!n.dataset.cliBridged){n.dataset.cliBridged="1";askAsset(h).then(function(r){n.href=r.url;n.dispatchEvent(new Event("load"))},function(){n.dispatchEvent(new Event("error"))});return false}}
|
|
37
|
+
if(tag==="IMG"){var g=n.getAttribute("src");if(isRel(g)&&!n.dataset.cliBridged){n.dataset.cliBridged="1";askAsset(g).then(function(r){n.src=r.url},function(){})}}
|
|
38
|
+
return false}
|
|
39
|
+
var origAppendChild=Node.prototype.appendChild,origInsertBefore=Node.prototype.insertBefore;
|
|
40
|
+
Node.prototype.appendChild=function(c){if(patchNode(c))return c;return origAppendChild.call(this,c)};
|
|
41
|
+
Node.prototype.insertBefore=function(c,r){if(patchNode(c))return c;return origInsertBefore.call(this,c,r)};
|
|
42
|
+
if(typeof MutationObserver!=="undefined"){new MutationObserver(function(ms){for(var i=0;i<ms.length;i++){var m=ms[i];if(m.type==="attributes"&&m.target)patchNode(m.target);else if(m.addedNodes)for(var j=0;j<m.addedNodes.length;j++){var nd=m.addedNodes[j];if(nd.nodeType===1){patchNode(nd);if(nd.querySelectorAll){var imgs=nd.querySelectorAll("img[src],link[href]");for(var k=0;k<imgs.length;k++)patchNode(imgs[k])}}}}}).observe(document.documentElement,{childList:true,subtree:true,attributes:true,attributeFilter:["src"]})}
|
|
43
|
+
if(typeof window.fetch==="function"){var origFetch=window.fetch.bind(window);window.fetch=function(input,init){var u=typeof input==="string"?input:input&&typeof input.url==="string"?input.url:"";if(isRel(u))return askAsset(u).then(function(r){return new Response(r.bytes,{status:200,headers:{"Content-Type":r.mime}})},function(){return new Response("Not Found",{status:404})});return origFetch(input,init)}}
|
|
44
|
+
if(typeof XMLHttpRequest!=="undefined"&&XMLHttpRequest.prototype){var xo=XMLHttpRequest.prototype.open,xs=XMLHttpRequest.prototype.send;XMLHttpRequest.prototype.open=function(m,u,a){this._cliRel=a!==false&&isRel(u)?u:null;return xo.apply(this,arguments)};XMLHttpRequest.prototype.send=function(){if(!this._cliRel)return xs.apply(this,arguments);var x=this,u=this._cliRel;this._cliRel=null;askAsset(u).then(function(r){var txt=new TextDecoder().decode(r.bytes),resp=txt;if(x.responseType==="arraybuffer")resp=r.bytes.buffer;else if(x.responseType==="blob")resp=new Blob([r.bytes],{type:r.mime});else if(x.responseType==="json"){try{resp=JSON.parse(txt)}catch(e){resp=null}}Object.defineProperty(x,"readyState",{configurable:true,value:4});Object.defineProperty(x,"status",{configurable:true,value:200});if(!x.responseType||x.responseType==="text")Object.defineProperty(x,"responseText",{configurable:true,value:txt});Object.defineProperty(x,"response",{configurable:true,value:resp});x.dispatchEvent(new Event("readystatechange"));x.dispatchEvent(new Event("load"));x.dispatchEvent(new Event("loadend"))},function(){Object.defineProperty(x,"readyState",{configurable:true,value:4});Object.defineProperty(x,"status",{configurable:true,value:404});x.dispatchEvent(new Event("readystatechange"));x.dispatchEvent(new Event("error"));x.dispatchEvent(new Event("loadend"))})}}
|
|
45
|
+
document.addEventListener("click",function(e){if(e.defaultPrevented||e.button!==0||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;var a=e.target&&e.target.closest&&e.target.closest("a[href]");if(!a)return;var hr=a.getAttribute("href")||"";if(!isRel(hr))return;var clean=hr.split(/[?#]/)[0]||"";if(/\\.(?:html|htm)$/i.test(clean)){e.preventDefault();post({openPath:clean})}});`;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function bridgeScript(token: string, allowScripts = false) {
|
|
17
49
|
const t = JSON.stringify(token);
|
|
18
50
|
return `(function(){var t=${t};function post(m){m.cliUiSel=t;try{parent.postMessage(m,"*")}catch(e){}}
|
|
19
51
|
function ready(){requestAnimationFrame(function(){requestAnimationFrame(function(){post({ready:true})})})}if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',ready,{once:true});else ready();
|
|
@@ -26,23 +58,25 @@ addEventListener("scroll",function(){post({scroll:true,top:scrollY,left:scrollX}
|
|
|
26
58
|
addEventListener("message",function(e){if(e.source===parent&&e.data&&e.data.cliUiClear===t){var s=getSelection();s&&s.removeAllRanges()}});
|
|
27
59
|
addEventListener("message",function(e){if(e.source===parent&&e.data&&e.data.cliUiRestore===t)scrollTo(Number(e.data.left)||0,Number(e.data.top)||0)});
|
|
28
60
|
document.addEventListener("click",function(e){var a=e.target&&e.target.closest&&e.target.closest('a[href^="#"]');if(!a)return;e.preventDefault();
|
|
29
|
-
var id=decodeURIComponent(a.getAttribute("href").slice(1)),el=id?document.getElementById(id)||document.getElementsByName(id)[0]:document.body;el&&el.scrollIntoView()})
|
|
61
|
+
var id=decodeURIComponent(a.getAttribute("href").slice(1)),el=id?document.getElementById(id)||document.getElementsByName(id)[0]:document.body;el&&el.scrollIntoView()});${allowScripts ? runtimeAssetBridge() : ""}})();`;
|
|
30
62
|
}
|
|
31
63
|
|
|
32
64
|
const escAttr = (s: string) => s.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<");
|
|
33
65
|
|
|
34
66
|
/**
|
|
35
|
-
* 给 HTML
|
|
36
|
-
*
|
|
67
|
+
* 给 HTML 文档插上选区桥:默认仅放行桥脚本(如 Word 转换文档);allowScripts=true 时在无同源权限的沙箱 iframe 内
|
|
68
|
+
* 放行页面自身脚本及工作区依赖(通过 Blob URL / 运行时资源桥加载),仍禁止直连外部网络与表单提交。
|
|
37
69
|
*/
|
|
38
|
-
export function bridgeDoc(html: string, opts: { token: string; base?: string }) {
|
|
70
|
+
export function bridgeDoc(html: string, opts: { token: string; base?: string; allowScripts?: boolean }) {
|
|
39
71
|
let origin = "";
|
|
40
72
|
if (opts.base) { try { origin = new URL(opts.base).origin; } catch { origin = ""; } }
|
|
41
73
|
const src = origin ? `${origin} ` : "";
|
|
42
|
-
const csp =
|
|
74
|
+
const csp = opts.allowScripts
|
|
75
|
+
? `default-src 'none'; script-src 'nonce-${opts.token}' 'unsafe-inline' 'unsafe-eval' blob: data: ${src}; img-src ${src}data: blob:; style-src ${src}blob: data: 'unsafe-inline'; font-src ${src}data: blob:; media-src ${src}data: blob:; connect-src ${src}data: blob:; frame-src ${src}data: blob:; worker-src blob:; form-action 'none'`
|
|
76
|
+
: `default-src 'none'; script-src 'nonce-${opts.token}'; img-src ${src}data: blob:; style-src ${src}'unsafe-inline'; font-src ${src}data:; media-src ${src}data: blob:`;
|
|
43
77
|
const head = `<meta http-equiv="Content-Security-Policy" content="${escAttr(csp)}">`
|
|
44
78
|
+ (opts.base ? `<base href="${escAttr(opts.base)}">` : "")
|
|
45
|
-
+ `<script nonce="${opts.token}">${bridgeScript(opts.token)}</script>`;
|
|
79
|
+
+ `<script nonce="${opts.token}">${bridgeScript(opts.token, opts.allowScripts)}</script>`;
|
|
46
80
|
// 只保留首部完整、常见的 doctype;其他原件内容必须全部位于 CSP 和桥之后。
|
|
47
81
|
// 不搜索原件中的 <head>:它可能在注释 / 脚本字符串中,未闭合标签也会令全文正则反复回溯。
|
|
48
82
|
// 有界首部匹配同时避开带引号的异常 doctype 把策略吞进声明里的情况。
|