v1.js 97 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625
  1. if(!window.docAppData) window.docAppData = {
  2. lastAppUrl: '',
  3. originalDocumentTitle: document.title,
  4. documentTitleSuffix: ' - ' + document.title.split(' - ').pop(),
  5. currentUser: null,
  6. currentSpaceType: '',
  7. userPrivs: {},
  8. };
  9. const docAppData = window.docAppData;
  10. let savingDocData = {};
  11. let docBasicModal = {};
  12. let currentDocApp = null;
  13. window.setZentaoSlashMenu = function(menus, title, position)
  14. {
  15. if(!menus?.length) return;
  16. const slashMenus = menus.map(menu =>
  17. {
  18. if(menu.subMenu)
  19. {
  20. menu.subMenu = menu.subMenu.map(subMenu => {
  21. subMenu.action = function (context) {
  22. zui.Modal.open({
  23. size: subMenu.modalSize ? subMenu.modalSize : 'lg',
  24. url: $.createLink(subMenu.module, subMenu.method, subMenu.params)
  25. });
  26. }
  27. return subMenu;
  28. });
  29. }
  30. else
  31. {
  32. if(menu.key == 'gantt' && !menu.isModal)
  33. {
  34. menu.action = function (context) {
  35. const doc = getDocApp().doc;
  36. $.ajaxSubmit({
  37. url: $.createLink(menu.module, menu.method, menu.params),
  38. data: {templateID: doc.data.id}
  39. });
  40. }
  41. }
  42. else
  43. {
  44. menu.action = function (context) {
  45. zui.Modal.open({
  46. size: menu.modalSize ? menu.modalSize : 'lg',
  47. url: $.createLink(menu.module, menu.method, menu.params)
  48. });
  49. }
  50. }
  51. }
  52. return menu;
  53. });
  54. slashMenus.unshift({ groupName: title});
  55. zui.Editor.setSlashMenu(slashMenus, {before: position, reset: true});
  56. zui.Editor.setGlobalConfig({slashMenuStyles: [`link:${$.libRoot}zui.zentao.css`]});
  57. }
  58. /**
  59. * 更多菜单操作。
  60. * More menu action.
  61. *
  62. * @param {MoreMenuItem} menu
  63. */
  64. window.moreMenuAction = function(menu)
  65. {
  66. if (menu.module && menu.method && menu.params)
  67. {
  68. if(menu.key == 'gantt' && !menu.isModal)
  69. {
  70. const doc = getDocApp().doc;
  71. $.ajaxSubmit({
  72. url: $.createLink(menu.module, menu.method, menu.params),
  73. data: {templateID: doc.data.id}
  74. });
  75. }
  76. else {
  77. zui.Modal.open({
  78. size: menu.modalSize ? menu.modalSize : 'lg',
  79. url: $.createLink(menu.module, menu.method, menu.params)
  80. });
  81. }
  82. }
  83. }
  84. /* 获取 ZentaoList 块属性。 */
  85. function getZentaoListProps(type, blockID, props)
  86. {
  87. if(props && props.isTemplate) blockID = '__TML_ZENTAOLIST__' + blockID;
  88. const zentaoListLang = getLang('zentaoList');
  89. const exportUrl = `${location.origin}${$.createLink('doc', 'ajaxExportZentaoList', `blockID=${blockID}`)}`;
  90. const title = [(zentaoListLang ? zentaoListLang[type] : type), getLang('list')].join(config.clientLang.includes('zh') ? '' : ' ');
  91. const fetcher = `${location.origin}${$.createLink('doc', 'zentaoList', `type=${type}&blockID=${blockID}`)}`;
  92. return $.extend({}, props,
  93. {
  94. title: title,
  95. fetcher: fetcher,
  96. clearBeforeLoad: false
  97. }, type === 'gantt' ? {
  98. fetcher: fetcher,
  99. export: [{type: 'link', props: {text: title, href: exportUrl}}]
  100. } : {
  101. exportUrl: exportUrl,
  102. });
  103. }
  104. /* 更新禅道列表。*/
  105. window.updateZentaoList = function(blockID, props)
  106. {
  107. const $block = $('#docApp').find(`.zentao-list[data-id="${blockID}"]`);
  108. if(!$block.length) return false;
  109. getDocApp().editor.$.updateBlock($block[0], props);
  110. };
  111. /* 替换禅道列表。*/
  112. window.replaceZentaoList = function(oldBlockID, newType, newblockID, props)
  113. {
  114. return updateZentaoList(oldBlockID, {content: getZentaoListProps(newType, newblockID, props), renderID: $.guid++});
  115. };
  116. /* 插入禅道列表。*/
  117. window.insertZentaoList = function(type, blockID, props, replaceBlockID)
  118. {
  119. if(Number(replaceBlockID)) return replaceZentaoList(replaceBlockID, type, blockID, props);
  120. getDocApp().editor.$.insertCustom(getZentaoListProps(type, blockID, props));
  121. };
  122. /* 从编辑器删除禅道列表。*/
  123. window.deleteZentaoList = function(blockID)
  124. {
  125. const $block = $('#docApp').find(`.zentao-list[data-id="${blockID}"]`);
  126. if(!$block.length) return false;
  127. getDocApp().editor.$.deleteBlock($block[0]);
  128. };
  129. /* 重新载入禅道列表。*/
  130. window.reloadZentaoList = function(blockID)
  131. {
  132. $('#docApp').find(`.zentao-list[data-id="${blockID}"]`)
  133. .closest('.lazy-content')
  134. .trigger('loadContent');
  135. };
  136. /**
  137. * Get doc app instance.
  138. * 获取文档应用组件实例。
  139. *
  140. * @returns {object}
  141. */
  142. window.getDocApp = function()
  143. {
  144. if(!currentDocApp)
  145. {
  146. const $docApp = $('#docApp');
  147. const docApp = $docApp.data('zui.DocApp') || $docApp.data('zui.DocViewer');
  148. currentDocApp = docApp ? docApp.$ : null;
  149. }
  150. return currentDocApp;
  151. }
  152. /**
  153. * 获取语言项,如果没有设置 key,则获取整个语言项对象,语言项定义在 module/doc/ui/app.html.php 的 $langData 中。
  154. * Get language item, if key is not set, return the whole language object, language items are defined in $langData in module/doc/ui/app.html.php.
  155. *
  156. * @param {string} key
  157. * @param {array|string|object} args
  158. */
  159. window.getLang = function(key, args)
  160. {
  161. if(!docAppData.docLangData)
  162. {
  163. const docApp = getDocApp();
  164. docAppData.docLangData = docApp ? docApp.props.langData : {};
  165. }
  166. if(typeof key !== 'string') return docAppData.docLangData;
  167. const value = docAppData.docLangData[key];
  168. if(value === undefined) return;
  169. if(args)
  170. {
  171. args = Array.isArray(args) ? args : [args];
  172. args.unshift(value);
  173. return zui.formatString.apply(null, args);
  174. }
  175. return value;
  176. }
  177. /**
  178. * 检查是否有指定的权限,权限定义在 module/doc/ui/app.html.php 的 $privs 中。
  179. * Check if the specified privilege exists, privileges are defined in $privs in module/doc/ui/app.html.php.
  180. * @param {string} priv
  181. */
  182. window.hasPriv = function(priv, value)
  183. {
  184. const setting = docAppData.userPrivs[priv];
  185. return value !== undefined ? setting === value : !!setting;
  186. }
  187. /**
  188. * 处理文档应用销毁事件,销毁文档基本信息对话框。
  189. * Handle the doc app destroy event, destroy the doc basic info dialog.
  190. */
  191. function handleDocAppDestroy()
  192. {
  193. if(docBasicModal.current)
  194. {
  195. docBasicModal.current.destroy();
  196. docBasicModal = {};
  197. }
  198. }
  199. function isApiLib(lib, docApp)
  200. {
  201. if(docApp && docApp.spaceType === 'api') return true;
  202. if(typeof lib === 'number') lib = getDocApp().getLib(lib);
  203. if(!lib)
  204. {
  205. docApp = docApp || getDocApp();
  206. if(!docApp) return false;
  207. if(docApp.spaceType === 'api') return true;
  208. lib = docApp.lib;
  209. }
  210. return lib && lib.data.type === 'api';
  211. }
  212. function isApiDoc(doc)
  213. {
  214. const docApp = getDocApp();
  215. if(docApp && docApp.spaceType === 'api') return true;
  216. if(typeof doc !== 'object' && docApp) doc = docApp.getDoc(doc);
  217. if(doc && doc.api !== undefined) return doc.api;
  218. const id = typeof doc === 'object' ? doc.id : doc;
  219. return String(id).startsWith('api.');
  220. }
  221. /**
  222. * 处理对话框的操作,执行文档应用实例上的方法。
  223. * Process dialog actions, execute methods on the doc app instance.
  224. *
  225. * @param {string|array|object} action
  226. * @param {object} docApp
  227. */
  228. function processDocAppAction(action, docApp)
  229. {
  230. docApp = docApp || getDocApp();
  231. if(typeof action === 'string')
  232. {
  233. action = {call: action};
  234. }
  235. if(Array.isArray(action))
  236. {
  237. if(typeof action[0] !== 'string')
  238. {
  239. action.forEach((act) => processDocAppAction(act, docApp));
  240. return;
  241. }
  242. action = {call: action[0], args: action.slice(1)};
  243. }
  244. if(!action.mode && action.call.includes(':'))
  245. {
  246. const parts = action.call.split(':');
  247. action.mode = parts[0];
  248. action.call = parts[1];
  249. }
  250. if(action.mode && action.mode !== docApp.mode) return;
  251. const method = zui.deepGet(docApp, action.call);
  252. if(typeof method === 'function') method.apply(docApp, action.args);
  253. }
  254. /**
  255. * 检查空间是否可以进行修改操作,如果不指定空间则判断当前空间。
  256. * Check if the space can be modified, if the space is not specified, check the current space.
  257. *
  258. * @param {object|number} space
  259. */
  260. window.canModifySpace = function(space)
  261. {
  262. const docApp = getDocApp();
  263. if(!docApp && !space) return false;
  264. space = typeof space !== 'object' ? docApp.getSpace(space) : space;
  265. return space && space.canModify !== false;
  266. }
  267. /*
  268. * 修改 Ajax 表单提交后的默认处理方法,改为处理文档应用的操作。
  269. * Modify the default processing method after Ajax form submission to process the actions of the doc app.
  270. */
  271. zui.AjaxForm.DEFAULT.onResult = function(res)
  272. {
  273. const docApp = getDocApp();
  274. if(docApp && res.docApp)
  275. {
  276. /* 请求响应对象中的 docApp 属性定义了如何进行后续操作。 */
  277. processDocAppAction(res.docApp, docApp);
  278. delete res.docApp;
  279. delete res.load;
  280. delete res.locate;
  281. delete res.callback;
  282. }
  283. };
  284. let lastViewedSpaceHome = '';
  285. let lastViewedSpace = '';
  286. let lastViewedLib = '';
  287. /**
  288. * 向服务器提交最新访问的文档对象。
  289. * Post last viewed data to server.
  290. *
  291. * @param {object} location Doc App location info.
  292. * @returns void
  293. */
  294. function postLastViewedToServer(location)
  295. {
  296. if(!location) return;
  297. const postData = {};
  298. const {spaceType, spaceID, libID} = location;
  299. if(spaceType && spaceType !== lastViewedSpaceHome)
  300. {
  301. lastViewedSpaceHome = spaceType;
  302. postData.lastViewedSpaceHome = spaceType;
  303. }
  304. if(spaceID && spaceID !== lastViewedSpace)
  305. {
  306. const realSpaceID = typeof spaceID === 'number'
  307. ? spaceID
  308. : spaceID.split('.')[1];
  309. if(typeof realSpaceID === 'number')
  310. {
  311. lastViewedSpace = spaceID;
  312. postData.lastViewedSpace = spaceID;
  313. }
  314. }
  315. if(libID && libID !== lastViewedLib)
  316. {
  317. lastViewedLib = libID;
  318. postData.lastViewedLib = libID;
  319. }
  320. if(Object.keys(postData).length) $.post($.createLink('doc', 'ajaxSetLastViewed'), postData);
  321. }
  322. /**
  323. * 处理文档应用界面切换事件,修改浏览器地址栏 URL 和标题。
  324. * Handle the doc app view switch event, modify the browser address bar URL and title.
  325. *
  326. * @param {string} mode Doc App ui mode.
  327. * @param {object} location Doc App location info.
  328. * @param {object} info Doc App view info.
  329. * @returns
  330. */
  331. function handleSwitchView(mode, location, info)
  332. {
  333. if(!this.element || this.element.closest('.modal')) return;
  334. const rawModule = config.rawModule.toLowerCase();
  335. const rawMethod = config.rawMethod.toLowerCase();
  336. const formatUrl = this.props.viewModeUrl;
  337. const formatOptions = $.extend({recTotal: 0, recPerPage: 20, page: 1}, location, location.pager,
  338. {
  339. mode : mode,
  340. rawModule : rawModule,
  341. rawMethod : rawMethod,
  342. search : encodeURIComponent(location.search || ''),
  343. noSpace : location.noSpace || 0,
  344. filterType: encodeURIComponent(location.filterType || '')
  345. });
  346. postLastViewedToServer(location);
  347. if(typeof formatUrl === 'function')
  348. {
  349. url = formatUrl.call(this, formatOptions);
  350. }
  351. else if(mode === 'view' || mode === 'diff')
  352. {
  353. url = $.createLink('doc', 'view', `docID=${location.docID}` + (info.data && location.docVersion && location.docVersion !== info.data.version ? `&version=${location.docVersion}` : ''));
  354. }
  355. else
  356. {
  357. url = zui.formatString(formatUrl, formatOptions).replace('&libID=0&moduleID=0&docID=0&mode=home&orderBy=id_desc&recTotal=0&recPerPage=0&pageID=1&filterType=&search=&noSpace=false', '').replace('&libID=0&moduleID=0&browseType=all&param=&orderBy=&recTotal=0&recPerPage=20&pageID=1&mode=home&docID=0&search=', '');
  358. }
  359. if(url === docAppData.lastAppUrl) return;
  360. if(docAppData.lastAppUrl && !$.apps.getAppUrl().endsWith(url)) $.apps.updateAppUrl(url, info.title ? (info.title + docAppData.documentTitleSuffix) : docAppData.originalDocumentTitle);
  361. docAppData.lastAppUrl = url;
  362. if(docBasicModal.current)
  363. {
  364. docBasicModal.current.destroy();
  365. docBasicModal = {};
  366. }
  367. }
  368. function showDocBasicModal(parentID, docID, isDraft, modalType = 'doc', doc = null)
  369. {
  370. const docApp = getDocApp();
  371. const spaceType = docApp.spaceType;
  372. const spaceID = docApp.spaceID;
  373. const libID = docApp.libID;
  374. const moduleID = docApp.moduleID;
  375. const url = $.createLink('doc', 'setDocBasic', `objectType=${spaceType}&objectID=${spaceID}&libID=${libID}&moduleID=${moduleID}&parentID=${parentID || 0}&docID=${docID || 0}&isDraft=${isDraft ? 'yes' : 'no'}&modalType=${modalType}`);
  376. if(docBasicModal.doc === docID && docBasicModal.current)
  377. {
  378. docBasicModal.current.show();
  379. }
  380. else
  381. {
  382. if(docBasicModal.current) docBasicModal.current.destroy();
  383. docBasicModal.doc = docID;
  384. zui.Modal.open(
  385. {
  386. key : `${config.rawModule}-${config.rawMethod}-${spaceType}-${docID}`,
  387. ref : docBasicModal,
  388. url : url,
  389. destroyOnHide: !docID,
  390. cache : true,
  391. request: {
  392. method: "POST",
  393. data: {
  394. title: doc?.title,
  395. },
  396. error: error => {
  397. if(docBasicModal.current) docBasicModal.current.hide();
  398. showSaveFailedAlert(error);
  399. }
  400. },
  401. onHidden: () => {
  402. if(!docBasicModal.keepOnHide && docBasicModal.current) docBasicModal.current.destroy();
  403. },
  404. $onDestroy: () => {
  405. if(docBasicModal.current) docBasicModal = {};
  406. }
  407. });
  408. }
  409. return new Promise((resolve) => {window.docBasicModalResolver = resolve;});
  410. }
  411. window.beforeSetDocBasicInfo = function(_, form)
  412. {
  413. docBasicModal.keepOnHide = true;
  414. if (window.docBasicModalResolver) window.docBasicModalResolver(new FormData(form));
  415. zui.Modal.query('#setDocBasicForm').hide();
  416. return false;
  417. };
  418. function mergeDocFormData(doc, formData)
  419. {
  420. if(!doc || !formData) return;
  421. const keys = new Set(formData.keys());
  422. for(const key of keys)
  423. {
  424. const values = formData.getAll(key);
  425. if(!values.length) continue;
  426. if(key === 'module' || key === 'lib') doc[key] = +values[0];
  427. else doc[key] = values.length > 1 ? values : values[0];
  428. }
  429. return doc;
  430. }
  431. window.showSaveFailedAlert = function(error)
  432. {
  433. zui.Modal.alert(
  434. {
  435. title: getLang('saveDocFailed'),
  436. content: error instanceof Error ? error.message : String(error),
  437. actions: [
  438. {key: 'close'}
  439. ]
  440. });
  441. console.error('Save doc failed:', error);
  442. }
  443. /**
  444. * 向服务器提交新文档。
  445. * Submit new doc to server.
  446. *
  447. * @param {object} doc
  448. * @param {number} spaceID
  449. * @param {number} libID
  450. * @param {number} moduleID
  451. * @param {FormData} formData
  452. * @returns
  453. */
  454. function submitNewDoc(doc, spaceID, libID, moduleID, formData, afterCreate)
  455. {
  456. const docApp = getDocApp();
  457. if(docApp.isSavingDoc) return;
  458. docApp.isSavingDoc = true;
  459. $(docApp.element).find('[zui-command^="saveDoc"],[zui-command^="saveNewDoc"]').attr('disabled', true);
  460. const spaceType = docApp.signals.spaceType.value;
  461. const url = $.createLink('doc', 'create', `objectType=${spaceType}&objectID=${Math.max(spaceID, 0)}&libID=${libID}&moduleID=${moduleID}`);
  462. const docData =
  463. {
  464. rawContent : doc.content,
  465. content : doc.html,
  466. status : doc.status || 'normal',
  467. contentType: doc.contentType,
  468. type : doc.type || 'text',
  469. lib : libID,
  470. module : moduleID,
  471. parent : doc.parent,
  472. title : doc.title,
  473. keywords : doc.keywords,
  474. acl : 'private',
  475. space : spaceType,
  476. uid : (doc.uid || `doc${doc.id}`),
  477. template : doc.template
  478. };
  479. if(formData) mergeDocFormData(docData, formData);
  480. const getErrorMessage = (res) => {
  481. if(typeof res.message === 'string') return res.message;
  482. if(typeof res.message === 'object' && res.message && Object.values(res.message).length)
  483. {
  484. for(const x of Object.values(res.message))
  485. {
  486. if(typeof x === 'string') return x;
  487. if(Array.isArray(x) && x.length) return x[0];
  488. }
  489. }
  490. if(typeof data.error === 'string') return data.error;
  491. return getLang('errorOccurred');
  492. };
  493. return new Promise((resolve, reject) =>
  494. {
  495. $.post(url, docData, (res) =>
  496. {
  497. try
  498. {
  499. const data = JSON.parse(res);
  500. if(!checkResponse(data)) return;
  501. if(typeof data !== 'object' || data.result === 'fail')
  502. {
  503. throw new Error(getErrorMessage(data));
  504. }
  505. const newDoc = $.extend(doc, {id: data.id}, docData, data.doc, {status: doc.status || data.status});
  506. if (!newDoc.space.includes('.')) {
  507. newDoc.space = `${spaceType}.${docData[spaceType]}`;
  508. }
  509. resolve(newDoc);
  510. if(afterCreate)
  511. {
  512. docApp.load(null, null, null, {noLoading: true, picks: 'doc'}).then(() => {
  513. afterCreate(newDoc);
  514. });
  515. }
  516. }
  517. catch (error)
  518. {
  519. showSaveFailedAlert(error);
  520. reject(error);
  521. }
  522. }).fail(error => {
  523. resolve(false);
  524. showSaveFailedAlert(error);
  525. }).complete(() => {
  526. docApp.isSavingDoc = false;
  527. $(docApp.element).find('[zui-command^="saveDoc"],[zui-command^="saveNewDoc"]').removeAttr('disabled');
  528. });
  529. });
  530. }
  531. function submitEditDoc(doc, formData)
  532. {
  533. const url = $.createLink('doc', 'edit', `docID=${doc.id}`);
  534. const docApp = getDocApp();
  535. const docData = {status: 'normal', type: 'chapter'};
  536. if(formData) mergeDocFormData(docData, formData);
  537. return new Promise((resolve) => {
  538. $.post(url, docData, (res) =>
  539. {
  540. try
  541. {
  542. const data = JSON.parse(res);
  543. if(!checkResponse(data)) return;
  544. if(typeof data !== 'object' || data.result === 'fail')
  545. {
  546. let message = data.message || data.error || getLang('errorOccurred');
  547. if(typeof message === 'object') message = Object.values(message).map(x => Array.isArray(x) ? x.join('\n') : x).join('\n');
  548. throw new Error(message);
  549. }
  550. resolve(doc);
  551. }
  552. catch (error)
  553. {
  554. resolve(false);
  555. showSaveFailedAlert(error);
  556. if(!error.message) return;
  557. }
  558. }).fail(error => {
  559. resolve(false);
  560. showSaveFailedAlert(error);
  561. }).complete(() => {
  562. docApp.load(null, null, null, {noLoading: true, picks: 'doc'});
  563. });
  564. });
  565. }
  566. /**
  567. * 处理创建文档的操作请求,向服务器发送请求并返回创建的文档对象。
  568. * Handle the create doc operation request, send a request to the server and return the created doc object.
  569. */
  570. function handleCreateDoc(doc, spaceID, libID, moduleID)
  571. {
  572. return showDocBasicModal(0, 0, doc.status === 'draft', 'doc', doc).then((formData) => {
  573. return submitNewDoc(doc, spaceID, libID, moduleID, formData);
  574. });
  575. }
  576. /**
  577. * 处理保存文档的操作请求,向服务器发送请求并返回保存的文档对象。
  578. * Handle the save doc operation request, send a request to the server and return the saved doc object.
  579. */
  580. function handleSaveDoc(doc)
  581. {
  582. const docApp = getDocApp();
  583. if(docApp.isSavingDoc) return;
  584. docApp.isSavingDoc = true;
  585. $(docApp.element).find('[zui-command^="saveDoc"],[zui-command^="saveNewDoc"]').attr('disabled', true);
  586. const spaceType = doc.object ? doc.object.type : (doc.objectType || docApp.signals.spaceType.value);
  587. const libID = doc.libInfo ? doc.libInfo.id : (doc.lib || docApp.signals.libID.value);
  588. const moduleID = doc.module || docApp.signals.moduleID.value;
  589. const url = $.createLink('doc', 'edit', `docID=${doc.id}`);
  590. const docData = {
  591. rawContent : doc.content,
  592. status : doc.status || 'normal',
  593. contentType: doc.contentType,
  594. type : 'text',
  595. lib : libID,
  596. module : moduleID,
  597. parent : doc.parent,
  598. title : doc.title,
  599. keywords : doc.keywords,
  600. acl : doc.acl,
  601. content : doc.html,
  602. space : spaceType,
  603. uid : (doc.uid || `doc${doc.id}`),
  604. };
  605. if(Array.isArray(doc.files)) docData.files = doc.files.map(f => typeof f === 'object' ? f.id : f).join(',');
  606. if(doc.fromVersion) docData.fromVersion = doc.fromVersion;
  607. if(savingDocData[doc.id])
  608. {
  609. mergeDocFormData(docData, savingDocData[doc.id]);
  610. delete savingDocData[doc.id];
  611. }
  612. return new Promise((resolve) => {
  613. $.post(url, docData, (res) =>
  614. {
  615. try
  616. {
  617. const data = JSON.parse(res);
  618. if(!checkResponse(data)) return;
  619. if(typeof data !== 'object' || data.result === 'fail')
  620. {
  621. let message = data.message || data.error || getLang('errorOccurred');
  622. if(typeof message === 'object') message = Object.values(message).map(x => Array.isArray(x) ? x.join('\n') : x).join('\n');
  623. throw new Error(message);
  624. }
  625. doc = $.extend({}, doc, docData, data.doc);
  626. if(docApp.spaceType == 'quick')
  627. {
  628. resolve(false);
  629. const libType = docApp.lib.data.quickType;
  630. return loadPage($.createLink('doc', 'quick', `type=${libType}&docID=${doc.id}`));
  631. }
  632. const libID = +doc.lib;
  633. const lib = docApp.getLib(libID);
  634. if(!lib)
  635. {
  636. resolve(false);
  637. return loadPage($.createLink('doc', 'view', `docID=${doc.id}`));
  638. }
  639. delete doc.title;
  640. delete doc.keywords;
  641. delete doc.content;
  642. resolve(doc);
  643. }
  644. catch (error)
  645. {
  646. resolve(false);
  647. showSaveFailedAlert(error);
  648. if(!error.message) return;
  649. }
  650. }).fail(error => {
  651. resolve(false);
  652. showSaveFailedAlert(error);
  653. }).complete(() => {
  654. docApp.isSavingDoc = false;
  655. $(docApp.element).find('[zui-command^="saveDoc"],[zui-command^="saveNewDoc"]').removeAttr('disabled');
  656. const {id, acl, users, groups, addedBy} = doc;
  657. let isInEditGroups = false;
  658. for(let groupID of Object.values(userGroups))
  659. {
  660. if(groups.includes(groupID)) isInEditGroups = true;
  661. }
  662. if(acl == 'private' && !users.includes(docAppData.currentUser) && addedBy !== docAppData.currentUser && !isInEditGroups)
  663. {
  664. if(docApp.hasEditingDoc)
  665. {
  666. docApp.cancelEditDoc().then(() => {
  667. docApp.delete('doc', id);
  668. docApp.load(null, null, null, {noLoading: true, picks: 'doc'});
  669. });
  670. }
  671. else
  672. {
  673. docApp.delete('doc', id);
  674. docApp.load(null, null, null, {noLoading: true, picks: 'doc'});
  675. }
  676. }
  677. });
  678. });
  679. }
  680. /**
  681. * 检查给定的文档是否可以进行移动操作。
  682. * Check if the given doc can be moved.
  683. */
  684. function canMoveDoc(doc)
  685. {
  686. return !String(doc.id).startsWith('api.') && getDocApp().props.privs.moveDoc;
  687. }
  688. /**
  689. * 处理删除文档文件的请求。
  690. * Handle the request to delete the doc file.
  691. * @param {object} file File info object.
  692. * @param {object} doc Doc info object.
  693. */
  694. function deleteDocFile(file, doc)
  695. {
  696. zui.Modal.confirm(getLang('fileConfirmDelete')).then(result =>
  697. {
  698. if(!result) return;
  699. $.ajaxSubmit(
  700. {
  701. url: $.createLink('doc', 'deleteFile', `docID=${doc.id}&fileID=${file.id}&confirm=yes`),
  702. load: false,
  703. callback: null,
  704. onSuccess: (res) =>
  705. {
  706. if(res && typeof res === 'object' && res.result === 'success')
  707. {
  708. getDocApp().update('doc', $.extend({}, doc, {files: doc.files.filter(f => f.id !== file.id)}));
  709. zui.HistoryPanel.update({objectType: 'doc', objectID: doc.id});
  710. }
  711. }
  712. })
  713. });
  714. }
  715. /**
  716. * 处理重命名文件的请求。
  717. * Handle the request to rename the file.
  718. *
  719. * @param {object} file
  720. * @param {object} doc
  721. */
  722. function renameDocFile(file, doc)
  723. {
  724. let fileName = file.title;
  725. let extension = file.extension;
  726. if(extension && fileName.endsWith(`.${extension}`)) fileName = fileName.substring(0, fileName.length - extension.length - 1);
  727. zui.Modal.prompt({message: getLang('fileRename'), defaultValue: fileName, placeholder: fileName}).then(newName =>
  728. {
  729. if(!newName) return;
  730. fileName = newName;
  731. if(extension && fileName.endsWith(`.${extension}`))
  732. {
  733. fileName = fileName.substring(0, fileName.length - extension.length - 1);
  734. }
  735. else if(!extension && fileName.includes('.'))
  736. {
  737. extension = fileName.split('.').pop();
  738. fileName = fileName.substring(0, fileName.length - extension.length - 1);
  739. }
  740. $.ajaxSubmit(
  741. {
  742. url: $.createLink('file', 'edit', `fileID=${file.id}`),
  743. data: {fileName: newName, extension : file.extension},
  744. load: false,
  745. onComplete: (res) =>
  746. {
  747. if(!res || typeof res !== 'object') return;
  748. const updatedFile = $.extend({}, file, {title: extension ? `${fileName}.${extension}` : fileName, extension}, res.id ? res : {});
  749. getDocApp().update('doc', $.extend({}, doc, {files: doc.files.map(f => f.id === file.id ? updatedFile : f)}));
  750. }
  751. });
  752. });
  753. }
  754. async function importContentToEditor(type)
  755. {
  756. const docApp = getDocApp();
  757. if(!docApp) return;
  758. const editor = docApp.editor.$;
  759. if(!editor) return;
  760. let content = '';
  761. if(navigator.clipboard) content = await navigator.clipboard.readText();
  762. content = await zui.Modal.prompt({size: 'lg', message: `Import ${type}`, defaultValue: content, placeholder: 'Paste content here...', multiline: true});
  763. return getDocApp().importDoc(content, type);
  764. }
  765. /* Import markdown or json file to editor. */
  766. function importFileToEditor(type, options)
  767. {
  768. if(options && options.fromText) return importContentToEditor(type);
  769. const accept = type === 'markdown' ? '.md' : (type === 'confluence' ? '.html,.txt' : '.json');
  770. return zui.selectFile(accept).then(file => {
  771. if(!file) return;
  772. zui.readFile(file).then(content => {
  773. if(typeof content !== 'string' || !content.length) return;
  774. return getDocApp().importDoc(content, type, file.name.split('.').shift());
  775. });
  776. });
  777. }
  778. function isOpenVersion(version) {
  779. return /^\d/.test(version || $('#zuiCSS').attr('href').split('?v=').pop());
  780. }
  781. /**
  782. * 定义文档各个试图和 UI 元素的上的操作方法。
  783. * Define the operation methods on the views and UI elements of the doc.
  784. */
  785. const actionsMap =
  786. {
  787. /**
  788. * 定义首页的操作按钮。
  789. * Define the actions on the home page.
  790. *
  791. * @returns {array}
  792. */
  793. home: function()
  794. {
  795. return [
  796. hasPriv('createSpace') ? {icon: 'plus', btnType: 'primary', text: getLang('createSpace'), command: 'createSpace'} : null,
  797. ];
  798. },
  799. /**
  800. * 定义空间的操作按钮。
  801. * Define the actions of space.
  802. */
  803. space: function(info)
  804. {
  805. const lang = getLang();
  806. const items = [];
  807. const space = info.data; // Space info object.
  808. /* 获取侧边栏没有文档库时的操作按钮。 Get actions when sidebar no lib. */
  809. if(info.ui === 'sidebar-no-lib')
  810. {
  811. if(!canModifySpace(space) || !hasPriv('createLib')) return null;
  812. return [{icon: 'plus', text: lang.createLib, command: 'createLib', btnType: 'primary-pale'}];
  813. }
  814. if(hasPriv('editSpace')) items.push({text: lang.actions.editSpace, command: `editSpace/${space.id}`});
  815. if(hasPriv('deleteSpace')) items.push({text: lang.actions.deleteSpace, command: `deleteSpace/${space.id}`});
  816. if(!items.length) return;
  817. return [
  818. {type: 'dropdown', icon: 'cog-outline', square: true, caret: false, placement: info.ui === 'space-card' ? 'bottom-end' : 'top-end', items: items},
  819. ];
  820. },
  821. /**
  822. * 定义文档的操作按钮。
  823. * Define the actions of doc.
  824. */
  825. doc: function(info)
  826. {
  827. const lang = getLang();
  828. const doc = info.data;
  829. const canModify = canModifySpace();
  830. const isApi = isApiDoc(doc);
  831. const isTemplate = doc.templateType !== '';
  832. const canEditDoc = canModify && hasPriv(isApi ? 'editApi' : 'edit');
  833. const isChapter = doc.type === 'chapter';
  834. /* 侧边栏上的文档操作按钮。Doc actions in sidebar. */
  835. if(info.ui === 'sidebar')
  836. {
  837. if(!canModify) return [];
  838. const moreItems =
  839. [
  840. hasPriv('addChapter') ? {icon: 'plus', text: lang.addSubChapter, command: `addChapter/${doc.id}`} : null,
  841. hasPriv('addChapter') && doc.parent != 0 ? {icon: 'plus', text: lang.addSameChapter, command: `addChapter/${doc.parent}`} : null,
  842. !isTemplate && hasPriv('create') ? {icon: 'plus', text: lang.addSubDoc, command: `startCreateDoc/${doc.id}`} : null,
  843. !isChapter && canMoveDoc(doc) ? {icon: 'folder-move', text: lang.moveDoc, command: `moveDoc/${doc.id}`} : null,
  844. !doc.frozen && !isChapter && hasPriv('delete') ? {icon: 'trash', text: lang.delete, command: `deleteDoc/${doc.id}`} : null,
  845. isChapter && hasPriv('editChapter') ? {icon: 'pencil', text: lang.editChapter, command: `editChapter/${doc.id}`} : null,
  846. isChapter && hasPriv('deleteChapter') ? {icon: 'trash', text: lang.deleteChapter, command: `deleteDoc/${doc.id}`} : null,
  847. ];
  848. return [
  849. (!isChapter && hasPriv('sortDoc')) || (isChapter && hasPriv('sortChapter')) ? {icon: 'move cursor-move', className: 'sort-handler', hint: lang.sortDoc, size: 'xs'} : null,
  850. moreItems.every(item => item === null) ? null : {icon: 'ellipsis-v', caret: false, placement: 'bottom-end', size: 'xs', items: moreItems},
  851. ];
  852. }
  853. const moreItems = [];
  854. if(canModify && canMoveDoc(doc)) moreItems.push({icon: 'folder-move', text: lang.moveDoc, command: `moveDoc/${doc.id}`});
  855. if(!doc.frozen && canModify && hasPriv('delete')) moreItems.push({icon: 'trash', text: lang.delete, command: `deleteDoc/${doc.id}`});
  856. if(!isApi && canModify && hasPriv('effort')) moreItems.push({icon: 'time', text: lang.effort, command: `effortDoc/${doc.id}`});
  857. if(!isApi && !isTemplate)
  858. {
  859. const canExportWord = hasPriv('exportDoc');
  860. if(canExportWord && (doc.contentType === 'doc' || doc.contentType === 'markdown'))
  861. {
  862. const exportItems = [
  863. {text: lang.exportWord, command: 'exportWord'},
  864. config.debug > 5 ? {text: lang.exportPdf, command: 'exportDoc/pdf'} : null,
  865. config.debug > 5 ? {text: lang.exportImage, command: 'exportDoc/png'} : null,
  866. {text: lang.exportMarkdown, command: 'exportDoc/markdown'},
  867. {text: lang.exportHtml, command: 'exportDoc/html'},
  868. {text: lang.exportJSON, command: 'exportDoc/json'},
  869. ].filter(Boolean);
  870. moreItems.push({icon: 'export', text: lang.export, items: exportItems});
  871. }
  872. else if(canExportWord)
  873. {
  874. moreItems.push({icon: 'export', text: lang.export, command: 'exportWord'});
  875. }
  876. }
  877. if (isApi) {
  878. const canExportApi = hasPriv('exportApi');
  879. if (canExportApi) {
  880. moreItems.push({icon: 'export', text: lang.export, command: 'exportApi'});
  881. }
  882. }
  883. const docApp = this;
  884. const isOpen = isOpenVersion(config.version);
  885. if(!isOpen && docApp && docApp.mode === 'view' && doc.status != 'draft' && !doc.api && !isTemplate)
  886. {
  887. moreItems.push({icon: 'link', text: getLang('relateObject'), className: 'relateObject-btn', command: 'toggleViewSideTab/relateObject'})
  888. }
  889. const isToolbar = info.ui === 'toolbar';
  890. const isInModal = $(this.element).closest('.modal').length;
  891. let aiAction = null;
  892. let aiTeammateAction = null;
  893. const docAIPrompts = window.docAIPrompts;
  894. if(!isApi && docAIPrompts && docAIPrompts.length)
  895. {
  896. const aiLang = window.docAIPromptLang;
  897. const aiActionItems = docAIPrompts.map(prompt => ({icon: 'magic', text: prompt.status !== 'active' ? zui.jsx`${prompt.name}<span class="label size-sm gray-500-pale ring-gray-500 whitespace-nowrap ml-1">${aiLang.statuses[prompt.status]}</span>` : prompt.name, command: `executeAIPrompt/${prompt.id}/${doc.id}`, hint: prompt.desc}));
  898. if(aiActionItems.length === 1) aiAction = aiActionItems[0];
  899. else aiAction = {icon: 'lightning', text: aiLang.dropdownTitle || 'AI', type: 'dropdown', btnType: 'ai-styled', size: 'sm', caret: 'down', placement: 'bottom-end', items: aiActionItems};
  900. const aiTeammateLang = window.docAITeammateLang;
  901. const aiTeammates = window.docAITeammates;
  902. if(aiTeammates.length)
  903. {
  904. const aiTeammateItems = aiTeammates.map(teammate => {
  905. const name = aiTeammateLang.nameLabel.replace('%s', teammate.name);
  906. return {text: zui.jsx`<img src="${teammate.avatar}" class="avatar rounded-full mr-2" style="width: 20px; height: 20px; line-height: 20px;" /> ${name}`, hint: name, command: `assignAITeammate/${teammate.id}/${doc.id}`,};
  907. });
  908. aiTeammateAction = {icon: 'hand-right', text: aiTeammateLang.dropdownTitle, type: 'dropdown', btnType: 'ai-styled', size: 'sm', caret: 'down', placement: 'bottom-end', items: aiTeammateItems};
  909. }
  910. }
  911. const actions = isInModal ? [] : [
  912. aiAction,
  913. aiTeammateAction,
  914. !isApi && canViewAITask ? {hint: lang.aiTask, icon: 'task-list', command: `viewAITasks/${doc.id}`} : null,
  915. isToolbar ? {hint: docApp.fullscreen ? lang.exitFullscreen : lang.enterFullscreen, icon: docApp.fullscreen ? 'fullscreen-exit' : 'fullscreen', command: 'toggleFullscreen'} : null,
  916. canEditDoc ? {icon: 'edit', class: doc.editable ? null : 'disabled', type: doc.editable ? 'ghost text-primary' : 'ghost text-gray', hint: doc.editable ? lang.edit : lang.needEditable, rounded: 'lg', command: doc.editable ? 'startEditDoc' : null} : null,
  917. (isToolbar && docApp.props.showDocOutline !== false) ? {hint: lang.docOutline, icon: 'list-box', command: 'toggleViewSideTab/outline'} : null,
  918. (isToolbar && docApp.props.showDocHistory !== false) ? {hint: lang.history, icon: 'file-log', command: 'toggleViewSideTab/history'} : null,
  919. moreItems.length ? {icon: 'icon-ellipsis-v', type: 'dropdown', rounded: 'lg', placement: 'bottom-end', caret: false, items: moreItems} : null,
  920. ];
  921. return actions;
  922. },
  923. /**
  924. * 定义文档库的操作按钮。
  925. * Define the actions of modules.
  926. */
  927. lib: function(info)
  928. {
  929. const docApp = getDocApp();
  930. const lang = getLang();
  931. const items = [];
  932. const lib = info.data;
  933. const canModify = canModifySpace() || docApp === null;
  934. const canAddModule = canModify && hasPriv('addModule');
  935. /* 获取侧边栏没有模块时的操作按钮。 Get actions when sidebar no module. */
  936. if(info.ui === 'sidebar-no-module')
  937. {
  938. if(!canAddModule) return;
  939. return [{text: lang.actions.addModule, command: `addModule/${lib.id}/0/${lib.id}/child`, icon: 'plus', type: 'primary-pale'}];
  940. }
  941. if(canAddModule && info.ui !== 'space-card' && info.ui !== 'sidebar') items.push({text: lang.actions.addModule, command: `addModule/${lib.id}/0/${lib.id}/child`});
  942. if(canModify && hasPriv('editLib')) items.push({text: lang.actions.editLib, command: `editLib/${lib.id}`});
  943. if(canModify && lib.type !== 'api' && hasPriv('moveLib') && info.ui !== 'space-card' && info.ui !== 'sidebar-toolbar') items.push({text: lang.moveTo, command: `moveLib/${lib.id}`});
  944. if(canModify && hasPriv('deleteLib')) items.push({text: lang.actions.deleteLib, command: `deleteLib/${lib.id}`});
  945. if(!items.length) return;
  946. if(info.ui === 'sidebar')
  947. {
  948. return [
  949. hasPriv('sortDoclib') ? {icon: 'move cursor-move', className: 'sort-handler', hint: lang.sortDoclib, size: 'xs'} : null,
  950. items.length ? {icon: 'ellipsis-v', caret: false, placement: 'bottom-end', size: 'xs', items: items} : null,
  951. ];
  952. }
  953. return [
  954. {type: 'dropdown', icon: info.ui === 'space-card' ? 'ellipsis-v' : 'cog-outline', square: true, caret: false, placement: info.ui === 'space-card' ? 'bottom-end' : 'top-end', items: items},
  955. ];
  956. },
  957. /**
  958. * 定义目录的操作按钮。
  959. * Define the actions on the lib page.
  960. */
  961. module: function(info)
  962. {
  963. const lang = getLang();
  964. const items = [];
  965. const module = info.data;
  966. if(hasPriv('addModule')) items.push({text: lang.actions.addSameModule, command: `addModule/${module.lib}/${module.parent || module.lib}/${module.id}/same`}, {text: lang.actions.addSubModule, command: `addModule/${module.lib}/${module.id}/${module.id}/child`});
  967. if(hasPriv('editModule')) items.push({text: lang.actions.editModule, command: `editModule/${module.id}`});
  968. if(hasPriv('deleteModule')) items.push({text: lang.actions.delModule, command: `deleteModule/${module.id}`});
  969. if(info.ui === 'sidebar')
  970. {
  971. return [
  972. hasPriv('sortModule') ? {icon: 'move cursor-move', className: 'sort-handler', hint: lang.sortLib, size: 'xs'} : null,
  973. items.length ? {icon: 'ellipsis-v', caret: false, placement: 'bottom-end', size: 'xs', items: items} : null,
  974. ];
  975. }
  976. return items;
  977. },
  978. /**
  979. * 定义文档表格操作栏的操作按钮。
  980. * Define the actions on the doc table footer.
  981. */
  982. 'doc-table': function(info)
  983. {
  984. const docApp = this;
  985. return [hasPriv('batchMoveDoc') ? {
  986. text: getLang('batchMove'),
  987. onClick: function()
  988. {
  989. /* Get all selected doc id list. */
  990. const selections = info.dtable.getChecks();
  991. if(!selections.length) return;
  992. const docIdList = window.btoa(JSON.stringify(selections));
  993. const spaceType = docApp.spaceType;
  994. const spaceID = docApp.spaceID;
  995. const libID = docApp.libID;
  996. const moduleID = docApp.moduleID;
  997. const url = $.createLink('doc', 'batchMoveDoc', 'type=' + spaceType + '&docIdList=' + docIdList + '&spaceID=' + spaceID + '&libID=' + libID + '&moduleID=' + moduleID);
  998. zui.Modal.open({size: 'sm', url: url});
  999. }
  1000. } : null];
  1001. },
  1002. /**
  1003. * 定义文档列表的操作按钮。
  1004. * Define the actions on the doc list.
  1005. */
  1006. 'doc-list': function(info)
  1007. {
  1008. const docApp = this;
  1009. const lang = getLang();
  1010. const canModify = canModifySpace();
  1011. const libID = docApp.libID;
  1012. const docID = docApp.docID;
  1013. if(isApiLib(docApp.lib))
  1014. {
  1015. if(!canModify) return;
  1016. const canCreateApi = hasPriv('createApi');
  1017. const command = 'startCreateDoc/' + docID + '/api';
  1018. if(info.ui === 'doc-list-empty')
  1019. {
  1020. return canCreateApi ? [{icon: 'plus', text: lang.createApi, btnType: 'primary', command}] : null;
  1021. }
  1022. const canCreateLib = hasPriv('createLib');
  1023. const items =
  1024. [
  1025. canCreateApi ? {icon: 'plus', text: lang.createApi, command} : null,
  1026. (canCreateApi && canCreateLib) ? {type: 'divider'} : null,
  1027. canCreateLib ? {icon: 'wiki-lib', text: lang.createLib, command: 'createLib'} : null,
  1028. ].filter(Boolean);
  1029. const canExportApi = hasPriv('exportApi') && libID;
  1030. return [
  1031. canExportApi ? {type: 'divider', style: {margin: '6px 0'}} : null,
  1032. canExportApi ? {icon: 'export', text: lang.export, command: 'exportApi'} : null,
  1033. items.length ? {icon: 'plus', type: 'dropdown', btnType: 'primary', size: 'md', text: lang.create, items: items} : null,
  1034. ];
  1035. }
  1036. const canCreateDoc = canModify && hasPriv('create');
  1037. const canCreateLib = canModify && hasPriv('createLib');
  1038. const canCreateSpace = canModify && hasPriv('createSpace');
  1039. const canCreateOffice = canModify && hasPriv('createOffice');
  1040. const canUploadDoc = canModify && hasPriv('uploadFile');
  1041. const canExportDoc = hasPriv('exportDoc') && docApp.spaceType !== 'quick';
  1042. /* 文档列表没有文档时的按钮。Actions for empty doc list. */
  1043. if(info.ui === 'doc-list-empty')
  1044. {
  1045. return canCreateDoc ? [{icon: 'plus', text: lang.createDoc, btnType: 'primary', command: `startCreateDoc/${docID}`}] : null;
  1046. }
  1047. const items = canModify ?
  1048. [
  1049. canCreateDoc ? {icon: 'plus', text: lang.createDoc, command: `startCreateDoc/${docID}`} : null,
  1050. canUploadDoc ? {icon: 'import', text: lang.uploadDoc, command: 'uploadDoc'} : null,
  1051. canCreateDoc ? {type: 'divider'} : null,
  1052. canCreateOffice ? {icon: 'file-word', text: lang.createList.word, command: 'startCreateOffice/word'} : null,
  1053. canCreateOffice ? {icon: 'file-powerpoint', text: lang.createList.ppt, command: 'startCreateOffice/ppt'} : null,
  1054. canCreateOffice ? {icon: 'file-excel', text: lang.createList.excel, command: 'startCreateOffice/excel'} : null,
  1055. (canCreateOffice && (canCreateLib || canCreateSpace)) ? {type: 'divider'} : null,
  1056. canCreateSpace ? {icon: 'cube', text: lang.createSpace, command: 'createSpace'} : null,
  1057. canCreateLib ? {icon: 'wiki-lib', text: lang.createLib, command: 'createLib'} : null,
  1058. ].filter(Boolean) : [];
  1059. return [
  1060. ((canExportDoc && libID > 0) || canCreateDoc) ? {type: 'divider', style: {margin: '6px 0'}} : null,
  1061. canExportDoc && libID > 0 ? {icon: 'export', text: lang.export, command: 'exportWord'} : null, // 不在库中,无法导出
  1062. items.length ? {icon: 'plus', type: 'dropdown', btnType: 'primary', size: 'md', text: lang.create, items: items} : null,
  1063. ];
  1064. },
  1065. /**
  1066. * 定义文档编辑时的操作按钮。
  1067. * Define the actions on toolbar of the doc editing page.
  1068. */
  1069. 'doc-edit': function(info)
  1070. {
  1071. const doc = info.data;
  1072. if(!doc) return;
  1073. const lang = getLang();
  1074. if(isApiLib())
  1075. {
  1076. return [
  1077. {text: lang.save, size: 'md', className: 'btn-wide', type: 'primary', command: 'saveApiDoc'},
  1078. {text: lang.cancel, size: 'md', className: 'btn-wide', type: 'primary-outline', command: 'cancelEditDoc'},
  1079. ];
  1080. }
  1081. const moreItems = [];
  1082. if(!enableHocuspocus && (doc.contentType === 'doc' || doc.contentType === 'markdown') && !isApiDoc(doc))
  1083. {
  1084. if(config.debug > 5) moreItems.push({text: lang.importConfluence, command: 'importFile/confluence'});
  1085. moreItems.push(
  1086. {text: lang.importMarkdown, command: 'importFile/markdown'},
  1087. {text: lang.importJSON, command: 'importFile/json'},
  1088. {type: 'divider'},
  1089. {text: lang.exportJSON, command: 'exportDoc/json'},
  1090. );
  1091. }
  1092. const isToolbar = info.ui === 'toolbar';
  1093. const docApp = this;
  1094. return [
  1095. isToolbar ? {hint: docApp.fullscreen ? lang.exitFullscreen : lang.enterFullscreen, icon: docApp.fullscreen ? 'fullscreen-exit' : 'fullscreen', command: 'toggleFullscreen'} : null,
  1096. (isToolbar && docApp.props.showDocOutline !== false) ? {hint: lang.docOutline, icon: 'list-box', command: 'toggleViewSideTab/outline'} : null,
  1097. (isToolbar && docApp.props.showDocHistory !== false) ? {hint: lang.history, icon: 'file-log', command: 'toggleViewSideTab/history'} : null,
  1098. doc.status === 'draft' ? {text: lang.saveDraft, size: 'md', className: 'btn-wide', type: 'secondary', command: 'saveDoc/draft'} : null,
  1099. {text: lang.release, size: 'md', className: 'btn-wide', type: 'primary', command: 'saveDoc'},
  1100. {text: lang.cancel, size: 'md', className: 'btn-wide', type: 'primary-outline', command: 'cancelEditDoc'},
  1101. {text: lang.settings, size: 'md', type: 'ghost', command: `showDocSettingModal/${doc.id}/${doc.contentType}/1`, icon: 'cog-outline'},
  1102. moreItems.length ? {icon: 'icon-ellipsis-v', type: 'dropdown', rounded: 'lg', placement: 'bottom-end', caret: false, items: moreItems} : null,
  1103. ].filter(Boolean);
  1104. },
  1105. /**
  1106. * 定义文档创建时的操作按钮。
  1107. * Define the actions on toolbar of the doc creating page.
  1108. */
  1109. 'doc-create': function(info)
  1110. {
  1111. const lang = getLang();
  1112. if(isApiLib())
  1113. {
  1114. return [
  1115. {text: lang.save, size: 'md', className: 'btn-wide', type: 'primary', command: 'saveApiDoc'},
  1116. {text: lang.cancel, size: 'md', className: 'btn-wide', type: 'primary-outline', command: 'cancelCreateDoc'},
  1117. ];
  1118. }
  1119. const moreItems = [];
  1120. const creatingDoc = this.signals.creatingDoc.value;
  1121. if(creatingDoc && creatingDoc.contentType === 'doc')
  1122. {
  1123. moreItems.push(
  1124. {text: lang.importMarkdown, command: 'importFile/markdown'},
  1125. {text: lang.importJSON, command: 'importFile/json'},
  1126. {type: 'divider'},
  1127. {text: lang.exportJSON, command: 'exportDoc/json'},
  1128. );
  1129. }
  1130. const isToolbar = info.ui === 'toolbar';
  1131. const docApp = this;
  1132. return [
  1133. isToolbar ? {hint: docApp.fullscreen ? lang.exitFullscreen : lang.enterFullscreen, icon: docApp.fullscreen ? 'fullscreen-exit' : 'fullscreen', command: 'toggleFullscreen'} : null,
  1134. (isToolbar && docApp.props.showDocOutline !== false) ? {hint: lang.docOutline, icon: 'list-box', command: 'toggleViewSideTab/outline'} : null,
  1135. {text: lang.saveDraft, size: 'md', className: 'btn-wide', type: 'secondary', command: 'saveNewDoc/draft'},
  1136. {text: lang.release, size: 'md', className: 'btn-wide', type: 'primary', command: 'saveNewDoc'},
  1137. {text: lang.cancel, size: 'md', className: 'btn-wide', type: 'primary-outline', command: 'cancelCreateDoc'},
  1138. moreItems.length ? {icon: 'icon-ellipsis-v', type: 'dropdown', rounded: 'lg', placement: 'bottom-end', caret: false, items: moreItems} : null,
  1139. ];
  1140. },
  1141. /**
  1142. * 定义文件的操作按钮。
  1143. * Define the actions of file.
  1144. */
  1145. file: function(info)
  1146. {
  1147. const doc = info.doc;
  1148. const file = info.data;
  1149. const docApp = getDocApp();
  1150. const isReadonly = docApp.mode === 'view';
  1151. const privs = docApp.props.privs;
  1152. const lang = getLang();
  1153. const canEdit = !isReadonly && privs.edit && (!doc.privs || doc.privs.edit !== false) && privs.editFile;
  1154. const canDelete = !isReadonly && privs.edit && (!doc.privs || doc.privs.edit !== false) && privs.deleteFile;
  1155. const canDownload = privs.downloadFile;
  1156. let previewAction = null;
  1157. let isOfficeFile = 'doc|docx|xls|xlsx|ppt|pptx|pdf'.includes(file.extension);
  1158. let canPreview = privs.previewFile && 'txt|jpg|jpeg|gif|png|bmp|mp4'.includes(file.extension);
  1159. if(privs.previewFile && typeof libreOfficeTurnon !== 'undefined' && libreOfficeTurnon && isOfficeFile) canPreview = true;
  1160. if(canPreview)
  1161. {
  1162. previewAction = {url: $.createLink('file', 'download', `fileID=${file.id}&mouse=left`), hint: lang.filePreview, icon: 'eye', target: '_blank'};
  1163. if(!isOfficeFile)
  1164. {
  1165. previewAction['data-toggle'] = 'modal';
  1166. previewAction['data-size'] = 'lg';
  1167. delete previewAction.target;
  1168. }
  1169. }
  1170. return [
  1171. previewAction,
  1172. canDownload ? {target: '_blank', url: zui.formatString(docApp.props.fileUrl, file), hint: lang.fileDownload, icon: 'download'} : null,
  1173. canEdit ? {hint: lang.fileRename, icon: 'pencil-alt', onClick: renameDocFile.bind(this, file, doc)} : null,
  1174. canDelete ? {hint: lang.fileDelete, icon: 'trash', onClick: deleteDocFile.bind(this, file, doc)} : null,
  1175. ].filter(Boolean);
  1176. },
  1177. 'file-list': function(info)
  1178. {
  1179. return [hasPriv('exportFiles') ? {icon: 'export', text: getLang('export'), command: 'exportFiles'} : null];
  1180. }
  1181. };
  1182. function getActions(type, info)
  1183. {
  1184. const builder = actionsMap[type];
  1185. if(builder) return builder.call(this, info);
  1186. }
  1187. /**
  1188. * 定义界面操作命令。文档中的大部分操作按钮都会调用这里定义的命令。
  1189. * Define the UI commands. Most of the action buttons in the doc will call the commands defined here.
  1190. */
  1191. const commands =
  1192. {
  1193. /* 创建文档。 Create doc. */
  1194. startCreateDoc: function(_, args)
  1195. {
  1196. const docApp = getDocApp();
  1197. if(!docApp.libList.length) return zui.Modal.alert(getLang('createLibFirst'));
  1198. const docType = (args && args[1]) || 'doc';
  1199. const {spaceType} = docApp;
  1200. if(spaceType === 'api' || docType === 'api') return docApp.startCreateDoc();
  1201. const templateID = args?.[1] ?? 0;
  1202. const {spaceID, libID, moduleID} = docApp;
  1203. return showDocBasicModal(args?.[0] ?? 0, 0, true, docType).then((formData) => {
  1204. zui.Editor.loadModule().then(() => {
  1205. const emptyDoc = zui.Editor.createEmptyDoc();
  1206. const snapshot = zui.Editor.toSnapshot(emptyDoc);
  1207. const doc = {contentType: 'doc', status: 'draft', content: JSON.stringify(snapshot), template: templateID};
  1208. return submitNewDoc(doc, spaceID, libID, moduleID, formData, (newDoc) => {
  1209. docApp.selectDoc(newDoc.id);
  1210. docApp.startEditDoc(newDoc.id);
  1211. });
  1212. });
  1213. });
  1214. },
  1215. startEditDoc: function(_, [doc], options)
  1216. {
  1217. const docApp = getDocApp();
  1218. doc = doc || docApp._doc.value?.data;
  1219. if (typeof doc !== 'object') {
  1220. doc = docApp._treeMap.value.docs.get(doc)?.data;
  1221. }
  1222. if(doc.frozen) return zui.Modal.alert(getLang('frozenTips').replace('%s', getLang('edit')));
  1223. /** 如果是附件类型并且没有内容的文档,则跳转到上传文档页面进行编辑。 */
  1224. if(doc.type === 'attachment' && !doc.hasContent) {
  1225. const type = docApp.lib ? docApp.lib.data.type : docApp.spaceType;
  1226. const url = $.createLink('doc', 'uploadDocs', `docID=${doc.id}&objectType=${type}&objectID=${docApp.spaceID}&libID=${doc.lib}&moduleID=${doc.module}&type=attachment`);
  1227. zui.Modal.open({url: url});
  1228. return false;
  1229. }
  1230. return docApp.startEditDoc(doc, options);
  1231. },
  1232. /** 上传文档。Upload Doc. */
  1233. uploadDoc: function(_, args)
  1234. {
  1235. const docApp = getDocApp();
  1236. const docID = args[0] || docApp.docID
  1237. const type = docApp.lib ? docApp.lib.data.type : docApp.spaceType;
  1238. const url = $.createLink('doc', 'uploadDocs', `docID=${docID}&objectType=${type}&objectID=${docApp.spaceID}&libID=${docApp.libID}&moduleID=${docApp.moduleID}&type=attachment`);
  1239. zui.Modal.open({url: url});
  1240. },
  1241. /** 创建 Office 文件。 Start create office file. */
  1242. startCreateOffice: function(_, args)
  1243. {
  1244. const type = args[0];
  1245. const docApp = getDocApp();
  1246. const url = $.createLink('doc', 'create', `objectType=${docApp.spaceType}&objectID=${docApp.spaceID}&libID=${docApp.libID}&moduleID=${docApp.moduleID}&type=${type}`);
  1247. zui.Modal.open({url: url});
  1248. },
  1249. createSpace: function()
  1250. {
  1251. const docApp = getDocApp();
  1252. const params = docApp.spaceType == 'mine' ? 'type=mine' : '';
  1253. const url = $.createLink('doc', 'createSpace', params);
  1254. zui.Modal.open({size: 'sm', url: url});
  1255. },
  1256. editSpace: function(_, args)
  1257. {
  1258. const docApp = getDocApp();
  1259. const spaceID = args[0] || docApp.spaceID;
  1260. const url = $.createLink('doc', 'editSpace', `libID=${spaceID}`);
  1261. zui.Modal.open({size: 'sm', url: url});
  1262. },
  1263. deleteSpace: function(_, args)
  1264. {
  1265. const docApp = getDocApp();
  1266. const spaceID = args[0] || docApp.spaceID;
  1267. $.ajaxSubmit(
  1268. {
  1269. confirm: getLang('confirmDeleteSpace'),
  1270. url: $.createLink('doc', 'deleteSpace', `libID=${spaceID}`),
  1271. load: false,
  1272. onSuccess: function(res)
  1273. {
  1274. if(res && res.result === 'success')
  1275. {
  1276. const docApp = getDocApp();
  1277. if(spaceID === docApp.spaceID && docApp.mode !== 'home')
  1278. {
  1279. const spaceList = docApp.spaceList.filter(x => x.id !== spaceID);
  1280. if(spaceList.length)
  1281. {
  1282. docApp.selectSpace(spaceList[0].id);
  1283. return;
  1284. }
  1285. docApp.switchView({spaceID: 0, libID: 0, moduleID: 0, docID: 0}, 'home');
  1286. }
  1287. docApp.delete('space', spaceID);
  1288. }
  1289. }
  1290. });
  1291. },
  1292. createLib: function(_, args)
  1293. {
  1294. const docApp = getDocApp();
  1295. const spaceID = args[0] || docApp.spaceID;
  1296. const url = $.createLink('doc', 'createLib', spaceID ? `type=${docApp.spaceType}&objectID=${spaceID}` : `type=${docApp.spaceType}`);
  1297. zui.Modal.open({size: 'sm', url: url});
  1298. },
  1299. moveLib: function(_, args)
  1300. {
  1301. const docApp = getDocApp();
  1302. const libID = args[0] || docApp.libID;
  1303. const url = $.createLink('doc', 'moveLib', `libID=${libID}`);
  1304. zui.Modal.open({size: 'sm', url: url});
  1305. },
  1306. editLib: function(_, args)
  1307. {
  1308. const docApp = getDocApp();
  1309. const libID = args[0] || docApp.libID;
  1310. const url = $.createLink(isApiLib(libID) ? 'api' : 'doc', 'editLib', `libID=${libID}`);
  1311. zui.Modal.open({size: 'sm', url: url});
  1312. },
  1313. deleteLib: function(_, args)
  1314. {
  1315. const docApp = getDocApp();
  1316. const libID = args[0] || docApp.libID;
  1317. $.ajaxSubmit(
  1318. {
  1319. confirm: getLang('confirmDeleteLib'),
  1320. url: $.createLink('doc', 'deleteLib', `libID=${libID}`),
  1321. load: false,
  1322. onSuccess: function()
  1323. {
  1324. const docApp = getDocApp();
  1325. docApp.delete('lib', libID);
  1326. if(docApp.mode === 'home') docApp.loadHomeLibs();
  1327. }
  1328. });
  1329. },
  1330. addModule: function(_, args)
  1331. {
  1332. zui.Modal.prompt({message: getLang('moduleName')}).then(newMoudleName =>
  1333. {
  1334. if(!newMoudleName) return;
  1335. const docApp = getDocApp();
  1336. const libID = args[0] || docApp.libID;
  1337. const parentID = args[1] || 0;
  1338. const objectID = args[2] || 0;
  1339. const createType = args[3] || 'child';
  1340. const data =
  1341. {
  1342. name: newMoudleName,
  1343. libID: libID,
  1344. parentID: parentID,
  1345. objectID: objectID,
  1346. moduleType: isApiLib(libID) ? 'api' : 'doc',
  1347. isUpdate: false,
  1348. createType: createType,
  1349. };
  1350. $.ajaxSubmit(
  1351. {
  1352. load: false,
  1353. url: $.createLink('tree', 'ajaxCreateModule'),
  1354. data: data,
  1355. onSuccess: (res) =>
  1356. {
  1357. if(!res.module) return;
  1358. const docApp = getDocApp();
  1359. docApp.update('module', res.module);
  1360. if(!docApp.hasEditingDoc) docApp.selectModule(res.module.id);
  1361. }
  1362. })
  1363. });
  1364. },
  1365. editModule: function(_, args)
  1366. {
  1367. const docApp = getDocApp();
  1368. const moduleID = args[0] || docApp.moduleID;
  1369. const url = $.createLink('doc', 'editCatalog', `moduleID=${moduleID}&type=doc`);
  1370. zui.Modal.open({size: 'sm', url: url});
  1371. },
  1372. deleteModule: function(_, args)
  1373. {
  1374. const docApp = getDocApp();
  1375. const moduleID = args[0] || docApp.moduleID;
  1376. const moduleInfo = docApp.treeMap.modules.get(+moduleID);
  1377. $.ajaxSubmit(
  1378. {
  1379. confirm: getLang(moduleInfo.modules.length > 0 || moduleInfo.docs.length > 0 ? 'confirmDeleteModuleWithSub' : 'confirmDeleteModule'),
  1380. url: $.createLink('doc', 'deleteCatalog', `moduleID=${moduleID}`),
  1381. load: false,
  1382. onSuccess: function(res)
  1383. {
  1384. if(!res) return;
  1385. if(res.result === 'success')
  1386. {
  1387. const docApp = getDocApp();
  1388. const moduleInfo = docApp.treeMap.modules.get(+moduleID);
  1389. if(moduleInfo)
  1390. {
  1391. const parent = moduleInfo.parent;
  1392. docApp.changeState(
  1393. {
  1394. libID: parent.type === 'lib' ? parent.data.id : docApp.libID,
  1395. module: parent.type === 'lib' ? 0 : parent.data.id,
  1396. })
  1397. }
  1398. else if(docApp.mode === 'list')
  1399. {
  1400. docApp.selectLib(docApp.libID, 0);
  1401. }
  1402. docApp.delete('module', moduleID);
  1403. }
  1404. else if(res.message)
  1405. {
  1406. zui.Modal.alert(res.message);
  1407. }
  1408. }
  1409. });
  1410. },
  1411. collectDoc: function(_, args)
  1412. {
  1413. const docApp = getDocApp();
  1414. const docID = args[0] || docApp.docID;
  1415. $.post($.createLink('doc', 'collect', `objectID=${docID}&objectType=doc`), {}, function(res)
  1416. {
  1417. if(typeof res == 'string') res = JSON.parse(res);
  1418. if(!checkResponse(res)) return;
  1419. const collected = res.status === 'yes';
  1420. const doc = docApp.getDoc(docID);
  1421. getDocApp().update('doc', $.extend(doc, {isCollector: collected, collects: collected ? doc.collects + 1 : doc.collects - 1}));
  1422. });
  1423. },
  1424. addChapter: function(_, args)
  1425. {
  1426. const docApp = getDocApp();
  1427. const {spaceID, libID, moduleID} = docApp;
  1428. return showDocBasicModal(args[0], 0, false, 'chapter').then((formData) => {
  1429. const doc = {type: 'chapter', status: 'normal', parent: args[0]};
  1430. return submitNewDoc(doc, spaceID, libID, moduleID, formData).then(() => {
  1431. docApp.load(null, null, null, {noLoading: false, picks: 'doc'});
  1432. if(docBasicModal.current)
  1433. {
  1434. docBasicModal.current.destroy();
  1435. docBasicModal = {};
  1436. }
  1437. });
  1438. });
  1439. },
  1440. editChapter: function(_, args)
  1441. {
  1442. const docApp = getDocApp();
  1443. const {spaceID, libID, moduleID} = docApp;
  1444. return showDocBasicModal(0, args[0], false, 'chapter').then((formData) => {
  1445. return submitEditDoc({id: args[0]}, formData);
  1446. });
  1447. },
  1448. moveDoc: function(_, args)
  1449. {
  1450. const docApp = getDocApp();
  1451. const docID = args[0] || docApp.docID;
  1452. const libID = docApp.libID;
  1453. const spaceType = docApp.spaceType;
  1454. const spaceID = docApp.spaceID;
  1455. const url = $.createLink('doc', 'moveDoc', `docID=${docID}&libID=${libID}&spaceType=${spaceType}&space=${spaceID}`);
  1456. zui.Modal.open({size: 'sm', url: url});
  1457. },
  1458. handleMovedDoc(_, args)
  1459. {
  1460. const docID = +args[0];
  1461. const space = args[1];
  1462. const spaceID = +(space.includes('.') ? space.split('.').pop() : space);
  1463. const docApp = getDocApp();
  1464. if(docApp.mode === 'view')
  1465. {
  1466. if(spaceID === docApp.spaceID) docApp.loadDoc(docID).then(() => docApp.selectDoc(docID));
  1467. else if(space.startsWith(docApp.spaceType)) docApp.loadDoc(docID).then(() => docApp.selectLib(docApp.libID));
  1468. else loadPage($.createLink('doc', 'view', `docID=${docID}`));
  1469. }
  1470. else
  1471. {
  1472. docApp.load(null, null, null, {noLoading: true, picks: 'doc'});
  1473. }
  1474. },
  1475. startConvertDoc: function(_, args)
  1476. {
  1477. const docApp = getDocApp();
  1478. const docID = args[0] || docApp.docID;
  1479. const lang = getLang();
  1480. zui.Modal.confirm({title: lang.convertToNewDoc, content: lang.convertToNewDocConfirm}).then(result =>
  1481. {
  1482. if(!result) return;
  1483. docApp.startEditDoc(docID, {convert: true});
  1484. });
  1485. },
  1486. deleteDoc: function(_, args)
  1487. {
  1488. const docApp = getDocApp();
  1489. const docID = args[0] || docApp.docID;
  1490. const isApi = isApiDoc(docID);
  1491. const docInfo = docApp.treeMap.docs.get(docID)
  1492. const doc = docInfo.data;
  1493. const isChapter = doc?.type === 'chapter';
  1494. $.ajaxSubmit(
  1495. {
  1496. confirm: getLang(isChapter ? (docInfo.docs.length > 0 ? 'confirmDeleteChapterWithSub' : 'confirmDeleteChapter') : (docInfo.docs.length > 0 ? 'confirmDeleteWithSub' : 'confirmDelete')),
  1497. url: $.createLink(isApi ? 'api' : 'doc', 'delete', `${isApi ? 'apiID' : 'docID'}=${isApi ? getApiID(docID) : docID}`),
  1498. load: false,
  1499. onSuccess: function()
  1500. {
  1501. getDocApp().delete('doc', docID);
  1502. }
  1503. });
  1504. },
  1505. effortDoc: function(_,args)
  1506. {
  1507. const docApp = getDocApp();
  1508. const docID = args[0] || docApp.docID;
  1509. const url = $.createLink('effort', 'createForObject', `objectType=doc&objectID=${docID}`);
  1510. zui.Modal.open({url: url, size: 'sm'});
  1511. },
  1512. exportWord: function(_, args)
  1513. {
  1514. const docApp = getDocApp();
  1515. const type = docApp.spaceType;
  1516. const libID = args[0] || docApp.libID;
  1517. const moduleID = args[1] || docApp.moduleID;
  1518. const docID = args[2] || docApp.docID;
  1519. const url = $.createLink('doc', `${type}2export`, `libID=${libID}&moduleID=${moduleID}&docID=${docID}&objectID=${docApp.spaceID}`);
  1520. if(docID)
  1521. {
  1522. window.open(url, '_self');
  1523. return;
  1524. }
  1525. zui.Modal.open({url: url, size: 'sm'});
  1526. },
  1527. exportApi: function(_, args)
  1528. {
  1529. const docApp = getDocApp();
  1530. const libID = args[0] || docApp.libID;
  1531. const release = args[1] || docApp.signals.libReleaseMap.value[libID] || 0;
  1532. const moduleID = args[2] || docApp.moduleID;
  1533. let docID = args[3] || docApp.docID;
  1534. if(typeof docID === 'string') docID = getApiID(docID);
  1535. const url = $.createLink('api', 'export', `libID=${libID}&version=0&release=${release}&moduleID=${moduleID}${docID ? `&apiID=${docID}` : ''}`);
  1536. if(docID)
  1537. {
  1538. window.open(url, '_self');
  1539. return;
  1540. }
  1541. zui.Modal.open({url: url, size: 'sm'});
  1542. },
  1543. importFile: function(info, args)
  1544. {
  1545. const type = args[0] || 'markdown';
  1546. const docApp = getDocApp();
  1547. const editor = docApp.editor.$;
  1548. const altKey = info.event.altKey;
  1549. if(editor.isEmpty) return importFileToEditor(type, {fromText: altKey});
  1550. zui.Modal.confirm({message: getLang('importConfirm')})
  1551. .then((result) => result && importFileToEditor(type, {fromText: altKey}));
  1552. },
  1553. showDocSettingModal: function(_, args)
  1554. {
  1555. const docApp = getDocApp();
  1556. const doc = docApp.doc;
  1557. const docID = args[0] || doc.id;
  1558. const docType = args[1] || doc.contentType;
  1559. const saveEdited = args[2] || 0;
  1560. showDocBasicModal(0, docID).then(formData => {
  1561. savingDocData[docID] = formData;
  1562. if(saveEdited == 1)
  1563. {
  1564. const docData = {
  1565. content : doc.data.content,
  1566. status : doc.data.status,
  1567. contentType: doc.data.contentType,
  1568. type : doc.data.type,
  1569. lib : doc.data.lib,
  1570. module : doc.data.module,
  1571. title : doc.data.title,
  1572. keywords : doc.data.keywords,
  1573. acl : doc.data.acl,
  1574. space : doc.data.space,
  1575. uid : doc.data.uid,
  1576. };
  1577. mergeDocFormData(docData, formData);
  1578. }
  1579. });
  1580. },
  1581. /**
  1582. * 保存 API 文档数据。
  1583. * Save the API doc data.
  1584. */
  1585. saveApiDoc: function()
  1586. {
  1587. /* 触发 API 表单的提交事件。 */
  1588. $('#docApp .doc-view form').trigger('submit');
  1589. },
  1590. /**
  1591. * 加载指定的 API 文档。
  1592. * Load the specified API doc.
  1593. */
  1594. loadApi: function(_, args)
  1595. {
  1596. const apiID = getApiID(args[0] || this.docID);
  1597. const version = args[1] || 0;
  1598. const release = args[2] || 0;
  1599. const select = !!args[3];
  1600. $.getJSON($.createLink('api', 'ajaxGetApi', `apiID=${apiID}&version=${version}&release=${release}`), function(result)
  1601. {
  1602. if(!result || typeof result !== 'object') return;
  1603. result.id = `api.${apiID}`;
  1604. const docApp = getDocApp();
  1605. docApp.update('doc', result);
  1606. if(select) docApp.selectDoc(result.id);
  1607. });
  1608. },
  1609. /**
  1610. * 选择 API 文档。
  1611. * Select the specified API doc.
  1612. */
  1613. selectApi: function(_, args)
  1614. {
  1615. const apiID = args[0];
  1616. getDocApp().selectDoc(`api.${getApiID(apiID)}`);
  1617. },
  1618. /**
  1619. * 显示结构列表。
  1620. * Show the struct list.
  1621. */
  1622. showStructs: function()
  1623. {
  1624. getDocApp().changeState(
  1625. {
  1626. mode: 'list',
  1627. moduleID: 0,
  1628. docID: 0,
  1629. listType: 'structs',
  1630. });
  1631. },
  1632. /**
  1633. * 显示版本列表。
  1634. * Show the release list.
  1635. */
  1636. showReleases: function()
  1637. {
  1638. getDocApp().changeState(
  1639. {
  1640. mode: 'list',
  1641. moduleID: 0,
  1642. docID: 0,
  1643. listType: 'releases',
  1644. });
  1645. },
  1646. /**
  1647. * 显示API 目录。
  1648. * Show the api catalog.
  1649. */
  1650. showModules: function()
  1651. {
  1652. getDocApp().changeState(
  1653. {
  1654. mode: 'list',
  1655. moduleID: 0,
  1656. docID: 0,
  1657. listType: '',
  1658. });
  1659. },
  1660. /**
  1661. * 获取库的 API 列表。
  1662. * Get the API list of the library.
  1663. */
  1664. loadLibApi: function(_, args)
  1665. {
  1666. const docApp = getDocApp();
  1667. const libReleaseMap = docApp.signals.libReleaseMap.value;
  1668. const libID = args[0] || docApp.libID;
  1669. if(!libID) return;
  1670. const releaseID = args[1] || libReleaseMap[libID] || 0;
  1671. const url = $.createLink('api', 'ajaxGetLibApiList', `libID=${libID}&releaseID=${releaseID}`);
  1672. $.getJSON(url, function(data)
  1673. {
  1674. const lib = docApp.getLib(libID);
  1675. if(lib && lib.docs && lib.docs.length) docApp.delete('doc', lib.docs.map(x => x.data.id));
  1676. data.forEach((x) => x.id = `api.${x.id}`);
  1677. docApp.update('doc', data);
  1678. });
  1679. },
  1680. /**
  1681. * 更改当前库的发布版本。
  1682. * Change the release of the current library.
  1683. */
  1684. changeLibRelease: function(_, args)
  1685. {
  1686. const docApp = getDocApp();
  1687. const libID = args[0];
  1688. const release = args[1];
  1689. const libReleaseMap = docApp.signals.libReleaseMap.value;
  1690. if(libReleaseMap[libID] === release) return;
  1691. libReleaseMap[libID] = release;
  1692. docApp.signals.libReleaseMap.value = $.extend({}, libReleaseMap);
  1693. docApp.executeCommand('loadLibApi', [libID, release]);
  1694. const doc = docApp.doc;
  1695. if(doc && doc.data.lib === libID) docApp.executeCommand('loadApi', [doc.data.id, 0, release]);
  1696. },
  1697. /**
  1698. * 加载懒加载内容。
  1699. * Load the lazy content.
  1700. */
  1701. loadLazyContent: function(_, args)
  1702. {
  1703. const selector = args[0];
  1704. if(!selector) return;
  1705. $(selector).closest('.lazy-content').trigger('loadContent');
  1706. },
  1707. /**
  1708. * 更新懒加载内容。
  1709. * Update the lazy content.
  1710. */
  1711. updateLazyContent: function(context, args)
  1712. {
  1713. const event = context.event;
  1714. const $element = $(event.currentTarget);
  1715. const selector = args[0] || $element.data('lazyTarget');
  1716. const $lazy = (selector ? $(selector) : $element).closest('.lazy-content');
  1717. const url = $element.data('url') || $element.attr('href');
  1718. if(url) $lazy.trigger('loadContent', url);
  1719. event.preventDefault();
  1720. event.stopPropagation();
  1721. },
  1722. /**
  1723. * 执行禅道智能体。
  1724. * Execute the zentao AI prompt.
  1725. */
  1726. executeAIPrompt: function(_, args)
  1727. {
  1728. const promptID = args[0];
  1729. const docID = args[1];
  1730. const url = $.createLink('ai', 'promptExecute', `promptId=${promptID}&objectId=${docID}&auto=0`);
  1731. $.ajaxSubmit({url: url, method: 'POST'});
  1732. },
  1733. /**
  1734. * 批量导出附件库中的附件。
  1735. * Batch export attachments in the attachment library.
  1736. */
  1737. exportFiles: function(_, args)
  1738. {
  1739. const docApp = getDocApp();
  1740. const objectID = docApp.spaceID;
  1741. const objectType = docApp.spaceType;
  1742. const url = $.createLink('doc', 'exportfiles', `objectID=${objectID}&objectType=${objectType}`);
  1743. zui.Modal.open({url: url, size: 'sm'});
  1744. },
  1745. /*
  1746. * 委派数字员工任务。
  1747. * Assign the ai task to the ai teammate.
  1748. */
  1749. assignAITeammate: function(_, args)
  1750. {
  1751. const teammateID = args[0];
  1752. const docID = args[1];
  1753. const pageInfo = 'doc,view';
  1754. loadModal($.createLink('aiteammate', 'assignagent', `teammateID=${teammateID}&objectType=doc&objectID=${docID}&pageInfo=${pageInfo}`), null, {size: 'sm'});
  1755. },
  1756. /**
  1757. * 查看数字员工任务。
  1758. * View the ai tasks.
  1759. */
  1760. viewAITasks: function(_, args)
  1761. {
  1762. const docID = args[0];
  1763. loadModal($.createLink('aitask', 'browse', `teammate=0&browseType=&involved=0&orderBy=id_desc&param=0&recTotal=0&recPerPage=20&pageID=1&objectType=doc&objectID=${docID}`));
  1764. }
  1765. };
  1766. function getApiID(id)
  1767. {
  1768. if(typeof id === 'number') return id;
  1769. if(String(+id) === id) return +id;
  1770. return +id.replace('api.', '');
  1771. }
  1772. /**
  1773. * 获取列表类型。
  1774. * Get the list type.
  1775. *
  1776. * @param {object} docApp
  1777. * @returns {string}
  1778. */
  1779. function getListType(docApp)
  1780. {
  1781. docApp = docApp || getDocApp();
  1782. if(docApp.mode !== 'list' || docApp.module) return '';
  1783. const listType = docApp.signals.listType.value;
  1784. return listType;
  1785. }
  1786. /**
  1787. * 定义页面上的自定义渲染器。
  1788. * Define the custom renderers on the page.
  1789. */
  1790. const customRenders =
  1791. {
  1792. /**
  1793. * 定义 API 文档编辑器渲染,包括查看、编辑和创建。
  1794. * Define the API doc editor render, including view, edit and create.
  1795. */
  1796. editor: function()
  1797. {
  1798. const mode = this.mode;
  1799. if(!isApiLib())
  1800. {
  1801. const docInfo = this.doc;
  1802. const doc = docInfo ? docInfo.data : null;
  1803. if (mode === 'diff') {
  1804. const {
  1805. diffVersions,
  1806. spaceType,
  1807. } = this.signals;
  1808. const versions = diffVersions ? diffVersions.value : [];
  1809. if (versions.length === 2) {
  1810. return {
  1811. fetcher: $.createLink('doc', 'ajaxDiff', `&objectType=${spaceType.value}&docID=${doc.id}&newVersion=${versions[0]}&oldVersion=${versions[1]}`),
  1812. };
  1813. }
  1814. }
  1815. if(mode === 'view' && !hasPriv('view')) return {html: `<h1>${doc ? doc.title : ''}</h1><p>${getDocAppLang('accessDenied')}</p>`};
  1816. return;
  1817. }
  1818. if(mode === 'create')
  1819. {
  1820. const libID = this.libID;
  1821. const moduleID = this.moduleID;
  1822. return {fetcher: $.createLink('api', 'create', `libID=${libID}&moduleID=${moduleID}&space=api`), loadingText: getDocAppLang('loading')};
  1823. }
  1824. if(mode === 'edit')
  1825. {
  1826. const doc = this.doc.data;
  1827. return {fetcher: $.createLink('api', 'edit', `apiID=${getApiID(doc.id)}`), loadingText: getDocAppLang('loading')};
  1828. }
  1829. const doc = this.doc.data;
  1830. if(!hasPriv('viewApi')) return {html: `<h1>${doc ? doc.title : ''}</h1><p>${getDocAppLang('accessDenied')}</p>`};
  1831. const release = this.signals.libReleaseMap.value[doc.lib] || 0;
  1832. const version = this.signals.docVersion.value || 0;
  1833. return {fetcher: $.createLink('api', 'view', `libID=${doc.lib}&apiID=${getApiID(doc.id)}&moduleID=${doc.module}&version=${version}&release=${release}`), loadingText: getDocAppLang('loadingDocsData'), className: 'doc-editor-content'};
  1834. },
  1835. /**
  1836. * 定义 API 文档列表渲染,包括结构和版本。
  1837. * Define the API doc list render, including structs and releases.
  1838. */
  1839. list: function()
  1840. {
  1841. if(!isApiLib()) return;
  1842. const listType = getListType(this);
  1843. const libID = getApiID(this.libID);
  1844. const releaseID = this.signals.libReleaseMap.value[libID] || 0;
  1845. if(listType === 'structs') return {fetcher: $.createLink('api', 'struct', `libID=${this.libID}&releaseID=${releaseID}`), loadingText: getDocAppLang('loading'), className: 'api-struct-list'};
  1846. if(listType === 'releases') return {fetcher: $.createLink('api', 'releases', `libID=${this.libID}`), loadingText: getDocAppLang('loading'), className: 'api-release-list'};
  1847. },
  1848. /**
  1849. * 定义 API 文档列表筛选菜单渲染,当展示结构和版本时不显示筛选菜单。
  1850. * Define the API doc list filter menu render, not show the filter menu when showing structs and releases.
  1851. */
  1852. filters: function()
  1853. {
  1854. if(!isApiLib(null, this)) return;
  1855. const listType = getListType(this);
  1856. if(this.mode !== 'list' || !listType) return;
  1857. return null;
  1858. },
  1859. /**
  1860. * 定义 API 文档列表工具栏渲染。
  1861. * Define the API doc list toolbar render.
  1862. */
  1863. toolbar: function()
  1864. {
  1865. if(!isApiLib()) return;
  1866. const listType = getListType(this);
  1867. if(this.mode === 'list' && listType)
  1868. {
  1869. const libID = getApiID(this.libID);
  1870. const items = [];
  1871. if(hasPriv('createStruct') && listType === 'structs') items.push({text: getDocAppLang('createStruct'), icon: 'plus', btnType: 'primary', 'data-toggle': 'modal', 'data-size': 'lg', url: $.createLink('api', 'createStruct', `libID=${libID}`)});
  1872. if(hasPriv('createRelease') && listType === 'releases') items.push({text: getDocAppLang('createRelease'), icon: 'plus', btnType: 'primary', 'data-toggle': 'modal', url: $.createLink('api', 'createRelease', `libID=${libID}`)});
  1873. if(!items.length) return null;
  1874. return {component: 'toolbar', props: {items: items}};
  1875. }
  1876. },
  1877. /**
  1878. * 定义顶部面包屑导航渲染。
  1879. * Define the top breadcrumb render.
  1880. */
  1881. 'app-nav': function(items)
  1882. {
  1883. const lib = this.lib;
  1884. if(!lib || !isApiLib(lib)) return items;
  1885. const versions = lib.data.versions;
  1886. if(versions && versions.length)
  1887. {
  1888. const viewIndex = items.findIndex(item => item[0] === 'lib');
  1889. if(viewIndex >= 0)
  1890. {
  1891. const libView = items[viewIndex][1];
  1892. const libID = getApiID(lib.data.id);
  1893. const release = this.signals.libReleaseMap.value[libID] || 0;
  1894. const options = [{text: getDocAppLang('latestVersion'), value: 0, selected: !release, command: `changeLibRelease/${libID}/0`}];
  1895. versions.forEach(version => options.push({selected: release === version.id, text: `v${version.version}`, value: version.id, command: `changeLibRelease/${libID}/${version.id}`}));
  1896. const currentVersion = versions.find(x => x.id === release);
  1897. const versionPicker = zui.renderCustomContent(
  1898. {
  1899. content:
  1900. {
  1901. component: 'DropdownButton',
  1902. props:
  1903. {
  1904. text : currentVersion ? currentVersion.version : getDocAppLang('latestVersion'),
  1905. size : 'xs',
  1906. type : 'gray-pale',
  1907. rounded : 'full',
  1908. className: 'h-4 gap-1 mr-2',
  1909. items : options,
  1910. }
  1911. }
  1912. });
  1913. items[viewIndex] = ['lib', [libView, versionPicker]];
  1914. }
  1915. }
  1916. const listType = getListType(this);
  1917. if(this.mode !== 'list' || !listType) return items;
  1918. if(listType === 'structs') items.push([listType, zui.renderCustomContent({className: 'mx-2', content: getDocAppLang('struct')})]);
  1919. if(listType === 'releases') items.push([listType, zui.renderCustomContent({className: 'mx-2', content: getDocAppLang('releases')})]);
  1920. return items;
  1921. },
  1922. /**
  1923. * 定义侧边栏渲染,显示结构、版本和模块。
  1924. * Define the sidebar render, show structs, releases and modules.
  1925. */
  1926. 'sidebar-before': function()
  1927. {
  1928. if(!isApiLib()) return;
  1929. const canViewStructs = docAppHasPriv('struct');
  1930. const canViewReleases = docAppHasPriv('releases');
  1931. if(!canViewStructs && !canViewReleases) return;
  1932. const isListMode = this.mode === 'list';
  1933. const lang = getDocAppLang();
  1934. const listType = getListType(this);
  1935. const items = [];
  1936. if(canViewStructs) items.push({text: lang.struct, selected: listType === 'structs' && isListMode, icon: 'treemap muted', command: 'showStructs'}, {type: 'divider', className: 'my-1'});
  1937. if(canViewReleases) items.push({text: lang.releases, selected: listType === 'releases' && isListMode, icon: 'version muted', command: 'showReleases'}, {type: 'divider', className: 'my-1'});
  1938. items.push({text: lang.module, icon: 'list muted', command: 'showModules'});
  1939. return {
  1940. component: 'tree',
  1941. className: 'p-2 pb-0 api-lib-menu',
  1942. props: {items: items, itemProps: {className: 'state'}}
  1943. };
  1944. }
  1945. };
  1946. /**
  1947. * 获取文档界面上的表格初始化选项。
  1948. * Get the table initialization options on the doc UI.
  1949. *
  1950. * @param {object} options
  1951. * @param {object} info
  1952. * @returns {object}
  1953. */
  1954. function getTableOptions(options, info)
  1955. {
  1956. const lang = getLang();
  1957. if(info.type === 'doc-list')
  1958. {
  1959. const tableCols = lang.tableCols;
  1960. const canModify = canModifySpace(this.space);
  1961. options.cols.forEach(col =>
  1962. {
  1963. if(typeof tableCols[col.name] === 'string') col.title = tableCols[col.name];
  1964. if(!config.clientLang.includes('zh'))
  1965. {
  1966. if(col.name === 'addedDate' || col.name == 'editedDate') col.width = '120';
  1967. }
  1968. if(col.name === 'actions' && col.actionsMap)
  1969. {
  1970. if(!canModify) col.actions = [];
  1971. col.actions = col.actions.filter(action => hasPriv(action == 'move' ? 'moveDoc' : action));
  1972. const actionHints = {edit: lang.editDoc, move: lang.moveDoc, delete: lang.deleteDoc};
  1973. const privMap = {edit: hasPriv('edit'), move: hasPriv('moveDoc'), delete: hasPriv('delete')};
  1974. $.each(col.actionsMap, (key, value) =>
  1975. {
  1976. if(typeof actionHints[key] === 'string') value.hint = actionHints[key];
  1977. value.disabled = !privMap[key];
  1978. });
  1979. col.actionItemCreator = function(item, info)
  1980. {
  1981. const rowData = info.row.data;
  1982. item.command = item.command.replace('{id}', String(rowData.id));
  1983. if(rowData.frozen && (item.key === 'edit' || item.key === 'trash'))
  1984. {
  1985. const actionHint = item.key == 'trash' ? actionHints['delete'] : actionHints[item.key];
  1986. item.hint = lang.frozenTips.replace('%s', actionHint);
  1987. item.disabled = true;
  1988. }
  1989. return item;
  1990. }
  1991. }
  1992. });
  1993. options.onCheckChange = function(changes)
  1994. {
  1995. const checkedList = this.getChecks();
  1996. $.cookie.set('checkedItem', checkedList, {expires:config.cookieLife, path:config.webRoot});
  1997. }
  1998. }
  1999. if(info.type === 'file-list')
  2000. {
  2001. const tableCols = lang.fileTableCols;
  2002. const canExportFiles = hasPriv('exportFiles');
  2003. options.cols.forEach(col =>
  2004. {
  2005. if(typeof tableCols[col.name] === 'string') col.title = tableCols[col.name];
  2006. if(col.name == 'objectName')
  2007. {
  2008. const onRenderCellBackup = col.onRenderCell;
  2009. col.onRenderCell = function(result, info)
  2010. {
  2011. const file = info.row.data;
  2012. if(file.rawObjectType == 'stepResult')
  2013. {
  2014. const url = $.createLink('testtask', 'results', `runID=0&caseID=${file.objectID}`);
  2015. result[0] = {html: `${file.objectName}<a href="${url}" data-toggle="modal" data-size="lg" title="${file.objectName}#${file.objectID} ${file.sourceName}">#${file.objectID} ${file.sourceName}</a>`};
  2016. return result;
  2017. }
  2018. return onRenderCellBackup.call(this,result,info);
  2019. }
  2020. }
  2021. if(col.name === 'id' && canExportFiles) col.checkbox = true;
  2022. });
  2023. if(canExportFiles)
  2024. {
  2025. options.checkable = true;
  2026. options.onCheckChange = function(changes)
  2027. {
  2028. const checkedList = this.getChecks();
  2029. $.cookie.set('checkedFileItem', checkedList, {expires:config.cookieLife, path:config.webRoot});
  2030. }
  2031. }
  2032. return options;
  2033. }
  2034. if(!hasPriv('batchMoveDoc') && !hasPriv('exportDoc'))
  2035. {
  2036. options.checkable = false;
  2037. options.footer = options.footer.filter(f => f !== 'checkbox' && f !== 'checkedInfo');
  2038. }
  2039. return options;
  2040. }
  2041. /**
  2042. * 获取文档界面上的列表筛选菜单。
  2043. * Get the filter menu on the doc UI.
  2044. *
  2045. * @param {string} mode
  2046. * @returns {[key: string, text: string][]}
  2047. */
  2048. function getFilterTypes(mode)
  2049. {
  2050. if(mode === 'home')
  2051. {
  2052. if(docAppData.currentSpaceType === 'project') return getLang('projectFilterTypes');
  2053. if(docAppData.currentSpaceType === 'product') return getLang('productFilterTypes');
  2054. return getLang('spaceFilterTypes');
  2055. }
  2056. if(mode === 'list')
  2057. {
  2058. const lib = this.lib;
  2059. if(lib && lib.data.type === 'api') return getLang('apifilterTypes');
  2060. return getLang('filterTypes');
  2061. }
  2062. if(mode === 'files') return getLang('fileFilterTypes');
  2063. }
  2064. /**
  2065. * 检查文档是否符合筛选条件。
  2066. * Check if the doc matches the filter condition.
  2067. *
  2068. * @param {string} type
  2069. */
  2070. function isMatchFilter(type, filterType, item)
  2071. {
  2072. if(type === 'doc')
  2073. {
  2074. if(filterType === 'createdByMe') return item.addedBy === docAppData.currentUser;
  2075. if(filterType === 'editedByMe') return item.editedBy === docAppData.currentUser;
  2076. if(filterType === 'draft') return item.status === 'draft';
  2077. if(filterType === 'collect') return item.isCollector;
  2078. if(filterType === 'released') return item.status === 'normal';
  2079. }
  2080. if(type === 'project' || type === 'product')
  2081. {
  2082. return filterType !== 'mine' || item.isMine;
  2083. }
  2084. return true;
  2085. }
  2086. /**
  2087. * 将 [key, ...] 形式的顺序列表转换为 {key: order, ...} 形式。
  2088. * Convert the order list in the form of [key, ...] to {key: order, ...}.
  2089. *
  2090. * @param {number[]} orders
  2091. * @returns {object}
  2092. */
  2093. function formatOrders(orders, useIndex)
  2094. {
  2095. const orderedKeys = useIndex ? [] : Array.from(orders).sort((a, b) => a - b);
  2096. return orders.reduce((map, key, index) =>
  2097. {
  2098. map[key] = useIndex ? index : orderedKeys[index];
  2099. return map;
  2100. }, {});
  2101. }
  2102. /**
  2103. * 对文档条目进行排序。
  2104. * Sort the doc items.
  2105. *
  2106. * @param {string} type 'doc' | 'module' | 'lib' | 'space'
  2107. * @param {object|array} orders {key: order, ...} | [key, ...]
  2108. */
  2109. function sortItems(type, orders)
  2110. {
  2111. if(Array.isArray(orders)) orders = formatOrders(orders, type === 'lib');
  2112. const sortMethods = {doc: 'sortDoc', module: 'sortCatalog', lib: 'sortDoclib'};
  2113. if(!sortMethods[type]) return console.error(`[DocApp] Invalid sort type: ${type}`);
  2114. const url = $.createLink('doc', sortMethods[type]);
  2115. return $.ajaxSubmit({
  2116. url,
  2117. data: {orders: JSON.stringify(orders)},
  2118. onSuccess: function()
  2119. {
  2120. const items = Object.keys(orders).map(id => ({id: +id, order: orders[id]}));
  2121. getDocApp().update(type, items);
  2122. }
  2123. });
  2124. }
  2125. /**
  2126. * 获取界面上条目排序选项。
  2127. * Get the sortable options on the doc UI.
  2128. *
  2129. * @param {string} type 'doc' | 'doc-module' | 'module' | 'lib' | 'space'
  2130. */
  2131. function getSortableOptions(type)
  2132. {
  2133. const canSortDocModule = hasPriv('sortModule') || hasPriv('sortDoc');
  2134. if((type === 'doc-module' && canSortDocModule) || (type === 'lib' && hasPriv('sortDoclib')))
  2135. {
  2136. const getItemType = (key) => key[0] === 'm' ? 'module' : (key[0] === 'l' ? 'lib' : 'doc');
  2137. return {
  2138. sortable: {handle: '.sort-handler'},
  2139. canSortTo: function(event)
  2140. {
  2141. let fromKey = event.dragged.getAttribute('z-key');
  2142. let toKey = event.related.getAttribute('z-key');
  2143. if(!fromKey || !toKey) return false;
  2144. const fromType = getItemType(fromKey);
  2145. const toType = getItemType(toKey);
  2146. if (fromType !== toType) return false;
  2147. return true;
  2148. },
  2149. onSort: function(event, orders)
  2150. {
  2151. const fromKey = event.item.getAttribute('z-key');
  2152. if(!fromKey || !orders.length) return;
  2153. const fromType = getItemType(fromKey);
  2154. const orderedList = [];
  2155. orders.forEach((key, index) =>
  2156. {
  2157. const keyType = getItemType(key);
  2158. if(keyType !== fromType) return;
  2159. if(fromType !== 'doc') key = key.substring(1);
  2160. orderedList.push(+key);
  2161. });
  2162. if(fromType === 'doc')
  2163. {
  2164. const docApp = getDocApp();
  2165. const doc = docApp.getDoc(orderedList[0]);
  2166. const lib = doc ? docApp.getLib(doc.lib) : null;
  2167. if(lib && typeof lib.data.orderBy === 'string' && lib.data.orderBy.endsWith('desc')) orderedList.reverse();
  2168. }
  2169. sortItems(fromType, orderedList);
  2170. }
  2171. }
  2172. }
  2173. }
  2174. window.checkResponse = function(res)
  2175. {
  2176. if(typeof res === 'string') res = JSON.parse(res);
  2177. if(typeof res !== 'object' || !res) return true;
  2178. if(res.load === 'login')
  2179. {
  2180. if(res.message) zui.Modal.alert(res.message).then(() => $.apps.logout());
  2181. else $.apps.logout();
  2182. return false;
  2183. }
  2184. return true;
  2185. }
  2186. /**
  2187. * 获取文档详情侧边栏标签页定义。
  2188. * Get the doc view sidebar tabs.
  2189. *
  2190. * @param {object} doc
  2191. */
  2192. window.getDocViewSidebarTabs = function(doc, info)
  2193. {
  2194. if(isApiLib())
  2195. {
  2196. const lang = getDocAppLang();
  2197. if(info.isNewDoc || info.mode === 'create') return [];
  2198. return [
  2199. {key: 'info', icon: 'info', title: lang.docInfo},
  2200. info.mode === 'edit' ? null : {key: 'outline', icon: 'list-box', title: lang.docOutline},
  2201. {key: 'history', icon: 'file-log', title: lang.history},
  2202. ].filter(Boolean);
  2203. }
  2204. let tabList = [];
  2205. if(info.isNewDoc)
  2206. {
  2207. tabList.push({key: 'outline', icon: 'list-box', title: getLang('docOutline')});
  2208. }
  2209. else
  2210. {
  2211. tabList.push(
  2212. {key: 'outline', icon: 'list-box', title: getLang('docOutline')},
  2213. {key: 'history', icon: 'file-log', title: getLang('history')}
  2214. );
  2215. }
  2216. if(info.mode == 'view' && doc.status != 'draft' && !doc.api)
  2217. {
  2218. tabList.push(
  2219. {
  2220. key : 'relateObject',
  2221. icon : 'link',
  2222. title : getLang('relateObject'),
  2223. render: function(doc){return {fetcher: $.createLink('doc', 'ajaxGetRelatedObjects', `docID=${doc.id}`)}}
  2224. });
  2225. }
  2226. return tabList;
  2227. }
  2228. function getSpaceFetcher(spaceType, spaceID = 0)
  2229. {
  2230. if(spaceType === 'product')
  2231. {
  2232. return $.createLink('product', 'ajaxGetDropMenu', `productID=${spaceID}&module=doc&method=app&extra=&from=&useLink=0`);
  2233. }
  2234. if(spaceType === 'project')
  2235. {
  2236. return $.createLink('project', 'ajaxGetDropMenu', `projectID=${spaceID}&module=doc&method=app&extra=&useLink=0`);
  2237. }
  2238. }
  2239. function initOfficePreview(options)
  2240. {
  2241. if(options.canPreviewOffice && options.fileInfoUrl)
  2242. {
  2243. const officeTypes = new Set(['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf']);
  2244. zui.Editor.setGlobalConfig(
  2245. {
  2246. canPreviewFile: (file) => {
  2247. const extension = file.name.split('.').pop();
  2248. return officeTypes.has(extension);
  2249. },
  2250. onPreviewFile: (file) => {
  2251. const doc = getDocApp().doc || {data: {id: 0}};
  2252. $.getJSON(zui.formatString(options.fileInfoUrl, {
  2253. gid: btoa(`g-${file.key}`),
  2254. objectType: 'doc',
  2255. objectID: doc.data.id,
  2256. title: '',
  2257. extra: '',
  2258. })).then(res => {
  2259. if(res.result === 'success' && res.file)
  2260. {
  2261. const editable = doc.data.editable !== false;
  2262. window.open($.createLink('file', 'download', `fileID=${res.file.id}&mouse=left&edit=${editable ? '0' : 'never'}`), '_blank');
  2263. }
  2264. });
  2265. }
  2266. });
  2267. }
  2268. if(options.privs.downloadFile === false) zui.Editor.setGlobalConfig({canDownloadFile: (file) => false});
  2269. }
  2270. /**
  2271. * 处理导入的文档快照。
  2272. * Handle the imported doc snapshot.
  2273. */
  2274. function handleImportDocSnapshot(snapshot)
  2275. {
  2276. const forEachBlock = (blocks, callback) =>
  2277. {
  2278. blocks.forEach(block =>
  2279. {
  2280. callback(block);
  2281. if(block.children) forEachBlock(block.children, callback);
  2282. });
  2283. };
  2284. const requestType = config.requestType.toUpperCase();
  2285. const fixUrl = (url, method, paramList) =>
  2286. {
  2287. const replaceOrign = url => {
  2288. try
  2289. {
  2290. const urlObj = new URL(url);
  2291. if(urlObj.origin != location.origin)
  2292. {
  2293. urlObj.protocol = location.protocol;
  2294. urlObj.host = location.host;
  2295. return urlObj.toString();
  2296. }
  2297. return url;
  2298. }
  2299. catch
  2300. {
  2301. return url;
  2302. }
  2303. };
  2304. const link = $.parseLink(replaceOrign(url), 'auto');
  2305. if(link.requestType.toUpperCase() === requestType || method.toLowerCase() !== link.methodName.toLowerCase()) return url
  2306. return `${location.origin}${$.createLink('doc', method, paramList.map((p, i) => [p, link.vars[i][1]]))}`;
  2307. };
  2308. /* Fix custom block with fetcher in difference request type. */
  2309. forEachBlock(snapshot.blocks.children, block =>
  2310. {
  2311. if(block.flavour !== 'affine:embed-zui-custom') return;
  2312. const content = block.props.content;
  2313. if(!content || typeof content !== 'object') return;
  2314. if(content.fetcher) content.fetcher = fixUrl(content.fetcher, 'zentaoList', ['type', 'blockID']);
  2315. if(content.exportUrl) content.exportUrl = fixUrl(content.exportUrl, 'ajaxExportZentaoList', ['blockID']);
  2316. });
  2317. return snapshot;
  2318. }
  2319. /**
  2320. * 设置文档应用组件选项。
  2321. * Set the doc app options.
  2322. */
  2323. window.setDocAppOptions = function(_, options)
  2324. {
  2325. docAppData.currentUser = options.currentUser;
  2326. docAppData.currentSpaceType = options.spaceType;
  2327. docAppData.userPrivs = options.privs;
  2328. docAppData.docLangData = options.langData;
  2329. initOfficePreview(options);
  2330. return $.extend(
  2331. {
  2332. editorProps : {onImportSnapshot: handleImportDocSnapshot},
  2333. defaultState : {listType: '', libReleaseMap: {}},
  2334. commands : commands,
  2335. customRenders : customRenders,
  2336. onCreateDoc : docAppData.userPrivs.create ? handleCreateDoc : null,
  2337. onSaveDoc : docAppData.userPrivs.edit ? handleSaveDoc : null,
  2338. canMoveDoc : canMoveDoc,
  2339. onSwitchView : handleSwitchView,
  2340. getActions : getActions,
  2341. getTableOptions : options.docViewer ? null : getTableOptions,
  2342. getFilterTypes : getFilterTypes,
  2343. isMatchFilter : isMatchFilter,
  2344. getSortableOptions : getSortableOptions,
  2345. getDocViewSidebarTabs: getDocViewSidebarTabs,
  2346. getSpaceFetcher : getSpaceFetcher,
  2347. showDocOutline : true,
  2348. showDocHistory : true,
  2349. $onDestroy : handleDocAppDestroy,
  2350. }, window.docAppOptions, options);
  2351. };
  2352. window.docAppActions = actionsMap;
  2353. window.docAppCommands = commands;
  2354. window.docAppCustomRenders = customRenders;
  2355. window.getDocApp = getDocApp;
  2356. window.getDocAppLang = getLang;
  2357. window.docAppHasPriv = hasPriv;
  2358. window.getFileActions = function(file)
  2359. {
  2360. let fileActions = [];
  2361. let canPreview = false;
  2362. let officeTypes = 'doc|docx|xls|xlsx|ppt|pptx|pdf';
  2363. let isOfficeFile = officeTypes.includes(file.extension);
  2364. let previewExtension = 'txt|jpg|jpeg|gif|png|bmp|mp4';
  2365. if(previewExtension.includes(file.extension)) canPreview = true;
  2366. if(libreOfficeTurnon && isOfficeFile) canPreview = true;
  2367. if(canPreview)
  2368. {
  2369. let previewAction = {icon: 'eye', title: previewLang, url: previewLink.replace('{id}', file.id).replace('\\', ''), className: 'text-primary', target: '_blank'};
  2370. if(!isOfficeFile)
  2371. {
  2372. previewAction['data-toggle'] = 'modal';
  2373. previewAction['data-size'] = 'lg';
  2374. delete previewAction.target;
  2375. }
  2376. fileActions.push(previewAction);
  2377. }
  2378. fileActions.push({icon: 'download', title: downloadLang, url: downloadLink.replace('{id}', file.id).replace('\\', ''), className: 'text-primary', target: '_blank'});
  2379. return fileActions;
  2380. };
  2381. window.useHocuspocus = function(app)
  2382. {
  2383. if(config.vision !== 'rnd') return false;
  2384. return enableHocuspocus && app.spaceType !== 'mine';
  2385. };
  2386. let lastDisconnectMessager = null;
  2387. window.onHocuspocusConnect = function(app)
  2388. {
  2389. if(app.spaceType === 'mine') return;
  2390. lastDisconnectMessager && lastDisconnectMessager.hide();
  2391. lastDisconnectMessager = null;
  2392. zui.Messager.show({
  2393. content: hocuspocusConnect,
  2394. type: 'success',
  2395. time: 3000,
  2396. });
  2397. };
  2398. window.onHocuspocusDisconnect = function(app)
  2399. {
  2400. if(app.spaceType === 'mine') return;
  2401. lastDisconnectMessager && lastDisconnectMessager.hide();
  2402. lastDisconnectMessager = zui.Messager.show({
  2403. content: hocuspocusDisconnect,
  2404. type: 'danger',
  2405. time: 0,
  2406. });
  2407. };
  2408. window.onAuthenticationFailed = function(app)
  2409. {
  2410. if(app.spaceType === 'mine') return;
  2411. zui.Messager.show({
  2412. content: needReadable,
  2413. type: 'danger',
  2414. time: 3000,
  2415. });
  2416. };
  2417. window.onDocAppModeChange = function()
  2418. {
  2419. lastDisconnectMessager && lastDisconnectMessager.hide();
  2420. lastDisconnectMessager = null;
  2421. };
  2422. window.getPageFormHelper = function()
  2423. {
  2424. const docApp = getDocApp();
  2425. if(docApp.mode === 'edit' && !isApiDoc(docApp.doc))
  2426. {
  2427. const fields =
  2428. {
  2429. title: (_, $scope) => $scope.find('.doc-editor-title'),
  2430. content: (_, $scope) => $scope.find('[z-use-editor]'),
  2431. };
  2432. return zui.formHelper($(docApp.element).find('.doc-editor'), {fields: fields});
  2433. }
  2434. };