dsh-linked-workspace 0.34.1 → 0.35.0
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 +49 -0
- package/docs/API.md +18 -0
- package/docs/VERIFY.md +44 -0
- package/lib/client.js +298 -53
- package/lib/index.js +373 -5
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,54 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.35.0 — 2026-12-03
|
|
4
|
+
|
|
5
|
+
- **The PDF page view lost its title/author row** — it was a preview pretending to be a form, and nothing wrote
|
|
6
|
+
those fields back.
|
|
7
|
+
- **The page counter shows real numbers**: `docPageOf` used single braces while `makeT` fills `{{name}}`, so the
|
|
8
|
+
counter rendered the placeholders; page responses also carry `pageCount` now, and switching a PDF to the page
|
|
9
|
+
view fetches page 1 when nothing was loaded yet (before, the stepper had no total to work with).
|
|
10
|
+
- **PDF, Office pages and the framed viewer zoom**: `−` / `+` / percentage in the toolbar; the frame is widened
|
|
11
|
+
instead of scaled so the browser viewer re-lays out the text, and the frame body scrolls.
|
|
12
|
+
- **An image that fails through the byte route falls back to the JSON read** (`media.read`, base64): the error now
|
|
13
|
+
reports the route status and body instead of repeating "无法预览图片".
|
|
14
|
+
|
|
15
|
+
- **Opening an HTML file no longer crashes the tab**: the HTML preview counted bytes with `Buffer`, a Node
|
|
16
|
+
global that does not exist in the browser, so the first render threw "Buffer is not defined" and the whole
|
|
17
|
+
directory tab went down (and stayed down after a restart, because the tab is restored and re-rendered).
|
|
18
|
+
The count now goes through `TextEncoder`.
|
|
19
|
+
- **A render error stays inside the tab**: both tab types are wrapped in a boundary that explains the failure
|
|
20
|
+
and offers "Retry", instead of letting the exception reach `dsh-better-sidebar`, which then showed its own
|
|
21
|
+
error for the tab and kept re-rendering the broken subtree on every restart.
|
|
22
|
+
- The client bundle is now checked for Node-only globals: `test/client-smoke.mjs` fails if `Buffer` appears in
|
|
23
|
+
it, and asserts the boundary and the byte-count helper are present.
|
|
24
|
+
|
|
25
|
+
- **CSV tables render only the visible window**: a 20k-row sheet no longer becomes 20k DOM rows, and the
|
|
26
|
+
1000-row cap is now 20000 with the note saying so.
|
|
27
|
+
- **Markdown gets an outline**: the document toolbar grows a "Outline" toggle for previews with two or more
|
|
28
|
+
headings; entries jump to their heading.
|
|
29
|
+
- **The local half of a workspace no longer dials the host** before serving bytes: `/fs/…/local/…` reads from
|
|
30
|
+
disk, so a workspace whose machine is unreachable still shows local images and PDFs.
|
|
31
|
+
|
|
32
|
+
- **One type table for every document family**: `.docx`/`.doc`/`.odt`, `.xlsx`/`.xls`/`.ods`, `.pptx`/`.ppt`/`.odp`
|
|
33
|
+
are all "office" now. The legacy binary formats go through LibreOffice for text extraction as well, so `read_doc`
|
|
34
|
+
and the preview no longer refuse them.
|
|
35
|
+
- **A read-only byte route**: `GET /dsh-linked-workspace/fs/linked/<id>/remote/…`, `…/local/…` and
|
|
36
|
+
`/fs/remote/<id>/…` serve files straight from the workspace (Range, `content-length`, `nosniff`,
|
|
37
|
+
`Cache-Control: no-store`, and `Content-Security-Policy: sandbox` for HTML/SVG). Paths are re-encoded per
|
|
38
|
+
segment and escapes are refused.
|
|
39
|
+
- **Images are streamed, not embedded**: the image tab loads through the route, so the 24 MB inline cap and the
|
|
40
|
+
base64 copy are gone and animated GIF/SVG work again.
|
|
41
|
+
- **HTML preview loads the real file**: the iframe now has a `src` (still `sandbox="allow-scripts"`), so relative
|
|
42
|
+
css/js/img resolve. Source editing and `expectedMtime` saving are unchanged.
|
|
43
|
+
- **PDF opens in the browser's viewer** (selection, search, outline, zoom) instead of a page image; the old
|
|
44
|
+
page-by-page view with rotate/delete stays one click away.
|
|
45
|
+
- **Office documents are framed from the converted PDF**: new `docs.officePdf { path }` returns
|
|
46
|
+
`/dsh-linked-workspace/cache/<sha1>.pdf` plus the page count, backed by the existing content-hash cache.
|
|
47
|
+
Machines without LibreOffice fall back to the per-page raster path.
|
|
48
|
+
- **Markdown relative images work**: `docs.mdPreview` rewrites relative `img src` to the byte route, and the
|
|
49
|
+
preview cache key now includes the document path (the same text in two folders renders differently).
|
|
50
|
+
- **Host**: `apiRevision` 17 → 18.
|
|
51
|
+
|
|
3
52
|
## 0.34.1 — 2026-12-02
|
|
4
53
|
|
|
5
54
|
- **Word / Excel / PowerPoint 现在能直接看了**:文档面板不再把 .docx/.xlsx/.pptx 拆成段落、单元格、文字块来编辑,
|
package/docs/API.md
CHANGED
|
@@ -27,6 +27,7 @@ Codes: `BAD_REQUEST`, `NOT_FOUND`, `SSH_CONNECT`, `AUTH_FAILED`,
|
|
|
27
27
|
| `docs.mdPreview` | `{ path, text?, linkedId?, remoteId? }` | `{ kind: 'markdown-preview', html }` (rendered in-process; the fragment carries the KaTeX stylesheet and expects the plugin's `/dsh-linked-workspace/assets/katex/` fonts; the last 3 renders are cached by content hash) or `{ kind: 'markdown-preview-too-large', chars \| bytes, limit }` for a document above 512 Ki characters — the viewer must show the editor instead |
|
|
28
28
|
| `docs.mdPdf` | `{ path, text?, linkedId?, remoteId? }` | `{ kind: "pdf", path, size, mtime }` |
|
|
29
29
|
| `docs.officePage` | `{ path, linkedId?/remoteId?, page }` | `{ kind, engine, pageCount, pages[{ index, png }] }` (docx/xlsx/pptx only: converts to PDF with LibreOffice, caches the PDF per content hash, renders the page as a PNG) |
|
|
30
|
+
| `docs.officePdf` | `{ path, linkedId?/remoteId? }` | `{ kind, engine, path, mtime, size, pageCount, url }` (converts once, caches by content hash, returns `/dsh-linked-workspace/cache/<sha1>.pdf`) |
|
|
30
31
|
|
|
31
32
|
## Records
|
|
32
33
|
|
|
@@ -178,6 +179,23 @@ Under `$DSH_HOME/linked-workspace/`:
|
|
|
178
179
|
- Local linked directories also hold `.local/linked.json` (same binding without
|
|
179
180
|
secrets) and the optional `.remote/` mirror.
|
|
180
181
|
|
|
182
|
+
## HTTP routes
|
|
183
|
+
|
|
184
|
+
Read-only, no JSON envelope, same trust gate as `/api`:
|
|
185
|
+
|
|
186
|
+
| Route | Purpose |
|
|
187
|
+
| --- | --- |
|
|
188
|
+
| `GET /dsh-linked-workspace/fs/linked/<id>/remote/<relative>` | a file under a linked workspace remote root |
|
|
189
|
+
| `GET /dsh-linked-workspace/fs/linked/<id>/local/<relative>` | a file under that workspace local directory |
|
|
190
|
+
| `GET /dsh-linked-workspace/fs/remote/<id>/<relative>` | a file under a remote workspace |
|
|
191
|
+
| `GET /dsh-linked-workspace/fs/local/<absolute segments>` | any absolute local path inside a configured workspace |
|
|
192
|
+
| `GET /dsh-linked-workspace/cache/<sha1>.pdf` | a converted Office document |
|
|
193
|
+
|
|
194
|
+
All of them answer `GET`/`HEAD` only, honour a single-range `Range` request (`206` + `Content-Range`), send
|
|
195
|
+
`Cache-Control: no-store` and `X-Content-Type-Options: nosniff`, and add `Content-Security-Policy: sandbox` for
|
|
196
|
+
`text/html` and `image/svg+xml`. Path segments are decoded individually and any `..`, empty segment, backslash or
|
|
197
|
+
NUL is refused.
|
|
198
|
+
|
|
181
199
|
## Agent tools
|
|
182
200
|
|
|
183
201
|
`linked_workspace` (Host tool, JSON-Schema parameters) actions: `list`, `info`,
|
package/docs/VERIFY.md
CHANGED
|
@@ -1,5 +1,49 @@
|
|
|
1
1
|
# Manual verification checklist
|
|
2
2
|
|
|
3
|
+
## PDF 页码、图片与缩放(未发布)
|
|
4
|
+
|
|
5
|
+
16. 打开一个多页 PDF:默认是浏览器查看器;点「逐页视图」→ 页码应显示 `第 1 / N 页`(N 与真实页数一致),
|
|
6
|
+
工具栏有 `−` `+` 与百分比,点 `+` 页图变大且可横向滚动。
|
|
7
|
+
17. 切回渲染视图后点 `+`:iframe 变宽、文字随之放大,容器可滚动。
|
|
8
|
+
18. PDF 逐页视图里不再出现「标题 / 作者」输入框。
|
|
9
|
+
19. 打开一张 workspace 里的 PNG(几百 KB):正常显示;断网或把主机改坏后再打开同一张,应回退到
|
|
10
|
+
`media.read`(图片仍显示),或在错误里给出路由的 4xx/5xx 与响应文字。
|
|
11
|
+
20. 图片预览:`Ctrl + 滚轮` 缩放,工具栏「适应」「1:1」有效。
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
## HTML 预览与标签页崩溃(未发布)
|
|
15
|
+
|
|
16
|
+
13. 在联动工作区的**本地**目录里放一个 `probe.html`,从本地树点开:应显示渲染后的页面(带样式),
|
|
17
|
+
状态栏显示 `HTML` 与文件大小,控制台没有 `Buffer is not defined`。
|
|
18
|
+
14. 把该文件的样式改坏或塞入非法 JS 后再次打开:最多显示一条错误提示,标签页本身仍可切换、可关闭。
|
|
19
|
+
15. 重启 DSH 后再次打开同一标签页:应正常渲染(错误边界把问题留在标签内,不再需要清状态)。
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
## 阶段 3 与 iframe 真机验证(未发布)
|
|
23
|
+
|
|
24
|
+
9. 打开一个 2 万行的 CSV:首屏立刻出现,滚动到中部/底部时行内容跟着出现(只渲染可视窗口),
|
|
25
|
+
底部提示「仅显示前 20000 行」。
|
|
26
|
+
10. 打开一篇有多级标题的 Markdown:工具栏出现「目录」,点一下弹出浮动目录;点条目跳到对应标题;
|
|
27
|
+
只有一两个标题时不出现该按钮。
|
|
28
|
+
11. 断网或把某个联动工作区的主机改坏,再用本地树打开 `E:\…` 下的图片/PDF:仍应正常显示
|
|
29
|
+
(本地字节不再先拨 SSH)。
|
|
30
|
+
12. 在真实浏览器里打开 PDF 标签:应出现浏览器自带的 PDF 阅读器(可选中文字、搜索),
|
|
31
|
+
而不是空白或「无法加载」的破图。
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
## 只读字节路由与真实渲染(未发布)
|
|
35
|
+
|
|
36
|
+
1. 在联动工作区里放一张 PNG 与一张动图 GIF:在目录栏打开它们 → 图片正常显示、GIF 会动;状态栏不再显示 24 MB 上限相关的报错。
|
|
37
|
+
2. 放一个 `page.html`(引用同目录 `style.css` 与 `img.png`):打开后预览应带上样式与图片;点「编辑」改一行保存,刷新后仍是新内容。
|
|
38
|
+
3. 打开一个 `.pdf`:默认是浏览器查看器(可选中文字、搜索、翻页),点工具栏「逐页视图」切回原来的页图模式(旋转/删页仍可用)。
|
|
39
|
+
4. 打开 `.docx`/`.pptx`/`.xlsx`:默认直接显示 PDF 渲染结果(`‹ 页码 ›` 在「逐页视图」下出现);同一文件再开一次应在 1 秒内出图。
|
|
40
|
+
5. 旧格式:把 `probe.docx` 改名为 `probe.doc` 或复制为 `.odt`,打开后仍应渲染(类型表已含 `.doc/.odt` 等)。
|
|
41
|
+
6. Markdown 里写 ``:预览中图片正常显示(相对路径已重写到字节路由)。
|
|
42
|
+
7. 安全:在浏览器地址栏把路由改成 `…/fs/linked/<id>/remote/../../etc/passwd` → 应返回 400/404,不泄露任何文件;
|
|
43
|
+
对同一路由发 `POST` → 405。
|
|
44
|
+
8. 本地文件:在联动工作区的本地目录里放一张图,用本地标签打开 → 正常显示;把地址改成 `C:\Windows\win.ini` → 400。
|
|
45
|
+
|
|
46
|
+
|
|
3
47
|
## Office 渲染预览与 HTML 编辑(未发布)
|
|
4
48
|
|
|
5
49
|
1. **准备**:本机需装 LibreOffice(`C:\Program Files\LibreOffice\program\soffice.exe`)。没有时打开 Office 文件应显示
|
package/lib/client.js
CHANGED
|
@@ -2200,6 +2200,46 @@ function isInsideRoot(root, target) {
|
|
|
2200
2200
|
return full === base || full.indexOf(base + '/') === 0
|
|
2201
2201
|
}
|
|
2202
2202
|
|
|
2203
|
+
// A render error in this subtree used to escape to dsh-better-sidebar, which
|
|
2204
|
+
// then showed its own error banner for the tab — and re-rendered the same
|
|
2205
|
+
// broken subtree on every restart. Catch it here instead, explain, offer a retry.
|
|
2206
|
+
var TabBoundary = (function () {
|
|
2207
|
+
var Base = React && typeof React.Component === 'function' ? React.Component : null;
|
|
2208
|
+
// Without a Component to extend there is nothing to catch with; fall back
|
|
2209
|
+
// to a pass-through so the tab still renders.
|
|
2210
|
+
if (!Base) return function (props) { return props.children; };
|
|
2211
|
+
|
|
2212
|
+
function Boundary(props) {
|
|
2213
|
+
Base.call(this, props);
|
|
2214
|
+
this.state = { error: null };
|
|
2215
|
+
this.retry = this.retry.bind(this);
|
|
2216
|
+
}
|
|
2217
|
+
|
|
2218
|
+
Boundary.prototype = Object.create(Base.prototype);
|
|
2219
|
+
Boundary.prototype.constructor = Boundary;
|
|
2220
|
+
Boundary.getDerivedStateFromError = function (error) { return { error: error }; };
|
|
2221
|
+
|
|
2222
|
+
Boundary.prototype.componentDidCatch = function (error) {
|
|
2223
|
+
try { console.error('[dsh-linked-workspace] tab render failed', error); } catch (ignored) { /* no console */ }
|
|
2224
|
+
};
|
|
2225
|
+
|
|
2226
|
+
Boundary.prototype.retry = function () {
|
|
2227
|
+
this.setState({ error: null });
|
|
2228
|
+
};
|
|
2229
|
+
|
|
2230
|
+
Boundary.prototype.render = function () {
|
|
2231
|
+
if (!this.state.error) return this.props.children;
|
|
2232
|
+
var t = this.props.t || function (key) { return key; };
|
|
2233
|
+
var detail = this.state.error && this.state.error.message ? this.state.error.message : String(this.state.error);
|
|
2234
|
+
return h('div', { className: 'rw-tab-crash' },
|
|
2235
|
+
h(Banner, { kind: 'error' }, t('tabCrashed')),
|
|
2236
|
+
h('div', { className: 'rw-muted', style: { marginTop: 4 } }, detail),
|
|
2237
|
+
h('button', { type: 'button', className: 'rw-btn', style: { marginTop: 8 }, onClick: this.retry }, IconRefresh(13), t('retry')));
|
|
2238
|
+
};
|
|
2239
|
+
|
|
2240
|
+
return Boundary;
|
|
2241
|
+
})();
|
|
2242
|
+
|
|
2203
2243
|
var TREE_TAB_TYPE = 'dsh-linked-workspace';
|
|
2204
2244
|
// Remote workspaces get their own page kind: the two modes show different
|
|
2205
2245
|
// trees (local ⇄ remote pair vs. a plain remote root), so a session must be
|
|
@@ -2640,7 +2680,7 @@ function isInsideRoot(root, target) {
|
|
|
2640
2680
|
csvTable: '表格',
|
|
2641
2681
|
csvSource: '源码',
|
|
2642
2682
|
csvEmpty: '没有可显示的数据',
|
|
2643
|
-
csvTruncated: '仅显示前
|
|
2683
|
+
csvTruncated: '仅显示前 20000 行(其余请在文本模式查看)',
|
|
2644
2684
|
moveTitle: '移动到…',
|
|
2645
2685
|
moveMessage: '选择「{{name}}」要移动到的目录',
|
|
2646
2686
|
moveMessageMany: '选择这 {{count}} 项要移动到的目录',
|
|
@@ -2833,11 +2873,14 @@ function isInsideRoot(root, target) {
|
|
|
2833
2873
|
docTable: '表格',
|
|
2834
2874
|
docSheet: '工作表',
|
|
2835
2875
|
docSlide: '幻灯片',
|
|
2836
|
-
|
|
2837
|
-
docPdfAuthor: '作者',
|
|
2838
|
-
docPageOf: '第 {page} / {total} 页',
|
|
2876
|
+
docPageOf: '第 {{page}} / {{total}} 页',
|
|
2839
2877
|
docExportDone: '已导出 PDF:{path}',
|
|
2840
2878
|
docRenderEmpty: '这一页没有渲染出内容,点「重新加载」再试一次。',
|
|
2879
|
+
docPageView: '逐页视图',
|
|
2880
|
+
docRenderedView: '渲染视图',
|
|
2881
|
+
outline: '目录',
|
|
2882
|
+
closeOutline: '关闭目录',
|
|
2883
|
+
tabCrashed: '这个标签页渲染时出错了。点「重试」可以重新渲染,或关掉它再从「+」打开。',
|
|
2841
2884
|
docPreviewFailed: '预览失败',
|
|
2842
2885
|
previewTooLarge: '这个文件太大({{chars}} 字符,上限 {{limit}}),没有生成预览;可以在编辑器里查看,或下载后用别的工具打开。',
|
|
2843
2886
|
previewTooLargeBytes: '这个文件太大({{bytes}}),没有生成预览;可以在编辑器里查看,或下载后用别的工具打开。',
|
|
@@ -3265,7 +3308,7 @@ function isInsideRoot(root, target) {
|
|
|
3265
3308
|
csvTable: 'Table',
|
|
3266
3309
|
csvSource: 'Source',
|
|
3267
3310
|
csvEmpty: 'No rows to show',
|
|
3268
|
-
csvTruncated: 'Showing the first
|
|
3311
|
+
csvTruncated: 'Showing the first 20000 rows only (text mode shows the rest)',
|
|
3269
3312
|
moveTitle: 'Move to…',
|
|
3270
3313
|
moveMessage: 'Choose the destination folder for "{{name}}"',
|
|
3271
3314
|
moveMessageMany: 'Choose the destination folder for these {{count}} items',
|
|
@@ -3458,11 +3501,14 @@ function isInsideRoot(root, target) {
|
|
|
3458
3501
|
docTable: 'Table',
|
|
3459
3502
|
docSheet: 'Sheet',
|
|
3460
3503
|
docSlide: 'Slide',
|
|
3461
|
-
|
|
3462
|
-
docPdfAuthor: 'Author',
|
|
3463
|
-
docPageOf: 'Page {page} / {total}',
|
|
3504
|
+
docPageOf: 'Page {{page}} / {{total}}',
|
|
3464
3505
|
docExportDone: 'Exported PDF: {path}',
|
|
3465
3506
|
docRenderEmpty: 'This page rendered empty; try reloading it.',
|
|
3507
|
+
docPageView: 'Page by page',
|
|
3508
|
+
docRenderedView: 'Rendered view',
|
|
3509
|
+
outline: 'Outline',
|
|
3510
|
+
closeOutline: 'Close the outline',
|
|
3511
|
+
tabCrashed: 'This tab failed to render. Retry re-renders it; you can also close it and open it from "+".',
|
|
3466
3512
|
docPreviewFailed: 'Preview failed',
|
|
3467
3513
|
previewTooLarge: 'Too large to preview ({{chars}} characters, the ceiling is {{limit}}). Read it in the editor, or download it and open it elsewhere.',
|
|
3468
3514
|
previewTooLargeBytes: 'Too large to preview ({{bytes}}). Read it in the editor, or download it and open it elsewhere.',
|
|
@@ -3870,7 +3916,7 @@ function isInsideRoot(root, target) {
|
|
|
3870
3916
|
* Host methods the running DSH process does not have yet, the directory
|
|
3871
3917
|
* pane says so instead of surfacing an unrelated error.
|
|
3872
3918
|
*/
|
|
3873
|
-
var HOST_API_REVISION =
|
|
3919
|
+
var HOST_API_REVISION = 18;
|
|
3874
3920
|
var hostInfoProbe = null;
|
|
3875
3921
|
|
|
3876
3922
|
function probeHostInfo() {
|
|
@@ -3943,15 +3989,33 @@ function isInsideRoot(root, target) {
|
|
|
3943
3989
|
return known + (locale === 'zh' ? ':' : ': ') + detail + hint;
|
|
3944
3990
|
}
|
|
3945
3991
|
|
|
3992
|
+
// Points at the Host's read-only byte route. Remote paths are absolute
|
|
3993
|
+
// inside the workspace; local ones are absolute on this machine and the Host
|
|
3994
|
+
// only serves them when they sit inside a configured workspace.
|
|
3995
|
+
function rawFileUrl(scope, local, filePath) {
|
|
3996
|
+
var normalized = String(filePath || '').split('\\').join('/');
|
|
3997
|
+
if (normalized === '') return '';
|
|
3998
|
+
var segments = normalized.split('/').filter(function (part) { return part !== ''; });
|
|
3999
|
+
if (segments.length === 0) return '';
|
|
4000
|
+
var encoded = segments.map(encodeURIComponent).join('/');
|
|
4001
|
+
if (local) return '/dsh-linked-workspace/fs/local/' + encoded;
|
|
4002
|
+
if (!scope || !scope.id) return '';
|
|
4003
|
+
if (scope.kind === 'linked') return '/dsh-linked-workspace/fs/linked/' + encodeURIComponent(scope.id) + '/remote/' + encoded;
|
|
4004
|
+
if (scope.kind === 'remote') return '/dsh-linked-workspace/fs/remote/' + encodeURIComponent(scope.id) + '/' + encoded;
|
|
4005
|
+
return '';
|
|
4006
|
+
}
|
|
4007
|
+
|
|
3946
4008
|
function documentKindOf(path) {
|
|
3947
4009
|
var ext = String(path || '').toLowerCase().match(/\.[^./\\]+$/);
|
|
3948
4010
|
if (!ext) return '';
|
|
3949
4011
|
var value = ext[0];
|
|
3950
4012
|
if (value === '.md' || value === '.markdown') return 'markdown';
|
|
3951
4013
|
if (value === '.pdf') return 'pdf';
|
|
3952
|
-
|
|
3953
|
-
|
|
3954
|
-
if (value === '.
|
|
4014
|
+
// Every office format is converted before it is shown, so the client only
|
|
4015
|
+
// needs to know that it is one: doc/docx/odt, xls/xlsx/ods, ppt/pptx/odp.
|
|
4016
|
+
if (value === '.doc' || value === '.docx' || value === '.odt') return 'office';
|
|
4017
|
+
if (value === '.xls' || value === '.xlsx' || value === '.ods') return 'office';
|
|
4018
|
+
if (value === '.ppt' || value === '.pptx' || value === '.odp') return 'office';
|
|
3955
4019
|
if (value === '.csv' || value === '.tsv') return 'csv';
|
|
3956
4020
|
if (value === '.html' || value === '.htm') return 'html';
|
|
3957
4021
|
if (value === '.png' || value === '.jpg' || value === '.jpeg' || value === '.gif'
|
|
@@ -4051,6 +4115,14 @@ function isInsideRoot(root, target) {
|
|
|
4051
4115
|
return index <= 0 ? '/' : clean.slice(0, index);
|
|
4052
4116
|
}
|
|
4053
4117
|
|
|
4118
|
+
function byteLengthOf(text) {
|
|
4119
|
+
var value = typeof text === 'string' ? text : '';
|
|
4120
|
+
if (typeof TextEncoder === 'function') {
|
|
4121
|
+
try { return new TextEncoder().encode(value).length; } catch (error) { /* fall through */ }
|
|
4122
|
+
}
|
|
4123
|
+
return value.length;
|
|
4124
|
+
}
|
|
4125
|
+
|
|
4054
4126
|
function formatBytes(size) {
|
|
4055
4127
|
var value = Number(size) || 0;
|
|
4056
4128
|
if (value < 1024) return value + ' B';
|
|
@@ -4483,6 +4555,16 @@ function isInsideRoot(root, target) {
|
|
|
4483
4555
|
'.rw-doc-preview img{max-width:100%}',
|
|
4484
4556
|
'.rw-doc-preview blockquote{border-left:3px solid var(--dsw-alias-border-l2);margin:0;padding-left:10px;color:var(--dsw-alias-label-secondary)}',
|
|
4485
4557
|
'.rw-html-source{flex:1 1 auto;min-height:0;resize:none;border:0;border-radius:0;font-family:var(--dsw-alias-font-mono,ui-monospace,SFMono-Regular,Menlo,monospace);font-size:12px;line-height:1.55}',
|
|
4558
|
+
'.rw-tab-crash{padding:14px;display:flex;flex-direction:column;align-items:flex-start}',
|
|
4559
|
+
'.rw-toc{position:absolute;top:8px;right:10px;z-index:3;width:min(240px,62%);max-height:70%;display:flex;flex-direction:column;background:var(--dsw-alias-bg-layer-1);border:1px solid var(--dsw-alias-border-l1);border-radius:8px;box-shadow:0 6px 20px rgba(0,0,0,.18);overflow:hidden}',
|
|
4560
|
+
'.rw-toc-head{display:flex;align-items:center;justify-content:space-between;gap:6px;padding:5px 6px 5px 9px;font-size:11px;color:var(--dsw-alias-label-secondary);border-bottom:1px solid var(--dsw-alias-border-l1)}',
|
|
4561
|
+
'.rw-toc-list{display:flex;flex-direction:column;overflow:auto;padding:3px}',
|
|
4562
|
+
'.rw-toc-item{display:block;width:100%;text-align:left;border:0;background:transparent;color:var(--dsw-alias-label-primary);font:inherit;font-size:11.5px;line-height:16px;padding:3px 5px;border-radius:5px;cursor:pointer;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}',
|
|
4563
|
+
'.rw-toc-item:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(127,127,127,.12))}',
|
|
4564
|
+
'.rw-toc-l1{font-weight:600}',
|
|
4565
|
+
'.rw-toc-l2{padding-left:14px}',
|
|
4566
|
+
'.rw-toc-l3{padding-left:24px;color:var(--dsw-alias-label-secondary)}',
|
|
4567
|
+
'.rw-doc-frame{flex:1 1 auto;width:100%;min-height:0;border:0;background:#fff}',
|
|
4486
4568
|
'.rw-doc-page{display:block;margin:0 auto;max-width:100%;background:#fff;box-shadow:0 1px 3px rgba(0,0,0,.18);border-radius:2px}',
|
|
4487
4569
|
'.rw-doc-pdf-page{display:block;max-width:100%;margin:0 auto 10px;border:1px solid var(--dsw-alias-border-l2);box-shadow:0 2px 10px rgba(0,0,0,.08);background:#fff}',
|
|
4488
4570
|
'.rw-doc-field{display:flex;align-items:center;gap:8px;margin:6px 0}',
|
|
@@ -4603,7 +4685,7 @@ function isInsideRoot(root, target) {
|
|
|
4603
4685
|
'.rw-csv-wrap{flex:1 1 auto;min-height:0;overflow:auto;background:var(--dsw-alias-bg-base)}',
|
|
4604
4686
|
'.rw-csv-table{border-collapse:collapse;font:12px/18px ui-monospace,"Cascadia Code",Consolas,monospace;min-width:100%}',
|
|
4605
4687
|
'.rw-csv-table th{position:sticky;top:0;z-index:1;background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-tertiary);font-weight:600;text-align:left;padding:4px 8px;border:1px solid var(--dsw-alias-border-l1);white-space:nowrap}',
|
|
4606
|
-
'.rw-csv-table td{padding:3px 8px;border:1px solid var(--dsw-alias-border-l1);vertical-align:top;max-width:360px;overflow-wrap:anywhere}',
|
|
4688
|
+
'.rw-csv-table td{height:26px;box-sizing:border-box;padding:3px 8px;border:1px solid var(--dsw-alias-border-l1);vertical-align:top;max-width:360px;overflow-wrap:anywhere}',
|
|
4607
4689
|
'.rw-csv-table tr:nth-child(even) td{background:color-mix(in srgb,var(--dsw-alias-bg-layer-1) 52%,transparent)}',
|
|
4608
4690
|
'.rw-csv-note{padding:5px 9px;font-size:10.5px;color:var(--dsw-alias-label-tertiary);border-top:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-1)}',
|
|
4609
4691
|
'.rw-queue-row{display:flex;align-items:center;gap:8px;padding:5px 0;border-bottom:1px solid var(--dsw-alias-border-l1);font-size:12px}',
|
|
@@ -5787,6 +5869,7 @@ function isInsideRoot(root, target) {
|
|
|
5787
5869
|
var zoom = zoomState[0];
|
|
5788
5870
|
var setZoom = zoomState[1];
|
|
5789
5871
|
var stageRef = useRef(null);
|
|
5872
|
+
var fallbackRef = useRef(false);
|
|
5790
5873
|
var params = scopeParams(scope);
|
|
5791
5874
|
var MIN_ZOOM = 0.05;
|
|
5792
5875
|
var MAX_ZOOM = 8;
|
|
@@ -5813,12 +5896,12 @@ function isInsideRoot(root, target) {
|
|
|
5813
5896
|
}
|
|
5814
5897
|
setNatural(null);
|
|
5815
5898
|
setView({ loading: true, error: null, data: null });
|
|
5816
|
-
var
|
|
5817
|
-
|
|
5818
|
-
setView({ loading: false, error:
|
|
5819
|
-
|
|
5820
|
-
|
|
5821
|
-
});
|
|
5899
|
+
var url = rawFileUrl(scope, local, filePath);
|
|
5900
|
+
if (url === '') {
|
|
5901
|
+
setView({ loading: false, error: new Error(t('noWorkspace')), data: null });
|
|
5902
|
+
return;
|
|
5903
|
+
}
|
|
5904
|
+
setView({ loading: false, error: null, data: { url: url, mime: '' } });
|
|
5822
5905
|
}, [scopeKeyOf(scope), filePath, local]);
|
|
5823
5906
|
|
|
5824
5907
|
useEffect(function () { load(); }, [load]);
|
|
@@ -5826,6 +5909,7 @@ function isInsideRoot(root, target) {
|
|
|
5826
5909
|
useEffect(function () {
|
|
5827
5910
|
setZoom(1);
|
|
5828
5911
|
setNatural(null);
|
|
5912
|
+
fallbackRef.current = false;
|
|
5829
5913
|
}, [filePath]);
|
|
5830
5914
|
|
|
5831
5915
|
useEffect(function () {
|
|
@@ -5898,7 +5982,7 @@ function isInsideRoot(root, target) {
|
|
|
5898
5982
|
h('div', { className: 'rw-image-canvas' },
|
|
5899
5983
|
h('img', {
|
|
5900
5984
|
className: 'rw-image',
|
|
5901
|
-
src:
|
|
5985
|
+
src: data.url,
|
|
5902
5986
|
alt: name,
|
|
5903
5987
|
style: imageStyle,
|
|
5904
5988
|
onLoad: function (event) {
|
|
@@ -5907,8 +5991,33 @@ function isInsideRoot(root, target) {
|
|
|
5907
5991
|
setNatural({ width: image.naturalWidth, height: image.naturalHeight });
|
|
5908
5992
|
}
|
|
5909
5993
|
},
|
|
5910
|
-
onError: function () {
|
|
5911
|
-
|
|
5994
|
+
onError: function (event) {
|
|
5995
|
+
var url = event.currentTarget.currentSrc || data.url;
|
|
5996
|
+
if (fallbackRef.current || local || !scope) {
|
|
5997
|
+
setView({ loading: false, error: new Error(t('imageLoadError')), data: null });
|
|
5998
|
+
return;
|
|
5999
|
+
}
|
|
6000
|
+
fallbackRef.current = true;
|
|
6001
|
+
// Ask the route why, then read the bytes over the JSON channel:
|
|
6002
|
+
// that path never depends on a subresource request succeeding.
|
|
6003
|
+
fetch(url, { credentials: 'same-origin' }).then(function (response) {
|
|
6004
|
+
if (response.ok) return '';
|
|
6005
|
+
return response.text().then(function (body) { return response.status + ' ' + String(body || '').trim().slice(0, 160); });
|
|
6006
|
+
}, function () { return ''; }).then(function (reason) {
|
|
6007
|
+
apiCall('media.read', Object.assign({ path: filePath }, params)).then(function (result) {
|
|
6008
|
+
setView({
|
|
6009
|
+
loading: false,
|
|
6010
|
+
error: null,
|
|
6011
|
+
data: {
|
|
6012
|
+
url: 'data:' + String(result.mime || 'application/octet-stream') + ';base64,' + String(result.base64 || ''),
|
|
6013
|
+
mime: result.mime,
|
|
6014
|
+
size: result.size,
|
|
6015
|
+
},
|
|
6016
|
+
});
|
|
6017
|
+
}, function (error) {
|
|
6018
|
+
setView({ loading: false, error: reason ? new Error(reason) : error, data: null });
|
|
6019
|
+
});
|
|
6020
|
+
});
|
|
5912
6021
|
},
|
|
5913
6022
|
}))),
|
|
5914
6023
|
h('div', { className: 'rw-editor-status' },
|
|
@@ -6011,6 +6120,10 @@ function isInsideRoot(root, target) {
|
|
|
6011
6120
|
h('button', { type: 'button', className: 'rw-btn', onClick: load }, IconRefresh(13), t('retry'))));
|
|
6012
6121
|
}
|
|
6013
6122
|
var data = view.data || {};
|
|
6123
|
+
// A real src lets the page pull its relative css/js/img through the same
|
|
6124
|
+
// read-only route; sandbox still keeps it in an opaque origin away from
|
|
6125
|
+
// the DSH UI.
|
|
6126
|
+
var htmlUrl = rawFileUrl(scope, local, filePath);
|
|
6014
6127
|
var stage = view.editing
|
|
6015
6128
|
? h('textarea', {
|
|
6016
6129
|
className: 'rw-doc-textarea rw-html-source',
|
|
@@ -6030,7 +6143,7 @@ function isInsideRoot(root, target) {
|
|
|
6030
6143
|
// allow-scripts runs the page's own JS (charts need it) inside an
|
|
6031
6144
|
// opaque origin: no access to the DSH UI, its storage or the tree.
|
|
6032
6145
|
sandbox: 'allow-scripts',
|
|
6033
|
-
|
|
6146
|
+
src: htmlUrl,
|
|
6034
6147
|
});
|
|
6035
6148
|
|
|
6036
6149
|
return h('div', { className: 'rw-html-preview' },
|
|
@@ -6040,7 +6153,7 @@ function isInsideRoot(root, target) {
|
|
|
6040
6153
|
h('div', { className: 'rw-html-stage' }, stage),
|
|
6041
6154
|
h('div', { className: 'rw-editor-status' },
|
|
6042
6155
|
h('span', { className: 'rw-status-chip' }, 'HTML'),
|
|
6043
|
-
h('span', { className: 'rw-status-chip' }, formatBytes(
|
|
6156
|
+
h('span', { className: 'rw-status-chip' }, formatBytes(byteLengthOf(view.draft))),
|
|
6044
6157
|
view.dirty ? h('span', { className: 'rw-status-chip rw-status-warn' }, t('dirty')) : null,
|
|
6045
6158
|
h('span', { className: 'rw-fill', style: { flex: '1 1 auto' } }),
|
|
6046
6159
|
h('span', { className: 'rw-status-chip' }, view.editing ? t('docEdit') : t('htmlSandboxed'))));
|
|
@@ -6457,10 +6570,13 @@ function isInsideRoot(root, target) {
|
|
|
6457
6570
|
if (!csvMode) return [];
|
|
6458
6571
|
var text = content.length > 1000000 ? content.slice(0, 1000000) : content;
|
|
6459
6572
|
var delimiter = csvDelimiterOf(filePath, text);
|
|
6460
|
-
return parseDelimited(text, delimiter).slice(0,
|
|
6573
|
+
return parseDelimited(text, delimiter).slice(0, 20000).map(function (row) {
|
|
6461
6574
|
return row.slice(0, 80);
|
|
6462
6575
|
});
|
|
6463
6576
|
}, [content, filePath, csvMode]);
|
|
6577
|
+
var csvWindowRef = useState({ start: 0, count: 60 });
|
|
6578
|
+
var csvWindow = csvWindowRef[0];
|
|
6579
|
+
var setCsvWindow = csvWindowRef[1];
|
|
6464
6580
|
var highlighted = useMemo(function () {
|
|
6465
6581
|
if (!editable) return null;
|
|
6466
6582
|
return highlightNodes(content, language, theme, 180000);
|
|
@@ -6542,22 +6658,49 @@ function isInsideRoot(root, target) {
|
|
|
6542
6658
|
var canView = Boolean(load.file && !load.file.binary && !load.file.tooLarge);
|
|
6543
6659
|
var csvColumnCount = 0;
|
|
6544
6660
|
csvRows.forEach(function (row) { if (row.length > csvColumnCount) csvColumnCount = row.length; });
|
|
6661
|
+
var CSV_ROW_PX = 26;
|
|
6662
|
+
var csvBodyRows = csvRows.length > 0 ? csvRows.slice(1) : [];
|
|
6663
|
+
var csvStart = Math.min(csvWindow.start, Math.max(0, csvBodyRows.length - 1));
|
|
6664
|
+
var csvEnd = Math.min(csvBodyRows.length, csvStart + csvWindow.count);
|
|
6665
|
+
var csvSpacer = function (rows) {
|
|
6666
|
+
return rows > 0
|
|
6667
|
+
? h('tr', { key: 'sp' + rows, 'aria-hidden': 'true' }, h('td', {
|
|
6668
|
+
colSpan: Math.max(csvColumnCount, 1),
|
|
6669
|
+
style: { height: rows * CSV_ROW_PX + 'px', padding: 0, border: 0 },
|
|
6670
|
+
}))
|
|
6671
|
+
: null;
|
|
6672
|
+
};
|
|
6545
6673
|
var csvTable = csvRows.length === 0
|
|
6546
6674
|
? h('div', { className: 'rw-editor-message' }, t('csvEmpty'))
|
|
6547
|
-
: h('div', {
|
|
6548
|
-
|
|
6549
|
-
|
|
6550
|
-
|
|
6551
|
-
|
|
6552
|
-
|
|
6553
|
-
|
|
6675
|
+
: h('div', {
|
|
6676
|
+
className: 'rw-csv-wrap',
|
|
6677
|
+
onScroll: function (event) {
|
|
6678
|
+
var node = event.currentTarget;
|
|
6679
|
+
var height = Number(node.clientHeight) || 480;
|
|
6680
|
+
var start = Math.max(0, Math.floor(node.scrollTop / CSV_ROW_PX) - 6);
|
|
6681
|
+
var count = Math.ceil(height / CSV_ROW_PX) + 12;
|
|
6682
|
+
setCsvWindow(function (previous) {
|
|
6683
|
+
return previous.start === start && previous.count === count ? previous : { start: start, count: count };
|
|
6684
|
+
});
|
|
6685
|
+
},
|
|
6686
|
+
},
|
|
6687
|
+
h('table', { className: 'rw-csv-table' },
|
|
6688
|
+
h('thead', null, h('tr', null,
|
|
6689
|
+
Array.from({ length: csvColumnCount }, function (_, index) {
|
|
6690
|
+
return h('th', { key: 'h' + index, title: csvRows[0][index] || '' }, csvRows[0][index] || '');
|
|
6691
|
+
}))),
|
|
6692
|
+
h('tbody', null,
|
|
6693
|
+
csvSpacer(csvStart),
|
|
6694
|
+
csvBodyRows.slice(csvStart, csvEnd).map(function (row, index) {
|
|
6695
|
+
var rowIndex = csvStart + index;
|
|
6554
6696
|
return h('tr', { key: 'r' + rowIndex },
|
|
6555
6697
|
Array.from({ length: csvColumnCount }, function (_, columnIndex) {
|
|
6556
6698
|
var value = row[columnIndex] === undefined ? '' : row[columnIndex];
|
|
6557
6699
|
return h('td', { key: 'c' + columnIndex, title: value }, value);
|
|
6558
6700
|
}));
|
|
6559
|
-
})
|
|
6560
|
-
|
|
6701
|
+
}),
|
|
6702
|
+
csvSpacer(csvBodyRows.length - csvEnd))),
|
|
6703
|
+
csvRows.length >= 20000 ? h('div', { className: 'rw-csv-note' }, t('csvTruncated')) : null);
|
|
6561
6704
|
var body = canView
|
|
6562
6705
|
? (csvMode && showCsvTable
|
|
6563
6706
|
? csvTable
|
|
@@ -8107,7 +8250,7 @@ function rememberShowHidden(value) {
|
|
|
8107
8250
|
var kind = documentKindOf(path);
|
|
8108
8251
|
// Word/Excel/PowerPoint are rendered through a PDF: the preview keeps the real
|
|
8109
8252
|
// layout and is read-only, because the PDF cannot be written back as .docx.
|
|
8110
|
-
var officeKind = kind === '
|
|
8253
|
+
var officeKind = kind === 'office';
|
|
8111
8254
|
var viewKey = (local ? 'local' : ((scope && scope.kind ? scope.kind : 'remote') + ':' + ((scope && scope.id) || ''))) + '|' + path;
|
|
8112
8255
|
var rememberedView = recallView(viewKey);
|
|
8113
8256
|
var stateRef = useState({
|
|
@@ -8120,6 +8263,11 @@ function rememberShowHidden(value) {
|
|
|
8120
8263
|
updates: {}, pptxUpdates: {}, rotations: {}, deleted: {}, pdfLoading: false, notice: '', warn: '',
|
|
8121
8264
|
findOpen: false, findQuery: '', findIndex: 0, findReplace: '',
|
|
8122
8265
|
office: null,
|
|
8266
|
+
frameUrl: '',
|
|
8267
|
+
frameMode: 'render',
|
|
8268
|
+
tocOpen: false,
|
|
8269
|
+
toc: [],
|
|
8270
|
+
zoom: 1,
|
|
8123
8271
|
});
|
|
8124
8272
|
var state = stateRef[0];
|
|
8125
8273
|
var setState = stateRef[1];
|
|
@@ -8127,6 +8275,27 @@ function rememberShowHidden(value) {
|
|
|
8127
8275
|
var docBodyRef = useRef(null);
|
|
8128
8276
|
var docPreviewRef = useRef(null);
|
|
8129
8277
|
|
|
8278
|
+
useEffect(function () {
|
|
8279
|
+
var node = docPreviewRef.current;
|
|
8280
|
+
if (!node || !state.html) {
|
|
8281
|
+
if (state.toc.length > 0) patch({ toc: [] });
|
|
8282
|
+
return;
|
|
8283
|
+
}
|
|
8284
|
+
var headings = node.querySelectorAll('h1, h2, h3');
|
|
8285
|
+
var items = [];
|
|
8286
|
+
for (var index = 0; index < headings.length; index += 1) {
|
|
8287
|
+
var element = headings[index];
|
|
8288
|
+
var text = (element.textContent || '').replace(/\s+/g, ' ').trim();
|
|
8289
|
+
if (text === '') continue;
|
|
8290
|
+
var id = 'rw-toc-' + index;
|
|
8291
|
+
element.id = id;
|
|
8292
|
+
items.push({ id: id, level: element.tagName === 'H1' ? 1 : element.tagName === 'H2' ? 2 : 3, text: text });
|
|
8293
|
+
}
|
|
8294
|
+
// A single heading is not an outline; keep the toolbar quiet below two.
|
|
8295
|
+
if (items.length < 2) items = [];
|
|
8296
|
+
patch({ toc: items });
|
|
8297
|
+
}, [state.html]);
|
|
8298
|
+
|
|
8130
8299
|
function patch(next) {
|
|
8131
8300
|
setState(function (previous) { return Object.assign({}, previous, next); });
|
|
8132
8301
|
}
|
|
@@ -8208,16 +8377,30 @@ function rememberShowHidden(value) {
|
|
|
8208
8377
|
|
|
8209
8378
|
function loadOffice(index) {
|
|
8210
8379
|
patch({ loading: true, error: '', notice: '', warn: '' });
|
|
8211
|
-
return apiCall('docs.
|
|
8380
|
+
return apiCall('docs.officePdf', params()).then(function (result) {
|
|
8381
|
+
patch({
|
|
8382
|
+
loading: false,
|
|
8383
|
+
frameUrl: String(result.url || ''),
|
|
8384
|
+
office: { png: '', page: 0, pageCount: Number(result.pageCount) || 0, engine: result.engine || '' },
|
|
8385
|
+
page: 0,
|
|
8386
|
+
});
|
|
8387
|
+
}, function (error) {
|
|
8388
|
+
// No renderer (or a failed conversion): the raster path still works and
|
|
8389
|
+
// the panel keeps telling the user what happened.
|
|
8390
|
+
if (!error || (error.code !== 'NO_RENDERER' && error.code !== 'DOC_UNSUPPORTED')) {
|
|
8391
|
+
patch({ error: messageOf(error, t, locale) });
|
|
8392
|
+
}
|
|
8393
|
+
return apiCall('docs.officePage', params({ page: index })).then(function (result) {
|
|
8212
8394
|
var rendered = (result.pages && result.pages[0]) || {};
|
|
8213
8395
|
patch({
|
|
8214
8396
|
loading: false,
|
|
8215
8397
|
office: { png: rendered.png || '', page: Number(rendered.index) || 0, pageCount: Number(result.pageCount) || 0, engine: result.engine || '' },
|
|
8216
8398
|
page: Number(rendered.index) || 0,
|
|
8217
8399
|
});
|
|
8218
|
-
|
|
8219
|
-
|
|
8220
|
-
|
|
8400
|
+
}).catch(function (fallbackError) {
|
|
8401
|
+
patch({ loading: false, error: messageOf(fallbackError, t, locale) });
|
|
8402
|
+
if (fallbackError && fallbackError.code === 'FS_NOT_FOUND' && typeof props.onMissing === 'function') props.onMissing(path);
|
|
8403
|
+
});
|
|
8221
8404
|
});
|
|
8222
8405
|
}
|
|
8223
8406
|
|
|
@@ -8240,6 +8423,7 @@ function rememberShowHidden(value) {
|
|
|
8240
8423
|
function load() {
|
|
8241
8424
|
if (officeKind) return loadOffice(Number((recallView(viewKey) || {}).page) || 0);
|
|
8242
8425
|
patch({ loading: true, error: '', notice: '', warn: '' });
|
|
8426
|
+
if (kind === 'pdf') patch({ frameUrl: rawFileUrl(scope, local, path) });
|
|
8243
8427
|
apiCall('docs.read', params()).then(function (result) {
|
|
8244
8428
|
var remembered = recallView(viewKey);
|
|
8245
8429
|
patch({
|
|
@@ -8485,7 +8669,8 @@ function rememberShowHidden(value) {
|
|
|
8485
8669
|
}
|
|
8486
8670
|
|
|
8487
8671
|
function goPdfPage(index) {
|
|
8488
|
-
|
|
8672
|
+
var known = Number(state.data.pageCount) || 0;
|
|
8673
|
+
if (index < 0 || (known > 0 && index >= known)) return;
|
|
8489
8674
|
var cached = (state.data.pages || []).filter(function (page) { return page.index === index; })[0];
|
|
8490
8675
|
if (cached) {
|
|
8491
8676
|
patch({ page: index });
|
|
@@ -8495,6 +8680,8 @@ function rememberShowHidden(value) {
|
|
|
8495
8680
|
apiCall('docs.pdfPage', params({ page: index })).then(function (result) {
|
|
8496
8681
|
var pages = (state.data.pages || []).filter(function (page) { return page.index !== result.pages[0].index; }).concat(result.pages);
|
|
8497
8682
|
pages.sort(function (left, right) { return left.index - right.index; });
|
|
8683
|
+
// The first page response also carries the total.
|
|
8684
|
+
if (Number(result.pageCount) > 0) state.data.pageCount = Number(result.pageCount);
|
|
8498
8685
|
patch({ data: Object.assign({}, state.data, { pages: pages }), page: index, pdfLoading: false });
|
|
8499
8686
|
}).catch(function (error) {
|
|
8500
8687
|
patch({ pdfLoading: false, error: messageOf(error, t, locale) });
|
|
@@ -8518,14 +8705,40 @@ function rememberShowHidden(value) {
|
|
|
8518
8705
|
h('span', { className: 'rw-hint', style: { flex: '1 1 auto', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }, title: path }, path),
|
|
8519
8706
|
kind === 'markdown' ? h('button', { type: 'button', className: 'rw-btn rw-btn-sm', onClick: showPreview }, state.preview ? t('docEdit') : t('docPreview')) : null,
|
|
8520
8707
|
kind === 'markdown' ? h('button', { type: 'button', className: 'rw-btn rw-btn-sm', onClick: exportPdf, disabled: state.saving }, IconDownload(12), t('exportPdf')) : null,
|
|
8521
|
-
|
|
8708
|
+
kind === 'pdf' || officeKind
|
|
8709
|
+
? h('button', {
|
|
8710
|
+
type: 'button',
|
|
8711
|
+
className: 'rw-btn rw-btn-sm',
|
|
8712
|
+
onClick: function () {
|
|
8713
|
+
var nextMode = state.frameMode === 'render' ? 'pages' : 'render';
|
|
8714
|
+
patch({ frameMode: nextMode });
|
|
8715
|
+
if (nextMode === 'pages' && kind === 'pdf' && !(state.data && Number(state.data.pageCount) > 0)) goPdfPage(0);
|
|
8716
|
+
},
|
|
8717
|
+
}, state.frameMode === 'render' ? t('docPageView') : t('docRenderedView'))
|
|
8718
|
+
: null,
|
|
8719
|
+
(kind === 'pdf' || officeKind) && state.data
|
|
8720
|
+
? h('div', { className: 'rw-inline' },
|
|
8721
|
+
h('button', { type: 'button', className: 'rw-btn rw-btn-sm', title: t('imageZoomOut'), onClick: function () { patch({ zoom: Math.max(0.5, Math.round(state.zoom / 1.25 * 100) / 100) }); } }, '−'),
|
|
8722
|
+
h('button', { type: 'button', className: 'rw-btn rw-btn-sm', title: t('imageZoomIn'), onClick: function () { patch({ zoom: Math.min(4, Math.round(state.zoom * 1.25 * 100) / 100) }); } }, '+'),
|
|
8723
|
+
h('button', { type: 'button', className: 'rw-btn rw-btn-sm', onClick: function () { patch({ zoom: 1 }); } }, Math.round(state.zoom * 100) + '%'))
|
|
8724
|
+
: null,
|
|
8725
|
+
officeKind && state.office && state.frameMode === 'pages'
|
|
8522
8726
|
? h('div', { className: 'rw-inline' },
|
|
8523
8727
|
h('button', { type: 'button', className: 'rw-btn rw-btn-sm', disabled: state.pdfLoading || state.office.page <= 0, onClick: function () { goOfficePage(state.office.page - 1); } }, '‹'),
|
|
8524
8728
|
h('span', { className: 'rw-hint' }, (state.office.page + 1) + ' / ' + Math.max(state.office.pageCount, 1)),
|
|
8525
8729
|
h('button', { type: 'button', className: 'rw-btn rw-btn-sm', disabled: state.pdfLoading || state.office.page >= state.office.pageCount - 1, onClick: function () { goOfficePage(state.office.page + 1); } }, '›'))
|
|
8526
8730
|
: null,
|
|
8527
|
-
|
|
8528
|
-
? h('button', {
|
|
8731
|
+
kind === 'markdown' && state.preview && state.toc.length > 0
|
|
8732
|
+
? h('button', {
|
|
8733
|
+
type: 'button',
|
|
8734
|
+
className: 'rw-chip-btn' + (state.tocOpen ? ' is-on' : ''),
|
|
8735
|
+
title: t('outline'),
|
|
8736
|
+
'aria-pressed': state.tocOpen ? 'true' : 'false',
|
|
8737
|
+
onClick: function () { patch({ tocOpen: !state.tocOpen }); },
|
|
8738
|
+
}, t('outline'))
|
|
8739
|
+
: null,
|
|
8740
|
+
officeKind || kind === 'pdf'
|
|
8741
|
+
? h('button', { type: 'button', className: 'rw-btn rw-btn-sm', onClick: function () { if (officeKind) loadOffice(state.office ? state.office.page : 0); else load(); }, disabled: state.loading || state.pdfLoading }, IconRefresh(13), t('reload'))
|
|
8529
8742
|
: h('button', { type: 'button', className: 'rw-btn rw-btn-sm rw-btn-primary', onClick: save, disabled: state.saving || !state.dirty }, state.saving ? Spinner(12) : IconSave(12), state.saving ? t('saving') : t('save')));
|
|
8530
8743
|
|
|
8531
8744
|
if (state.loading) {
|
|
@@ -8539,12 +8752,36 @@ function rememberShowHidden(value) {
|
|
|
8539
8752
|
}
|
|
8540
8753
|
|
|
8541
8754
|
var body = null;
|
|
8755
|
+
// PDF and Office both arrive as a real PDF over the byte route: the
|
|
8756
|
+
// browser's viewer gives text selection, search and the outline for free.
|
|
8757
|
+
// The per-page raster view stays one click away for the old workflows.
|
|
8758
|
+
var framed = (kind === 'pdf' || officeKind) && state.frameMode === 'render' && state.frameUrl !== '';
|
|
8542
8759
|
if (kind === 'markdown') {
|
|
8543
8760
|
body = state.preview
|
|
8544
8761
|
? h('div', { className: 'rw-doc-body', ref: docBodyRef, onScroll: rememberScroll },
|
|
8545
8762
|
state.previewLoading ? h('div', { className: 'rw-editor-message' }, Spinner(14), t('loading')) : null,
|
|
8546
8763
|
state.html ? h('style', { 'data-rw-katex': '1', dangerouslySetInnerHTML: { __html: state.css || '' } }) : null,
|
|
8547
|
-
state.html ? h('div', { ref: docPreviewRef, className: 'rw-doc-preview', onScroll: rememberScroll, onClick: previewLink, onAuxClick: previewAuxClick, onDragStart: previewDragStart, dangerouslySetInnerHTML: { __html: state.html } }) : null
|
|
8764
|
+
state.html ? h('div', { ref: docPreviewRef, className: 'rw-doc-preview', onScroll: rememberScroll, onClick: previewLink, onAuxClick: previewAuxClick, onDragStart: previewDragStart, dangerouslySetInnerHTML: { __html: state.html } }) : null,
|
|
8765
|
+
state.tocOpen && state.toc.length > 0
|
|
8766
|
+
? h('div', { className: 'rw-toc' },
|
|
8767
|
+
h('div', { className: 'rw-toc-head' },
|
|
8768
|
+
h('span', null, t('outline')),
|
|
8769
|
+
h('button', {
|
|
8770
|
+
type: 'button', className: 'rw-icon-btn', title: t('closeOutline'),
|
|
8771
|
+
onClick: function () { patch({ tocOpen: false }); },
|
|
8772
|
+
}, IconClose(12))),
|
|
8773
|
+
h('div', { className: 'rw-toc-list' }, state.toc.map(function (item) {
|
|
8774
|
+
return h('button', {
|
|
8775
|
+
key: item.id,
|
|
8776
|
+
type: 'button',
|
|
8777
|
+
className: 'rw-toc-item rw-toc-l' + item.level,
|
|
8778
|
+
title: item.text,
|
|
8779
|
+
onClick: function () {
|
|
8780
|
+
var target = document.getElementById(item.id);
|
|
8781
|
+
if (target && typeof target.scrollIntoView === 'function') target.scrollIntoView({ block: 'start', behavior: 'smooth' });
|
|
8782
|
+
},
|
|
8783
|
+
}, item.text);
|
|
8784
|
+
}))) : null)
|
|
8548
8785
|
: h('div', { className: 'rw-doc-body', ref: docBodyRef, onScroll: rememberScroll },
|
|
8549
8786
|
state.findOpen ? h('div', { className: 'rw-find-bar rw-doc-find' },
|
|
8550
8787
|
h('input', {
|
|
@@ -8593,11 +8830,6 @@ function rememberShowHidden(value) {
|
|
|
8593
8830
|
var total = state.data.pageCount || 0;
|
|
8594
8831
|
var current = (state.data.pages || []).filter(function (page) { return page.index === state.page; })[0] || null;
|
|
8595
8832
|
body = h('div', { className: 'rw-doc-body' },
|
|
8596
|
-
h('div', { className: 'rw-doc-field' },
|
|
8597
|
-
h('label', null, t('docPdfTitle')),
|
|
8598
|
-
h('input', { className: 'rw-doc-input', style: { flex: '1 1 auto' }, value: (state.data.metadata && state.data.metadata.title) || '', onChange: function (event) { patch({ data: Object.assign({}, state.data, { metadata: Object.assign({}, state.data.metadata, { title: event.currentTarget.value }) }), dirty: true }); } }),
|
|
8599
|
-
h('label', null, t('docPdfAuthor')),
|
|
8600
|
-
h('input', { className: 'rw-doc-input', style: { flex: '1 1 auto' }, value: (state.data.metadata && state.data.metadata.author) || '', onChange: function (event) { patch({ data: Object.assign({}, state.data, { metadata: Object.assign({}, state.data.metadata, { author: event.currentTarget.value }) }), dirty: true }); } })),
|
|
8601
8833
|
h('div', { className: 'rw-inline', style: { justifyContent: 'space-between', margin: '6px 0' } },
|
|
8602
8834
|
h('div', { className: 'rw-inline' },
|
|
8603
8835
|
h('button', { type: 'button', className: 'rw-btn rw-btn-sm', disabled: state.page <= 0, onClick: function () { stepPdfPage(-1); } }, '‹'),
|
|
@@ -8607,14 +8839,25 @@ function rememberShowHidden(value) {
|
|
|
8607
8839
|
h('button', { type: 'button', className: 'rw-btn rw-btn-sm', disabled: !current, onClick: function () { var rotations = Object.assign({}, state.rotations); rotations[state.page] = ((rotations[state.page] || (current && current.rotation) || 0) + 90) % 360; patch({ rotations: rotations, dirty: true }); } }, t('docRotate')),
|
|
8608
8840
|
h('button', { type: 'button', className: 'rw-btn rw-btn-sm rw-btn-danger', disabled: total <= 1, onClick: function () { var deleted = Object.assign({}, state.deleted); deleted[state.page] = true; var next = state.page + 1; while (next < total && deleted[next]) next += 1; if (next >= total) { next = state.page - 1; while (next >= 0 && deleted[next]) next -= 1; } var nextPage = next >= 0 ? next : state.page; patch({ deleted: deleted, dirty: true, page: nextPage }); if (next >= 0 && !((state.data.pages || []).some(function (page) { return page.index === next; }))) goPdfPage(next); } }, t('docDeletePage')))),
|
|
8609
8841
|
state.pdfLoading ? h('div', { className: 'rw-editor-message' }, Spinner(14), t('loading')) : null,
|
|
8610
|
-
current ? h('img', { className: 'rw-doc-pdf-page', src: current.png, style: { transform: 'rotate(' + ((state.rotations[current.index] || current.rotation || 0) % 360) + 'deg)' } }) : null);
|
|
8842
|
+
current ? h('img', { className: 'rw-doc-pdf-page', src: current.png, style: { width: Math.round(state.zoom * 100) + '%', maxWidth: state.zoom <= 1 ? '100%' : 'none', transform: 'rotate(' + ((state.rotations[current.index] || current.rotation || 0) % 360) + 'deg)' } }) : null);
|
|
8843
|
+
} else if (framed) {
|
|
8844
|
+
// A widened frame has to be able to scroll.
|
|
8845
|
+
body = h('div', { className: 'rw-doc-body', style: { padding: 0, overflow: 'auto' } },
|
|
8846
|
+
h('iframe', {
|
|
8847
|
+
className: 'rw-doc-frame',
|
|
8848
|
+
title: basename(path),
|
|
8849
|
+
src: state.frameUrl,
|
|
8850
|
+
// The browser viewer lays out at the frame's width, so widening the
|
|
8851
|
+
// frame is the zoom it understands.
|
|
8852
|
+
style: { width: Math.round(state.zoom * 100) + '%', height: Math.round(state.zoom * 100) + '%', minWidth: '100%', minHeight: '100%' },
|
|
8853
|
+
}));
|
|
8611
8854
|
} else if (officeKind && state.office) {
|
|
8612
8855
|
// A rendered page is the whole point: the layout came out of LibreOffice,
|
|
8613
8856
|
// so nothing here re-flows the document.
|
|
8614
8857
|
body = h('div', { className: 'rw-doc-body', ref: docBodyRef, onScroll: rememberScroll },
|
|
8615
8858
|
state.pdfLoading ? h('div', { className: 'rw-editor-message' }, Spinner(14), t('loading')) : null,
|
|
8616
8859
|
state.office.png
|
|
8617
|
-
? h('img', { className: 'rw-doc-page', alt: basename(path), src: state.office.png })
|
|
8860
|
+
? h('img', { className: 'rw-doc-page', alt: basename(path), src: state.office.png, style: { width: Math.round(state.zoom * 100) + '%', maxWidth: state.zoom <= 1 ? '100%' : 'none' } })
|
|
8618
8861
|
: h('div', { className: 'rw-editor-message' }, t('docRenderEmpty')));
|
|
8619
8862
|
}
|
|
8620
8863
|
|
|
@@ -14839,7 +15082,8 @@ function rememberShowHidden(value) {
|
|
|
14839
15082
|
component: function (props) {
|
|
14840
15083
|
var currentLocale = useLocale(ctx);
|
|
14841
15084
|
var t = useMemo(function () { return makeT(currentLocale); }, [currentLocale]);
|
|
14842
|
-
return h(
|
|
15085
|
+
return h(TabBoundary, { t: t },
|
|
15086
|
+
h(RemoteDirectoryTab, Object.assign({}, props, { ctx: ctx, t: t, locale: currentLocale, variant: 'linked' })));
|
|
14843
15087
|
},
|
|
14844
15088
|
});
|
|
14845
15089
|
if (track !== false) tabDisposers.push(function () { disposeLinkedTab(); });
|
|
@@ -14865,7 +15109,8 @@ function rememberShowHidden(value) {
|
|
|
14865
15109
|
component: function (props) {
|
|
14866
15110
|
var currentLocale = useLocale(ctx);
|
|
14867
15111
|
var t = useMemo(function () { return makeT(currentLocale); }, [currentLocale]);
|
|
14868
|
-
return h(
|
|
15112
|
+
return h(TabBoundary, { t: t },
|
|
15113
|
+
h(RemoteDirectoryTab, Object.assign({}, props, { ctx: ctx, t: t, locale: currentLocale, variant: 'remote' })));
|
|
14869
15114
|
},
|
|
14870
15115
|
});
|
|
14871
15116
|
if (track !== false) tabDisposers.push(function () { disposeRemoteTab(); });
|
package/lib/index.js
CHANGED
|
@@ -42,7 +42,7 @@ export const inject = ['webServer', 'tools', 'systemPrompt', 'workingDirectory']
|
|
|
42
42
|
* is still running an older copy of the Host — refreshing the page only swaps
|
|
43
43
|
* the browser bundle, so the two halves can drift by one restart.
|
|
44
44
|
*/
|
|
45
|
-
const API_REVISION =
|
|
45
|
+
const API_REVISION = 18
|
|
46
46
|
|
|
47
47
|
/** When this copy of the Host was loaded; shown by `meta.info`. */
|
|
48
48
|
const STARTED_AT = new Date().toISOString()
|
|
@@ -172,6 +172,33 @@ const IMAGE_MIME = Object.freeze({
|
|
|
172
172
|
'.avif': 'image/avif',
|
|
173
173
|
'.svg': 'image/svg+xml',
|
|
174
174
|
})
|
|
175
|
+
// Types the read-only byte route may serve. Anything else falls back to
|
|
176
|
+
// application/octet-stream, which the browser downloads rather than renders.
|
|
177
|
+
const RAW_MIME = Object.freeze({
|
|
178
|
+
...IMAGE_MIME,
|
|
179
|
+
'.html': 'text/html; charset=utf-8',
|
|
180
|
+
'.htm': 'text/html; charset=utf-8',
|
|
181
|
+
'.css': 'text/css; charset=utf-8',
|
|
182
|
+
'.js': 'text/javascript; charset=utf-8',
|
|
183
|
+
'.mjs': 'text/javascript; charset=utf-8',
|
|
184
|
+
'.json': 'application/json; charset=utf-8',
|
|
185
|
+
'.jsonl': 'application/x-ndjson; charset=utf-8',
|
|
186
|
+
'.txt': 'text/plain; charset=utf-8',
|
|
187
|
+
'.md': 'text/markdown; charset=utf-8',
|
|
188
|
+
'.markdown': 'text/markdown; charset=utf-8',
|
|
189
|
+
'.csv': 'text/csv; charset=utf-8',
|
|
190
|
+
'.tsv': 'text/tab-separated-values; charset=utf-8',
|
|
191
|
+
'.pdf': 'application/pdf',
|
|
192
|
+
'.wasm': 'application/wasm',
|
|
193
|
+
'.woff': 'font/woff',
|
|
194
|
+
'.woff2': 'font/woff2',
|
|
195
|
+
'.ttf': 'font/ttf',
|
|
196
|
+
'.otf': 'font/otf',
|
|
197
|
+
})
|
|
198
|
+
const RAW_PREFIX = '/dsh-linked-workspace/fs'
|
|
199
|
+
const CACHE_PREFIX = '/dsh-linked-workspace/cache'
|
|
200
|
+
const RAW_CHUNK = 1024 * 1024
|
|
201
|
+
const RAW_CACHE_NAME = /^[0-9a-f]{40}\.pdf$/
|
|
175
202
|
const MAX_NAME_LENGTH = 120
|
|
176
203
|
const CONNECT_TIMEOUT_MS = 20_000
|
|
177
204
|
const OP_TIMEOUT_MS = 60_000
|
|
@@ -2661,8 +2688,14 @@ export function apply(ctx) {
|
|
|
2661
2688
|
const DOC_TOOL = join(dirname(fileURLToPath(import.meta.url)), '..', 'scripts', 'doc_tool.py')
|
|
2662
2689
|
const DOC_KIND_BY_EXT = new Map([
|
|
2663
2690
|
['.md', 'markdown'], ['.markdown', 'markdown'],
|
|
2664
|
-
['.pdf', 'pdf'],
|
|
2691
|
+
['.pdf', 'pdf'],
|
|
2692
|
+
['.doc', 'doc'], ['.docx', 'docx'], ['.odt', 'odt'],
|
|
2693
|
+
['.xls', 'xls'], ['.xlsx', 'xlsx'], ['.ods', 'ods'],
|
|
2694
|
+
['.ppt', 'ppt'], ['.pptx', 'pptx'], ['.odp', 'odp'],
|
|
2665
2695
|
])
|
|
2696
|
+
// Everything below is converted by LibreOffice before it is rendered, so the
|
|
2697
|
+
// panel never has to understand the binary format itself.
|
|
2698
|
+
const OFFICE_KINDS = new Set(['doc', 'docx', 'odt', 'xls', 'xlsx', 'ods', 'ppt', 'pptx', 'odp'])
|
|
2666
2699
|
|
|
2667
2700
|
function docKind(path) {
|
|
2668
2701
|
return DOC_KIND_BY_EXT.get(extname(String(path || '')).toLowerCase()) || ''
|
|
@@ -2838,7 +2871,7 @@ export function apply(ctx) {
|
|
|
2838
2871
|
|
|
2839
2872
|
function assertDocKind(path, expected) {
|
|
2840
2873
|
const kind = docKind(path)
|
|
2841
|
-
if (kind === '') throw new ApiError('DOC_UNSUPPORTED', '仅支持 Markdown、PDF、
|
|
2874
|
+
if (kind === '') throw new ApiError('DOC_UNSUPPORTED', '仅支持 Markdown、PDF 与 Office 文档(doc/docx/odt、xls/xlsx/ods、ppt/pptx/odp)')
|
|
2842
2875
|
if (expected && expected !== kind) throw new ApiError('DOC_UNSUPPORTED', '文件类型与请求不一致')
|
|
2843
2876
|
return kind
|
|
2844
2877
|
}
|
|
@@ -2886,6 +2919,48 @@ async function officePdfFor(bytes, ext) {
|
|
|
2886
2919
|
|
|
2887
2920
|
const officePdfPending = new Map()
|
|
2888
2921
|
|
|
2922
|
+
function rawUrlForRemote(scope, absolute) {
|
|
2923
|
+
const root = scope.root
|
|
2924
|
+
if (typeof absolute !== 'string' || !absolute.startsWith(root + '/')) return ''
|
|
2925
|
+
const relative = absolute.slice(root.length + 1).split('/').map((part) => encodeURIComponent(part)).join('/')
|
|
2926
|
+
return scope.kind === 'linked'
|
|
2927
|
+
? `${RAW_PREFIX}/linked/${encodeURIComponent(scope.id)}/remote/${relative}`
|
|
2928
|
+
: `${RAW_PREFIX}/remote/${encodeURIComponent(scope.id)}/${relative}`
|
|
2929
|
+
}
|
|
2930
|
+
|
|
2931
|
+
function rawUrlForLocal(absolute) {
|
|
2932
|
+
const encoded = absolute.split(/[\\/]+/).filter((part) => part !== '').map((part) => encodeURIComponent(part)).join('/')
|
|
2933
|
+
return `${RAW_PREFIX}/local/${encoded}`
|
|
2934
|
+
}
|
|
2935
|
+
|
|
2936
|
+
// A preview used to show broken images for every relative reference: the HTML is
|
|
2937
|
+
// injected into the host page, so "images/x.png" resolved against the app, not
|
|
2938
|
+
// against the document. Send them through the byte route instead.
|
|
2939
|
+
function rewriteRelativeImages(html, target) {
|
|
2940
|
+
if (typeof html !== 'string' || html.indexOf('<img') < 0) return html
|
|
2941
|
+
const baseDir = target.remote ? posix.dirname(target.path) : dirname(target.path)
|
|
2942
|
+
return html.replace(/(<img\b[^>]*?\bsrc=")([^"]*)(")/gi, (whole, before, src, after) => {
|
|
2943
|
+
if (src === '' || /^(?:[a-z][a-z0-9+.-]*:|\/\/|#)/i.test(src)) return whole
|
|
2944
|
+
let decoded = src
|
|
2945
|
+
try {
|
|
2946
|
+
decoded = decodeURIComponent(src)
|
|
2947
|
+
} catch {
|
|
2948
|
+
/* keep the raw value */
|
|
2949
|
+
}
|
|
2950
|
+
const suffix = decoded.search(/[?#]/)
|
|
2951
|
+
const clean = suffix < 0 ? decoded : decoded.slice(0, suffix)
|
|
2952
|
+
const tail = suffix < 0 ? '' : decoded.slice(suffix)
|
|
2953
|
+
if (clean === '') return whole
|
|
2954
|
+
if (target.remote) {
|
|
2955
|
+
const absolute = posix.resolve(baseDir, clean)
|
|
2956
|
+
const url = rawUrlForRemote(target.scope, absolute)
|
|
2957
|
+
return url === '' ? whole : before + url + tail + after
|
|
2958
|
+
}
|
|
2959
|
+
const absolute = resolve(baseDir, clean)
|
|
2960
|
+
return before + rawUrlForLocal(absolute) + tail + after
|
|
2961
|
+
})
|
|
2962
|
+
}
|
|
2963
|
+
|
|
2889
2964
|
async function docStat(target) {
|
|
2890
2965
|
if (!target.remote) {
|
|
2891
2966
|
try { const info = await fsStat(target.path); return info } catch { return null }
|
|
@@ -3955,6 +4030,37 @@ const GREP_MAX_QUERY = 200
|
|
|
3955
4030
|
return { kind, engine, path: target.path, mtime: current.mtime, ...rendered }
|
|
3956
4031
|
},
|
|
3957
4032
|
|
|
4033
|
+
/**
|
|
4034
|
+
* The Office preview used to arrive as one PNG per page. The converted PDF
|
|
4035
|
+
* is already cached by content hash, so give the browser its URL instead and
|
|
4036
|
+
* let the built-in viewer handle selection, search and zoom.
|
|
4037
|
+
*/
|
|
4038
|
+
async 'docs.officePdf'(params = {}) {
|
|
4039
|
+
const target = await docTarget(params)
|
|
4040
|
+
const kind = assertDocKind(target.path)
|
|
4041
|
+
if (!OFFICE_KINDS.has(kind)) throw new ApiError('BAD_REQUEST', '只有 Office 文档需要转换')
|
|
4042
|
+
if (sofficePath() === '') throw new ApiError('NO_RENDERER', '这台机器上没有 LibreOffice,无法渲染 Office 文档')
|
|
4043
|
+
const current = await readDocBytes(target, target)
|
|
4044
|
+
const pdf = await officePdfFor(current.data, kind)
|
|
4045
|
+
const hash = basename(pdf, '.pdf')
|
|
4046
|
+
let pageCount = 0
|
|
4047
|
+
try {
|
|
4048
|
+
const probe = await runDocTool(['read', '--kind', 'pdf', '--file', pdf, '--page', '0'])
|
|
4049
|
+
pageCount = Number(probe.pageCount) || 0
|
|
4050
|
+
} catch {
|
|
4051
|
+
pageCount = 0
|
|
4052
|
+
}
|
|
4053
|
+
return {
|
|
4054
|
+
kind,
|
|
4055
|
+
engine: 'libreoffice',
|
|
4056
|
+
path: target.path,
|
|
4057
|
+
mtime: current.mtime,
|
|
4058
|
+
size: current.size,
|
|
4059
|
+
pageCount,
|
|
4060
|
+
url: `${CACHE_PREFIX}/${hash}.pdf`,
|
|
4061
|
+
}
|
|
4062
|
+
},
|
|
4063
|
+
|
|
3958
4064
|
async 'docs.pdfPage'(params = {}) {
|
|
3959
4065
|
const target = await docTarget(params)
|
|
3960
4066
|
assertDocKind(target.path, 'pdf')
|
|
@@ -4044,14 +4150,17 @@ const GREP_MAX_QUERY = 200
|
|
|
4044
4150
|
}
|
|
4045
4151
|
// F2: keep the last few previews. The key is the text itself, because the
|
|
4046
4152
|
// caller may send unsaved text, in which case path + mtime would be stale.
|
|
4047
|
-
|
|
4153
|
+
// The path is part of the key: relative images are rewritten against the
|
|
4154
|
+
// document's own directory, so the same text in two folders renders
|
|
4155
|
+
// differently.
|
|
4156
|
+
const cacheKey = createHash('sha1').update(target.path + '\u0000' + text).digest('hex')
|
|
4048
4157
|
const cached = previewCache.get(cacheKey)
|
|
4049
4158
|
if (typeof cached === 'string') {
|
|
4050
4159
|
previewCache.delete(cacheKey)
|
|
4051
4160
|
previewCache.set(cacheKey, cached)
|
|
4052
4161
|
return { kind: 'markdown-preview', html: cached }
|
|
4053
4162
|
}
|
|
4054
|
-
const html = renderMarkdownFragment(text)
|
|
4163
|
+
const html = rewriteRelativeImages(renderMarkdownFragment(text), target)
|
|
4055
4164
|
previewCache.set(cacheKey, html)
|
|
4056
4165
|
while (previewCache.size > PREVIEW_CACHE_LIMIT) {
|
|
4057
4166
|
const oldest = previewCache.keys().next()
|
|
@@ -6346,6 +6455,265 @@ const GREP_MAX_QUERY = 200
|
|
|
6346
6455
|
'dsh-linked-workspace: katex assets',
|
|
6347
6456
|
)
|
|
6348
6457
|
|
|
6458
|
+
// ── read-only bytes ──────────────────────────────────────────────────────
|
|
6459
|
+
// The renderers (images, HTML, PDF, Office PDFs) point the browser at these
|
|
6460
|
+
// URLs instead of shipping base64 through the API: no 24 MB image ceiling, no
|
|
6461
|
+
// 33% base64 tax, and a relative <img>/<link> inside a previewed page resolves
|
|
6462
|
+
// because the URL mirrors the directory tree.
|
|
6463
|
+
function rawMimeOf(filePath) {
|
|
6464
|
+
return RAW_MIME[extname(String(filePath || '')).toLowerCase()] || 'application/octet-stream'
|
|
6465
|
+
}
|
|
6466
|
+
|
|
6467
|
+
function parseRawUrl(url) {
|
|
6468
|
+
const path = String(url || '').split('?')[0]
|
|
6469
|
+
if (!path.startsWith(RAW_PREFIX + '/')) return null
|
|
6470
|
+
let segments
|
|
6471
|
+
try {
|
|
6472
|
+
segments = path.slice(RAW_PREFIX.length + 1).split('/').map((part) => decodeURIComponent(part))
|
|
6473
|
+
} catch {
|
|
6474
|
+
return null
|
|
6475
|
+
}
|
|
6476
|
+
if (segments.some((part) => part === '' || part === '.' || part === '..' || part.includes('\\') || part.includes('\u0000'))) return null
|
|
6477
|
+
if (segments[0] === 'linked' && segments.length >= 4 && (segments[2] === 'remote' || segments[2] === 'local')) {
|
|
6478
|
+
return { kind: 'linked', id: segments[1], side: segments[2], relative: segments.slice(3).join('/') }
|
|
6479
|
+
}
|
|
6480
|
+
if (segments[0] === 'local' && segments.length >= 2) {
|
|
6481
|
+
// Windows drive letters arrive as their own segment ("local/D:/x/y"), so a
|
|
6482
|
+
// leading slash would turn into D:\D:\x; POSIX paths need it back.
|
|
6483
|
+
const rest = segments.slice(1)
|
|
6484
|
+
const drive = /^[A-Za-z]:$/.test(rest[0])
|
|
6485
|
+
return { kind: 'local', side: 'local', absolute: (drive ? '' : '/') + rest.join('/') }
|
|
6486
|
+
}
|
|
6487
|
+
if (segments[0] === 'remote' && segments.length >= 3) {
|
|
6488
|
+
return { kind: 'remote', id: segments[1], side: 'remote', relative: segments.slice(2).join('/') }
|
|
6489
|
+
}
|
|
6490
|
+
return null
|
|
6491
|
+
}
|
|
6492
|
+
|
|
6493
|
+
function parseRange(header, size) {
|
|
6494
|
+
if (typeof header !== 'string' || !header.startsWith('bytes=')) return null
|
|
6495
|
+
const spec = header.slice(6).split(',')[0].trim()
|
|
6496
|
+
const parts = spec.split('-')
|
|
6497
|
+
if (parts.length !== 2) return null
|
|
6498
|
+
let start = parts[0] === '' ? null : Number(parts[0])
|
|
6499
|
+
let end = parts[1] === '' ? null : Number(parts[1])
|
|
6500
|
+
if (start === null && end === null) return null
|
|
6501
|
+
if (start === null) {
|
|
6502
|
+
start = Math.max(0, size - end)
|
|
6503
|
+
end = size - 1
|
|
6504
|
+
} else if (end === null) {
|
|
6505
|
+
end = size - 1
|
|
6506
|
+
}
|
|
6507
|
+
if (!Number.isInteger(start) || !Number.isInteger(end) || start < 0 || start > end || start >= size) return null
|
|
6508
|
+
return { start, end: Math.min(end, size - 1) }
|
|
6509
|
+
}
|
|
6510
|
+
|
|
6511
|
+
async function serveLocalFile(res, req, filePath, size, range) {
|
|
6512
|
+
const info = await fsStat(filePath)
|
|
6513
|
+
if (!info.isFile()) return false
|
|
6514
|
+
const fd = openSync(filePath, 'r')
|
|
6515
|
+
try {
|
|
6516
|
+
let offset = range ? range.start : 0
|
|
6517
|
+
const end = range ? range.end : info.size - 1
|
|
6518
|
+
while (offset <= end) {
|
|
6519
|
+
const want = Math.min(RAW_CHUNK, end - offset + 1)
|
|
6520
|
+
const buffer = Buffer.allocUnsafe(want)
|
|
6521
|
+
const read = readSync(fd, buffer, 0, want, offset)
|
|
6522
|
+
if (read <= 0) break
|
|
6523
|
+
offset += read
|
|
6524
|
+
if (!res.write(buffer.subarray(0, read))) await new Promise((resolve) => res.once('drain', resolve))
|
|
6525
|
+
}
|
|
6526
|
+
res.end()
|
|
6527
|
+
return true
|
|
6528
|
+
} finally {
|
|
6529
|
+
closeSync(fd)
|
|
6530
|
+
}
|
|
6531
|
+
}
|
|
6532
|
+
|
|
6533
|
+
async function serveRemoteFile(res, remote, target, size, range) {
|
|
6534
|
+
let offset = range ? range.start : 0
|
|
6535
|
+
const end = range ? range.end : size - 1
|
|
6536
|
+
while (offset <= end) {
|
|
6537
|
+
const want = Math.min(RAW_CHUNK, end - offset + 1)
|
|
6538
|
+
const read = await remote.readFile(target, { offset, maxBytes: want })
|
|
6539
|
+
const buffer = read && read.data ? read.data : Buffer.alloc(0)
|
|
6540
|
+
if (buffer.length === 0) break
|
|
6541
|
+
offset += buffer.length
|
|
6542
|
+
if (!res.write(buffer)) await new Promise((resolve) => res.once('drain', resolve))
|
|
6543
|
+
}
|
|
6544
|
+
res.end()
|
|
6545
|
+
}
|
|
6546
|
+
|
|
6547
|
+
async function rawFileHandler(req, res) {
|
|
6548
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
6549
|
+
res.writeHead(405, { 'content-type': 'text/plain; charset=utf-8' })
|
|
6550
|
+
res.end('method not allowed')
|
|
6551
|
+
return
|
|
6552
|
+
}
|
|
6553
|
+
const parsed = parseRawUrl(req.url)
|
|
6554
|
+
if (!parsed) {
|
|
6555
|
+
res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' })
|
|
6556
|
+
res.end('not found')
|
|
6557
|
+
return
|
|
6558
|
+
}
|
|
6559
|
+
try {
|
|
6560
|
+
if (parsed.kind === 'local') {
|
|
6561
|
+
const absolute = resolve(parsed.absolute)
|
|
6562
|
+
const owner = linkedStore.list().find((record) => {
|
|
6563
|
+
const root = typeof record.localPath === 'string' ? resolve(record.localPath) : ''
|
|
6564
|
+
return root !== '' && (absolute === root || absolute.startsWith(root + sep))
|
|
6565
|
+
})
|
|
6566
|
+
if (!owner) throw new ApiError('BAD_REQUEST', '本地路径不在任何工作区里')
|
|
6567
|
+
const info = await fsStat(absolute)
|
|
6568
|
+
if (!info.isFile()) throw new ApiError('FS_NOT_DIR', '只能读取文件')
|
|
6569
|
+
const size = Number(info.size) || 0
|
|
6570
|
+
const mime = rawMimeOf(absolute)
|
|
6571
|
+
const range = parseRange(req.headers.range, size)
|
|
6572
|
+
const headers = {
|
|
6573
|
+
'content-type': mime,
|
|
6574
|
+
'content-length': String(range ? range.end - range.start + 1 : size),
|
|
6575
|
+
'accept-ranges': 'bytes',
|
|
6576
|
+
'cache-control': 'no-store',
|
|
6577
|
+
'x-content-type-options': 'nosniff',
|
|
6578
|
+
}
|
|
6579
|
+
if (mime === 'text/html; charset=utf-8' || mime === 'image/svg+xml') headers['content-security-policy'] = 'sandbox'
|
|
6580
|
+
if (range) headers['content-range'] = `bytes ${range.start}-${range.end}/${size}`
|
|
6581
|
+
res.writeHead(range ? 206 : 200, headers)
|
|
6582
|
+
if (req.method === 'HEAD' || size === 0) {
|
|
6583
|
+
res.end()
|
|
6584
|
+
return
|
|
6585
|
+
}
|
|
6586
|
+
await serveLocalFile(res, req, absolute, size, range)
|
|
6587
|
+
return
|
|
6588
|
+
}
|
|
6589
|
+
// The local half of a linked workspace lives on this machine: serve it
|
|
6590
|
+
// straight from disk. Resolving the scope first would dial the SSH host
|
|
6591
|
+
// and fail the whole local tree whenever that host is down.
|
|
6592
|
+
if (parsed.side === 'local') {
|
|
6593
|
+
if (parsed.kind !== 'linked') throw new ApiError('BAD_REQUEST', '这个工作区没有本地目录')
|
|
6594
|
+
const record = linkedStore.get(parsed.id)
|
|
6595
|
+
if (!record) throw new ApiError('NOT_FOUND', '联动工作区不存在')
|
|
6596
|
+
const root = resolve(record.localPath)
|
|
6597
|
+
const localTarget = resolve(root, parsed.relative)
|
|
6598
|
+
if (!isInsideLocal(root, localTarget)) throw new ApiError('BAD_REQUEST', '路径超出该工作区的本地目录')
|
|
6599
|
+
const localInfo = await fsStat(localTarget)
|
|
6600
|
+
if (!localInfo.isFile()) throw new ApiError('FS_NOT_DIR', '只能读取文件')
|
|
6601
|
+
const localSize = Number(localInfo.size) || 0
|
|
6602
|
+
const localMime = rawMimeOf(localTarget)
|
|
6603
|
+
const localRange = parseRange(req.headers.range, localSize)
|
|
6604
|
+
const localHeaders = {
|
|
6605
|
+
'content-type': localMime,
|
|
6606
|
+
'content-length': String(localRange ? localRange.end - localRange.start + 1 : localSize),
|
|
6607
|
+
'accept-ranges': 'bytes',
|
|
6608
|
+
'cache-control': 'no-store',
|
|
6609
|
+
'x-content-type-options': 'nosniff',
|
|
6610
|
+
}
|
|
6611
|
+
if (localMime === 'text/html; charset=utf-8' || localMime === 'image/svg+xml') localHeaders['content-security-policy'] = 'sandbox'
|
|
6612
|
+
if (localRange) localHeaders['content-range'] = `bytes ${localRange.start}-${localRange.end}/${localSize}`
|
|
6613
|
+
res.writeHead(localRange ? 206 : 200, localHeaders)
|
|
6614
|
+
if (req.method === 'HEAD' || localSize === 0) {
|
|
6615
|
+
res.end()
|
|
6616
|
+
return
|
|
6617
|
+
}
|
|
6618
|
+
await serveLocalFile(res, req, localTarget, localSize, localRange)
|
|
6619
|
+
return
|
|
6620
|
+
}
|
|
6621
|
+
const scope = await requireScope(parsed.kind === 'linked' ? { linkedId: parsed.id } : { remoteId: parsed.id })
|
|
6622
|
+
const target = scopeTarget(scope, parsed.relative)
|
|
6623
|
+
const stat = await scope.remote.stat(target)
|
|
6624
|
+
if (stat.type !== 'file') throw new ApiError('FS_NOT_DIR', '只能读取文件')
|
|
6625
|
+
const size = Number(stat.size) || 0
|
|
6626
|
+
const mime = rawMimeOf(target)
|
|
6627
|
+
const range = parseRange(req.headers.range, size)
|
|
6628
|
+
const headers = {
|
|
6629
|
+
'content-type': mime,
|
|
6630
|
+
'content-length': String(range ? range.end - range.start + 1 : size),
|
|
6631
|
+
'accept-ranges': 'bytes',
|
|
6632
|
+
'cache-control': 'no-store',
|
|
6633
|
+
'x-content-type-options': 'nosniff',
|
|
6634
|
+
}
|
|
6635
|
+
if (mime === 'text/html; charset=utf-8' || mime === 'image/svg+xml') headers['content-security-policy'] = 'sandbox'
|
|
6636
|
+
if (range) headers['content-range'] = `bytes ${range.start}-${range.end}/${size}`
|
|
6637
|
+
res.writeHead(range ? 206 : 200, headers)
|
|
6638
|
+
if (req.method === 'HEAD' || size === 0) {
|
|
6639
|
+
res.end()
|
|
6640
|
+
return
|
|
6641
|
+
}
|
|
6642
|
+
await serveRemoteFile(res, scope.remote, target, size, range)
|
|
6643
|
+
} catch (error) {
|
|
6644
|
+
const apiError = asApiError(error)
|
|
6645
|
+
if (!res.headersSent) {
|
|
6646
|
+
res.writeHead(apiError.status, { 'content-type': 'text/plain; charset=utf-8' })
|
|
6647
|
+
res.end(apiError.message)
|
|
6648
|
+
} else {
|
|
6649
|
+
try { res.end() } catch { /* already gone */ }
|
|
6650
|
+
}
|
|
6651
|
+
}
|
|
6652
|
+
}
|
|
6653
|
+
|
|
6654
|
+
// Converted Office PDFs, addressed by the content hash officePdfFor already
|
|
6655
|
+
// uses: the browser's own PDF viewer then handles text selection and search.
|
|
6656
|
+
async function cachePdfHandler(req, res) {
|
|
6657
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
6658
|
+
res.writeHead(405, { 'content-type': 'text/plain; charset=utf-8' })
|
|
6659
|
+
res.end('method not allowed')
|
|
6660
|
+
return
|
|
6661
|
+
}
|
|
6662
|
+
const path = String(req.url || '').split('?')[0]
|
|
6663
|
+
if (!path.startsWith(CACHE_PREFIX + '/')) {
|
|
6664
|
+
res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' })
|
|
6665
|
+
res.end('not found')
|
|
6666
|
+
return
|
|
6667
|
+
}
|
|
6668
|
+
const name = path.slice(CACHE_PREFIX.length + 1)
|
|
6669
|
+
if (!RAW_CACHE_NAME.test(name)) {
|
|
6670
|
+
res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' })
|
|
6671
|
+
res.end('not found')
|
|
6672
|
+
return
|
|
6673
|
+
}
|
|
6674
|
+
const file = join(officeRenderDir(), name)
|
|
6675
|
+
if (!existsSync(file)) {
|
|
6676
|
+
res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' })
|
|
6677
|
+
res.end('expired')
|
|
6678
|
+
return
|
|
6679
|
+
}
|
|
6680
|
+
const info = await fsStat(file)
|
|
6681
|
+
const range = parseRange(req.headers.range, info.size)
|
|
6682
|
+
const headers = {
|
|
6683
|
+
'content-type': 'application/pdf',
|
|
6684
|
+
'content-length': String(range ? range.end - range.start + 1 : info.size),
|
|
6685
|
+
'accept-ranges': 'bytes',
|
|
6686
|
+
'cache-control': 'no-store',
|
|
6687
|
+
}
|
|
6688
|
+
if (range) headers['content-range'] = `bytes ${range.start}-${range.end}/${info.size}`
|
|
6689
|
+
res.writeHead(range ? 206 : 200, headers)
|
|
6690
|
+
if (req.method === 'HEAD') {
|
|
6691
|
+
res.end()
|
|
6692
|
+
return
|
|
6693
|
+
}
|
|
6694
|
+
await serveLocalFile(res, req, file, info.size, range)
|
|
6695
|
+
}
|
|
6696
|
+
|
|
6697
|
+
ctx.effect(
|
|
6698
|
+
() =>
|
|
6699
|
+
ctx.webServer.register({
|
|
6700
|
+
kind: 'prefix',
|
|
6701
|
+
path: RAW_PREFIX,
|
|
6702
|
+
handler: rawFileHandler,
|
|
6703
|
+
}),
|
|
6704
|
+
'dsh-linked-workspace: raw files',
|
|
6705
|
+
)
|
|
6706
|
+
|
|
6707
|
+
ctx.effect(
|
|
6708
|
+
() =>
|
|
6709
|
+
ctx.webServer.register({
|
|
6710
|
+
kind: 'prefix',
|
|
6711
|
+
path: CACHE_PREFIX,
|
|
6712
|
+
handler: cachePdfHandler,
|
|
6713
|
+
}),
|
|
6714
|
+
'dsh-linked-workspace: rendered pdf cache',
|
|
6715
|
+
)
|
|
6716
|
+
|
|
6349
6717
|
ctx.effect(
|
|
6350
6718
|
() => () => {
|
|
6351
6719
|
pool.disposeAll().catch(() => {})
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-linked-workspace",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.35.0",
|
|
4
4
|
"description": "Linked local ⇄ remote workspaces and remote workspaces for DeepSeek Harness: theme-aware split editor, file-type icons, and agent tools that edit remote files directly.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "lib/index.js",
|