space.vue.subassembly.js 136 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209
  1. /**
  2. * 图片上传
  3. */
  4. Vue.component('spaceUploadImg', {
  5. data: function () {
  6. return {
  7. id: "spaceUploadImg" + space.utils.random(6),
  8. }
  9. },
  10. name: "spaceUploadImg",
  11. model: {
  12. prop: 'patharry',
  13. evnet: 'click'
  14. },
  15. /**
  16. * patharry: v-model 绑定的值,非空,字符串数组
  17. * type: 上传按钮的风格,可空,缺省值为 button ,可选值为button / img
  18. * width: 图片裁剪的宽度,可空
  19. * height: 图片裁剪的高度,可空
  20. * maxsize: 最大上传的图片数量,可空,缺省值为1
  21. * tip: 提示语,可空
  22. * color: 图片背景,可空,值的类型与css的color值类型一样
  23. * source: 是否可上传原图
  24. */
  25. props: {
  26. patharry: {
  27. type: Array,
  28. required: true
  29. },
  30. type: {
  31. type: String,
  32. default: "button"
  33. },
  34. width: [String, Number],
  35. height: [String, Number],
  36. maxsize: {
  37. type: [String, Number],
  38. default: 1
  39. },
  40. tip: [String, Number],
  41. color: [String, Number],
  42. source: {
  43. type: Boolean,
  44. default: false,
  45. }
  46. },
  47. created: function () {
  48. // 对初始化值进行处理,排除掉空数据
  49. if (!this.patharry) {
  50. this.patharry = [];
  51. }
  52. var newAry = [];
  53. if (typeof this.patharry == "string") {
  54. if (space.utils.notNull(this.patharry)) {
  55. newAry.push(this.patharry);
  56. }
  57. } else {
  58. for (let index = 0; index < this.patharry.length; index++) {
  59. const element = this.patharry[index];
  60. if (space.utils.notNull(element)) {
  61. newAry.push(element);
  62. }
  63. }
  64. }
  65. this.patharry = newAry;
  66. this.$emit("input", newAry);
  67. },
  68. mounted: function () {
  69. var that = this;
  70. space.plugins.cropper.init({
  71. el: $("#" + that.id),
  72. photoSize: { // 裁剪的图片大小,会自动计算裁剪比例
  73. width: that.width,
  74. height: that.height,
  75. source: that.source,
  76. },
  77. show: function (setting) { //打开裁剪框前的回调
  78. setting.photoSize = {
  79. width: that.width,
  80. height: that.height,
  81. source: that.source,
  82. }
  83. },
  84. success: function (path) { // 成功后的回调方法,path为裁剪后的img路径
  85. that.patharry.push(path);
  86. that.$emit("input", that.patharry);
  87. },
  88. });
  89. },
  90. methods: {
  91. uploadClick: function () {
  92. if (this.patharry.length >= this.maxsize) {
  93. space.message.warning("最多上传" + this.maxsize + "张图片");
  94. return false;
  95. }
  96. $("#" + this.id).click();
  97. },
  98. removeCropperImg: function (index) {
  99. this.patharry.splice(index, 1);
  100. space.message.success("图片已删除");
  101. this.$emit("input", this.patharry);
  102. },
  103. },
  104. template: `
  105. <div class="space-upload-img">
  106. <el-button size="small" icon="el-icon-upload" @click="uploadClick" :disabled="patharry.length >= maxsize" v-if="type == 'button' || space.utils.isNull(type)">上传</el-button>
  107. <span v-show="patharry.length >= maxsize" style="color: #C0C4CC;margin-left: 6px;">
  108. 最多上传{{maxsize}}张图片
  109. </span>
  110. <span v-show="tip" style="color: #888;margin-left: 6px;">
  111. {{tip}}
  112. </span>
  113. <input type="file" accept="image/*" :id="id" style="display: none;" />
  114. <div>
  115. <div v-show="patharry" class="cropper-img-content" v-for="(item, index) in patharry" :key="index"">
  116. <el-image class="cropper-img" fit="contain" :style="{'background-color': color}"
  117. :src="item" @click="space.plugins.elPreview.show(item, patharry)">
  118. </el-image>
  119. <i class="el-icon-close" @click="removeCropperImg(index)"></i>
  120. </div>
  121. <div class="uploadButton-img" v-if="type == 'img'" @click="uploadClick" v-show="patharry.length < maxsize">
  122. <i class="el-icon-plus"></i>
  123. </div>
  124. </div>
  125. </div>
  126. `
  127. })
  128. /**
  129. * 图片预览
  130. */
  131. Vue.component('spacePreviewImg', {
  132. data: function () {
  133. return {
  134. newAry: [],
  135. }
  136. },
  137. name: "spacePreviewImg",
  138. /**
  139. * paths: 绑定的值,非空,字符串/数组
  140. * color: 图片背景色,可空,值的类型与css的color值类型一样
  141. */
  142. props: {
  143. paths: {
  144. type: [Array, String],
  145. required: true
  146. },
  147. color: {
  148. type: String,
  149. }
  150. },
  151. created: function () {
  152. // 对初始化值进行处理,排除掉空数据
  153. if (!this.paths) {
  154. this.paths = [];
  155. }
  156. if (typeof this.paths == "string") {
  157. if (space.utils.notNull(this.paths)) {
  158. this.newAry.push(this.paths);
  159. }
  160. } else {
  161. for (let index = 0; index < this.paths.length; index++) {
  162. const element = this.paths[index];
  163. if (space.utils.notNull(element)) {
  164. this.newAry.push(element);
  165. }
  166. }
  167. }
  168. this.$emit("input", this.newAry);
  169. },
  170. mounted: function () {
  171. },
  172. methods: {
  173. },
  174. template: `
  175. <div class="space-preview-img">
  176. <div class="cropper-img-content" v-for="(item, index) in newAry" :key="index">
  177. <el-image class="cropper-img" fit="contain" :style="{'background-color': color}"
  178. :src="item" @click="space.plugins.elPreview.show(item, newAry)">
  179. </el-image>
  180. </div>
  181. </div>
  182. `
  183. })
  184. /**
  185. * 对象选择器
  186. */
  187. Vue.component('spaceSelect', {
  188. data: function () {
  189. return {
  190. id: "spaceSelect" + space.utils.random(6),
  191. randomNum: space.utils.random(6),
  192. options: [],
  193. isOpen: true, // 是否打开
  194. }
  195. },
  196. name: "spaceSelect",
  197. model: {
  198. prop: 'modelAry',
  199. evnet: 'click'
  200. },
  201. /**
  202. * modelAry: 绑定的值,非空,字符串/数组
  203. * predefine: 预定义对象,非空,可选值有person、department、post、role
  204. * datasize: 最多选择的数量,可空,默认值为1
  205. * method:自定义方法
  206. */
  207. props: ['modelAry', "predefine", "datasize", "method"],
  208. watch: {
  209. modelAry: function (newVal, oldVal) {
  210. // 没有打开时,则可以初始化选择数据集合
  211. if (!this.isOpen) {
  212. this.isOpen = true;
  213. this.initSelectedDataList();
  214. } else {
  215. this.isOpen = false;
  216. }
  217. }
  218. },
  219. created: function () {
  220. if (this.predefine && this.method) {
  221. space.message.error('predefine 与 method 不能同时存在');
  222. }
  223. if (!this.isPredefine()) {
  224. if (!this.method) {
  225. space.message.warning('预定义选择器不存在:' + this.predefine);
  226. }
  227. }
  228. },
  229. mounted: function () {
  230. var that = this;
  231. if (!this.method) {
  232. // 初始化选择窗
  233. space.choose[that.predefine].init({
  234. el: $("#choose" + that.predefine + that.randomNum), // 点击弹出选择窗的元素
  235. selectAry: function () {
  236. return that.modelAry;
  237. }, // 已选的数组
  238. selectCountNum: that.datasize || 1, // 最多选择的数量
  239. success: function (param) { // 成功后的回调
  240. that.options = param;
  241. that.modelAry = [];
  242. that.options.forEach(function (item) {
  243. that.modelAry.push(item["id"]);
  244. });
  245. that.$emit("input", that.modelAry);
  246. }
  247. })
  248. }
  249. /* 监听容器高度 */
  250. const erd = elementResizeDetectorMaker();
  251. var eles = $("#" + that.id).find("div.el-input--suffix")[0];
  252. erd.listenTo(eles, element => {
  253. const height = element.offsetHeight;
  254. $("#choose" + that.predefine + that.randomNum).css("height", height);
  255. });
  256. this.initSelectedDataList();
  257. },
  258. methods: {
  259. removeFun: function () {
  260. this.$emit("input", this.modelAry);
  261. },
  262. /**
  263. * 获取最大限制绑定的值
  264. */
  265. getMaxSelectedModelAry: function () {
  266. var tmpAry = [];
  267. var _this = this;
  268. this.options.forEach(function (item) {
  269. tmpAry.push(item["id"]);
  270. });
  271. if (this.datasize == undefined || this.datasize == 1) {
  272. return tmpAry.length > 0 ? [tmpAry[tmpAry.length - 1]] : [];
  273. } else if (this.datasize > 1) {
  274. var selectedAry = [];
  275. tmpAry.forEach(function (item, index) {
  276. if ((index + 1) > _this.datasize) {
  277. return;
  278. }
  279. selectedAry.push(item);
  280. });
  281. return selectedAry;
  282. } else if (this.datasize == '*') {
  283. return tmpAry;
  284. } else {
  285. return [];
  286. }
  287. },
  288. /**
  289. * 是否预定义选择器,false:不是预定义选择器,true:是预定义选择器
  290. */
  291. isPredefine: function () {
  292. if (this.predefine != "person" && this.predefine != "department" && this.predefine != "post" && this.predefine != "role") {
  293. return false; // 不是预定义选择器
  294. } else {
  295. return true; // 预定义选择器
  296. }
  297. },
  298. /**
  299. * 获取预定义的服务
  300. */
  301. getPredefineService: function () {
  302. var map = new Map();
  303. map.set("person", "/apps?ark=personnel.person_getChoolsePersonInfoApi");
  304. map.set("department", "/apps?ark=sys.department_getChoolseDepartmentInfoApi");
  305. map.set("post", "/apps?ark=sys.post_getChoolsePostInfoApi");
  306. map.set("role", "/apps?ark=sys.role_getChoolseRoleInfoApi");
  307. return map.get(this.predefine);
  308. },
  309. /**
  310. * 初始化选择数据集合
  311. */
  312. initSelectedDataList: function () {
  313. if (!this.isPredefine() || this.method) {
  314. return;
  315. }
  316. if (!this.modelAry || this.modelAry.length == 0) {
  317. this.isOpen = false; // 没有数据时,则关闭
  318. return;
  319. }
  320. var url = this.getPredefineService();
  321. var ids = typeof (this.modelAry) == 'string' || typeof (this.modelAry) == 'number' ? this.modelAry : this.modelAry.join(',');
  322. var _this = this;
  323. // 查询选中的列表
  324. space.utils.ajax({
  325. url: url,
  326. data: {
  327. "ids": ids
  328. },
  329. dataType: 'json',
  330. callback: function (data) {
  331. _this.options = data.data;
  332. var tmpAry = _this.getMaxSelectedModelAry();
  333. _this.$emit("input", tmpAry);
  334. }
  335. })
  336. },
  337. },
  338. template: `
  339. <div class="space-select" :id="id" >
  340. <el-select class="choose-obj" v-model="modelAry" multiple placeholder="请选择" :value-key="id" clearable
  341. :popper-append-to-body="false" style="width: calc(100% - 60px);" :disabled="!modelAry.length>0" @remove-tag="removeFun" @clear="removeFun">
  342. <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id">
  343. </el-option>
  344. </el-select>
  345. <el-button type="button" size="medium" class="choose-btn" :id="'choose' + predefine + randomNum" icon="el-icon-search"></el-button>
  346. </div>
  347. `
  348. })
  349. /**
  350. * Editor 编辑器
  351. */
  352. Vue.component('spaceEditor', {
  353. data: function () {
  354. return {
  355. id: "spaceEditor" + space.utils.random(6),
  356. editor: undefined,
  357. // 编辑器需要的 js 文件
  358. jsUrl: [
  359. '/apps/space/plug-in/ckeditor5/build/ckeditor.js',
  360. '/apps/space/plug-in/ckeditor5/src/plugins/upload/src/myUploadAdapter.js?v=20260719-image-src'
  361. ],
  362. // 标识,全部为 true 则代表全部加载完成
  363. jsUrlFlag: [],
  364. notLoadEditor: true, // 未加载完 editor 编辑器,true:未加载完,false:已加载完
  365. imageQuality: 'standard',
  366. uploading: false,
  367. uploadStatus: '',
  368. previewVisible: false,
  369. previewMode: 'pc',
  370. previewUrl: '',
  371. previewLoading: false,
  372. videoPlaybackSyncTimer: undefined,
  373. activePdf: null,
  374. uploadedImageUrls: [],
  375. pdfFloatToolbarStyle: null,
  376. _emitEditorHtmlTimer: undefined,
  377. _enhancePdfTimer: undefined,
  378. _pdfEnhancing: false,
  379. defaultEditorFontFamily: "'仿宋_GB2312', 'FangSong_GB2312', FangSong, serif",
  380. defaultEditorFontSize: "20pt",
  381. defaultEditorLineHeight: "1.75",
  382. }
  383. },
  384. name: "spaceEditor",
  385. model: {
  386. prop: 'htmlContent',
  387. evnet: 'click'
  388. },
  389. /**
  390. * htmlContent: v-model 绑定的值,非空,html 字符串
  391. * size: 编辑器的大小,small、medium、large
  392. * width: 编辑器的宽度,可空
  393. * height: 编辑器的高度,可空
  394. * placeholder:占位符
  395. * type:编辑器工具栏类型
  396. * isfullscreen:是否有全屏,
  397. */
  398. props: ['htmlContent', 'size', 'width', 'height', 'placeholder', 'type', 'isfullscreen', 'articlepreview', 'previewdata', 'previewurl', 'wordconverturl'],
  399. computed: {
  400. previewFrameStyle: function () {
  401. var widthMap = {
  402. pc: '1200px',
  403. pad: '768px',
  404. mobile: '390px'
  405. };
  406. return {
  407. width: widthMap[this.previewMode] || widthMap.pc,
  408. height: '680px'
  409. };
  410. }
  411. },
  412. watch: {
  413. height: function (newVal, oldVal) {
  414. if (this.height && this.height.toString().toLocaleLowerCase().indexOf('px') == -1) {
  415. this.height += 'px';
  416. } else {
  417. this.setEditorHeight();
  418. }
  419. },
  420. editor: function (newVal, oldVal) {
  421. this.setEditorHeight();
  422. },
  423. jsUrlFlag: function (newVal, oldVal) {
  424. if (this.jsUrl.length > 0 && this.jsUrl.length == this.jsUrlFlag.length) {
  425. if (this.jsUrlFlag.indexOf('false') != -1) {
  426. return;
  427. }
  428. this.initEditor();
  429. this.notLoadEditor = false;
  430. this.setEditorHeight();
  431. }
  432. },
  433. notLoadEditor: function (newVal, oldVal) {
  434. this.setEditorHeight();
  435. },
  436. },
  437. created: function () {
  438. var _this = this;
  439. for (var i = 0; i < _this.jsUrl.length; i++) {
  440. _this.loadJS(_this.jsUrl[i], function () {
  441. _this.jsUrlFlag.push('true');
  442. });
  443. }
  444. },
  445. methods: {
  446. loadJS: function (url, callback) {
  447. for (var i = 0; i < document.getElementsByTagName('head')[0].getElementsByTagName('script').length; i++) {
  448. var src = document.getElementsByTagName('head')[0].getElementsByTagName('script')[i].getAttribute('src');
  449. if (url == src) {
  450. // 防止一个页面有多个编辑器时,编辑器加载失败
  451. if (space.vars.editorReady != true) {
  452. var winInterval = setInterval(function () {
  453. if (space.vars.editorReady != true) {
  454. return;
  455. }
  456. window.clearInterval(winInterval);
  457. if (callback) {
  458. callback();
  459. }
  460. }, 100)
  461. }
  462. return;
  463. }
  464. }
  465. var script = document.createElement('script');
  466. script.type = 'text/javascript';
  467. script.onload = function () {
  468. if (callback) {
  469. callback();
  470. }
  471. };
  472. script.src = url;
  473. document.getElementsByTagName('head')[0].appendChild(script);
  474. },
  475. isArticlePreview: function () {
  476. return this.articlepreview === true || this.articlepreview === 'true';
  477. },
  478. showEditorTools: function () {
  479. return this.type != 'flow' && this.isArticlePreview();
  480. },
  481. normalizeEditorMediaUrl: function (url) {
  482. if (space.utils.isNull(url)) {
  483. return "";
  484. }
  485. return this.normalizeLocalUploadUrl(url);
  486. },
  487. getEditorEditableElement: function (editor) {
  488. if (!editor) {
  489. return null;
  490. }
  491. if (editor.ui && editor.ui.view && editor.ui.view.editable && editor.ui.view.editable.element) {
  492. return editor.ui.view.editable.element;
  493. }
  494. if (editor.editing && editor.editing.view && typeof editor.editing.view.getDomRoot === 'function') {
  495. var domRoot = editor.editing.view.getDomRoot();
  496. if (domRoot) {
  497. return domRoot;
  498. }
  499. }
  500. if (editor.ui && typeof editor.ui.getEditableElement === 'function') {
  501. var editable = editor.ui.getEditableElement();
  502. if (editable) {
  503. return editable;
  504. }
  505. }
  506. if (editor.ui && editor.ui.view && editor.ui.view.element) {
  507. return editor.ui.view.element.querySelector('.ck-editor__editable_inline');
  508. }
  509. return null;
  510. },
  511. normalizeVideoHtmlForEditor: function (html) {
  512. if (!html || html.indexOf("<video") === -1 || html.indexOf("<source") === -1) {
  513. return html || "";
  514. }
  515. var wrapper = document.createElement("div");
  516. wrapper.innerHTML = html;
  517. var videos = wrapper.querySelectorAll("video");
  518. var changed = false;
  519. for (var i = 0; i < videos.length; i++) {
  520. var video = videos[i];
  521. if (video.getAttribute("src")) {
  522. continue;
  523. }
  524. var source = video.querySelector("source[src]");
  525. if (!source) {
  526. continue;
  527. }
  528. video.setAttribute("src", this.normalizeEditorMediaUrl(source.getAttribute("src") || ""));
  529. changed = true;
  530. }
  531. return changed ? wrapper.innerHTML : html;
  532. },
  533. sanitizePdfHtmlForSave: function (html) {
  534. if (!html) {
  535. return "";
  536. }
  537. if (html.indexOf("space-editor-pdf") === -1 && html.indexOf("data-space-pdf") === -1) {
  538. return html;
  539. }
  540. var wrapper = document.createElement("div");
  541. wrapper.innerHTML = html;
  542. var junk = wrapper.querySelectorAll(
  543. ".space-editor-pdf-toolbar-overlay, .space-editor-pdf-select-layer, .space-editor-pdf-preview-error, .space-editor-pdf-shell"
  544. );
  545. for (var j = 0; j < junk.length; j++) {
  546. var node = junk[j];
  547. if (node.classList.contains("space-editor-pdf-shell")) {
  548. var shellIframe = node.querySelector("iframe.space-editor-pdf-frame");
  549. if (shellIframe && node.parentNode) {
  550. node.parentNode.insertBefore(shellIframe, node);
  551. }
  552. }
  553. if (node.parentNode) {
  554. node.parentNode.removeChild(node);
  555. }
  556. }
  557. var figures = wrapper.querySelectorAll("figure.space-editor-pdf-viewer, figure[data-space-pdf='true']");
  558. for (var i = 0; i < figures.length; i++) {
  559. var figure = figures[i];
  560. var iframe = figure.querySelector("iframe.space-editor-pdf-frame");
  561. var src = this.normalizeEditorMediaUrl(figure.getAttribute("data-space-pdf-src")
  562. || (iframe ? iframe.getAttribute("src") : "") || "");
  563. var secure = figure.getAttribute("data-space-pdf-secure") || "0";
  564. if (src) {
  565. figure.setAttribute("data-space-pdf-src", src);
  566. }
  567. figure.setAttribute("data-space-pdf-secure", secure);
  568. if (iframe) {
  569. var iframeSrc = iframe.getAttribute("src") || "";
  570. if (iframeSrc.indexOf("secure-viewer.html") !== -1 || secure === "1") {
  571. iframe.removeAttribute("src");
  572. } else if (src) {
  573. iframe.setAttribute("src", src);
  574. }
  575. }
  576. }
  577. return wrapper.innerHTML;
  578. },
  579. sanitizeVideoHtmlForSave: function (html) {
  580. if (!html) {
  581. return "";
  582. }
  583. if (html.indexOf("<video") === -1 && html.indexOf("space-editor-video") === -1 && html.indexOf("data-space-video") === -1) {
  584. return html;
  585. }
  586. var wrapper = document.createElement("div");
  587. wrapper.innerHTML = html;
  588. var _this = this;
  589. var getVideoSrc = function (video) {
  590. if (!video) {
  591. return "";
  592. }
  593. var figure = video.closest ? video.closest("figure.space-editor-video-viewer, figure[data-space-video='true']") : null;
  594. var source = video.querySelector("source[src]");
  595. return _this.normalizeEditorMediaUrl((figure && figure.getAttribute("data-space-video-src"))
  596. || video.getAttribute("src")
  597. || (source ? source.getAttribute("src") : "")
  598. || "");
  599. };
  600. var inferVideoType = function (src) {
  601. if (/\.webm(\?.*)?$/i.test(src)) {
  602. return "video/webm";
  603. }
  604. if (/\.ogg|\.ogv(\?.*)?$/i.test(src)) {
  605. return "video/ogg";
  606. }
  607. return "video/mp4";
  608. };
  609. var buildCleanVideoBlock = function (video, src) {
  610. var p = document.createElement("p");
  611. var cleanVideo = document.createElement("video");
  612. var source = document.createElement("source");
  613. cleanVideo.setAttribute("controls", "controls");
  614. cleanVideo.setAttribute("playsinline", "playsinline");
  615. cleanVideo.setAttribute("webkit-playsinline", "webkit-playsinline");
  616. cleanVideo.setAttribute("preload", video.getAttribute("preload") || "metadata");
  617. var poster = video.getAttribute("poster") || "";
  618. if (poster) {
  619. cleanVideo.setAttribute("poster", _this.normalizeEditorMediaUrl(poster));
  620. }
  621. cleanVideo.setAttribute("style", video.getAttribute("style")
  622. || "display:block;width:100%;max-width:960px;background:#000;");
  623. source.setAttribute("src", src);
  624. source.setAttribute("type", inferVideoType(src));
  625. cleanVideo.appendChild(source);
  626. cleanVideo.appendChild(document.createTextNode("您的浏览器暂不支持视频播放。"));
  627. p.appendChild(cleanVideo);
  628. return p;
  629. };
  630. var videos = Array.prototype.slice.call(wrapper.querySelectorAll("video"));
  631. for (var v = 0; v < videos.length; v++) {
  632. var looseVideo = videos[v];
  633. if (!looseVideo.parentNode) {
  634. continue;
  635. }
  636. var src = getVideoSrc(looseVideo);
  637. if (!src) {
  638. continue;
  639. }
  640. var cleanBlock = buildCleanVideoBlock(looseVideo, src);
  641. var videoFigure = looseVideo.closest ? looseVideo.closest("figure.space-editor-video-viewer, figure[data-space-video='true']") : null;
  642. var parent = looseVideo.parentNode;
  643. var shouldReplaceParent = false;
  644. if (parent && /^(p|div)$/i.test(parent.tagName || "") && parent.querySelectorAll("video").length == 1) {
  645. var parentClone = parent.cloneNode(true);
  646. var cloneVideo = parentClone.querySelector("video");
  647. if (cloneVideo && cloneVideo.parentNode) {
  648. cloneVideo.parentNode.removeChild(cloneVideo);
  649. }
  650. shouldReplaceParent = (parentClone.textContent || "").replace(/\s+/g, "") == "";
  651. }
  652. var replaceTarget = videoFigure || (shouldReplaceParent ? parent : looseVideo);
  653. if (replaceTarget && replaceTarget.parentNode) {
  654. replaceTarget.parentNode.replaceChild(cleanBlock, replaceTarget);
  655. }
  656. }
  657. return wrapper.innerHTML;
  658. },
  659. restoreImageSourcesForSave: function (html) {
  660. if (!html || html.indexOf("<img") === -1 || !this.editor) {
  661. return html || "";
  662. }
  663. var wrapper = document.createElement("div");
  664. wrapper.innerHTML = html;
  665. var outputImages = wrapper.querySelectorAll("img");
  666. if (!outputImages.length) {
  667. return html;
  668. }
  669. var getImageSrc = function (image) {
  670. if (!image) {
  671. return "";
  672. }
  673. var src = image.getAttribute("src") || image.src || "";
  674. if (!src) {
  675. var srcset = image.getAttribute("srcset") || "";
  676. if (srcset) {
  677. src = srcset.split(",")[0].trim().split(/\s+/)[0] || "";
  678. }
  679. }
  680. return this.normalizeEditorMediaUrl(src);
  681. }.bind(this);
  682. var editorImages = [];
  683. var editable = this.getEditorEditableElement(this.editor);
  684. if (editable) {
  685. var domImages = editable.querySelectorAll("img");
  686. for (var i = 0; i < domImages.length; i++) {
  687. editorImages.push(getImageSrc(domImages[i]));
  688. }
  689. }
  690. var modelImages = [];
  691. if (this.editor.model && this.editor.model.document) {
  692. var root = this.editor.model.document.getRoot();
  693. var range = this.editor.model.createRangeIn(root);
  694. var walker = range.getWalker({ ignoreElementEnd: true });
  695. for (var step = walker.next(); !step.done; step = walker.next()) {
  696. var item = step.value.item;
  697. if (item.is && item.is("element") && (item.name === "imageBlock" || item.name === "imageInline")) {
  698. modelImages.push(this.normalizeEditorMediaUrl(item.getAttribute("src") || ""));
  699. }
  700. }
  701. }
  702. var missingImageIndex = 0;
  703. for (var imageIndex = 0; imageIndex < outputImages.length; imageIndex++) {
  704. var outputImage = outputImages[imageIndex];
  705. var src = getImageSrc(outputImage);
  706. if (!src) {
  707. src = editorImages[imageIndex]
  708. || modelImages[imageIndex]
  709. || (this.uploadedImageUrls ? this.uploadedImageUrls[missingImageIndex] : "")
  710. || (this.uploadedImageUrls ? this.uploadedImageUrls[imageIndex] : "")
  711. || "";
  712. src = this.normalizeEditorMediaUrl(src);
  713. }
  714. if (src) {
  715. outputImage.setAttribute("src", src);
  716. outputImage.removeAttribute("data-original");
  717. outputImage.removeAttribute("data-src");
  718. outputImage.removeAttribute("data-lazy-src");
  719. }
  720. missingImageIndex++;
  721. }
  722. return wrapper.innerHTML;
  723. },
  724. getEditorSaveHtml: function () {
  725. if (!this.editor) {
  726. return this.htmlContent || "";
  727. }
  728. var html = this.editor.getData();
  729. html = this.restoreImageSourcesForSave(html);
  730. html = this.normalizeAttachmentLinksForSave(html);
  731. html = this.sanitizePdfHtmlForSave(html);
  732. html = this.sanitizeVideoHtmlForSave(html);
  733. return html;
  734. },
  735. normalizeAttachmentLinksForSave: function (html) {
  736. if (!html || html.indexOf('/web/upload/') === -1) {
  737. return html || "";
  738. }
  739. var wrapper = document.createElement('div');
  740. wrapper.innerHTML = html;
  741. var links = wrapper.querySelectorAll('a[href]');
  742. for (var i = 0; i < links.length; i++) {
  743. var link = links[i];
  744. var href = this.normalizeLocalUploadUrl(link.getAttribute('href') || '');
  745. if (!href || href.indexOf('/web/upload/') !== 0) {
  746. continue;
  747. }
  748. var fileName = (link.textContent || '').replace(/\s+/g, ' ').trim();
  749. if (!fileName) {
  750. try {
  751. fileName = decodeURIComponent(href.split('?')[0].split('#')[0].split('/').pop() || '附件');
  752. } catch (error) {
  753. fileName = href.split('?')[0].split('#')[0].split('/').pop() || '附件';
  754. }
  755. }
  756. link.setAttribute('href', href);
  757. link.setAttribute('download', fileName);
  758. link.setAttribute('target', '_blank');
  759. link.setAttribute('rel', 'noopener');
  760. link.setAttribute('title', '下载附件:' + fileName);
  761. link.classList.add('article-attachment');
  762. link.style.color = '#1769ff';
  763. link.style.textDecoration = 'underline';
  764. }
  765. return wrapper.innerHTML;
  766. },
  767. deferEmitEditorHtml: function () {
  768. if (this._emitEditorHtmlTimer) {
  769. window.clearTimeout(this._emitEditorHtmlTimer);
  770. }
  771. var _this = this;
  772. this._emitEditorHtmlTimer = window.setTimeout(function () {
  773. _this._emitEditorHtmlTimer = undefined;
  774. if (!_this.editor) {
  775. return;
  776. }
  777. _this.$emit("input", _this.getEditorSaveHtml());
  778. }, 150);
  779. },
  780. deferEnhanceEditorPdfViewers: function () {
  781. if (this._enhancePdfTimer) {
  782. window.clearTimeout(this._enhancePdfTimer);
  783. }
  784. var _this = this;
  785. this._enhancePdfTimer = window.setTimeout(function () {
  786. _this._enhancePdfTimer = undefined;
  787. _this.enhanceEditorPdfViewers();
  788. }, 80);
  789. },
  790. syncEditorBodyToForm: function () {
  791. var html = this.getEditorSaveHtml();
  792. this.$emit("input", html);
  793. if (space.vue && space.vue.$data && space.vue.$data.obj) {
  794. space.vue.$data.obj.body = html;
  795. }
  796. return html;
  797. },
  798. bindFormSubmitSync: function () {
  799. if (this.type === 'flow') {
  800. return;
  801. }
  802. var _this = this;
  803. var previousBefore = space.forms.before;
  804. space.forms.before = function () {
  805. _this.syncEditorBodyToForm();
  806. if (typeof previousBefore === "function") {
  807. return previousBefore.apply(this, arguments);
  808. }
  809. };
  810. },
  811. findPdfModelBySrc: function (src) {
  812. var editor = this.editor;
  813. var target = this.normalizeEditorMediaUrl(src);
  814. if (!editor || !target) {
  815. return null;
  816. }
  817. var root = editor.model.document.getRoot();
  818. var range = editor.model.createRangeIn(root);
  819. var walker = range.getWalker({ ignoreElementEnd: true });
  820. for (var step = walker.next(); !step.done; step = walker.next()) {
  821. var item = step.value.item;
  822. if (item.is && item.is("element") && item.name === "spacePdfViewer") {
  823. var itemSrc = this.normalizeEditorMediaUrl(item.getAttribute("src") || "");
  824. if (itemSrc === target) {
  825. return item;
  826. }
  827. }
  828. }
  829. return null;
  830. },
  831. resolvePdfContextFromDom: function (domTarget) {
  832. var editor = this.editor;
  833. if (!editor || !domTarget || !domTarget.closest) {
  834. return null;
  835. }
  836. var iframe = domTarget.closest("iframe.space-editor-pdf-frame");
  837. if (!iframe) {
  838. var figure = domTarget.closest("figure.space-editor-pdf-viewer");
  839. if (figure) {
  840. iframe = figure.querySelector("iframe.space-editor-pdf-frame");
  841. }
  842. }
  843. if (!iframe) {
  844. return null;
  845. }
  846. var figureEl = iframe.closest("figure.space-editor-pdf-viewer") || iframe.closest("figure");
  847. var src = (figureEl && figureEl.getAttribute("data-space-pdf-src")) || iframe.getAttribute("src") || "";
  848. src = this.normalizeEditorMediaUrl(src);
  849. if (!src) {
  850. return null;
  851. }
  852. var secure = (figureEl && figureEl.getAttribute("data-space-pdf-secure")) || "0";
  853. var title = iframe.getAttribute("title") || "PDF文件";
  854. var modelElement = this.findPdfModelBySrc(src);
  855. if (modelElement) {
  856. secure = modelElement.getAttribute("secure") || secure || "0";
  857. title = modelElement.getAttribute("title") || title;
  858. }
  859. return {
  860. src: src,
  861. title: title,
  862. secure: secure === "1" ? "1" : "0",
  863. iframe: iframe,
  864. modelElement: modelElement
  865. };
  866. },
  867. updateActivePdfContext: function (domTarget) {
  868. var context = this.resolvePdfContextFromDom(domTarget);
  869. if (!context) {
  870. return;
  871. }
  872. this.activePdf = {
  873. src: context.src,
  874. title: context.title,
  875. secure: context.secure
  876. };
  877. this.updatePdfFloatToolbarPosition(context.iframe);
  878. this.refreshPdfSecureStatusBar();
  879. },
  880. activateLastPdfInEditor: function () {
  881. var editor = this.editor;
  882. if (!editor || !editor.editing || !editor.editing.view) {
  883. return;
  884. }
  885. var iframes = editor.editing.view.getDomRoot().querySelectorAll("iframe.space-editor-pdf-frame");
  886. if (!iframes.length) {
  887. return;
  888. }
  889. this.updateActivePdfContext(iframes[iframes.length - 1]);
  890. },
  891. updatePdfFloatToolbarPosition: function (iframe) {
  892. if (!iframe || !iframe.getBoundingClientRect) {
  893. this.pdfFloatToolbarStyle = null;
  894. return;
  895. }
  896. var wrap = this.$el && this.$el.querySelector ? this.$el.querySelector(".space-editor-wrap") : null;
  897. if (!wrap) {
  898. this.pdfFloatToolbarStyle = null;
  899. return;
  900. }
  901. var iframeRect = iframe.getBoundingClientRect();
  902. var wrapRect = wrap.getBoundingClientRect();
  903. this.pdfFloatToolbarStyle = {
  904. top: (iframeRect.top - wrapRect.top) + "px",
  905. left: (iframeRect.left - wrapRect.left) + "px",
  906. width: iframeRect.width + "px"
  907. };
  908. },
  909. applyActivePdfSecure: function (secure) {
  910. var activePdf = this.activePdf;
  911. if (!activePdf || !activePdf.src || !this.editor) {
  912. return;
  913. }
  914. secure = secure === "1" ? "1" : "0";
  915. activePdf.secure = secure;
  916. var modelElement = this.findPdfModelBySrc(activePdf.src);
  917. if (modelElement) {
  918. this.editor.model.change(function (writer) {
  919. writer.setAttribute("secure", secure, modelElement);
  920. });
  921. } else {
  922. this.setPdfSecureFlagInDocument(activePdf.src, secure);
  923. }
  924. this.$emit("input", this.getEditorSaveHtml());
  925. this.refreshPdfSecureStatusBar();
  926. window.setTimeout(function () {
  927. this.enhanceEditorPdfViewers();
  928. this.activateLastPdfInEditor();
  929. this.refreshPdfSecureStatusBar();
  930. }.bind(this), 0);
  931. },
  932. setPdfSecureFlagInDocument: function (src, secure) {
  933. var editor = this.editor;
  934. var target = this.normalizeEditorMediaUrl(src);
  935. if (!editor || !target) {
  936. return;
  937. }
  938. var data = editor.getData();
  939. if (data.indexOf(".pdf") === -1) {
  940. return;
  941. }
  942. var wrapper = document.createElement("div");
  943. wrapper.innerHTML = data;
  944. var figures = wrapper.querySelectorAll("figure.space-editor-pdf-viewer, figure[data-space-pdf='true']");
  945. var changed = false;
  946. for (var i = 0; i < figures.length; i++) {
  947. var figure = figures[i];
  948. var iframe = figure.querySelector("iframe.space-editor-pdf-frame");
  949. var figureSrc = this.normalizeEditorMediaUrl(figure.getAttribute("data-space-pdf-src")
  950. || (iframe ? iframe.getAttribute("src") : "") || "");
  951. if (figureSrc !== target) {
  952. continue;
  953. }
  954. figure.setAttribute("data-space-pdf-secure", secure);
  955. figure.setAttribute("data-space-pdf-src", target);
  956. if (iframe) {
  957. iframe.setAttribute("title", iframe.getAttribute("title") || "PDF文件");
  958. if (secure === "1") {
  959. iframe.removeAttribute("src");
  960. } else {
  961. iframe.setAttribute("src", target);
  962. }
  963. }
  964. var caption = figure.querySelector("figcaption");
  965. if (secure === "1" && caption) {
  966. caption.parentNode.removeChild(caption);
  967. }
  968. changed = true;
  969. }
  970. if (changed) {
  971. editor.setData(wrapper.innerHTML);
  972. }
  973. },
  974. selectPdfBlockFromDom: function (editor, domTarget) {
  975. if (!editor || !domTarget || !domTarget.closest) {
  976. return false;
  977. }
  978. if (this.isPdfToolbarControl(domTarget)) {
  979. return false;
  980. }
  981. var figure = domTarget.closest("figure.space-editor-pdf-viewer");
  982. if (!figure) {
  983. var shell = domTarget.closest(".space-editor-pdf-shell");
  984. if (shell) {
  985. figure = shell.closest("figure.space-editor-pdf-viewer");
  986. }
  987. }
  988. if (!figure) {
  989. return false;
  990. }
  991. var viewFigure = editor.editing.view.domConverter.mapDomToView(figure);
  992. if (!viewFigure) {
  993. return false;
  994. }
  995. var modelElement = editor.editing.mapper.toModelElement(viewFigure);
  996. if (!modelElement) {
  997. return false;
  998. }
  999. editor.model.change(function (writer) {
  1000. writer.setSelection(modelElement, "on");
  1001. });
  1002. if (editor.editing && editor.editing.view && editor.editing.view.focus) {
  1003. editor.editing.view.focus();
  1004. }
  1005. this.updateActivePdfContext(domTarget);
  1006. this.syncPdfSelectedVisual(editor);
  1007. return true;
  1008. },
  1009. bindPdfKeyboardDelete: function (editor) {
  1010. var _this = this;
  1011. if (!editor || editor._spacePdfKeyboardDeleteBound) {
  1012. return;
  1013. }
  1014. editor._spacePdfKeyboardDeleteBound = true;
  1015. editor.editing.view.document.on("keydown", function (evt, data) {
  1016. if (data.keyCode !== 8 && data.keyCode !== 46) {
  1017. return;
  1018. }
  1019. if (_this.deleteSelectedPdf(editor)) {
  1020. evt.stop();
  1021. data.preventDefault();
  1022. }
  1023. }, { priority: "high" });
  1024. var editable = _this.getEditorEditableElement(editor);
  1025. if (editable) {
  1026. editable.addEventListener("keydown", function (event) {
  1027. if (event.keyCode !== 8 && event.keyCode !== 46) {
  1028. return;
  1029. }
  1030. if (_this.deleteSelectedPdf(editor)) {
  1031. event.stopPropagation();
  1032. event.preventDefault();
  1033. }
  1034. }, true);
  1035. }
  1036. },
  1037. bindPdfSecureControls: function (editor) {
  1038. var _this = this;
  1039. editor.editing.view.document.on("mousedown", function (evt, data) {
  1040. if (!data.domTarget) {
  1041. return;
  1042. }
  1043. if (_this.selectPdfBlockFromDom(editor, data.domTarget)) {
  1044. evt.stop();
  1045. }
  1046. }, { priority: "high" });
  1047. editor.editing.view.document.on("click", function (evt, data) {
  1048. if (!data.domTarget) {
  1049. return;
  1050. }
  1051. _this.selectPdfBlockFromDom(editor, data.domTarget);
  1052. }, { priority: "low" });
  1053. editor.model.document.selection.on("change", function () {
  1054. window.setTimeout(function () {
  1055. var selected = editor.model.document.selection.getSelectedElement();
  1056. if (selected && selected.is && selected.is("element") && selected.name === "spacePdfViewer") {
  1057. _this.activePdf = {
  1058. src: _this.normalizeEditorMediaUrl(selected.getAttribute("src") || ""),
  1059. title: selected.getAttribute("title") || "PDF文件",
  1060. secure: selected.getAttribute("secure") === "1" ? "1" : "0"
  1061. };
  1062. window.setTimeout(function () {
  1063. _this.activateLastPdfInEditor();
  1064. _this.refreshPdfSecureStatusBar();
  1065. _this.syncPdfSelectedVisual(editor);
  1066. }, 0);
  1067. } else {
  1068. _this.syncPdfSelectedVisual(editor);
  1069. }
  1070. }, 0);
  1071. });
  1072. window.addEventListener("resize", function () {
  1073. if (_this.activePdf) {
  1074. _this.activateLastPdfInEditor();
  1075. }
  1076. });
  1077. },
  1078. getUploadOptions: function () {
  1079. var _this = this;
  1080. return {
  1081. imageQuality: this.imageQuality,
  1082. imageMaxWidth: 1920,
  1083. imageMaxSize: 20 * 1024 * 1024,
  1084. videoMaxSize: 1024 * 1024 * 1024,
  1085. pdfMaxSize: 100 * 1024 * 1024,
  1086. fileMaxSize: 10 * 1024 * 1024,
  1087. onUploaded: function (url, file) {
  1088. var isImage = file && (
  1089. (file.type && file.type.indexOf("image/") === 0)
  1090. || /\.(jpg|jpeg|png|gif|bmp|webp|svg)$/i.test(file.name || "")
  1091. );
  1092. if (isImage) {
  1093. _this.rememberUploadedImageUrl(url);
  1094. }
  1095. }
  1096. };
  1097. },
  1098. rememberUploadedImageUrl: function (url) {
  1099. var src = this.normalizeEditorMediaUrl(url);
  1100. if (!src) {
  1101. return;
  1102. }
  1103. this.uploadedImageUrls.push(src);
  1104. },
  1105. myCustomUploadAdapterPlugin: function (editor) {
  1106. this.installUploadAdapter(editor);
  1107. },
  1108. installUploadAdapter: function (editor) {
  1109. var _this = this;
  1110. editor.plugins.get('FileRepository').createUploadAdapter = (loader) => {
  1111. // 第二个参数设置上传图片的地址
  1112. return new MyUploadAdapter(loader, _this.getUploadOptions());
  1113. };
  1114. },
  1115. installPdfViewerPlugin: function (editor) {
  1116. var _this = this;
  1117. editor.model.schema.register("spacePdfViewer", {
  1118. isObject: true,
  1119. allowWhere: "$block",
  1120. allowAttributes: ["src", "title", "secure"]
  1121. });
  1122. var createPdfViewerEditingView = function (modelItem, viewWriter) {
  1123. var src = modelItem.getAttribute("src") || "";
  1124. var title = modelItem.getAttribute("title") || "PDF文件";
  1125. var secure = modelItem.getAttribute("secure") || "0";
  1126. var figure = viewWriter.createContainerElement("figure", {
  1127. "class": "space-editor-pdf-viewer media",
  1128. "data-space-pdf": "true",
  1129. "data-space-pdf-src": src,
  1130. "data-space-pdf-secure": secure
  1131. });
  1132. var iframe = viewWriter.createRawElement("iframe", {
  1133. "class": "space-editor-pdf-frame",
  1134. src: secure === "1" ? "" : src,
  1135. title: title,
  1136. loading: "lazy",
  1137. frameborder: "0"
  1138. });
  1139. viewWriter.insert(viewWriter.createPositionAt(figure, 0), iframe);
  1140. if (secure !== "1") {
  1141. var caption = viewWriter.createContainerElement("figcaption");
  1142. var link = viewWriter.createContainerElement("a", {
  1143. href: src,
  1144. target: "_blank",
  1145. rel: "noopener"
  1146. });
  1147. var text = viewWriter.createText("打开 PDF:" + title);
  1148. viewWriter.insert(viewWriter.createPositionAt(link, 0), text);
  1149. viewWriter.insert(viewWriter.createPositionAt(caption, 0), link);
  1150. viewWriter.insert(viewWriter.createPositionAt(figure, "end"), caption);
  1151. }
  1152. return figure;
  1153. };
  1154. var createPdfViewerDataView = function (modelItem, viewWriter) {
  1155. var src = modelItem.getAttribute("src") || "";
  1156. var title = modelItem.getAttribute("title") || "PDF文件";
  1157. var secure = modelItem.getAttribute("secure") || "0";
  1158. var figure = viewWriter.createContainerElement("figure", {
  1159. "class": "space-editor-pdf-viewer media",
  1160. "data-space-pdf": "true",
  1161. "data-space-pdf-src": src,
  1162. "data-space-pdf-secure": secure
  1163. });
  1164. var iframe = viewWriter.createEmptyElement("iframe", {
  1165. "class": "space-editor-pdf-frame",
  1166. src: secure === "1" ? "" : src,
  1167. title: title,
  1168. loading: "lazy",
  1169. frameborder: "0"
  1170. });
  1171. viewWriter.insert(viewWriter.createPositionAt(figure, 0), iframe);
  1172. if (secure !== "1") {
  1173. var caption = viewWriter.createContainerElement("figcaption");
  1174. var link = viewWriter.createContainerElement("a", {
  1175. href: src,
  1176. target: "_blank",
  1177. rel: "noopener"
  1178. });
  1179. var text = viewWriter.createText("打开 PDF:" + title);
  1180. viewWriter.insert(viewWriter.createPositionAt(link, 0), text);
  1181. viewWriter.insert(viewWriter.createPositionAt(caption, 0), link);
  1182. viewWriter.insert(viewWriter.createPositionAt(figure, "end"), caption);
  1183. }
  1184. return figure;
  1185. };
  1186. editor.conversion.for("editingDowncast").elementToElement({
  1187. model: "spacePdfViewer",
  1188. view: function (modelItem, conversionApi) {
  1189. return createPdfViewerEditingView(modelItem, conversionApi.writer);
  1190. }
  1191. });
  1192. editor.conversion.for("dataDowncast").elementToElement({
  1193. model: "spacePdfViewer",
  1194. view: function (modelItem, conversionApi) {
  1195. return createPdfViewerDataView(modelItem, conversionApi.writer);
  1196. }
  1197. });
  1198. editor.conversion.for("upcast").elementToElement({
  1199. view: {
  1200. name: "figure",
  1201. classes: "space-editor-pdf-viewer"
  1202. },
  1203. model: function (viewElement, conversionApi) {
  1204. var src = viewElement.getAttribute("data-space-pdf-src") || "";
  1205. var secure = viewElement.getAttribute("data-space-pdf-secure") || "0";
  1206. var title = "PDF文件";
  1207. var findPdfIframe = function (element) {
  1208. if (!element || !element.is || !element.is("element")) {
  1209. return null;
  1210. }
  1211. if (element.is("element:iframe") && element.hasClass("space-editor-pdf-frame")) {
  1212. return element;
  1213. }
  1214. var child = element.getChild(0);
  1215. while (child) {
  1216. var matched = findPdfIframe(child);
  1217. if (matched) {
  1218. return matched;
  1219. }
  1220. child = child.nextSibling;
  1221. }
  1222. return null;
  1223. };
  1224. var iframe = findPdfIframe(viewElement);
  1225. if (!src && iframe) {
  1226. src = iframe.getAttribute("src") || "";
  1227. }
  1228. if (iframe && iframe.getAttribute("title")) {
  1229. title = iframe.getAttribute("title");
  1230. }
  1231. return conversionApi.writer.createElement("spacePdfViewer", {
  1232. src: src,
  1233. title: title,
  1234. secure: secure
  1235. });
  1236. },
  1237. converterPriority: "high"
  1238. });
  1239. editor.conversion.for("upcast").elementToElement({
  1240. view: {
  1241. name: "iframe",
  1242. classes: "space-editor-pdf-frame"
  1243. },
  1244. model: function (viewElement, conversionApi) {
  1245. return conversionApi.writer.createElement("spacePdfViewer", {
  1246. src: viewElement.getAttribute("src") || "",
  1247. title: viewElement.getAttribute("title") || "PDF文件",
  1248. secure: "0"
  1249. });
  1250. }
  1251. });
  1252. editor.editing.view.document.on("click", function (evt, data) {
  1253. var domTarget = data.domTarget;
  1254. if (!domTarget) {
  1255. return;
  1256. }
  1257. var toggle = domTarget.classList && domTarget.classList.contains("space-editor-pdf-secure-toggle")
  1258. ? domTarget
  1259. : (domTarget.closest ? domTarget.closest(".space-editor-pdf-secure-toggle") : null);
  1260. var switchLabel = domTarget.classList && domTarget.classList.contains("space-editor-pdf-secure-switch")
  1261. ? domTarget
  1262. : (domTarget.closest ? domTarget.closest(".space-editor-pdf-secure-switch") : null);
  1263. if (!toggle && switchLabel) {
  1264. toggle = switchLabel.querySelector(".space-editor-pdf-secure-toggle");
  1265. }
  1266. if (!toggle) {
  1267. return;
  1268. }
  1269. evt.stop();
  1270. data.preventDefault();
  1271. var figureDom = toggle.closest("figure.space-editor-pdf-viewer");
  1272. if (!figureDom) {
  1273. return;
  1274. }
  1275. var viewFigure = editor.editing.view.domConverter.mapDomToView(figureDom);
  1276. if (!viewFigure) {
  1277. return;
  1278. }
  1279. var modelElement = editor.editing.mapper.toModelElement(viewFigure);
  1280. if (!modelElement) {
  1281. return;
  1282. }
  1283. editor.model.change(function (writer) {
  1284. var current = modelElement.getAttribute("secure") || "0";
  1285. writer.setAttribute("secure", current === "1" ? "0" : "1", modelElement);
  1286. });
  1287. }, { priority: "high" });
  1288. editor.model.document.on("change:data", function () {
  1289. _this.deferEnhanceEditorPdfViewers();
  1290. });
  1291. },
  1292. installVideoViewerPlugin: function (editor) {
  1293. var inferVideoType = function (src) {
  1294. if (/\.webm(\?.*)?$/i.test(src)) {
  1295. return "video/webm";
  1296. }
  1297. if (/\.ogg|\.ogv(\?.*)?$/i.test(src)) {
  1298. return "video/ogg";
  1299. }
  1300. return "video/mp4";
  1301. };
  1302. var createVideoView = function (modelItem, viewWriter, isData) {
  1303. var src = modelItem.getAttribute("src") || "";
  1304. var title = modelItem.getAttribute("title") || "视频";
  1305. var poster = modelItem.getAttribute("poster") || "";
  1306. if (isData) {
  1307. var p = viewWriter.createContainerElement("p");
  1308. var dataAttrs = {
  1309. controls: "controls",
  1310. playsinline: "playsinline",
  1311. "webkit-playsinline": "webkit-playsinline",
  1312. preload: "metadata",
  1313. title: title,
  1314. style: "display:block;width:100%;max-width:960px;background:#000;"
  1315. };
  1316. if (poster) {
  1317. dataAttrs.poster = poster;
  1318. }
  1319. var dataVideo = viewWriter.createContainerElement("video", dataAttrs);
  1320. var source = viewWriter.createEmptyElement("source", {
  1321. src: src,
  1322. type: inferVideoType(src)
  1323. });
  1324. viewWriter.insert(viewWriter.createPositionAt(dataVideo, 0), source);
  1325. viewWriter.insert(viewWriter.createPositionAt(dataVideo, "end"), viewWriter.createText("您的浏览器暂不支持视频播放。"));
  1326. viewWriter.insert(viewWriter.createPositionAt(p, 0), dataVideo);
  1327. return p;
  1328. }
  1329. var figure = viewWriter.createContainerElement("figure", {
  1330. "class": "space-editor-video-viewer media",
  1331. "data-space-video": "true",
  1332. "data-space-video-src": src
  1333. });
  1334. var attrs = {
  1335. "class": "space-editor-video-frame",
  1336. controls: "controls",
  1337. playsinline: "playsinline",
  1338. "webkit-playsinline": "webkit-playsinline",
  1339. preload: "metadata",
  1340. src: src,
  1341. title: title,
  1342. style: "max-width:100%;width:100%;display:block;"
  1343. };
  1344. if (poster) {
  1345. attrs.poster = poster;
  1346. }
  1347. var video = viewWriter.createRawElement("video", attrs);
  1348. viewWriter.insert(viewWriter.createPositionAt(figure, 0), video);
  1349. return figure;
  1350. };
  1351. var findVideo = function (element) {
  1352. if (!element || !element.is || !element.is("element")) {
  1353. return null;
  1354. }
  1355. if (element.is("element:video")) {
  1356. return element;
  1357. }
  1358. var child = element.getChild(0);
  1359. while (child) {
  1360. var matched = findVideo(child);
  1361. if (matched) {
  1362. return matched;
  1363. }
  1364. child = child.nextSibling;
  1365. }
  1366. return null;
  1367. };
  1368. var createModelFromVideo = function (viewElement, conversionApi, fallbackSrc) {
  1369. var video = viewElement.is && viewElement.is("element:video") ? viewElement : findVideo(viewElement);
  1370. var src = fallbackSrc || viewElement.getAttribute("data-space-video-src") || "";
  1371. var title = viewElement.getAttribute("title") || "视频";
  1372. var poster = "";
  1373. if (video) {
  1374. src = src || video.getAttribute("src") || "";
  1375. var child = video.getChild(0);
  1376. while (!src && child) {
  1377. if (child.is && child.is("element:source") && child.getAttribute("src")) {
  1378. src = child.getAttribute("src");
  1379. break;
  1380. }
  1381. child = child.nextSibling;
  1382. }
  1383. title = video.getAttribute("title") || title;
  1384. poster = video.getAttribute("poster") || "";
  1385. }
  1386. return conversionApi.writer.createElement("spaceVideoViewer", {
  1387. src: src,
  1388. title: title,
  1389. poster: poster
  1390. });
  1391. };
  1392. editor.model.schema.register("spaceVideoViewer", {
  1393. isObject: true,
  1394. allowWhere: "$block",
  1395. allowAttributes: ["src", "title", "poster"]
  1396. });
  1397. editor.conversion.for("editingDowncast").elementToElement({
  1398. model: "spaceVideoViewer",
  1399. view: function (modelItem, conversionApi) {
  1400. return createVideoView(modelItem, conversionApi.writer, false);
  1401. }
  1402. });
  1403. editor.conversion.for("dataDowncast").elementToElement({
  1404. model: "spaceVideoViewer",
  1405. view: function (modelItem, conversionApi) {
  1406. return createVideoView(modelItem, conversionApi.writer, true);
  1407. }
  1408. });
  1409. editor.conversion.for("upcast").elementToElement({
  1410. view: {
  1411. name: "figure",
  1412. classes: "space-editor-video-viewer"
  1413. },
  1414. model: function (viewElement, conversionApi) {
  1415. return createModelFromVideo(viewElement, conversionApi);
  1416. },
  1417. converterPriority: "high"
  1418. });
  1419. editor.conversion.for("upcast").elementToElement({
  1420. view: {
  1421. name: "video"
  1422. },
  1423. model: function (viewElement, conversionApi) {
  1424. return createModelFromVideo(viewElement, conversionApi, viewElement.getAttribute("src") || "");
  1425. },
  1426. converterPriority: "high"
  1427. });
  1428. },
  1429. enhanceEditorPdfViewers: function () {
  1430. var _this = this;
  1431. if (this._pdfEnhancing) {
  1432. return;
  1433. }
  1434. this._pdfEnhancing = true;
  1435. try {
  1436. var editor = this.editor;
  1437. if (!editor || !editor.editing || !editor.editing.view) {
  1438. return;
  1439. }
  1440. var root = editor.editing.view.getDomRoot();
  1441. if (!root) {
  1442. return;
  1443. }
  1444. var figures = root.querySelectorAll("figure.space-editor-pdf-viewer");
  1445. for (var i = 0; i < figures.length; i++) {
  1446. var figure = figures[i];
  1447. var viewFigure = editor.editing.view.domConverter.mapDomToView(figure);
  1448. var modelElement = viewFigure ? editor.editing.mapper.toModelElement(viewFigure) : null;
  1449. var src = modelElement ? (modelElement.getAttribute("src") || "") : (figure.getAttribute("data-space-pdf-src") || "");
  1450. var secure = modelElement ? (modelElement.getAttribute("secure") || "0") : (figure.getAttribute("data-space-pdf-secure") || "0");
  1451. var iframe = figure.querySelector("iframe.space-editor-pdf-frame");
  1452. if (!iframe) {
  1453. continue;
  1454. }
  1455. iframe.setAttribute("tabindex", "-1");
  1456. if (!src) {
  1457. src = iframe.getAttribute("src") || "";
  1458. }
  1459. figure.setAttribute("data-space-pdf-src", src);
  1460. figure.setAttribute("data-space-pdf-secure", secure);
  1461. var shell = figure.querySelector(".space-editor-pdf-shell");
  1462. if (!shell) {
  1463. shell = document.createElement("div");
  1464. shell.className = "space-editor-pdf-shell";
  1465. iframe.parentNode.insertBefore(shell, iframe);
  1466. shell.appendChild(iframe);
  1467. } else if (iframe.parentNode !== shell) {
  1468. shell.appendChild(iframe);
  1469. }
  1470. var overlay = shell.querySelector(".space-editor-pdf-toolbar-overlay");
  1471. if (!overlay) {
  1472. overlay = document.createElement("div");
  1473. overlay.className = "space-editor-pdf-toolbar-overlay";
  1474. overlay.innerHTML = '<div class="space-editor-pdf-toolbar-left"><span class="space-editor-pdf-toolbar-title">PDF 预览</span></div>'
  1475. + '<div class="space-editor-pdf-toolbar-right">'
  1476. + '<label class="space-editor-pdf-secure-switch">'
  1477. + '<input type="checkbox" class="space-editor-pdf-secure-toggle">'
  1478. + '<span class="space-editor-pdf-secure-label">安全模式</span>'
  1479. + '</label>'
  1480. + '<button type="button" class="space-editor-pdf-fullscreen-btn">全屏</button>'
  1481. + '<a class="space-editor-pdf-download-original" target="_blank" rel="noopener">下载原文件</a>'
  1482. + '</div>';
  1483. shell.insertBefore(overlay, iframe);
  1484. }
  1485. var fullscreenBtn = overlay.querySelector(".space-editor-pdf-fullscreen-btn");
  1486. if (fullscreenBtn && !fullscreenBtn.getAttribute("data-bound")) {
  1487. fullscreenBtn.setAttribute("data-bound", "1");
  1488. fullscreenBtn.addEventListener("click", function (event) {
  1489. event.preventDefault();
  1490. event.stopPropagation();
  1491. var target = shell;
  1492. if (document.fullscreenElement) {
  1493. document.exitFullscreen();
  1494. return;
  1495. }
  1496. if (target && target.requestFullscreen) {
  1497. target.requestFullscreen();
  1498. }
  1499. });
  1500. }
  1501. var selectLayer = shell.querySelector(".space-editor-pdf-select-layer");
  1502. if (!selectLayer) {
  1503. selectLayer = document.createElement("div");
  1504. selectLayer.className = "space-editor-pdf-select-layer";
  1505. selectLayer.setAttribute("title", "点击选中 PDF,按 Backspace 删除");
  1506. shell.appendChild(selectLayer);
  1507. }
  1508. if (!selectLayer.getAttribute("data-bound")) {
  1509. selectLayer.setAttribute("data-bound", "1");
  1510. (function (figureDom) {
  1511. selectLayer.addEventListener("mousedown", function (event) {
  1512. event.preventDefault();
  1513. event.stopPropagation();
  1514. _this.selectPdfBlockFromDom(editor, figureDom);
  1515. });
  1516. })(figure);
  1517. }
  1518. var toggle = overlay.querySelector(".space-editor-pdf-secure-toggle");
  1519. if (toggle) {
  1520. toggle.checked = secure === "1";
  1521. }
  1522. if (toggle && !toggle.getAttribute("data-bound-change")) {
  1523. toggle.setAttribute("data-bound-change", "1");
  1524. (function (figureDom, iframeEl) {
  1525. toggle.addEventListener("change", function (event) {
  1526. event.stopPropagation();
  1527. var viewFigure = editor.editing.view.domConverter.mapDomToView(figureDom);
  1528. if (!viewFigure) {
  1529. return;
  1530. }
  1531. var modelElement = editor.editing.mapper.toModelElement(viewFigure);
  1532. if (!modelElement) {
  1533. return;
  1534. }
  1535. var nextSecure = event.target.checked ? "1" : "0";
  1536. editor.model.change(function (writer) {
  1537. writer.setAttribute("secure", nextSecure, modelElement);
  1538. });
  1539. window.setTimeout(function () {
  1540. _this.enhanceEditorPdfViewers();
  1541. }, 0);
  1542. });
  1543. })(figure, iframe);
  1544. }
  1545. var downloadLink = overlay.querySelector(".space-editor-pdf-download-original");
  1546. if (downloadLink && src) {
  1547. downloadLink.setAttribute("href", src);
  1548. }
  1549. if (secure === "1") {
  1550. _this.loadEditorSecurePdfPreview(figure, src, iframe);
  1551. } else {
  1552. _this.hideEditorPdfPreviewError(shell);
  1553. if (src && iframe.getAttribute("src") !== src) {
  1554. iframe.setAttribute("src", src);
  1555. }
  1556. }
  1557. var caption = figure.querySelector("figcaption");
  1558. if (caption) {
  1559. caption.style.display = secure === "1" ? "none" : "";
  1560. }
  1561. }
  1562. } finally {
  1563. this._pdfEnhancing = false;
  1564. }
  1565. },
  1566. uploadPlainFileByAdapter: function (file, options, onProgress) {
  1567. if (typeof MyUploadAdapter == "undefined") {
  1568. return Promise.reject("上传组件未加载完成,请刷新页面后重试");
  1569. }
  1570. if (typeof MyUploadAdapter.uploadPlainFile == "function") {
  1571. return MyUploadAdapter.uploadPlainFile(file, options, onProgress);
  1572. }
  1573. var adapter = new MyUploadAdapter(null, options || {});
  1574. if (typeof adapter.uploadPlainFile == "function") {
  1575. return adapter.uploadPlainFile(file, onProgress);
  1576. }
  1577. return Promise.reject("上传组件未加载完成,请刷新页面后重试");
  1578. },
  1579. /**
  1580. * 获取高度
  1581. */
  1582. getHeight: function () {
  1583. if (!this.height) {
  1584. if (this.size == undefined || this.size == "small") {
  1585. return '200px';
  1586. } else if (this.size == "medium") {
  1587. return '400px';
  1588. } else if (this.size == "large") {
  1589. return '600px';
  1590. }
  1591. } else if (this.height) {
  1592. if (this.height.toString().toLocaleLowerCase().indexOf('px') == -1) {
  1593. return this.height + 'px';
  1594. } else {
  1595. return this.height;
  1596. }
  1597. }
  1598. return "";
  1599. },
  1600. /**
  1601. * 设置编辑器高度
  1602. */
  1603. setEditorHeight: function () {
  1604. if (this.notLoadEditor) {
  1605. return;
  1606. }
  1607. var height = this.getHeight();
  1608. if (!this.editor || !height) {
  1609. return;
  1610. }
  1611. var _this = this;
  1612. // 设置编辑器高度
  1613. _this.editor.editing.view.change(writer => {
  1614. writer.setStyle(
  1615. "height",
  1616. height,
  1617. _this.editor.editing.view.document.getRoot()
  1618. );
  1619. });
  1620. },
  1621. /**
  1622. * 获取工具栏
  1623. */
  1624. getToolbar: function () {
  1625. var items = [];
  1626. // 是否有全屏工具
  1627. if (this.isfullscreen == false) {
  1628. // 没有全屏工具栏
  1629. items = [
  1630. 'fontfamily', 'fontsize', 'fontColor', 'fontBackgroundColor', 'blockQuote', 'bold', 'italic', 'link', '|',
  1631. 'alignment', 'horizontalLine', '|', 'indent', 'outdent', '|', 'imageUpload', 'wordUpload', 'insertTable', 'mediaEmbed', 'phrase', 'undo', 'redo'
  1632. ];
  1633. } else {
  1634. items = [
  1635. 'fontfamily', 'fontsize', 'fontColor', 'fontBackgroundColor', 'blockQuote', 'bold', 'italic', 'link', '|',
  1636. 'alignment', 'horizontalLine', '|', 'indent', 'outdent', '|', 'imageUpload', 'wordUpload', 'insertTable', 'mediaEmbed', 'phrase', 'undo', 'redo', 'fullScreen'
  1637. ];
  1638. }
  1639. var toolbar = {
  1640. items: items
  1641. };
  1642. if (!this.type) {
  1643. return toolbar;
  1644. }
  1645. var map = new Map();
  1646. map.set("flow", ['phrase']);
  1647. if (map.get(this.type)) {
  1648. return {
  1649. items: map.get(this.type)
  1650. }
  1651. }
  1652. return toolbar;
  1653. },
  1654. installFirstLineIndentPlugin: function (editor) {
  1655. if (!editor.model.schema.checkAttribute('$block', 'textIndent')) {
  1656. editor.model.schema.extend('$block', { allowAttributes: ['textIndent'] });
  1657. }
  1658. editor.conversion.attributeToAttribute({
  1659. model: { key: 'textIndent', value: '2em' },
  1660. view: { key: 'style', value: { 'text-indent': '2em' } }
  1661. });
  1662. },
  1663. getSelectedTextBlocks: function (editor, attributeName) {
  1664. var blocks = [];
  1665. var attribute = attributeName || 'textIndent';
  1666. var selection = editor.model.document.selection;
  1667. if (!selection.isCollapsed && typeof selection.getSelectedBlocks === 'function') {
  1668. blocks = Array.prototype.slice.call(selection.getSelectedBlocks());
  1669. } else {
  1670. var node = selection.getFirstPosition().parent;
  1671. while (node && (!node.is || !node.is('element') || !editor.model.schema.isBlock(node.name))) {
  1672. node = node.parent;
  1673. }
  1674. if (node && node.is('element')) {
  1675. blocks.push(node);
  1676. }
  1677. }
  1678. return blocks.filter(function (block) {
  1679. return block && editor.model.schema.checkAttribute(block.name, attribute);
  1680. });
  1681. },
  1682. toggleFirstLineIndent: function (editor) {
  1683. var blocks = this.getSelectedTextBlocks(editor);
  1684. if (!blocks.length) {
  1685. return;
  1686. }
  1687. var removeIndent = blocks.every(function (block) {
  1688. return block.getAttribute('textIndent') === '2em';
  1689. });
  1690. editor.model.change(function (writer) {
  1691. blocks.forEach(function (block) {
  1692. if (removeIndent) {
  1693. writer.removeAttribute('textIndent', block);
  1694. } else {
  1695. writer.setAttribute('textIndent', '2em', block);
  1696. }
  1697. });
  1698. });
  1699. editor.editing.view.focus();
  1700. },
  1701. refreshFirstLineIndentButton: function (editor) {
  1702. if (!editor || !editor.ui || !editor.ui.view || !editor.ui.view.element) {
  1703. return;
  1704. }
  1705. var button = editor.ui.view.element.querySelector('[data-space-first-line-indent="true"]');
  1706. if (!button) {
  1707. return;
  1708. }
  1709. var blocks = this.getSelectedTextBlocks(editor);
  1710. var active = blocks.length > 0 && blocks.every(function (block) {
  1711. return block.getAttribute('textIndent') === '2em';
  1712. });
  1713. button.classList.toggle('ck-on', active);
  1714. button.classList.toggle('ck-off', !active);
  1715. button.setAttribute('aria-pressed', active ? 'true' : 'false');
  1716. },
  1717. mountFirstLineIndentToolbarButton: function (editor) {
  1718. if (!editor || !editor.ui || !editor.ui.view || !editor.ui.view.element) {
  1719. return;
  1720. }
  1721. var toolbarItems = editor.ui.view.element.querySelector('.ck-toolbar__items');
  1722. if (!toolbarItems || toolbarItems.querySelector('[data-space-first-line-indent="true"]')) {
  1723. return;
  1724. }
  1725. var buttons = toolbarItems.querySelectorAll('.ck-button');
  1726. var templateButton = null;
  1727. var outdentButton = null;
  1728. for (var i = 0; i < buttons.length; i++) {
  1729. var label = buttons[i].getAttribute('aria-label') || buttons[i].textContent || '';
  1730. if (!templateButton && buttons[i].querySelector('svg.ck-button__icon')) {
  1731. templateButton = buttons[i];
  1732. }
  1733. if (label.indexOf('减少缩进') !== -1 || label.indexOf('减少縮排') !== -1) {
  1734. outdentButton = buttons[i];
  1735. if (!templateButton) {
  1736. templateButton = buttons[i];
  1737. }
  1738. }
  1739. }
  1740. if (!templateButton) {
  1741. return;
  1742. }
  1743. var button = templateButton.cloneNode(true);
  1744. button.removeAttribute('aria-disabled');
  1745. button.removeAttribute('aria-labelledby');
  1746. button.removeAttribute('aria-haspopup');
  1747. button.setAttribute('aria-label', '首行缩进两字符');
  1748. button.setAttribute('aria-pressed', 'false');
  1749. button.setAttribute('title', '首行缩进两字符');
  1750. button.setAttribute('data-space-first-line-indent', 'true');
  1751. button.classList.remove('ck-disabled', 'ck-on');
  1752. button.classList.add('ck-off');
  1753. button.tabIndex = 0;
  1754. var tooltipText = button.querySelector('.ck-tooltip__text');
  1755. if (tooltipText) {
  1756. tooltipText.textContent = '首行缩进两字符';
  1757. }
  1758. var buttonLabel = button.querySelector('.ck-button__label');
  1759. if (buttonLabel) {
  1760. buttonLabel.textContent = '首行缩进两字符';
  1761. }
  1762. var _this = this;
  1763. button.addEventListener('click', function (event) {
  1764. event.preventDefault();
  1765. event.stopPropagation();
  1766. _this.toggleFirstLineIndent(editor);
  1767. });
  1768. var referenceButton = outdentButton || templateButton;
  1769. if (referenceButton && referenceButton.parentNode === toolbarItems) {
  1770. toolbarItems.insertBefore(button, referenceButton.nextSibling);
  1771. } else {
  1772. toolbarItems.appendChild(button);
  1773. }
  1774. editor.model.document.selection.on('change', function () {
  1775. _this.refreshFirstLineIndentButton(editor);
  1776. });
  1777. editor.model.document.on('change:data', function () {
  1778. _this.refreshFirstLineIndentButton(editor);
  1779. });
  1780. this.refreshFirstLineIndentButton(editor);
  1781. },
  1782. installLineHeightPlugin: function (editor) {
  1783. if (!editor.model.schema.checkAttribute('$block', 'lineHeight')) {
  1784. editor.model.schema.extend('$block', { allowAttributes: ['lineHeight'] });
  1785. }
  1786. editor.model.schema.setAttributeProperties('lineHeight', { isFormatting: true });
  1787. editor.conversion.for('downcast').attributeToAttribute({
  1788. model: 'lineHeight',
  1789. view: function (modelAttributeValue) {
  1790. return {
  1791. key: 'style',
  1792. value: { 'line-height': modelAttributeValue }
  1793. };
  1794. }
  1795. });
  1796. editor.conversion.for('upcast').attributeToAttribute({
  1797. view: {
  1798. styles: { 'line-height': /[\s\S]+/ }
  1799. },
  1800. model: {
  1801. key: 'lineHeight',
  1802. value: function (viewElement) {
  1803. return viewElement.getStyle('line-height');
  1804. }
  1805. }
  1806. });
  1807. },
  1808. applyLineHeight: function (editor, value) {
  1809. var blocks = this.getSelectedTextBlocks(editor, 'lineHeight');
  1810. if (!blocks.length) {
  1811. return;
  1812. }
  1813. editor.model.change(function (writer) {
  1814. blocks.forEach(function (block) {
  1815. if (value) {
  1816. writer.setAttribute('lineHeight', value, block);
  1817. } else {
  1818. writer.removeAttribute('lineHeight', block);
  1819. }
  1820. });
  1821. });
  1822. editor.editing.view.focus();
  1823. },
  1824. refreshLineHeightControl: function (editor) {
  1825. if (!editor || !editor.ui || !editor.ui.view || !editor.ui.view.element) {
  1826. return;
  1827. }
  1828. var control = editor.ui.view.element.querySelector('[data-space-line-height="true"]');
  1829. if (!control) {
  1830. return;
  1831. }
  1832. var blocks = this.getSelectedTextBlocks(editor, 'lineHeight');
  1833. var current = '';
  1834. if (blocks.length) {
  1835. current = blocks[0].getAttribute('lineHeight') || '';
  1836. for (var i = 1; i < blocks.length; i++) {
  1837. if ((blocks[i].getAttribute('lineHeight') || '') !== current) {
  1838. current = '';
  1839. break;
  1840. }
  1841. }
  1842. }
  1843. control.value = current;
  1844. },
  1845. mountLineHeightToolbar: function (editor) {
  1846. if (!editor || !editor.ui || !editor.ui.view || !editor.ui.view.element) {
  1847. return;
  1848. }
  1849. var toolbarItems = editor.ui.view.element.querySelector('.ck-toolbar__items');
  1850. if (!toolbarItems || toolbarItems.querySelector('[data-space-line-height="true"]')) {
  1851. return;
  1852. }
  1853. var _this = this;
  1854. var wrapper = document.createElement('label');
  1855. wrapper.className = 'space-editor-line-height';
  1856. wrapper.setAttribute('title', '行距');
  1857. var label = document.createElement('span');
  1858. label.className = 'space-editor-line-height-label';
  1859. label.textContent = '行距';
  1860. var select = document.createElement('select');
  1861. select.className = 'space-editor-line-height-select';
  1862. select.setAttribute('aria-label', '行距');
  1863. select.setAttribute('data-space-line-height', 'true');
  1864. [
  1865. ['', '默认'],
  1866. ['1', '1.0 倍'],
  1867. ['1.25', '1.25 倍'],
  1868. ['1.5', '1.5 倍'],
  1869. ['1.75', '1.75 倍'],
  1870. ['1.8', '1.8 倍'],
  1871. ['2', '2.0 倍'],
  1872. ['2.5', '2.5 倍'],
  1873. ['3', '3.0 倍']
  1874. ].forEach(function (item) {
  1875. var option = document.createElement('option');
  1876. option.value = item[0];
  1877. option.textContent = item[1];
  1878. select.appendChild(option);
  1879. });
  1880. wrapper.appendChild(label);
  1881. wrapper.appendChild(select);
  1882. wrapper.addEventListener('mousedown', function (event) {
  1883. event.stopPropagation();
  1884. });
  1885. wrapper.addEventListener('click', function (event) {
  1886. event.stopPropagation();
  1887. });
  1888. select.addEventListener('change', function (event) {
  1889. event.stopPropagation();
  1890. _this.applyLineHeight(editor, select.value);
  1891. });
  1892. var fontSizeDropdown = null;
  1893. var dropdowns = toolbarItems.querySelectorAll('.ck-dropdown');
  1894. for (var i = 0; i < dropdowns.length; i++) {
  1895. var button = dropdowns[i].querySelector('.ck-button');
  1896. var buttonLabel = button ? (button.getAttribute('aria-label') || button.getAttribute('title') || button.textContent || '') : '';
  1897. buttonLabel = buttonLabel.replace(/\s/g, '').toLowerCase();
  1898. if (buttonLabel.indexOf('字体大小') !== -1 || buttonLabel.indexOf('字号') !== -1 || buttonLabel.indexOf('fontsize') !== -1) {
  1899. fontSizeDropdown = dropdowns[i];
  1900. break;
  1901. }
  1902. }
  1903. if (fontSizeDropdown && fontSizeDropdown.parentNode === toolbarItems) {
  1904. toolbarItems.insertBefore(wrapper, fontSizeDropdown.nextSibling);
  1905. } else {
  1906. toolbarItems.appendChild(wrapper);
  1907. }
  1908. editor.model.document.selection.on('change', function () {
  1909. _this.refreshLineHeightControl(editor);
  1910. });
  1911. editor.model.document.on('change:data', function () {
  1912. _this.refreshLineHeightControl(editor);
  1913. });
  1914. this.refreshLineHeightControl(editor);
  1915. },
  1916. mountAttachmentToolbarButton: function (editor) {
  1917. if (!editor || !editor.ui || !editor.ui.view || !editor.ui.view.element) {
  1918. return;
  1919. }
  1920. var toolbarItems = editor.ui.view.element.querySelector('.ck-toolbar__items');
  1921. if (!toolbarItems || toolbarItems.querySelector('[data-space-attachment="true"]')) {
  1922. return;
  1923. }
  1924. var phraseButton = null;
  1925. var buttons = toolbarItems.querySelectorAll('.ck-button');
  1926. for (var i = 0; i < buttons.length; i++) {
  1927. var label = (buttons[i].getAttribute('aria-label') || buttons[i].getAttribute('title') || buttons[i].textContent || '').replace(/\s/g, '');
  1928. if (label.indexOf('常用语') !== -1) {
  1929. phraseButton = buttons[i];
  1930. break;
  1931. }
  1932. }
  1933. if (!phraseButton) {
  1934. return;
  1935. }
  1936. var button = phraseButton.cloneNode(true);
  1937. button.removeAttribute('aria-haspopup');
  1938. button.removeAttribute('aria-controls');
  1939. button.removeAttribute('aria-expanded');
  1940. button.removeAttribute('aria-disabled');
  1941. button.removeAttribute('aria-labelledby');
  1942. button.removeAttribute('data-cke-tooltip-text');
  1943. button.classList.remove('ck-dropdown__button', 'ck-disabled', 'ck-on');
  1944. button.classList.add('ck-off');
  1945. button.setAttribute('aria-label', '附件');
  1946. button.setAttribute('title', '附件');
  1947. button.setAttribute('data-space-attachment', 'true');
  1948. button.tabIndex = 0;
  1949. var buttonLabel = button.querySelector('.ck-button__label');
  1950. if (buttonLabel) {
  1951. buttonLabel.textContent = '附件';
  1952. }
  1953. var arrow = button.querySelector('.ck-dropdown__arrow');
  1954. if (arrow) {
  1955. arrow.remove();
  1956. }
  1957. var _this = this;
  1958. button.addEventListener('click', function (event) {
  1959. event.preventDefault();
  1960. event.stopPropagation();
  1961. _this.openAttachmentPicker();
  1962. });
  1963. var anchor = phraseButton;
  1964. while (anchor && anchor.parentNode && anchor.parentNode !== toolbarItems) {
  1965. anchor = anchor.parentNode;
  1966. }
  1967. if (anchor && anchor.parentNode === toolbarItems) {
  1968. toolbarItems.insertBefore(button, anchor.nextSibling);
  1969. } else {
  1970. toolbarItems.appendChild(button);
  1971. }
  1972. },
  1973. alignFullScreenToolbarButton: function () {
  1974. if (!this.editor || !this.editor.ui || !this.editor.ui.view || !this.editor.ui.view.element) {
  1975. return;
  1976. }
  1977. var toolbarItems = this.editor.ui.view.element.querySelector(".ck-toolbar__items");
  1978. if (!toolbarItems) {
  1979. return;
  1980. }
  1981. var buttons = toolbarItems.querySelectorAll(".ck-button");
  1982. for (var i = 0; i < buttons.length; i++) {
  1983. var label = (buttons[i].getAttribute("aria-label") || buttons[i].getAttribute("title") || buttons[i].textContent || "").replace(/\s/g, "");
  1984. if (label.indexOf("全屏") != -1) {
  1985. buttons[i].style.marginLeft = "auto";
  1986. toolbarItems.appendChild(buttons[i]);
  1987. return;
  1988. }
  1989. }
  1990. },
  1991. mountVideoUploadToolbarButton: function (retryCount) {
  1992. if (!this.editor || !this.editor.ui || !this.editor.ui.view || !this.editor.ui.view.element) {
  1993. return;
  1994. }
  1995. var toolbarItems = this.editor.ui.view.element.querySelector(".ck-toolbar__items");
  1996. if (!toolbarItems) {
  1997. return;
  1998. }
  1999. if (toolbarItems.querySelector(".space-editor-video-upload-ck-button")) {
  2000. return;
  2001. }
  2002. var dropdowns = toolbarItems.querySelectorAll(".ck-dropdown");
  2003. var mediaDropdown = null;
  2004. for (var i = 0; i < dropdowns.length; i++) {
  2005. var button = dropdowns[i].querySelector(".ck-button");
  2006. var label = button ? (button.getAttribute("aria-label") || button.getAttribute("title") || button.textContent || "") : "";
  2007. label = label.replace(/\s/g, "").toLowerCase();
  2008. if (label.indexOf("媒体") != -1 || label.indexOf("media") != -1) {
  2009. mediaDropdown = dropdowns[i];
  2010. break;
  2011. }
  2012. }
  2013. if (!mediaDropdown) {
  2014. if ((retryCount || 0) < 3) {
  2015. var _this = this;
  2016. setTimeout(function () {
  2017. _this.mountVideoUploadToolbarButton((retryCount || 0) + 1);
  2018. }, 200);
  2019. }
  2020. return;
  2021. }
  2022. var _this = this;
  2023. var videoButton = document.createElement("button");
  2024. videoButton.type = "button";
  2025. videoButton.className = "ck ck-button ck-off space-editor-video-upload-ck-button";
  2026. videoButton.setAttribute("aria-label", "上传视频");
  2027. videoButton.setAttribute("title", "上传视频");
  2028. videoButton.innerHTML = '<svg class="ck ck-icon ck-button__icon space-editor-video-upload-icon" viewBox="0 0 20 20" aria-hidden="true"><path d="M3.2 5.4c-.9 0-1.6.7-1.6 1.6v6.2c0 .9.7 1.6 1.6 1.6h8.2c.9 0 1.6-.7 1.6-1.6V7c0-.9-.7-1.6-1.6-1.6H3.2zm.2 1.8h7.8V13H3.4V7.2z"></path><path d="M13.9 8.2l2.9-2c.7-.5 1.6 0 1.6.9v6c0 .8-.9 1.3-1.6.9l-2.9-2V8.2z"></path><path d="M7.6 12.2h1.8V9.3l1.1 1.1 1.2-1.2-3.2-3-3.2 3 1.2 1.2 1.1-1.1v2.9z"></path></svg><span class="ck ck-button__label">上传视频</span>';
  2029. videoButton.addEventListener("click", function (event) {
  2030. event.preventDefault();
  2031. event.stopPropagation();
  2032. _this.openVideoPicker();
  2033. });
  2034. mediaDropdown.classList.add("space-editor-media-link-dropdown");
  2035. mediaDropdown.parentNode.insertBefore(videoButton, mediaDropdown);
  2036. },
  2037. mountPdfUploadToolbarButton: function (retryCount) {
  2038. if (!this.editor || !this.editor.ui || !this.editor.ui.view || !this.editor.ui.view.element) {
  2039. return;
  2040. }
  2041. var toolbarItems = this.editor.ui.view.element.querySelector(".ck-toolbar__items");
  2042. if (!toolbarItems) {
  2043. return;
  2044. }
  2045. if (toolbarItems.querySelector(".space-editor-pdf-upload-ck-button")) {
  2046. return;
  2047. }
  2048. var dropdowns = toolbarItems.querySelectorAll(".ck-dropdown");
  2049. var mediaDropdown = null;
  2050. for (var i = 0; i < dropdowns.length; i++) {
  2051. var button = dropdowns[i].querySelector(".ck-button");
  2052. var label = button ? (button.getAttribute("aria-label") || button.getAttribute("title") || button.textContent || "") : "";
  2053. label = label.replace(/\s/g, "").toLowerCase();
  2054. if (label.indexOf("媒体") != -1 || label.indexOf("media") != -1) {
  2055. mediaDropdown = dropdowns[i];
  2056. break;
  2057. }
  2058. }
  2059. if (!mediaDropdown) {
  2060. if ((retryCount || 0) < 3) {
  2061. var _this = this;
  2062. setTimeout(function () {
  2063. _this.mountPdfUploadToolbarButton((retryCount || 0) + 1);
  2064. }, 200);
  2065. }
  2066. return;
  2067. }
  2068. var _this = this;
  2069. var pdfButton = document.createElement("button");
  2070. pdfButton.type = "button";
  2071. pdfButton.className = "ck ck-button ck-off space-editor-upload-ck-button space-editor-pdf-upload-ck-button";
  2072. pdfButton.setAttribute("aria-label", "上传PDF");
  2073. pdfButton.setAttribute("title", "上传PDF");
  2074. pdfButton.innerHTML = '<svg class="ck ck-icon ck-button__icon space-editor-pdf-upload-icon" viewBox="0 0 20 20" aria-hidden="true"><path d="M4 1.8h7.2L16 6.6v11.6H4V1.8zm7.6 1.9v3.5h3.5L11.6 3.7zM6 9.4h8v1.4H6V9.4zm0 2.7h8v1.4H6v-1.4zm0 2.7h5.2v1.4H6v-1.4z"></path><path d="M7.1 6.9h1.3c.8 0 1.3-.4 1.3-1.1 0-.7-.5-1.1-1.3-1.1H6v3.9h1.1V6.9zm0-.8v-.6h1.1c.2 0 .4.1.4.3 0 .2-.1.3-.4.3H7.1z"></path></svg><span class="ck ck-button__label">上传PDF</span>';
  2075. pdfButton.addEventListener("click", function (event) {
  2076. event.preventDefault();
  2077. event.stopPropagation();
  2078. _this.openPdfPicker();
  2079. });
  2080. mediaDropdown.classList.add("space-editor-media-link-dropdown");
  2081. mediaDropdown.parentNode.insertBefore(pdfButton, mediaDropdown);
  2082. },
  2083. mountPdfSecureStatusBar: function (retryCount) {
  2084. if (!this.editor || !this.editor.ui || !this.editor.ui.view || !this.editor.ui.view.element) {
  2085. return;
  2086. }
  2087. var editorEl = this.editor.ui.view.element;
  2088. if (editorEl.querySelector(".space-editor-pdf-ck-secure-bar")) {
  2089. this.refreshPdfSecureStatusBar();
  2090. return;
  2091. }
  2092. var toolbar = editorEl.querySelector(".ck-toolbar");
  2093. if (!toolbar) {
  2094. if ((retryCount || 0) < 5) {
  2095. var _this = this;
  2096. setTimeout(function () {
  2097. _this.mountPdfSecureStatusBar((retryCount || 0) + 1);
  2098. }, 200);
  2099. }
  2100. return;
  2101. }
  2102. var _this = this;
  2103. var bar = document.createElement("div");
  2104. bar.className = "space-editor-pdf-ck-secure-bar";
  2105. bar.style.display = "none";
  2106. bar.innerHTML = '<div class="space-editor-pdf-ck-secure-bar-left">'
  2107. + '<span class="space-editor-pdf-ck-secure-title">PDF</span>'
  2108. + '<span class="space-editor-pdf-ck-secure-name"></span>'
  2109. + '</div>'
  2110. + '<div class="space-editor-pdf-ck-secure-bar-right">'
  2111. + '<label class="space-editor-pdf-secure-switch">'
  2112. + '<input type="checkbox" class="space-editor-pdf-secure-toggle space-editor-pdf-ck-secure-toggle">'
  2113. + '<span class="space-editor-pdf-secure-label">PDF 安全模式</span>'
  2114. + '</label>'
  2115. + '<a class="space-editor-pdf-download-original space-editor-pdf-ck-download" target="_blank" rel="noopener">下载原文件</a>'
  2116. + '</div>';
  2117. toolbar.parentNode.insertBefore(bar, toolbar.nextSibling);
  2118. var toggle = bar.querySelector(".space-editor-pdf-ck-secure-toggle");
  2119. toggle.addEventListener("change", function (event) {
  2120. event.stopPropagation();
  2121. _this.applyActivePdfSecure(event.target.checked ? "1" : "0");
  2122. });
  2123. bar.addEventListener("click", function (event) {
  2124. event.stopPropagation();
  2125. });
  2126. this.refreshPdfSecureStatusBar();
  2127. },
  2128. refreshPdfSecureStatusBar: function () {
  2129. if (!this.editor || !this.editor.ui || !this.editor.ui.view || !this.editor.ui.view.element) {
  2130. return;
  2131. }
  2132. var bar = this.editor.ui.view.element.querySelector(".space-editor-pdf-ck-secure-bar");
  2133. if (!bar) {
  2134. return;
  2135. }
  2136. var activePdf = this.activePdf;
  2137. if (!activePdf || !activePdf.src) {
  2138. bar.style.display = "none";
  2139. return;
  2140. }
  2141. bar.style.display = "flex";
  2142. var nameEl = bar.querySelector(".space-editor-pdf-ck-secure-name");
  2143. if (nameEl) {
  2144. nameEl.textContent = activePdf.title || "PDF文件";
  2145. }
  2146. var toggle = bar.querySelector(".space-editor-pdf-ck-secure-toggle");
  2147. if (toggle) {
  2148. toggle.checked = activePdf.secure === "1";
  2149. }
  2150. var downloadLink = bar.querySelector(".space-editor-pdf-ck-download");
  2151. if (downloadLink) {
  2152. downloadLink.setAttribute("href", activePdf.src);
  2153. }
  2154. },
  2155. resolveEditorWebsiteId: function () {
  2156. if (window.__ZQ_GUEST_GATE__ && window.__ZQ_GUEST_GATE__.websiteId) {
  2157. return String(window.__ZQ_GUEST_GATE__.websiteId);
  2158. }
  2159. if (this.previewdata && this.previewdata.websiteid) {
  2160. return String(this.previewdata.websiteid);
  2161. }
  2162. return "";
  2163. },
  2164. showEditorPdfPreviewError: function (shell, message) {
  2165. if (!shell) {
  2166. return;
  2167. }
  2168. var errEl = shell.querySelector(".space-editor-pdf-preview-error");
  2169. if (!errEl) {
  2170. errEl = document.createElement("div");
  2171. errEl.className = "space-editor-pdf-preview-error";
  2172. shell.appendChild(errEl);
  2173. }
  2174. errEl.textContent = message || "安全模式预览加载失败";
  2175. errEl.style.display = "flex";
  2176. },
  2177. hideEditorPdfPreviewError: function (shell) {
  2178. if (!shell) {
  2179. return;
  2180. }
  2181. var errEl = shell.querySelector(".space-editor-pdf-preview-error");
  2182. if (errEl) {
  2183. errEl.style.display = "none";
  2184. }
  2185. },
  2186. loadEditorSecurePdfPreview: function (figure, src, iframe) {
  2187. if (!figure || !src || !iframe) {
  2188. return;
  2189. }
  2190. var normalizedSrc = this.normalizeEditorMediaUrl(src);
  2191. if (!normalizedSrc || normalizedSrc.indexOf("/web/upload/") !== 0 || !/\.pdf$/i.test(normalizedSrc)) {
  2192. var shell = figure.querySelector(".space-editor-pdf-shell");
  2193. this.showEditorPdfPreviewError(shell, "PDF 路径无效,无法开启安全模式预览");
  2194. return;
  2195. }
  2196. var previewKey = normalizedSrc;
  2197. var currentSrc = iframe.getAttribute("src") || "";
  2198. if (figure.getAttribute("data-space-pdf-preview-key") === previewKey
  2199. && currentSrc.indexOf("/apps/space/pdf/secure-viewer.html") !== -1
  2200. && figure.getAttribute("data-space-pdf-preview-error") !== "1") {
  2201. return;
  2202. }
  2203. var shell = figure.querySelector(".space-editor-pdf-shell");
  2204. this.hideEditorPdfPreviewError(shell);
  2205. figure.setAttribute("data-space-pdf-preview-key", previewKey);
  2206. figure.removeAttribute("data-space-pdf-preview-error");
  2207. var tokenUrl = "/website/secure-pdf/token/?file=" + encodeURIComponent(normalizedSrc);
  2208. var viewerBase = "/apps/space/pdf/secure-viewer.html?v=20260709-pdf-secure10";
  2209. var websiteId = this.resolveEditorWebsiteId();
  2210. fetch(tokenUrl, { credentials: "same-origin" })
  2211. .then(function (res) { return res.json(); })
  2212. .then(function (payload) {
  2213. if (!payload || payload.code !== "success" || !payload.data || !payload.data.token) {
  2214. var msg = payload && payload.msg ? payload.msg : "token failed";
  2215. throw new Error(msg);
  2216. }
  2217. var viewerUrl = viewerBase + "&token=" + encodeURIComponent(payload.data.token);
  2218. if (websiteId) {
  2219. viewerUrl += "&websiteid=" + encodeURIComponent(websiteId);
  2220. }
  2221. iframe.setAttribute("src", viewerUrl);
  2222. figure.removeAttribute("data-space-pdf-preview-error");
  2223. })
  2224. .catch(function (err) {
  2225. figure.setAttribute("data-space-pdf-preview-error", "1");
  2226. figure.removeAttribute("data-space-pdf-preview-key");
  2227. iframe.removeAttribute("src");
  2228. var errMsg = "安全模式预览加载失败";
  2229. if (err && err.message && err.message !== "token failed") {
  2230. errMsg += ":" + err.message;
  2231. }
  2232. this.showEditorPdfPreviewError(shell, errMsg);
  2233. }.bind(this));
  2234. },
  2235. formatContent: function () {
  2236. if (!this.editor) {
  2237. return;
  2238. }
  2239. var html = this.editor.getData();
  2240. if (space.utils.isNull(html)) {
  2241. space.message.warning("正文内容为空");
  2242. return;
  2243. }
  2244. var wrapper = document.createElement("div");
  2245. wrapper.innerHTML = html;
  2246. var all = wrapper.querySelectorAll("*");
  2247. for (var i = 0; i < all.length; i++) {
  2248. var node = all[i];
  2249. node.removeAttribute("lang");
  2250. node.removeAttribute("width");
  2251. node.removeAttribute("height");
  2252. node.removeAttribute("onload");
  2253. node.removeAttribute("border");
  2254. node.removeAttribute("vspace");
  2255. node.removeAttribute("hspace");
  2256. var style = node.getAttribute("style") || "";
  2257. if (/mso-|font-family|text-indent:\s*0|background:\s*transparent/i.test(style)) {
  2258. node.removeAttribute("style");
  2259. }
  2260. }
  2261. var inlineNodes = wrapper.querySelectorAll("span, font");
  2262. for (var s = inlineNodes.length - 1; s >= 0; s--) {
  2263. var inlineNode = inlineNodes[s];
  2264. if (inlineNode.attributes.length == 0 && inlineNode.parentNode) {
  2265. while (inlineNode.firstChild) {
  2266. inlineNode.parentNode.insertBefore(inlineNode.firstChild, inlineNode);
  2267. }
  2268. inlineNode.parentNode.removeChild(inlineNode);
  2269. }
  2270. }
  2271. var emptyBlocks = wrapper.querySelectorAll("p, div");
  2272. for (var e = emptyBlocks.length - 1; e >= 0; e--) {
  2273. var block = emptyBlocks[e];
  2274. var hasMedia = block.querySelector("img, video, iframe, object, embed, table, .space-editor-pdf-viewer, .space-editor-video-viewer");
  2275. var text = (block.textContent || "").replace(/\u00a0/g, "").trim();
  2276. if (!hasMedia && text == "" && block.parentNode) {
  2277. block.parentNode.removeChild(block);
  2278. }
  2279. }
  2280. var headings = wrapper.querySelectorAll("h1, h2, h3, h4, h5, h6");
  2281. for (var headingIndex = 0; headingIndex < headings.length; headingIndex++) {
  2282. headings[headingIndex].style.textAlign = "center";
  2283. headings[headingIndex].style.textIndent = "0";
  2284. }
  2285. var findFirstTextNode = function (node) {
  2286. for (var child = node.firstChild; child; child = child.nextSibling) {
  2287. if (child.nodeType == 3 && child.nodeValue.replace(/[\s\u00a0\u3000]/g, "") != "") {
  2288. return child;
  2289. }
  2290. if (child.nodeType == 1 && !/^(img|video|iframe|object|embed|table)$/i.test(child.tagName)) {
  2291. var textNode = findFirstTextNode(child);
  2292. if (textNode) {
  2293. return textNode;
  2294. }
  2295. }
  2296. }
  2297. return null;
  2298. };
  2299. var trimFirstTextIndent = function (node) {
  2300. var textNode = findFirstTextNode(node);
  2301. if (textNode) {
  2302. textNode.nodeValue = textNode.nodeValue.replace(/^[\s\u00a0\u3000]+/, "");
  2303. }
  2304. };
  2305. var textBlocks = wrapper.querySelectorAll("p, div");
  2306. for (var blockIndex = 0; blockIndex < textBlocks.length; blockIndex++) {
  2307. var textBlock = textBlocks[blockIndex];
  2308. var blockHasMedia = textBlock.querySelector("img, video, iframe, object, embed, table, .space-editor-pdf-viewer, .space-editor-video-viewer");
  2309. var blockText = (textBlock.textContent || "").replace(/\u00a0/g, "").trim();
  2310. if (blockHasMedia) {
  2311. textBlock.style.textAlign = "left";
  2312. textBlock.style.textIndent = "0";
  2313. } else if (blockText != "") {
  2314. textBlock.style.textAlign = "justify";
  2315. textBlock.style.textIndent = "2em";
  2316. textBlock.style.lineHeight = "1.75";
  2317. trimFirstTextIndent(textBlock);
  2318. }
  2319. }
  2320. var images = wrapper.querySelectorAll("img");
  2321. for (var imgIndex = 0; imgIndex < images.length; imgIndex++) {
  2322. images[imgIndex].style.width = "100%";
  2323. images[imgIndex].style.maxWidth = "100%";
  2324. images[imgIndex].style.height = "auto";
  2325. images[imgIndex].style.display = "block";
  2326. images[imgIndex].style.margin = "18px 0";
  2327. }
  2328. var figures = wrapper.querySelectorAll("figure.image, figure");
  2329. for (var figureIndex = 0; figureIndex < figures.length; figureIndex++) {
  2330. var figure = figures[figureIndex];
  2331. if (!figure.querySelector("img")) {
  2332. continue;
  2333. }
  2334. figure.removeAttribute("width");
  2335. figure.removeAttribute("height");
  2336. figure.style.display = "block";
  2337. figure.style.width = "100%";
  2338. figure.style.maxWidth = "100%";
  2339. figure.style.margin = "18px 0";
  2340. figure.style.textAlign = "left";
  2341. }
  2342. var videos = wrapper.querySelectorAll("video, iframe, object, embed");
  2343. for (var v = 0; v < videos.length; v++) {
  2344. videos[v].style.width = "100%";
  2345. videos[v].style.maxWidth = "100%";
  2346. if (videos[v].tagName.toLowerCase() == "video") {
  2347. videos[v].setAttribute("controls", "controls");
  2348. videos[v].setAttribute("playsinline", "playsinline");
  2349. videos[v].style.display = "block";
  2350. videos[v].style.margin = "18px 0";
  2351. }
  2352. }
  2353. var videoFigures = wrapper.querySelectorAll("figure.space-editor-video-viewer");
  2354. for (var vf = 0; vf < videoFigures.length; vf++) {
  2355. videoFigures[vf].style.width = "100%";
  2356. videoFigures[vf].style.maxWidth = "100%";
  2357. videoFigures[vf].style.margin = "18px 0";
  2358. videoFigures[vf].style.textAlign = "center";
  2359. }
  2360. var tables = wrapper.querySelectorAll("table");
  2361. for (var t = 0; t < tables.length; t++) {
  2362. tables[t].style.width = "100%";
  2363. tables[t].style.borderCollapse = "collapse";
  2364. }
  2365. this.editor.setData(wrapper.innerHTML);
  2366. this.$emit("input", this.getEditorSaveHtml());
  2367. this.deferSyncEditorPlayableVideos();
  2368. space.message.success("正文已完成排版整理");
  2369. },
  2370. configureWordUploadPlugin: function (editor) {
  2371. if (!editor || !editor.plugins) {
  2372. return;
  2373. }
  2374. var wordUi = null;
  2375. try {
  2376. wordUi = editor.plugins.get('WordUploadUi');
  2377. } catch (error) {
  2378. for (var entry of editor.plugins) {
  2379. var plugin = Array.isArray(entry) ? entry[1] : entry;
  2380. if (plugin && typeof plugin.importWordFile === 'function') {
  2381. wordUi = plugin;
  2382. break;
  2383. }
  2384. }
  2385. }
  2386. if (!wordUi || wordUi.spaceFormatOverride) {
  2387. return;
  2388. }
  2389. var _this = this;
  2390. wordUi.spaceFormatOverride = true;
  2391. wordUi.importWordFile = function (targetEditor, file) {
  2392. return _this.importFormattedWordFile(targetEditor, file, wordUi);
  2393. };
  2394. },
  2395. importFormattedWordFile: function (editor, file, wordUi) {
  2396. if (!file) {
  2397. return;
  2398. }
  2399. var fileName = (file.name || '').toLowerCase();
  2400. if (!/\.(doc|docx)$/.test(fileName)) {
  2401. wordUi.showMessage('error', '请选择 .doc 或 .docx 格式的 Word 文件。');
  2402. return;
  2403. }
  2404. wordUi.showLoading();
  2405. this.uploadStatus = '正在导入 Word 文档…';
  2406. return this.convertWordWithServer(file)
  2407. .catch(function (error) {
  2408. if (!/\.docx$/.test(fileName)) {
  2409. throw new Error('旧版 .doc 转换失败,请在 Word 中另存为 .docx 后再导入。');
  2410. }
  2411. console.warn('LibreOffice Word conversion unavailable, fallback to mammoth:', error);
  2412. return this.convertWordWithMammoth(file, wordUi);
  2413. }.bind(this))
  2414. .then(function (result) {
  2415. var htmlContent = this.normalizeImportedWordHtml(wordUi, result.html);
  2416. if (!htmlContent) {
  2417. throw new Error('没有读取到可导入的正文内容。');
  2418. }
  2419. this.insertFormattedWordHtml(editor, htmlContent);
  2420. if (result.messages && result.messages.length) {
  2421. wordUi.showMessage('warning', 'Word 已导入,少量复杂格式可能需要人工检查。');
  2422. } else {
  2423. wordUi.showMessage('success', 'Word 文件已导入正文,原有段落格式已尽量保留;未指定格式的段落使用仿宋_GB2312、20pt、首行缩进2字符、1.75倍行距。');
  2424. }
  2425. }.bind(this))
  2426. .catch(function (error) {
  2427. console.error(error);
  2428. wordUi.showMessage('error', error && error.message ? error.message : 'Word 文件导入失败,请确认文件未损坏。');
  2429. })
  2430. .finally(function () {
  2431. this.uploadStatus = '';
  2432. wordUi.closeLoading();
  2433. }.bind(this));
  2434. },
  2435. convertWordWithMammoth: function (file, wordUi) {
  2436. return wordUi.loadMammoth()
  2437. .then(function () { return wordUi.readFileAsArrayBuffer(file); })
  2438. .then(function (arrayBuffer) {
  2439. return window.mammoth.convertToHtml({ arrayBuffer: arrayBuffer }, {
  2440. convertImage: window.mammoth.images.imgElement(function (image) {
  2441. return image.read('base64').then(function (imageBuffer) {
  2442. return { src: 'data:' + image.contentType + ';base64,' + imageBuffer };
  2443. });
  2444. }),
  2445. styleMap: [
  2446. "p[style-name='Title'] => h1:fresh",
  2447. "p[style-name='Subtitle'] => p.subtitle:fresh",
  2448. "p[style-name='标题'] => h2:fresh",
  2449. "p[style-name='标题 1'] => h2:fresh",
  2450. "p[style-name='标题 2'] => h3:fresh",
  2451. "p[style-name='标题 3'] => h4:fresh",
  2452. "p[style-name='标题 4'] => h5:fresh",
  2453. "p[style-name='Heading 1'] => h2:fresh",
  2454. "p[style-name='Heading 2'] => h3:fresh",
  2455. "p[style-name='Heading 3'] => h4:fresh",
  2456. "p[style-name='Heading 4'] => h5:fresh",
  2457. "p[style-name='正文'] => p:fresh",
  2458. "p[style-name='Normal'] => p:fresh",
  2459. "p[style-name='Body Text'] => p:fresh",
  2460. "p[style-name='Quote'] => blockquote:fresh",
  2461. "p[style-name='引用'] => blockquote:fresh",
  2462. "r[style-name='Strong'] => strong",
  2463. "r[style-name='Emphasis'] => em",
  2464. "r[style-name='加粗'] => strong",
  2465. "r[style-name='倾斜'] => em"
  2466. ]
  2467. });
  2468. })
  2469. .then(function (conversion) {
  2470. return { html: conversion.value, messages: conversion.messages || [] };
  2471. });
  2472. },
  2473. normalizeImportedWordHtml: function (wordUi, html) {
  2474. var normalized = wordUi.normalizeWordHtml(html || '');
  2475. if (!normalized) {
  2476. return '';
  2477. }
  2478. var wrapper = document.createElement('div');
  2479. wrapper.innerHTML = normalized;
  2480. wrapper.style.position = 'absolute';
  2481. wrapper.style.left = '-99999px';
  2482. wrapper.style.top = '0';
  2483. wrapper.style.visibility = 'hidden';
  2484. document.body.appendChild(wrapper);
  2485. var nodes = wrapper.querySelectorAll('p, div, blockquote, table, td, th, span, font');
  2486. for (var i = 0; i < nodes.length; i++) {
  2487. var node = nodes[i];
  2488. var styleText = node.getAttribute('style') || '';
  2489. var keptStyles = styleText.split(';').filter(function (rule) {
  2490. return rule.trim() && !/^\s*mso-/i.test(rule);
  2491. }).join(';');
  2492. if (keptStyles) {
  2493. node.setAttribute('style', keptStyles);
  2494. } else {
  2495. node.removeAttribute('style');
  2496. }
  2497. var textIndent = node.style && node.style.textIndent;
  2498. if (textIndent && !/^0(?:px|pt|em|%)?$/i.test(textIndent.trim())) {
  2499. node.style.textIndent = '2em';
  2500. } else if (!textIndent && /^(P|LI|BLOCKQUOTE)$/i.test(node.tagName)) {
  2501. node.style.textIndent = '2em';
  2502. }
  2503. if (!(node.style && node.style.lineHeight) && /^(P|LI|BLOCKQUOTE)$/i.test(node.tagName)) {
  2504. node.style.lineHeight = this.defaultEditorLineHeight;
  2505. }
  2506. if (node.getAttribute && node.getAttribute('align')) {
  2507. node.style.textAlign = node.getAttribute('align');
  2508. node.removeAttribute('align');
  2509. }
  2510. }
  2511. var walker = document.createTreeWalker(wrapper, NodeFilter.SHOW_TEXT, {
  2512. acceptNode: function (textNode) {
  2513. return textNode.nodeValue && textNode.nodeValue.trim()
  2514. ? NodeFilter.FILTER_ACCEPT
  2515. : NodeFilter.FILTER_REJECT;
  2516. }
  2517. });
  2518. var textNodes = [];
  2519. while (walker.nextNode()) {
  2520. textNodes.push(walker.currentNode);
  2521. }
  2522. textNodes.forEach(function (textNode) {
  2523. var parent = textNode.parentElement;
  2524. if (!parent || !window.getComputedStyle) {
  2525. return;
  2526. }
  2527. var computed = window.getComputedStyle(parent);
  2528. var explicitFontFamily = "";
  2529. var explicitFontSize = "";
  2530. var fontNode = parent;
  2531. while (fontNode && fontNode != wrapper) {
  2532. if (!explicitFontFamily && fontNode.style && fontNode.style.fontFamily) {
  2533. explicitFontFamily = fontNode.style.fontFamily;
  2534. }
  2535. if (!explicitFontSize && fontNode.style && fontNode.style.fontSize) {
  2536. explicitFontSize = fontNode.style.fontSize;
  2537. }
  2538. fontNode = fontNode.parentElement;
  2539. }
  2540. var formattedSpan = document.createElement('span');
  2541. formattedSpan.setAttribute('data-word-format', 'true');
  2542. formattedSpan.style.fontFamily = explicitFontFamily || this.defaultEditorFontFamily;
  2543. formattedSpan.style.fontSize = explicitFontSize || this.defaultEditorFontSize;
  2544. formattedSpan.style.color = computed.color;
  2545. if (computed.fontWeight && computed.fontWeight !== '400' && computed.fontWeight !== 'normal') {
  2546. formattedSpan.style.fontWeight = computed.fontWeight;
  2547. }
  2548. if (computed.fontStyle && computed.fontStyle !== 'normal') {
  2549. formattedSpan.style.fontStyle = computed.fontStyle;
  2550. }
  2551. if (computed.textDecorationLine && computed.textDecorationLine !== 'none') {
  2552. formattedSpan.style.textDecoration = computed.textDecorationLine;
  2553. }
  2554. if (computed.verticalAlign && computed.verticalAlign !== 'baseline') {
  2555. formattedSpan.style.verticalAlign = computed.verticalAlign;
  2556. }
  2557. formattedSpan.appendChild(textNode.cloneNode(true));
  2558. textNode.parentNode.replaceChild(formattedSpan, textNode);
  2559. }.bind(this));
  2560. var inlineNodes = wrapper.querySelectorAll('span, font, b, strong, i, em, u, s, strike, sub, sup');
  2561. for (var inlineIndex = inlineNodes.length - 1; inlineIndex >= 0; inlineIndex--) {
  2562. var inlineNode = inlineNodes[inlineIndex];
  2563. if (inlineNode.getAttribute('data-word-format') === 'true' || !inlineNode.parentNode) {
  2564. continue;
  2565. }
  2566. while (inlineNode.firstChild) {
  2567. inlineNode.parentNode.insertBefore(inlineNode.firstChild, inlineNode);
  2568. }
  2569. inlineNode.parentNode.removeChild(inlineNode);
  2570. }
  2571. var importedImages = wrapper.querySelectorAll('img');
  2572. for (var importedImageIndex = 0; importedImageIndex < importedImages.length; importedImageIndex++) {
  2573. var importedImage = importedImages[importedImageIndex];
  2574. var importedSrc = this.normalizeEditorMediaUrl(importedImage.getAttribute('data-original')
  2575. || importedImage.getAttribute('data-src')
  2576. || importedImage.getAttribute('data-lazy-src')
  2577. || importedImage.getAttribute('src')
  2578. || '');
  2579. if (importedSrc) {
  2580. importedImage.setAttribute('src', importedSrc);
  2581. importedImage.removeAttribute('data-original');
  2582. importedImage.removeAttribute('data-src');
  2583. importedImage.removeAttribute('data-lazy-src');
  2584. }
  2585. }
  2586. var normalizedHtml = wrapper.innerHTML;
  2587. document.body.removeChild(wrapper);
  2588. return normalizedHtml;
  2589. },
  2590. insertFormattedWordHtml: function (editor, htmlContent) {
  2591. this.insertHtml(htmlContent);
  2592. this.$emit('input', this.getEditorSaveHtml());
  2593. this.deferSyncEditorPlayableVideos();
  2594. },
  2595. applyDefaultEditorTypography: function (editor) {
  2596. if (!editor || !editor.model || !editor.model.document) {
  2597. return;
  2598. }
  2599. var root = editor.model.document.getRoot();
  2600. var firstBlock = root.getChild(0);
  2601. editor.model.change(function (writer) {
  2602. if (!firstBlock) {
  2603. firstBlock = writer.appendElement('paragraph', root);
  2604. }
  2605. writer.setSelection(firstBlock, 'in');
  2606. if (editor.model.schema.checkAttribute(firstBlock.name, 'textIndent')) {
  2607. writer.setAttribute('textIndent', '2em', firstBlock);
  2608. }
  2609. if (editor.model.schema.checkAttribute(firstBlock.name, 'lineHeight')) {
  2610. writer.setAttribute('lineHeight', this.defaultEditorLineHeight, firstBlock);
  2611. }
  2612. }.bind(this));
  2613. editor.execute('fontFamily', { value: this.defaultEditorFontFamily });
  2614. editor.execute('fontSize', { value: this.defaultEditorFontSize });
  2615. this.refreshLineHeightControl(editor);
  2616. },
  2617. convertWordWithServer: function (file) {
  2618. var formData = new FormData();
  2619. var convertUrl = this.wordconverturl;
  2620. formData.append('upload', file);
  2621. return fetch('/apps?ark=sys.uploadAjax', {
  2622. method: 'POST',
  2623. body: formData,
  2624. credentials: 'same-origin'
  2625. }).then(readJsonResponse).then(function (uploadResult) {
  2626. var uploadData = uploadResult && (uploadResult.data || uploadResult);
  2627. var path = uploadResult && uploadResult.data && uploadResult.data[0] && uploadResult.data[0].msg;
  2628. path = path || (uploadData && (uploadData.msg || uploadData.path));
  2629. if (!path) {
  2630. throw new Error('Word 文件上传失败。');
  2631. }
  2632. return fetch(convertUrl, {
  2633. method: 'POST',
  2634. headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
  2635. body: 'path=' + encodeURIComponent(path),
  2636. credentials: 'same-origin'
  2637. });
  2638. }).then(readJsonResponse).then(function (conversionResult) {
  2639. var data = conversionResult && (conversionResult.data || conversionResult);
  2640. var html = conversionResult && conversionResult.htmlContent;
  2641. html = html || (data && data.htmlContent);
  2642. html = html || (conversionResult && conversionResult.data && conversionResult.data[0] && conversionResult.data[0].htmlContent);
  2643. if (!html) {
  2644. throw new Error('服务器没有返回可导入的 Word 内容。');
  2645. }
  2646. return { html: html, messages: [] };
  2647. });
  2648. function readJsonResponse(response) {
  2649. if (!response || !response.ok) {
  2650. throw new Error('Word 转换服务不可用。');
  2651. }
  2652. return response.text().then(function (text) {
  2653. try {
  2654. var json = JSON.parse(text);
  2655. if (json && json.code && json.code !== 'success') {
  2656. throw new Error(json.msg || 'Word 转换失败。');
  2657. }
  2658. return json;
  2659. } catch (error) {
  2660. throw new Error(error && error.message ? error.message : 'Word 转换服务返回异常。');
  2661. }
  2662. });
  2663. }
  2664. },
  2665. openWordImporter: function () {
  2666. if (!this.editor || !this.editor.ui || !this.editor.ui.view || !this.editor.ui.view.element) {
  2667. space.message.warning("编辑器尚未加载完成");
  2668. return;
  2669. }
  2670. var editorEl = this.editor.ui.view.element;
  2671. var wordButton = editorEl.querySelector('button[aria-label="导入word文件"]')
  2672. || editorEl.querySelector('button[title="导入word文件"]');
  2673. if (!wordButton) {
  2674. var labels = editorEl.querySelectorAll(".ck-button__label");
  2675. for (var i = 0; i < labels.length; i++) {
  2676. if ((labels[i].textContent || "").trim() == "导入word文件") {
  2677. wordButton = labels[i].closest("button");
  2678. break;
  2679. }
  2680. }
  2681. }
  2682. if (!wordButton) {
  2683. space.message.warning("Word 导入功能尚未加载完成");
  2684. return;
  2685. }
  2686. wordButton.click();
  2687. },
  2688. insertHtml: function (html) {
  2689. if (!this.editor || space.utils.isNull(html)) {
  2690. return;
  2691. }
  2692. var viewFragment = this.editor.data.processor.toView(html);
  2693. var modelFragment = this.editor.data.toModel(viewFragment);
  2694. this.editor.model.insertContent(modelFragment);
  2695. this.$emit("input", this.getEditorSaveHtml());
  2696. this.deferSyncEditorPlayableVideos();
  2697. },
  2698. escapeHtmlAttr: function (value) {
  2699. return String(value || "").replace(/[&<>"']/g, function (text) {
  2700. return {
  2701. "&": "&amp;",
  2702. "<": "&lt;",
  2703. ">": "&gt;",
  2704. "\"": "&quot;",
  2705. "'": "&#39;"
  2706. }[text];
  2707. });
  2708. },
  2709. normalizeLocalUploadUrl: function (url) {
  2710. var text = String(url || "").trim().replace(/\\/g, "/");
  2711. var match = text.match(/^(?:https?:)?\/\/[^/]*(\/web\/upload\/.*)$/i);
  2712. if (match) {
  2713. text = match[1];
  2714. }
  2715. text = text.replace(/^(https?:)\/+(\/web\/upload\/.*)$/i, "$2");
  2716. text = text.replace(/(\/web\/upload\/modules)\/+/i, "$1/");
  2717. return text;
  2718. },
  2719. toAbsoluteEditorMediaUrl: function (url) {
  2720. var text = String(url || "").trim();
  2721. if (/^(https?:)?\/\//i.test(text) || /^(data|blob):/i.test(text)) {
  2722. return text;
  2723. }
  2724. if (text.charAt(0) == "/") {
  2725. return window.location.origin + text;
  2726. }
  2727. return text;
  2728. },
  2729. openVideoPicker: function () {
  2730. if (this.$refs.videoInput) {
  2731. this.$refs.videoInput.click();
  2732. }
  2733. },
  2734. openPdfPicker: function () {
  2735. if (this.$refs.pdfInput) {
  2736. this.$refs.pdfInput.click();
  2737. }
  2738. },
  2739. openAttachmentPicker: function () {
  2740. if (this.$refs.attachmentInput) {
  2741. this.$refs.attachmentInput.click();
  2742. }
  2743. },
  2744. handleVideoSelect: function (event) {
  2745. var files = Array.prototype.slice.call(event.target.files || []);
  2746. event.target.value = "";
  2747. if (files.length > 0) {
  2748. this.uploadVideoFile(files[0]);
  2749. }
  2750. },
  2751. handlePdfSelect: function (event) {
  2752. var files = Array.prototype.slice.call(event.target.files || []);
  2753. event.target.value = "";
  2754. if (files.length > 0) {
  2755. this.uploadPdfFile(files[0]);
  2756. }
  2757. },
  2758. handleAttachmentSelect: function (event) {
  2759. var files = Array.prototype.slice.call(event.target.files || []);
  2760. event.target.value = "";
  2761. if (files.length > 0) {
  2762. this.uploadAttachmentFile(files[0]);
  2763. }
  2764. },
  2765. uploadAttachmentFile: function (file) {
  2766. if (!file) {
  2767. return;
  2768. }
  2769. var _this = this;
  2770. _this.uploading = true;
  2771. _this.uploadStatus = '正在上传附件';
  2772. _this.uploadPlainFileByAdapter(file, {
  2773. imageQuality: 'origin',
  2774. fileMaxSize: 100 * 1024 * 1024
  2775. }, function (loaded, total) {
  2776. if (total > 0) {
  2777. _this.uploadStatus = '正在上传附件 ' + Math.round(loaded * 100 / total) + '%';
  2778. }
  2779. }).then(function (res) {
  2780. var attachmentUrl = _this.normalizeLocalUploadUrl(res && res.default ? res.default : res);
  2781. if (!attachmentUrl) {
  2782. throw new Error('附件上传失败');
  2783. }
  2784. _this.insertAttachmentLink(attachmentUrl, file.name);
  2785. _this.$emit('input', _this.getEditorSaveHtml());
  2786. space.message.success('附件已插入正文');
  2787. }).catch(function (msg) {
  2788. space.message.error(msg || '附件上传失败');
  2789. }).finally(function () {
  2790. _this.uploading = false;
  2791. _this.uploadStatus = '';
  2792. });
  2793. },
  2794. buildAttachmentLink: function (url, fileName) {
  2795. var safeUrl = this.escapeHtmlAttr(url);
  2796. var safeName = this.escapeHtmlAttr(fileName || '附件');
  2797. return '<p data-space-attachment="true"><a href="' + safeUrl + '" download="' + safeName
  2798. + '" target="_blank" rel="noopener" title="下载附件:' + safeName
  2799. + '" style="color:#1769ff;text-decoration:underline;">' + safeName + '</a></p><p></p>';
  2800. },
  2801. insertAttachmentLink: function (url, fileName) {
  2802. if (!url) {
  2803. return;
  2804. }
  2805. this.insertHtml(this.buildAttachmentLink(url, fileName));
  2806. },
  2807. isPdfFile: function (file) {
  2808. return !!file && ((file.type && file.type.toLowerCase() == "application/pdf") || /\.pdf$/i.test(file.name || ""));
  2809. },
  2810. uploadVideoFile: function (file) {
  2811. if (!file || !file.type || file.type.indexOf("video/") !== 0) {
  2812. space.message.warning("请选择视频文件");
  2813. return;
  2814. }
  2815. var _this = this;
  2816. _this.uploading = true;
  2817. _this.uploadStatus = "正在上传视频";
  2818. _this.uploadPlainFileByAdapter(file, {
  2819. imageQuality: 'origin'
  2820. }, function (loaded, total) {
  2821. if (total > 0) {
  2822. _this.uploadStatus = "正在上传视频 " + Math.round(loaded * 100 / total) + "%";
  2823. }
  2824. }).then(function (res) {
  2825. var videoUrl = _this.normalizeLocalUploadUrl(res.default);
  2826. _this.insertVideoViewer(videoUrl, file.name);
  2827. _this.$emit("input", _this.getEditorSaveHtml());
  2828. space.message.success("视频已插入正文");
  2829. }).catch(function (msg) {
  2830. space.message.error(msg || "视频上传失败");
  2831. }).finally(function () {
  2832. _this.uploading = false;
  2833. _this.uploadStatus = "";
  2834. });
  2835. },
  2836. buildVideoViewerHtml: function (url, fileName) {
  2837. var safeUrl = this.escapeHtmlAttr(url);
  2838. var safeName = this.escapeHtmlAttr(fileName || "视频");
  2839. var type = /\.webm(\?.*)?$/i.test(url) ? "video/webm" : ((/\.ogg|\.ogv(\?.*)?$/i.test(url)) ? "video/ogg" : "video/mp4");
  2840. return '<p><video controls playsinline webkit-playsinline preload="metadata" title="' + safeName
  2841. + '" style="display:block;width:100%;max-width:960px;background:#000;">'
  2842. + '<source src="' + safeUrl + '" type="' + type + '">'
  2843. + '您的浏览器暂不支持视频播放。'
  2844. + '</video></p><p></p>';
  2845. },
  2846. insertVideoViewer: function (url, fileName) {
  2847. if (!this.editor || space.utils.isNull(url)) {
  2848. return;
  2849. }
  2850. var title = fileName || "视频";
  2851. try {
  2852. this.editor.model.change(function (writer) {
  2853. var videoViewer = writer.createElement("spaceVideoViewer", {
  2854. src: url,
  2855. title: title,
  2856. poster: ""
  2857. });
  2858. this.editor.model.insertContent(videoViewer);
  2859. }.bind(this));
  2860. this.$emit("input", this.getEditorSaveHtml());
  2861. this.deferSyncEditorPlayableVideos();
  2862. return;
  2863. } catch (e) {
  2864. console.log(e);
  2865. }
  2866. this.insertHtml(this.buildVideoViewerHtml(url, title));
  2867. this.$emit("input", this.getEditorSaveHtml());
  2868. this.deferSyncEditorPlayableVideos();
  2869. },
  2870. uploadPdfFile: function (file) {
  2871. if (!this.isPdfFile(file)) {
  2872. space.message.warning("请选择PDF文件");
  2873. return;
  2874. }
  2875. var _this = this;
  2876. _this.uploading = true;
  2877. _this.uploadStatus = "正在上传PDF";
  2878. _this.uploadPlainFileByAdapter(file, {
  2879. imageQuality: 'origin',
  2880. pdfMaxSize: 100 * 1024 * 1024
  2881. }, function (loaded, total) {
  2882. if (total > 0) {
  2883. _this.uploadStatus = "正在上传PDF " + Math.round(loaded * 100 / total) + "%";
  2884. }
  2885. }).then(function (res) {
  2886. var pdfUrl = _this.normalizeLocalUploadUrl(res.default);
  2887. _this.insertPdfViewer(pdfUrl, file.name);
  2888. _this.$emit("input", _this.getEditorSaveHtml());
  2889. window.setTimeout(function () {
  2890. _this.enhanceEditorPdfViewers();
  2891. _this.activateLastPdfInEditor();
  2892. _this.refreshPdfSecureStatusBar();
  2893. }, 120);
  2894. space.message.success("PDF已插入正文");
  2895. }).catch(function (msg) {
  2896. space.message.error(msg || "PDF上传失败");
  2897. }).finally(function () {
  2898. _this.uploading = false;
  2899. _this.uploadStatus = "";
  2900. });
  2901. },
  2902. buildPdfViewerHtml: function (url, fileName, secure) {
  2903. var safeUrl = this.escapeHtmlAttr(url);
  2904. var safeName = this.escapeHtmlAttr(fileName || "PDF文件");
  2905. var secureFlag = secure === "1" ? "1" : "0";
  2906. var html = '<figure class="space-editor-pdf-viewer media" data-space-pdf="true"'
  2907. + ' data-space-pdf-src="' + safeUrl + '" data-space-pdf-secure="' + secureFlag + '">'
  2908. + '<iframe class="space-editor-pdf-frame" src="' + (secureFlag === "1" ? "" : safeUrl)
  2909. + '" title="' + safeName + '" loading="lazy"></iframe>';
  2910. if (secureFlag !== "1") {
  2911. html += '<figcaption><a href="' + safeUrl + '" target="_blank" rel="noopener">打开 PDF:' + safeName + '</a></figcaption>';
  2912. }
  2913. return html + '</figure><p></p>';
  2914. },
  2915. insertPdfViewer: function (url, fileName) {
  2916. if (!this.editor || space.utils.isNull(url)) {
  2917. return;
  2918. }
  2919. var title = fileName || "PDF文件";
  2920. try {
  2921. this.editor.model.change(function (writer) {
  2922. var pdfViewer = writer.createElement("spacePdfViewer", {
  2923. src: url,
  2924. title: title,
  2925. secure: "0"
  2926. });
  2927. this.editor.model.insertContent(pdfViewer);
  2928. }.bind(this));
  2929. this.activePdf = {
  2930. src: this.normalizeEditorMediaUrl(url),
  2931. title: title,
  2932. secure: "0"
  2933. };
  2934. this.$emit("input", this.getEditorSaveHtml());
  2935. this.deferSyncEditorPlayableVideos();
  2936. this.enhanceEditorPdfViewers();
  2937. this.refreshPdfSecureStatusBar();
  2938. return;
  2939. } catch (e) {
  2940. console.log(e);
  2941. }
  2942. this.insertHtml(this.buildPdfViewerHtml(url, title, "0"));
  2943. this.$emit("input", this.getEditorSaveHtml());
  2944. this.activePdf = {
  2945. src: this.normalizeEditorMediaUrl(url),
  2946. title: title,
  2947. secure: "0"
  2948. };
  2949. this.refreshPdfSecureStatusBar();
  2950. var _this = this;
  2951. window.setTimeout(function () {
  2952. _this.enhanceEditorPdfViewers();
  2953. _this.activateLastPdfInEditor();
  2954. }, 120);
  2955. },
  2956. buildPdfLinkHtml: function (url, fileName) {
  2957. var safeUrl = this.escapeHtmlAttr(url);
  2958. var safeName = this.escapeHtmlAttr(fileName || "PDF文件");
  2959. return '<p class="space-editor-pdf-link"><a href="' + safeUrl
  2960. + '" target="_blank" rel="noopener">打开 PDF:' + safeName + '</a></p>';
  2961. },
  2962. upgradePdfLinksToViewers: function () {
  2963. if (!this.editor) {
  2964. return;
  2965. }
  2966. var data = this.editor.getData();
  2967. if (data.indexOf(".pdf") == -1) {
  2968. return;
  2969. }
  2970. var wrapper = document.createElement("div");
  2971. wrapper.innerHTML = data;
  2972. var links = wrapper.querySelectorAll(".space-editor-pdf-link a[href], a[href]");
  2973. var changed = false;
  2974. for (var i = 0; i < links.length; i++) {
  2975. var link = links[i];
  2976. var href = link.getAttribute("href") || "";
  2977. var text = (link.textContent || "").replace(/\s+/g, " ").trim();
  2978. var isPdf = /\.pdf(\?.*)?$/i.test(href);
  2979. var isEditorPdfLink = link.closest(".space-editor-pdf-link") || /^打开\s*PDF[::]/i.test(text);
  2980. if (!isPdf || !isEditorPdfLink) {
  2981. continue;
  2982. }
  2983. var title = text.replace(/^打开\s*PDF[::]\s*/i, "") || href.split("/").pop() || "PDF文件";
  2984. var holder = document.createElement("div");
  2985. holder.innerHTML = this.buildPdfViewerHtml(href, title);
  2986. var viewer = holder.firstElementChild;
  2987. var replaceTarget = link.closest(".space-editor-pdf-link") || link.parentNode;
  2988. if (viewer && replaceTarget && replaceTarget.parentNode) {
  2989. replaceTarget.parentNode.replaceChild(viewer, replaceTarget);
  2990. changed = true;
  2991. }
  2992. }
  2993. if (changed) {
  2994. this.editor.setData(wrapper.innerHTML);
  2995. this.$emit("input", this.getEditorSaveHtml());
  2996. this.deferSyncEditorPlayableVideos();
  2997. }
  2998. },
  2999. bindVideoPasteUpload: function () {
  3000. if (!this.editor) {
  3001. return;
  3002. }
  3003. var editable = this.getEditorEditableElement(this.editor);
  3004. if (!editable || editable.getAttribute("data-space-video-upload") == "true") {
  3005. return;
  3006. }
  3007. editable.setAttribute("data-space-video-upload", "true");
  3008. var _this = this;
  3009. var handler = function (event) {
  3010. var dataTransfer = event.clipboardData || event.dataTransfer;
  3011. var files = _this.getClipboardFiles(dataTransfer);
  3012. if (!files.length) {
  3013. return;
  3014. }
  3015. var videoFile = files.find(function (file) {
  3016. return file && file.type && file.type.indexOf("video/") === 0;
  3017. });
  3018. var pdfFile = files.find(function (file) {
  3019. return _this.isPdfFile(file);
  3020. });
  3021. var imageFiles = files.filter(function (file) {
  3022. return _this.isImageFile(file);
  3023. });
  3024. var htmlContent = _this.readClipboardData(dataTransfer, 'text/html');
  3025. var plainText = _this.readClipboardData(dataTransfer, 'text/plain');
  3026. var hasTextContent = !!(htmlContent.replace(/\s+/g, '') || plainText.trim());
  3027. if (videoFile) {
  3028. event.preventDefault();
  3029. if (event.stopImmediatePropagation) {
  3030. event.stopImmediatePropagation();
  3031. }
  3032. _this.uploadVideoFile(videoFile);
  3033. } else if (pdfFile) {
  3034. event.preventDefault();
  3035. if (event.stopImmediatePropagation) {
  3036. event.stopImmediatePropagation();
  3037. }
  3038. _this.uploadPdfFile(pdfFile);
  3039. } else if (imageFiles.length && hasTextContent) {
  3040. event.preventDefault();
  3041. if (event.stopImmediatePropagation) {
  3042. event.stopImmediatePropagation();
  3043. }
  3044. _this.insertMixedClipboardContent(htmlContent, plainText, imageFiles);
  3045. }
  3046. };
  3047. editable.addEventListener("paste", handler, true);
  3048. editable.addEventListener("drop", handler, true);
  3049. },
  3050. getClipboardFiles: function (dataTransfer) {
  3051. if (!dataTransfer) {
  3052. return [];
  3053. }
  3054. var files = dataTransfer.files ? Array.prototype.slice.call(dataTransfer.files) : [];
  3055. if (files.length || !dataTransfer.items) {
  3056. return files;
  3057. }
  3058. for (var i = 0; i < dataTransfer.items.length; i++) {
  3059. var item = dataTransfer.items[i];
  3060. if (item && item.kind === 'file' && typeof item.getAsFile === 'function') {
  3061. var file = item.getAsFile();
  3062. if (file) {
  3063. files.push(file);
  3064. }
  3065. }
  3066. }
  3067. return files;
  3068. },
  3069. isImageFile: function (file) {
  3070. return !!(file && ((file.type && file.type.indexOf('image/') === 0)
  3071. || /\.(jpg|jpeg|png|gif|bmp|webp|svg)$/i.test(file.name || '')));
  3072. },
  3073. readClipboardData: function (dataTransfer, type) {
  3074. if (!dataTransfer || typeof dataTransfer.getData !== 'function') {
  3075. return '';
  3076. }
  3077. try {
  3078. return dataTransfer.getData(type) || '';
  3079. } catch (error) {
  3080. return '';
  3081. }
  3082. },
  3083. insertMixedClipboardContent: function (htmlContent, plainText, imageFiles) {
  3084. if (!this.editor || !imageFiles || !imageFiles.length) {
  3085. return;
  3086. }
  3087. var _this = this;
  3088. this.uploadStatus = '正在上传粘贴内容中的图片…';
  3089. if (window.space && space.plugins && space.plugins.loading) {
  3090. space.plugins.loading.show();
  3091. }
  3092. Promise.all(imageFiles.map(function (file) {
  3093. return _this.uploadPlainFileByAdapter(file, _this.getUploadOptions()).then(function (result) {
  3094. return result && result.default ? result.default : '';
  3095. });
  3096. })).then(function (imageUrls) {
  3097. var html = _this.buildMixedClipboardHtml(htmlContent, plainText, imageUrls, imageFiles);
  3098. if (!html) {
  3099. throw new Error('粘贴内容为空');
  3100. }
  3101. _this.insertHtml(html);
  3102. _this.$emit('input', _this.getEditorSaveHtml());
  3103. _this.deferSyncEditorPlayableVideos();
  3104. space.message.success('文字和图片已同时粘贴');
  3105. }).catch(function (error) {
  3106. console.error(error);
  3107. space.message.error(error && error.message ? error.message : '粘贴图片上传失败,请重试');
  3108. }).finally(function () {
  3109. _this.uploadStatus = '';
  3110. if (window.space && space.plugins && space.plugins.loading) {
  3111. space.plugins.loading.close();
  3112. }
  3113. });
  3114. },
  3115. buildMixedClipboardHtml: function (htmlContent, plainText, imageUrls, imageFiles) {
  3116. var safeUrls = imageUrls || [];
  3117. var wrapper = document.createElement('div');
  3118. if (htmlContent) {
  3119. wrapper.innerHTML = htmlContent;
  3120. } else {
  3121. var lines = (plainText || '').replace(/\r\n/g, '\n').split('\n');
  3122. wrapper.innerHTML = lines.map(function (line) {
  3123. return '<p>' + this.escapeClipboardText(line) + '</p>';
  3124. }.bind(this)).join('');
  3125. }
  3126. var images = wrapper.querySelectorAll('img');
  3127. for (var i = 0; i < images.length && i < safeUrls.length; i++) {
  3128. if (safeUrls[i]) {
  3129. images[i].setAttribute('src', safeUrls[i]);
  3130. }
  3131. }
  3132. for (var imageIndex = images.length; imageIndex < safeUrls.length; imageIndex++) {
  3133. if (!safeUrls[imageIndex]) {
  3134. continue;
  3135. }
  3136. var figure = document.createElement('figure');
  3137. figure.className = 'image';
  3138. var image = document.createElement('img');
  3139. image.setAttribute('src', safeUrls[imageIndex]);
  3140. image.setAttribute('alt', imageFiles[imageIndex] && imageFiles[imageIndex].name ? imageFiles[imageIndex].name : '粘贴图片');
  3141. figure.appendChild(image);
  3142. wrapper.appendChild(figure);
  3143. }
  3144. return wrapper.innerHTML;
  3145. },
  3146. escapeClipboardText: function (text) {
  3147. return String(text || '').replace(/&/g, '&amp;').replace(/</g, '&lt;')
  3148. .replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;');
  3149. },
  3150. isPdfToolbarControl: function (domTarget) {
  3151. if (!domTarget || !domTarget.closest) {
  3152. return false;
  3153. }
  3154. return !!(domTarget.closest(".space-editor-pdf-secure-toggle")
  3155. || domTarget.closest(".space-editor-pdf-secure-switch")
  3156. || domTarget.closest(".space-editor-pdf-fullscreen-btn")
  3157. || domTarget.closest(".space-editor-pdf-download-original")
  3158. || domTarget.closest(".space-editor-pdf-ck-secure-bar"));
  3159. },
  3160. syncPdfSelectedVisual: function (editor) {
  3161. if (!editor || !editor.editing || !editor.editing.view) {
  3162. return;
  3163. }
  3164. var root = editor.editing.view.getDomRoot();
  3165. if (!root) {
  3166. return;
  3167. }
  3168. var figures = root.querySelectorAll("figure.space-editor-pdf-viewer");
  3169. var selected = editor.model.document.selection.getSelectedElement();
  3170. var isPdfSelected = selected && selected.is && selected.is("element") && selected.name === "spacePdfViewer";
  3171. for (var i = 0; i < figures.length; i++) {
  3172. var figure = figures[i];
  3173. if (isPdfSelected) {
  3174. var viewFigure = editor.editing.view.domConverter.mapDomToView(figure);
  3175. var modelElement = viewFigure ? editor.editing.mapper.toModelElement(viewFigure) : null;
  3176. if (modelElement === selected) {
  3177. figure.classList.add("space-editor-pdf-selected");
  3178. } else {
  3179. figure.classList.remove("space-editor-pdf-selected");
  3180. }
  3181. } else {
  3182. figure.classList.remove("space-editor-pdf-selected");
  3183. }
  3184. }
  3185. },
  3186. removePdfFromEditorHtml: function (editor, src) {
  3187. var target = this.normalizeEditorMediaUrl(src);
  3188. if (!editor || !target) {
  3189. return false;
  3190. }
  3191. var data = editor.getData();
  3192. if (!data || data.indexOf("space-editor-pdf") === -1) {
  3193. return false;
  3194. }
  3195. var wrapper = document.createElement("div");
  3196. wrapper.innerHTML = data;
  3197. var figures = wrapper.querySelectorAll("figure.space-editor-pdf-viewer, figure[data-space-pdf='true']");
  3198. var removed = false;
  3199. for (var i = 0; i < figures.length; i++) {
  3200. var figure = figures[i];
  3201. var figureSrc = this.normalizeEditorMediaUrl(figure.getAttribute("data-space-pdf-src")
  3202. || ((figure.querySelector("iframe.space-editor-pdf-frame") || {}).src || ""));
  3203. if (figureSrc !== target) {
  3204. continue;
  3205. }
  3206. figure.parentNode.removeChild(figure);
  3207. removed = true;
  3208. break;
  3209. }
  3210. if (!removed) {
  3211. return false;
  3212. }
  3213. editor.setData(wrapper.innerHTML);
  3214. return true;
  3215. },
  3216. deleteSelectedPdf: function (editor) {
  3217. if (!editor) {
  3218. return false;
  3219. }
  3220. var selected = editor.model.document.selection.getSelectedElement();
  3221. if (!selected || !selected.is || !selected.is("element") || selected.name !== "spacePdfViewer") {
  3222. if (this.activePdf && this.activePdf.src) {
  3223. selected = this.findPdfModelBySrc(this.activePdf.src);
  3224. if (selected) {
  3225. editor.model.change(function (writer) {
  3226. writer.setSelection(selected, "on");
  3227. });
  3228. }
  3229. }
  3230. }
  3231. if (selected && selected.is && selected.is("element") && selected.name === "spacePdfViewer") {
  3232. editor.model.change(function (writer) {
  3233. writer.remove(selected);
  3234. });
  3235. } else if (this.activePdf && this.activePdf.src && this.removePdfFromEditorHtml(editor, this.activePdf.src)) {
  3236. // HTML 兜底删除
  3237. } else {
  3238. return false;
  3239. }
  3240. this.activePdf = null;
  3241. this.pdfFloatToolbarStyle = null;
  3242. this.refreshPdfSecureStatusBar();
  3243. this.syncPdfSelectedVisual(editor);
  3244. this.$emit("input", this.getEditorSaveHtml());
  3245. return true;
  3246. },
  3247. findClosestEditorMedia: function (target) {
  3248. if (!target) {
  3249. return null;
  3250. }
  3251. if (target.nodeType == 3) {
  3252. target = target.parentNode;
  3253. }
  3254. if (!target || target.nodeType != 1) {
  3255. return null;
  3256. }
  3257. if (target.closest && target.closest("figure.space-editor-pdf-viewer")) {
  3258. return null;
  3259. }
  3260. if (target.classList && target.classList.contains("space-editor-pdf-frame")) {
  3261. return null;
  3262. }
  3263. if (/^(video|iframe)$/i.test(target.tagName)) {
  3264. if ((target.tagName || "").toLowerCase() === "iframe"
  3265. && target.classList && target.classList.contains("space-editor-pdf-frame")) {
  3266. return null;
  3267. }
  3268. return target;
  3269. }
  3270. if (target.closest) {
  3271. var media = target.closest("video, iframe");
  3272. if (media && media.classList && media.classList.contains("space-editor-pdf-frame")) {
  3273. return null;
  3274. }
  3275. if (media && media.closest && media.closest("figure.space-editor-pdf-viewer")) {
  3276. return null;
  3277. }
  3278. return media;
  3279. }
  3280. return null;
  3281. },
  3282. prepareEditorPlayableMedia: function (media) {
  3283. if (!media || media.nodeType != 1) {
  3284. return;
  3285. }
  3286. var tagName = (media.tagName || "").toLowerCase();
  3287. if (tagName == "video") {
  3288. media.setAttribute("controls", "controls");
  3289. media.setAttribute("playsinline", "playsinline");
  3290. media.setAttribute("webkit-playsinline", "webkit-playsinline");
  3291. if (!media.getAttribute("preload")) {
  3292. media.setAttribute("preload", "metadata");
  3293. }
  3294. }
  3295. media.classList.add("space-editor-playable-media");
  3296. var mediaWidget = media.closest ? media.closest("figure.media") : null;
  3297. if (mediaWidget) {
  3298. mediaWidget.classList.add("space-editor-playable-media-widget");
  3299. }
  3300. },
  3301. bindPlayableMediaNativeEvents: function (media) {
  3302. if (!media || media.getAttribute("data-space-playable-media-bound") == "true") {
  3303. return;
  3304. }
  3305. if (media.classList && media.classList.contains("space-editor-pdf-frame")) {
  3306. return;
  3307. }
  3308. if (media.closest && media.closest("figure.space-editor-pdf-viewer")) {
  3309. return;
  3310. }
  3311. this.prepareEditorPlayableMedia(media);
  3312. media.setAttribute("data-space-playable-media-bound", "true");
  3313. var _this = this;
  3314. var stopWidgetSelection = function (event) {
  3315. _this.prepareEditorPlayableMedia(media);
  3316. event.stopPropagation();
  3317. };
  3318. var eventNames = ["pointerdown", "pointerup", "mousedown", "mouseup", "click", "dblclick", "touchstart", "touchend"];
  3319. for (var i = 0; i < eventNames.length; i++) {
  3320. media.addEventListener(eventNames[i], stopWidgetSelection);
  3321. }
  3322. },
  3323. syncEditorPlayableVideos: function () {
  3324. if (!this.editor) {
  3325. return;
  3326. }
  3327. var editable = this.getEditorEditableElement(this.editor);
  3328. if (!editable) {
  3329. return;
  3330. }
  3331. var medias = editable.querySelectorAll("video, iframe:not(.space-editor-pdf-frame)");
  3332. for (var i = 0; i < medias.length; i++) {
  3333. this.bindPlayableMediaNativeEvents(medias[i]);
  3334. }
  3335. },
  3336. deferSyncEditorPlayableVideos: function () {
  3337. if (this.videoPlaybackSyncTimer) {
  3338. window.clearTimeout(this.videoPlaybackSyncTimer);
  3339. }
  3340. var _this = this;
  3341. this.videoPlaybackSyncTimer = window.setTimeout(function () {
  3342. _this.syncEditorPlayableVideos();
  3343. _this.videoPlaybackSyncTimer = undefined;
  3344. }, 0);
  3345. },
  3346. bindEditorVideoPlayback: function () {
  3347. if (!this.editor) {
  3348. return;
  3349. }
  3350. var editable = this.getEditorEditableElement(this.editor);
  3351. if (!editable || editable.getAttribute("data-space-playable-media-root") == "true") {
  3352. this.syncEditorPlayableVideos();
  3353. return;
  3354. }
  3355. editable.setAttribute("data-space-playable-media-root", "true");
  3356. var _this = this;
  3357. var stopNativeWidgetSelection = function (event) {
  3358. var media = _this.findClosestEditorMedia(event.target);
  3359. if (!media) {
  3360. return;
  3361. }
  3362. _this.prepareEditorPlayableMedia(media);
  3363. event.stopPropagation();
  3364. };
  3365. ["pointerdown", "pointerup", "mousedown", "mouseup", "click", "dblclick", "touchstart", "touchend"].forEach(function (eventName) {
  3366. editable.addEventListener(eventName, stopNativeWidgetSelection);
  3367. });
  3368. if (this.editor.editing && this.editor.editing.view && this.editor.editing.view.document) {
  3369. ["mousedown", "mouseup", "click", "dblclick", "touchstart", "touchend"].forEach(function (eventName) {
  3370. _this.editor.editing.view.document.on(eventName, function (evt, data) {
  3371. var domTarget = data ? (data.domTarget || (data.domEvent ? data.domEvent.target : null)) : null;
  3372. var media = _this.findClosestEditorMedia(domTarget);
  3373. if (!media) {
  3374. return;
  3375. }
  3376. _this.prepareEditorPlayableMedia(media);
  3377. evt.stop();
  3378. }, { priority: "highest" });
  3379. });
  3380. }
  3381. this.syncEditorPlayableVideos();
  3382. },
  3383. getPreviewPostData: function () {
  3384. var data = this.previewdata || {};
  3385. return {
  3386. title: data.title || '',
  3387. source: data.source || '',
  3388. navigationid: data.navigationid || '',
  3389. desc: data.desc || '',
  3390. body: this.editor ? this.getEditorSaveHtml() : (this.htmlContent || '')
  3391. };
  3392. },
  3393. openArticlePreview: function () {
  3394. if (!this.editor) {
  3395. return;
  3396. }
  3397. var postData = this.getPreviewPostData();
  3398. if (space.utils.isNull(postData.navigationid)) {
  3399. space.message.warning("请先选择发布栏目");
  3400. return;
  3401. }
  3402. if (space.utils.isNull(postData.body)) {
  3403. space.message.warning("正文内容为空");
  3404. return;
  3405. }
  3406. var _this = this;
  3407. _this.previewLoading = true;
  3408. $.ajax({
  3409. url: _this.previewurl || "/apps?ark=website.article_preview",
  3410. type: "POST",
  3411. data: postData,
  3412. dataType: "json",
  3413. success: function (res) {
  3414. if (res.code != "success") {
  3415. space.message.error(res.msg || "生成预览失败");
  3416. return;
  3417. }
  3418. var data = res.data || {};
  3419. var baseUrl = data.url || data.previewUrl || "";
  3420. if (space.utils.isNull(baseUrl)) {
  3421. space.message.error("生成预览失败");
  3422. return;
  3423. }
  3424. _this.previewUrl = baseUrl + (baseUrl.indexOf("?") == -1 ? "?" : "&") + "_t=" + new Date().getTime();
  3425. _this.previewVisible = true;
  3426. },
  3427. error: function () {
  3428. space.message.error("生成预览失败");
  3429. },
  3430. complete: function () {
  3431. _this.previewLoading = false;
  3432. }
  3433. });
  3434. },
  3435. setPreviewMode: function (mode) {
  3436. this.previewMode = mode || 'pc';
  3437. },
  3438. handlePreviewFrameLoad: function (event) {
  3439. var frame = event ? event.target : null;
  3440. var _this = this;
  3441. this.scrollPreviewFrameToArticle(frame);
  3442. window.setTimeout(function () {
  3443. _this.scrollPreviewFrameToArticle(frame);
  3444. }, 220);
  3445. },
  3446. scrollPreviewFrameToArticle: function (frame) {
  3447. if (!frame || !frame.contentWindow || !frame.contentWindow.document) {
  3448. return;
  3449. }
  3450. try {
  3451. var doc = frame.contentWindow.document;
  3452. var target = doc.querySelector('.article-header')
  3453. || doc.querySelector('article[class*="article-panel"]')
  3454. || doc.querySelector('.article-body')
  3455. || doc.querySelector('main');
  3456. if (!target) {
  3457. return;
  3458. }
  3459. var top = target.getBoundingClientRect().top + frame.contentWindow.pageYOffset - 24;
  3460. frame.contentWindow.scrollTo(0, top > 0 ? top : 0);
  3461. } catch (e) {
  3462. console.log(e);
  3463. }
  3464. },
  3465. /**
  3466. * 初始化编辑器
  3467. */
  3468. initEditor: function () {
  3469. var toolbar = this.getToolbar();
  3470. var _this = this;
  3471. ClassicEditor.create(document.querySelector("#" + _this.id), {
  3472. extraPlugins: [function (editor) {
  3473. _this.installUploadAdapter(editor);
  3474. _this.installFirstLineIndentPlugin(editor);
  3475. _this.installLineHeightPlugin(editor);
  3476. _this.installVideoViewerPlugin(editor);
  3477. _this.installPdfViewerPlugin(editor);
  3478. }], // 添加上传适配器
  3479. toolbar: toolbar || {},
  3480. language: 'zh-cn',
  3481. placeholder: _this.placeholder || '',
  3482. fontFamily: {
  3483. supportAllValues: true,
  3484. options: [
  3485. 'default',
  3486. { title: '宋体', model: 'SimSun, serif', view: { name: 'span', styles: { 'font-family': "'SimSun', serif" }, priority: 7 } },
  3487. { title: '仿宋', model: 'FangSong, serif', view: { name: 'span', styles: { 'font-family': "'FangSong', serif" }, priority: 7 } },
  3488. { title: '仿宋_GB2312', model: "'仿宋_GB2312', 'FangSong_GB2312', FangSong, serif", view: { name: 'span', styles: { 'font-family': "'仿宋_GB2312', 'FangSong_GB2312', FangSong, serif" }, priority: 7 } },
  3489. { title: '楷体', model: 'KaiTi, serif', view: { name: 'span', styles: { 'font-family': "'KaiTi', serif" }, priority: 7 } },
  3490. { title: '黑体', model: 'SimHei, sans-serif', view: { name: 'span', styles: { 'font-family': "'SimHei', sans-serif" }, priority: 7 } },
  3491. { title: '微软雅黑', model: 'Microsoft YaHei, sans-serif', view: { name: 'span', styles: { 'font-family': "'Microsoft YaHei', sans-serif" }, priority: 7 } },
  3492. { title: '等线', model: 'DengXian, sans-serif', view: { name: 'span', styles: { 'font-family': "'DengXian', sans-serif" }, priority: 7 } },
  3493. { title: '思源宋体', model: 'Source Han Serif SC, serif', view: { name: 'span', styles: { 'font-family': "'Source Han Serif SC', serif" }, priority: 7 } },
  3494. { title: '思源黑体', model: 'Source Han Sans SC, sans-serif', view: { name: 'span', styles: { 'font-family': "'Source Han Sans SC', sans-serif" }, priority: 7 } },
  3495. { title: 'Arial', model: 'Arial, Helvetica, sans-serif', view: { name: 'span', styles: { 'font-family': "'Arial', Helvetica, sans-serif" }, priority: 7 } },
  3496. { title: 'Times New Roman', model: 'Times New Roman, Times, serif', view: { name: 'span', styles: { 'font-family': "'Times New Roman', Times, serif" }, priority: 7 } }
  3497. ]
  3498. },
  3499. fontSize: {
  3500. supportAllValues: true,
  3501. options: ['default', '10.5pt', '12pt', '14pt', '16pt', '18pt', '20pt', '22pt', '26pt', '36pt']
  3502. },
  3503. mediaEmbed: {
  3504. previewsInData: true,
  3505. providers: [{
  3506. name: 'spaceVideo',
  3507. url: [
  3508. /\.(mp4|webm|ogg)(\?.*)?$/i
  3509. ],
  3510. html: match => {
  3511. const input = match['input'];
  3512. return (
  3513. `<video controls playsinline preload="metadata" src="${input}" style="max-width:100%;"></video>`
  3514. );
  3515. }
  3516. }, {
  3517. name: 'spacePdf',
  3518. url: [
  3519. /\.pdf(\?.*)?$/i
  3520. ],
  3521. html: match => {
  3522. const input = match['input'];
  3523. return (
  3524. `<iframe class="space-editor-pdf-frame" src="${input}" title="PDF文件" loading="lazy" frameborder="0"></iframe>`
  3525. );
  3526. }
  3527. }, {
  3528. name: 'myprovider',
  3529. url: [
  3530. /^lizzy.*\.com.*\/media\/(\w+)/,
  3531. /^www\.lizzy.*/,
  3532. /^.*/
  3533. ],
  3534. html: match => {
  3535. //获取媒体url
  3536. const input = match['input'];
  3537. return (
  3538. `<iframe src="${input}" allowFullScreen="true" frameborder="0"></iframe>`
  3539. );
  3540. }
  3541. }]
  3542. }
  3543. }).then(editor => {
  3544. space.vars.editorReady = true;
  3545. _this.editor = editor;
  3546. _this.alignFullScreenToolbarButton();
  3547. _this.mountFirstLineIndentToolbarButton(editor);
  3548. _this.mountLineHeightToolbar(editor);
  3549. _this.mountAttachmentToolbarButton(editor);
  3550. _this.configureWordUploadPlugin(editor);
  3551. if (_this.type !== 'flow') {
  3552. _this.mountVideoUploadToolbarButton();
  3553. _this.mountPdfUploadToolbarButton();
  3554. _this.mountPdfSecureStatusBar();
  3555. _this.bindVideoPasteUpload();
  3556. _this.bindEditorVideoPlayback();
  3557. _this.bindPdfSecureControls(editor);
  3558. _this.bindPdfKeyboardDelete(editor);
  3559. _this.bindFormSubmitSync();
  3560. }
  3561. if (_this.htmlContent != undefined) {
  3562. _this.editor.setData(_this.normalizeVideoHtmlForEditor(_this.htmlContent));
  3563. if (!String(_this.htmlContent || '').trim()) {
  3564. _this.applyDefaultEditorTypography(_this.editor);
  3565. }
  3566. _this.upgradePdfLinksToViewers();
  3567. _this.deferSyncEditorPlayableVideos();
  3568. _this.enhanceEditorPdfViewers();
  3569. }
  3570. window.setTimeout(function () {
  3571. _this.upgradePdfLinksToViewers();
  3572. _this.enhanceEditorPdfViewers();
  3573. }, 300);
  3574. /**
  3575. * 禁止在编辑器内回车事件
  3576. */
  3577. editor.ui.view.element.onkeydown = function (event) {
  3578. // 回车键
  3579. if (event.keyCode == 13) {
  3580. event.stopPropagation();
  3581. return false;
  3582. }
  3583. // 删除选中的 PDF 块
  3584. if (event.keyCode == 8 || event.keyCode == 46) {
  3585. if (_this.deleteSelectedPdf(editor)) {
  3586. event.stopPropagation();
  3587. event.preventDefault();
  3588. return false;
  3589. }
  3590. }
  3591. // tab 转空格
  3592. if (event.keyCode == 9) {
  3593. const model = editor.model;
  3594. model.change(writer => {
  3595. const ele = writer.createElement('span');
  3596. writer.insertText(" ", ele);
  3597. // 一定要 Element
  3598. model.insertContent(ele);
  3599. });
  3600. event.stopPropagation();
  3601. return false;
  3602. }
  3603. _this.deferEmitEditorHtml();
  3604. };
  3605. // 设置编辑器宽度
  3606. if (_this.width) {
  3607. $(editor.ui.view.element).css({
  3608. 'width': _this.width
  3609. })
  3610. }
  3611. // 监听编辑器的内容变动事件
  3612. editor.model.document.on('change:data', function () {
  3613. _this.deferEmitEditorHtml();
  3614. _this.deferSyncEditorPlayableVideos();
  3615. });
  3616. }).catch(error => {
  3617. console.log(error);
  3618. });
  3619. }
  3620. },
  3621. template: `
  3622. <div class="space-editor-wrap">
  3623. <div class="space-editor-toolstrip" v-if="showEditorTools()">
  3624. <el-button class="space-editor-tool-btn" size="small" plain icon="el-icon-document" @click="openWordImporter">导入word文件</el-button>
  3625. <el-button class="space-editor-tool-btn" size="small" plain icon="el-icon-video-camera" @click="openVideoPicker">上传视频</el-button>
  3626. <el-button class="space-editor-tool-btn" size="small" plain icon="el-icon-document" @click="openPdfPicker">上传PDF</el-button>
  3627. <span class="space-editor-tool-divider"></span>
  3628. <el-select class="space-editor-quality" v-model="imageQuality" size="small" placeholder="图片质量压缩" title="图片质量压缩">
  3629. <el-option label="原图" value="origin"></el-option>
  3630. <el-option label="高清 85%" value="high"></el-option>
  3631. <el-option label="标准 70%" value="standard"></el-option>
  3632. <el-option label="低流量 50%" value="low"></el-option>
  3633. </el-select>
  3634. <el-button class="space-editor-tool-btn space-editor-preview-btn" size="small" type="primary" plain icon="el-icon-view" @click="openArticlePreview" :loading="previewLoading">三端预览</el-button>
  3635. <template v-if="activePdf && activePdf.src">
  3636. <span class="space-editor-tool-divider"></span>
  3637. <span class="space-editor-pdf-secure-tools">
  3638. <span class="space-editor-pdf-secure-label-text">PDF 安全模式</span>
  3639. <el-switch v-model="activePdf.secure" active-value="1" inactive-value="0" @change="applyActivePdfSecure"></el-switch>
  3640. <a class="space-editor-pdf-download-original" :href="activePdf.src" target="_blank" rel="noopener">下载原文件</a>
  3641. </span>
  3642. </template>
  3643. <span class="space-editor-upload-status" v-if="uploadStatus">{{uploadStatus}}</span>
  3644. </div>
  3645. <div class="space-editor-pdf-float-toolbar" v-if="activePdf && activePdf.src && pdfFloatToolbarStyle" :style="pdfFloatToolbarStyle">
  3646. <div class="space-editor-pdf-toolbar-left"><span class="space-editor-pdf-toolbar-title">PDF 预览</span></div>
  3647. <div class="space-editor-pdf-toolbar-right">
  3648. <label class="space-editor-pdf-secure-switch">
  3649. <input type="checkbox" class="space-editor-pdf-secure-toggle" :checked="activePdf.secure === '1'" @change="applyActivePdfSecure($event.target.checked ? '1' : '0')">
  3650. <span class="space-editor-pdf-secure-label">安全模式</span>
  3651. </label>
  3652. <a class="space-editor-pdf-download-original" :href="activePdf.src" target="_blank" rel="noopener">下载原文件</a>
  3653. </div>
  3654. </div>
  3655. <input ref="videoInput" type="file" accept="video/*" style="display:none;" @change="handleVideoSelect">
  3656. <input ref="pdfInput" type="file" accept="application/pdf,.pdf" style="display:none;" @change="handlePdfSelect">
  3657. <input ref="attachmentInput" type="file" style="display:none;" @change="handleAttachmentSelect">
  3658. <div :id="id">
  3659. <script type="text/plain"></script>
  3660. </div>
  3661. <el-dialog title="正文预览" :visible.sync="previewVisible" width="calc(100vw - 32px)" top="4vh" append-to-body custom-class="space-editor-preview-dialog">
  3662. <div class="space-editor-preview-toolbar">
  3663. <el-button-group class="space-editor-preview-modes">
  3664. <el-button size="small" :type="previewMode == 'pc' ? 'primary' : 'default'" @click="setPreviewMode('pc')">PC端</el-button>
  3665. <el-button size="small" :type="previewMode == 'pad' ? 'primary' : 'default'" @click="setPreviewMode('pad')">平板端</el-button>
  3666. <el-button size="small" :type="previewMode == 'mobile' ? 'primary' : 'default'" @click="setPreviewMode('mobile')">手机端</el-button>
  3667. </el-button-group>
  3668. <el-button size="small" icon="el-icon-refresh" @click="openArticlePreview" :loading="previewLoading">刷新预览</el-button>
  3669. </div>
  3670. <div class="space-editor-preview-stage">
  3671. <iframe v-if="previewUrl" :key="previewMode + previewUrl" :src="previewUrl" :style="previewFrameStyle" frameborder="0" @load="handlePreviewFrameLoad"></iframe>
  3672. </div>
  3673. </el-dialog>
  3674. </div>
  3675. `
  3676. })
  3677. /**
  3678. * CMS
  3679. */
  3680. Vue.component('spaceCms', {
  3681. data: function () {
  3682. return {
  3683. fileCount: 0, // 文件总数
  3684. }
  3685. },
  3686. name: "spaceCms",
  3687. model: {
  3688. prop: 'cmsid',
  3689. evnet: 'click'
  3690. },
  3691. props: {
  3692. // v-model
  3693. cmsid: {
  3694. type: [String],
  3695. required: true
  3696. },
  3697. // 文件类型
  3698. accept: {
  3699. type: String
  3700. },
  3701. // 最大上传数量,默认199
  3702. maxsize: {
  3703. type: [String, Number],
  3704. default: 199
  3705. },
  3706. },
  3707. created: function () {
  3708. this.getCmsFileCount(this.cmsid);
  3709. },
  3710. watch: {
  3711. cmsid: function (newVal, oldVal) {
  3712. this.getCmsFileCount(newVal);
  3713. }
  3714. },
  3715. methods: {
  3716. open: function () {
  3717. var that = this;
  3718. space.plugins.cms.openCMS({
  3719. cmsid: that.cmsid,
  3720. accept: that.accept,
  3721. maxsize: that.maxsize
  3722. }, that.callback);
  3723. },
  3724. callback: function (data, callback2) {
  3725. this.$emit("input", data.cmsid);
  3726. this.cmsid = data.cmsid;
  3727. this.fileCount = data.fileCount;
  3728. callback2();
  3729. },
  3730. getCmsFileCount: function (cmsid) {
  3731. if (space.utils.isNull(cmsid)) {
  3732. return;
  3733. }
  3734. var that = this;
  3735. space.utils.ajax({
  3736. url: '/apps?ark=sys.cms_getCmsInfo',
  3737. data: {
  3738. "idcard": cmsid
  3739. },
  3740. dataType: 'json',
  3741. loadLayer: false,
  3742. autoTip: false,
  3743. async: false, // 同步请求
  3744. callback: function (data) {
  3745. if (data.code == "success") {
  3746. that.fileCount = data.data.filecount;
  3747. }
  3748. }
  3749. });
  3750. }
  3751. },
  3752. template: `<div class="cms-upload">
  3753. <el-badge :value="fileCount" type="primary" v-show="fileCount > 0">
  3754. <el-button icon="el-icon-upload2" @click="open" >上传文件</el-button>
  3755. </el-badge>
  3756. <el-button icon="el-icon-upload2" v-show="fileCount == 0" @click="open" >上传文件</el-button>
  3757. </div>`
  3758. })
  3759. /**
  3760. * CMS预览
  3761. */
  3762. Vue.component('spaceCmsView', {
  3763. data: function () {
  3764. return {
  3765. thumbnail: "",
  3766. filename: "",
  3767. filecount: 0,
  3768. isShowEl: true, //是否显示整个组件元素
  3769. }
  3770. },
  3771. name: "spaceCmsView",
  3772. /**
  3773. * cmsid: 绑定的值,非空
  3774. * thumbnail: 缩略图
  3775. * filename: 文件名
  3776. * filecount: 文件数
  3777. */
  3778. props: {
  3779. cmsid: {
  3780. type: [String, Number],
  3781. required: true
  3782. }
  3783. },
  3784. created: function () {
  3785. var that = this;
  3786. if (space.utils.isNull(that.cmsid)) {
  3787. // 不显示整个组件元素
  3788. that.isShowEl = false;
  3789. return;
  3790. }
  3791. space.utils.ajax({
  3792. url: '/apps?ark=sys.cms_getCmsInfo',
  3793. data: {
  3794. "idcard": that.cmsid
  3795. },
  3796. dataType: 'json',
  3797. loadLayer: false,
  3798. autoTip: false,
  3799. async: false, // 同步请求
  3800. callback: function (data) {
  3801. if (data.code == "success") {
  3802. that.thumbnail = data.data.thumbnail;
  3803. that.filename = data.data.filename;
  3804. that.filecount = data.data.filecount;
  3805. } else if (data.code == "warning") {
  3806. // 不显示整个组件元素
  3807. that.isShowEl = false;
  3808. }
  3809. }
  3810. });
  3811. },
  3812. methods: {
  3813. open: function () {
  3814. var that = this;
  3815. space.plugins.cms.openCMSView({
  3816. cmsid: that.cmsid
  3817. });
  3818. },
  3819. },
  3820. template: `
  3821. <div class="space-cms-view" v-if="isShowEl">
  3822. <div class="space-cms-view-wrap" @click="open">
  3823. <div class="space-cms-view-main">
  3824. <el-image :src="thumbnail">
  3825. <div slot="error" class="image-slot">
  3826. <i class="el-icon-picture-outline"></i>
  3827. </div>
  3828. </el-image>
  3829. <span>{{filename}}</span>
  3830. </div>
  3831. <div v-show="filecount >=2 " class="more-file"></div>
  3832. <div v-show="filecount >=2 " class="more-file more-file-bottom"></div>
  3833. </div>
  3834. </div>
  3835. `
  3836. })
  3837. /**
  3838. * 业务流转
  3839. */
  3840. Vue.component('spacePluginFlow', {
  3841. data: function () {
  3842. return {
  3843. isOpenFlowDrawer: false, // 是否打开抽屉
  3844. isLoadShow: true, // 是否显示加载动画
  3845. frameID: space.utils.randomStringAndNumber(6) + 'Frm', // frame 窗口ID
  3846. closeBtnID: space.utils.randomStringAndNumber(6) + 'Close', // 关闭按钮的ID
  3847. url: '/app/flow/time/', // url
  3848. title: '业务流转', // 标题
  3849. closeTitle: '收起', // 关闭按钮文本内容
  3850. }
  3851. },
  3852. name: "spacePluginFlow",
  3853. /**
  3854. * cmsid: 绑定的值,非空
  3855. * size: 抽屉大小,可传px、%,默认30%
  3856. */
  3857. props: {
  3858. audit: {
  3859. type: String,
  3860. required: true
  3861. },
  3862. apply: {
  3863. type: String,
  3864. required: true
  3865. },
  3866. open: {
  3867. type: Boolean,
  3868. },
  3869. size: {
  3870. type: String
  3871. },
  3872. },
  3873. created: function () {
  3874. this.url = this.url + "?auditid=" + this.audit + "&applyid=" + this.apply;
  3875. this.size = space.utils.isNull(this.size) ? '360px' : this.size;
  3876. this.isOpenFlowDrawer = space.utils.isNull(this.open) ? false : this.open;
  3877. this.showLoad();
  3878. },
  3879. mounted: function () {
  3880. var that = this;
  3881. // 监听窗口变化,计算关闭按钮的位置
  3882. window.onresize = function () {
  3883. // 抽屉打开状态
  3884. if (that.isOpenFlowDrawer) {
  3885. that.initCloseBtnLocation();
  3886. }
  3887. }
  3888. },
  3889. methods: {
  3890. /**
  3891. * 计算关闭按钮的坐标
  3892. */
  3893. initCloseBtnLocation: function () {
  3894. var offset = space.utils.getDomPosition(document.getElementById(this.frameID));
  3895. $("#" + this.closeBtnID).css("left", (offset.left - $("#" + this.closeBtnID).width()) + "px");
  3896. },
  3897. /**
  3898. * 显示抽屉
  3899. */
  3900. showDrawer: function () {
  3901. var that = this;
  3902. that.initCloseBtnLocation();
  3903. $("#" + that.closeBtnID).fadeIn(200);
  3904. // 为了更好的动画体验
  3905. setTimeout(() => {
  3906. $("#" + that.closeBtnID).css("z-index", "999999999999999");
  3907. }, 200);
  3908. },
  3909. /**
  3910. * 控制加载动画
  3911. */
  3912. showLoad: function () {
  3913. var that = this;
  3914. var loadInterval = setInterval(() => {
  3915. var frameEle = document.getElementById(that.frameID);
  3916. console.log("loadInterval");
  3917. frameEle.onload = function () {
  3918. window.clearInterval(loadInterval);
  3919. that.isLoadShow = false;
  3920. }
  3921. }, 100);
  3922. }
  3923. },
  3924. watch: {
  3925. isOpenFlowDrawer: function (newVal, oldVal) {
  3926. var that = this;
  3927. // 打开
  3928. if (newVal) {
  3929. var getFrameInterval = setInterval(() => {
  3930. var frameEle = document.getElementById(that.frameID);
  3931. if (!frameEle) {
  3932. return;
  3933. }
  3934. window.clearInterval(getFrameInterval);
  3935. that.showDrawer();
  3936. }, 200);
  3937. }
  3938. // 关闭
  3939. else {
  3940. $("#" + that.closeBtnID).hide();
  3941. $("#" + that.closeBtnID).css("z-index", "");
  3942. }
  3943. },
  3944. open: function (newVal, oldVal) {
  3945. this.isOpenFlowDrawer = space.utils.isNull(newVal) ? false : newVal;
  3946. }
  3947. },
  3948. template: `
  3949. <div class="space-app-plugin">
  3950. <div class="space-app-plugin-open disable-select animate__animated animate__slideInRight" v-show="!isOpenFlowDrawer" @click="isOpenFlowDrawer = true">{{title}}</div>
  3951. <div :id="closeBtnID" class="space-app-plugin-close disable-select animate__animated animate__slideInRight" @click="isOpenFlowDrawer = false">{{closeTitle}}</div>
  3952. <el-drawer :modal="false" :visible.sync="isOpenFlowDrawer" :size="size" :with-header="false" :wrapper-closable="false" >
  3953. <iframe :id="frameID" :src="url"></iframe>
  3954. <div class="space-app-plugin-load" v-show="isLoadShow" ><i class="el-icon-loading" ></i>加载中</div>
  3955. </el-drawer>
  3956. </div>
  3957. `
  3958. })