@file-viewer/renderer-cad 2.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,160 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction, and
10
+ distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright
13
+ owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all other entities
16
+ that control, are controlled by, or are under common control with that entity.
17
+ For the purposes of this definition, "control" means (i) the power, direct or
18
+ indirect, to cause the direction or management of such entity, whether by
19
+ contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
20
+ outstanding shares, or (iii) beneficial ownership of such entity.
21
+
22
+ "You" (or "Your") shall mean an individual or Legal Entity exercising
23
+ permissions granted by this License.
24
+
25
+ "Source" form shall mean the preferred form for making modifications, including
26
+ but not limited to software source code, documentation source, and configuration
27
+ files.
28
+
29
+ "Object" form shall mean any form resulting from mechanical transformation or
30
+ translation of a Source form, including but not limited to compiled object code,
31
+ generated documentation, and conversions to other media types.
32
+
33
+ "Work" shall mean the work of authorship, whether in Source or Object form,
34
+ made available under the License, as indicated by a copyright notice that is
35
+ included in or attached to the work.
36
+
37
+ "Derivative Works" shall mean any work, whether in Source or Object form, that
38
+ is based on (or derived from) the Work and for which the editorial revisions,
39
+ annotations, elaborations, or other modifications represent, as a whole, an
40
+ original work of authorship. For the purposes of this License, Derivative Works
41
+ shall not include works that remain separable from, or merely link (or bind by
42
+ name) to the interfaces of, the Work and Derivative Works thereof.
43
+
44
+ "Contribution" shall mean any work of authorship, including the original version
45
+ of the Work and any modifications or additions to that Work or Derivative Works
46
+ thereof, that is intentionally submitted to Licensor for inclusion in the Work by
47
+ the copyright owner or by an individual or Legal Entity authorized to submit on
48
+ behalf of the copyright owner. For the purposes of this definition, "submitted"
49
+ means any form of electronic, verbal, or written communication sent to the
50
+ Licensor or its representatives, including but not limited to communication on
51
+ electronic mailing lists, source code control systems, and issue tracking systems
52
+ that are managed by, or on behalf of, the Licensor for the purpose of discussing
53
+ and improving the Work, but excluding communication that is conspicuously marked
54
+ or otherwise designated in writing by the copyright owner as "Not a
55
+ Contribution."
56
+
57
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf
58
+ of whom a Contribution has been received by Licensor and subsequently
59
+ incorporated within the Work.
60
+
61
+ 2. Grant of Copyright License. Subject to the terms and conditions of this
62
+ License, each Contributor hereby grants to You a perpetual, worldwide,
63
+ non-exclusive, no-charge, royalty-free, irrevocable copyright license to
64
+ reproduce, prepare Derivative Works of, publicly display, publicly perform,
65
+ sublicense, and distribute the Work and such Derivative Works in Source or
66
+ Object form.
67
+
68
+ 3. Grant of Patent License. Subject to the terms and conditions of this License,
69
+ each Contributor hereby grants to You a perpetual, worldwide, non-exclusive,
70
+ no-charge, royalty-free, irrevocable (except as stated in this section) patent
71
+ license to make, have made, use, offer to sell, sell, import, and otherwise
72
+ transfer the Work, where such license applies only to those patent claims
73
+ licensable by such Contributor that are necessarily infringed by their
74
+ Contribution(s) alone or by combination of their Contribution(s) with the Work to
75
+ which such Contribution(s) was submitted. If You institute patent litigation
76
+ against any entity (including a cross-claim or counterclaim in a lawsuit)
77
+ alleging that the Work or a Contribution incorporated within the Work
78
+ constitutes direct or contributory patent infringement, then any patent licenses
79
+ granted to You under this License for that Work shall terminate as of the date
80
+ such litigation is filed.
81
+
82
+ 4. Redistribution. You may reproduce and distribute copies of the Work or
83
+ Derivative Works thereof in any medium, with or without modifications, and in
84
+ Source or Object form, provided that You meet the following conditions:
85
+
86
+ (a) You must give any other recipients of the Work or Derivative Works a copy of
87
+ this License; and
88
+
89
+ (b) You must cause any modified files to carry prominent notices stating that
90
+ You changed the files; and
91
+
92
+ (c) You must retain, in the Source form of any Derivative Works that You
93
+ distribute, all copyright, patent, trademark, and attribution notices from the
94
+ Source form of the Work, excluding those notices that do not pertain to any part
95
+ of the Derivative Works; and
96
+
97
+ (d) If the Work includes a "NOTICE" text file as part of its distribution, then
98
+ any Derivative Works that You distribute must include a readable copy of the
99
+ attribution notices contained within such NOTICE file, excluding those notices
100
+ that do not pertain to any part of the Derivative Works, in at least one of the
101
+ following places: within a NOTICE text file distributed as part of the Derivative
102
+ Works; within the Source form or documentation, if provided along with the
103
+ Derivative Works; or, within a display generated by the Derivative Works, if and
104
+ wherever such third-party notices normally appear. The contents of the NOTICE
105
+ file are for informational purposes only and do not modify the License. You may
106
+ add Your own attribution notices within Derivative Works that You distribute,
107
+ alongside or as an addendum to the NOTICE text from the Work, provided that such
108
+ additional attribution notices cannot be construed as modifying the License.
109
+
110
+ You may add Your own copyright statement to Your modifications and may provide
111
+ additional or different license terms and conditions for use, reproduction, or
112
+ distribution of Your modifications, or for any such Derivative Works as a whole,
113
+ provided Your use, reproduction, and distribution of the Work otherwise complies
114
+ with the conditions stated in this License.
115
+
116
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any
117
+ Contribution intentionally submitted for inclusion in the Work by You to the
118
+ Licensor shall be under the terms and conditions of this License, without any
119
+ additional terms or conditions. Notwithstanding the above, nothing herein shall
120
+ supersede or modify the terms of any separate license agreement you may have
121
+ executed with Licensor regarding such Contributions.
122
+
123
+ 6. Trademarks. This License does not grant permission to use the trade names,
124
+ trademarks, service marks, or product names of the Licensor, except as required
125
+ for reasonable and customary use in describing the origin of the Work and
126
+ reproducing the content of the NOTICE file.
127
+
128
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in
129
+ writing, Licensor provides the Work (and each Contributor provides its
130
+ Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
131
+ KIND, either express or implied, including, without limitation, any warranties or
132
+ conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
133
+ PARTICULAR PURPOSE. You are solely responsible for determining the
134
+ appropriateness of using or redistributing the Work and assume any risks
135
+ associated with Your exercise of permissions under this License.
136
+
137
+ 8. Limitation of Liability. In no event and under no legal theory, whether in
138
+ tort (including negligence), contract, or otherwise, unless required by
139
+ applicable law (such as deliberate and grossly negligent acts) or agreed to in
140
+ writing, shall any Contributor be liable to You for damages, including any
141
+ direct, indirect, special, incidental, or consequential damages of any character
142
+ arising as a result of this License or out of the use or inability to use the
143
+ Work (including but not limited to damages for loss of goodwill, work stoppage,
144
+ computer failure or malfunction, or any and all other commercial damages or
145
+ losses), even if such Contributor has been advised of the possibility of such
146
+ damages.
147
+
148
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or
149
+ Derivative Works thereof, You may choose to offer, and charge a fee for,
150
+ acceptance of support, warranty, indemnity, or other liability obligations and/or
151
+ rights consistent with this License. However, in accepting such obligations, You
152
+ may act only on Your own behalf and on Your sole responsibility, not on behalf of
153
+ any other Contributor, and only if You agree to indemnify, defend, and hold each
154
+ Contributor harmless for any liability incurred by, or claims asserted against,
155
+ such Contributor by reason of your accepting any such warranty or additional
156
+ liability.
157
+
158
+ END OF TERMS AND CONDITIONS
159
+
160
+ Copyright 2026 Flyfish Viewer
package/README.en.md ADDED
@@ -0,0 +1,49 @@
1
+ # @file-viewer/renderer-cad
2
+
3
+ Standalone CAD renderer package for Flyfish File Viewer. It is powered by `@flyfish-dev/cad-viewer`, previews DWG, DXF, DWF, DWFx, and XPS in the browser, and resolves wasm / worker URLs through the File Viewer asset manifest for offline enterprise deployments.
4
+
5
+ ## Usage
6
+
7
+ ```ts
8
+ import FileViewer from '@file-viewer/vue3'
9
+ import { cadRenderer } from '@file-viewer/renderer-cad'
10
+
11
+ const options = {
12
+ rendererMode: 'replace',
13
+ renderers: cadRenderer,
14
+ }
15
+ ```
16
+
17
+ You can also compose it with other renderer packages:
18
+
19
+ ```ts
20
+ import { cadRenderer } from '@file-viewer/renderer-cad'
21
+ import { pdfRenderer } from '@file-viewer/renderer-pdf'
22
+
23
+ const options = {
24
+ rendererMode: 'replace',
25
+ renderers: [pdfRenderer, cadRenderer],
26
+ }
27
+ ```
28
+
29
+ ## Capabilities
30
+
31
+ - Supports `.dwg`, `.dxf`, `.dwf`, `.dwfx`, and `.xps`.
32
+ - DWG is parsed on demand with a worker and LibreDWG WASM to keep the main thread responsive.
33
+ - DXF is parsed in JavaScript and normalized into the common CAD document model.
34
+ - DWF / DWFx / XPS use the native renderer with `dwfv-render.wasm` for performant raster / WebGL fallback.
35
+ - Includes layer toggling, structure stats, fit-to-view, zoom controls, global toolbar zoom provider, and resize handling.
36
+
37
+ ## Offline Assets
38
+
39
+ The default asset paths are:
40
+
41
+ - `wasm/cad/`
42
+ - `wasm/cad/dwg-worker.js`
43
+ - `wasm/cad/dwfv-render.wasm`
44
+
45
+ For private deployments, override them with `options.cad.wasmPath`, `options.cad.workerUrl`, and `options.cad.dwfWasmUrl`.
46
+
47
+ ## Migration Note
48
+
49
+ CAD preview has moved completely out of `@file-viewer/core`. Core now only keeps the asset manifest, shared types, and a compatibility error message, and it no longer installs `@flyfish-dev/cad-viewer` by default. Install this package and pass it through `renderers`, or use `@file-viewer/preset-all` for the complete CAD experience.
package/README.md ADDED
@@ -0,0 +1,49 @@
1
+ # @file-viewer/renderer-cad
2
+
3
+ Flyfish File Viewer 的独立 CAD renderer 包。它基于 `@flyfish-dev/cad-viewer` 提供 DWG、DXF、DWF、DWFx 和 XPS 的浏览器端预览,并通过 File Viewer 统一的 asset manifest 解析 wasm / worker 路径,适合企业内网和离线部署。
4
+
5
+ ## 用法
6
+
7
+ ```ts
8
+ import FileViewer from '@file-viewer/vue3'
9
+ import { cadRenderer } from '@file-viewer/renderer-cad'
10
+
11
+ const options = {
12
+ rendererMode: 'replace',
13
+ renderers: cadRenderer,
14
+ }
15
+ ```
16
+
17
+ 也可以和其他 renderer 一起组合:
18
+
19
+ ```ts
20
+ import { cadRenderer } from '@file-viewer/renderer-cad'
21
+ import { pdfRenderer } from '@file-viewer/renderer-pdf'
22
+
23
+ const options = {
24
+ rendererMode: 'replace',
25
+ renderers: [pdfRenderer, cadRenderer],
26
+ }
27
+ ```
28
+
29
+ ## 能力边界
30
+
31
+ - 支持 `.dwg`、`.dxf`、`.dwf`、`.dwfx`、`.xps`。
32
+ - DWG 使用 Worker + LibreDWG WASM 按需解析,避免阻塞主线程。
33
+ - DXF 使用 JavaScript parser 并归一化为统一 CAD document。
34
+ - DWF / DWFx / XPS 使用 native renderer,并通过 `dwfv-render.wasm` 提供高性能 raster / WebGL fallback。
35
+ - 支持图层显示切换、结构统计、适配视图、缩放、全局 toolbar zoom provider 和 resize observer。
36
+
37
+ ## 离线资产
38
+
39
+ 默认会从 viewer assets 下读取:
40
+
41
+ - `wasm/cad/`
42
+ - `wasm/cad/dwg-worker.js`
43
+ - `wasm/cad/dwfv-render.wasm`
44
+
45
+ 私有化部署时可以通过 `options.cad.wasmPath`、`options.cad.workerUrl`、`options.cad.dwfWasmUrl` 覆盖。
46
+
47
+ ## 迁移说明
48
+
49
+ CAD 预览已经从 `@file-viewer/core` 中彻底移出,core 只保留资产 manifest、类型和兼容错误提示,不再默认安装 `@flyfish-dev/cad-viewer`。完整 CAD 能力请安装本包并传入 `renderers`,或直接使用 `@file-viewer/preset-all`。
package/dist/cad.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ import { type FileRenderContext, type FileViewerRenderedInstance } from '@file-viewer/core';
2
+ export default function renderCad(buffer: ArrayBuffer, target: HTMLDivElement, type?: string, context?: FileRenderContext): Promise<FileViewerRenderedInstance>;
package/dist/cad.js ADDED
@@ -0,0 +1,445 @@
1
+ import { CadViewer, } from '@flyfish-dev/cad-viewer';
2
+ import { resolveFileViewerCadAssetUrls } from '@file-viewer/core/assets';
3
+ import { createFileViewerZoomChangeEmitter, registerFileViewerZoomProvider, unregisterFileViewerZoomProvider, } from '@file-viewer/core';
4
+ const CAD_WORKER_TIMEOUT = 120000;
5
+ const cadStyle = `
6
+ .cad-shell{display:flex;height:100%;min-height:100%;flex-direction:column;background:#f5f7fb;color:#142335}
7
+ .cad-shell *{box-sizing:border-box}
8
+ .cad-toolbar{display:flex;min-height:48px;align-items:center;justify-content:space-between;gap:16px;padding:0 14px;border-bottom:1px solid rgba(15,23,42,.08);background:#fff}
9
+ .cad-tools,.cad-meta{display:flex;align-items:center;gap:8px}
10
+ .cad-tools button{min-width:34px;min-height:30px;border:0;border-radius:8px;background:rgba(15,23,42,.06);color:#25344c;cursor:pointer;font-weight:800;letter-spacing:0;transition:background-color .18s ease,color .18s ease}
11
+ .cad-tools button:hover{background:rgba(31,150,110,.14);color:#0f8f62}
12
+ .cad-zoom,.cad-meta span{color:#64748b;font-size:12px;font-weight:800;letter-spacing:0}
13
+ .cad-meta span{border-radius:999px;padding:5px 9px;background:rgba(15,23,42,.06)}
14
+ .cad-body{display:grid;min-height:0;flex:1;grid-template-columns:minmax(168px,220px) minmax(0,1fr) minmax(150px,190px);background:#eef2f7}
15
+ .cad-body.without-layers{grid-template-columns:minmax(0,1fr) minmax(150px,190px)}
16
+ .cad-layers,.cad-inspector{min-height:0;overflow:auto;border-right:1px solid rgba(15,23,42,.08);background:#fff}
17
+ .cad-layers[hidden]{display:none}
18
+ .cad-inspector{border-right:0;border-left:1px solid rgba(15,23,42,.08);padding:14px}
19
+ .cad-layers-head{position:sticky;top:0;display:flex;align-items:center;justify-content:space-between;padding:12px 12px 8px;background:#fff;color:#1f2a3d;font-size:13px;z-index:1}
20
+ .cad-layers-head span{color:#7b8ca5;font-size:12px;font-weight:700}
21
+ .cad-layers-list{display:flex;flex-direction:column;padding:0 0 8px}
22
+ .cad-layers button{display:flex;width:calc(100% - 16px);min-height:34px;align-items:center;gap:8px;margin:0 8px 6px;border:1px solid rgba(148,163,184,.22);border-radius:8px;background:#f8fafc;color:#25344c;cursor:pointer;font-size:12px;font-weight:700;text-align:left}
23
+ .cad-layers button.muted{opacity:.48}
24
+ .cad-layer-color{width:10px;height:10px;flex:0 0 auto;border-radius:50%;background:#1f966e;box-shadow:inset 0 0 0 1px rgba(15,23,42,.14)}
25
+ .cad-canvas-wrap{position:relative;min-width:0;min-height:0;overflow:hidden;background:linear-gradient(90deg,rgba(15,23,42,.04) 1px,transparent 1px),linear-gradient(180deg,rgba(15,23,42,.04) 1px,transparent 1px),#f8fafc;background-size:28px 28px}
26
+ .cad-stage{position:relative;width:100%;height:100%;min-height:420px;overflow:hidden}
27
+ .cad-stage canvas{position:absolute;inset:0;display:block;width:100%!important;height:100%!important}
28
+ .cad-native-stage{position:absolute;inset:0;z-index:2;display:none;overflow:hidden}
29
+ .cad-native-stage:not(:empty),.cad-native-stage.is-active{display:block}
30
+ .cad-native-stage *{box-sizing:border-box}
31
+ .dwfv-root{height:100%;min-height:0;display:grid;grid-template-rows:auto 1fr;font-family:system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif;color:#111827}
32
+ .dwfv-toolbar{display:flex;gap:8px;align-items:center;padding:8px 12px;background:#fff;border-bottom:1px solid #e5e7eb}
33
+ .dwfv-toolbar button,.dwfv-toolbar select{font:inherit}
34
+ .dwfv-workspace{min-height:0;display:grid;grid-template-columns:minmax(220px,300px) 1fr}
35
+ .dwfv-tree{overflow:auto;border-right:1px solid #d6d8dd;background:#fff;font-size:12px;padding:8px}
36
+ .dwfv-tree[style*="display: none"]+.dwfv-stage{grid-column:1/-1}
37
+ .dwfv-tree-header{font-weight:700;margin-bottom:4px}
38
+ .dwfv-tree-stats{color:#6b7280;margin-bottom:8px}
39
+ .dwfv-tree details{margin-left:8px}
40
+ .dwfv-tree summary{cursor:pointer;padding:2px 0}
41
+ .dwfv-tree-meta{color:#6b7280;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:10px;padding-left:14px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
42
+ .dwfv-stage{position:relative;overflow:hidden;background:#e5e7eb}
43
+ .dwfv-canvas{position:absolute;top:0;right:0;bottom:0;left:0;width:100%;height:100%}
44
+ .dwfv-webgl-canvas{pointer-events:none}
45
+ .dwfv-overlay-canvas{pointer-events:auto;touch-action:none;cursor:grab}
46
+ .dwfv-overlay-canvas:active{cursor:grabbing}
47
+ .dwfv-status{margin-left:auto;font-size:12px;color:#4b5563}
48
+ .dwfv-warn{color:#92400e}
49
+ .cad-viewer-container{position:relative;overflow:hidden;min-width:0;min-height:0}
50
+ .cad-viewer-canvas{display:block;width:100%;height:100%;cursor:grab;touch-action:none;-webkit-user-select:none;user-select:none}
51
+ .cad-viewer-canvas.is-dragging{cursor:grabbing}
52
+ .cad-viewer-webgl-canvas{position:relative;z-index:0}
53
+ .cad-viewer-text-overlay{display:block;contain:strict;-webkit-user-select:none;user-select:none}
54
+ .cad-viewer-native-host{position:absolute;top:0;right:0;bottom:0;left:0;display:none;z-index:2;min-width:0;min-height:0;background:#05070d}
55
+ .cad-viewer-native-host.is-active{display:block}
56
+ .cad-viewer-native-host .dwfv-root{height:100%;min-height:0;color:#dbeafe;background:#05070d}
57
+ .cad-viewer-native-host .dwfv-toolbar{min-height:34px;padding:5px 8px;gap:6px;border-bottom:1px solid rgba(71,85,105,.65);background:#0f172af5;color:#e5e7eb}
58
+ .cad-viewer-native-host .dwfv-toolbar button,.cad-viewer-native-host .dwfv-toolbar select{height:24px;border:1px solid rgba(100,116,139,.75);border-radius:6px;background:#111827;color:#e5e7eb;font-size:12px}
59
+ .cad-viewer-native-host .dwfv-toolbar button{padding:0 8px;cursor:pointer}
60
+ .cad-viewer-native-host .dwfv-toolbar button:hover,.cad-viewer-native-host .dwfv-toolbar select:hover{border-color:#60a5fa;color:#bfdbfe}
61
+ .cad-viewer-native-host .dwfv-status{color:#93c5fd;font-size:12px}
62
+ .cad-viewer-native-host .dwfv-workspace{min-height:0;background:#05070d}
63
+ .cad-viewer-native-host .dwfv-stage{background:#05070d}
64
+ .cad-viewer-native-host .dwfv-tree{border-right:1px solid rgba(71,85,105,.7);background:#0f172a;color:#dbeafe}
65
+ .cad-viewer-native-host .dwfv-tree-stats,.cad-viewer-native-host .dwfv-tree-meta{color:#94a3b8}
66
+ .cad-viewer-native-host .dwfv-warn{color:#fbbf24}
67
+ .cad-native-stage .dwfv-root,.cad-native-stage .dwfv-workspace,.cad-native-stage .dwfv-stage{width:100%;min-width:0;min-height:0}
68
+ .cad-native-stage .dwfv-root{height:100%}
69
+ .cad-state{position:absolute;inset:50% auto auto 50%;max-width:min(520px,calc(100% - 48px));transform:translate(-50%,-50%);border-radius:12px;padding:14px 18px;background:rgba(255,255,255,.92);box-shadow:0 14px 38px rgba(15,23,42,.12);color:#53637a;font-size:13px;font-weight:800;text-align:center}
70
+ .cad-state[hidden]{display:none!important}
71
+ .cad-state.error{color:#b42318}
72
+ .cad-inspector strong{display:block;margin-bottom:12px;color:#1f2a3d;font-size:13px}
73
+ .cad-inspector dl{display:grid;gap:8px;margin:0}
74
+ .cad-inspector dl div{display:flex;align-items:center;justify-content:space-between;gap:12px;border-radius:8px;padding:8px 10px;background:#f8fafc}
75
+ .cad-inspector dt,.cad-inspector dd{margin:0;font-size:12px}
76
+ .cad-inspector dt{color:#7b8ca5;font-weight:700}
77
+ .cad-inspector dd{color:#20304a;font-weight:900}
78
+ .cad-warning{margin:12px 0 0;border-radius:8px;padding:10px;background:rgba(245,158,11,.13);color:#92400e;font-size:12px;line-height:1.55}
79
+ .file-viewer[data-viewer-theme='dark'] .cad-shell{background:#111827;color:#e5edf6}
80
+ .file-viewer[data-viewer-theme='dark'] .cad-toolbar,.file-viewer[data-viewer-theme='dark'] .cad-layers,.file-viewer[data-viewer-theme='dark'] .cad-inspector{background:#fff;color:#142335}
81
+ @media (prefers-color-scheme:dark){.file-viewer[data-viewer-theme='system'] .cad-shell{background:#111827;color:#e5edf6}.file-viewer[data-viewer-theme='system'] .cad-toolbar,.file-viewer[data-viewer-theme='system'] .cad-layers,.file-viewer[data-viewer-theme='system'] .cad-inspector{background:#fff;color:#142335}}
82
+ @media (max-width:860px){.cad-body,.cad-body.without-layers{grid-template-columns:minmax(0,1fr)}.cad-layers,.cad-inspector{display:none}}
83
+ `;
84
+ const createStyle = () => {
85
+ const style = document.createElement('style');
86
+ style.textContent = cadStyle;
87
+ return style;
88
+ };
89
+ const createElement = (tagName, className, text) => {
90
+ const element = document.createElement(tagName);
91
+ if (className) {
92
+ element.className = className;
93
+ }
94
+ if (text !== undefined) {
95
+ element.textContent = text;
96
+ }
97
+ return element;
98
+ };
99
+ const normalizeType = (type) => {
100
+ return (type || 'dxf').toLowerCase();
101
+ };
102
+ const collectLayers = (result) => {
103
+ if (!result) {
104
+ return [];
105
+ }
106
+ return Object.entries(result.document.layers)
107
+ .map(([name, layer]) => ({ ...layer, name }))
108
+ .sort((left, right) => left.name.localeCompare(right.name));
109
+ };
110
+ const formatNumber = (value) => {
111
+ if (!Number.isFinite(value)) {
112
+ return '0';
113
+ }
114
+ return new Intl.NumberFormat('zh-CN').format(Math.round(value || 0));
115
+ };
116
+ const getCadDocumentBaseUrl = (target) => {
117
+ var _a;
118
+ return ((_a = target.ownerDocument) === null || _a === void 0 ? void 0 : _a.baseURI) || 'http://localhost/';
119
+ };
120
+ export default async function renderCad(buffer, target, type = 'dxf', context) {
121
+ var _a;
122
+ const normalizedType = normalizeType(type);
123
+ const options = ((_a = context === null || context === void 0 ? void 0 : context.options) === null || _a === void 0 ? void 0 : _a.cad) || {};
124
+ let status = 'loading';
125
+ let progressMessage = '正在加载 CAD 预览器...';
126
+ let errorMessage = '';
127
+ let loadResult = null;
128
+ let renderStats = null;
129
+ let viewState = null;
130
+ let layers = [];
131
+ let viewer = null;
132
+ let resizeObserver = null;
133
+ let abortController = null;
134
+ let disposed = false;
135
+ const style = createStyle();
136
+ const shell = createElement('div', 'cad-shell');
137
+ shell.dataset.viewerZoomProvider = 'cad';
138
+ const toolbar = createElement('div', 'cad-toolbar');
139
+ const tools = createElement('div', 'cad-tools');
140
+ const fitButton = createElement('button', undefined, '适配');
141
+ const zoomOutButton = createElement('button', undefined, '-');
142
+ const zoomText = createElement('span', 'cad-zoom', '100%');
143
+ const zoomInButton = createElement('button', undefined, '+');
144
+ const meta = createElement('div', 'cad-meta');
145
+ const typeMeta = createElement('span', undefined, normalizedType.toUpperCase());
146
+ const backendMeta = createElement('span', undefined, 'AUTO');
147
+ [fitButton, zoomOutButton, zoomInButton].forEach(button => {
148
+ button.type = 'button';
149
+ });
150
+ zoomOutButton.title = '缩小';
151
+ zoomInButton.title = '放大';
152
+ tools.append(fitButton, zoomOutButton, zoomText, zoomInButton);
153
+ meta.append(typeMeta, backendMeta);
154
+ toolbar.append(tools, meta);
155
+ const body = createElement('div', 'cad-body without-layers');
156
+ const layersPanel = createElement('aside', 'cad-layers');
157
+ layersPanel.hidden = true;
158
+ const layersHead = createElement('div', 'cad-layers-head');
159
+ const layersCount = createElement('span', undefined, '0 项');
160
+ layersHead.append(createElement('strong', undefined, '图层'), layersCount);
161
+ const layersList = createElement('div', 'cad-layers-list');
162
+ layersPanel.append(layersHead, layersList);
163
+ const canvasWrap = createElement('div', 'cad-canvas-wrap');
164
+ const stage = createElement('div', 'cad-stage');
165
+ const nativeHost = createElement('div', 'cad-native-stage');
166
+ stage.append(nativeHost);
167
+ const state = createElement('div', 'cad-state', progressMessage);
168
+ canvasWrap.append(stage, state);
169
+ const inspector = createElement('aside', 'cad-inspector');
170
+ const inspectorTitle = createElement('strong', undefined, '结构');
171
+ const inspectorList = createElement('dl');
172
+ const warningText = createElement('p', 'cad-warning');
173
+ warningText.hidden = true;
174
+ inspector.append(inspectorTitle, inspectorList, warningText);
175
+ body.append(layersPanel, canvasWrap, inspector);
176
+ shell.append(toolbar, body);
177
+ target.replaceChildren(style, shell);
178
+ const buildFileName = () => {
179
+ return (context === null || context === void 0 ? void 0 : context.filename) || `drawing.${normalizedType}`;
180
+ };
181
+ const getWarnings = () => (loadResult === null || loadResult === void 0 ? void 0 : loadResult.warnings) || (loadResult === null || loadResult === void 0 ? void 0 : loadResult.document.warnings) || [];
182
+ const getZoomPercent = () => {
183
+ var _a, _b, _c;
184
+ const zoom = (_c = (_a = viewState === null || viewState === void 0 ? void 0 : viewState.zoomPercent) !== null && _a !== void 0 ? _a : (_b = viewer === null || viewer === void 0 ? void 0 : viewer.getZoomPercent) === null || _b === void 0 ? void 0 : _b.call(viewer)) !== null && _c !== void 0 ? _c : 100;
185
+ return Number.isFinite(zoom) ? Math.round(zoom) : 100;
186
+ };
187
+ const getCadZoomState = () => {
188
+ const ready = status === 'ready' && !!viewer;
189
+ const zoomPercent = getZoomPercent();
190
+ return {
191
+ scale: zoomPercent / 100,
192
+ label: `${zoomPercent}%`,
193
+ canZoomIn: ready,
194
+ canZoomOut: ready,
195
+ canReset: ready,
196
+ minScale: 0.05,
197
+ maxScale: 16,
198
+ };
199
+ };
200
+ const cadZoomEmitter = createFileViewerZoomChangeEmitter();
201
+ const syncInspector = () => {
202
+ const summary = loadResult === null || loadResult === void 0 ? void 0 : loadResult.summary;
203
+ const rows = [
204
+ ['实体', formatNumber(summary === null || summary === void 0 ? void 0 : summary.entityCount)],
205
+ ['块', formatNumber(summary === null || summary === void 0 ? void 0 : summary.blockCount)],
206
+ ['页面', formatNumber(summary === null || summary === void 0 ? void 0 : summary.pageCount)],
207
+ ['绘制', formatNumber(renderStats === null || renderStats === void 0 ? void 0 : renderStats.drawn)],
208
+ ];
209
+ inspectorList.replaceChildren(...rows.map(([label, value]) => {
210
+ const row = createElement('div');
211
+ row.append(createElement('dt', undefined, label), createElement('dd', undefined, value));
212
+ return row;
213
+ }));
214
+ const warning = getWarnings()[0];
215
+ warningText.textContent = warning || '';
216
+ warningText.hidden = !warning;
217
+ };
218
+ const syncLayers = () => {
219
+ layersCount.textContent = `${layers.length} 项`;
220
+ layersPanel.hidden = layers.length === 0;
221
+ body.classList.toggle('without-layers', layers.length === 0);
222
+ layersList.replaceChildren(...layers.map(layer => {
223
+ const button = createElement('button');
224
+ button.type = 'button';
225
+ button.classList.toggle('muted', layer.isVisible === false || !!layer.isFrozen);
226
+ const color = createElement('span', 'cad-layer-color');
227
+ if (typeof layer.color === 'string') {
228
+ color.style.background = layer.color;
229
+ }
230
+ button.append(color, createElement('span', undefined, layer.name));
231
+ button.addEventListener('click', () => {
232
+ const document = viewer === null || viewer === void 0 ? void 0 : viewer.getDocument();
233
+ if (!(document === null || document === void 0 ? void 0 : document.layers[layer.name])) {
234
+ return;
235
+ }
236
+ const current = document.layers[layer.name];
237
+ current.isVisible = current.isVisible === false;
238
+ loadResult = (viewer === null || viewer === void 0 ? void 0 : viewer.setDocument(document, buildFileName())) || null;
239
+ layers = collectLayers(loadResult);
240
+ syncUi();
241
+ queueMicrotask(() => {
242
+ viewer === null || viewer === void 0 ? void 0 : viewer.fit();
243
+ cadZoomEmitter.emit();
244
+ });
245
+ });
246
+ return button;
247
+ }));
248
+ };
249
+ const syncState = () => {
250
+ zoomText.textContent = `${getZoomPercent()}%`;
251
+ backendMeta.textContent = ((renderStats === null || renderStats === void 0 ? void 0 : renderStats.backend) || 'auto').toUpperCase();
252
+ state.hidden = status === 'ready';
253
+ state.classList.toggle('error', status === 'error');
254
+ if (status === 'loading') {
255
+ state.textContent = progressMessage;
256
+ }
257
+ else if (status === 'error') {
258
+ state.textContent = errorMessage;
259
+ }
260
+ };
261
+ const syncUi = () => {
262
+ syncState();
263
+ syncLayers();
264
+ syncInspector();
265
+ };
266
+ const updateProgress = (progress) => {
267
+ const prefix = progress.format ? `${progress.format.toUpperCase()} ` : '';
268
+ const percent = Number.isFinite(progress.percent) ? ` ${Math.round(progress.percent || 0)}%` : '';
269
+ progressMessage = `${prefix}${progress.message}${percent}`;
270
+ syncState();
271
+ };
272
+ const fitToView = () => {
273
+ viewer === null || viewer === void 0 ? void 0 : viewer.fit();
274
+ cadZoomEmitter.emit();
275
+ syncState();
276
+ };
277
+ const zoomIn = () => {
278
+ viewer === null || viewer === void 0 ? void 0 : viewer.zoomIn();
279
+ cadZoomEmitter.emit();
280
+ syncState();
281
+ };
282
+ const zoomOut = () => {
283
+ viewer === null || viewer === void 0 ? void 0 : viewer.zoomOut();
284
+ cadZoomEmitter.emit();
285
+ syncState();
286
+ };
287
+ registerFileViewerZoomProvider(shell, {
288
+ zoomIn: () => {
289
+ zoomIn();
290
+ return getCadZoomState();
291
+ },
292
+ zoomOut: () => {
293
+ zoomOut();
294
+ return getCadZoomState();
295
+ },
296
+ resetZoom: () => {
297
+ fitToView();
298
+ return getCadZoomState();
299
+ },
300
+ getState: getCadZoomState,
301
+ subscribe: cadZoomEmitter.subscribe,
302
+ });
303
+ fitButton.addEventListener('click', fitToView);
304
+ zoomInButton.addEventListener('click', zoomIn);
305
+ zoomOutButton.addEventListener('click', zoomOut);
306
+ const createViewer = () => {
307
+ var _a, _b, _c, _d, _e, _f, _g;
308
+ const { wasmPath, workerUrl, dwfWasmUrl } = resolveFileViewerCadAssetUrls(options, getCadDocumentBaseUrl(target));
309
+ const canvasOptions = {
310
+ background: '#f8fafc',
311
+ foreground: '#0f172a',
312
+ contrastMode: 'adaptive',
313
+ minColorContrast: 2.4,
314
+ showPageBounds: true,
315
+ showUnsupportedMarkers: true,
316
+ enableSpatialIndex: true,
317
+ maxVisibleTextLabels: 2400,
318
+ ...(options.canvasOptions || {}),
319
+ };
320
+ const nextViewer = new CadViewer({
321
+ container: stage,
322
+ nativeHost,
323
+ renderer: options.renderer || 'auto',
324
+ wasmPath,
325
+ workerUrl,
326
+ dwfWasmUrl,
327
+ dxfEncoding: options.dxfEncoding,
328
+ useWorker: (_a = options.useWorker) !== null && _a !== void 0 ? _a : true,
329
+ workerTimeoutMs: (_b = options.workerTimeoutMs) !== null && _b !== void 0 ? _b : CAD_WORKER_TIMEOUT,
330
+ preferDwgWasm: (_c = options.preferDwgWasm) !== null && _c !== void 0 ? _c : true,
331
+ includePaperSpace: (_d = options.includePaperSpace) !== null && _d !== void 0 ? _d : true,
332
+ maxInsertDepth: options.maxInsertDepth,
333
+ keepRaw: (_e = options.keepRaw) !== null && _e !== void 0 ? _e : false,
334
+ dwfPreferWebgl: (_f = options.dwfPreferWebgl) !== null && _f !== void 0 ? _f : true,
335
+ dwfPreferWasm: (_g = options.dwfPreferWasm) !== null && _g !== void 0 ? _g : true,
336
+ dwfBackground: options.dwfBackground || '#f8fafc',
337
+ dwfMaxDevicePixelRatio: options.dwfMaxDevicePixelRatio,
338
+ dwfMaxCanvasPixels: options.dwfMaxCanvasPixels,
339
+ dwfMaxGpuCacheBytes: options.dwfMaxGpuCacheBytes,
340
+ dwfMaxCachedScenes: options.dwfMaxCachedScenes,
341
+ dwfLineWeightMode: options.dwfLineWeightMode,
342
+ dwfMinStrokeCssPx: options.dwfMinStrokeCssPx,
343
+ dwfMaxOverviewStrokeCssPx: options.dwfMaxOverviewStrokeCssPx,
344
+ dwfMinTextCssPx: options.dwfMinTextCssPx,
345
+ dwfMinFilledAreaCssPx: options.dwfMinFilledAreaCssPx,
346
+ autoFit: true,
347
+ canvasOptions,
348
+ onLoadProgress: updateProgress,
349
+ onRenderStats: stats => {
350
+ renderStats = stats;
351
+ syncState();
352
+ syncInspector();
353
+ },
354
+ onViewChange: event => {
355
+ viewState = event;
356
+ cadZoomEmitter.emit();
357
+ syncState();
358
+ },
359
+ onLoad: result => {
360
+ loadResult = result;
361
+ layers = collectLayers(result);
362
+ syncUi();
363
+ },
364
+ onError: error => {
365
+ errorMessage = error.message || 'CAD 文件解析失败';
366
+ syncState();
367
+ },
368
+ });
369
+ if (options.preloadDwg !== false && normalizedType === 'dwg') {
370
+ void nextViewer.preloadDwg({ wasmPath, workerUrl }).catch(() => {
371
+ // 预热失败不阻断真实加载,loadBuffer 会返回完整错误上下文。
372
+ });
373
+ }
374
+ return nextViewer;
375
+ };
376
+ const loadCad = async () => {
377
+ status = 'loading';
378
+ progressMessage = '正在解析 CAD...';
379
+ errorMessage = '';
380
+ loadResult = null;
381
+ renderStats = null;
382
+ viewState = null;
383
+ layers = [];
384
+ syncUi();
385
+ abortController === null || abortController === void 0 ? void 0 : abortController.abort();
386
+ const controller = new AbortController();
387
+ abortController = controller;
388
+ try {
389
+ viewer === null || viewer === void 0 ? void 0 : viewer.destroy();
390
+ viewer = createViewer();
391
+ const cadAssets = resolveFileViewerCadAssetUrls(options, getCadDocumentBaseUrl(target));
392
+ const result = await viewer.loadBuffer(buffer.slice(0), buildFileName(), {
393
+ signal: controller.signal,
394
+ transferInputBuffer: false,
395
+ dxfEncoding: options.dxfEncoding,
396
+ wasmPath: cadAssets.wasmPath,
397
+ workerUrl: cadAssets.workerUrl,
398
+ dwfWasmUrl: cadAssets.dwfWasmUrl,
399
+ });
400
+ if (disposed || controller.signal.aborted) {
401
+ return;
402
+ }
403
+ loadResult = result;
404
+ layers = collectLayers(result);
405
+ status = 'ready';
406
+ syncUi();
407
+ queueMicrotask(() => {
408
+ viewer === null || viewer === void 0 ? void 0 : viewer.fit();
409
+ cadZoomEmitter.emit();
410
+ syncState();
411
+ });
412
+ }
413
+ catch (reason) {
414
+ if (disposed || controller.signal.aborted) {
415
+ return;
416
+ }
417
+ console.error(reason);
418
+ status = 'error';
419
+ errorMessage = reason instanceof Error ? reason.message : 'CAD 文件解析失败';
420
+ syncUi();
421
+ }
422
+ };
423
+ if (typeof ResizeObserver !== 'undefined') {
424
+ resizeObserver = new ResizeObserver(() => {
425
+ viewer === null || viewer === void 0 ? void 0 : viewer.resize();
426
+ });
427
+ resizeObserver.observe(stage);
428
+ }
429
+ syncUi();
430
+ void loadCad();
431
+ return {
432
+ $el: shell,
433
+ unmount() {
434
+ disposed = true;
435
+ unregisterFileViewerZoomProvider(shell);
436
+ abortController === null || abortController === void 0 ? void 0 : abortController.abort();
437
+ abortController = null;
438
+ resizeObserver === null || resizeObserver === void 0 ? void 0 : resizeObserver.disconnect();
439
+ resizeObserver = null;
440
+ viewer === null || viewer === void 0 ? void 0 : viewer.destroy();
441
+ viewer = null;
442
+ target.replaceChildren();
443
+ },
444
+ };
445
+ }
@@ -0,0 +1,5 @@
1
+ import { type FileRenderHandler, type FileViewerRenderedInstance, type FileViewerRendererPlugin, type RendererDefinition } from '@file-viewer/core';
2
+ export declare const cadRendererDefinition: RendererDefinition;
3
+ export declare const renderFileViewerCad: FileRenderHandler<FileViewerRenderedInstance, HTMLDivElement>;
4
+ export declare const cadRenderer: FileViewerRendererPlugin<FileRenderHandler<FileViewerRenderedInstance, HTMLDivElement>>;
5
+ export default cadRenderer;
package/dist/index.js ADDED
@@ -0,0 +1,17 @@
1
+ import { DEFAULT_RENDERER_DEFINITIONS, } from '@file-viewer/core';
2
+ const cadDefinition = DEFAULT_RENDERER_DEFINITIONS.find(definition => definition.id === 'cad');
3
+ if (!cadDefinition) {
4
+ throw new Error('@file-viewer/renderer-cad could not locate the shared CAD format definition.');
5
+ }
6
+ export const cadRendererDefinition = cadDefinition;
7
+ export const renderFileViewerCad = (buffer, target, type, context) => import('./cad.js').then(({ default: renderCad }) => renderCad(buffer, target, type, context));
8
+ export const cadRenderer = {
9
+ id: 'file-viewer-renderer-cad',
10
+ label: 'Flyfish File Viewer CAD renderer',
11
+ definitions: [cadRendererDefinition],
12
+ handlers: [{
13
+ rendererId: cadRendererDefinition.id,
14
+ handler: renderFileViewerCad,
15
+ }],
16
+ };
17
+ export default cadRenderer;
package/package.json ADDED
@@ -0,0 +1,70 @@
1
+ {
2
+ "name": "@file-viewer/renderer-cad",
3
+ "version": "2.0.11",
4
+ "private": false,
5
+ "type": "module",
6
+ "description": "Standalone CAD renderer plugin for Flyfish File Viewer powered by @flyfish-dev/cad-viewer.",
7
+ "keywords": [
8
+ "file-viewer",
9
+ "renderer",
10
+ "cad",
11
+ "dwg",
12
+ "dxf",
13
+ "dwf",
14
+ "document-preview",
15
+ "document-viewer",
16
+ "file-preview",
17
+ "self-hosted",
18
+ "cad-viewer"
19
+ ],
20
+ "publishConfig": {
21
+ "access": "public",
22
+ "registry": "https://registry.npmjs.org/"
23
+ },
24
+ "author": {
25
+ "name": "Wangyu",
26
+ "email": "wybaby168@gmail.com"
27
+ },
28
+ "repository": {
29
+ "type": "git",
30
+ "url": "git+https://github.com/flyfish-dev/file-viewer-renderer-cad.git",
31
+ "directory": "packages/renderers/cad"
32
+ },
33
+ "homepage": "https://doc.file-viewer.app/guide/on-demand-renderers",
34
+ "bugs": {
35
+ "url": "https://github.com/flyfish-dev/file-viewer-renderer-cad/issues"
36
+ },
37
+ "funding": {
38
+ "type": "individual",
39
+ "url": "https://dev.flyfish.group/shop"
40
+ },
41
+ "main": "./dist/index.js",
42
+ "module": "./dist/index.js",
43
+ "types": "./dist/index.d.ts",
44
+ "exports": {
45
+ ".": {
46
+ "types": "./dist/index.d.ts",
47
+ "import": "./dist/index.js",
48
+ "default": "./dist/index.js"
49
+ },
50
+ "./package.json": "./package.json"
51
+ },
52
+ "files": [
53
+ "dist",
54
+ "README.md",
55
+ "README.en.md",
56
+ "LICENSE"
57
+ ],
58
+ "dependencies": {
59
+ "@file-viewer/core": "^2.0.11",
60
+ "@flyfish-dev/cad-viewer": "^0.6.4"
61
+ },
62
+ "devDependencies": {
63
+ "typescript": "^6.0.3"
64
+ },
65
+ "license": "Apache-2.0",
66
+ "scripts": {
67
+ "build": "tsc -b tsconfig.json",
68
+ "type-check": "tsc -b tsconfig.json"
69
+ }
70
+ }