@coda-console/resource-manager 0.9.0 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # 资源管理器
2
2
 
3
- Coda 插件:会话旁的文件浏览器。浏览这个会话的工作目录,读文本、图片、音频和视频,把路径交给对话。只读。
3
+ Coda 插件:会话旁的文件浏览器。浏览这个会话的工作目录,读文本、图片、音频、视频和 3D 模型,把路径交给对话。只读。
4
4
 
5
5
  - **Mac**:在会话侧栏里,和对话并排。
6
6
  - **iPhone**:在会话右上角菜单里打开,点文件在资源页里切到预览,系统返回(左上「‹」、左边缘侧滑)回到打开它的那一层。iPad 和 iPhone Duo 用同一套界面,没有单独适配。
@@ -14,6 +14,7 @@ Coda 插件:会话旁的文件浏览器。浏览这个会话的工作目录,
14
14
  - **Mac 的键盘**:点一下目录树或图标视图让它拿到焦点(Tab 也能进来),↑ ↓ 移动选中(图标视图按行列走),列表里 → 展开、← 收起或选中所在的文件夹,图标视图里 ← → 选左右的条目;⌘↓ 同双击(打开、展开、进入);⌘↑ 在图标视图里回上一层,在预览里返回目录树或图标视图;⌘F 聚焦搜索框。搜索框里 ↓ 进结果,Esc 清空;结果里 Esc 回搜索框。不做多选、按字母跳转,Return 和空格也没绑定。读屏的 `aria-activedescendant` 没做(见 `docs/backlog.md`)。
15
15
  - 文本预览(带行号,可跨行选中复制,最多读 1 MiB)。
16
16
  - **图片、音频、视频预览**(`0.9.0`):经 Coda 开放的本机流式服务,边播边取,不分块传、没有大小上限,音视频可拖动进度。图片:PNG、JPEG、GIF、WebP、SVG、AVIF、HEIC、BMP、TIFF;音频:MP3、M4A、AAC、WAV、FLAC、OGG(Opus)、AIFF、CAF;视频:MP4、M4V、MOV、WebM。用系统自带的播放控件;元信息行写目录、大小,音视频加时长。能不能放取决于这台设备的浏览器内核(Mac 和 iPhone 不同),放不了的写「这台设备放不了这种格式」;MKV、AVI 播放器不支持,直接写「这种格式不能预览」,只给大小和修改时间。不缓存,每次都向模块要。刷新不打断播放:文件变了,元信息行写「文件已变化」,点头部「重载」才换。旧版本的 Coda 没有这个服务:图片退回分块读取(最多 8 MiB),音视频不预览。
