@chao194/office 1.0.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.
Files changed (50) hide show
  1. package/README.md +481 -0
  2. package/dist/cjs/core/index.cjs +2 -0
  3. package/dist/cjs/core/index.cjs.map +1 -0
  4. package/dist/cjs/react/index.cjs +2 -0
  5. package/dist/cjs/react/index.cjs.map +1 -0
  6. package/dist/cjs/vue2/index.cjs +2 -0
  7. package/dist/cjs/vue2/index.cjs.map +1 -0
  8. package/dist/cjs/vue3/index.cjs +2 -0
  9. package/dist/cjs/vue3/index.cjs.map +1 -0
  10. package/dist/esm/core/index.mjs +2 -0
  11. package/dist/esm/core/index.mjs.map +1 -0
  12. package/dist/esm/react/index.mjs +2 -0
  13. package/dist/esm/react/index.mjs.map +1 -0
  14. package/dist/esm/vue2/index.mjs +2 -0
  15. package/dist/esm/vue2/index.mjs.map +1 -0
  16. package/dist/esm/vue3/index.mjs +2 -0
  17. package/dist/esm/vue3/index.mjs.map +1 -0
  18. package/dist/types/core/editor.d.ts +64 -0
  19. package/dist/types/core/editor.d.ts.map +1 -0
  20. package/dist/types/core/index.d.ts +55 -0
  21. package/dist/types/core/index.d.ts.map +1 -0
  22. package/dist/types/core/utils/fileType.d.ts +14 -0
  23. package/dist/types/core/utils/fileType.d.ts.map +1 -0
  24. package/dist/types/core/utils/http.d.ts +45 -0
  25. package/dist/types/core/utils/http.d.ts.map +1 -0
  26. package/dist/types/index.d.ts +5 -0
  27. package/dist/types/index.d.ts.map +1 -0
  28. package/dist/types/react/OnlyOfficeEditor.d.ts +51 -0
  29. package/dist/types/react/OnlyOfficeEditor.d.ts.map +1 -0
  30. package/dist/types/react/index.d.ts +7 -0
  31. package/dist/types/react/index.d.ts.map +1 -0
  32. package/dist/types/react/useOnlyOffice.d.ts +56 -0
  33. package/dist/types/react/useOnlyOffice.d.ts.map +1 -0
  34. package/dist/types/types/index.d.ts +184 -0
  35. package/dist/types/types/index.d.ts.map +1 -0
  36. package/dist/types/vue2/component.d.ts +77 -0
  37. package/dist/types/vue2/component.d.ts.map +1 -0
  38. package/dist/types/vue2/index.d.ts +5 -0
  39. package/dist/types/vue2/index.d.ts.map +1 -0
  40. package/dist/types/vue2/mixin.d.ts +59 -0
  41. package/dist/types/vue2/mixin.d.ts.map +1 -0
  42. package/dist/types/vue3/component.d.ts +88 -0
  43. package/dist/types/vue3/component.d.ts.map +1 -0
  44. package/dist/types/vue3/index.d.ts +6 -0
  45. package/dist/types/vue3/index.d.ts.map +1 -0
  46. package/dist/types/vue3/useOnlyOffice.d.ts +52 -0
  47. package/dist/types/vue3/useOnlyOffice.d.ts.map +1 -0
  48. package/dist/umd/index.js +2 -0
  49. package/dist/umd/index.js.map +1 -0
  50. package/package.json +100 -0
