@chao194/office 1.0.2 → 1.0.4
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/dist/cjs/core/index.cjs +1 -1
- package/dist/cjs/core/index.cjs.map +1 -1
- package/dist/cjs/react/index.cjs +1 -1
- package/dist/cjs/react/index.cjs.map +1 -1
- package/dist/cjs/vue2/index.cjs +1 -1
- package/dist/cjs/vue2/index.cjs.map +1 -1
- package/dist/cjs/vue3/index.cjs +1 -1
- package/dist/cjs/vue3/index.cjs.map +1 -1
- package/dist/esm/core/index.mjs +1 -1
- package/dist/esm/core/index.mjs.map +1 -1
- package/dist/esm/react/index.mjs +1 -1
- package/dist/esm/react/index.mjs.map +1 -1
- package/dist/esm/vue2/index.mjs +1 -1
- package/dist/esm/vue2/index.mjs.map +1 -1
- package/dist/esm/vue3/index.mjs +1 -1
- package/dist/esm/vue3/index.mjs.map +1 -1
- package/dist/types/core/editor.d.ts.map +1 -1
- package/dist/types/vue3/component.d.ts.map +1 -1
- package/dist/umd/index.js +1 -1
- package/dist/umd/index.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","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","createOfficeEditor","_config","warn","_event","_callback","shareSave","fileKey","Promise","resolve","then","http","downloadSave"],"mappings":"kDAOM,SAAUA,EAAgBC,GAC9B,MAAMC,EAAOD,EAASE,cAItB,GADkB,CAAC,MAAO,OAAQ,MAAO,MAAO,MAAO,OAAQ,QACjDC,SAASF,GACrB,MAAO,OAKT,GADkB,CAAC,MAAO,OAAQ,MAAO,OAC3BE,SAASF,GACrB,MAAO,OAKT,MADmB,CAAC,MAAO,OAAQ,OACpBE,SAASF,GACf,QAII,QAATA,EACK,MAGF,OACT,CAOM,SAAUG,EAAoBJ,GAClC,MAAqC,UAA9B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IACdjG,QAAQqG,KAAK,uCACf,CAMM,SAAUR,EAAGS,EAAyBC,GAC1CvG,QAAQqG,KAAK,kCACf,CAQO1G,eAAe6G,EACpBtG,EACAuG,EACAzB,GAEA,MAAM/E,gBAAEA,SAA0ByG,QAAAC,UAAAC,KAAA,WAAA,OAAAC,CAAA,SAC5B5G,EAAgBC,EAAa,CACjC0E,OAAQ,GACRpD,IAAKiF,EACL5B,SAAUC,KAAKC,UAAU,CAAEC,eAE/B,CAQOrF,eAAemH,EACpB5G,EACAuG,EACAzB,GAEA,MAAM/E,gBAAEA,SAA0ByG,QAAAC,UAAAC,KAAA,WAAA,OAAAC,CAAA,SAC5B5G,EAAgBC,EAAa,CACjC0E,OAAQ,EACRpD,IAAKiF,EACL5B,SAAUC,KAAKC,UAAU,CAAEC,eAE/B"}
|
|
1
|
+
{"version":3,"file":"index.mjs","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 console.log('[OnlyOffice] createEditor called', { dom, officeApiUrl });\n\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 console.log('[OnlyOffice] DOM dimensions:', { width: dom.offsetWidth, height: dom.offsetHeight });\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 console.log('[OnlyOffice] Loading script:', officeApiUrl);\n const script = document.createElement('script');\n script.id = scriptId;\n script.src = officeApiUrl;\n script.onload = () => {\n console.log('[OnlyOffice] Script loaded successfully');\n console.log('[OnlyOffice] window.DocsAPI:', window.DocsAPI);\n this.instantiateEditor();\n };\n script.onerror = (err) => {\n console.error('[OnlyOffice] Script load failed:', err);\n };\n document.head.appendChild(script);\n } else {\n console.log('[OnlyOffice] Script already loaded');\n this.instantiateEditor();\n }\n\n return this;\n }\n\n /**\n * 实例化编辑器\n */\n private instantiateEditor(): void {\n console.log('[OnlyOffice] instantiateEditor called');\n\n // 销毁现有实例\n if (this.editor) {\n this.editor.destroyEditor();\n this.editor = null;\n }\n\n // 检查 DocsAPI 是否可用\n if (!window.DocsAPI || !window.DocsAPI.DocEditor) {\n console.error('[OnlyOffice] window.DocsAPI.DocEditor is not available');\n return;\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 console.log('[OnlyOffice] Creating editor with config:', config);\n console.log('[OnlyOffice] Editor container ID:', this.editorId);\n console.log('[OnlyOffice] Container element:', document.getElementById(this.editorId));\n\n // 创建编辑器实例\n try {\n this.editor = new window.DocsAPI.DocEditor(this.editorId, config);\n console.log('[OnlyOffice] Editor created successfully:', this.editor);\n } catch (err) {\n console.error('[OnlyOffice] Error creating editor:', err);\n }\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","log","style","position","offsetWidth","offsetHeight","mainDiv","document","createElement","appendChild","scriptId","querySelector","instantiateEditor","script","src","onload","window","DocsAPI","onerror","err","head","destroyEditor","DocEditor","documentType","events","createEventHandlers","getElementById","onDocumentStateChange","event","emit","onDocumentReady","status","userdata","JSON","stringify","appUserId","_b","call","onInfo","onError","errorCode","errorDescription","onRequestHistory","onRequestHistoryData","onRequestHistoryClose","onRequestRestore","onRequestSendNotify","onRequestUsers","on","off","getConfig","getEditor","destroy","removeAllListeners","createOfficeEditor","_config","warn","_event","_callback","shareSave","fileKey","Promise","resolve","then","http","downloadSave"],"mappings":"kDAOM,SAAUA,EAAgBC,GAC9B,MAAMC,EAAOD,EAASE,cAItB,GADkB,CAAC,MAAO,OAAQ,MAAO,MAAO,MAAO,OAAQ,QACjDC,SAASF,GACrB,MAAO,OAKT,GADkB,CAAC,MAAO,OAAQ,MAAO,OAC3BE,SAASF,GACrB,MAAO,OAKT,MADmB,CAAC,MAAO,OAAQ,OACpBE,SAASF,GACf,QAII,QAATA,EACK,MAGF,OACT,CAOM,SAAUG,EAAoBJ,GAClC,MAAqC,UAA9BD,EAAgBC,EACzB,OCtCaK,EAGX,WAAAC,CAAYC,EAAkB,IAC5BC,KAAKD,QAAUA,CACjB,CASA,UAAME,CACJC,EACAC,EACAC,GAEA,MAAMC,EAAUL,KAAKD,QAAU,GAAGC,KAAKD,UAAUG,IAAQA,EACzD,OAAOI,EAAML,KAAQI,EAASF,EAAMC,EACtC,CAQA,SAAMG,CACJL,EACAE,GAEA,MAAMC,EAAUL,KAAKD,QAAU,GAAGC,KAAKD,UAAUG,IAAQA,EACzD,OAAOI,EAAMC,IAAOF,EAASD,EAC/B,EASKI,eAAeC,EACpBV,EACAI,SAMA,IACE,MAAMO,EAAS,IAAIb,EAAWE,GAK9B,OAA+B,KAAX,iBAJGW,EAAOT,KAC5B,oCACAE,IAEcA,YAAI,IAAAQ,OAAA,EAAAA,EAAER,KACxB,CAAE,MAAOS,GAEP,OADAC,QAAQD,MAAM,UAAWA,IAClB,CACT,CACF,CAOOJ,eAAeM,EACpBC,EACAZ,GAMA,UACQG,EAAML,KAAKc,EAAaZ,EAChC,CAAE,MAAOS,GACPC,QAAQD,MAAM,YAAaA,EAC7B,CACF,wFCrEA,MAAMI,EAA2C,CAC/CC,SAAS,EACTC,UAAU,EACVC,MAAM,EACNC,OAAO,EACPC,QAAQ,EACRC,uBAAuB,E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QAAAC,UAAAC,KAAA,WAAA,OAAAC,CAAA,SAC5BjH,EAAgBC,EAAa,CACjC+E,OAAQ,GACRzD,IAAKsF,EACL5B,SAAUC,KAAKC,UAAU,CAAEC,eAE/B,CAQO1F,eAAewH,EACpBjH,EACA4G,EACAzB,GAEA,MAAMpF,gBAAEA,SAA0B8G,QAAAC,UAAAC,KAAA,WAAA,OAAAC,CAAA,SAC5BjH,EAAgBC,EAAa,CACjC+E,OAAQ,EACRzD,IAAKsF,EACL5B,SAAUC,KAAKC,UAAU,CAAEC,eAE/B"}
|
package/dist/esm/react/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{jsxs as
|
|
1
|
+
import{jsxs as e,jsx as t}from"react/jsx-runtime";import{useRef as i,useState as o,useCallback as r,useEffect as n}from"react";import s from"eventemitter3";import c from"axios";function l(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 a{constructor(e=""){this.baseUrl=e}async post(e,t,i){const o=this.baseUrl?`${this.baseUrl}${e}`:e;return c.post(o,t,i)}async get(e,t){const i=this.baseUrl?`${this.baseUrl}${e}`:e;return c.get(i,t)}}async function d(e,t){var i;try{const o=new a(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 u(e,t){try{await c.post(e,t)}catch(e){console.error("保存操作信息失败:",e)}}var f=Object.freeze({__proto__:null,HttpClient:a,saveSuccessInfo:u,verifyTokenSign:d});const h={comment:!1,download:!1,edit:!1,print:!0,review:!1,editCommentAuthorOnly:!1,fillForms:!1,modifyContentControl:!1};class y{constructor(){this.editor=null,this.callback=null,this.height="100%",this.width="100%",this.editorId=`editor-${Date.now().toString(32)}`,this.emitter=new s,this.documentConfig={fileType:"docx",key:"",url:"",title:"",permissions:{...h}},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"===l(e.fileType))throw new Error(`不支持的文件类型: ${e.fileType}`);"other"!==l(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 d(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(console.log("[OnlyOffice] createEditor called",{dom:e,officeApiUrl:t}),!e)throw new Error("必须提供挂载的 DOM 元素");if(!t)throw new Error("必须提供 OnlyOffice API 脚本地址");e.style.position="relative",console.log("[OnlyOffice] DOM dimensions:",{width:e.offsetWidth,height:e.offsetHeight});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}`))console.log("[OnlyOffice] Script already loaded"),this.instantiateEditor();else{console.log("[OnlyOffice] Loading script:",t);const e=document.createElement("script");e.id=o,e.src=t,e.onload=()=>{console.log("[OnlyOffice] Script loaded successfully"),console.log("[OnlyOffice] window.DocsAPI:",window.DocsAPI),this.instantiateEditor()},e.onerror=e=>{console.error("[OnlyOffice] Script load failed:",e)},document.head.appendChild(e)}return this}instantiateEditor(){if(console.log("[OnlyOffice] instantiateEditor called"),this.editor&&(this.editor.destroyEditor(),this.editor=null),!window.DocsAPI||!window.DocsAPI.DocEditor)return void console.error("[OnlyOffice] window.DocsAPI.DocEditor is not available");const e={width:this.width,height:this.height,documentType:this.getDocumentType(),document:this.documentConfig,editorConfig:this.editorConfig,events:this.createEventHandlers()};console.log("[OnlyOffice] Creating editor with config:",e),console.log("[OnlyOffice] Editor container ID:",this.editorId),console.log("[OnlyOffice] Container element:",document.getElementById(this.editorId));try{this.editor=new window.DocsAPI.DocEditor(this.editorId,e),console.log("[OnlyOffice] Editor created successfully:",this.editor)}catch(e){console.error("[OnlyOffice] Error creating editor:",e)}}getDocumentType(){const e=l(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&&u(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}}const m=({officeApiUrl:s,document:c,auth:l,verifyFunction:a,height:d="100%",width:u="100%",onReady:f,onError:h,onDocumentStateChange:m,onRequestHistory:g,onRequestHistoryData:p,onRequestHistoryClose:v,onRequestRestore:w})=>{const C=i(null),O=i(null),[R,E]=o(!1),[k,I]=o(null),b=r(async()=>{if(C.current)try{const e=new y;e.configure({...c,height:d,width:u});const t=(e,t,i)=>{switch(e){case"onDocumentReady":E(!0),null==f||f(i);break;case"onInfo":break;case"onRequestHistory":null==g||g({event:t,editor:i});break;case"onRequestHistoryData":null==p||p({event:t,editor:i});break;case"onRequestHistoryClose":null==v||v({event:t,editor:i});break;case"onRequestRestore":null==w||w({event:t,editor:i})}},i={dom:C.current,officeApiUrl:s,callback:t,auth:l,verifyFunction:a};O.current=await e.initOffice(i),e.on("onError",e=>{var t;const i=(null===(t=e.data)||void 0===t?void 0:t.errorDescription)||"编辑器错误";I(i),null==h||h(e)}),e.on("documentStateChange",e=>{null==m||m(e)})}catch(e){const t=e.message||"初始化失败";I(t),null==h||h(e)}},[s,c,d,u,l,a,f,h,m,g,p,v,w]),D=r(()=>{O.current&&(O.current.destroy(),O.current=null,E(!1))},[]);return n(()=>(b(),()=>{D()}),[b,D]),n(()=>{O.current&&c&&(D(),b())},[c,D,b]),e("div",{className:"onlyoffice-editor-container",style:{width:"100%",height:"100%",position:"relative"},children:[t("div",{ref:C,style:{width:"100%",height:"100%"}}),k&&t("div",{className:"onlyoffice-error",style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",color:"red"},children:k})]})};function g(e){const{officeApiUrl:t,document:s,auth:c,verifyFunction:l,height:a="100%",width:d="100%",autoInit:u=!0,onReady:f,onError:h}=e,m=i(null),g=i(null),p=i(null),[v,w]=o(!1),[C,O]=o(null),R=r(async()=>{if(m.current)try{E();const e=new y;g.current=e,e.configure({...s,height:a,width:d});const i=(e,t,i)=>{if("onDocumentReady"===e)w(!0),null==f||f(i)},o={dom:m.current,officeApiUrl:t,callback:i,auth:c,verifyFunction:l};p.current=await e.initOffice(o),e.on("onError",e=>{var t;const i=(null===(t=e.data)||void 0===t?void 0:t.errorDescription)||"编辑器错误";O(i),null==h||h(e)})}catch(e){const t=e.message||"初始化失败";O(t),null==h||h(e)}else O("容器元素未找到")},[t,s,a,d,c,l,f,h]),E=r(()=>{g.current&&(g.current.destroy(),g.current=null,p.current=null,w(!1))},[]),k=r(async()=>{E(),await R()},[E,R]),I=r((e,t)=>{g.current&&g.current.on(e,t)},[]),b=r((e,t)=>{g.current&&g.current.off(e,t)},[]);return n(()=>(u&&R(),()=>{E()}),[u,R,E]),n(()=>{g.current&&s&&k()},[s,k]),{containerRef:m,editorInstance:p.current,isReady:v,error:C,init:R,destroy:E,reinit:k,on:I,off:b}}function p(){return new y}async function v(e){return(new y).initOffice(e)}function w(e,t,i){return(new y).init(e,t,i)}async function C(e,t,i){const{saveSuccessInfo:o}=await Promise.resolve().then(function(){return f});await o(e,{status:10,key:t,userdata:JSON.stringify({appUserId:i})})}async function O(e,t,i){const{saveSuccessInfo:o}=await Promise.resolve().then(function(){return f});await o(e,{status:9,key:t,userdata:JSON.stringify({appUserId:i})})}export{m as OnlyOfficeEditor,p as createOfficeEditor,O as downloadSave,w as init,v as initOffice,C as shareSave,g as useOnlyOffice};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","sources":["../../../src/core/utils/fileType.ts","../../../src/core/utils/http.ts","../../../src/core/editor.ts","../../../src/react/OnlyOfficeEditor.tsx","../../../src/react/useOnlyOffice.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}","import React, {\n useRef,\n useEffect,\n useState,\n useCallback,\n type FC,\n type MutableRefObject,\n} from 'react';\nimport { OfficeEditor } from '../core/editor';\nimport type {\n OfficeDocumentConfig,\n OfficeInitConfig,\n OfficeCallback,\n OfficeEventType,\n AuthConfig,\n VerifyTokenSignFunction,\n OfficeEditorInstance,\n} from '../types';\n\n/**\n * OnlyOfficeEditor 组件属性\n */\nexport interface OnlyOfficeEditorProps {\n /** OnlyOffice API 脚本地址 */\n officeApiUrl: string;\n /** 文档配置 */\n document: OfficeDocumentConfig;\n /** 验签配置 */\n auth?: AuthConfig;\n /** 自定义验签函数 */\n verifyFunction?: VerifyTokenSignFunction;\n /** 编辑器高度 */\n height?: string;\n /** 编辑器宽度 */\n width?: string;\n /** 就绪回调 */\n onReady?: (editor: OfficeEditorInstance) => void;\n /** 错误回调 */\n onError?: (error: any) => void;\n /** 文档状态变化回调 */\n onDocumentStateChange?: (event: any) => void;\n /** 历史记录请求回调 */\n onRequestHistory?: (data: { event: any; editor: any }) => void;\n /** 历史数据请求回调 */\n onRequestHistoryData?: (data: { event: any; editor: any }) => void;\n /** 历史关闭请求回调 */\n onRequestHistoryClose?: (data: { event: any; editor: any }) => void;\n /** 恢复请求回调 */\n onRequestRestore?: (data: { event: any; editor: any }) => void;\n}\n\n/**\n * OnlyOffice 编辑器 React 组件\n */\nexport const OnlyOfficeEditor: FC<OnlyOfficeEditorProps> = ({\n officeApiUrl,\n document: documentConfig,\n auth,\n verifyFunction,\n height = '100%',\n width = '100%',\n onReady,\n onError,\n onDocumentStateChange,\n onRequestHistory,\n onRequestHistoryData,\n onRequestHistoryClose,\n onRequestRestore,\n}) => {\n const containerRef = useRef<HTMLDivElement>(null);\n const editorInstanceRef = useRef<OfficeEditorInstance | null>(null);\n const [isReady, setIsReady] = useState(false);\n const [error, setError] = useState<string | null>(null);\n\n /**\n * 初始化编辑器\n */\n const initEditor = useCallback(async () => {\n if (!containerRef.current) return;\n\n try {\n const editor = new OfficeEditor();\n\n // 配置文档参数\n editor.configure({\n ...documentConfig,\n height,\n width,\n });\n\n // 事件回调\n const callback: OfficeCallback = (type, event, editorInst) => {\n switch (type) {\n case 'onDocumentReady':\n setIsReady(true);\n onReady?.(editorInst as OfficeEditorInstance);\n break;\n case 'onInfo':\n break;\n case 'onRequestHistory':\n onRequestHistory?.({ event, editor: editorInst });\n break;\n case 'onRequestHistoryData':\n onRequestHistoryData?.({ event, editor: editorInst });\n break;\n case 'onRequestHistoryClose':\n onRequestHistoryClose?.({ event, editor: editorInst });\n break;\n case 'onRequestRestore':\n onRequestRestore?.({ event, editor: editorInst });\n break;\n }\n };\n\n // 初始化配置\n const initConfig: OfficeInitConfig = {\n dom: containerRef.current,\n officeApiUrl,\n callback,\n auth,\n verifyFunction,\n };\n\n // 初始化编辑器\n editorInstanceRef.current = await editor.initOffice(initConfig);\n\n // 监听错误事件\n editor.on('onError' as OfficeEventType, (event: any) => {\n const errorMsg = event.data?.errorDescription || '编辑器错误';\n setError(errorMsg);\n onError?.(event);\n });\n\n // 监听文档状态变化\n editor.on('documentStateChange' as OfficeEventType, (event: any) => {\n onDocumentStateChange?.(event);\n });\n } catch (err: any) {\n const errorMsg = err.message || '初始化失败';\n setError(errorMsg);\n onError?.(err);\n }\n }, [\n officeApiUrl,\n documentConfig,\n height,\n width,\n auth,\n verifyFunction,\n onReady,\n onError,\n onDocumentStateChange,\n onRequestHistory,\n onRequestHistoryData,\n onRequestHistoryClose,\n onRequestRestore,\n ]);\n\n /**\n * 销毁编辑器\n */\n const destroyEditor = useCallback(() => {\n if (editorInstanceRef.current) {\n editorInstanceRef.current.destroy();\n editorInstanceRef.current = null;\n setIsReady(false);\n }\n }, []);\n\n // 初始化和清理\n useEffect(() => {\n initEditor();\n\n return () => {\n destroyEditor();\n };\n }, [initEditor, destroyEditor]);\n\n // 监听文档配置变化\n useEffect(() => {\n if (editorInstanceRef.current && documentConfig) {\n destroyEditor();\n initEditor();\n }\n }, [documentConfig, destroyEditor, initEditor]);\n\n return (\n <div\n className=\"onlyoffice-editor-container\"\n style={{\n width: '100%',\n height: '100%',\n position: 'relative',\n }}\n >\n <div\n ref={containerRef}\n style={{\n width: '100%',\n height: '100%',\n }}\n />\n {error && (\n <div\n className=\"onlyoffice-error\"\n style={{\n position: 'absolute',\n top: '50%',\n left: '50%',\n transform: 'translate(-50%, -50%)',\n color: 'red',\n }}\n >\n {error}\n </div>\n )}\n </div>\n );\n};\n\nexport default OnlyOfficeEditor;","import { useRef, useEffect, useState, useCallback, type MutableRefObject } from 'react';\nimport { OfficeEditor } from '../core/editor';\nimport type {\n OfficeDocumentConfig,\n OfficeInitConfig,\n OfficeCallback,\n OfficeEventType,\n AuthConfig,\n VerifyTokenSignFunction,\n OfficeEditorInstance,\n} from '../types';\n\n/**\n * useOnlyOffice 配置选项\n */\nexport interface UseOnlyOfficeOptions {\n /** OnlyOffice API 脚本地址 */\n officeApiUrl: string;\n /** 文档配置 */\n document: OfficeDocumentConfig;\n /** 验签配置 */\n auth?: AuthConfig;\n /** 自定义验签函数 */\n verifyFunction?: VerifyTokenSignFunction;\n /** 编辑器高度 */\n height?: string;\n /** 编辑器宽度 */\n width?: string;\n /** 是否自动初始化 */\n autoInit?: boolean;\n /** 就绪回调 */\n onReady?: (editor: OfficeEditorInstance) => void;\n /** 错误回调 */\n onError?: (error: any) => void;\n}\n\n/**\n * useOnlyOffice 返回值\n */\nexport interface UseOnlyOfficeReturn {\n /** 容器元素引用 */\n containerRef: MutableRefObject<HTMLDivElement | null>;\n /** 编辑器实例 */\n editorInstance: OfficeEditorInstance | null;\n /** 是否已就绪 */\n isReady: boolean;\n /** 错误信息 */\n error: string | null;\n /** 初始化编辑器 */\n init: () => Promise<void>;\n /** 销毁编辑器 */\n destroy: () => void;\n /** 重新初始化 */\n reinit: () => Promise<void>;\n /** 监听事件 */\n on: (event: OfficeEventType, callback: (...args: any[]) => void) => void;\n /** 移除事件监听 */\n off: (event: OfficeEventType, callback: (...args: any[]) => void) => void;\n}\n\n/**\n * OnlyOffice React Hook\n * @param options 配置选项\n * @returns 编辑器状态和方法\n */\nexport function useOnlyOffice(options: UseOnlyOfficeOptions): UseOnlyOfficeReturn {\n const {\n officeApiUrl,\n document: documentConfig,\n auth,\n verifyFunction,\n height = '100%',\n width = '100%',\n autoInit = true,\n onReady,\n onError,\n } = options;\n\n const containerRef = useRef<HTMLDivElement | null>(null);\n const editorRef = useRef<OfficeEditor | null>(null);\n const editorInstanceRef = useRef<OfficeEditorInstance | null>(null);\n\n const [isReady, setIsReady] = useState(false);\n const [error, setError] = useState<string | null>(null);\n\n /**\n * 初始化编辑器\n */\n const init = useCallback(async () => {\n if (!containerRef.current) {\n setError('容器元素未找到');\n return;\n }\n\n try {\n // 销毁现有实例\n destroy();\n\n const editor = new OfficeEditor();\n editorRef.current = editor;\n\n // 配置文档参数\n editor.configure({\n ...documentConfig,\n height,\n width,\n });\n\n // 事件回调\n const callback: OfficeCallback = (type, event, editorInst) => {\n switch (type) {\n case 'onDocumentReady':\n setIsReady(true);\n onReady?.(editorInst as OfficeEditorInstance);\n break;\n case 'onInfo':\n break;\n }\n };\n\n // 初始化配置\n const initConfig: OfficeInitConfig = {\n dom: containerRef.current,\n officeApiUrl,\n callback,\n auth,\n verifyFunction,\n };\n\n // 初始化编辑器\n editorInstanceRef.current = await editor.initOffice(initConfig);\n\n // 监听错误事件\n editor.on('onError' as OfficeEventType, (event: any) => {\n const errorMsg = event.data?.errorDescription || '编辑器错误';\n setError(errorMsg);\n onError?.(event);\n });\n } catch (err: any) {\n const errorMsg = err.message || '初始化失败';\n setError(errorMsg);\n onError?.(err);\n }\n }, [\n officeApiUrl,\n documentConfig,\n height,\n width,\n auth,\n verifyFunction,\n onReady,\n onError,\n ]);\n\n /**\n * 销毁编辑器\n */\n const destroy = useCallback(() => {\n if (editorRef.current) {\n editorRef.current.destroy();\n editorRef.current = null;\n editorInstanceRef.current = null;\n setIsReady(false);\n }\n }, []);\n\n /**\n * 重新初始化\n */\n const reinit = useCallback(async () => {\n destroy();\n await init();\n }, [destroy, init]);\n\n /**\n * 监听事件\n */\n const on = useCallback(\n (event: OfficeEventType, callback: (...args: any[]) => void) => {\n if (editorRef.current) {\n editorRef.current.on(event, callback);\n }\n },\n []\n );\n\n /**\n * 移除事件监听\n */\n const off = useCallback(\n (event: OfficeEventType, callback: (...args: any[]) => void) => {\n if (editorRef.current) {\n editorRef.current.off(event, callback);\n }\n },\n []\n );\n\n // 初始化和清理\n useEffect(() => {\n if (autoInit) {\n init();\n }\n\n return () => {\n destroy();\n };\n }, [autoInit, init, destroy]);\n\n // 监听文档配置变化\n useEffect(() => {\n if (editorRef.current && documentConfig) {\n reinit();\n }\n }, [documentConfig, reinit]);\n\n return {\n containerRef,\n editorInstance: editorInstanceRef.current,\n isReady,\n error,\n init,\n destroy,\n reinit,\n on,\n off,\n };\n}\n\nexport default useOnlyOffice;","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","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","OnlyOfficeEditor","onReady","containerRef","useRef","editorInstanceRef","isReady","setIsReady","useState","setError","initEditor","useCallback","current","editorInst","initConfig","errorMsg","err","message","useEffect","_jsxs","className","children","_jsx","ref","top","left","transform","color","useOnlyOffice","options","autoInit","editorRef","reinit","editorInstance","createOfficeEditor","shareSave","fileKey","Promise","resolve","then","http","downloadSave"],"mappings":"iLAOM,SAAUA,EAAgBC,GAC9B,MAAMC,EAAOD,EAASE,cAItB,GADkB,CAAC,MAAO,OAAQ,MAAO,MAAO,MAAO,OAAQ,QACjDC,SAASF,GACrB,MAAO,OAKT,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,SAAUC,KAAKC,UAAU,CAAEC,eAE/B,CAQOrF,eAAegJ,EACpBzI,EACAoI,EACAtD,GAEA,MAAM/E,gBAAEA,SAA0BsI,QAAAC,UAAAC,KAAA,WAAA,OAAAC,CAAA,SAC5BzI,EAAgBC,EAAa,CACjC0E,OAAQ,EACRpD,IAAK8G,EACLzD,SAAUC,KAAKC,UAAU,CAAEC,eAE/B"}
|
|
1
|
+
{"version":3,"file":"index.mjs","sources":["../../../src/core/utils/fileType.ts","../../../src/core/utils/http.ts","../../../src/core/editor.ts","../../../src/react/OnlyOfficeEditor.tsx","../../../src/react/useOnlyOffice.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 console.log('[OnlyOffice] createEditor called', { dom, officeApiUrl });\n\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 console.log('[OnlyOffice] DOM dimensions:', { width: dom.offsetWidth, height: dom.offsetHeight });\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 console.log('[OnlyOffice] Loading script:', officeApiUrl);\n const script = document.createElement('script');\n script.id = scriptId;\n script.src = officeApiUrl;\n script.onload = () => {\n console.log('[OnlyOffice] Script loaded successfully');\n console.log('[OnlyOffice] window.DocsAPI:', window.DocsAPI);\n this.instantiateEditor();\n };\n script.onerror = (err) => {\n console.error('[OnlyOffice] Script load failed:', err);\n };\n document.head.appendChild(script);\n } else {\n console.log('[OnlyOffice] Script already loaded');\n this.instantiateEditor();\n }\n\n return this;\n }\n\n /**\n * 实例化编辑器\n */\n private instantiateEditor(): void {\n console.log('[OnlyOffice] instantiateEditor called');\n\n // 销毁现有实例\n if (this.editor) {\n this.editor.destroyEditor();\n this.editor = null;\n }\n\n // 检查 DocsAPI 是否可用\n if (!window.DocsAPI || !window.DocsAPI.DocEditor) {\n console.error('[OnlyOffice] window.DocsAPI.DocEditor is not available');\n return;\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 console.log('[OnlyOffice] Creating editor with config:', config);\n console.log('[OnlyOffice] Editor container ID:', this.editorId);\n console.log('[OnlyOffice] Container element:', document.getElementById(this.editorId));\n\n // 创建编辑器实例\n try {\n this.editor = new window.DocsAPI.DocEditor(this.editorId, config);\n console.log('[OnlyOffice] Editor created successfully:', this.editor);\n } catch (err) {\n console.error('[OnlyOffice] Error creating editor:', err);\n }\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}","import React, {\n useRef,\n useEffect,\n useState,\n useCallback,\n type FC,\n type MutableRefObject,\n} from 'react';\nimport { OfficeEditor } from '../core/editor';\nimport type {\n OfficeDocumentConfig,\n OfficeInitConfig,\n OfficeCallback,\n OfficeEventType,\n AuthConfig,\n VerifyTokenSignFunction,\n OfficeEditorInstance,\n} from '../types';\n\n/**\n * OnlyOfficeEditor 组件属性\n */\nexport interface OnlyOfficeEditorProps {\n /** OnlyOffice API 脚本地址 */\n officeApiUrl: string;\n /** 文档配置 */\n document: OfficeDocumentConfig;\n /** 验签配置 */\n auth?: AuthConfig;\n /** 自定义验签函数 */\n verifyFunction?: VerifyTokenSignFunction;\n /** 编辑器高度 */\n height?: string;\n /** 编辑器宽度 */\n width?: string;\n /** 就绪回调 */\n onReady?: (editor: OfficeEditorInstance) => void;\n /** 错误回调 */\n onError?: (error: any) => void;\n /** 文档状态变化回调 */\n onDocumentStateChange?: (event: any) => void;\n /** 历史记录请求回调 */\n onRequestHistory?: (data: { event: any; editor: any }) => void;\n /** 历史数据请求回调 */\n onRequestHistoryData?: (data: { event: any; editor: any }) => void;\n /** 历史关闭请求回调 */\n onRequestHistoryClose?: (data: { event: any; editor: any }) => void;\n /** 恢复请求回调 */\n onRequestRestore?: (data: { event: any; editor: any }) => void;\n}\n\n/**\n * OnlyOffice 编辑器 React 组件\n */\nexport const OnlyOfficeEditor: FC<OnlyOfficeEditorProps> = ({\n officeApiUrl,\n document: documentConfig,\n auth,\n verifyFunction,\n height = '100%',\n width = '100%',\n onReady,\n onError,\n onDocumentStateChange,\n onRequestHistory,\n onRequestHistoryData,\n onRequestHistoryClose,\n onRequestRestore,\n}) => {\n const containerRef = useRef<HTMLDivElement>(null);\n const editorInstanceRef = useRef<OfficeEditorInstance | null>(null);\n const [isReady, setIsReady] = useState(false);\n const [error, setError] = useState<string | null>(null);\n\n /**\n * 初始化编辑器\n */\n const initEditor = useCallback(async () => {\n if (!containerRef.current) return;\n\n try {\n const editor = new OfficeEditor();\n\n // 配置文档参数\n editor.configure({\n ...documentConfig,\n height,\n width,\n });\n\n // 事件回调\n const callback: OfficeCallback = (type, event, editorInst) => {\n switch (type) {\n case 'onDocumentReady':\n setIsReady(true);\n onReady?.(editorInst as OfficeEditorInstance);\n break;\n case 'onInfo':\n break;\n case 'onRequestHistory':\n onRequestHistory?.({ event, editor: editorInst });\n break;\n case 'onRequestHistoryData':\n onRequestHistoryData?.({ event, editor: editorInst });\n break;\n case 'onRequestHistoryClose':\n onRequestHistoryClose?.({ event, editor: editorInst });\n break;\n case 'onRequestRestore':\n onRequestRestore?.({ event, editor: editorInst });\n break;\n }\n };\n\n // 初始化配置\n const initConfig: OfficeInitConfig = {\n dom: containerRef.current,\n officeApiUrl,\n callback,\n auth,\n verifyFunction,\n };\n\n // 初始化编辑器\n editorInstanceRef.current = await editor.initOffice(initConfig);\n\n // 监听错误事件\n editor.on('onError' as OfficeEventType, (event: any) => {\n const errorMsg = event.data?.errorDescription || '编辑器错误';\n setError(errorMsg);\n onError?.(event);\n });\n\n // 监听文档状态变化\n editor.on('documentStateChange' as OfficeEventType, (event: any) => {\n onDocumentStateChange?.(event);\n });\n } catch (err: any) {\n const errorMsg = err.message || '初始化失败';\n setError(errorMsg);\n onError?.(err);\n }\n }, [\n officeApiUrl,\n documentConfig,\n height,\n width,\n auth,\n verifyFunction,\n onReady,\n onError,\n onDocumentStateChange,\n onRequestHistory,\n onRequestHistoryData,\n onRequestHistoryClose,\n onRequestRestore,\n ]);\n\n /**\n * 销毁编辑器\n */\n const destroyEditor = useCallback(() => {\n if (editorInstanceRef.current) {\n editorInstanceRef.current.destroy();\n editorInstanceRef.current = null;\n setIsReady(false);\n }\n }, []);\n\n // 初始化和清理\n useEffect(() => {\n initEditor();\n\n return () => {\n destroyEditor();\n };\n }, [initEditor, destroyEditor]);\n\n // 监听文档配置变化\n useEffect(() => {\n if (editorInstanceRef.current && documentConfig) {\n destroyEditor();\n initEditor();\n }\n }, [documentConfig, destroyEditor, initEditor]);\n\n return (\n <div\n className=\"onlyoffice-editor-container\"\n style={{\n width: '100%',\n height: '100%',\n position: 'relative',\n }}\n >\n <div\n ref={containerRef}\n style={{\n width: '100%',\n height: '100%',\n }}\n />\n {error && (\n <div\n className=\"onlyoffice-error\"\n style={{\n position: 'absolute',\n top: '50%',\n left: '50%',\n transform: 'translate(-50%, -50%)',\n color: 'red',\n }}\n >\n {error}\n </div>\n )}\n </div>\n );\n};\n\nexport default OnlyOfficeEditor;","import { useRef, useEffect, useState, useCallback, type MutableRefObject } from 'react';\nimport { OfficeEditor } from '../core/editor';\nimport type {\n OfficeDocumentConfig,\n OfficeInitConfig,\n OfficeCallback,\n OfficeEventType,\n AuthConfig,\n VerifyTokenSignFunction,\n OfficeEditorInstance,\n} from '../types';\n\n/**\n * useOnlyOffice 配置选项\n */\nexport interface UseOnlyOfficeOptions {\n /** OnlyOffice API 脚本地址 */\n officeApiUrl: string;\n /** 文档配置 */\n document: OfficeDocumentConfig;\n /** 验签配置 */\n auth?: AuthConfig;\n /** 自定义验签函数 */\n verifyFunction?: VerifyTokenSignFunction;\n /** 编辑器高度 */\n height?: string;\n /** 编辑器宽度 */\n width?: string;\n /** 是否自动初始化 */\n autoInit?: boolean;\n /** 就绪回调 */\n onReady?: (editor: OfficeEditorInstance) => void;\n /** 错误回调 */\n onError?: (error: any) => void;\n}\n\n/**\n * useOnlyOffice 返回值\n */\nexport interface UseOnlyOfficeReturn {\n /** 容器元素引用 */\n containerRef: MutableRefObject<HTMLDivElement | null>;\n /** 编辑器实例 */\n editorInstance: OfficeEditorInstance | null;\n /** 是否已就绪 */\n isReady: boolean;\n /** 错误信息 */\n error: string | null;\n /** 初始化编辑器 */\n init: () => Promise<void>;\n /** 销毁编辑器 */\n destroy: () => void;\n /** 重新初始化 */\n reinit: () => Promise<void>;\n /** 监听事件 */\n on: (event: OfficeEventType, callback: (...args: any[]) => void) => void;\n /** 移除事件监听 */\n off: (event: OfficeEventType, callback: (...args: any[]) => void) => void;\n}\n\n/**\n * OnlyOffice React Hook\n * @param options 配置选项\n * @returns 编辑器状态和方法\n */\nexport function useOnlyOffice(options: UseOnlyOfficeOptions): UseOnlyOfficeReturn {\n const {\n officeApiUrl,\n document: documentConfig,\n auth,\n verifyFunction,\n height = '100%',\n width = '100%',\n autoInit = true,\n onReady,\n onError,\n } = options;\n\n const containerRef = useRef<HTMLDivElement | null>(null);\n const editorRef = useRef<OfficeEditor | null>(null);\n const editorInstanceRef = useRef<OfficeEditorInstance | null>(null);\n\n const [isReady, setIsReady] = useState(false);\n const [error, setError] = useState<string | null>(null);\n\n /**\n * 初始化编辑器\n */\n const init = useCallback(async () => {\n if (!containerRef.current) {\n setError('容器元素未找到');\n return;\n }\n\n try {\n // 销毁现有实例\n destroy();\n\n const editor = new OfficeEditor();\n editorRef.current = editor;\n\n // 配置文档参数\n editor.configure({\n ...documentConfig,\n height,\n width,\n });\n\n // 事件回调\n const callback: OfficeCallback = (type, event, editorInst) => {\n switch (type) {\n case 'onDocumentReady':\n setIsReady(true);\n onReady?.(editorInst as OfficeEditorInstance);\n break;\n case 'onInfo':\n break;\n }\n };\n\n // 初始化配置\n const initConfig: OfficeInitConfig = {\n dom: containerRef.current,\n officeApiUrl,\n callback,\n auth,\n verifyFunction,\n };\n\n // 初始化编辑器\n editorInstanceRef.current = await editor.initOffice(initConfig);\n\n // 监听错误事件\n editor.on('onError' as OfficeEventType, (event: any) => {\n const errorMsg = event.data?.errorDescription || '编辑器错误';\n setError(errorMsg);\n onError?.(event);\n });\n } catch (err: any) {\n const errorMsg = err.message || '初始化失败';\n setError(errorMsg);\n onError?.(err);\n }\n }, [\n officeApiUrl,\n documentConfig,\n height,\n width,\n auth,\n verifyFunction,\n onReady,\n onError,\n ]);\n\n /**\n * 销毁编辑器\n */\n const destroy = useCallback(() => {\n if (editorRef.current) {\n editorRef.current.destroy();\n editorRef.current = null;\n editorInstanceRef.current = null;\n setIsReady(false);\n }\n }, []);\n\n /**\n * 重新初始化\n */\n const reinit = useCallback(async () => {\n destroy();\n await init();\n }, [destroy, init]);\n\n /**\n * 监听事件\n */\n const on = useCallback(\n (event: OfficeEventType, callback: (...args: any[]) => void) => {\n if (editorRef.current) {\n editorRef.current.on(event, callback);\n }\n },\n []\n );\n\n /**\n * 移除事件监听\n */\n const off = useCallback(\n (event: OfficeEventType, callback: (...args: any[]) => void) => {\n if (editorRef.current) {\n editorRef.current.off(event, callback);\n }\n },\n []\n );\n\n // 初始化和清理\n useEffect(() => {\n if (autoInit) {\n init();\n }\n\n return () => {\n destroy();\n };\n }, [autoInit, init, destroy]);\n\n // 监听文档配置变化\n useEffect(() => {\n if (editorRef.current && documentConfig) {\n reinit();\n }\n }, [documentConfig, reinit]);\n\n return {\n containerRef,\n editorInstance: editorInstanceRef.current,\n isReady,\n error,\n init,\n destroy,\n reinit,\n on,\n off,\n };\n}\n\nexport default useOnlyOffice;","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","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","log","style","position","offsetWidth","offsetHeight","mainDiv","document","createElement","appendChild","scriptId","querySelector","instantiateEditor","script","src","onload","window","DocsAPI","onerror","err","head","destroyEditor","DocEditor","documentType","events","createEventHandlers","getElementById","onDocumentStateChange","event","emit","onDocumentReady","status","userdata","JSON","stringify","appUserId","_b","call","onInfo","onError","errorCode","errorDescription","onRequestHistory","onRequestHistoryData","onRequestHistoryClose","onRequestRestore","onRequestSendNotify","onRequestUsers","on","off","getConfig","getEditor","destroy","removeAllListeners","OnlyOfficeEditor","onReady","containerRef","useRef","editorInstanceRef","isReady","setIsReady","useState","setError","initEditor","useCallback","current","editorInst","initConfig","errorMsg","message","useEffect","_jsxs","className","children","_jsx","ref","top","left","transform","color","useOnlyOffice","options","autoInit","editorRef","reinit","editorInstance","createOfficeEditor","shareSave","fileKey","Promise","resolve","then","http","downloadSave"],"mappings":"iLAOM,SAAUA,EAAgBC,GAC9B,MAAMC,EAAOD,EAASE,cAItB,GADkB,CAAC,MAAO,OAAQ,MAAO,MAAO,MAAO,OAAQ,QACjDC,SAASF,GACrB,MAAO,OAKT,GADkB,CAAC,MAAO,OAAQ,MAAO,OAC3BE,SAASF,GACrB,MAAO,OAKT,MADmB,CAAC,MAAO,OAAQ,OACpBE,SAASF,GACf,QAII,QAATA,EACK,MAGF,OACT,OC7BaG,EAGX,WAAAC,CAAYC,EAAkB,IAC5BC,KAAKD,QAAUA,CACjB,CASA,UAAME,CACJC,EACAC,EACAC,GAEA,MAAMC,EAAUL,KAAKD,QAAU,GAAGC,KAAKD,UAAUG,IAAQA,EACzD,OAAOI,EAAML,KAAQI,EAASF,EAAMC,EACtC,CAQA,SAAMG,CACJL,EACAE,GAEA,MAAMC,EAAUL,KAAKD,QAAU,GAAGC,KAAKD,UAAUG,IAAQA,EACzD,OAAOI,EAAMC,IAAOF,EAASD,EAC/B,EASKI,eAAeC,EACpBV,EACAI,SAMA,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ACArD,GAEA,MAAMpF,gBAAEA,SAA0B0I,QAAAC,UAAAC,KAAA,WAAA,OAAAC,CAAA,SAC5B7I,EAAgBC,EAAa,CACjC+E,OAAQ,GACRzD,IAAKkH,EACLxD,SAAUC,KAAKC,UAAU,CAAEC,eAE/B,CAQO1F,eAAeoJ,EACpB7I,EACAwI,EACArD,GAEA,MAAMpF,gBAAEA,SAA0B0I,QAAAC,UAAAC,KAAA,WAAA,OAAAC,CAAA,SAC5B7I,EAAgBC,EAAa,CACjC+E,OAAQ,EACRzD,IAAKkH,EACLxD,SAAUC,KAAKC,UAAU,CAAEC,eAE/B"}
|
package/dist/esm/vue2/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import t from"eventemitter3";import e from"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"}class o{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 r(t,e){var i;try{const r=new o(t);return!0===(null===(i=(await r.post("/onlyoffice/token/verifyTokenSign",e)).data)||void 0===i?void 0:i.data)}catch(t){return console.error("验签请求失败:",t),!1}}async function s(t,i){try{await e.post(t,i)}catch(t){console.error("保存操作信息失败:",t)}}var n=Object.freeze({__proto__:null,HttpClient:o,saveSuccessInfo:s,verifyTokenSign:r});const c={comment:!1,download:!1,edit:!1,print:!0,review:!1,editCommentAuthorOnly:!1,fillForms:!1,modifyContentControl:!1};class d{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:{...c}},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("other"===i(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:s,verifyFunction:n}=t;if(o&&(this.callback=o),s){let t=!1;if(n)t=await n(s);else{if(!s.verifyUrl)throw new Error("使用验签配置时,必须提供 verifyFunction 或 verifyUrl");t=await r(s.verifyUrl,{appId:s.appId,sign:s.sign,timestamp:s.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&&s(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}}const a={name:"OnlyOfficeEditor",props:{officeApiUrl:{type:String,required:!0},document:{type:Object,required:!0},auth:{type:Object,default:void 0},verifyFunction:{type:Function,default:void 0},height:{type:String,default:"100%"},width:{type:String,default:"100%"}},data:()=>({editorInstance:null,isReady:!1,error:null}),watch:{document:{handler(){this.editorInstance&&this.reinit()},deep:!0}},mounted(){this.init()},beforeDestroy(){this.destroy()},methods:{async init(){const t=this.$refs.container;if(t)try{const e=new d;e.configure({...this.document,height:this.height,width:this.width});const i=(t,e,i)=>{switch(t){case"onDocumentReady":this.isReady=!0,this.$emit("ready",i);break;case"onInfo":break;case"onRequestHistory":this.$emit("request-history",{event:e,editor:i});break;case"onRequestHistoryData":this.$emit("request-history-data",{event:e,editor:i});break;case"onRequestHistoryClose":this.$emit("request-history-close",{event:e,editor:i});break;case"onRequestRestore":this.$emit("request-restore",{event:e,editor:i})}},o={dom:t,officeApiUrl:this.officeApiUrl,callback:i,auth:this.auth,verifyFunction:this.verifyFunction};this.editorInstance=await e.initOffice(o),e.on("onError",t=>{var e;this.error=(null===(e=t.data)||void 0===e?void 0:e.errorDescription)||"编辑器错误",this.$emit("error",t)}),e.on("documentStateChange",t=>{this.$emit("document-state-change",t)})}catch(t){this.error=t.message||"初始化失败",this.$emit("error",t)}},destroy(){this.editorInstance&&(this.editorInstance.destroy(),this.editorInstance=null,this.isReady=!1)},async reinit(){this.destroy(),await this.init()},on(t,e){this.editorInstance&&this.editorInstance.on(t,e)},off(t,e){this.editorInstance&&this.editorInstance.off(t,e)}},template:'\n <div class="onlyoffice-editor-container" style="width: 100%; height: 100%; position: relative;">\n <div ref="container" style="width: 100%; height: 100%;"></div>\n <div v-if="error" class="onlyoffice-error" style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); color: red;">\n {{ error }}\n </div>\n </div>\n '},h={data:()=>({officeEditor:null,officeInstance:null,officeReady:!1,officeError:null}),beforeDestroy(){this.$destroyOffice()},methods:{async $initOffice(t,e,i,o){try{const r="string"==typeof t?document.querySelector(t):t;if(!r)throw new Error("容器元素未找到");this.officeEditor=new d,this.officeEditor.configure(i);const s={dom:r,officeApiUrl:e,callback:null==o?void 0:o.callback,auth:null==o?void 0:o.auth,verifyFunction:null==o?void 0:o.verifyFunction};return this.officeInstance=await this.officeEditor.initOffice(s),this.officeReady=!0,this.officeEditor.on("onError",t=>{var e;this.officeError=(null===(e=t.data)||void 0===e?void 0:e.errorDescription)||"编辑器错误",this.$emit("office-error",t)}),this.officeEditor.on("documentStateChange",t=>{this.$emit("office-state-change",t)}),this.officeInstance}catch(t){return this.officeError=t.message||"初始化失败",this.$emit("office-error",t),null}},$destroyOffice(){this.officeEditor&&(this.officeEditor.destroy(),this.officeEditor=null,this.officeInstance=null,this.officeReady=!1)},$onOfficeEvent(t,e){this.officeEditor&&this.officeEditor.on(t,e)},$offOfficeEvent(t,e){this.officeEditor&&this.officeEditor.off(t,e)},async $reinitOffice(t,e,i,o){return this.$destroyOffice(),this.$initOffice(t,e,i,o)}}};function f(){return new d}async function l(t){return(new d).initOffice(t)}function u(t,e,i){return(new d).init(t,e,i)}async function m(t,e,i){const{saveSuccessInfo:o}=await Promise.resolve().then(function(){return n});await o(t,{status:10,key:e,userdata:JSON.stringify({appUserId:i})})}async function y(t,e,i){const{saveSuccessInfo:o}=await Promise.resolve().then(function(){return n});await o(t,{status:9,key:e,userdata:JSON.stringify({appUserId:i})})}export{a as OnlyOfficeEditor,h as OnlyOfficeMixin,f as createOfficeEditor,y as downloadSave,u as init,l as initOffice,m as shareSave};
|
|
1
|
+
import t from"eventemitter3";import e from"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"}class o{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 r(t,e){var i;try{const r=new o(t);return!0===(null===(i=(await r.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 s=Object.freeze({__proto__:null,HttpClient:o,saveSuccessInfo:n,verifyTokenSign:r});const c={comment:!1,download:!1,edit:!1,print:!0,review:!1,editCommentAuthorOnly:!1,fillForms:!1,modifyContentControl:!1};class d{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:{...c}},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("other"===i(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:n,verifyFunction:s}=t;if(o&&(this.callback=o),n){let t=!1;if(s)t=await s(n);else{if(!n.verifyUrl)throw new Error("使用验签配置时,必须提供 verifyFunction 或 verifyUrl");t=await r(n.verifyUrl,{appId:n.appId,sign:n.sign,timestamp:n.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(console.log("[OnlyOffice] createEditor called",{dom:t,officeApiUrl:e}),!t)throw new Error("必须提供挂载的 DOM 元素");if(!e)throw new Error("必须提供 OnlyOffice API 脚本地址");t.style.position="relative",console.log("[OnlyOffice] DOM dimensions:",{width:t.offsetWidth,height:t.offsetHeight});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}`))console.log("[OnlyOffice] Script already loaded"),this.instantiateEditor();else{console.log("[OnlyOffice] Loading script:",e);const t=document.createElement("script");t.id=o,t.src=e,t.onload=()=>{console.log("[OnlyOffice] Script loaded successfully"),console.log("[OnlyOffice] window.DocsAPI:",window.DocsAPI),this.instantiateEditor()},t.onerror=t=>{console.error("[OnlyOffice] Script load failed:",t)},document.head.appendChild(t)}return this}instantiateEditor(){if(console.log("[OnlyOffice] instantiateEditor called"),this.editor&&(this.editor.destroyEditor(),this.editor=null),!window.DocsAPI||!window.DocsAPI.DocEditor)return void console.error("[OnlyOffice] window.DocsAPI.DocEditor is not available");const t={width:this.width,height:this.height,documentType:this.getDocumentType(),document:this.documentConfig,editorConfig:this.editorConfig,events:this.createEventHandlers()};console.log("[OnlyOffice] Creating editor with config:",t),console.log("[OnlyOffice] Editor container ID:",this.editorId),console.log("[OnlyOffice] Container element:",document.getElementById(this.editorId));try{this.editor=new window.DocsAPI.DocEditor(this.editorId,t),console.log("[OnlyOffice] Editor created successfully:",this.editor)}catch(t){console.error("[OnlyOffice] Error creating editor:",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}}const l={name:"OnlyOfficeEditor",props:{officeApiUrl:{type:String,required:!0},document:{type:Object,required:!0},auth:{type:Object,default:void 0},verifyFunction:{type:Function,default:void 0},height:{type:String,default:"100%"},width:{type:String,default:"100%"}},data:()=>({editorInstance:null,isReady:!1,error:null}),watch:{document:{handler(){this.editorInstance&&this.reinit()},deep:!0}},mounted(){this.init()},beforeDestroy(){this.destroy()},methods:{async init(){const t=this.$refs.container;if(t)try{const e=new d;e.configure({...this.document,height:this.height,width:this.width});const i=(t,e,i)=>{switch(t){case"onDocumentReady":this.isReady=!0,this.$emit("ready",i);break;case"onInfo":break;case"onRequestHistory":this.$emit("request-history",{event:e,editor:i});break;case"onRequestHistoryData":this.$emit("request-history-data",{event:e,editor:i});break;case"onRequestHistoryClose":this.$emit("request-history-close",{event:e,editor:i});break;case"onRequestRestore":this.$emit("request-restore",{event:e,editor:i})}},o={dom:t,officeApiUrl:this.officeApiUrl,callback:i,auth:this.auth,verifyFunction:this.verifyFunction};this.editorInstance=await e.initOffice(o),e.on("onError",t=>{var e;this.error=(null===(e=t.data)||void 0===e?void 0:e.errorDescription)||"编辑器错误",this.$emit("error",t)}),e.on("documentStateChange",t=>{this.$emit("document-state-change",t)})}catch(t){this.error=t.message||"初始化失败",this.$emit("error",t)}},destroy(){this.editorInstance&&(this.editorInstance.destroy(),this.editorInstance=null,this.isReady=!1)},async reinit(){this.destroy(),await this.init()},on(t,e){this.editorInstance&&this.editorInstance.on(t,e)},off(t,e){this.editorInstance&&this.editorInstance.off(t,e)}},template:'\n <div class="onlyoffice-editor-container" style="width: 100%; height: 100%; position: relative;">\n <div ref="container" style="width: 100%; height: 100%;"></div>\n <div v-if="error" class="onlyoffice-error" style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); color: red;">\n {{ error }}\n </div>\n </div>\n '},a={data:()=>({officeEditor:null,officeInstance:null,officeReady:!1,officeError:null}),beforeDestroy(){this.$destroyOffice()},methods:{async $initOffice(t,e,i,o){try{const r="string"==typeof t?document.querySelector(t):t;if(!r)throw new Error("容器元素未找到");this.officeEditor=new d,this.officeEditor.configure(i);const n={dom:r,officeApiUrl:e,callback:null==o?void 0:o.callback,auth:null==o?void 0:o.auth,verifyFunction:null==o?void 0:o.verifyFunction};return this.officeInstance=await this.officeEditor.initOffice(n),this.officeReady=!0,this.officeEditor.on("onError",t=>{var e;this.officeError=(null===(e=t.data)||void 0===e?void 0:e.errorDescription)||"编辑器错误",this.$emit("office-error",t)}),this.officeEditor.on("documentStateChange",t=>{this.$emit("office-state-change",t)}),this.officeInstance}catch(t){return this.officeError=t.message||"初始化失败",this.$emit("office-error",t),null}},$destroyOffice(){this.officeEditor&&(this.officeEditor.destroy(),this.officeEditor=null,this.officeInstance=null,this.officeReady=!1)},$onOfficeEvent(t,e){this.officeEditor&&this.officeEditor.on(t,e)},$offOfficeEvent(t,e){this.officeEditor&&this.officeEditor.off(t,e)},async $reinitOffice(t,e,i,o){return this.$destroyOffice(),this.$initOffice(t,e,i,o)}}};function f(){return new d}async function h(t){return(new d).initOffice(t)}function u(t,e,i){return(new d).init(t,e,i)}async function y(t,e,i){const{saveSuccessInfo:o}=await Promise.resolve().then(function(){return s});await o(t,{status:10,key:e,userdata:JSON.stringify({appUserId:i})})}async function m(t,e,i){const{saveSuccessInfo:o}=await Promise.resolve().then(function(){return s});await o(t,{status:9,key:e,userdata:JSON.stringify({appUserId:i})})}export{l as OnlyOfficeEditor,a as OnlyOfficeMixin,f as createOfficeEditor,m as downloadSave,u as init,h as initOffice,y as shareSave};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|