17
+ - **3D 模型预览**(`0.9.1`):用 [three.js](https://threejs.org/) 在页面里画,字节同样经本机流式服务取。格式:glb、glTF(外部 `.bin` 和贴图按相对路径取)、STL(二进制和 ASCII)、OBJ(按 `mtllib` 找同目录的 `.mtl` 和贴图)、PLY(含顶点色和点云)、3MF。自动取景,单指转、双指缩放平移(Mac 拖动和滚轮),「复位视角」回到取景的位置;带环境光,金属材质不发黑。glb、glTF 有动画时自动循环播放第一段,有「播放/暂停」,多于一段时可选播哪一段;只在播放时连续渲染,切到后台、关预览、换文件都会停,系统开了「减弱动态效果」时不自动播放。元信息行写目录、大小、面数(点云写点数)和动画段数。glTF、OBJ、STL、PLY 内容是文本时,头部有「3D / 文本」切换,文本走普通的文本预览(二进制的没有切换)。超过 64 MiB 的模型先问「仍然加载」。用了 Draco、meshopt、KTX2 压缩的 glTF 不能预览;这台设备没有 WebGL 时写「这台设备不能显示 3D 模型」。文件变了不打断,元信息行写「文件已变化」,点头部「重载」才换。解析在主线程,很大的模型打开时页面会卡一下。
17
18
  - 代码按语言上色:三十多种常见语言,只按文件名和扩展名认,不猜内容,深浅各一套配色;认不出的显示纯文本。超过 128 KiB 的文件不上色,说明区注明「不高亮」。用的是近似的语法规则,不是语法检查,个别文件会认错(如 `.h` 一律按 C++,`.m` 一律按 Objective-C),不保证完整支持。
18
19
  - Agent 一轮结束后,已展开的目录和正在看的文件自动更新。
19
20
  - 每行带修改日期和大小:Mac 在名字右边(按日期排序时显示日期,否则显示大小,侧栏很窄时隐藏),iPhone 在名字下面一行。右键或长按的菜单里有大小和完整修改时间。文件夹不显示大小(列表和菜单都没有),只有修改日期。
@@ -42,7 +43,7 @@ Coda 插件:会话旁的文件浏览器。浏览这个会话的工作目录,
42
43
 
43
44
  ## 开发
44
45
 
45
- 不需要安装依赖,也没有构建步骤;第三方代码只有 `view/vendor/highlight/` 下原样复制的 highlight.js(升级方法见三期设计第 15.2 节)。Node 由 Coda 提供(`$CODA_NODE`)。
46
+ 不需要安装依赖,也没有构建步骤;第三方代码只有 `view/vendor/` 下原样复制的 highlight.js 和 three.js(升级方法见三期设计第 15.2、21.2 节;three 用 `node scripts/vendor-three.mjs [版本]` 重新生成)。Node 由 Coda 提供(`$CODA_NODE`)。
46
47
 
47
48
  ```sh
48
49
  # 测试,也可以用 npm test。Node 24 上不能写成 node --test test/
@@ -88,3 +89,5 @@ npx --yes github:coda-console/coda-plugins#<提交> . --manifest
88
89
  MIT。
89
90
 
90
91
  第三方:`view/vendor/highlight/` 里是 [highlight.js](https://highlightjs.org/) 11.12.0 的浏览器构建,BSD-3-Clause 许可,版权声明和许可全文在同目录的 `LICENSE`,文件原样复制,没有修改。
92
+
93
+ `view/vendor/three/` 里是 [three.js](https://threejs.org/) 0.187.0 的构建和几个示例模块(加载器、轨道控制、房间环境、fflate),MIT 许可,版权声明和许可全文在同目录的 `LICENSE`。内容原样复制,只做两处机械改动:文件后缀 `.js` 改成 `.mjs`(含文件之间的相对导入),裸导入 `'three'` 改成相对路径;不压缩、不打包。
package/lib/media.mjs CHANGED
@@ -1,14 +1,16 @@
1
- // 音视频和图片的本机流式服务(设计见 docs/design/phase-3.md 第 20 节):页面的 <audio>、<video>、<img> 指向 coda-view://service/media/<口令>/<相对路径>。
1
+ // 音视频、图片和 3D 模型的本机流式服务(设计见 docs/design/phase-3.md 第 20、21 节):页面的 <audio>、<video>、<img> 指向 coda-view://service/media/<口令>/<相对路径>,3D 查看器用 fetch 取字节。
2
2
  // 口令由主模块按视图发,映射到那个视图当时的根目录;根目录变了、换会话、视图关了就作废。只接 GET、HEAD,只读文件,路径校验同 READ。
3
3
  import { randomUUID } from 'node:crypto';
4
4
  import { constants } from 'node:fs';
5
5
  import { open } from 'node:fs/promises';
6
6
  import { pipeline } from 'node:stream/promises';
7
- import { ErrorCode, mediaOf } from '../view/protocol.mjs';
7
+ import { ErrorCode, servedType } from '../view/protocol.mjs';
8
8
  import { fromFsError, resolveInRoot } from './paths.mjs';
9
9
 
10
10
  const NOFOLLOW = constants.O_NOFOLLOW ?? 0;
11
11
 
12
+ const CORS = { 'access-control-allow-origin': '*', 'access-control-expose-headers': 'content-length, content-range, etag' };
13
+
12
14
  const STATUS = {
13
15
  [ErrorCode.INVALID_PATH]: 400, [ErrorCode.OUTSIDE_ROOT]: 403, [ErrorCode.DENIED]: 403,
14
16
  [ErrorCode.NOT_FOUND]: 404, [ErrorCode.NOT_DIR]: 404, [ErrorCode.NOT_FILE]: 404,
@@ -36,15 +38,16 @@ export function createMedia() {
36
38
  const revoke = token => { if (token) grants.delete(token); };
37
39
 
38
40
  async function handler(req, res) {
39
- const end = status => { res.writeHead(status, { 'content-type': 'text/plain; charset=utf-8' }); res.end(); };
41
+ const end = status => { res.writeHead(status, { 'content-type': 'text/plain; charset=utf-8', ...CORS }); res.end(); };
42
+ if (req.method === 'OPTIONS') { res.writeHead(204, { ...CORS, 'access-control-allow-methods': 'GET, HEAD', 'access-control-allow-headers': 'range, if-none-match, if-range' }); return res.end(); }
40
43
  if (req.method !== 'GET' && req.method !== 'HEAD') return end(405);
41
44
  const [, token, ...rest] = new URL(req.url, 'http://x').pathname.split('/');
42
45
  const root = grants.get(token);
43
46
  if (root === undefined) return end(404);
44
47
  let path;
45
48
  try { path = rest.map(decodeURIComponent).join('/'); } catch { return end(400); }
46
- const media = mediaOf(path);
47
- if (!media?.preview) return end(415);
49
+ const type = servedType(path);
50
+ if (!type) return end(415);
48
51
  let handle;
49
52
  try {
50
53
  handle = await open(await resolveInRoot(root, path), constants.O_RDONLY | NOFOLLOW);
@@ -53,14 +56,15 @@ export function createMedia() {
53
56
  const { size } = info;
54
57
  // 不缓存:每次都问(no-cache);内容没变回 304,续传带的 If-Range 对不上就整份重来。
55
58
  const etag = `"${size}-${Math.floor(info.mtimeMs)}"`;
56
- const headers = { 'content-type': media.type, 'accept-ranges': 'bytes', etag, 'cache-control': 'no-cache' };
59
+ // 跨源头:3D 模型页面用 fetch 取字节、WebGL 贴图要带 crossOrigin 的 <img>,都需要。口令本身就是授权,所以放开来源。
60
+ const headers = { 'content-type': type, 'accept-ranges': 'bytes', etag, 'cache-control': 'no-cache', ...CORS };
57
61
  if (String(req.headers['if-none-match'] ?? '').split(',').some(tag => tag.trim().replace(/^W\//, '') === etag)) {
58
- res.writeHead(304, { etag, 'cache-control': 'no-cache' });
62
+ res.writeHead(304, { etag, 'cache-control': 'no-cache', ...CORS });
59
63
  return res.end();
60
64
  }
61
65
  const ifRange = req.headers['if-range'];
62
66
  const range = ifRange && ifRange !== etag ? null : parseRange(req.headers.range, size);
63
- if (range === 'bad') { res.writeHead(416, { 'content-range': `bytes */${size}` }); return res.end(); }
67
+ if (range === 'bad') { res.writeHead(416, { 'content-range': `bytes */${size}`, ...CORS }); return res.end(); }
64
68
  const [status, start, last] = range ? [206, range.start, range.end] : [200, 0, size - 1];
65
69
  if (range) headers['content-range'] = `bytes ${start}-${last}/${size}`;
66
70
  headers['content-length'] = String(size === 0 ? 0 : last - start + 1);
package/package.json CHANGED
@@ -2,8 +2,8 @@
2
2
  "id": "resource-manager",
3
3
  "name": "@coda-console/resource-manager",
4
4
  "displayName": "资源管理器",
5
- "description": "会话旁的只读文件浏览器:浏览会话工作目录,预览文本、图片、音频和视频,把路径交给对话。",
6
- "version": "0.9.0",
5
+ "description": "会话旁的只读文件浏览器:浏览会话工作目录,预览文本、图片、音频、视频和 3D 模型,把路径交给对话。",
6
+ "version": "0.9.1",
7
7
  "categories": ["工作流程"],
8
8
  "license": "MIT",
9
9
  "repository": {
@@ -0,0 +1,85 @@
1
+ // 3D 模型预览里不碰 DOM、不碰 three 的部分(设计见 docs/design/phase-3.md 第 21 节):服务地址、glTF 的头和压缩扩展检查、obj 的 mtllib、相对路径、文本切换的条件、动画的播放状态。Node 里能直接测。
2
+ import { ContentKind } from './protocol.mjs';
3
+
4
+ export const BIG_FILE = 64 * 1024 * 1024; // 超过这个大小先问一声再读(整份读进内存,iPhone 上可能直接崩掉页面)
5
+ export const Z_UP = new Set(['stl', 'ply', '3mf']); // 这几种格式多半是 Z 轴朝上,转成 three.js 的 Y 轴朝上
6
+
7
+ // 这三种压缩 three 自带的 GLTFLoader 不能直接解(要另外的解码器和 wasm),不带,提示不能预览。
8
+ export const UNSUPPORTED_GLTF = ['KHR_draco_mesh_compression', 'EXT_meshopt_compression', 'KHR_texture_basisu'];
9
+
10
+ const encodePath = path => path.split('/').map(encodeURIComponent).join('/');
11
+ // 流式服务里文件的地址;v 只用来在文件变了之后换地址。
12
+ export const serviceUrl = (token, path, version = '') => `coda-view://service/media/${token}/${encodePath(path)}${version ? `?v=${version}` : ''}`;
13
+ // 一个文件所在目录的地址,带结尾的斜杠:gltf 的 .bin、贴图和 obj 的 .mtl 按相对路径接在它后面。
14
+ export const directoryUrl = (token, path) => {
15
+ const dir = path.includes('/') ? path.slice(0, path.lastIndexOf('/')) : '';
16
+ return `coda-view://service/media/${token}/${dir ? `${encodePath(dir)}/` : ''}`;
17
+ };
18
+ export const extensionOf = path => (path.includes('.') ? path.slice(path.lastIndexOf('.') + 1).toLowerCase() : '');
19
+
20
+ // 「3D / 文本」切换:这四种格式既可以是文本也可以是二进制,要读一块看内容;内容是文本(模块按前 8000 字节没有 NUL 判断)才提供。glb、3mf 一定是二进制,不用读。
21
+ const TEXTUAL = new Set(['gltf', 'obj', 'stl', 'ply']);
22
+ export const mayBeText = path => TEXTUAL.has(extensionOf(path));
23
+ export const offersTextView = (path, contentKind) => mayBeText(path) && contentKind === ContentKind.TEXT;
24
+
25
+ // glTF 的 JSON:.gltf 是文本;.glb 是 12 字节头,后面第一块必须是 JSON 块。读不出来抛带原因的错。
26
+ export function gltfJson(bytes, ext) {
27
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
28
+ let text;
29
+ if (ext === 'glb') {
30
+ if (bytes.byteLength < 20 || view.getUint32(0, true) !== 0x46546c67) throw new Error('不是有效的 glb(文件头不是 glTF)');
31
+ const declared = view.getUint32(8, true), length = view.getUint32(12, true), type = view.getUint32(16, true);
32
+ if (declared > bytes.byteLength) throw new Error(`glb 头里写的总长度是 ${declared} 字节,文件只有 ${bytes.byteLength} 字节(文件被截断)`);
33
+ if (type !== 0x4e4f534a) throw new Error('glb 的第一块不是 JSON');
34
+ if (20 + length > bytes.byteLength) throw new Error('glb 的 JSON 块超出文件末尾(文件被截断)');
35
+ text = new TextDecoder().decode(bytes.subarray(20, 20 + length));
36
+ } else text = new TextDecoder().decode(bytes);
37
+ try { return JSON.parse(text); } catch (error) { throw new Error(`glTF 的 JSON 读不出来:${error.message}`); }
38
+ }
39
+
40
+ // extensionsRequired 和 extensionsUsed 里有不支持的压缩,返回它们的名字(可能为空)。
41
+ export function unsupportedExtensions(json) {
42
+ const names = new Set([...(json?.extensionsRequired ?? []), ...(json?.extensionsUsed ?? [])]);
43
+ return UNSUPPORTED_GLTF.filter(name => names.has(name));
44
+ }
45
+
46
+ // obj 里第一行 mtllib 给的材质文件名(可以含空格);没有返回 null。
47
+ export function mtllibOf(text) {
48
+ const match = /^[ \t]*mtllib[ \t]+(.+?)[ \t]*$/m.exec(text);
49
+ return match ? match[1].replaceAll('\\', '/') : null;
50
+ }
51
+
52
+ // 相对路径接在目录后面:合并 ./ 和 ../,不让它跑出根目录(跑出去返回 null)。
53
+ export function joinRelative(dir, rel) {
54
+ const out = dir ? dir.split('/') : [];
55
+ for (const part of rel.split('/')) {
56
+ if (part === '' || part === '.') continue;
57
+ if (part === '..') { if (out.length === 0) return null; out.pop(); } else out.push(part);
58
+ }
59
+ return out.join('/');
60
+ }
61
+
62
+ // PLY 头里 element face 的个数(ASCII 和二进制都适用);没有或读不出头返回 0,按点云处理。
63
+ export function plyFaceCount(bytes) {
64
+ const head = new TextDecoder('latin1').decode(bytes.subarray(0, 65536));
65
+ const end = /^end_header/m.exec(head);
66
+ if (!end) return 0;
67
+ const face = /^element[ \t]+face[ \t]+(\d+)/m.exec(head.slice(0, end.index));
68
+ return face ? Number(face[1]) : 0;
69
+ }
70
+
71
+ // 动画的播放状态:是否在连续渲染(running)只看这里。clips 是动画段数;reducedMotion 为真时不自动播放。
72
+ // 选了一段就从头播;页面不可见时不跑,可见了接着跑(用户没按暂停的话);停止之后不再跑。
73
+ export function createPlayback({ clips, reducedMotion }) {
74
+ const state = { playing: clips > 0 && !reducedMotion, clip: 0, visible: true, stopped: false };
75
+ return {
76
+ get clips() { return clips; },
77
+ get playing() { return state.playing; },
78
+ get clip() { return state.clip; },
79
+ get running() { return clips > 0 && state.playing && state.visible && !state.stopped; },
80
+ toggle() { if (clips > 0) state.playing = !state.playing; },
81
+ select(index) { if (Number.isInteger(index) && index >= 0 && index < clips) { state.clip = index; state.playing = true; } },
82
+ setVisible(visible) { state.visible = visible; },
83
+ stop() { state.stopped = true; },
84
+ };
85
+ }
package/view/preview.mjs CHANGED
@@ -7,6 +7,8 @@ import { icon, iconFor } from './icons.mjs';
7
7
  import { languageOf } from './languages.mjs';
8
8
  import { ContentKind, EntryKind, ErrorCode, IMAGE_LIMIT, TEXT_LIMIT, imageType, mediaOf } from './protocol.mjs';
9
9
  import { clippedSelection, linesOf } from './selection.mjs';
10
+ import { mayBeText, offersTextView } from './model3d.mjs';
11
+ import { mountViewer } from './viewer3d.mjs';
10
12
 
11
13
  function fromBase64(data) {
12
14
  const binary = atob(data), bytes = new Uint8Array(binary.length);
@@ -65,7 +67,8 @@ export const lineCount = text => (text === '' ? 1 : text.split('\n').length - (t
65
67
  // 选区为空、或裁到正文里之后为空时不接管,走系统默认。内容和行号在这里取好,交出去之后和选区无关。
66
68
  // media(path) → Promise<{ token, size, mtimeMs }>(第 20 节):音视频和图片经模块的本机流式服务显示,token 是这个视图的口令;token 为 null 表示宿主没有流式服务。
67
69
  // 不传 media 就一律走分块读取(直接挂载预览的测试用)。
68
- export function mountPreview(el, { read, copy, actions = [], copyInHead = true, back = null, selectionMenu = null, consumed = () => false, media = null }) {
70
+ // 3D 模型(第 21 节):mountModel 挂查看器(默认 viewer3d.mjs,测试可换)。gltf、obj、stl、ply 的内容是文本时头部有「3D / 文本」切换,文本走分块读取。
71
+ export function mountPreview(el, { read, copy, actions = [], copyInHead = true, back = null, selectionMenu = null, consumed = () => false, media = null, mountModel = mountViewer }) {
69
72
  const name = h('div', { class: 'pname truncate' }), meta = h('div', { class: 'pmeta caption secondary truncate' }, ' ');
70
73
  const fileIcon = h('span', { class: 'pico', 'aria-hidden': 'true' });
71
74
  // 图标按钮:可访问名称和 Mac 的悬停提示都是 label;没有图标的退回文字。
@@ -73,10 +76,12 @@ export function mountPreview(el, { read, copy, actions = [], copyInHead = true,
73
76
  const copyPath = () => path !== null && copy(path);
74
77
  const retryButton = h('button', { class: 'link', onclick: () => load(!changed), hidden: true }, '重试');
75
78
  const body = h('div', { class: 'pbody', tabindex: '-1' }); // 可聚焦:关查找条后焦点回正文
79
+ const modes = [['3d', '3D'], ['text', '文本']].map(([value, label]) => ({ value, button: h('button', { class: 'link', onclick: () => setMode(value) }, label) }));
80
+ const modeBar = h('div', { class: 'pmode', role: 'group', 'aria-label': '显示方式', hidden: true }, ...modes.map(({ button }) => button));
76
81
  let gutterEl = null;
77
82
  const find = createFind({ body, gutterWidth: () => gutterEl?.offsetWidth ?? 0 });
78
83
  const extra = actions.map(({ label, icon: glyph, run }) => { const button = action(label, glyph, () => path !== null && run(path, button)); return button; });
79
- el.replaceChildren(h('div', { class: 'phead' }, ...(back ? [action('返回', 'back', back)] : []), fileIcon, h('div', { class: 'grow' }, name, meta), retryButton,
84
+ el.replaceChildren(h('div', { class: 'phead' }, ...(back ? [action('返回', 'back', back)] : []), fileIcon, h('div', { class: 'grow' }, name, meta), modeBar, retryButton,
80
85
  ...(copyInHead ? [action('复制路径', 'copy', copyPath)] : []), ...extra), find.el, body);
81
86
  find.done.addEventListener('click', () => { find.close(); body.focus(); });
82
87
  // 查找条的键盘:Esc 关(从查找条里关,焦点回正文;焦点在正文里,焦点留在正文);⌘G、⇧⌘G 下一个、上一个。输入法组字中的按键不管,菜单消费掉的 Esc 不再处理。
@@ -111,12 +116,24 @@ export function mountPreview(el, { read, copy, actions = [], copyInHead = true,
111
116
  const setMeta = (text, title = '') => { metaText = text; metaTitle = title; stale = null; changed = false; paintMeta(); };
112
117
  const setStale = reason => { stale = reason; paintMeta(); };
113
118
  let player = null; // 正在显示的音视频或图片元素
119
+ let viewer = null; // 正在显示的 3D 模型视图:revoke 释放它,stop 只停加载和动画
120
+ let mode = '3d', offersText = false; // 模型文件现在看 3D 还是文本;内容是文本的才有切换(换文件时都回到初始)
121
+ const paintMode = () => {
122
+ modeBar.hidden = !offersText;
123
+ for (const { value, button } of modes) button.setAttribute('aria-pressed', String(mode === value));
124
+ };
125
+ function setMode(next) {
126
+ if (path === null || mode === next) return;
127
+ mode = next;
128
+ paintMode();
129
+ load(false);
130
+ }
114
131
  const stopMedia = () => {
115
132
  if (!player) return;
116
133
  player.pause?.(); player.removeAttribute('src'); player.load?.();
117
134
  player = null;
118
135
  };
119
- const revoke = () => { stopMedia(); if (objectUrl) URL.revokeObjectURL(objectUrl); objectUrl = null; };
136
+ const revoke = () => { stopMedia(); viewer?.dispose(); viewer = null; if (objectUrl) URL.revokeObjectURL(objectUrl); objectUrl = null; };
120
137
  const notice = (title, detail, action) => body.replaceChildren(h('div', { class: 'empty' },
121
138
  h('p', {}, title), detail ? h('p', { class: 'secondary' }, detail) : null,
122
139
  action ? h('button', { class: 'link', onclick: action.run }, action.label) : null));
@@ -166,7 +183,8 @@ export function mountPreview(el, { read, copy, actions = [], copyInHead = true,
166
183
 
167
184
  function failure(error, silent, retry) {
168
185
  if (error.stale) return;
169
- if (error.code === ErrorCode.NOT_FOUND) { shown = null; textShown = false; find.clearContent(); setMeta(' '); return notice('文件已不存在', path); }
186
+ // 文件没了(后台刷新发现):先释放,正文被换掉后,播放中的音视频和 3D 的画布不能继续占着。
187
+ if (error.code === ErrorCode.NOT_FOUND) { revoke(); shown = null; textShown = false; find.clearContent(); setMeta(' '); return notice('文件已不存在', path); }
170
188
  if (silent && shown) return setStale(error.message); // 后台刷新失败:保留正文,提示原因
171
189
  textShown = false;
172
190
  find.clearContent(); // 整页重读失败:标记清掉,计数写「—」,之后再读成功就重新找
@@ -196,20 +214,36 @@ export function mountPreview(el, { read, copy, actions = [], copyInHead = true,
196
214
  el.src = `coda-view://service/media/${key}/${path.split('/').map(encodeURIComponent).join('/')}?v=${size}-${mtimeMs}`;
197
215
  }
198
216
 
199
- // 媒体文件(按扩展名):返回 true 表示已经处理(显示、提示或已作废),false 表示这个文件走分块读取(宿主没有流式服务时的图片)。
200
- // 刷新不打断播放:音视频变了只在元信息行提示「文件已变化」,点「重载」才换;图片和提示页变了直接换。
217
+ // 3D 模型:查看器自己取字节、解析、渲染(第 21 节)。
218
+ function showModel({ token: key, size, mtimeMs }) {
219
+ revoke();
220
+ textShown = false; find.close(); pendingFind = null;
221
+ shown = { size, mtimeMs };
222
+ const parts = mediaMeta(size), title = `修改于 ${formatTime(mtimeMs)}`;
223
+ setMeta(line(parts), title);
224
+ const mine = viewer = mountModel({ body, token: key, path, size, version: `${size}-${mtimeMs}`, onMeta: extra => { if (viewer === mine) setMetaText(line([...parts, ...extra]), title); } });
225
+ }
226
+
227
+ // 媒体文件(按扩展名):返回 true 表示已经处理(显示、提示或已作废),false 表示这个文件走分块读取(宿主没有流式服务时的图片和模型,模型选了看文本时)。
228
+ // 刷新不打断播放:音视频和模型变了只在元信息行提示「文件已变化」,点「重载」才换;图片和提示页变了直接换。
201
229
  async function loadMedia({ kind, preview }, silent, mark) {
230
+ if (kind === 'model' && mode === 'text') return false;
202
231
  const granted = await media(path);
203
232
  if (!mark()) return true;
204
233
  const { token: key, size, mtimeMs } = granted;
205
- if (key === null && preview && kind === 'image') return false;
234
+ if (key === null && preview && (kind === 'image' || kind === 'model')) return false;
206
235
  if (silent && shown) {
207
236
  if (shown.size === size && shown.mtimeMs === mtimeMs) { changed = false; setStale(null); return true; }
208
- if (player && kind !== 'image') { changed = true; paintMeta(); return true; }
237
+ if ((player && kind !== 'image') || (viewer && kind === 'model')) { changed = true; paintMeta(); return true; }
238
+ }
239
+ if (kind === 'model') { // 内容是不是文本,用模块现有的判断(读第一块);不经查看器,没有 WebGL 的设备上文本模型也能切到文本看
240
+ const first = mayBeText(path) ? await read(path, 0) : null;
241
+ if (!mark()) return true; // 先核对作废,再动共享状态
242
+ offersText = first !== null && offersTextView(path, first.kind);
243
+ paintMode();
209
244
  }
210
245
  const keep = carry?.scroll ?? (silent ? { top: body.scrollTop, left: body.scrollLeft } : { top: 0, left: 0 });
211
- if (preview && key !== null) showMedia(kind, granted);
212
- else {
246
+ if (preview && key !== null) { if (kind === 'model') showModel(granted); else showMedia(kind, granted); } else {
213
247
  revoke();
214
248
  textShown = false; find.close(); pendingFind = null;
215
249
  shown = { size, mtimeMs };
@@ -251,6 +285,7 @@ export function mountPreview(el, { read, copy, actions = [], copyInHead = true,
251
285
  settle(false);
252
286
  if (next !== path) find.close(); // 换了文件就关查找,不靠调用方先 stop()
253
287
  opens++;
288
+ if (next !== path) { mode = '3d'; offersText = false; paintMode(); } // 换了文件:回到 3D,切换等读到内容再决定有没有
254
289
  path = next;
255
290
  const base = next.split('/').pop();
256
291
  name.textContent = base;
@@ -265,7 +300,7 @@ export function mountPreview(el, { read, copy, actions = [], copyInHead = true,
265
300
  // 内容的来源变了(根目录换了位置):旧正文不能留,也不能按元数据判断「没变」。
266
301
  reload() { find.close(); return path === null ? undefined : load(false); }, // 来源变了:查找也关
267
302
  // 停止(逻辑关闭,立即):不再读、不再刷新,待恢复的位置结算;画面(正文、图片的 URL)留着,由 release 在退场结束时清掉。
268
- stop() { settle(false); player?.pause?.(); token++; path = null; shown = null; textShown = false; find.close(); stoppedAt = opens; },
303
+ stop() { settle(false); player?.pause?.(); viewer?.cancel(); token++; path = null; shown = null; textShown = false; find.close(); stoppedAt = opens; },
269
304
  // 释放(画面):停止之后又打开过就什么都不做。
270
305
  release() {
271
306
  if (stoppedAt !== opens) return; // 停止之后又打开过(打开次数变了):这一屏是新的,不是退场的旧页
package/view/protocol.mjs CHANGED
@@ -72,11 +72,16 @@ const MEDIA_TYPES = {
72
72
  png: ['image', 'image/png'], jpg: ['image', 'image/jpeg'], jpeg: ['image', 'image/jpeg'], gif: ['image', 'image/gif'], webp: ['image', 'image/webp'],
73
73
  svg: ['image', 'image/svg+xml'], avif: ['image', 'image/avif'], heic: ['image', 'image/heic'], heif: ['image', 'image/heif'],
74
74
  bmp: ['image', 'image/bmp'], tif: ['image', 'image/tiff'], tiff: ['image', 'image/tiff'],
75
+ // 3D 模型(第 21 节):页面用 three.js 画,字节同样经流式服务取。
76
+ glb: ['model', 'model/gltf-binary'], gltf: ['model', 'model/gltf+json'], stl: ['model', 'model/stl'], obj: ['model', 'model/obj'],
77
+ ply: ['model', 'model/ply'], '3mf': ['model', 'model/3mf'],
75
78
  };
79
+ // 模型的伴随文件:服务要供应(gltf 的 .bin、obj 的 .mtl),但页面不把它们当媒体预览(.mtl 仍是文本,.bin 仍是二进制)。
80
+ const COMPANION_TYPES = { bin: 'application/octet-stream', mtl: 'text/plain; charset=utf-8' };
76
81
  // 查证过 Coda 播放器不支持的视频:按扩展名直接不预览,不读字节(mkv 容器不支持,avi 的 canPlayType 说 maybe 但实际报错)。
77
82
  const NO_PREVIEW = new Set(['mkv', 'avi']);
78
83
 
79
- // 按扩展名给出 { kind: 'audio' | 'video' | 'image', type, preview };不是媒体文件返回 null。preview 为 false 的没有 type,不经服务。
84
+ // 按扩展名给出 { kind: 'audio' | 'video' | 'image' | 'model', type, preview };不是媒体文件返回 null。preview 为 false 的没有 type,不经服务。
80
85
  export function mediaOf(name) {
81
86
  const dot = String(name).lastIndexOf('.');
82
87
  if (dot < 0) return null;
@@ -86,6 +91,14 @@ export function mediaOf(name) {
86
91
  return entry ? { kind: entry[0], type: entry[1], preview: true } : null;
87
92
  }
88
93
 
94
+ // 流式服务肯供应的文件的 MIME 类型:能预览的媒体加上模型的伴随文件;其余返回 null(服务回 415)。
95
+ export function servedType(name) {
96
+ const media = mediaOf(name);
97
+ if (media) return media.preview ? media.type : null;
98
+ const dot = String(name).lastIndexOf('.');
99
+ return dot < 0 ? null : COMPANION_TYPES[name.slice(dot + 1).toLowerCase()] ?? null;
100
+ }
101
+
89
102
  // 相对路径的规则只在这一处:模块(lib/paths.mjs)校验请求,页面恢复保存的 cwd 时用同一个函数。
90
103
  // 空串是根目录;拒绝过长、控制字符、绝对路径和 `..`。返回 { segments }(去掉空段和 `.`)或 { problem }(给人看的原因)。
91
104
  export const MAX_PATH = 4096;
package/view/style.css CHANGED
@@ -179,6 +179,21 @@ button.icon svg { display: block; }
179
179
  .media { display: grid; place-items: start center; padding: 12px; }
180
180
  .media video { width: 100%; max-height: 70vh; border-radius: var(--coda-radius, 6px); background: #000; }
181
181
  .media audio { width: 100%; }
182
+ /* 3D 模型(第 21 节):正文不滚动,整块是画布;状态、复位和动画控制浮在画布上。「3D / 文本」切换在头部。 */
183
+ .pmode { flex: none; display: flex; gap: 2px; }
184
+ .pmode button { padding: 2px 8px; border-radius: var(--coda-radius, 6px); }
185
+ .pmode button[aria-pressed="true"] { background: var(--coda-selection, var(--hover)); font-weight: 600; }
186
+ .pbody.model { display: flex; flex-direction: column; overflow: hidden; }
187
+ .mview { flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; }
188
+ .mstage { position: relative; flex: 1 1 auto; min-height: 160px; overflow: hidden; background: var(--coda-secondary-background, rgba(127,127,127,.08)); }
189
+ .mcanvas { position: absolute; inset: 0; width: 100%; height: 100%; display: block; outline: none; -webkit-user-select: none; user-select: none; -webkit-touch-callout: none; }
190
+ .mstatus { position: absolute; inset: 0; display: grid; align-content: center; justify-items: center; gap: 6px; padding: 20px; text-align: center; pointer-events: none; }
191
+ .mstatus[hidden] { display: none; }
192
+ .mstatus button { pointer-events: auto; }
193
+ .mbtn, .mclip { padding: 4px 10px; border-radius: var(--coda-radius, 6px); background: var(--coda-card, var(--coda-background, #fff)); border: 1px solid var(--line); color: var(--coda-accent, #0a84ff); }
194
+ .mreset { position: absolute; top: 8px; right: 8px; }
195
+ .mbar { position: absolute; left: 8px; bottom: 8px; display: flex; gap: 8px; }
196
+ .mbar[hidden], .mclip[hidden] { display: none; }
182
197
  .image { display: grid; place-items: start center; padding: 12px; }
183
198
  .image img { max-width: 100%; height: auto; border-radius: var(--coda-radius, 6px); background: var(--coda-secondary-background, transparent); }
184
199
 
@@ -0,0 +1,21 @@
1
+ The MIT License
2
+
3
+ Copyright © 2010-2026 three.js authors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
@@ -0,0 +1 @@
1
+ three@0.187.0