package/README.md ADDED
@@ -0,0 +1,481 @@
1
+ # @chao194/office
2
+
3
+ 即插即用的 OnlyOffice 前端集成方案,支持 Vue 2/3、React 和原生 JavaScript。
4
+
5
+ ## 特性
6
+
7
+ - 🚀 **即插即用** - 简单的 API 设计,快速集成 OnlyOffice 文档编辑器
8
+ - 📦 **多框架支持** - 支持 Vue 2、Vue 3、React 和原生 JavaScript
9
+ - 🔐 **灵活的验签** - 支持自定义验签函数或内置验签接口
10
+ - 📝 **TypeScript** - 完整的 TypeScript 类型定义
11
+ - 🎯 **Tree-shaking** - 支持按需引入,优化打包体积
12
+ - 📚 **完整文档** - 详细的 API 文档和使用示例
13
+
14
+ ## 安装
15
+
16
+ ```bash
17
+ # npm
18
+ npm install @chao194/office
19
+
20
+ # yarn
21
+ yarn add @chao194/office
22
+
23
+ # pnpm
24
+ pnpm add @chao194/office
25
+ ```
26
+
27
+ ## 快速开始
28
+
29
+ ### 原生 JavaScript
30
+
31
+ ```javascript
32
+ import { createOfficeEditor } from '@chao194/office';
33
+
34
+ // 创建编辑器实例
35
+ const editor = createOfficeEditor();
36
+
37
+ // 配置文档参数
38
+ editor.configure({
39
+ fileType: 'docx',
40
+ key: 'your-document-key',
41
+ url: 'https://example.com/document.docx',
42
+ title: '示例文档',
43
+ callbackUrl: 'https://your-server.com/callback',
44
+ userId: 'user123',
45
+ userName: '张三',
46
+ });
47
+
48
+ // 初始化编辑器(带验签)
49
+ const instance = await editor.initOffice({
50
+ dom: document.getElementById('office-container'),
51
+ officeApiUrl: 'https://your-onlyoffice-server/web-apps/apps/api/documents/api.js',
52
+ auth: {
53
+ appId: 'your-app-id',
54
+ sign: 'your-sign',
55
+ timestamp: Date.now(),
56
+ verifyUrl: 'https://your-server.com',
57
+ },
58
+ });
59
+
60
+ // 监听事件
61
+ instance.on('onDocumentReady', () => {
62
+ console.log('文档已就绪');
63
+ });
64
+
65
+ // 组件销毁时清理
66
+ instance.destroy();
67
+ ```
68
+
69
+ ### Vue 3 组件
70
+
71
+ ```vue
72
+ <template>
73
+ <OnlyOfficeEditor
74
+ :office-api-url="officeApiUrl"
75
+ :document="documentConfig"
76
+ :auth="authConfig"
77
+ @ready="onReady"
78
+ @error="onError"
79
+ />
80
+ </template>
81
+
82
+ <script setup lang="ts">
83
+ import { ref } from 'vue';
84
+ import { OnlyOfficeEditor } from '@chao194/office/vue3';
85
+ import type { OfficeDocumentConfig, AuthConfig } from '@chao194/office';
86
+
87
+ const officeApiUrl = 'https://your-onlyoffice-server/web-apps/apps/api/documents/api.js';
88
+
89
+ const documentConfig: OfficeDocumentConfig = {
90
+ fileType: 'docx',
91
+ key: 'your-document-key',
92
+ url: 'https://example.com/document.docx',
93
+ title: '示例文档',
94
+ callbackUrl: 'https://your-server.com/callback',
95
+ userId: 'user123',
96
+ userName: '张三',
97
+ };
98
+
99
+ const authConfig: AuthConfig = {
100
+ appId: 'your-app-id',
101
+ sign: 'your-sign',
102
+ timestamp: Date.now(),
103
+ };
104
+
105
+ const onReady = (editor) => {
106
+ console.log('编辑器已就绪', editor);
107
+ };
108
+
109
+ const onError = (error) => {
110
+ console.error('编辑器错误', error);
111
+ };
112
+ </script>
113
+ ```
114
+
115
+ ### Vue 3 组合式函数
116
+
117
+ ```vue
118
+ <template>
119
+ <div ref="containerRef" style="width: 100%; height: 600px;"></div>
120
+ </template>
121
+
122
+ <script setup lang="ts">
123
+ import { useOnlyOffice } from '@chao194/office/vue3';
124
+
125
+ const { containerRef, isReady, error } = useOnlyOffice({
126
+ officeApiUrl: 'https://your-onlyoffice-server/web-apps/apps/api/documents/api.js',
127
+ document: {
128
+ fileType: 'docx',
129
+ key: 'your-document-key',
130
+ url: 'https://example.com/document.docx',
131
+ title: '示例文档',
132
+ callbackUrl: 'https://your-server.com/callback',
133
+ userId: 'user123',
134
+ userName: '张三',
135
+ },
136
+ });
137
+ </script>
138
+ ```
139
+
140
+ ### Vue 2 组件
141
+
142
+ ```vue
143
+ <template>
144
+ <OnlyOfficeEditor
145
+ :office-api-url="officeApiUrl"
146
+ :document="documentConfig"
147
+ :auth="authConfig"
148
+ @ready="onReady"
149
+ @error="onError"
150
+ />
151
+ </template>
152
+
153
+ <script>
154
+ import { OnlyOfficeEditor } from '@chao194/office/vue2';
155
+
156
+ export default {
157
+ components: {
158
+ OnlyOfficeEditor,
159
+ },
160
+ data() {
161
+ return {
162
+ officeApiUrl: 'https://your-onlyoffice-server/web-apps/apps/api/documents/api.js',
163
+ documentConfig: {
164
+ fileType: 'docx',
165
+ key: 'your-document-key',
166
+ url: 'https://example.com/document.docx',
167
+ title: '示例文档',
168
+ callbackUrl: 'https://your-server.com/callback',
169
+ userId: 'user123',
170
+ userName: '张三',
171
+ },
172
+ authConfig: {
173
+ appId: 'your-app-id',
174
+ sign: 'your-sign',
175
+ timestamp: Date.now(),
176
+ },
177
+ };
178
+ },
179
+ methods: {
180
+ onReady(editor) {
181
+ console.log('编辑器已就绪', editor);
182
+ },
183
+ onError(error) {
184
+ console.error('编辑器错误', error);
185
+ },
186
+ },
187
+ };
188
+ </script>
189
+ ```
190
+
191
+ ### Vue 2 混入
192
+
193
+ ```vue
194
+ <template>
195
+ <div ref="officeContainer" style="width: 100%; height: 600px;"></div>
196
+ </template>
197
+
198
+ <script>
199
+ import { OnlyOfficeMixin } from '@chao194/office/vue2';
200
+
201
+ export default {
202
+ mixins: [OnlyOfficeMixin],
203
+ mounted() {
204
+ this.$initOffice(
205
+ this.$refs.officeContainer,
206
+ 'https://your-onlyoffice-server/web-apps/apps/api/documents/api.js',
207
+ {
208
+ fileType: 'docx',
209
+ key: 'your-document-key',
210
+ url: 'https://example.com/document.docx',
211
+ title: '示例文档',
212
+ callbackUrl: 'https://your-server.com/callback',
213
+ userId: 'user123',
214
+ userName: '张三',
215
+ }
216
+ );
217
+ },
218
+ beforeDestroy() {
219
+ this.$destroyOffice();
220
+ },
221
+ };
222
+ </script>
223
+ ```
224
+
225
+ ### React 组件
226
+
227
+ ```tsx
228
+ import React from 'react';
229
+ import { OnlyOfficeEditor } from '@chao194/office/react';
230
+ import type { OfficeDocumentConfig, AuthConfig } from '@chao194/office';
231
+
232
+ const officeApiUrl = 'https://your-onlyoffice-server/web-apps/apps/api/documents/api.js';
233
+
234
+ const documentConfig: OfficeDocumentConfig = {
235
+ fileType: 'docx',
236
+ key: 'your-document-key',
237
+ url: 'https://example.com/document.docx',
238
+ title: '示例文档',
239
+ callbackUrl: 'https://your-server.com/callback',
240
+ userId: 'user123',
241
+ userName: '张三',
242
+ };
243
+
244
+ const authConfig: AuthConfig = {
245
+ appId: 'your-app-id',
246
+ sign: 'your-sign',
247
+ timestamp: Date.now(),
248
+ };
249
+
250
+ function App() {
251
+ return (
252
+ <div style={{ width: '100%', height: '600px' }}>
253
+ <OnlyOfficeEditor
254
+ officeApiUrl={officeApiUrl}
255
+ document={documentConfig}
256
+ auth={authConfig}
257
+ onReady={(editor) => console.log('编辑器已就绪', editor)}
258
+ onError={(error) => console.error('编辑器错误', error)}
259
+ />
260
+ </div>
261
+ );
262
+ }
263
+
264
+ export default App;
265
+ ```
266
+
267
+ ### React Hook
268
+
269
+ ```tsx
270
+ import React from 'react';
271
+ import { useOnlyOffice } from '@chao194/office/react';
272
+
273
+ function App() {
274
+ const { containerRef, isReady, error } = useOnlyOffice({
275
+ officeApiUrl: 'https://your-onlyoffice-server/web-apps/apps/api/documents/api.js',
276
+ document: {
277
+ fileType: 'docx',
278
+ key: 'your-document-key',
279
+ url: 'https://example.com/document.docx',
280
+ title: '示例文档',
281
+ callbackUrl: 'https://your-server.com/callback',
282
+ userId: 'user123',
283
+ userName: '张三',
284
+ },
285
+ });
286
+
287
+ return (
288
+ <div>
289
+ <div ref={containerRef} style={{ width: '100%', height: '600px' }} />
290
+ {error && <div style={{ color: 'red' }}>{error}</div>}
291
+ </div>
292
+ );
293
+ }
294
+
295
+ export default App;
296
+ ```
297
+
298
+ ## API 文档
299
+
300
+ ### 核心 API
301
+
302
+ #### `createOfficeEditor()`
303
+
304
+ 创建一个新的 Office 编辑器实例。
305
+
306
+ **返回值:** `OfficeEditor`
307
+
308
+ #### `initOffice(config)`
309
+
310
+ 快速初始化 Office 编辑器(带验签)。
311
+
312
+ **参数:**
313
+ - `config: OfficeInitConfig` - 初始化配置
314
+
315
+ **返回值:** `Promise<OfficeEditorInstance>`
316
+
317
+ #### `init(dom, officeApiUrl, callback?)`
318
+
319
+ 简化初始化(无验签)。
320
+
321
+ **参数:**
322
+ - `dom: HTMLElement` - 挂载的 DOM 元素
323
+ - `officeApiUrl: string` - OnlyOffice API 地址
324
+ - `callback?: OfficeCallback` - 事件回调函数
325
+
326
+ **返回值:** `OfficeEditorInstance`
327
+
328
+ ### OfficeEditor 实例方法
329
+
330
+ #### `configure(config)`
331
+
332
+ 配置文档参数。
333
+
334
+ **参数:**
335
+ - `config: OfficeDocumentConfig` - 文档配置
336
+
337
+ #### `initOffice(config)`
338
+
339
+ 初始化编辑器(带验签)。
340
+
341
+ **参数:**
342
+ - `config: OfficeInitConfig` - 初始化配置
343
+
344
+ **返回值:** `Promise<OfficeEditorInstance>`
345
+
346
+ #### `init(dom, officeApiUrl, callback?)`
347
+
348
+ 简化初始化(无验签)。
349
+
350
+ **参数:**
351
+ - `dom: HTMLElement` - 挂载的 DOM 元素
352
+ - `officeApiUrl: string` - OnlyOffice API 地址
353
+ - `callback?: OfficeCallback` - 事件回调函数
354
+
355
+ **返回值:** `OfficeEditorInstance`
356
+
357
+ #### `on(event, callback)`
358
+
359
+ 监听事件。
360
+
361
+ **参数:**
362
+ - `event: OfficeEventType` - 事件类型
363
+ - `callback: (...args: any[]) => void` - 回调函数
364
+
365
+ #### `off(event, callback)`
366
+
367
+ 移除事件监听。
368
+
369
+ **参数:**
370
+ - `event: OfficeEventType` - 事件类型
371
+ - `callback: (...args: any[]) => void` - 回调函数
372
+
373
+ #### `destroy()`
374
+
375
+ 销毁编辑器实例。
376
+
377
+ #### `getConfig()`
378
+
379
+ 获取当前配置。
380
+
381
+ **返回值:** `DocumentConfig & EditorConfig`
382
+
383
+ #### `getEditor()`
384
+
385
+ 获取内部 OnlyOffice 编辑器实例。
386
+
387
+ **返回值:** `any`
388
+
389
+ ### 类型定义
390
+
391
+ #### `OfficeDocumentConfig`
392
+
393
+ ```typescript
394
+ interface OfficeDocumentConfig {
395
+ height?: string;
396
+ width?: string;
397
+ fileType?: FileType;
398
+ key?: string;
399
+ url?: string;
400
+ title?: string;
401
+ permissions?: DocumentPermissions;
402
+ callbackUrl?: string;
403
+ userId?: string;
404
+ userName?: string;
405
+ userGroup?: string;
406
+ }
407
+ ```
408
+
409
+ #### `OfficeInitConfig`
410
+
411
+ ```typescript
412
+ interface OfficeInitConfig {
413
+ dom: HTMLElement;
414
+ officeApiUrl: string;
415
+ callback?: OfficeCallback;
416
+ auth?: AuthConfig;
417
+ verifyFunction?: VerifyTokenSignFunction;
418
+ }
419
+ ```
420
+
421
+ #### `AuthConfig`
422
+
423
+ ```typescript
424
+ interface AuthConfig {
425
+ appId: string;
426
+ sign: string;
427
+ timestamp: number;
428
+ verifyUrl?: string;
429
+ }
430
+ ```
431
+
432
+ #### `OfficeEventType`
433
+
434
+ ```typescript
435
+ type OfficeEventType =
436
+ | 'documentStateChange'
437
+ | 'onDocumentReady'
438
+ | 'onInfo'
439
+ | 'onError'
440
+ | 'onRequestHistory'
441
+ | 'onRequestHistoryData'
442
+ | 'onRequestHistoryClose'
443
+ | 'onRequestRestore'
444
+ | 'onRequestSendNotify'
445
+ | 'onRequestUsers';
446
+ ```
447
+
448
+ ## 从旧版本迁移
449
+
450
+ ### 从 script 标签方式迁移
451
+
452
+ 旧版本使用 `<script>` 标签加载全局变量 `bingoOffice`:
453
+
454
+ ```html
455
+ <script src="https://onlyoffice.bin-go.me/sdk/bingo-office-dev.js"></script>
456
+ <script>
457
+ bingoOffice.sdk.config({...});
458
+ bingoOffice.sdk.initOffice({...});
459
+ </script>
460
+ ```
461
+
462
+ 新版本使用 npm 包导入:
463
+
464
+ ```javascript
465
+ import { createOfficeEditor } from '@chao194/office';
466
+
467
+ const editor = createOfficeEditor();
468
+ editor.configure({...});
469
+ await editor.initOffice({...});
470
+ ```
471
+
472
+ ### 主要变化
473
+
474
+ 1. **导入方式**: 从全局变量改为 ES Module 导入
475
+ 2. **验签配置**: 验签配置从 `signData` 改为 `auth`,支持自定义验签函数
476
+ 3. **实例管理**: 从全局单例改为可创建多个独立实例
477
+ 4. **类型支持**: 完整的 TypeScript 类型定义
478
+
479
+ ## 许可证
480
+
481
+ MIT
@@ -0,0 +1,2 @@
1
+ "use strict";var t=require("eventemitter3"),e=require("axios");function i(t){const e=t.toLowerCase();if(["doc","docx","odt","rtf","txt","html","epub"].includes(e))return"word";if(["xls","xlsx","ods","csv"].includes(e))return"cell";return["ppt","pptx","odp"].includes(e)?"slide":"pdf"===e?"pdf":"other"}function o(t){return"other"!==i(t)}class r{constructor(t=""){this.baseUrl=t}async post(t,i,o){const r=this.baseUrl?`${this.baseUrl}${t}`:t;return e.post(r,i,o)}async get(t,i){const o=this.baseUrl?`${this.baseUrl}${t}`:t;return e.get(o,i)}}async function s(t,e){var i;try{const o=new r(t);return!0===(null===(i=(await o.post("/onlyoffice/token/verifyTokenSign",e)).data)||void 0===i?void 0:i.data)}catch(t){return console.error("验签请求失败:",t),!1}}async function n(t,i){try{await e.post(t,i)}catch(t){console.error("保存操作信息失败:",t)}}var c=Object.freeze({__proto__:null,HttpClient:r,saveSuccessInfo:n,verifyTokenSign:s});const d={comment:!1,download:!1,edit:!1,print:!0,review:!1,editCommentAuthorOnly:!1,fillForms:!1,modifyContentControl:!1};class a{constructor(){this.editor=null,this.callback=null,this.height="100%",this.width="100%",this.editorId=`editor-${Date.now().toString(32)}`,this.emitter=new t,this.documentConfig={fileType:"docx",key:"",url:"",title:"",permissions:{...d}},this.editorConfig={lang:"zh",user:{id:"",name:""}}}configure(t){if(t.height&&(this.height=t.height),t.width&&(this.width=t.width),t.fileType){if(!o(t.fileType))throw new Error(`不支持的文件类型: ${t.fileType}`);"other"!==i(t.fileType)&&(this.documentConfig.fileType=t.fileType)}t.key&&(this.documentConfig.key=t.key),t.url&&(this.documentConfig.url=t.url),t.title&&(this.documentConfig.title=t.title),t.permissions&&(this.documentConfig.permissions={...this.documentConfig.permissions,...t.permissions},"pdf"===this.documentConfig.fileType&&(this.documentConfig.permissions.edit=!1,this.documentConfig.permissions.review=!1,this.editorConfig.mode="view")),t.callbackUrl&&(this.editorConfig.callbackUrl=t.callbackUrl),t.userId&&(this.editorConfig.user={...this.editorConfig.user,id:t.userId}),t.userName&&(this.editorConfig.user={...this.editorConfig.user,name:t.userName}),t.userGroup&&(this.editorConfig.user={...this.editorConfig.user,group:t.userGroup})}async initOffice(t){const{dom:e,officeApiUrl:i,callback:o,auth:r,verifyFunction:n}=t;if(o&&(this.callback=o),r){let t=!1;if(n)t=await n(r);else{if(!r.verifyUrl)throw new Error("使用验签配置时,必须提供 verifyFunction 或 verifyUrl");t=await s(r.verifyUrl,{appId:r.appId,sign:r.sign,timestamp:r.timestamp})}if(!t)throw new Error("验签失败,请检查验签配置")}return this.createEditor(e,i)}init(t,e,i){return i&&(this.callback=i),this.createEditor(t,e)}createEditor(t,e){if(!t)throw new Error("必须提供挂载的 DOM 元素");if(!e)throw new Error("必须提供 OnlyOffice API 脚本地址");t.style.position="relative";const i=document.createElement("div");i.id=this.editorId,i.style.height="100%",i.style.width="100%",t.appendChild(i);const o=`script-${this.editorId}`;if(document.querySelector(`#${o}`))this.instantiateEditor();else{const t=document.createElement("script");t.id=o,t.src=e,t.onload=()=>this.instantiateEditor(),document.head.appendChild(t)}return this}instantiateEditor(){this.editor&&(this.editor.destroyEditor(),this.editor=null);const t={width:this.width,height:this.height,documentType:this.getDocumentType(),document:this.documentConfig,editorConfig:this.editorConfig,events:this.createEventHandlers()};this.editor=new window.DocsAPI.DocEditor(this.editorId,t)}getDocumentType(){const t=i(this.documentConfig.fileType);return"other"===t?"word":t}createEventHandlers(){return{onDocumentStateChange:t=>{this.emitter.emit("documentStateChange",t)},onDocumentReady:()=>{var t,e;console.log("Document is loaded"),this.editorConfig.callbackUrl&&n(this.editorConfig.callbackUrl,{status:8,key:this.documentConfig.key,userdata:JSON.stringify({appUserId:null===(t=this.editorConfig.user)||void 0===t?void 0:t.id})}),null===(e=this.callback)||void 0===e||e.call(this,"onDocumentReady"),this.emitter.emit("onDocumentReady")},onInfo:t=>{var e;console.log("ONLYOFFICE Document Editor is opened in mode",t.data.mode),null===(e=this.callback)||void 0===e||e.call(this,"onInfo",t.data),this.emitter.emit("onInfo",t)},onError:t=>{console.error("ONLYOFFICE Error:",t.data.errorCode,t.data.errorDescription),this.emitter.emit("onError",t)},onRequestHistory:t=>{var e;null===(e=this.callback)||void 0===e||e.call(this,"onRequestHistory",t,this.editor),this.emitter.emit("onRequestHistory",{event:t,editor:this.editor})},onRequestHistoryData:t=>{var e;null===(e=this.callback)||void 0===e||e.call(this,"onRequestHistoryData",t,this.editor),this.emitter.emit("onRequestHistoryData",{event:t,editor:this.editor})},onRequestHistoryClose:t=>{var e;null===(e=this.callback)||void 0===e||e.call(this,"onRequestHistoryClose",t,this.editor),this.emitter.emit("onRequestHistoryClose",{event:t,editor:this.editor})},onRequestRestore:t=>{var e;null===(e=this.callback)||void 0===e||e.call(this,"onRequestRestore",t,this.editor),this.emitter.emit("onRequestRestore",{event:t,editor:this.editor})},onRequestSendNotify:t=>{console.log("onRequestSendNotify",t),this.emitter.emit("onRequestSendNotify",t)},onRequestUsers:t=>{console.log("onRequestUsers",t),this.emitter.emit("onRequestUsers",t)}}}on(t,e){this.emitter.on(t,e)}off(t,e){this.emitter.off(t,e)}getConfig(){return{...this.documentConfig,...this.editorConfig}}getEditor(){return this.editor}destroy(){this.editor&&(this.editor.destroyEditor(),this.editor=null),this.emitter.removeAllListeners(),this.callback=null}}exports.HttpClient=r,exports.OfficeEditor=a,exports.config=function(t){console.warn("此方法已废弃,请使用 OfficeEditor.configure() 方法")},exports.createOfficeEditor=function(){return new a},exports.destroy=function(){console.warn("此方法已废弃,请使用 OfficeEditor.destroy() 方法")},exports.downloadSave=async function(t,e,i){const{saveSuccessInfo:o}=await Promise.resolve().then(function(){return c});await o(t,{status:9,key:e,userdata:JSON.stringify({appUserId:i})})},exports.getDocumentType=i,exports.init=function(t,e,i){return(new a).init(t,e,i)},exports.initOffice=async function(t){return(new a).initOffice(t)},exports.isSupportedFileType=o,exports.on=function(t,e){console.warn("此方法已废弃,请使用 OfficeEditor.on() 方法")},exports.saveSuccessInfo=n,exports.shareSave=async function(t,e,i){const{saveSuccessInfo:o}=await Promise.resolve().then(function(){return c});await o(t,{status:10,key:e,userdata:JSON.stringify({appUserId:i})})},exports.verifyTokenSign=s;
2
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","sources":["../../../src/core/utils/fileType.ts","../../../src/core/utils/http.ts","../../../src/core/editor.ts","../../../src/core/index.ts"],"sourcesContent":["import type { DocumentType, FileType } from '../../types';\n\n/**\n * 根据文件扩展名获取 OnlyOffice 文档类型\n * @param fileType 文件扩展名\n * @returns 文档类型\n */\nexport function getDocumentType(fileType: FileType | string): DocumentType | 'other' {\n const type = fileType.toLowerCase();\n\n // 文档类型\n const wordTypes = ['doc', 'docx', 'odt', 'rtf', 'txt', 'html', 'epub'];\n if (wordTypes.includes(type)) {\n return 'word';\n }\n\n // 表格类型\n const cellTypes = ['xls', 'xlsx', 'ods', 'csv'];\n if (cellTypes.includes(type)) {\n return 'cell';\n }\n\n // 演示类型\n const slideTypes = ['ppt', 'pptx', 'odp'];\n if (slideTypes.includes(type)) {\n return 'slide';\n }\n\n // PDF 类型\n if (type === 'pdf') {\n return 'pdf';\n }\n\n return 'other';\n}\n\n/**\n * 检查文件类型是否受支持\n * @param fileType 文件扩展名\n * @returns 是否支持\n */\nexport function isSupportedFileType(fileType: string): boolean {\n return getDocumentType(fileType) !== 'other';\n}","import axios, { type AxiosRequestConfig, type AxiosResponse } from 'axios';\n\n/**\n * HTTP 请求工具\n */\nexport class HttpClient {\n private baseUrl: string;\n\n constructor(baseUrl: string = '') {\n this.baseUrl = baseUrl;\n }\n\n /**\n * 发送 POST 请求\n * @param url 请求地址\n * @param data 请求数据\n * @param config 额外配置\n * @returns Promise\n */\n async post<T = any>(\n url: string,\n data?: any,\n config?: AxiosRequestConfig\n ): Promise<AxiosResponse<T>> {\n const fullUrl = this.baseUrl ? `${this.baseUrl}${url}` : url;\n return axios.post<T>(fullUrl, data, config);\n }\n\n /**\n * 发送 GET 请求\n * @param url 请求地址\n * @param config 额外配置\n * @returns Promise\n */\n async get<T = any>(\n url: string,\n config?: AxiosRequestConfig\n ): Promise<AxiosResponse<T>> {\n const fullUrl = this.baseUrl ? `${this.baseUrl}${url}` : url;\n return axios.get<T>(fullUrl, config);\n }\n}\n\n/**\n * 验签接口请求\n * @param baseUrl 基础 URL\n * @param data 验签数据\n * @returns 验签结果\n */\nexport async function verifyTokenSign(\n baseUrl: string,\n data: {\n appId: string;\n sign: string;\n timestamp: number;\n }\n): Promise<boolean> {\n try {\n const client = new HttpClient(baseUrl);\n const response = await client.post<{ data: boolean }>(\n '/onlyoffice/token/verifyTokenSign',\n data\n );\n return response.data?.data === true;\n } catch (error) {\n console.error('验签请求失败:', error);\n return false;\n }\n}\n\n/**\n * 保存操作信息\n * @param callbackUrl 回调地址\n * @param data 操作数据\n */\nexport async function saveSuccessInfo(\n callbackUrl: string,\n data: {\n status: number;\n key: string;\n userdata: string;\n }\n): Promise<void> {\n try {\n await axios.post(callbackUrl, data);\n } catch (error) {\n console.error('保存操作信息失败:', error);\n }\n}","import EventEmitter from 'eventemitter3';\nimport type {\n DocumentConfig,\n EditorConfig,\n DocumentPermissions,\n OfficeEventType,\n OfficeCallback,\n OfficeEditorInstance,\n OfficeDocumentConfig,\n OfficeInitConfig,\n AuthConfig,\n VerifyTokenSignFunction,\n} from '../types';\nimport { getDocumentType, isSupportedFileType } from './utils/fileType';\nimport { verifyTokenSign, saveSuccessInfo } from './utils/http';\n\n/**\n * 默认文档权限\n */\nconst DEFAULT_PERMISSIONS: DocumentPermissions = {\n comment: false,\n download: false,\n edit: false,\n print: true,\n review: false,\n editCommentAuthorOnly: false,\n fillForms: false,\n modifyContentControl: false,\n};\n\n/**\n * OnlyOffice 编辑器管理类\n */\nexport class OfficeEditor implements OfficeEditorInstance {\n private editor: any = null;\n private editorId: string;\n private emitter: EventEmitter;\n private documentConfig: DocumentConfig;\n private editorConfig: EditorConfig;\n private callback: OfficeCallback | null = null;\n private height: string = '100%';\n private width: string = '100%';\n\n constructor() {\n this.editorId = `editor-${Date.now().toString(32)}`;\n this.emitter = new EventEmitter();\n this.documentConfig = {\n fileType: 'docx',\n key: '',\n url: '',\n title: '',\n permissions: { ...DEFAULT_PERMISSIONS },\n };\n this.editorConfig = {\n lang: 'zh',\n user: { id: '', name: '' },\n };\n }\n\n /**\n * 配置文档参数\n */\n configure(config: OfficeDocumentConfig): void {\n if (config.height) this.height = config.height;\n if (config.width) this.width = config.width;\n\n if (config.fileType) {\n if (!isSupportedFileType(config.fileType)) {\n throw new Error(`不支持的文件类型: ${config.fileType}`);\n }\n const docType = getDocumentType(config.fileType);\n if (docType !== 'other') {\n this.documentConfig.fileType = config.fileType;\n }\n }\n\n if (config.key) this.documentConfig.key = config.key;\n if (config.url) this.documentConfig.url = config.url;\n if (config.title) this.documentConfig.title = config.title;\n\n if (config.permissions) {\n this.documentConfig.permissions = {\n ...this.documentConfig.permissions,\n ...config.permissions,\n };\n\n // PDF 文件特殊处理\n if (this.documentConfig.fileType === 'pdf') {\n this.documentConfig.permissions.edit = false;\n this.documentConfig.permissions.review = false;\n this.editorConfig.mode = 'view';\n }\n }\n\n if (config.callbackUrl) this.editorConfig.callbackUrl = config.callbackUrl;\n if (config.userId) {\n this.editorConfig.user = {\n ...this.editorConfig.user,\n id: config.userId,\n };\n }\n if (config.userName) {\n this.editorConfig.user = {\n ...this.editorConfig.user,\n name: config.userName,\n };\n }\n if (config.userGroup) {\n this.editorConfig.user = {\n ...this.editorConfig.user,\n group: config.userGroup,\n };\n }\n }\n\n /**\n * 初始化编辑器(带验签)\n */\n async initOffice(config: OfficeInitConfig): Promise<OfficeEditorInstance> {\n const { dom, officeApiUrl, callback, auth, verifyFunction } = config;\n\n if (callback) this.callback = callback;\n\n // 验签逻辑\n if (auth) {\n let verified = false;\n\n if (verifyFunction) {\n // 使用自定义验签函数\n verified = await verifyFunction(auth);\n } else if (auth.verifyUrl) {\n // 使用自定义验签地址\n verified = await verifyTokenSign(auth.verifyUrl, {\n appId: auth.appId,\n sign: auth.sign,\n timestamp: auth.timestamp,\n });\n } else {\n throw new Error('使用验签配置时,必须提供 verifyFunction 或 verifyUrl');\n }\n\n if (!verified) {\n throw new Error('验签失败,请检查验签配置');\n }\n }\n\n return this.createEditor(dom, officeApiUrl);\n }\n\n /**\n * 简化初始化(无验签)\n */\n init(\n dom: HTMLElement,\n officeApiUrl: string,\n callback?: OfficeCallback\n ): OfficeEditorInstance {\n if (callback) this.callback = callback;\n return this.createEditor(dom, officeApiUrl);\n }\n\n /**\n * 创建编辑器实例\n */\n private createEditor(dom: HTMLElement, officeApiUrl: string): OfficeEditorInstance {\n if (!dom) {\n throw new Error('必须提供挂载的 DOM 元素');\n }\n\n if (!officeApiUrl) {\n throw new Error('必须提供 OnlyOffice API 脚本地址');\n }\n\n // 设置容器样式\n dom.style.position = 'relative';\n\n // 创建编辑器容器\n const mainDiv = document.createElement('div');\n mainDiv.id = this.editorId;\n mainDiv.style.height = '100%';\n mainDiv.style.width = '100%';\n dom.appendChild(mainDiv);\n\n // 动态加载 OnlyOffice API 脚本\n const scriptId = `script-${this.editorId}`;\n const existingScript = document.querySelector(`#${scriptId}`);\n\n if (!existingScript) {\n const script = document.createElement('script');\n script.id = scriptId;\n script.src = officeApiUrl;\n script.onload = () => this.instantiateEditor();\n document.head.appendChild(script);\n } else {\n this.instantiateEditor();\n }\n\n return this;\n }\n\n /**\n * 实例化编辑器\n */\n private instantiateEditor(): void {\n // 销毁现有实例\n if (this.editor) {\n this.editor.destroyEditor();\n this.editor = null;\n }\n\n // 构建配置对象\n const config = {\n width: this.width,\n height: this.height,\n documentType: this.getDocumentType(),\n document: this.documentConfig,\n editorConfig: this.editorConfig,\n events: this.createEventHandlers(),\n };\n\n // 创建编辑器实例\n this.editor = new window.DocsAPI.DocEditor(this.editorId, config);\n }\n\n /**\n * 获取文档类型\n */\n private getDocumentType(): string {\n const type = getDocumentType(this.documentConfig.fileType);\n return type === 'other' ? 'word' : type;\n }\n\n /**\n * 创建事件处理器\n */\n private createEventHandlers(): Record<string, (event: any) => void> {\n return {\n onDocumentStateChange: (event: any) => {\n this.emitter.emit('documentStateChange', event);\n },\n onDocumentReady: () => {\n console.log('Document is loaded');\n // 通知后端文档加载成功\n if (this.editorConfig.callbackUrl) {\n saveSuccessInfo(this.editorConfig.callbackUrl, {\n status: 8,\n key: this.documentConfig.key,\n userdata: JSON.stringify({\n appUserId: this.editorConfig.user?.id,\n }),\n });\n }\n this.callback?.('onDocumentReady');\n this.emitter.emit('onDocumentReady');\n },\n onInfo: (event: any) => {\n console.log('ONLYOFFICE Document Editor is opened in mode', event.data.mode);\n this.callback?.('onInfo', event.data);\n this.emitter.emit('onInfo', event);\n },\n onError: (event: any) => {\n console.error('ONLYOFFICE Error:', event.data.errorCode, event.data.errorDescription);\n this.emitter.emit('onError', event);\n },\n onRequestHistory: (event: any) => {\n this.callback?.('onRequestHistory', event, this.editor);\n this.emitter.emit('onRequestHistory', { event, editor: this.editor });\n },\n onRequestHistoryData: (event: any) => {\n this.callback?.('onRequestHistoryData', event, this.editor);\n this.emitter.emit('onRequestHistoryData', { event, editor: this.editor });\n },\n onRequestHistoryClose: (event: any) => {\n this.callback?.('onRequestHistoryClose', event, this.editor);\n this.emitter.emit('onRequestHistoryClose', { event, editor: this.editor });\n },\n onRequestRestore: (event: any) => {\n this.callback?.('onRequestRestore', event, this.editor);\n this.emitter.emit('onRequestRestore', { event, editor: this.editor });\n },\n onRequestSendNotify: (event: any) => {\n console.log('onRequestSendNotify', event);\n this.emitter.emit('onRequestSendNotify', event);\n },\n onRequestUsers: (event: any) => {\n console.log('onRequestUsers', event);\n this.emitter.emit('onRequestUsers', event);\n },\n };\n }\n\n /**\n * 监听事件\n */\n on(event: OfficeEventType, callback: (...args: any[]) => void): void {\n this.emitter.on(event, callback);\n }\n\n /**\n * 移除事件监听\n */\n off(event: OfficeEventType, callback: (...args: any[]) => void): void {\n this.emitter.off(event, callback);\n }\n\n /**\n * 获取当前配置\n */\n getConfig(): DocumentConfig & EditorConfig {\n return {\n ...this.documentConfig,\n ...this.editorConfig,\n };\n }\n\n /**\n * 获取内部编辑器实例\n */\n getEditor(): any {\n return this.editor;\n }\n\n /**\n * 销毁编辑器\n */\n destroy(): void {\n if (this.editor) {\n this.editor.destroyEditor();\n this.editor = null;\n }\n this.emitter.removeAllListeners();\n this.callback = null;\n }\n}","export { OfficeEditor } from './editor';\nexport { getDocumentType, isSupportedFileType } from './utils/fileType';\nexport { HttpClient, verifyTokenSign, saveSuccessInfo } from './utils/http';\n\n// 导出类型\nexport type {\n DocumentType,\n FileType,\n DocumentPermissions,\n UserInfo,\n DocumentConfig,\n EditorConfig,\n AuthConfig,\n VerifyTokenSignFunction,\n OfficeInitConfig,\n OfficeDocumentConfig,\n OfficeEventType,\n OfficeCallbackType,\n OfficeCallback,\n OfficeEditorInstance,\n OfficeSDK,\n} from '../types';\n\nimport { OfficeEditor } from './editor';\nimport type {\n OfficeDocumentConfig,\n OfficeInitConfig,\n OfficeCallback,\n OfficeEventType,\n OfficeEditorInstance,\n} from '../types';\n\n/**\n * 创建 Office 编辑器实例\n * @returns OfficeEditor 实例\n */\nexport function createOfficeEditor(): OfficeEditor {\n return new OfficeEditor();\n}\n\n/**\n * 快速初始化 Office 编辑器\n * @param config 初始化配置\n * @returns Promise<OfficeEditorInstance>\n */\nexport async function initOffice(config: OfficeInitConfig): Promise<OfficeEditorInstance> {\n const editor = new OfficeEditor();\n return editor.initOffice(config);\n}\n\n/**\n * 简化初始化(无验签)\n * @param dom 挂载的 DOM 元素\n * @param officeApiUrl OnlyOffice API 地址\n * @param callback 事件回调\n * @returns OfficeEditorInstance\n */\nexport function init(\n dom: HTMLElement,\n officeApiUrl: string,\n callback?: OfficeCallback\n): OfficeEditorInstance {\n const editor = new OfficeEditor();\n return editor.init(dom, officeApiUrl, callback);\n}\n\n/**\n * 配置文档参数(全局配置,需要先创建编辑器实例)\n * @deprecated 建议使用 OfficeEditor.configure() 方法\n */\nexport function config(_config: OfficeDocumentConfig): void {\n console.warn('此方法已废弃,请使用 OfficeEditor.configure() 方法');\n}\n\n/**\n * 销毁编辑器(全局方法,需要先创建编辑器实例)\n * @deprecated 建议使用 OfficeEditor.destroy() 方法\n */\nexport function destroy(): void {\n console.warn('此方法已废弃,请使用 OfficeEditor.destroy() 方法');\n}\n\n/**\n * 监听事件(全局方法,需要先创建编辑器实例)\n * @deprecated 建议使用 OfficeEditor.on() 方法\n */\nexport function on(_event: OfficeEventType, _callback: (...args: any[]) => void): void {\n console.warn('此方法已废弃,请使用 OfficeEditor.on() 方法');\n}\n\n/**\n * 记录分享动作\n * @param callbackUrl 回调地址\n * @param fileKey 文件标识\n * @param appUserId 用户 ID\n */\nexport async function shareSave(\n callbackUrl: string,\n fileKey: string,\n appUserId: string\n): Promise<void> {\n const { saveSuccessInfo } = await import('./utils/http');\n await saveSuccessInfo(callbackUrl, {\n status: 10,\n key: fileKey,\n userdata: JSON.stringify({ appUserId }),\n });\n}\n\n/**\n * 记录下载动作\n * @param callbackUrl 回调地址\n * @param fileKey 文件标识\n * @param appUserId 用户 ID\n */\nexport async function downloadSave(\n callbackUrl: string,\n fileKey: string,\n appUserId: string\n): Promise<void> {\n const { saveSuccessInfo } = await import('./utils/http');\n await saveSuccessInfo(callbackUrl, {\n status: 9,\n key: fileKey,\n userdata: JSON.stringify({ appUserId }),\n });\n}"],"names":["getDocumentType","fileType","type","toLowerCase","includes","isSupportedFileType","HttpClient","constructor","baseUrl","this","post","url","data","config","fullUrl","axios","get","async","verifyTokenSign","client","_a","error","console","saveSuccessInfo","callbackUrl","DEFAULT_PERMISSIONS","comment","download","edit","print","review","editCommentAuthorOnly","fillForms","modifyContentControl","OfficeEditor","editor","callback","height","width","editorId","Date","now","toString","emitter","EventEmitter","documentConfig","key","title","permissions","editorConfig","lang","user","id","name","configure","Error","mode","userId","userName","userGroup","group","initOffice","dom","officeApiUrl","auth","verifyFunction","verified","verifyUrl","appId","sign","timestamp","createEditor","init","style","position","mainDiv","document","createElement","appendChild","scriptId","querySelector","instantiateEditor","script","src","onload","head","destroyEditor","documentType","events","createEventHandlers","window","DocsAPI","DocEditor","onDocumentStateChange","event","emit","onDocumentReady","log","status","userdata","JSON","stringify","appUserId","_b","call","onInfo","onError","errorCode","errorDescription","onRequestHistory","onRequestHistoryData","onRequestHistoryClose","onRequestRestore","onRequestSendNotify","onRequestUsers","on","off","getConfig","getEditor","destroy","removeAllListeners","_config","warn","fileKey","Promise","resolve","then","http","_event","_callback"],"mappings":"+DAOM,SAAUA,EAAgBC,GAC9B,MAAMC,EAAOD,EAASE,cAItB,GADkB,CAAC,MAAO,OAAQ,MAAO,MAAO,MAAO,OAAQ,QACjDC,SAASF,GACrB,MAAO,OAK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xF,CACb,6BAyCEZ,QAAQoG,KAAK,uCACf,uBAmCOzG,eACLO,EACAmG,EACArB,GAEA,MAAM/E,gBAAEA,SAA0BqG,QAAAC,UAAAC,KAAA,WAAA,OAAAC,CAAA,SAC5BxG,EAAgBC,EAAa,CACjC0E,OAAQ,EACRpD,IAAK6E,EACLxB,SAAUC,KAAKC,UAAU,CAAEC,eAE/B,kDApEExC,EACAC,EACA3B,GAGA,OADe,IAAIF,GACLsC,KAAKV,EAAKC,EAAc3B,EACxC,qBAnBOnB,eAA0BJ,GAE/B,OADe,IAAIqB,GACL2B,WAAWhD,EAC3B,2CAsCM,SAAamH,EAAyBC,GAC1C3G,QAAQoG,KAAK,kCACf,8CAQOzG,eACLO,EACAmG,EACArB,GAEA,MAAM/E,gBAAEA,SAA0BqG,QAAAC,UAAAC,KAAA,WAAA,OAAAC,CAAA,SAC5BxG,EAAgBC,EAAa,CACjC0E,OAAQ,GACRpD,IAAK6E,EACLxB,SAAUC,KAAKC,UAAU,CAAEC,eAE/B"}
@@ -0,0 +1,2 @@
1
+ "use strict";var e=require("react/jsx-runtime"),t=require("react"),i=require("eventemitter3"),o=require("axios");function r(e){const t=e.toLowerCase();if(["doc","docx","odt","rtf","txt","html","epub"].includes(t))return"word";if(["xls","xlsx","ods","csv"].includes(t))return"cell";return["ppt","pptx","odp"].includes(t)?"slide":"pdf"===t?"pdf":"other"}class n{constructor(e=""){this.baseUrl=e}async post(e,t,i){const r=this.baseUrl?`${this.baseUrl}${e}`:e;return o.post(r,t,i)}async get(e,t){const i=this.baseUrl?`${this.baseUrl}${e}`:e;return o.get(i,t)}}async function s(e,t){var i;try{const o=new n(e);return!0===(null===(i=(await o.post("/onlyoffice/token/verifyTokenSign",t)).data)||void 0===i?void 0:i.data)}catch(e){return console.error("验签请求失败:",e),!1}}async function c(e,t){try{await o.post(e,t)}catch(e){console.error("保存操作信息失败:",e)}}var l=Object.freeze({__proto__:null,HttpClient:n,saveSuccessInfo:c,verifyTokenSign:s});const a={comment:!1,download:!1,edit:!1,print:!0,review:!1,editCommentAuthorOnly:!1,fillForms:!1,modifyContentControl:!1};class u{constructor(){this.editor=null,this.callback=null,this.height="100%",this.width="100%",this.editorId=`editor-${Date.now().toString(32)}`,this.emitter=new i,this.documentConfig={fileType:"docx",key:"",url:"",title:"",permissions:{...a}},this.editorConfig={lang:"zh",user:{id:"",name:""}}}configure(e){if(e.height&&(this.height=e.height),e.width&&(this.width=e.width),e.fileType){if("other"===r(e.fileType))throw new Error(`不支持的文件类型: ${e.fileType}`);"other"!==r(e.fileType)&&(this.documentConfig.fileType=e.fileType)}e.key&&(this.documentConfig.key=e.key),e.url&&(this.documentConfig.url=e.url),e.title&&(this.documentConfig.title=e.title),e.permissions&&(this.documentConfig.permissions={...this.documentConfig.permissions,...e.permissions},"pdf"===this.documentConfig.fileType&&(this.documentConfig.permissions.edit=!1,this.documentConfig.permissions.review=!1,this.editorConfig.mode="view")),e.callbackUrl&&(this.editorConfig.callbackUrl=e.callbackUrl),e.userId&&(this.editorConfig.user={...this.editorConfig.user,id:e.userId}),e.userName&&(this.editorConfig.user={...this.editorConfig.user,name:e.userName}),e.userGroup&&(this.editorConfig.user={...this.editorConfig.user,group:e.userGroup})}async initOffice(e){const{dom:t,officeApiUrl:i,callback:o,auth:r,verifyFunction:n}=e;if(o&&(this.callback=o),r){let e=!1;if(n)e=await n(r);else{if(!r.verifyUrl)throw new Error("使用验签配置时,必须提供 verifyFunction 或 verifyUrl");e=await s(r.verifyUrl,{appId:r.appId,sign:r.sign,timestamp:r.timestamp})}if(!e)throw new Error("验签失败,请检查验签配置")}return this.createEditor(t,i)}init(e,t,i){return i&&(this.callback=i),this.createEditor(e,t)}createEditor(e,t){if(!e)throw new Error("必须提供挂载的 DOM 元素");if(!t)throw new Error("必须提供 OnlyOffice API 脚本地址");e.style.position="relative";const i=document.createElement("div");i.id=this.editorId,i.style.height="100%",i.style.width="100%",e.appendChild(i);const o=`script-${this.editorId}`;if(document.querySelector(`#${o}`))this.instantiateEditor();else{const e=document.createElement("script");e.id=o,e.src=t,e.onload=()=>this.instantiateEditor(),document.head.appendChild(e)}return this}instantiateEditor(){this.editor&&(this.editor.destroyEditor(),this.editor=null);const e={width:this.width,height:this.height,documentType:this.getDocumentType(),document:this.documentConfig,editorConfig:this.editorConfig,events:this.createEventHandlers()};this.editor=new window.DocsAPI.DocEditor(this.editorId,e)}getDocumentType(){const e=r(this.documentConfig.fileType);return"other"===e?"word":e}createEventHandlers(){return{onDocumentStateChange:e=>{this.emitter.emit("documentStateChange",e)},onDocumentReady:()=>{var e,t;console.log("Document is loaded"),this.editorConfig.callbackUrl&&c(this.editorConfig.callbackUrl,{status:8,key:this.documentConfig.key,userdata:JSON.stringify({appUserId:null===(e=this.editorConfig.user)||void 0===e?void 0:e.id})}),null===(t=this.callback)||void 0===t||t.call(this,"onDocumentReady"),this.emitter.emit("onDocumentReady")},onInfo:e=>{var t;console.log("ONLYOFFICE Document Editor is opened in mode",e.data.mode),null===(t=this.callback)||void 0===t||t.call(this,"onInfo",e.data),this.emitter.emit("onInfo",e)},onError:e=>{console.error("ONLYOFFICE Error:",e.data.errorCode,e.data.errorDescription),this.emitter.emit("onError",e)},onRequestHistory:e=>{var t;null===(t=this.callback)||void 0===t||t.call(this,"onRequestHistory",e,this.editor),this.emitter.emit("onRequestHistory",{event:e,editor:this.editor})},onRequestHistoryData:e=>{var t;null===(t=this.callback)||void 0===t||t.call(this,"onRequestHistoryData",e,this.editor),this.emitter.emit("onRequestHistoryData",{event:e,editor:this.editor})},onRequestHistoryClose:e=>{var t;null===(t=this.callback)||void 0===t||t.call(this,"onRequestHistoryClose",e,this.editor),this.emitter.emit("onRequestHistoryClose",{event:e,editor:this.editor})},onRequestRestore:e=>{var t;null===(t=this.callback)||void 0===t||t.call(this,"onRequestRestore",e,this.editor),this.emitter.emit("onRequestRestore",{event:e,editor:this.editor})},onRequestSendNotify:e=>{console.log("onRequestSendNotify",e),this.emitter.emit("onRequestSendNotify",e)},onRequestUsers:e=>{console.log("onRequestUsers",e),this.emitter.emit("onRequestUsers",e)}}}on(e,t){this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}getConfig(){return{...this.documentConfig,...this.editorConfig}}getEditor(){return this.editor}destroy(){this.editor&&(this.editor.destroyEditor(),this.editor=null),this.emitter.removeAllListeners(),this.callback=null}}exports.OnlyOfficeEditor=({officeApiUrl:i,document:o,auth:r,verifyFunction:n,height:s="100%",width:c="100%",onReady:l,onError:a,onDocumentStateChange:d,onRequestHistory:h,onRequestHistoryData:f,onRequestHistoryClose:m,onRequestRestore:y})=>{const p=t.useRef(null),g=t.useRef(null),[v,C]=t.useState(!1),[w,R]=t.useState(null),k=t.useCallback(async()=>{if(p.current)try{const e=new u;e.configure({...o,height:s,width:c});const t=(e,t,i)=>{switch(e){case"onDocumentReady":C(!0),null==l||l(i);break;case"onInfo":break;case"onRequestHistory":null==h||h({event:t,editor:i});break;case"onRequestHistoryData":null==f||f({event:t,editor:i});break;case"onRequestHistoryClose":null==m||m({event:t,editor:i});break;case"onRequestRestore":null==y||y({event:t,editor:i})}},v={dom:p.current,officeApiUrl:i,callback:t,auth:r,verifyFunction:n};g.current=await e.initOffice(v),e.on("onError",e=>{var t;const i=(null===(t=e.data)||void 0===t?void 0:t.errorDescription)||"编辑器错误";R(i),null==a||a(e)}),e.on("documentStateChange",e=>{null==d||d(e)})}catch(e){const t=e.message||"初始化失败";R(t),null==a||a(e)}},[i,o,s,c,r,n,l,a,d,h,f,m,y]),b=t.useCallback(()=>{g.current&&(g.current.destroy(),g.current=null,C(!1))},[]);return t.useEffect(()=>(k(),()=>{b()}),[k,b]),t.useEffect(()=>{g.current&&o&&(b(),k())},[o,b,k]),e.jsxs("div",{className:"onlyoffice-editor-container",style:{width:"100%",height:"100%",position:"relative"},children:[e.jsx("div",{ref:p,style:{width:"100%",height:"100%"}}),w&&e.jsx("div",{className:"onlyoffice-error",style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",color:"red"},children:w})]})},exports.createOfficeEditor=function(){return new u},exports.downloadSave=async function(e,t,i){const{saveSuccessInfo:o}=await Promise.resolve().then(function(){return l});await o(e,{status:9,key:t,userdata:JSON.stringify({appUserId:i})})},exports.init=function(e,t,i){return(new u).init(e,t,i)},exports.initOffice=async function(e){return(new u).initOffice(e)},exports.shareSave=async function(e,t,i){const{saveSuccessInfo:o}=await Promise.resolve().then(function(){return l});await o(e,{status:10,key:t,userdata:JSON.stringify({appUserId:i})})},exports.useOnlyOffice=function(e){const{officeApiUrl:i,document:o,auth:r,verifyFunction:n,height:s="100%",width:c="100%",autoInit:l=!0,onReady:a,onError:d}=e,h=t.useRef(null),f=t.useRef(null),m=t.useRef(null),[y,p]=t.useState(!1),[g,v]=t.useState(null),C=t.useCallback(async()=>{if(h.current)try{w();const e=new u;f.current=e,e.configure({...o,height:s,width:c});const t=(e,t,i)=>{if("onDocumentReady"===e)p(!0),null==a||a(i)},l={dom:h.current,officeApiUrl:i,callback:t,auth:r,verifyFunction:n};m.current=await e.initOffice(l),e.on("onError",e=>{var t;const i=(null===(t=e.data)||void 0===t?void 0:t.errorDescription)||"编辑器错误";v(i),null==d||d(e)})}catch(e){const t=e.message||"初始化失败";v(t),null==d||d(e)}else v("容器元素未找到")},[i,o,s,c,r,n,a,d]),w=t.useCallback(()=>{f.current&&(f.current.destroy(),f.current=null,m.current=null,p(!1))},[]),R=t.useCallback(async()=>{w(),await C()},[w,C]),k=t.useCallback((e,t)=>{f.current&&f.current.on(e,t)},[]),b=t.useCallback((e,t)=>{f.current&&f.current.off(e,t)},[]);return t.useEffect(()=>(l&&C(),()=>{w()}),[l,C,w]),t.useEffect(()=>{f.current&&o&&R()},[o,R]),{containerRef:h,editorInstance:m.current,isReady:y,error:g,init:C,destroy:w,reinit:R,on:k,off:b}};
2
+ //# sourceMappingURL=index.cjs.map