@onlyoffice/docspace-sdk-js
Version:
Simple integration JavaScript SDK for ONLYOFFICE DocSpace
19 lines (18 loc) • 14.8 kB
JavaScript
"use strict";var b=Object.defineProperty;var j=Object.getOwnPropertyDescriptor;var D=Object.getOwnPropertyNames;var I=Object.prototype.hasOwnProperty;var H=(o,e)=>{for(var t in e)b(o,t,{get:e[t],enumerable:!0})},M=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of D(e))!I.call(o,r)&&r!==t&&b(o,r,{get:()=>e[r],enumerable:!(n=j(e,r))||n.enumerable});return o};var O=o=>M(b({},"__esModule",{value:!0}),o);var N={};H(N,{default:()=>A});module.exports=O(N);var x="/api/2.0/security/csp",T="frameDocSpace",C={src:"",rootPath:"/rooms/shared/",requestToken:null,width:"100%",height:"100%",name:T,type:"desktop",frameId:"ds-frame",mode:"manager",id:null,locale:null,theme:"System",editorType:"desktop",editorGoBack:!0,selectorType:"all",showSelectorCancel:!1,showSelectorHeader:!1,showHeader:!1,showHeaderBanner:"none",showTitle:!0,showMenu:!1,showFilter:!1,showSignOut:!0,destroyText:"",viewAs:"row",viewTableColumns:"Index,Name,Size,Type,Tags",checkCSP:!0,disableActionButton:!1,showSettings:!1,waiting:!1,noLoader:!0,withSearch:!0,withBreadCrumbs:!0,withSubtitle:!0,filterParam:"ALL",buttonColor:"#5299E0",infoPanelVisible:!0,downloadToEvent:!1,filter:{count:"100",page:"1",sortOrder:"descending",sortBy:"DateAndTime",search:"",withSubfolders:!1},editorCustomization:{},events:{onSelectCallback:null,onCloseCallback:null,onAppReady:null,onAppError:null,onEditorCloseCallback:null,onAuthSuccess:null,onSignOut:null,onDownload:null,onNoAccess:null,onNotFound:null,onContentReady:null,onEditorOpen:null,onFileManagerClick:null}},E="The current domain is not set in the Content Security Policy (CSP) settings.",L="Message bus is not connected with frame";var h=o=>o?(Object.keys(o).forEach(e=>(o[e]===void 0||o[e]===null)&&delete o[e]),new URLSearchParams(o).toString()):"",P=async o=>{let{origin:e,host:t}=window.location;if(e.includes(o))return;let n=await fetch(`${o}${x}`),r;try{r=await n.json()}catch(l){throw new Error(`CSP validation failed: ${l}`)}let{response:{domains:s}}=r,a=t||new URL(e).host;if(!s.map(l=>{try{let c=new URL(l.toLowerCase());return c.host+(c.pathname!=="/"?c.pathname:"")}catch{return l}}).includes(a.toLowerCase()))throw new Error(E)},k=o=>`<body style=background:#f3f4f4><link href="https://fonts.googleapis.com/css?family=Open+Sans:400,600,300"rel=stylesheet><div style="display:flex;flex-direction:column;gap:80px;align-items:center;justify-content:flex-start;margin-top:60px;padding:0 30px"><div style=flex-shrink:0;position:relative><img src=${o}/static/images/logo/lightsmall.svg></div><div style=display:flex;flex-direction:column;gap:16px;align-items:center;justify-content:flex-start;flex-shrink:0;position:relative><div style=flex-shrink:0;width:120px;height:100px;position:relative><img src=${o}/static/images/frame-error.svg></div><span style="color:#a3a9ae;text-align:center;font-family:Open Sans;font-size:14px;font-style:normal;font-weight:700;line-height:16px">${E} Please add it via <a href=${o}/developer-tools/javascript-sdk style="color:#4781d1;text-align:center;font-family:Open Sans;font-size:14px;font-style:normal;font-weight:700;line-height:16px;text-decoration-line:underline"target=_blank>the Developer Tools section</a>.</span></div></div></body>`,R=o=>` rotate { 0%{ transform: rotate(-45deg); will-change: transform; } 15%{ transform: rotate(45deg); } 30%{ transform: rotate(135deg); } 45%{ transform: rotate(225deg); } 60%, 100%{ transform: rotate(315deg); } } .${o} { width: 74px; height: 74px; border: 4px solid rgba(51,51,51, 0.1); border-top-color: #333333; border-radius: 50%; transform: rotate(-45deg); position: relative; box-sizing: border-box; animation: 1s linear infinite rotate; will-change: transform; } (prefers-color-scheme: dark) { .${o} { border-color: rgba(204, 204, 204, 0.1); border-top-color: #CCCCCC; } } (prefers-reduced-motion: reduce) { .${o} { animation-duration: 1.5s; } }`;var $=o=>{let e={theme:o.theme,locale:o.locale},t={acceptLabel:o.acceptButtonLabel,cancel:o.showSelectorCancel,cancelLabel:o.cancelButtonLabel,header:o.showSelectorHeader,roomType:o.roomType,search:o.withSearch},n={isSDK:!0,fileId:!o.id||o.id==="undefined"||o.id==="null"?-1:o.id,editorType:o.editorType,share:o.requestToken?o.requestToken:void 0,is_file:o.requestToken?!0:void 0,editorGoBack:o.events?.onEditorCloseCallback&&typeof o.events.onEditorCloseCallback=="function"?"event":o.editorGoBack?o.editorGoBack:void 0};switch(o.mode){case"manager":{o.id&&(o.filter.folder=o.id);let r=o.requestToken?{key:o.requestToken,...o.filter}:o.filter;r?.withSubfolders||delete r?.withSubfolders;let s=h(r);return`${o.rootPath}${o.requestToken?`?${s}`:`${o.id?o.id+"/":""}filter?${s}`}`}case"room-selector":{let r={...e,...t},s=h(r);return`/sdk/room-selector${s?`?${s}`:""}`}case"file-selector":{let r={...e,...t,breadCrumbs:o.withBreadCrumbs,filter:o.filterParam,id:o.id,selectorType:o.selectorType,subtitle:o.withSubtitle},s=h(r);return`/sdk/file-selector${s?`?${s}`:""}`}case"public-room":{let r={...e,folder:o.id,key:o.requestToken,showFilter:o.showFilter,showHeader:o.showHeader,showTitle:o.showTitle},s=h(r);return`/sdk/public-room${s?`?${s}`:""}`}case"system":{let r=h(e);return`/old-sdk/system${r?`?${r}`:""}`}case"editor":{let r={...e,...n},s=h(r);return`/doceditor${s?`?${s}`:""}`}case"viewer":{let r={...e,...n,action:"view"},s=h(r);return`/doceditor${s?`?${s}`:""}`}default:return o.rootPath||"/"}};var y=class o{#n=!1;#t=[];#o=[];#s="";config;constructor(e){this.config=e}static _loaderCache={style:new Map,container:document.createElement("div"),templates:new Map};static _iframeCache;#c=e=>{let{frameId:t,width:n,height:r}=e,s=`${t}-loader__element`,a=`${n}_${r}`,i=o._loaderCache.style,l=o._loaderCache.templates;if(!i.has(s)){let m=document.createElement("style");m.textContent=R(s);let f=document.createDocumentFragment();f.appendChild(m),document.head.appendChild(f),i.set(s,m)}let c;if(l.has(a))c=l.get(a).cloneNode(!0),c.id=`${t}-loader`;else{c=o._loaderCache.container.cloneNode(),Object.assign(c.style,{width:n,height:r,display:"flex",justifyContent:"center",alignItems:"center",position:"relative",zIndex:"1",backgroundColor:"transparent",transition:"opacity 0.15s ease-out"});let m=document.createElement("div");m.className=s,c.appendChild(m),l.set(a,c.cloneNode(!0)),c.id=`${t}-loader`}return c};#m=e=>{if(!o._iframeCache){let w=document.createElement("iframe");w.allowFullscreen=!0,w.setAttribute("allow","storage-access *"),o._iframeCache={template:w,pathCache:new Map,styleCache:new Map}}let{mode:t,id:n,frameId:r,type:s,width:a,height:i,src:l,events:c,checkCSP:m}=e,f=s==="mobile",d=o._iframeCache.template.cloneNode(),v=`${t}_${n||""}_${r}`,F=`${a}_${i}_${f?"mobile":"desktop"}`,g=o._iframeCache.pathCache.get(v);g||(g=$(e),o._iframeCache.pathCache.set(v,g)),d.id=r,d.name=`${T}__#${r}`,d.src=l+g;let p=o._iframeCache.styleCache.get(F);return p||(p={width:a,height:i,border:"0px",opacity:"0",...f&&{position:"fixed",overflow:"hidden",webkitOverflowScrolling:"touch"}},o._iframeCache.styleCache.set(F,p)),Object.assign(d.style,p),f&&(document.body.style.overscrollBehaviorY!=="contain"&&(document.body.style.overscrollBehaviorY="contain"),"loading"in HTMLIFrameElement.prototype&&(d.loading="eager")),m&&this.#d(d,l,c),d};#d(e,t,n){requestAnimationFrame(()=>{P(t).catch(r=>{n?.onAppError?.(r.message),e.srcdoc=k(t),this.setIsLoaded()})})}setIsLoaded(){let{frameId:e,width:t,height:n,events:r}=this.config,s=document.getElementById(e),a=s?.parentElement;!s||!a||requestAnimationFrame(()=>{try{a.style.width=t,a.style.height=n;let i=document.getElementById(`${e}-loader`);i?(i.style.opacity="0",requestAnimationFrame(()=>{try{i.parentNode&&i.parentNode.removeChild(i),r?.onContentReady?.()}catch(l){console.error("Error removing loader:",l),r?.onContentReady?.()}})):r?.onContentReady?.(),requestAnimationFrame(()=>{Object.assign(s.style,{opacity:"1",position:"relative",width:t,height:n})})}catch(i){console.error("Error in setIsLoaded:",i),r?.onContentReady?.()}})}#i=e=>{try{let{frameId:t,src:n}=this.config,r=document.getElementById(t);if(!r?.contentWindow)return;let s={frameId:t,type:"",data:e};r.contentWindow.postMessage(JSON.stringify(s,(a,i)=>typeof i=="function"?i.toString():i),n)}catch(t){this.#r(t)}};#a=e=>{try{if(typeof e.data!="string")return;let t=this.#h(e.data);if(t.frameId!==this.config.frameId)return;switch(t.type){case"onMethodReturn":this.#f(t);break;case"onEventReturn":t.eventReturnData&&this.#u(t.eventReturnData);break;case"onCallCommand":this.#g(t);break;case"error":t.error&&this.#r(t.error);break;default:console.warn("Unrecognized message type:",t.type)}}catch(t){this.#r(t)}};#h(e){try{let t=JSON.parse(e);if(!t||typeof t!="object")throw new Error("Invalid message structure");return t.frameId||(t.frameId=""),t}catch(t){let n=t instanceof Error?t.message:"Unknown parsing error";return console.warn("Failed to parse message:",n),{frameId:"error",type:"error",commandName:"parseMessageData",error:{message:"Invalid message format: "+n}}}}#f(e){let t=this.#t.shift();if(t)try{t(e.methodReturnData||{})}catch(n){console.error("Error in callback execution:",n)}this.#o.length>0&&this.#i(this.#o.shift())}#u(e){if(!e?.event)return;let t=e.event,n=this.config.events?.[t];if(typeof n=="function")try{n(e.data||{})}catch(r){console.error("Event handler failed:",t,r)}}#g(e){if(!e.commandName)return;let t=this[e.commandName];typeof t=="function"&&t.call(this,e.commandData)}#r(e){console.error("SDK Error:",e),this.config.events?.onAppError?.(e instanceof Error?e.message:"Unknown error occurred")}#p(e,t,n){if(!this.#n&&e!=="setConfig"){this.#r({message:L});return}this.#t.push(n);let r={type:"method",methodName:e,data:t};this.#t.length>1?this.#o.push(r):this.#i(r)}#C(e){let t={...this.config,...C,...e};return(t.mode==="manager"||t.mode==="system")&&(t.noLoader=!1),t}#y(e){let t=document.getElementById(e);if(!t)return null;let n=document.getElementById(`${e}-container`);if(n){let r=n.parentNode;if(r){let s=document.createElement("div");s.id=e,r.replaceChild(s,n);let a=`${this.config.mode}_${this.config.id||""}_${this.config.frameId}`;return o._iframeCache.pathCache.delete(a),this.#l(s)}}return this.#s=t.className,this.#l(t)}#l(e){let t=document.createElement("div");return t.id=e.id+"-container",t.className="frame-container",Object.assign(t.style,{position:"relative",width:this.config.width,height:this.config.height}),{container:t,target:e}}#w(){let e=this.#m(this.config);return Object.assign(e.style,{opacity:this.config.noLoader?"1":"0",zIndex:"2",position:this.config.noLoader?"relative":"absolute",width:this.config.noLoader?this.config.width:"100%",height:this.config.noLoader?this.config.height:"100%",top:"0",left:"0"}),e}#b(e){let t=()=>{window.addEventListener("message",this.#a,!1),this.#n=!0,this.config.noLoader&&this.config.events?.onContentReady?.(),e.removeEventListener("load",t)};e.addEventListener("load",t)}#T(e,t,n){let r=document.createDocumentFragment();if((!this.config.waiting||this.config.mode==="system")&&r.appendChild(n),this.config.noLoader)e.style.height=this.config.height,e.style.width=this.config.width;else{let s=this.#c(this.config);r.appendChild(s)}return e.appendChild(r),t?.parentNode?(t.parentNode.insertBefore(e,t),t.remove()):t?.replaceWith(e),n}#E(){window.DocSpace.SDK.frames=window.DocSpace.SDK.frames||{},window.DocSpace.SDK.frames[this.config.frameId]=this}initFrame(e){this.config=this.#C(e);let t=this.#y(this.config.frameId);if(!t)return null;let{container:n,target:r}=t,s=this.#w();return this.#b(s),this.#T(n,r,s),this.#E(),s}destroyFrame(){let e=this.config.frameId,t=document.getElementById(`${e}-container`),n=document.createElement("div");if(n.id=e,n.className=this.#s,n.innerHTML=this.config.destroyText||"",t&&(t.parentNode?t.parentNode.replaceChild(n,t):document.body.appendChild(n),o._iframeCache)){let s=`${this.config.mode}_${this.config.id||""}_${this.config.frameId}`;o._iframeCache.pathCache.delete(s)}window.removeEventListener("message",this.#a),this.#n=!1,this.#t=[],this.#o=[];let r=window.DocSpace?.SDK?.frames;r&&e in r&&delete r[e]}#e=(e,t=null)=>new Promise(n=>{this.#p(e,t,r=>n(r))});setConfig(e=C){return this.config={...this.config,...e},this.#e("setConfig",this.config)}getConfig(){return this.config}getFolderInfo(){return this.#e("getFolderInfo")}getSelection(){return this.#e("getSelection")}getFiles(){return this.#e("getFiles")}getFolders(){return this.#e("getFolders")}getList(){return this.#e("getList")}getRooms(e){return this.#e("getRooms",e)}getUserInfo(){return this.#e("getUserInfo")}getHashSettings(){return this.#e("getHashSettings")}openModal(e,t){return this.#e("openModal",{type:e,options:t})}createFile(e,t,n,r){return this.#e("createFile",{folderId:e,title:t,templateId:n,formId:r})}createFolder(e,t){return this.#e("createFolder",{parentFolderId:e,title:t})}createRoom(e,t,n,r,s,a,i,l){return this.#e("createRoom",{title:e,roomType:t,...n!==void 0&&{quota:n},...l!==void 0&&{denyDownload:l},...r!==void 0&&{tags:r},...s!==void 0&&{color:s},...a!==void 0&&{cover:a},...i!==void 0&&{indexing:i}})}setListView(e){return this.#e("setListView",{viewType:e})}createHash(e,t){return this.#e("createHash",{password:e,hashSettings:t})}login(e,t,n,r){return this.#e("login",{email:e,passwordHash:t,...n!==void 0&&{password:n},...r!==void 0&&{session:r}})}logout(){return this.#e("logout")}createTag(e){return this.#e("createTag",{name:e})}addTagsToRoom(e,t){return this.#e("addTagsToRoom",{roomId:e,tags:t})}removeTagsFromRoom(e,t){return this.#e("removeTagsFromRoom",{roomId:e,tags:t})}executeInEditor(e,t){this.#e("executeInEditor",{callback:e,data:t})}};var u=class{frames={};init=e=>{let{frameId:t}=e,n=this.frames[t];if(n)return n.initFrame(e),n;let r=new y(e);return r.initFrame(e),this.frames[t]=r,r};initFrame=e=>this.init(e);initManager=e=>this.init({...e,mode:"manager"});initViewer=e=>this.init({...e,mode:"viewer"});initEditor=e=>this.init({...e,mode:"editor"});initRoomSelector=e=>this.init({...e,mode:"room-selector"});initFileSelector=e=>this.init({...e,mode:"file-selector"});initSystem=e=>this.init({...e,mode:"system"})};window.DocSpace=window.DocSpace||{};window.DocSpace.SDK=window.DocSpace.SDK||new u;var A=u;
/**
* (c) Copyright Ascensio System SIA 2025
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @license
*/