o2.js 159 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750
  1. /** ***** BEGIN LICENSE BLOCK *****
  2. * |------------------------------------------------------------------------------|
  3. * | O2OA 活力办公 创意无限 o2.js |
  4. * |------------------------------------------------------------------------------|
  5. * | Distributed under the AGPL license: |
  6. * |------------------------------------------------------------------------------|
  7. * | Copyright © 2018, o2oa.net, o2server.io O2 Team |
  8. * | All rights reserved. |
  9. * |------------------------------------------------------------------------------|
  10. *
  11. * This file is part of O2OA.
  12. *
  13. * O2OA is free software: you can redistribute it and/or modify
  14. * it under the terms of the GNU Affero General Public License as published by
  15. * the Free Software Foundation, either version 3 of the License, or
  16. * (at your option) any later version.
  17. *
  18. * O2OA is distributed in the hope that it will be useful,
  19. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  21. * GNU Affero General Public License for more details.
  22. *
  23. * You should have received a copy of the GNU General Public License
  24. * along with O2OA. If not, see <https://www.gnu.org/licenses/>.
  25. *
  26. * ***** END LICENSE BLOCK ******/
  27. /* load o2 Core
  28. * |------------------------------------------------------------------------------|
  29. * |addReady: o2.addReady(fn), |
  30. * |------------------------------------------------------------------------------|
  31. * |load: o2.load(urls, callback, reload) |
  32. * |loadCss: o2.loadCss(urls, dom, callback, reload, doc) |
  33. * |------------------------------------------------------------------------------|
  34. * |typeOf: o2.typeOf(o) |
  35. * |------------------------------------------------------------------------------|
  36. * |uuid: o2.uuid() |
  37. * |------------------------------------------------------------------------------|
  38. */
  39. //Element.firstElementChild Polyfill
  40. // (function(constructor) {
  41. // if (constructor &&
  42. // constructor.prototype &&
  43. // constructor.prototype.firstElementChild == null) {
  44. // Object.defineProperty(constructor.prototype, 'firstElementChild', {
  45. // get: function() {
  46. // var node, nodes = this.childNodes, i = 0;
  47. // while (node = nodes[i++]) {
  48. // if (node.nodeType === 1) {
  49. // return node;
  50. // }
  51. // }
  52. // return null;
  53. // }
  54. // });
  55. // }
  56. // })(window.Node || window.Element);
  57. if (window.Promise && !Promise.any){
  58. Promise.any = function(promises){
  59. if (!promises || !promises.length) return new Promise();
  60. return new Promise(function(resolve){
  61. var value = null;
  62. var resolved = false;
  63. var checkValue = function(){
  64. if (resolved) resolve(value);
  65. };
  66. for (var i=0; i<promises.length; i++){
  67. promises[i],then(function(v){
  68. value == v;
  69. resolved = true;
  70. checkValue();
  71. });
  72. }
  73. });
  74. }
  75. }
  76. if (!window.o2) {
  77. (function () {
  78. var _language = ""
  79. try {
  80. _language = localStorage.getItem("o2.language");
  81. } catch (e) {};
  82. var _href = window.location.href;
  83. var _debug = (_href.indexOf("debugger") !== -1);
  84. var _par = _href.substr(_href.lastIndexOf("?") + 1, _href.length);
  85. // var supportedLanguages = ["zh-cn", "en", "es", "ko", "zh-tw", "zh-hk", "ja"];
  86. var _lp = _language || navigator.language || "zh-cn";
  87. //if (!_lp) _lp = "zh-cn";
  88. if (_par) {
  89. var _parList = _par.split("&");
  90. for (var i = 0; i < _parList.length; i++) {
  91. var _v = _parList[i];
  92. var _kv = _v.split("=");
  93. if (_kv[0].toLowerCase() === "lg") _lp = _kv[1];
  94. if (_kv[0].toLowerCase() === "lp") _lp = _kv[1];
  95. }
  96. }
  97. /**
  98. * @summary 平台全局对象,在前端(浏览器/移动端H5页面)可用。<br/>
  99. * @namespace o2
  100. * @o2cn 平台全局对象
  101. * @o2category web
  102. */
  103. this.o2 = window.o2 || {};
  104. /**
  105. * @summary 平台版本信息。
  106. * @member {Object} version
  107. * @memberOf o2
  108. * @o2syntax
  109. * //获取版本号
  110. * var v = o2.version.v;
  111. */
  112. this.o2.version = {
  113. "v": "o2oa",
  114. "build": "2022.09.13",
  115. "info": "O2OA 活力办公 创意无限. Copyright © 2022, o2oa.net O2 Team All rights reserved."
  116. };
  117. /**
  118. * @summary 平台运行环境。
  119. * @member {Object} session
  120. * @memberOf o2
  121. * @property {Boolean} isDebugger 是否是调试模式
  122. * @property {Boolean} isMobile 是否是移动端环境
  123. * @o2syntax
  124. * var debuggerMode = o2.session.isDebugger;
  125. * var ismobile = o2.session.isMobile;
  126. */
  127. if (!this.o2.session) this.o2.session = {
  128. "isDebugger": _debug,
  129. "path": "../o2_core/o2"
  130. };
  131. /**
  132. * @summary 语言环境名称。
  133. * @member {String} language
  134. * @memberOf o2
  135. * @o2syntax
  136. * var lp = o2.language;
  137. */
  138. this.o2.languageName = _lp;
  139. _lp = _lp.toLocaleLowerCase();
  140. // if (supportedLanguages.indexOf(_lp) == -1){
  141. // _lp = _lp.substring(0, _lp.indexOf('-'));
  142. // }
  143. // if (supportedLanguages.indexOf(_lp) == -1) _lp = "zh-cn";
  144. this.o2.language = _lp;
  145. this.o2.splitStr = /\s*(?:,|;)\s*/;
  146. this.wrdp = this.o2;
  147. var debug = function (reload) {
  148. if (!o2.session.isMobile) {
  149. window.location.assign(_href + ((_href.indexOf("?") == -1) ? "?" : "&") + "debugger");
  150. } else {
  151. if (!o2.session.isDebugger) {
  152. o2.session.isDebugger = true;
  153. if (o2.session.isMobile || layout.mobile) o2.load("../o2_lib/eruda/eruda.js");
  154. }
  155. }
  156. };
  157. /**
  158. * @summary 使平台进入调试模式。
  159. * @function debug
  160. * @memberOf o2
  161. * @o2syntax
  162. * o2.debug();
  163. */
  164. this.o2.debug = debug;
  165. this.o2.runningRequestsList = [];
  166. var o2 = this.o2;
  167. var requestSend = XMLHttpRequest.prototype.send;
  168. var requestOpen = XMLHttpRequest.prototype.open;
  169. XMLHttpRequest.prototype.send = function(){
  170. var request = this;
  171. o2.runningRequestsList.push(request);
  172. request.addEventListener("loadend", function(){
  173. o2.runningRequestsList.splice(o2.runningRequestsList.indexOf(request, 1));
  174. });
  175. requestSend.apply(this, arguments);
  176. }
  177. XMLHttpRequest.prototype.open = function(){
  178. var request = this;
  179. request.requestOptions = Array.from(arguments);
  180. requestOpen.apply(this, arguments);
  181. }
  182. var _attempt = function () {
  183. for (var i = 0, l = arguments.length; i < l; i++) {
  184. try {
  185. arguments[i]();
  186. return arguments[i];
  187. } catch (e) {
  188. }
  189. }
  190. return null;
  191. };
  192. var _typeOf = function (item) {
  193. if (item == null) return 'null';
  194. if (item.$family != null) return item.$family();
  195. if (item.constructor == window.Array) return "array";
  196. if (item.nodeName) {
  197. if (item.nodeType == 1) return 'element';
  198. if (item.nodeType == 3) return (/\S/).test(item.nodeValue) ? 'textnode' : 'whitespace';
  199. } else if (typeof item.length == 'number') {
  200. if (item.callee) return 'arguments';
  201. }
  202. return typeof item;
  203. };
  204. /**
  205. * @summary 判断一个任意参数的类型。
  206. * @function typeOf
  207. * @memberOf o2
  208. * @param {Object} [obj] 要检查的对象
  209. * @return {String} 对象的类型,返回值:
  210. * <pre><code class="language-js">'element' - 如果obj是一个DOM Element对象.
  211. * 'elements' - 如果obj是一个Elements实例.
  212. * 'textnode' - 如果obj是一个DOM text节点.
  213. * 'whitespace' - 如果obj是一个DOM whitespace 节点.
  214. * 'arguments' - 如果obj是一个arguments对象.
  215. * 'array' - 如果obj是一个array数组.
  216. * 'object' - 如果obj是一个object对象.
  217. * 'string' - 如果obj是一个string.
  218. * 'number' - 如果obj是一个数字number.
  219. * 'date' - 如果obj是一个日期date.
  220. * 'boolean' - 如果obj是一个布尔值boolean.
  221. * 'function' - 如果obj是一个function.
  222. * 'regexp' - 如果obj是一个正则表达式.
  223. * 'collection' - 如果obj是一个原生HTML elements collection, 如childNodes or getElementsByTagName获取的对象.
  224. * 'window' - 如果obj是window对象.
  225. * 'document' - 如果obj是document对象.
  226. * 'domevent' - 如果obj是一个event.
  227. * 'null' - 如果obj是undefined, null, NaN 或者 none.
  228. * </code></pre>
  229. * @o2syntax
  230. * o2.typeOf(obj);
  231. * @example
  232. * var myString = 'hello';
  233. * o2.typeOf(myString); // returns "string"
  234. */
  235. this.o2.typeOf = _typeOf;
  236. var _addListener = function (dom, type, fn) {
  237. if (type == 'unload') {
  238. var old = fn, self = this;
  239. fn = function () {
  240. _removeListener(dom, 'unload', fn);
  241. old();
  242. };
  243. }
  244. if (dom.addEventListener) dom.addEventListener(type, fn, !!arguments[2]);
  245. else dom.attachEvent('on' + type, fn);
  246. };
  247. var _removeListener = function (dom, type, fn) {
  248. if (dom.removeEventListener) dom.removeEventListener(type, fn, !!arguments[2]);
  249. else dom.detachEvent('on' + type, fn);
  250. };
  251. //http request class
  252. var _request = (function () {
  253. var XMLHTTP = function () {
  254. return new XMLHttpRequest();
  255. };
  256. var MSXML2 = function () {
  257. return new ActiveXObject('MSXML2.XMLHTTP');
  258. };
  259. var MSXML = function () {
  260. return new ActiveXObject('Microsoft.XMLHTTP');
  261. };
  262. return _attempt(XMLHTTP, MSXML2, MSXML);
  263. })();
  264. this.o2.request = _request;
  265. var _returnBase = function (number, base) {
  266. return (number).toString(base).toUpperCase();
  267. };
  268. var _getIntegerBits = function (val, start, end) {
  269. var base16 = _returnBase(val, 16);
  270. var quadArray = new Array();
  271. var quadString = '';
  272. var i = 0;
  273. for (i = 0; i < base16.length; i++) {
  274. quadArray.push(base16.substring(i, i + 1));
  275. }
  276. for (i = Math.floor(start / 4); i <= Math.floor(end / 4); i++) {
  277. if (!quadArray[i] || quadArray[i] == '')
  278. quadString += '0';
  279. else
  280. quadString += quadArray[i];
  281. }
  282. return quadString;
  283. };
  284. var _rand = function (max) {
  285. return Math.floor(Math.random() * (max + 1));
  286. };
  287. this.o2.addListener = _addListener;
  288. this.o2.removeListener = _removeListener;
  289. //uuid
  290. var _uuid = function () {
  291. var dg = new Date(1582, 10, 15, 0, 0, 0, 0);
  292. var dc = new Date();
  293. var t = dc.getTime() - dg.getTime();
  294. var tl = _getIntegerBits(t, 0, 31);
  295. var tm = _getIntegerBits(t, 32, 47);
  296. var thv = _getIntegerBits(t, 48, 59) + '1';
  297. var csar = _getIntegerBits(_rand(4095), 0, 7);
  298. var csl = _getIntegerBits(_rand(4095), 0, 7);
  299. var n = _getIntegerBits(_rand(8191), 0, 7)
  300. + _getIntegerBits(_rand(8191), 8, 15)
  301. + _getIntegerBits(_rand(8191), 0, 7)
  302. + _getIntegerBits(_rand(8191), 8, 15)
  303. + _getIntegerBits(_rand(8191), 0, 15);
  304. return tl + tm + thv + csar + csl + n;
  305. };
  306. /**
  307. * @summary 生成一个唯一的uuid。
  308. * @function uuid
  309. * @memberOf o2
  310. * @o2syntax
  311. * var id = o2.uuid();
  312. */
  313. this.o2.uuid = _uuid;
  314. var _runCallback = function (callback, key, par, bind, promise_cb) {
  315. var b = bind || callback;
  316. if (!key) key = "success";
  317. var cb;
  318. if (callback) {
  319. var type = o2.typeOf(callback).toLowerCase();
  320. if (key.toLowerCase() === "success" && type === "function") {
  321. cb = callback;
  322. } else {
  323. var name = ("on-" + key).camelCase();
  324. cb = (callback[name]) ? callback[name] : ((callback[key]) ? callback[key] : null);
  325. }
  326. }
  327. if (cb) return cb.apply(b, par);
  328. };
  329. this.o2.runCallback = _runCallback;
  330. if (window.CustomEvent) this.o2.customEventLoad = new CustomEvent("o2load");
  331. //load js, css, html adn all.
  332. var _getAllOptions = function (options) {
  333. var doc = (options && options.doc) || document;
  334. if (!doc.unid) doc.unid = _uuid();
  335. var type = (options && options.type) || "text/javascript";
  336. return {
  337. "noCache": !!(options && options.nocache),
  338. "reload": !!(options && options.reload),
  339. "sequence": !!(options && options.sequence),
  340. "type": type,
  341. "doc": doc,
  342. "dom": (options && options.dom) || document.body,
  343. "module": (options && options.module) || null,
  344. "noConflict": (options && options.noConflict) || false,
  345. "url": !!(options && options.url),
  346. "bind": (options && options.bind) || null,
  347. "evalScripts": (options && options.evalScripts) || false,
  348. "baseUrl": (options && options.baseUrl) ? options.baseUrl : "",
  349. "position": (options && options.position) || "beforeend" //'beforebegin' 'afterbegin' 'beforeend' 'afterend'debugger
  350. }
  351. };
  352. var _getCssOptions = function (options) {
  353. var doc = (options && options.doc) || document;
  354. if (!doc.unid) doc.unid = _uuid();
  355. return {
  356. "url": !!(options && options.url),
  357. "noCache": !!(options && options.nocache),
  358. "reload": !!(options && options.reload),
  359. "sequence": !!(options && options.sequence),
  360. "doc": doc,
  361. "dom": (options && options.dom) || null
  362. }
  363. };
  364. var _getJsOptions = function (options) {
  365. var doc = (options && options.doc) || document;
  366. if (!doc.unid) doc.unid = _uuid();
  367. var type = (options && options.type) || "text/javascript";
  368. return {
  369. "noCache": !!(options && options.nocache),
  370. "reload": !!(options && options.reload),
  371. "sequence": (!(options && options.sequence == false)),
  372. "type": type,
  373. "baseUrl": (options && options.baseUrl) ? options.baseUrl : "",
  374. "doc": doc
  375. }
  376. };
  377. var _getHtmlOptions = function (options) {
  378. var doc = (options && options.doc) || document;
  379. if (!doc.unid) doc.unid = _uuid();
  380. return {
  381. "noCache": !!(options && options.nocache),
  382. "reload": !!(options && options.reload),
  383. "sequence": !!(options && options.sequence),
  384. "doc": doc,
  385. "dom": (options && options.dom) || null,
  386. "module": (options && options.module) || null,
  387. "noConflict": (options && options.noConflict) || false,
  388. "bind": (options && options.bind) || null,
  389. "evalScripts": (options && options.evalScripts) || false,
  390. "baseUrl": (options && options.baseUrl) ? options.baseUrl : "",
  391. "position": (options && options.position) || "beforeend" //'beforebegin' 'afterbegin' 'beforeend' 'afterend'
  392. }
  393. };
  394. _filterUrl = function (url) {
  395. if (o2.base) {
  396. if (url.indexOf(":") === -1) {
  397. var s = url.substring(0, url.indexOf("/") + 1);
  398. var r = url.substring(url.indexOf("/") + 1, url.length);
  399. if ("../" === s || "./" === s || "/" === s) {
  400. return s + o2.base + r;
  401. } else {
  402. return o2.base + url
  403. }
  404. }
  405. }
  406. if (window.layout && layout.config && layout.config.urlMapping) {
  407. for (var k in layout.config.urlMapping) {
  408. var regex = new RegExp(k);
  409. if (regex.test(url)) {
  410. return url.replace(regex, layout.config.urlMapping[k]);
  411. }
  412. }
  413. }
  414. return url;
  415. };
  416. /**
  417. * @summary 解析平台内的url,如果配置了反向代理的路径转发,平台内的url需要通过filterUrl解析后,才能得到正确的url。
  418. * @see {@link https://www.o2oa.net/search.html?q=urlmapping|基于nginx快速集群部署-上下文分发}
  419. * @function filterUrl
  420. * @memberOf o2
  421. * @param {String} [url] 要解析的url
  422. * @return {String} 解析后的url
  423. * @o2syntax
  424. * var url = o2.filterUrl(url);
  425. * @example
  426. * <caption>
  427. * 当我们配置了按路径转发后,在portal.json中配置了urlMapping如:
  428. * <pre><code class="language-js">"urlMapping": {
  429. * "qmx.o2oa.net:20020": "qmx.o2oa.net/dev/app",
  430. * "qmx.o2oa.net:20030": "qmx.o2oa.net/dev/center"
  431. * },</code></pre>
  432. * 在获取平台内部的url时,如附件的下载地址,需要通过filterUrl解析。
  433. * </caption>
  434. * var attachmentUrl = "http://qmx.o2oa.net:20020/x_processplatform_assemble_surface/jaxrs/attachment/{attid}/work/{workid}";
  435. * var url = o2.filterUrl(attachmentUrl);
  436. * //return "http://qmx.o2oa.net/dev/app/x_processplatform_assemble_surface/jaxrs/attachment/{attid}/work/{workid}"
  437. */
  438. this.o2.filterUrl = _filterUrl;
  439. var _xhr_get = function (url, success, failure, completed, sync) {
  440. var xhr = new _request();
  441. url = _filterUrl(url);
  442. xhr.open("GET", url, !sync);
  443. var _checkCssLoaded = function (_, err) {
  444. if (!(xhr.readyState == 4)) return;
  445. if (err) {
  446. if (completed) completed(xhr);
  447. return;
  448. }
  449. _removeListener(xhr, 'readystatechange', _checkCssLoaded);
  450. _removeListener(xhr, 'load', _checkCssLoaded);
  451. _removeListener(xhr, 'error', _checkCssErrorLoaded);
  452. if (err) {
  453. if (failure) failure(xhr);
  454. return
  455. }
  456. var status = xhr.status;
  457. status = (status == 1223) ? 204 : status;
  458. if ((status >= 200 && status < 300))
  459. if (success) success(xhr);
  460. else if ((status >= 300 && status < 400))
  461. if (failure) failure(xhr);
  462. else
  463. failure(xhr);
  464. if (completed) completed(xhr);
  465. };
  466. var _checkCssErrorLoaded = function (err) {
  467. _checkCssLoaded(err)
  468. };
  469. if ("load" in xhr) _addListener(xhr, "load", _checkCssLoaded);
  470. if ("error" in xhr) _addListener(xhr, "load", _checkCssErrorLoaded);
  471. _addListener(xhr, "readystatechange", _checkCssLoaded);
  472. xhr.send();
  473. };
  474. this.o2.xhr_get = _xhr_get;
  475. var _loadSequence = function (ms, cb, op, n, thisLoaded, loadSingle, uuid, fun) {
  476. loadSingle(ms[n], function (module) {
  477. if (module) thisLoaded.push(module);
  478. n++;
  479. if (fun) fun(module);
  480. if (n === ms.length) {
  481. if (cb) cb(thisLoaded);
  482. } else {
  483. _loadSequence(ms, cb, op, n, thisLoaded, loadSingle, uuid, fun);
  484. }
  485. }, op, uuid);
  486. };
  487. var _loadDisarray = function (ms, cb, op, thisLoaded, loadSingle, uuid, fun) {
  488. var count = 0;
  489. for (var i = 0; i < ms.length; i++) {
  490. loadSingle(ms[i], function (module) {
  491. if (module) thisLoaded.push(module);
  492. count++;
  493. if (fun) fun(module);
  494. if (count === ms.length) if (cb) cb(thisLoaded);
  495. }, op, uuid);
  496. }
  497. };
  498. //load js
  499. //use framework url
  500. var _frameworks = {
  501. "o2.core": ["../o2_core/o2/o2.core.js"],
  502. "o2.more": ["../o2_core/o2/o2.more.js"],
  503. "ie_adapter": ["../o2_core/o2/ie_adapter.js"],
  504. "jquery": ["../o2_lib/jquery/jquery.min.js"],
  505. "mootools": ["../o2_lib/mootools/mootools-1.6.0_all.js"],
  506. "ckeditor": ["../o2_lib/htmleditor/ckeditor4161/ckeditor.js"],
  507. "ckeditor5": ["../o2_lib/htmleditor/ckeditor5-12-1-0/ckeditor.js"],
  508. "raphael": ["../o2_lib/raphael/raphael.js"],
  509. "d3": ["../o2_lib/d3/d3.min.js"],
  510. "ace": ["../o2_lib/ace/src-min-noconflict/ace.js", "../o2_lib/ace/src-min-noconflict/ext-language_tools.js"],
  511. //"ace": ["../o2_lib/ace/src-noconflict/ace.js","../o2_lib/ace/src-noconflict/ext-language_tools.js"],
  512. "monaco": ["../o2_lib/vs/loader.js"],
  513. "JSBeautifier": ["../o2_lib/JSBeautifier/beautify.js"],
  514. "JSBeautifier_css": ["../o2_lib/JSBeautifier/beautify-css.js"],
  515. "JSBeautifier_html": ["../o2_lib/JSBeautifier/beautify-html.js"],
  516. "JSONTemplate": ["../o2_lib/mootools/plugin/Template.js"],
  517. "kity": ["../o2_lib/kityminder/kity/kity.js"],
  518. "kityminder": ["../o2_lib/kityminder/core/dist/kityminder.core.js"],
  519. "vue": ["../o2_lib/vue/vue.pro.js"],
  520. "vue_develop": ["../o2_lib/vue/vue.js"],
  521. "elementui": ["../o2_lib/vue/element/index.js"]
  522. };
  523. var _loaded = {};
  524. var _loadedCss = {};
  525. var _loadedHtml = {};
  526. var _loadCssRunning = {};
  527. var _loadCssQueue = [];
  528. var _loadingModules = {};
  529. var _checkUrl = function (url, base) {
  530. var urlStr = new URI(url, {base: base}).toString();
  531. return urlStr;
  532. }
  533. var _loadSingle = function (module, callback, op) {
  534. var url = module;
  535. if (op.baseUrl) url = _checkUrl(url, op.baseUrl);
  536. var uuid = _uuid();
  537. if (op.noCache) url = (url.indexOf("?") !== -1) ? url + "&v=" + uuid : addr_uri + "?v=" + uuid;
  538. var key = encodeURIComponent(url + op.doc.unid);
  539. if (!op.reload) if (_loaded[key]) {
  540. Promise.resolve(_loaded[key]).then(function(o){
  541. if (callback) callback(o);
  542. });
  543. //if (callback) callback();
  544. return;
  545. }
  546. if (_loadingModules[key] && !op.reload) {
  547. if (!_loadingModules[key].callbacks) _loadingModules[key].callbacks = [];
  548. _loadingModules[key].callbacks.push(callback);
  549. } else {
  550. _loadingModules[key] = {callbacks: [callback]};
  551. var head = (op.doc.head || op.doc.getElementsByTagName("head")[0] || op.doc.documentElement);
  552. var s = op.doc.createElement('script');
  553. s.type = op.type || "text/javascript";
  554. head.appendChild(s);
  555. s.id = uuid;
  556. s.src = this.o2.filterUrl(url);
  557. var _checkScriptLoaded = function (_, isAbort, err) {
  558. if (isAbort || !s.readyState || s.readyState === "loaded" || s.readyState === "complete") {
  559. var scriptObj = {"module": module, "id": uuid, "script": s, "doc": op.doc};
  560. if (!err) _loaded[key] = scriptObj;
  561. _removeListener(s, 'readystatechange', _checkScriptLoaded);
  562. _removeListener(s, 'load', _checkScriptLoaded);
  563. _removeListener(s, 'error', _checkScriptErrorLoaded);
  564. if (!isAbort || err) {
  565. if (err) {
  566. if (s) head.removeChild(s);
  567. while (_loadingModules[key].callbacks.length) {
  568. (_loadingModules[key].callbacks.shift())();
  569. }
  570. delete _loadingModules[key];
  571. //if (callback)callback();
  572. } else {
  573. //head.removeChild(s);
  574. while (_loadingModules[key].callbacks.length) {
  575. (_loadingModules[key].callbacks.shift())(scriptObj);
  576. }
  577. delete _loadingModules[key];
  578. //if (callback)callback(scriptObj);
  579. }
  580. }
  581. }
  582. };
  583. var _checkScriptErrorLoaded = function (e, err) {
  584. console.log("Error: load javascript module: " + module);
  585. _checkScriptLoaded(e, true, "error");
  586. };
  587. if ('onreadystatechange' in s) _addListener(s, 'readystatechange', _checkScriptLoaded);
  588. _addListener(s, 'load', _checkScriptLoaded);
  589. _addListener(s, 'error', _checkScriptErrorLoaded);
  590. }
  591. };
  592. var _load = function (urls, options, callback) {
  593. if (window.document && !window.importScripts) {
  594. var ms = (_typeOf(urls) === "array") ? urls : [urls];
  595. var op = (_typeOf(options) === "object") ? _getJsOptions(options) : _getJsOptions(null);
  596. var cbk = (_typeOf(options) === "function") ? options : callback;
  597. var cb = cbk;
  598. if (typeof define === 'function' && define.amd) {
  599. define.amd = false;
  600. cb = (cbk) ? function () {
  601. define.amd = true;
  602. cbk();
  603. } : function () {
  604. define.amd = true;
  605. }
  606. }
  607. var modules = [];
  608. for (var i = 0; i < ms.length; i++) {
  609. var url = ms[i];
  610. var module = _frameworks[url] || url;
  611. if (_typeOf(module) === "array") {
  612. modules = modules.concat(module)
  613. } else {
  614. modules.push(module)
  615. }
  616. }
  617. var thisLoaded = [];
  618. if (op.sequence) {
  619. _loadSequence(modules, cb, op, 0, thisLoaded, _loadSingle);
  620. } else {
  621. _loadDisarray(modules, cb, op, thisLoaded, _loadSingle);
  622. }
  623. } else {
  624. if (window.importScripts) {
  625. var ms = (_typeOf(urls) === "array") ? urls : [urls];
  626. ms.each(function (url) {
  627. window.importScripts(o2.filterUrl(url));
  628. });
  629. var cbk = (_typeOf(options) === "function") ? options : callback;
  630. if (cbk) cbk();
  631. }
  632. }
  633. };
  634. /**
  635. * @summary 引入外部javascript文件。
  636. * @function load
  637. * @memberOf o2
  638. * @param {String|Array} [urls] 要载入的js文件url,或要载入多个js问价的urls数组。
  639. * @param {Object|Function} [options|callback] 载入js文件的配置参数,或者载入成功后的回调。
  640. * <pre><code class="language-js">options参数格式如下:
  641. * {
  642. * "noCache": 是否使用缓存,默认true,
  643. * "reload": 如果相同路径的js文件已经加载了,是否重新载入,默认为:false
  644. * "sequence": 当urls参数为数组时,多个脚本文件是否按数组顺序依次载入,默认为false
  645. * "type": 载入脚本的类型,默认为"text/javascript"
  646. * "baseUrl": 要载入脚本的url的base路径,默认""
  647. * "doc": 要在哪个document对象中载入脚本文件,默认为当前document
  648. * }
  649. * </code></pre>
  650. * @param {Function} [callback] 可选参数,载入成功后的回调方法。
  651. * @o2syntax
  652. * o2.load(urls, options, callback);
  653. * @example
  654. * //载入jsfile1.js和js/jsfile2.js两个文件,它们是按顺序载入的
  655. * o2.load(["js/jsfile1.js", "js/jsfile2.js"], function(){
  656. * //js文件已经载入
  657. * });
  658. *
  659. * //载入jsfile1.js和js/jsfile2.js两个文件,它们是同时载入的
  660. * //并且无论是否已经加载过,都需要重新加载,并且要按顺序加载
  661. * o2.load(["js/jsfile1.js", "js/jsfile2.js"], {"reload": true, "sequence": true}, function(){
  662. * //js文件已经载入
  663. * });
  664. */
  665. this.o2.load = _load;
  666. //load css
  667. var _loadSingleCss = function (module, callback, op, uuid) {
  668. var url = module;
  669. var uid = _uuid();
  670. if (op.noCache) url = (url.indexOf("?") !== -1) ? url + "&v=" + uid : url + "?v=" + uid;
  671. var key = encodeURIComponent(url + op.doc.unid);
  672. if (_loadCssRunning[key]) {
  673. _loadCssQueue.push(function () {
  674. _loadSingleCss(module, callback, op, uuid);
  675. });
  676. return;
  677. }
  678. var completed = function () {
  679. if (_loadCssRunning[key]) {
  680. _loadCssRunning[key] = false;
  681. delete _loadCssRunning[key];
  682. }
  683. if (_loadCssQueue && _loadCssQueue.length) {
  684. (_loadCssQueue.shift())();
  685. }
  686. };
  687. if (_loadedCss[key]) uuid = _loadedCss[key]["class"];
  688. if (op.dom) _parseDom(op.dom, function (node) {
  689. if (node.className.indexOf(uuid) == -1) node.className += ((node.className) ? " " + uuid : uuid);
  690. }, op.doc);
  691. if (_loadedCss[key]) if (!op.reload) {
  692. Promise.resolve(_loadedCss[key]).then(function(o){
  693. if (callback) callback(o);
  694. });
  695. //if (callback) callback(_loadedCss[key]);
  696. completed();
  697. return;
  698. }
  699. if (op.url){
  700. var style = op.doc.createElement("link");
  701. style.setAttribute("rel", "stylesheet");
  702. style.setAttribute("type", "text/css");
  703. style.setAttribute("id", uuid);
  704. style.setAttribute("href", url);
  705. if (!op.notInject) {
  706. var head = (op.doc.head || op.doc.getElementsByTagName("head")[0] || op.doc.documentElement);
  707. head.appendChild(style);
  708. }
  709. var styleObj = {"module": module, "id": uid, "style": style, "doc": op.doc, "class": uuid};
  710. if (callback) callback(styleObj);
  711. completed();
  712. }else{
  713. var success = function (xhr) {
  714. var cssText = xhr.responseText;
  715. try {
  716. if (cssText) {
  717. op.uuid = uuid;
  718. var style = _loadCssText(cssText, op);
  719. }
  720. style.id = uid;
  721. var styleObj = {"module": module, "id": uid, "style": style, "doc": op.doc, "class": uuid};
  722. _loadedCss[key] = styleObj;
  723. if (callback) callback(styleObj);
  724. } catch (e) {
  725. if (callback) callback();
  726. return;
  727. }
  728. };
  729. var failure = function (xhr) {
  730. console.log("Error: load css module: " + module);
  731. if (callback) callback();
  732. };
  733. _loadCssRunning[key] = true;
  734. _xhr_get(url, success, failure, completed);
  735. }
  736. };
  737. var _parseDomString = function (dom, fn, sourceDoc) {
  738. var doc = sourceDoc || document;
  739. var list = doc.querySelectorAll(dom);
  740. if (list.length) for (var i = 0; i < list.length; i++) _parseDomElement(list[i], fn);
  741. };
  742. var _parseDomElement = function (dom, fn) {
  743. if (fn) fn(dom);
  744. };
  745. var _parseDom = function (dom, fn, sourceDoc) {
  746. var domType = _typeOf(dom);
  747. if (domType === "string") _parseDomString(dom, fn, sourceDoc);
  748. if (domType === "element") _parseDomElement(dom, fn);
  749. if (domType === "array") for (var i = 0; i < dom.length; i++) _parseDom(dom[i], fn, sourceDoc);
  750. };
  751. var _loadCss = function (modules, options, callback) {
  752. var ms = (_typeOf(modules) === "array") ? modules : [modules];
  753. var op = (_typeOf(options) === "object") ? _getCssOptions(options) : _getCssOptions(null);
  754. var cb = (_typeOf(options) === "function") ? options : callback;
  755. var uuid = "css" + _uuid();
  756. var thisLoaded = [];
  757. if (op.sequence) {
  758. _loadSequence(ms, cb, op, 0, thisLoaded, _loadSingleCss, uuid);
  759. } else {
  760. _loadDisarray(ms, cb, op, thisLoaded, _loadSingleCss, uuid);
  761. }
  762. };
  763. var _removeCss = function (modules, doc) {
  764. var thisDoc = doc || document;
  765. var ms = (_typeOf(modules) === "array") ? modules : [modules];
  766. for (var i = 0; i < ms.length; i++) {
  767. var module = ms[i];
  768. var k = encodeURIComponent(module + (thisDoc.unid || ""));
  769. var removeCss = _loadedCss[k];
  770. if (!removeCss) for (key in _loadedCss) {
  771. if (_loadedCss[key].id == module) {
  772. removeCss = _loadedCss[key];
  773. k = key;
  774. break;
  775. }
  776. }
  777. if (removeCss) {
  778. delete _loadedCss[k];
  779. var styleNode = removeCss.doc.getElementById(removeCss.id);
  780. if (styleNode) styleNode.parentNode.removeChild(styleNode);
  781. removeCss = null;
  782. }
  783. }
  784. };
  785. var _loadCssText = function (cssText, options, callback) {
  786. var op = (_typeOf(options) === "object") ? _getCssOptions(options) : _getCssOptions(null);
  787. var cb = (_typeOf(options) === "function") ? options : callback;
  788. var uuid = options.uuid || "css" + _uuid();
  789. if (cssText) {
  790. if (op.dom) _parseDom(op.dom, function (node) {
  791. if (node.className.indexOf(uuid) == -1) node.className += ((node.className) ? " " + uuid : uuid);
  792. }, op.doc);
  793. cssText = cssText.replace(/\/\*(\s|\S)*?\*\//g, "");
  794. if (op.bind) cssText = cssText.bindJson(op.bind);
  795. if (op.dom) {
  796. var rex = new RegExp("(.+)(?=[\\r\\n]*\\{)", "g");
  797. var match;
  798. var prefix = "." + uuid + " ";
  799. while ((match = rex.exec(cssText)) !== null) {
  800. // var rule = prefix + match[0];
  801. // cssText = cssText.substring(0, match.index) + rule + cssText.substring(rex.lastIndex, cssText.length);
  802. // rex.lastIndex = rex.lastIndex + prefix.length;
  803. var rulesStr = match[0];
  804. var startWith = rulesStr.substring(0, 1);
  805. if (startWith === "@" || startWith === ":" || rulesStr.indexOf("%") !== -1) {
  806. // var begin = 0;
  807. // var end = 0;
  808. }else if (rulesStr.trim()==='from' || rulesStr.trim()==='to'){
  809. //nothing
  810. } else {
  811. if (rulesStr.indexOf(",") != -1) {
  812. //var rules = rulesStr.split(/\s*,\s*/g);
  813. var rules = rulesStr.split(/,/g);
  814. rules = rules.map(function (r) {
  815. return prefix + r;
  816. });
  817. var rule = rules.join(",");
  818. cssText = cssText.substring(0, match.index) + rule + cssText.substring(rex.lastIndex, cssText.length);
  819. rex.lastIndex = rex.lastIndex + (prefix.length * rules.length);
  820. } else {
  821. var rule = prefix + match[0];
  822. cssText = cssText.substring(0, match.index) + rule + cssText.substring(rex.lastIndex, cssText.length);
  823. rex.lastIndex = rex.lastIndex + prefix.length;
  824. }
  825. }
  826. }
  827. }
  828. var style = op.doc.createElement("style");
  829. style.setAttribute("type", "text/css");
  830. style.setAttribute("id", uuid);
  831. if (!op.notInject) {
  832. var head = (op.doc.head || op.doc.getElementsByTagName("head")[0] || op.doc.documentElement);
  833. head.appendChild(style);
  834. }
  835. if (style.styleSheet) {
  836. var setFunc = function () {
  837. style.styleSheet.cssText = cssText;
  838. };
  839. if (style.styleSheet.disabled) {
  840. setTimeout(setFunc, 10);
  841. } else {
  842. setFunc();
  843. }
  844. } else {
  845. var cssTextNode = op.doc.createTextNode(cssText);
  846. style.appendChild(cssTextNode);
  847. }
  848. }
  849. if (callback) callback(style, uuid);
  850. return style;
  851. };
  852. /**
  853. * @summary 引入外部css资源。
  854. * @function loadCss
  855. * @memberOf o2
  856. * @param {String|Array} [urls] 要载入的css文件url,或要载入多个css文件的urls数组。
  857. * @param {Object|Function} [options|callback] 载入css文件的配置参数,或者载入成功后的回调。
  858. * <pre><code class="language-js">options参数格式如下:
  859. * {
  860. * "noCache": 是否使用缓存,默认true,
  861. * "reload": 如果相同路径的css文件已经引入了,是否重新载入,默认为:false
  862. * "sequence": 当urls参数为数组时,多个css文件是否按数组顺序依次载入,默认为false
  863. * "dom": dom element对象,表示css在这个element生效,默认是null,表示对整个document生效
  864. * }
  865. * </code></pre>
  866. * @param {Function} [callback] 可选参数,载入成功后的回调方法。
  867. * @o2syntax
  868. * o2.loadCss(urls, options, callback);
  869. * @o2syntax
  870. * Element.loadCss(urls, options, callback);
  871. * @example
  872. * //载入style1.css和style2.css两个文件,作用于document
  873. * o2.loadCss(["../css/style1.css", "../css/style2.css"], function(){
  874. * //css文件已经载入
  875. * });
  876. *
  877. * //载入style1.css和style2.css两个文件,作用于id为content的dom对象
  878. * o2.loadCss(["../css/style1.css", "../css/style2.css"], {"dom": document.getELementById("content")}, function(){
  879. * //css文件已经载入
  880. * });
  881. * //在Dom对象上载入style1.css和style2.css两个css
  882. * var node = document.getElementById("mydiv");
  883. * node.loadCss(["../css/style1.css", "../css/style2.css"], function(){
  884. * //css文件已经载入
  885. * });
  886. */
  887. this.o2.loadCss = _loadCss;
  888. /**
  889. * @summary 引入文本css资源。
  890. * @function loadCssText
  891. * @memberOf o2
  892. * @param {String} [cssText] 要载入的css文本内容。
  893. * @param {Object|Function} [options|callback] 载入css文件的配置参数,或者载入成功后的回调。
  894. * <pre><code class="language-js">options参数格式如下:
  895. * {
  896. * "dom": dom element对象,表示css在这个element生效,默认是null,表示对整个document生效
  897. * }
  898. * </code></pre>
  899. * @param {Function} [callback] 可选参数,载入成功后的回调方法。
  900. * @o2syntax
  901. * o2.loadCssText(cssText, options, callback);
  902. * @o2syntax
  903. * Element.loadCssText(cssText, options, callback);
  904. * @see o2.loadCss
  905. * @example
  906. * //引入css文本,作用于id为content的dom对象
  907. * var csstext = ".myclass{color:#ff0000}"
  908. * o2.loadCssText(csstext, {"dom": document.getELementById("content")}, function(){
  909. * //css已经载入
  910. * });
  911. * //引入css文本,作用于id为content的dom对象
  912. * var csstext = ".myclass{color:#ff0000}"
  913. * var node = document.getELementById("content");
  914. * node.loadCssText(csstext, function(){
  915. * //css已经载入
  916. * });
  917. */
  918. this.o2.loadCssText = _loadCssText;
  919. if (window.Element) Element.prototype.loadCss = function (modules, options, callback) {
  920. var op = (_typeOf(options) === "object") ? options : {};
  921. var cb = (_typeOf(options) === "function") ? options : callback;
  922. op.dom = this;
  923. _loadCss(modules, op, cb);
  924. };
  925. if (window.Element) Element.prototype.loadCssText = function (cssText, options, callback) {
  926. var op = (_typeOf(options) === "object") ? options : {};
  927. var cb = (_typeOf(options) === "function") ? options : callback;
  928. op.dom = this;
  929. return _loadCssText(cssText, op, cb);
  930. };
  931. /**
  932. * @summary 移除通过o2.loadCss方法引入css资源。
  933. * @function removeCss
  934. * @memberOf o2
  935. * @param {String|Array} [urls] 要移除的的css文本url,必须与引入时所使用的url相同。
  936. * @o2syntax
  937. * o2.removeCss(urls);
  938. * @example
  939. * //载入style1.css和style2.css两个文件,作用于id为content的dom对象
  940. * o2.load(["../css/style1.css", "../css/style2.css"], {"dom": document.getELementById("content")}, function(){
  941. * //css文件已经载入
  942. * });
  943. *
  944. * //移除style1.css和style2.css两个文件
  945. * //引入时使用了"../css/style1.css"字符串作为路径,移除时也要使用相同的字符串
  946. * o2.removeCss(["../css/style1.css", "../css/style2.css"])
  947. */
  948. this.o2.removeCss = _removeCss;
  949. //load html
  950. _loadSingleHtml = function (module, callback, op) {
  951. var url = module;
  952. var uid = _uuid();
  953. if (op.noCache) url = (url.indexOf("?") !== -1) ? url + "&v=" + uid : url + "?v=" + uid;
  954. var key = encodeURIComponent(url + op.doc.unid);
  955. if (!op.reload) if (_loadedHtml[key]) {
  956. Promise.resolve(_loadedHtml[key]).then(function(html){
  957. if (callback) callback(html);
  958. });
  959. //if (callback) callback(_loadedHtml[key]);
  960. return;
  961. }
  962. var success = function (xhr) {
  963. var htmlObj = {"module": module, "id": uid, "data": xhr.responseText, "doc": op.doc};
  964. _loadedHtml[key] = htmlObj;
  965. if (callback) callback(htmlObj);
  966. };
  967. var failure = function () {
  968. console.log("Error: load html module: " + module);
  969. if (callback) callback();
  970. };
  971. _xhr_get(url, success, failure);
  972. };
  973. var _injectHtml = function (op, data, baseUrl) {
  974. if (op.bind) data = data.bindJson(op.bind);
  975. if (op.dom) _parseDom(op.dom, function (node) {
  976. var scriptText;
  977. var scriptSrc;
  978. var text = data.stripScriptSrcs(function (script) {
  979. scriptSrc = script;
  980. });
  981. text = text.stripScripts(function (script) {
  982. scriptText = script;
  983. });
  984. if (op.baseUrl){
  985. var reg = /(?:href|src)\s*=\s*"([^"]*)"/gi;
  986. var m = reg.exec(text);
  987. while (m) {
  988. var l = m[0].length;
  989. var u = new URI(m[1], {base: baseUrl}).toString();
  990. var r = m[0].replace(m[1], u);
  991. var i = r.length - l;
  992. var left = text.substring(0, m.index);
  993. var right = text.substring(m.index + l, text.length);
  994. text = left + r + right;
  995. reg.lastIndex = reg.lastIndex + i;
  996. m = reg.exec(text);
  997. }
  998. }
  999. if (op.module) {
  1000. _parseModule(node, text, op);
  1001. //node.insertAdjacentHTML(op.position, data);
  1002. } else {
  1003. node.insertAdjacentHTML(op.position, text);
  1004. }
  1005. if (op.evalScripts) {
  1006. if (scriptSrc) {
  1007. var scriptSrcs = scriptSrc.split(/\n/g).trim();
  1008. if (scriptSrcs && scriptSrcs.length) {
  1009. o2.load(scriptSrcs, {baseUrl: baseUrl, reload:true}, function () {
  1010. });
  1011. if (op.evalScripts && scriptText) Browser.exec(scriptText);
  1012. } else {
  1013. if (op.evalScripts && scriptText) Browser.exec(scriptText);
  1014. }
  1015. }
  1016. }
  1017. }, op.doc);
  1018. };
  1019. var _parseModule = function (node, data, op) {
  1020. var dom = op.noConflict ? document.createElement("div") : node;
  1021. if (op.noConflict) {
  1022. dom.insertAdjacentHTML("afterbegin", data);
  1023. } else {
  1024. dom.insertAdjacentHTML(op.position, data);
  1025. }
  1026. var bindDataId = "";
  1027. var bindDataNode = dom.querySelector("[data-o2-binddata]");
  1028. if (bindDataNode){
  1029. bindDataId = bindDataNode.dataset["o2Binddata"];
  1030. bindDataNode.destroy();
  1031. }
  1032. var els = dom.querySelectorAll("[data-o2-element],[data-o2-events]");
  1033. for (var i = 0; i < els.length; i++) {
  1034. var el = els.item(i);
  1035. var name = el.getAttribute("data-o2-element");
  1036. if (name) _bindToModule(op.module, el, name.toString());
  1037. if (el.hasAttribute("data-o2-events")) {
  1038. var events = el.getAttribute("data-o2-events").toString();
  1039. if (events) _bindToEvents(op.module, el, events, bindDataId);
  1040. el.removeAttribute("data-o2-events");
  1041. }
  1042. }
  1043. if (op.noConflict) {
  1044. var n = dom.firstElementChild;
  1045. var newNode = node.insertAdjacentElement(op.position, n);
  1046. nextNode = dom.firstElementChild;
  1047. while (nextNode) {
  1048. newNode = newNode.insertAdjacentElement("afterend", nextNode);
  1049. nextNode = dom.firstElementChild;
  1050. }
  1051. dom.destroy();
  1052. }
  1053. };
  1054. var _bindToEvents = function (m, node, events, bindDataId) {
  1055. var p = node.getParent("div[data-o2-binddataid]");
  1056. var data = null;
  1057. if (p){
  1058. data = _parseDataCache[p.dataset["o2Binddataid"]];
  1059. //_parseDataCache[p.dataset["o2Binddataid"]] = null;
  1060. //delete _parseDataCache[p.dataset["o2Binddataid"]];
  1061. }else{
  1062. if (bindDataId) data = (_parseDataCache[bindDataId] || null);
  1063. //_parseDataCache[bindDataId] = null;
  1064. //delete _parseDataCache[bindDataId];
  1065. }
  1066. // var data = (p) ? _parseDataCache[p.dataset["o2Binddataid"]] : (_parseDataCache["bind"] || null);
  1067. var eventList = events.split(/\s*;\s*/);
  1068. eventList.forEach(function (ev) {
  1069. var evs = ev.split(/\s*:\s*/);
  1070. if (evs.length > 1) {
  1071. var event = evs.shift();
  1072. var method = evs.shift();
  1073. // if (event==="o2load"){
  1074. //
  1075. // if (m[method]) m[method].apply(m, evs.concat([new PointerEvent("o2load"), data]));
  1076. // }else{
  1077. node.addEventListener(event, function (e) {
  1078. if (m[method]) m[method].apply(m, evs.concat([e, data]));
  1079. }, false);
  1080. // }
  1081. }
  1082. });
  1083. // try {
  1084. node.dispatchEvent(o2.customEventLoad);
  1085. // }catch(e){
  1086. // debugger;
  1087. // console.error(e)
  1088. // }
  1089. }
  1090. var _bindToModule = function (m, node, name) {
  1091. // if (m[name]){
  1092. // if (o2.typeOf(m[name])!=="array"){
  1093. // var tmp = m[name];
  1094. // m[name] = [];
  1095. // m[name].push(tmp);
  1096. // }
  1097. // m[name].push(node);
  1098. // }else{
  1099. m[name] = node;
  1100. // }
  1101. };
  1102. var _loadHtml = function (modules, options, callback) {
  1103. var ms = (_typeOf(modules) === "array") ? modules : [modules];
  1104. var op = (_typeOf(options) === "object") ? _getHtmlOptions(options) : _getHtmlOptions(null);
  1105. var cb = (_typeOf(options) === "function") ? options : callback;
  1106. var thisLoaded = [];
  1107. if (op.sequence) {
  1108. _loadSequence(ms, cb, op, 0, thisLoaded, _loadSingleHtml, null, function (html) {
  1109. if (html) _injectHtml(op, html.data, html.module);
  1110. });
  1111. } else {
  1112. _loadDisarray(ms, cb, op, thisLoaded, _loadSingleHtml, null, function (html) {
  1113. if (html) _injectHtml(op, html.data, html.module);
  1114. });
  1115. }
  1116. };
  1117. /**
  1118. * @summary 引入外部html模板资源,并将html内容渲染到指定dom对象的某个位置。
  1119. * @function loadHtml
  1120. * @memberOf o2
  1121. * @param {String|Array} [urls] 要载入的html文件url,或要载入多个html文件的urls数组。
  1122. * @param {Object|Function} [options|callback] 载入html文件的配置参数,或者载入成功后的回调。
  1123. * <pre><code class="language-js">options参数格式如下:
  1124. * {
  1125. * "noCache": 是否使用缓存,默认true,
  1126. * "reload": 如果相同路径的html文件已经引入了,是否重新载入,默认为:false
  1127. * "sequence": 当urls参数为数组时,多个html文件是否按数组顺序依次载入,默认为false
  1128. * "dom": 引入html后,要将html内容渲染到的目标dom对象(具体位置由position参数确定),
  1129. * "position": 渲染到的目标dom对象的位置,可以是以下值:'beforebegin' 'afterbegin' 'beforeend'(默认) 'afterend'
  1130. * "module": Object,与此html模板关联的对象。(在下面的例子中详细介绍)
  1131. * "bind": Json,与此html模板关联的Json对象。(在下面的例子中详细介绍)
  1132. * "evalScripts": html模板中通过&lt;script&gt;引入或内嵌的javascript,是否要执行。默认为false
  1133. * "baseUrl": html模板中引用连接的baseUrl,默认为空
  1134. * }
  1135. * </code></pre>
  1136. * @param {Function} [callback] 可选参数,载入成功后的回调方法。
  1137. * @o2syntax
  1138. * o2.loadHtml(urls, options, callback);
  1139. * @o2syntax
  1140. * Element.loadHtml(urls, options, callback);
  1141. * @example
  1142. * <caption><b>样例1: </b>引入一个html模板文件,并插入到id为content的dom对象的最后</caption>
  1143. * //引入一个html模板文件,并插入到id为content的dom对象的最后
  1144. * var node = document.getELementById("content");
  1145. * o2.loadHtml("../html/template.html", {"dom": node}, function(){
  1146. * //html文件已经载入
  1147. * });
  1148. *
  1149. * //或者使用Element.loadHtml方法
  1150. * var node = document.getELementById("content");
  1151. * node.loadHtml("../html/template.html", function(){
  1152. * //html文件已经载入
  1153. * });
  1154. *
  1155. * @example
  1156. * <caption>
  1157. * <b>样例2: </b>本例中我们使用一个html模板来渲染展现已有的数据。我们将一个json对象绑定到要载入的模板,通过{{$.xxx}}来展现json数据。<br>
  1158. * html模板内容如下:
  1159. * <pre><code class="language-js">&lt;div&gt;{{$.title}}&lt;/div&gt;
  1160. * &lt;div&gt;{{$.description}}&lt;/div&gt;</code></pre>
  1161. * 然后通过以下代码来载入html模板:
  1162. * </caption>
  1163. * var json = {
  1164. * "title": "这是标题",
  1165. * "description": "描述内容"
  1166. * };
  1167. * var node = document.getELementById("content");
  1168. * o2.loadHtml("../html/template.html", {"dom": node, "bind": json}, function(){
  1169. * //html文件已经载入
  1170. * //载入后,node对象的html如下:
  1171. * //<div>
  1172. * // ......
  1173. * // <div>这是标题</div>;
  1174. * // <div>描述内容</div>
  1175. * //</div>
  1176. * });
  1177. * @example
  1178. * <caption>
  1179. * <b>样例3: </b>本例中我们除了使用一个html模板来渲染展现已有的json数据,还给已有模块绑定上html模板中的一个dom对象,并监听html模板中的指定元素的事件。<br>
  1180. * html模板内容如下:
  1181. * <pre><code class="language-js">&lt;div&gt;{{$.title}}&lt;/div&gt;
  1182. * &lt;div&gt;{{$.description}}&lt;/div&gt;
  1183. * &lt;div data-o2-element="myElement"&gt;&lt;/div&gt;
  1184. * &lt;button data-o2-events="click:clickMe:{{$.info}};mouseover:overMe;mouseout:outMe"&gt;绑定了事件的按钮&lt;/button&gt;
  1185. * </code></pre>
  1186. * 然后通过以下代码来载入html模板:
  1187. * </caption>
  1188. * //json数据
  1189. * var json = {
  1190. * "title": "这是标题",
  1191. * "description": "描述内容",
  1192. * "info": "按钮点击后的信息"
  1193. * };
  1194. * //业务模块
  1195. * var module = {
  1196. * //当button按钮被点击时,会调用此方法
  1197. * clickMe: function(info, e){
  1198. * this.myElement.insertAdjacentText("afterbegin", "button clicked " + info);
  1199. * },
  1200. * //当鼠标移动到button按钮时,会调用此方法
  1201. * overMe: function(e){
  1202. * console.log("button over");
  1203. * console.log(e); //MouseEvent对象
  1204. * },
  1205. * //当鼠标移出button按钮时,会调用此方法
  1206. * outMe: function(e){
  1207. * console.log("button out");
  1208. * console.log(e); //MouseEvent对象
  1209. * }
  1210. * };
  1211. *
  1212. * var node = document.getELementById("content");
  1213. * node.loadHtml("../html/template.html", {"bind": json, "module": module}, function(){
  1214. * //html文件已经载入
  1215. * //载入后,node对象的html如下:
  1216. * //<div>
  1217. * // ......
  1218. * // <div>这是标题</div>;
  1219. * // <div>描述内容</div>
  1220. * // <div data-o2-element="myElement"></div>
  1221. * // <button>绑定了事件的按钮</button>
  1222. * //</div>
  1223. * console.log(module.myElement); //Dom对象:<div data-o2-element="myElement"></div>
  1224. * //html模板中的div对象,被绑定到了module对象的myElement属性上
  1225. *
  1226. * });
  1227. * @example
  1228. * <caption>
  1229. * <b>样例4: </b>本例中演示了html模板中each和if的用法。<br>
  1230. * html模板内容如下:
  1231. * <pre><code class="language-js">&lt;div&gt;
  1232. * {{each $.items}}
  1233. * &lt;div&gt;{{$.title}}&lt;/div&gt;
  1234. * &lt;div&gt;{{$.description}}&lt;/div&gt;
  1235. * {{if $.title=="这是标题2"}}
  1236. * &lt;div&gt;这是标题2的个性化内容&lt;/div&gt;
  1237. * {{end if}}
  1238. * &lt;button data-o2-events="click:clickMe:{{$.info}}"&gt;绑定了事件的按钮&lt;/button&gt;
  1239. * &lt;hr&gt;
  1240. * {{end each}}
  1241. * &lt;/div&gt;</code></pre>
  1242. * 然后通过以下代码来载入html模板:
  1243. * </caption>
  1244. * //json数据
  1245. * var json = {
  1246. * "items": [{
  1247. * "title": "这是标题1",
  1248. * "description": "描述内容1",
  1249. * "info": "按钮点击后的信息1"
  1250. * },{
  1251. * "title": "这是标题2",
  1252. * "description": "描述内容2",
  1253. * "info": "按钮点击后的信息2"
  1254. * },{
  1255. * "title": "这是标题3",
  1256. * "description": "描述内容3",
  1257. * "info": "按钮点击后的信息3"
  1258. * }]
  1259. * };
  1260. * //业务模块
  1261. * var module = {
  1262. * //当button按钮被点击时,会调用此方法
  1263. * clickMe: function(info, e){
  1264. * alert(info);
  1265. * }
  1266. * };
  1267. * var node = document.getELementById("content");
  1268. * node.loadHtml("../html/template.html", {"bind": json, "module": module}, function(){
  1269. * //html文件已经载入
  1270. * //载入后,node对象的html如下:
  1271. * //<div>
  1272. * // <div>这是标题1</div>;
  1273. * // <div>描述内容1</div>
  1274. * // <button>绑定了事件的按钮</button>
  1275. * // <hr>
  1276. * //</div>
  1277. * //<div>
  1278. * // <div>这是标题2</div>;
  1279. * // <div>描述内容2</div>
  1280. * // <div>描这是标题2的个性化内容</div>
  1281. * // <button>绑定了事件的按钮</button>
  1282. * // <hr>
  1283. * //</div>
  1284. * //<div>
  1285. * // <div>这是标题3</div>;
  1286. * // <div>描述内容3</div>
  1287. * // <button>绑定了事件的按钮</button>
  1288. * // <hr>
  1289. * //</div>
  1290. * //当点击按钮时,会alert对应的items的info数据
  1291. * });
  1292. */
  1293. this.o2.loadHtml = _loadHtml;
  1294. if (window.Element) Element.prototype.loadHtml = function (modules, options, callback) {
  1295. var op = (_typeOf(options) === "object") ? options : {};
  1296. var cb = (_typeOf(options) === "function") ? options : callback;
  1297. op.dom = this;
  1298. _loadHtml(modules, op, cb);
  1299. };
  1300. /**
  1301. * @summary 解析html文本内容,并将html内容渲染到指定dom对象的某个位置,与loadHtml相同,只是传入html内容,而不是获取html的url。
  1302. * @function loadHtmlText
  1303. * @memberOf o2
  1304. * @param {String} [html] 要解析的html文本内容。
  1305. * @param {Object} [options] 载入html文件的配置参数。
  1306. * <pre><code class="language-js">options参数格式如下:
  1307. * {
  1308. * "noCache": 是否使用缓存,默认true,
  1309. * "reload": 如果相同路径的html文件已经引入了,是否重新载入,默认为:false
  1310. * "sequence": 当urls参数为数组时,多个html文件是否按数组顺序依次载入,默认为false
  1311. * "dom": 引入html后,要将html内容渲染到的目标dom对象(具体位置由position参数确定),
  1312. * "position": 渲染到的目标dom对象的位置,可以是以下值:'beforebegin' 'afterbegin' 'beforeend'(默认) 'afterend'
  1313. * "module": Object,与此html模板关联的对象。(在下面的例子中详细介绍)
  1314. * "bind": Json,与此html模板关联的Json对象。(在下面的例子中详细介绍)
  1315. * "evalScripts": html模板中通过&lt;script&gt;引入或内嵌的javascript,是否要执行。默认为false
  1316. * "baseUrl": html模板中引用连接的baseUrl,默认为空
  1317. * }
  1318. * </code></pre>
  1319. * @o2syntax
  1320. * o2.loadHtmlText(html, options);
  1321. * @o2syntax
  1322. * Element.loadHtmlText(html, options);
  1323. * @see o2.loadHtml
  1324. * @example
  1325. * var html = "<div>{{$.title}}</div>"
  1326. * var json = {"title": "标题"};
  1327. * var node = document.getELementById("content");
  1328. * o2.loadHtmlText(html, {"dom": node, "bind": json});
  1329. *
  1330. * //获
  1331. * node.loadHtmlText(html, {"bind": json});
  1332. */
  1333. this.o2.loadHtmlText = this.o2.injectHtml = function (html, options) {
  1334. var op = (_typeOf(options) === "object") ? _getHtmlOptions(options) : _getHtmlOptions(null);
  1335. _injectHtml(op, html);
  1336. };
  1337. if (window.Element) Element.prototype.loadHtmlText = Element.prototype.injectHtml = function (html, options) {
  1338. var op = (_typeOf(options) === "object") ? options : {};
  1339. op.dom = this;
  1340. op.position = (options && options.position) || "beforeend"
  1341. _injectHtml(op, html);
  1342. };
  1343. //load all
  1344. _loadAll = function (modules, options, callback) {
  1345. //var ms = (_typeOf(modules)==="array") ? modules : [modules];
  1346. var op = (_typeOf(options) === "object") ? _getAllOptions(options) : _getAllOptions(null);
  1347. var cb = (_typeOf(options) === "function") ? options : callback;
  1348. var ms, htmls, styles, sctipts;
  1349. var _htmlLoaded = (!modules.html), _cssLoaded = (!modules.css), _jsLoaded = (!modules.js);
  1350. var _checkloaded = function () {
  1351. if (_htmlLoaded && _cssLoaded && _jsLoaded) if (cb) cb(htmls, styles, sctipts);
  1352. };
  1353. if (modules.html) {
  1354. _loadHtml(modules.html, op, function (h) {
  1355. htmls = h;
  1356. _htmlLoaded = true;
  1357. _checkloaded();
  1358. });
  1359. }
  1360. if (modules.css) {
  1361. _loadCss(modules.css, op, function (s) {
  1362. styles = s;
  1363. _cssLoaded = true;
  1364. _checkloaded();
  1365. });
  1366. }
  1367. if (modules.js) {
  1368. _load(modules.js, op, function (s) {
  1369. sctipts = s;
  1370. _jsLoaded = true;
  1371. _checkloaded();
  1372. });
  1373. }
  1374. };
  1375. /**
  1376. * @summary 同时载入js文件、css文件和html模板文件,相当于同时调用了o2.load, o2.loadCss 和 o2.loadHtml。
  1377. * @function loadAll
  1378. * @memberOf o2
  1379. * @param {Object} [modules] 要解析的html文本内容。
  1380. * <pre><code class="language-js">modules参数格式如下:
  1381. * {
  1382. * "js": {String|Array} 要载入的js文件url,或要载入多个js文件的urls数组。
  1383. * "css": {String|Array} 要载入的css文件url,或要载入多个css文件的urls数组。
  1384. * "html": {String|Array} 要载入的html文件url,或要载入多个html文件的urls数组。
  1385. * }
  1386. * </code></pre>
  1387. * @param {Object} [options] 载入html文件的配置参数。
  1388. * <pre><code class="language-js">options参数格式如下:
  1389. * {
  1390. * "noCache": 是否使用缓存,默认true,
  1391. * "reload": 如果相同路径的html文件已经引入了,是否重新载入,默认为:false
  1392. * "sequence": 当urls参数为数组时,多个html文件是否按数组顺序依次载入,默认为false
  1393. * "dom": 引入html后,要将html内容渲染到的目标dom对象(具体位置由position参数确定),
  1394. * "position": 渲染到的目标dom对象的位置,可以是以下值:'beforebegin' 'afterbegin' 'beforeend'(默认) 'afterend'
  1395. * "module": Object,与此html模板关联的对象。(在下面的例子中详细介绍)
  1396. * "bind": Json,与此html模板关联的Json对象。(在下面的例子中详细介绍)
  1397. * "evalScripts": html模板中通过&lt;script&gt;引入或内嵌的javascript,是否要执行。默认为false
  1398. * "baseUrl": html模板中引用连接的baseUrl,默认为空
  1399. * }
  1400. * </code></pre>
  1401. * @param {Function} [callback] 可选参数,载入成功后的回调方法。
  1402. * @o2syntax
  1403. * o2.loadAll(modules, options, callback);
  1404. * @o2syntax
  1405. * Element.loadAll(modules, options, callback);
  1406. * @see o2.load
  1407. * @see o2.loadCss
  1408. * @see o2.loadHtml
  1409. * @example
  1410. * var html = "<div>{{$.title}}</div>"
  1411. * var json = {"title": "标题"};
  1412. * var node = document.getELementById("content");
  1413. * o2.loadAll({
  1414. * "js": ["file1.js", "file2.js"],
  1415. * "css": ["style.css"],
  1416. * "html": "template.html",
  1417. * }, {"dom": node, "bind": json}, function(){
  1418. * //载入完成后的回调
  1419. * });
  1420. */
  1421. this.o2.loadAll = _loadAll;
  1422. if (window.Element) Element.prototype.loadAll = function (modules, options, callback) {
  1423. var op = (_typeOf(options) === "object") ? options : {};
  1424. var cb = (_typeOf(options) === "function") ? options : callback;
  1425. op.dom = this;
  1426. _loadAll(modules, op, cb);
  1427. };
  1428. var _getIfBlockEnd = function (v) {
  1429. var rex = /(\{\{if\s+)|(\{\{\s*end if\s*\}\})/gmi;
  1430. var rexEnd = /\{\{\s*end if\s*\}\}/gmi;
  1431. var subs = 1;
  1432. while ((match = rex.exec(v)) !== null) {
  1433. var fullMatch = match[0];
  1434. if (fullMatch.search(rexEnd) !== -1) {
  1435. subs--;
  1436. if (subs == 0) break;
  1437. } else {
  1438. subs++
  1439. }
  1440. }
  1441. if (match) return {"codeIndex": match.index, "lastIndex": rex.lastIndex};
  1442. return {"codeIndex": v.length - 1, "lastIndex": v.length - 1};
  1443. }
  1444. var _getEachBlockEnd = function (v) {
  1445. var rex = /(\{\{each\s+)|(\{\{\s*end each\s*\}\})/gmi;
  1446. var rexEnd = /\{\{\s*end each\s*\}\}/gmi;
  1447. var subs = 1;
  1448. while ((match = rex.exec(v)) !== null) {
  1449. var fullMatch = match[0];
  1450. if (fullMatch.search(rexEnd) !== -1) {
  1451. subs--;
  1452. if (subs == 0) break;
  1453. } else {
  1454. subs++;
  1455. }
  1456. }
  1457. if (match) return {"codeIndex": match.index, "lastIndex": rex.lastIndex};
  1458. return {"codeIndex": v.length - 1, "lastIndex": v.length - 1};
  1459. }
  1460. var _parseDataCache = {};
  1461. var _parseHtml = function (str, json, i) {
  1462. var v = str;
  1463. var r = (Math.random() * 1000000).toInt().toString();
  1464. while (_parseDataCache[r]) r = (Math.random() * 1000000).toInt().toString();
  1465. if (i || i===0) {
  1466. _parseDataCache[r] = json;
  1467. v = "<div data-o2-binddataid='" + r + "'>" + str + "</div>";
  1468. }else{
  1469. var regex = new RegExp("\\<[\\s\\S]+\\>");
  1470. if (regex.test(str)){
  1471. if (json.data){
  1472. _parseDataCache[r] = json.data;
  1473. v = str+"<div style='display: none' data-o2-binddata='" + r + "'></div>"
  1474. }
  1475. }
  1476. }
  1477. var rex = /(\{\{\s*)[\s\S]*?(\s*\}\})/gmi;
  1478. var match;
  1479. while ((match = rex.exec(v)) !== null) {
  1480. var fullMatch = match[0];
  1481. var offset = 0;
  1482. //if statement begin
  1483. if (fullMatch.search(/\{\{if\s+/i) !== -1) {
  1484. //找到对应的end if
  1485. var condition = fullMatch.replace(/^\{\{if\s*/i, "");
  1486. condition = condition.replace(/\s*\}\}$/i, "");
  1487. var flag = _jsonText(json, condition, "boolean");
  1488. var tmpStr = v.substring(rex.lastIndex, v.length);
  1489. var endIfIndex = _getIfBlockEnd(tmpStr);
  1490. if (flag) { //if 为 true
  1491. var parseStr = _parseHtml(tmpStr.substring(0, endIfIndex.codeIndex), json);
  1492. var vLeft = v.substring(0, match.index);
  1493. var vRight = v.substring(rex.lastIndex + endIfIndex.lastIndex, v.length);
  1494. v = vLeft + parseStr + vRight;
  1495. offset = parseStr.length - fullMatch.length;
  1496. } else {
  1497. v = v.substring(0, match.index) + v.substring(rex.lastIndex + endIfIndex.lastIndex, v.length);
  1498. offset = 0 - fullMatch.length;
  1499. }
  1500. } else if (fullMatch.search(/\{\{each\s+/) !== -1) { //each statement
  1501. var itemString = fullMatch.replace(/^\{\{each\s*/, "");
  1502. itemString = itemString.replace(/\s*\}\}$/, "");
  1503. var eachValue = _jsonText(json, itemString, "object");
  1504. var tmpEachStr = v.substring(rex.lastIndex, v.length);
  1505. var endEachIndex = _getEachBlockEnd(tmpEachStr);
  1506. var parseEachStr = tmpEachStr.substring(0, endEachIndex.codeIndex);
  1507. var eachResult = "";
  1508. if (eachValue && _typeOf(eachValue) === "array") {
  1509. for (var i = 0; i < eachValue.length; i++) {
  1510. eachValue[i]._ = json;
  1511. eachResult += _parseHtml(parseEachStr, eachValue[i], i);
  1512. }
  1513. var eLeft = v.substring(0, match.index);
  1514. var eRight = v.substring(rex.lastIndex + endEachIndex.lastIndex, v.length);
  1515. v = eLeft + eachResult + eRight;
  1516. offset = eachResult.length - fullMatch.length;
  1517. } else {
  1518. v = v.substring(0, match.index) + v.substring(rex.lastIndex + endEachIndex.lastIndex, v.length);
  1519. offset = 0 - fullMatch.length;
  1520. }
  1521. } else { //text statement
  1522. var text = fullMatch.replace(/^\{\{\s*/, "");
  1523. text = text.replace(/\}\}\s*$/, "");
  1524. var value = _jsonText(json, text);
  1525. offset = value.length - fullMatch.length;
  1526. v = v.substring(0, match.index) + value + v.substring(rex.lastIndex, v.length);
  1527. }
  1528. rex.lastIndex = rex.lastIndex + offset;
  1529. }
  1530. return v;
  1531. };
  1532. var _jsonText = function (json, text, type) {
  1533. try {
  1534. var $ = json;
  1535. var f = eval("(function($){\n return " + text + ";\n})");
  1536. returnValue = f.apply(json, [$]);
  1537. if (returnValue === undefined) returnValue = "";
  1538. if (type === "boolean") return (!!returnValue);
  1539. if (type === "object") return returnValue;
  1540. returnValue = returnValue.toString();
  1541. returnValue = returnValue.replace(/\&/g, "&amp;");
  1542. returnValue = returnValue.replace(/>/g, "&gt;");
  1543. returnValue = returnValue.replace(/</g, "&lt;");
  1544. returnValue = returnValue.replace(/\"/g, "&quot;");
  1545. return returnValue || "";
  1546. } catch (e) {
  1547. if (type === "boolean") return false;
  1548. if (type === "object") return null;
  1549. return "";
  1550. }
  1551. };
  1552. o2.bindJson = function (str, json) {
  1553. return _parseHtml(str, json);
  1554. };
  1555. String.prototype.bindJson = function (json) {
  1556. return _parseHtml(this, json);
  1557. };
  1558. var _createComponent = function(o, res){
  1559. o.multitask = false;
  1560. };
  1561. var _loadComponent = function(o, res){
  1562. o.loading = new Promise(function(resolve){
  1563. o2.loadAll(res, {evalScripts:true, url: true}, function(){ resolve(); });
  1564. });
  1565. };
  1566. o2.component = function(name, res){
  1567. o2.xApplication = o2.xApplication || {};
  1568. var names = name.split(".");
  1569. var o = o2.xApplication;
  1570. names.forEach(function(n){
  1571. o = o[n] = o[n] || {};
  1572. });
  1573. if (o2.typeOf(res)==="object"){
  1574. _loadComponent(o, res)
  1575. }else{
  1576. _createComponent(o, res);
  1577. }
  1578. }
  1579. })();
  1580. /** ***** BEGIN LICENSE BLOCK *****
  1581. * |------------------------------------------------------------------------------|
  1582. * | O2OA 活力办公 创意无限 o2.core.js |
  1583. * |------------------------------------------------------------------------------|
  1584. * | Distributed under the AGPL license: |
  1585. * |------------------------------------------------------------------------------|
  1586. * | Copyright © 2018, o2oa.net, o2server.io O2 Team |
  1587. * | All rights reserved. |
  1588. * |------------------------------------------------------------------------------|
  1589. *
  1590. * This file is part of O2OA.
  1591. *
  1592. * O2OA is free software: you can redistribute it and/or modify
  1593. * it under the terms of the GNU Affero General Public License as published by
  1594. * the Free Software Foundation, either version 3 of the License, or
  1595. * (at your option) any later version.
  1596. *
  1597. * O2OA is distributed in the hope that it will be useful,
  1598. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  1599. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  1600. * GNU Affero General Public License for more details.
  1601. *
  1602. * You should have received a copy of the GNU General Public License
  1603. * along with Foobar. If not, see <https://www.gnu.org/licenses/>.
  1604. *
  1605. * ***** END LICENSE BLOCK ******/
  1606. (function () {
  1607. var _Class = {
  1608. create: function (options) {
  1609. // var newClass = function() {
  1610. // this.initialize.apply(this, arguments);
  1611. // };
  1612. return _copyPrototype(function () {
  1613. return this.initialize.apply(this, arguments) || this;
  1614. }, options);
  1615. //return newClass;
  1616. }
  1617. };
  1618. var _copyPrototype = function (currentNS, props) {
  1619. if (!props) {
  1620. return currentNS;
  1621. }
  1622. if (!currentNS) {
  1623. return currentNS;
  1624. }
  1625. if ((typeof currentNS).toLowerCase() === "object") {
  1626. for (var prop in props) {
  1627. currentNS[prop] = props[prop];
  1628. }
  1629. }
  1630. if ((typeof currentNS).toLowerCase() === "function") {
  1631. for (var propfun in props) {
  1632. currentNS.prototype[propfun] = props[propfun];
  1633. }
  1634. }
  1635. return currentNS;
  1636. };
  1637. var _loaded = {};
  1638. var _requireJs = function (url, callback, async, compression, module) {
  1639. var key = encodeURIComponent(url);
  1640. if (_loaded[key]) {
  1641. o2.runCallback(callback, "success", [module]);
  1642. return "";
  1643. }
  1644. var jsPath = (compression || !this.o2.session.isDebugger) ? url.replace(/\.js/, ".min.js") : url;
  1645. jsPath = (jsPath.indexOf("?") !== -1) ? jsPath + "&v=" + this.o2.version.v : jsPath + "?v=" + this.o2.version.v;
  1646. if (window.importScripts) {
  1647. window.importScripts(o2.filterUrl(jsPath));
  1648. o2.runCallback(callback, "success", [module]);
  1649. } else {
  1650. var xhr = new Request({
  1651. url: o2.filterUrl(jsPath), async: async, method: "get",
  1652. onSuccess: function () {
  1653. //try{
  1654. _loaded[key] = true;
  1655. o2.runCallback(callback, "success", [module]);
  1656. //}catch (e){
  1657. // o2.runCallback(callback, "failure", [e]);
  1658. //}
  1659. },
  1660. onFailure: function (r) {
  1661. var rex = /lp\/.+\.js/;
  1662. if (rex.test(url)) {
  1663. var zhcnUrl = url.replace(rex, "lp/zh-cn.js");
  1664. if (zhcnUrl !== url) {
  1665. _requireJs(zhcnUrl, callback, async, compression, module)
  1666. } else {
  1667. o2.runCallback(callback, "failure", [r]);
  1668. }
  1669. } else {
  1670. o2.runCallback(callback, "failure", [r]);
  1671. }
  1672. }
  1673. });
  1674. xhr.send();
  1675. }
  1676. };
  1677. var _requireSingle = function (module, callback, async, compression) {
  1678. if (o2.typeOf(module) === "array") {
  1679. _requireAppSingle(module, callback, async, compression);
  1680. } else {
  1681. module = module.replace("MWF.", "o2.");
  1682. var levels = module.split(".");
  1683. if (levels[levels.length - 1] === "*") levels[levels.length - 1] = "package";
  1684. levels.shift();
  1685. var o = o2;
  1686. var i = 0;
  1687. while (o && i < levels.length) {
  1688. o = o[levels[i]];
  1689. i++
  1690. }
  1691. if (!o) {
  1692. var jsPath = this.o2.session.path;
  1693. jsPath += "/" + levels.join("/") + ".js";
  1694. var loadAsync = (async !== false);
  1695. _requireJs(jsPath, callback, loadAsync, compression, module);
  1696. } else {
  1697. o2.runCallback(callback, "success", [module]);
  1698. }
  1699. }
  1700. };
  1701. var _requireSequence = function (fun, module, thisLoaded, thisErrorLoaded, callback, async, compression) {
  1702. var m = module.shift();
  1703. fun(m, {
  1704. "onSuccess": function (m) {
  1705. thisLoaded.push(m);
  1706. o2.runCallback(callback, "every", [m]);
  1707. if (module.length) {
  1708. _requireSequence(fun, module, thisLoaded, thisErrorLoaded, callback, async, compression);
  1709. } else {
  1710. if (thisErrorLoaded.length) {
  1711. o2.runCallback(callback, "failure", [thisLoaded, thisErrorLoaded]);
  1712. } else {
  1713. o2.runCallback(callback, "success", [thisLoaded, thisErrorLoaded]);
  1714. }
  1715. }
  1716. },
  1717. "onFailure": function () {
  1718. thisErrorLoaded.push(module[i]);
  1719. o2.runCallback(callback, "failure", [thisLoaded, thisErrorLoaded]);
  1720. }
  1721. }, async, compression);
  1722. };
  1723. var _requireDisarray = function (fun, module, thisLoaded, thisErrorLoaded, callback, async, compression) {
  1724. for (var i = 0; i < module.length; i++) {
  1725. fun(module[i], {
  1726. "onSuccess": function (m) {
  1727. thisLoaded.push(m);
  1728. o2.runCallback(callback, "every", [m]);
  1729. if ((thisLoaded.length + thisErrorLoaded.length) === module.length) {
  1730. if (thisErrorLoaded.length) {
  1731. o2.runCallback(callback, "failure", [thisLoaded, thisErrorLoaded]);
  1732. } else {
  1733. o2.runCallback(callback, "success", [thisLoaded, thisErrorLoaded]);
  1734. }
  1735. }
  1736. },
  1737. "onFailure": function () {
  1738. thisErrorLoaded.push(module[i]);
  1739. o2.runCallback(callback, "failure", [thisLoaded, thisErrorLoaded]);
  1740. }
  1741. }, async, compression);
  1742. }
  1743. };
  1744. var _require = function (module, callback, async, sequence, compression) {
  1745. var type = typeOf(module);
  1746. if (type === "array") {
  1747. var sql = !!sequence;
  1748. var thisLoaded = [];
  1749. var thisErrorLoaded = [];
  1750. if (sql) {
  1751. _requireSequence(_requireSingle, module, thisLoaded, thisErrorLoaded, callback, async, compression);
  1752. } else {
  1753. _requireDisarray(_requireSingle, module, thisLoaded, thisErrorLoaded, callback, async, compression);
  1754. }
  1755. }
  1756. if (type === "string") {
  1757. _requireSingle(module, callback, async, compression);
  1758. }
  1759. };
  1760. var _requireAppSingle = function (modules, callback, async, compression) {
  1761. var module = modules[0];
  1762. var clazz = modules[1];
  1763. var levels = module.split(".");
  1764. var o = o2.xApplication;
  1765. var i = 0;
  1766. while (o && i < levels.length) {
  1767. o = o[levels[i]];
  1768. i++
  1769. }
  1770. if (o) o = o[clazz || "Main"];
  1771. if (!o) {
  1772. //levels.shift();
  1773. var root = "x_component_" + levels.join("_");
  1774. var clazzName = clazz || "Main";
  1775. var path = "../" + root + "/" + clazzName.replace(/\./g, "/") + ".js";
  1776. var loadAsync = (async !== false);
  1777. _requireJs(path, callback, loadAsync, compression);
  1778. } else {
  1779. o2.runCallback(callback, "success");
  1780. }
  1781. };
  1782. var _requireApp = function (module, clazz, callback, async, sequence, compression) {
  1783. var type = typeOf(module);
  1784. if (type === "array") {
  1785. var sql = !!sequence;
  1786. var thisLoaded = [];
  1787. var thisErrorLoaded = [];
  1788. if (sql) {
  1789. _requireSequence(_requireAppSingle, module, thisLoaded, thisErrorLoaded, callback, async, compression);
  1790. } else {
  1791. _requireDisarray(_requireAppSingle, module, thisLoaded, thisErrorLoaded, callback, async, compression);
  1792. }
  1793. }
  1794. if (type === "string") {
  1795. var modules = [module, clazz];
  1796. _requireAppSingle(modules, callback, async, compression);
  1797. }
  1798. };
  1799. JSON = window.JSON || {};
  1800. var _json = JSON;
  1801. _json.get = function (url, callback, async, nocache) {
  1802. var loadAsync = (async !== false);
  1803. var noJsonCache = (nocache === true);
  1804. if (url.indexOf("config.json") > -1){
  1805. noJsonCache = true;
  1806. }
  1807. url = (url.indexOf("?") !== -1) ? url + "&v=" + o2.version.v : url + "?v=" + o2.version.v;
  1808. var json = null;
  1809. var res = new Request.JSON({
  1810. url: o2.filterUrl(url),
  1811. secure: false,
  1812. method: "get",
  1813. noCache: noJsonCache,
  1814. async: loadAsync,
  1815. withCredentials: true,
  1816. onSuccess: function (responseJSON, responseText) {
  1817. json = responseJSON;
  1818. if (typeOf(callback).toLowerCase() === 'function') {
  1819. callback(responseJSON, responseText);
  1820. } else {
  1821. o2.runCallback(callback, "success", [responseJSON, responseText]);
  1822. }
  1823. }.bind(this),
  1824. onFailure: function (xhr) {
  1825. o2.runCallback(callback, "requestFailure", [xhr]);
  1826. }.bind(this),
  1827. onError: function (text, error) {
  1828. o2.runCallback(callback, "error", [text, error]);
  1829. }.bind(this)
  1830. });
  1831. res.send();
  1832. return json;
  1833. };
  1834. _json.getJsonp = function (url, callback, async, callbackKey) {
  1835. var loadAsync = (async !== false);
  1836. var callbackKeyWord = callbackKey || "callback";
  1837. url = (url.indexOf("?") !== -1) ? url + "&v=" + o2.version.v : url + "?v=" + o2.version.v;
  1838. var res = new Request.JSONP({
  1839. url: o2.filterUrl(url),
  1840. secure: false,
  1841. method: "get",
  1842. noCache: true,
  1843. async: loadAsync,
  1844. callbackKey: callbackKeyWord,
  1845. onSuccess: function (responseJSON, responseText) {
  1846. o2.runCallback(callback, "success", [responseJSON, responseText]);
  1847. }.bind(this),
  1848. onFailure: function (xhr) {
  1849. o2.runCallback(callback, "requestFailure", [xhr]);
  1850. }.bind(this),
  1851. onError: function (text, error) {
  1852. o2.runCallback(callback, "error", [text, error]);
  1853. }.bind(this)
  1854. });
  1855. res.send();
  1856. };
  1857. var _loadLP = function (name) {
  1858. var jsPath = o2.session.path;
  1859. jsPath = jsPath + "/lp/" + name + ".js";
  1860. var r = new Request({
  1861. url: o2.filterUrl(jsPath),
  1862. async: false,
  1863. method: "get",
  1864. onSuccess: function (responseText) {
  1865. try {
  1866. Browser.exec(responseText);
  1867. } catch (e) {
  1868. }
  1869. },
  1870. onFailure: function (xhr) {
  1871. if (name != "zh-cn") {
  1872. _loadLP("zh-cn");
  1873. } else {
  1874. throw "loadLP Error: " + xhr.responseText;
  1875. }
  1876. }
  1877. });
  1878. r.send();
  1879. };
  1880. var _cacheUrls = (Browser.name == "ie") ? [] : [
  1881. /jaxrs\/form\/workorworkcompleted\/.+/ig,
  1882. /jaxrs\/form\/.+/ig,
  1883. /jaxrs\/script\/.+\/app\/.+\/imported/ig,
  1884. /jaxrs\/script\/portal\/.+\/name\/.+\/imported/ig,
  1885. /jaxrs\/script\/.+\/application\/.+\/imported/ig,
  1886. /jaxrs\/page\/.+\/portal\/.+/ig,
  1887. /jaxrs\/document\/.+/ig,
  1888. /jaxrs\/applicationdict\/.+/ig,
  1889. /jaxrs\/custom\/.+/ig,
  1890. /jaxrs\/definition\/idea.+/ig,
  1891. /jaxrs\/distribute\/assemble\/source\/.+/ig,
  1892. ];
  1893. // _restful_bak = function(method, address, data, callback, async, withCredentials, cache){
  1894. // var loadAsync = (async !== false);
  1895. // var credentials = (withCredentials !== false);
  1896. // address = (address.indexOf("?")!==-1) ? address+"&v="+o2.version.v : address+"?v="+o2.version.v;
  1897. // //var noCache = cache===false;
  1898. // var noCache = !cache;
  1899. //
  1900. //
  1901. // //if (Browser.name == "ie")
  1902. // if (_cacheUrls.length){
  1903. // for (var i=0; i<_cacheUrls.length; i++){
  1904. // _cacheUrls[i].lastIndex = 0;
  1905. // if (_cacheUrls[i].test(address)){
  1906. // noCache = false;
  1907. // break;
  1908. // }
  1909. // }
  1910. // }
  1911. // //var noCache = false;
  1912. // var res = new Request.JSON({
  1913. // url: o2.filterUrl(address),
  1914. // secure: false,
  1915. // method: method,
  1916. // emulation: false,
  1917. // noCache: noCache,
  1918. // async: loadAsync,
  1919. // withCredentials: credentials,
  1920. // onSuccess: function(responseJSON, responseText){
  1921. // // var xToken = this.getHeader("authorization");
  1922. // // if (!xToken) xToken = this.getHeader("x-token");
  1923. // var xToken = this.getHeader("x-token");
  1924. // if (xToken){
  1925. // if (window.layout){
  1926. // if (!layout.session) layout.session = {};
  1927. // layout.session.token = xToken;
  1928. // }
  1929. // }
  1930. // o2.runCallback(callback, "success", [responseJSON]);
  1931. // },
  1932. // onFailure: function(xhr){
  1933. // o2.runCallback(callback, "requestFailure", [xhr]);
  1934. // }.bind(this),
  1935. // onError: function(text, error){
  1936. // o2.runCallback(callback, "error", [text, error]);
  1937. // }.bind(this)
  1938. // });
  1939. //
  1940. // res.setHeader("Content-Type", "application/json; charset=utf-8");
  1941. // res.setHeader("Accept", "text/html,application/json,*/*");
  1942. // if (window.layout) {
  1943. // if (layout["debugger"]){
  1944. // res.setHeader("x-debugger", "true");
  1945. // }
  1946. // if (layout.session && layout.session.user){
  1947. // if (layout.session.user.token) {
  1948. // res.setHeader("x-token", layout.session.user.token);
  1949. // res.setHeader("authorization", layout.session.user.token);
  1950. // }
  1951. // }
  1952. // }
  1953. // //Content-Type application/x-www-form-urlencoded; charset=utf-8
  1954. // res.send(data);
  1955. // return res;
  1956. // };
  1957. var _resGetQueue = {};
  1958. var _checkRestful = function(address, callback){
  1959. if (_resGetQueue[address]){
  1960. var resPromise = _resGetQueue[address];
  1961. var p = new Promise(function(resolve, reject){
  1962. resPromise.then(function(){
  1963. resolve(resPromise.json);
  1964. }, function(){
  1965. reject(resPromise.err);
  1966. });
  1967. });
  1968. if (_resGetQueue[address].res) p.res = _resGetQueue[address].res;
  1969. if (_resGetQueue[address].actionWorker) p.actionWorker = _resGetQueue[address].actionWorker;
  1970. return p;
  1971. }
  1972. return false
  1973. }
  1974. _restful = function (method, address, data, callback, async, withCredentials, cache) {
  1975. var p = null;
  1976. if (method.toLowerCase()==="get" && async!==false){
  1977. p = _checkRestful(address, callback);
  1978. //if (p) return p;
  1979. }
  1980. var _addr = address;
  1981. var loadAsync = (async !== false);
  1982. var credentials = (withCredentials !== false);
  1983. address = (address.indexOf("?") !== -1) ? address + "&v=" + o2.version.v : address + "?v=" + o2.version.v;
  1984. //var noCache = cache===false;
  1985. var noCache = !cache;
  1986. //if (Browser.name == "ie")
  1987. if (_cacheUrls.length) {
  1988. for (var i = 0; i < _cacheUrls.length; i++) {
  1989. _cacheUrls[i].lastIndex = 0;
  1990. if (_cacheUrls[i].test(address)) {
  1991. noCache = false;
  1992. break;
  1993. }
  1994. }
  1995. }
  1996. var useWebWorker = (window.layout && layout.config && layout.config.useWebWorker);
  1997. //var noCache = false;
  1998. if (!loadAsync || !useWebWorker) {
  1999. var res;
  2000. if (!p) p = new Promise(function (resolve, reject) {
  2001. res = new Request.JSON({
  2002. url: o2.filterUrl(address),
  2003. secure: false,
  2004. method: method,
  2005. emulation: false,
  2006. noCache: noCache,
  2007. async: loadAsync,
  2008. withCredentials: credentials,
  2009. onSuccess: function (responseJSON, responseText) {
  2010. // var xToken = this.getHeader("authorization");
  2011. // if (!xToken) xToken = this.getHeader("x-token");
  2012. _resGetQueue[_addr] = null;
  2013. delete _resGetQueue[_addr];
  2014. var xToken = this.getHeader(o2.tokenName);
  2015. if (xToken) {
  2016. if (window.layout) {
  2017. if (!layout.session) layout.session = {};
  2018. layout.session.token = xToken;
  2019. }
  2020. if (layout.config && layout.config.sessionStorageEnable && window.sessionStorage) window.sessionStorage.setItem("o2LayoutSessionToken", xToken);
  2021. }
  2022. if (!loadAsync){
  2023. var r = o2.runCallback(callback, "success", [responseJSON], null);
  2024. resolve(r || responseJSON);
  2025. }else{
  2026. resolve(responseJSON);
  2027. }
  2028. //resolve(responseJSON);
  2029. //return o2.runCallback(callback, "success", [responseJSON],null, resolve);
  2030. },
  2031. onFailure: function (xhr) {
  2032. _resGetQueue[_addr] = null;
  2033. delete _resGetQueue[_addr];
  2034. if (!loadAsync){
  2035. var r = o2.runCallback(callback, "failure", [xhr, "", ""], null);
  2036. reject((r) ? r : {"xhr": xhr, "text": "", "error": "error"});
  2037. }else{
  2038. reject({"xhr": xhr, "text": "", "error": "error"});
  2039. }
  2040. }.bind(this),
  2041. onError: function (text, error) {
  2042. _resGetQueue[_addr] = null;
  2043. delete _resGetQueue[_addr];
  2044. if (!loadAsync){
  2045. var r = o2.runCallback(callback, "failure", [text, error], null);
  2046. reject((r) ? r : {"xhr": xhr, "text": text, "error": "error"});
  2047. }else{
  2048. reject({"xhr": xhr, "text": text, "error": "error"});
  2049. }
  2050. }.bind(this),
  2051. onComplete: function(){
  2052. _resGetQueue[_addr] = null;
  2053. delete _resGetQueue[_addr];
  2054. },
  2055. onCancel: function(){
  2056. _resGetQueue[_addr] = null;
  2057. delete _resGetQueue[_addr];
  2058. }
  2059. });
  2060. res.setHeader("Content-Type", "application/json; charset=utf-8");
  2061. res.setHeader("Accept", "text/html,application/json,*/*");
  2062. res.setHeader("Accept-Language", o2.languageName);
  2063. if (window.layout) {
  2064. if (layout["debugger"]) {
  2065. res.setHeader("x-debugger", "true");
  2066. }
  2067. var token = (layout.config && layout.config.sessionStorageEnable && window.sessionStorage) ? window.sessionStorage.getItem("o2LayoutSessionToken") : "";
  2068. if (!token) {
  2069. if (layout.session && (layout.session.user || layout.session.token)) {
  2070. token = layout.session.token;
  2071. if (!token && layout.session.user && layout.session.user.token) token = layout.session.user.token;
  2072. }
  2073. }
  2074. if (token) {
  2075. //res.setHeader(o2.tokenName, token);
  2076. res.setHeader("Authorization", token);
  2077. }
  2078. }
  2079. res.send(data);
  2080. }.bind(this)).catch(function (err) {
  2081. throw err;
  2082. });
  2083. // .then(function (responseJSON) {
  2084. //
  2085. // _resGetQueue[address].events.each(function(e){
  2086. // var r = o2.runCallback(e.callback, "success", [responseJSON], null);
  2087. // if (e.promise){
  2088. // e.promise
  2089. // }
  2090. // });
  2091. //
  2092. // return responseJSON;
  2093. // }, function(err){
  2094. // var r = o2.runCallback(callback, "failure", [xhr, "", ""], null);
  2095. // return r || err;
  2096. // }).catch(function (err) {
  2097. // throw err;
  2098. // //return Promise.reject(err);
  2099. // });
  2100. var oReturn = p;
  2101. //oReturn.res = res;
  2102. var resPromise = Promise.resolve(oReturn).then(function(json){
  2103. if (!loadAsync) return json;
  2104. resPromise.json = json;
  2105. var r = o2.runCallback(callback, "success", [json], null);
  2106. if (r) return r;
  2107. }, function(err){
  2108. if (!loadAsync) return err;
  2109. resPromise.err = err;
  2110. var r = o2.runCallback(callback, "failure", [err.xhr, err.text, err.error], null);
  2111. if (r) return Promise.reject(r);
  2112. return Promise.reject(err);
  2113. }).catch(function (err) { throw err;});
  2114. resPromise.res = res;
  2115. if (loadAsync) _resGetQueue[_addr] = resPromise;
  2116. return resPromise;
  2117. } else {
  2118. var workerMessage = {
  2119. method: method,
  2120. noCache: noCache,
  2121. loadAsync: loadAsync,
  2122. credentials: credentials,
  2123. address: o2.filterUrl(address),
  2124. body: data,
  2125. debug: (window.layout && layout["debugger"]),
  2126. token: (window.layout && layout.session && layout.session.user) ? layout.session.user.token : "",
  2127. tokenName: o2.tokenName
  2128. }
  2129. var actionWorker = new Worker("../o2_core/o2/actionWorker.js");
  2130. if (!p) p = new Promise(function (s, f) {
  2131. actionWorker.onmessage = function (e) {
  2132. _resGetQueue[_addr] = null;
  2133. delete _resGetQueue[_addr];
  2134. result = e.data;
  2135. if (result.type === "done") {
  2136. var xToken = result.data.xToken;
  2137. if (xToken) {
  2138. if (window.layout) {
  2139. if (!layout.session) layout.session = {};
  2140. layout.session.token = xToken;
  2141. }
  2142. }
  2143. s(result.data);
  2144. //o2.runCallback(callback, "success", [result.data], null, s);
  2145. } else {
  2146. f(result.data);
  2147. //o2.runCallback(callback, "failure", [result.data], null, f);
  2148. }
  2149. actionWorker.terminate();
  2150. }
  2151. actionWorker.postMessage(workerMessage);
  2152. }.bind(this));
  2153. // p = p.then(function (data) {
  2154. // return o2.runCallback(callback, "success", [data], null);
  2155. // }, function (data) {
  2156. // return o2.runCallback(callback, "failure", [data], null);
  2157. // });
  2158. //var oReturn = (callback.success && callback.success.addResolve) ? callback.success : callback;
  2159. var oReturn = p;
  2160. //oReturn.actionWorker = actionWorker;
  2161. var resPromise = Promise.resolve(oReturn).then(function(json){
  2162. resPromise.json = json;
  2163. var r = o2.runCallback(callback, "success", [json], null);
  2164. if (r) return r;
  2165. }, function(err){
  2166. resPromise.err = err;
  2167. var r = o2.runCallback(callback, "failure", [err], null);
  2168. if (r) return r;
  2169. }).catch(function (err) { throw err;});
  2170. resPromise.actionWorker = actionWorker;
  2171. _resGetQueue[_addr] = resPromise;
  2172. return resPromise;
  2173. //return oReturn;
  2174. //return callback;
  2175. }
  2176. //return res;
  2177. };
  2178. var _release = function (o) {
  2179. var type = typeOf(o);
  2180. switch (type) {
  2181. case "object":
  2182. for (var k in o) {
  2183. //if (o[k] && o[k].destroy) o[k].destroy();
  2184. o[k] = null;
  2185. }
  2186. break;
  2187. case "array":
  2188. for (var i = 0; i < o.length; i++) {
  2189. _release(o[i]);
  2190. if (o[i]) o[i] = null;
  2191. }
  2192. break;
  2193. }
  2194. };
  2195. var _defineProperties = Object.defineProperties || function (obj, properties) {
  2196. function convertToDescriptor(desc) {
  2197. function hasProperty(obj, prop) {
  2198. return Object.prototype.hasOwnProperty.call(obj, prop);
  2199. }
  2200. function isCallable(v) {
  2201. // NB: modify as necessary if other values than functions are callable.
  2202. return typeof v === "function";
  2203. }
  2204. if (typeof desc !== "object" || desc === null)
  2205. throw new TypeError("bad desc");
  2206. var d = {};
  2207. if (hasProperty(desc, "enumerable"))
  2208. d.enumerable = !!desc.enumerable;
  2209. if (hasProperty(desc, "configurable"))
  2210. d.configurable = !!desc.configurable;
  2211. if (hasProperty(desc, "value"))
  2212. d.value = desc.value;
  2213. if (hasProperty(desc, "writable"))
  2214. d.writable = !!desc.writable;
  2215. if (hasProperty(desc, "get")) {
  2216. var g = desc.get;
  2217. if (!isCallable(g) && typeof g !== "undefined")
  2218. throw new TypeError("bad get");
  2219. d.get = g;
  2220. }
  2221. if (hasProperty(desc, "set")) {
  2222. var s = desc.set;
  2223. if (!isCallable(s) && typeof s !== "undefined")
  2224. throw new TypeError("bad set");
  2225. d.set = s;
  2226. }
  2227. if (("get" in d || "set" in d) && ("value" in d || "writable" in d))
  2228. throw new TypeError("identity-confused descriptor");
  2229. return d;
  2230. }
  2231. if (typeof obj !== "object" || obj === null)
  2232. throw new TypeError("bad obj");
  2233. properties = Object(properties);
  2234. var keys = Object.keys(properties);
  2235. var descs = [];
  2236. for (var j = 0; j < keys.length; j++)
  2237. descs.push([keys[j], convertToDescriptor(properties[keys[j]])]);
  2238. for (var i = 0; i < descs.length; i++) {
  2239. if (Object.defineProperty && (Browser.name == "ie" && Browser.version != 8)) {
  2240. Object.defineProperty(obj, descs[i][0], descs[i][1]);
  2241. } else {
  2242. if (descs[i][1].value) obj[descs[i][0]] = descs[i][1].value;
  2243. if (descs[i][1].get) obj["get" + descs[i][0].capitalize()] = descs[i][1].get;
  2244. if (descs[i][1].set) obj["set" + descs[i][0].capitalize()] = descs[i][1].set;
  2245. }
  2246. }
  2247. return obj;
  2248. };
  2249. if (!Array.prototype.findIndex) {
  2250. Object.defineProperty(Array.prototype, 'findIndex', {
  2251. value: function (predicate) {
  2252. if (this == null) {
  2253. throw new TypeError('"this" is null or not defined');
  2254. }
  2255. var o = Object(this);
  2256. var len = o.length >>> 0;
  2257. if (typeof predicate !== 'function') {
  2258. throw new TypeError('predicate must be a function');
  2259. }
  2260. var thisArg = arguments[1];
  2261. var k = 0;
  2262. while (k < len) {
  2263. var kValue = o[k];
  2264. if (predicate.call(thisArg, kValue, k, o)) {
  2265. return k;
  2266. }
  2267. k++;
  2268. }
  2269. return -1;
  2270. }
  2271. });
  2272. }
  2273. if (!Array.prototype.find) {
  2274. Object.defineProperty(Array.prototype, 'find', {
  2275. value: function (predicate) {
  2276. if (this == null) {
  2277. throw new TypeError('"this" is null or not defined');
  2278. }
  2279. var o = Object(this);
  2280. var len = o.length >>> 0;
  2281. if (typeof predicate !== 'function') {
  2282. throw new TypeError('predicate must be a function');
  2283. }
  2284. var thisArg = arguments[1];
  2285. var k = 0;
  2286. while (k < len) {
  2287. var kValue = o[k];
  2288. if (predicate.call(thisArg, kValue, k, o)) {
  2289. return kValue;
  2290. }
  2291. k++;
  2292. }
  2293. return undefined;
  2294. }
  2295. });
  2296. }
  2297. var _txt = function (v) {
  2298. if (typeof v !== "string") return v;
  2299. var t = v.replace(/\</g, "&lt;");
  2300. t = t.replace(/\>/g, "&gt;");
  2301. return t;
  2302. };
  2303. var _dtxt = function (v) {
  2304. if (typeof v !== "string") return v;
  2305. var t = v.replace(/&lt;/g, "<");
  2306. t = t.replace(/&gt;/g, ">");
  2307. return t;
  2308. };
  2309. this.o2.Class = _Class;
  2310. this.o2.require = _require;
  2311. this.o2.requireApp = _requireApp;
  2312. this.o2.JSON = _json;
  2313. this.o2.loadLP = _loadLP;
  2314. this.o2.restful = _restful;
  2315. this.o2.release = _release;
  2316. this.o2.defineProperties = _defineProperties;
  2317. this.o2.txt = _txt;
  2318. this.o2.dtxt = _dtxt;
  2319. Object.repeatArray = function (o, count) {
  2320. var arr = [];
  2321. for (var i = 0; i < count; i++) {
  2322. arr.push(o)
  2323. }
  2324. return arr;
  2325. }
  2326. /**
  2327. * @summary 从服务器获取当前时间。
  2328. * @function getDateFromServer
  2329. * @memberOf o2
  2330. * @param {Boolean|Function} [async|callback] 可选,如果传入true或一个Function:表示异步调用此方法,传入的function为回调方法。如果省略此参数或传入false,则为同步方法
  2331. * @return {Date|Promise} 同步调用时,返回获取到的时间Date;异步调用时,返回Promise。
  2332. * @o2syntax
  2333. * o2.getDateFromServer(async);
  2334. * @o2syntax
  2335. * Date.getFromServer(async);
  2336. * @example
  2337. * //同步获取服务器时间
  2338. * var d = o2.getDateFromServer();
  2339. * //或者
  2340. * var d = Date.getFromServer();
  2341. *
  2342. * //通过回调方法异步获取服务器时间
  2343. * o2.getDateFromServer(function(d){
  2344. * console.log(d); //从服务器获取的当前时间
  2345. * });
  2346. * //或者
  2347. * Date.getFromServer(function(d){
  2348. * console.log(d); //从服务器获取的当前时间
  2349. * });
  2350. *
  2351. * //通过Promise异步获取服务器时间
  2352. * o2.getDateFromServer(true).then((d)=>{
  2353. * console.log(d); //从服务器获取的当前时间
  2354. * });
  2355. * //或者
  2356. * Date.getFromServer(true).then((d)=>{
  2357. * console.log(d); //从服务器获取的当前时间
  2358. * });
  2359. */
  2360. this.o2.getDateFromServer = Date.getFromServer = function (async) {
  2361. var d;
  2362. // var cb = ((async && o2.typeOf(async) == "function") ? async : null) || function (json) {
  2363. // //var cb = function(json){
  2364. // d = Date.parse(json.data.serverTime);
  2365. // return d;
  2366. // };
  2367. var cb = function(json){
  2368. d = Date.parse(json.data.serverTime);
  2369. return d;
  2370. }
  2371. var promise = o2.Actions.get("x_program_center").echo(cb, null, !!async);
  2372. if (async && o2.typeOf(async) == "function"){
  2373. return promise.then(async);
  2374. }
  2375. return (!!async) ? promise : d;
  2376. };
  2377. var _promiseAll = function (p) {
  2378. if (o2.typeOf(p) == "array") {
  2379. if (p.some(function (e) {
  2380. return (e && o2.typeOf(e.then) == "function")
  2381. })) {
  2382. return Promise.all(p);
  2383. } else {
  2384. return {
  2385. "then": function (s) {
  2386. if (s) {
  2387. var r = s(p);
  2388. return (r && r.then && o2.typeOf(r.then) == "function") ? r : this;
  2389. }
  2390. return this;
  2391. }
  2392. };
  2393. }
  2394. } else {
  2395. if (p && o2.typeOf(p.then) == "function") {
  2396. return Promise.resolve(p);
  2397. } else {
  2398. return {
  2399. "then": function (s) {
  2400. if (s) {
  2401. var r = s(p);
  2402. return (r && r.then && o2.typeOf(r.then) == "function") ? r : this;
  2403. }
  2404. return this;
  2405. }
  2406. };
  2407. //return new Promise(function(s){s(p); return this;});
  2408. }
  2409. }
  2410. // var method = (o2.typeOf(p)=="array") ? "all" : "resolve";
  2411. // return Promise[method](p);
  2412. }
  2413. o2.promiseAll = _promiseAll;
  2414. })();
  2415. o2.defer = function(fn, timer, bind, pars){
  2416. if (fn.timerId) clearTimeout(fn.timerId);
  2417. fn.timerId = setTimeout(function(){
  2418. fn.timerId = null;
  2419. fn.apply((bind || this), pars);
  2420. }, timer);
  2421. }
  2422. o2.core = true;
  2423. /** ***** BEGIN LICENSE BLOCK *****
  2424. * |------------------------------------------------------------------------------|
  2425. * | O2OA 活力办公 创意无限 o2.more.js |
  2426. * |------------------------------------------------------------------------------|
  2427. * | Distributed under the AGPL license: |
  2428. * |------------------------------------------------------------------------------|
  2429. * | Copyright © 2018, o2oa.net, o2server.io O2 Team |
  2430. * | All rights reserved. |
  2431. * |------------------------------------------------------------------------------|
  2432. *
  2433. * This file is part of O2OA.
  2434. *
  2435. * O2OA is free software: you can redistribute it and/or modify
  2436. * it under the terms of the GNU Affero General Public License as published by
  2437. * the Free Software Foundation, either version 3 of the License, or
  2438. * (at your option) any later version.
  2439. *
  2440. * O2OA is distributed in the hope that it will be useful,
  2441. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  2442. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  2443. * GNU Affero General Public License for more details.
  2444. *
  2445. * You should have received a copy of the GNU General Public License
  2446. * along with Foobar. If not, see <https://www.gnu.org/licenses/>.
  2447. *
  2448. * ***** END LICENSE BLOCK ******/
  2449. (function () {
  2450. o2.getCenterPosition = function (el, width, height) {
  2451. var elPositon = $(el).getPosition();
  2452. var elSize = $(el).getSize();
  2453. var node = $("layout");
  2454. var size = (node) ? $(node).getSize() : $(document.body).getSize();
  2455. var top = (elPositon.y + elSize.y) / 2 - (height / 2);
  2456. var left = (elPositon.x + elSize.x) / 2 - (width / 2);
  2457. if ((left + width) > size.x) {
  2458. left = size.x - width - 10;
  2459. }
  2460. if ((top + height) > size.y) {
  2461. top = size.y - height - 10;
  2462. }
  2463. return {"x": left, "y": top};
  2464. };
  2465. o2.getMarkSize = function (node) {
  2466. var size;
  2467. if (!node) {
  2468. size = $(document.body).getSize();
  2469. var winSize = $(window).getSize();
  2470. var height = size.y;
  2471. var width = size.x;
  2472. if (height < winSize.y) height = winSize.y;
  2473. if (width < winSize.x) width = winSize.x;
  2474. return {x: size.x, y: height};
  2475. } else {
  2476. size = $(node).getSize();
  2477. return {x: size.x, y: size.y};
  2478. }
  2479. };
  2480. o2.json = function (jsonString, fun) {
  2481. var obj = JSON.decode(jsonString);
  2482. var p = fun.split(".");
  2483. var tmp = obj;
  2484. p.each(function (item) {
  2485. if (item.indexOf("[") !== -1) {
  2486. var x = item.split("[");
  2487. var i = parseInt(x[1].substr(0, x[1].indexOf("]")));
  2488. tmp = tmp[x[0]][i];
  2489. } else {
  2490. tmp = tmp[item];
  2491. }
  2492. });
  2493. return tmp;
  2494. };
  2495. o2.getHTMLTemplate = function (url, callback, async) {
  2496. var loadAsync = (async !== false);
  2497. var res = new Request.HTML({
  2498. url: url,
  2499. async: loadAsync,
  2500. method: "get",
  2501. onSuccess: function (responseTree, responseElements, responseHTML, responseJavaScript) {
  2502. o2.runCallback(callback, "success", [responseTree, responseElements, responseHTML, responseJavaScript]);
  2503. }.bind(this),
  2504. onFailure: function (xhr) {
  2505. o2.runCallback(callback, "requestFailure", [xhr]);
  2506. }
  2507. });
  2508. res.send();
  2509. };
  2510. o2.getRequestText = function (url, callback, async) {
  2511. var loadAsync = (async !== false);
  2512. url = (url.indexOf("?") !== -1) ? url + "&v=" + o2.version.v : url + "?v=" + o2.version.v;
  2513. var res = new Request({
  2514. url: url,
  2515. async: loadAsync,
  2516. method: "get",
  2517. onSuccess: function (responseText, responseXML) {
  2518. o2.runCallback(callback, "success", [responseText, responseXML]);
  2519. }.bind(this),
  2520. onFailure: function (xhr) {
  2521. o2.runCallback(callback, "requestFailure", [xhr]);
  2522. }
  2523. });
  2524. res.send();
  2525. };
  2526. o2.encodeJsonString = function (str) {
  2527. var tmp = [str];
  2528. var dataStr = (JSON.encode(tmp));
  2529. return dataStr.substr(2, dataStr.length - 4);
  2530. };
  2531. o2.decodeJsonString = function (str) {
  2532. var tmp = "[\"" + str + "\"]";
  2533. var dataObj = (JSON.decode(tmp));
  2534. return dataObj[0];
  2535. };
  2536. o2.getTextSize = function (text, styles) {
  2537. var tmpSpan = new Element("span", {
  2538. "text": text,
  2539. "styles": styles
  2540. }).inject($(document.body));
  2541. var size = tmpSpan.getSize();
  2542. tmpSpan.destroy();
  2543. return size;
  2544. };
  2545. o2.getCenter = function (size, target, offset) {
  2546. if (!target) target = document.body;
  2547. var targetSize = target.getSize();
  2548. var targetPosition = target.getPosition(offset);
  2549. var targetScroll = target.getScroll();
  2550. var x = targetSize.x / 2;
  2551. var y = targetSize.y / 2;
  2552. x = x - (size.x / 2);
  2553. y = y - (size.y / 2);
  2554. x = x + targetPosition.x;
  2555. y = y + targetPosition.y;
  2556. x = x + targetScroll.x;
  2557. y = y + targetScroll.y;
  2558. return {"x": x, "y": y};
  2559. };
  2560. o2.getEPointer = function (e) {
  2561. var x = 0;
  2562. var y = 0;
  2563. if (typeOf(e) == "element") {
  2564. var position = e.getPosition(this.content);
  2565. x = position.x;
  2566. y = position.y;
  2567. } else {
  2568. if (Browser.name == "firefox") {
  2569. x = parseFloat(e.event.clientX || e.event.x);
  2570. y = parseFloat(e.event.clientY || e.event.y);
  2571. } else {
  2572. x = parseFloat(e.event.x);
  2573. y = parseFloat(e.event.y);
  2574. }
  2575. if (e.target) {
  2576. var position = e.target.getPosition(this.content);
  2577. x = position.x;
  2578. y = position.y;
  2579. }
  2580. // }
  2581. }
  2582. return {"x": x, "y": y};
  2583. };
  2584. o2.getParent = function (node, tag) {
  2585. var pNode = node.parentElement;
  2586. while (pNode && pNode.tagName.toString().toLowerCase() !== tag.toString().toLowerCase()) {
  2587. pNode = pNode.parentElement;
  2588. }
  2589. return pNode;
  2590. };
  2591. o2.getOffset = function (evt) {
  2592. if (Browser.name === "firefox") {
  2593. return {
  2594. "offsetX": evt.layerX,
  2595. "offsetY": evt.layerY
  2596. };
  2597. } else {
  2598. return {
  2599. "offsetX": evt.offsetX,
  2600. "offsetY": evt.offsetY
  2601. }
  2602. }
  2603. };
  2604. /**
  2605. * @summary 对页面进行缩放。
  2606. * @function zoom
  2607. * @memberOf o2
  2608. * @param {Number} [scale] 缩放的比例。1表示原始大小
  2609. * @o2syntax
  2610. * o2.zoom(scale);
  2611. * @example
  2612. * //将页面放大到150%大小
  2613. * o2.zoom(1.5);
  2614. */
  2615. o2.zoom = function (scale) {
  2616. if (!layout) layout = {};
  2617. if (layout && !layout.userLayout) layout.userLayout = {};
  2618. layout.userLayout.scale = scale;
  2619. // var s = (1 / layout.userLayout.scale) * 100;
  2620. // var p = s + "%";
  2621. // document.id(document.documentElement).setStyles({
  2622. // "transform": "scale(" + layout.userLayout.scale + ")",
  2623. // "transform-origin": "0 0",
  2624. // "width": p,
  2625. // "height": p
  2626. // });
  2627. document.body.style.zoom = scale;
  2628. if (layout.desktop){
  2629. if (layout.desktop.resizeHeight) layout.desktop.resizeHeight();
  2630. }
  2631. };
  2632. if (String.implement) String.implement({
  2633. "getAllIndexOf": function (str) {
  2634. var idxs = [];
  2635. var idx = this.indexOf(str);
  2636. while (idx !== -1) {
  2637. idxs.push(idx);
  2638. idx = this.indexOf(str, idx + 1);
  2639. }
  2640. return idxs;
  2641. }
  2642. });
  2643. if (Array.implement) Array.implement({
  2644. "trim": function () {
  2645. var arr = [];
  2646. this.each(function (v) {
  2647. if (v) arr.push(v);
  2648. });
  2649. return arr;
  2650. },
  2651. "isIntersect": function (arr) {
  2652. return this.some(function (item) {
  2653. return (arr.indexOf(item) !== -1);
  2654. })
  2655. },
  2656. "add": function(newKey, newValue, overwrite){
  2657. if (arguments.length<2){
  2658. this[this.length] = newKey;
  2659. //this.push(newKey);
  2660. }else{
  2661. if (o2.typeOf(newKey)=="number"){
  2662. if (newKey<this.length){
  2663. if (overwrite) this[newKey] = newValue;
  2664. }else if (newKey==this.length){
  2665. //this.push(newValue);
  2666. this[this.length] = newValue;
  2667. }
  2668. }
  2669. }
  2670. }
  2671. });
  2672. if (!Array.prototype.find) {
  2673. if (Array.implement) Array.implement({
  2674. "find": this.find || function (callback, thisArg) {
  2675. for (var i = 0; i < this.length; i++) {
  2676. if (callback.apply((thisArg || this), this[i], i, this)) {
  2677. return this[i];
  2678. }
  2679. }
  2680. return undefined;
  2681. }
  2682. });
  2683. }
  2684. var styleString = Element.getComputedStyle;
  2685. function styleNumber(element, style) {
  2686. return styleString(element, style).toInt() || 0;
  2687. }
  2688. function topBorder(element) {
  2689. return styleNumber(element, 'border-top-width');
  2690. }
  2691. function leftBorder(element) {
  2692. return styleNumber(element, 'border-left-width');
  2693. }
  2694. function isBody(element) {
  2695. return (/^(?:body|html)$/i).test(element.tagName);
  2696. }
  2697. var heightComponents = ['height', 'paddingTop', 'paddingBottom', 'borderTopWidth', 'borderBottomWidth'],
  2698. widthComponents = ['width', 'paddingLeft', 'paddingRight', 'borderLeftWidth', 'borderRightWidth'];
  2699. var svgCalculateSize = function (el) {
  2700. var gCS = window.getComputedStyle(el),
  2701. bounds = {x: 0, y: 0};
  2702. heightComponents.each(function (css) {
  2703. bounds.y += parseFloat(gCS[css]);
  2704. });
  2705. widthComponents.each(function (css) {
  2706. bounds.x += parseFloat(gCS[css]);
  2707. });
  2708. return bounds;
  2709. };
  2710. [Document, Window].invoke('implement', {
  2711. getSize: function () {
  2712. var doc = this.getDocument();
  2713. doc = ((!doc.compatMode || doc.compatMode == 'CSS1Compat') && (!layout || !layout.userLayout || !layout.userLayout.scale || layout.userLayout.scale == 1)) ? doc.html : doc.body;
  2714. return {x: doc.clientWidth, y: doc.clientHeight};
  2715. },
  2716. });
  2717. if (window.Element && Element.implement) Element.implement({
  2718. "isIntoView": function () {
  2719. // var pNode = this.getParent();
  2720. // while (pNode && ((pNode.getScrollSize().y-(pNode.getComputedSize().height+1)<=0) || pNode.getStyle("overflow")==="visible")) pNode = pNode.getParent();
  2721. //
  2722. var pNode = this.getParentSrcollNode();
  2723. if (!pNode) pNode = document.body;
  2724. var size = pNode.getSize();
  2725. var srcoll = pNode.getScroll();
  2726. var p = (pNode == window) ? {"x": 0, "y": 0} : this.getPosition(pNode);
  2727. var nodeSize = this.getSize();
  2728. //return (p.x-srcoll.x>=0 && p.y-srcoll.y>=0) && (p.x+nodeSize.x<size.x+srcoll.x && p.y+nodeSize.y<size.y+srcoll.y);
  2729. return (p.x - srcoll.x >= 0 && p.y >= 0) && (p.x + nodeSize.x < size.x + srcoll.x && p.y + nodeSize.y < size.y)
  2730. },
  2731. "appendHTML": function (html, where) {
  2732. if (this.insertAdjacentHTML) {
  2733. var whereText = "beforeEnd";
  2734. if (where === "before") whereText = "beforeBegin";
  2735. if (where === "after") whereText = "afterEnd";
  2736. if (where === "bottom") whereText = "beforeEnd";
  2737. if (where === "top") whereText = "afterBegin";
  2738. this.insertAdjacentHTML(whereText, html);
  2739. } else {
  2740. if (where === "bottom") this.innerHTML = this.innerHTML + html;
  2741. if (where === "top") this.innerHTML = html + this.innerHTML;
  2742. }
  2743. },
  2744. "positionTo": function (x, y) {
  2745. var left = x.toFloat();
  2746. var top = y.toFloat();
  2747. var offsetNode = this.getOffsetParent();
  2748. if (offsetNode) {
  2749. var offsetPosition = offsetNode.getPosition();
  2750. left = left - offsetPosition.x;
  2751. top = top - offsetPosition.y;
  2752. }
  2753. this.setStyles({"top": top, "left": left});
  2754. return this;
  2755. },
  2756. "getBorder": function () {
  2757. var positions = ["top", "left", "right", "bottom"];
  2758. var styles = ["color", "style", "width"];
  2759. var obj = {};
  2760. positions.each(function (position) {
  2761. styles.each(function (style) {
  2762. var key = "border-" + position + "-" + style;
  2763. obj[key] = this.getStyle(key);
  2764. }.bind(this));
  2765. }.bind(this));
  2766. return obj;
  2767. },
  2768. "isOutside": function (e) {
  2769. var elementCoords = this.getCoordinates();
  2770. var targetCoords = this.getCoordinates();
  2771. if (((e.page.x < elementCoords.left || e.page.x > (elementCoords.left + elementCoords.width)) ||
  2772. (e.page.y < elementCoords.top || e.page.y > (elementCoords.top + elementCoords.height))) &&
  2773. ((e.page.x < targetCoords.left || e.page.x > (targetCoords.left + targetCoords.width)) ||
  2774. (e.page.y < targetCoords.top || e.page.y > (targetCoords.top + targetCoords.height)))) return true;
  2775. return false;
  2776. },
  2777. "getAbsolutePosition": function () {
  2778. var styleLeft = 0;
  2779. var styleTop = 0;
  2780. var node = this;
  2781. styleLeft = node.offsetLeft;
  2782. styleTop = node.offsetTop;
  2783. node = node.parentElement;
  2784. while (node && node.tagName.toString().toLowerCase() !== "body") {
  2785. styleLeft += node.offsetLeft;
  2786. styleTop += node.offsetTop;
  2787. node = node.offsetParent;
  2788. }
  2789. return {x: styleLeft, y: styleTop};
  2790. },
  2791. "tweenScroll": function (to, time) {
  2792. if (!this.tweenScrollQueue) {
  2793. this.tweenScrollQueue = [];
  2794. }
  2795. if (this.tweenScrollQueue.length) {
  2796. this.tweenScrollQueue.push(to);
  2797. } else {
  2798. this.tweenScrollQueue.push(to);
  2799. this.doTweenScrollQueue(time);
  2800. }
  2801. },
  2802. "doTweenScrollQueue": function (time) {
  2803. if (this.tweenScrollQueue.length) {
  2804. var i = this.tweenScrollQueue.length;
  2805. var to = this.tweenScrollQueue[this.tweenScrollQueue.length - 1];
  2806. var scroll = this.getScroll();
  2807. var dy = to - scroll.y;
  2808. var step = dy / time;
  2809. var count = 0;
  2810. var move = 0;
  2811. var id = window.setInterval(function () {
  2812. this.scrollTo(0, scroll.y + count * step);
  2813. count++;
  2814. if (count > time) {
  2815. window.clearInterval(id);
  2816. for (var x = 1; x <= i; x++) this.tweenScrollQueue.shift();
  2817. if (this.tweenScrollQueue.length) this.doTweenScrollQueue(time);
  2818. }
  2819. }.bind(this), 1);
  2820. }
  2821. },
  2822. "isPointIn": function (px, py, offX, offY, el) {
  2823. if (!offX) offX = 0;
  2824. if (!offY) offY = 0;
  2825. var position = this.getPosition(el);
  2826. var size = this.getSize();
  2827. return (position.x - offX <= px && position.x + size.x + offX >= px && position.y - offY <= py && position.y + size.y + offY >= py);
  2828. },
  2829. "isInPointInRect": function (sx, sy, ex, ey) {
  2830. var position = this.getPosition();
  2831. var size = this.getSize();
  2832. var p1 = {"x": position.x, "y": position.y};
  2833. var p2 = {"x": position.x + size.x, "y": position.y};
  2834. var p3 = {"x": position.x + size.x, "y": position.y + size.y};
  2835. var p4 = {"x": position.x, "y": position.y + size.y};
  2836. var sp = {"x": Math.min(sx, ex), "y": Math.min(sy, ey)};
  2837. var ep = {"x": Math.max(sx, ex), "y": Math.max(sy, ey)};
  2838. if (p1.x >= sp.x && p1.y >= sp.y && p1.x <= ep.x && p1.y <= ep.y) return true;
  2839. if (p2.x >= sp.x && p2.y >= sp.y && p2.x <= ep.x && p2.y <= ep.y) return true;
  2840. if (p3.x >= sp.x && p3.y >= sp.y && p3.x <= ep.x && p3.y <= ep.y) return true;
  2841. if (p4.x >= sp.x && p4.y >= sp.y && p4.x <= ep.x && p4.y <= ep.y) return true;
  2842. if (p3.x >= sp.x && p3.y >= sp.y && p1.x <= sp.x && p1.y <= sp.y) return true;
  2843. if (p3.x >= ep.x && p3.y >= ep.y && p1.x <= ep.x && p1.y <= ep.y) return true;
  2844. if (p1.x <= sp.x && p2.x >= sp.x && p1.y >= sp.y && p4.y <= ep.y) return true;
  2845. if (p1.y <= sp.y && p4.y >= sp.y && p1.x >= sp.x && p2.x <= ep.x) return true;
  2846. return false;
  2847. },
  2848. "isOverlap": function (node) {
  2849. var p = node.getPosition();
  2850. var s = node.getSize();
  2851. return this.isInPointInRect(p.x, p.y, p.x + s.x, p.y + s.y);
  2852. },
  2853. "getUsefulSize": function () {
  2854. var size = this.getSize();
  2855. var borderLeft = this.getStyle("border-left").toInt();
  2856. var borderBottom = this.getStyle("border-bottom").toInt();
  2857. var borderTop = this.getStyle("border-top").toInt();
  2858. var borderRight = this.getStyle("border-right").toInt();
  2859. var paddingLeft = this.getStyle("padding-left").toInt();
  2860. var paddingBottom = this.getStyle("padding-bottom").toInt();
  2861. var paddingTop = this.getStyle("padding-top").toInt();
  2862. var paddingRight = this.getStyle("padding-right").toInt();
  2863. var x = size.x - paddingLeft - paddingRight;
  2864. var y = size.y - paddingTop - paddingBottom;
  2865. return {"x": x, "y": y};
  2866. },
  2867. "clearStyles": function (isChild) {
  2868. this.removeProperty("style");
  2869. if (isChild) {
  2870. var subNode = this.getFirst();
  2871. while (subNode) {
  2872. subNode.clearStyles(isChild);
  2873. subNode = subNode.getNext();
  2874. }
  2875. }
  2876. },
  2877. "maskIf": function (styles, click) {
  2878. var style = {
  2879. "background-color": "#666666",
  2880. "opacity": 0.4,
  2881. "z-index": 100
  2882. };
  2883. if (styles) {
  2884. style = Object.merge(style, styles);
  2885. }
  2886. var position = this.getPosition(this.getOffsetParent());
  2887. this.mask({
  2888. "destroyOnHide": true,
  2889. "style": style,
  2890. "useIframeShim": true,
  2891. "iframeShimOptions": {"browsers": true},
  2892. "onShow": function () {
  2893. this.shim.shim.setStyles({
  2894. "opacity": 0,
  2895. "top": "" + position.y + "px",
  2896. "left": "" + position.x + "px"
  2897. });
  2898. },
  2899. "onClick": click
  2900. });
  2901. },
  2902. "scrollIn": function (where) {
  2903. var wh = (where) ? where.toString().toLowerCase() : "center";
  2904. if (Browser.name == "ie" || Browser.name == "safari") {
  2905. var scrollNode = this.getParentSrcollNode();
  2906. var scrollFx = new Fx.Scroll(scrollNode);
  2907. var scroll = scrollNode.getScroll();
  2908. var size = scrollNode.getSize();
  2909. var thisSize = this.getComputedSize();
  2910. var p = this.getPosition(scrollNode);
  2911. if (wh == "start") {
  2912. var top = 0;
  2913. scrollFx.start(scroll.x, p.y - top + scroll.y);
  2914. } else if (wh == "end") {
  2915. var bottom = size.y - thisSize.totalHeight;
  2916. scrollFx.start(scroll.x, p.y - bottom + scroll.y);
  2917. } else {
  2918. var center = size.y / 2 - thisSize.totalHeight / 2;
  2919. scrollFx.start(scroll.x, p.y - center + scroll.y);
  2920. }
  2921. } else {
  2922. if (wh !== "start" && wh !== "end") wh = "center"
  2923. this.scrollIntoView({"behavior": "smooth", "block": wh, "inline": "nearest"});
  2924. }
  2925. },
  2926. scrollToNode: function (el, where) {
  2927. var scrollSize = this.getScrollSize();
  2928. if (!scrollSize.y) return true;
  2929. var wh = (where) ? where.toString().toLowerCase() : "bottom";
  2930. var node = $(el);
  2931. var size = node.getComputedSize();
  2932. var p = node.getPosition(this);
  2933. var thisSize = this.getComputedSize();
  2934. var scroll = this.getScroll();
  2935. if (wh === "top") {
  2936. var n = (p.y - thisSize.computedTop);
  2937. if (n < 0) this.scrollTo(scroll.x, scroll.y + n);
  2938. n = (size.totalHeight + p.y - thisSize.computedTop) - thisSize.height;
  2939. if (n > 0) this.scrollTo(scroll.x, scroll.y + n);
  2940. } else {
  2941. var n = (size.totalHeight + p.y - thisSize.computedTop) - thisSize.height;
  2942. if (n > 0) this.scrollTo(scroll.x, scroll.y + n);
  2943. n = p.y - thisSize.computedTop;
  2944. if (n < 0) this.scrollTo(scroll.x, scroll.y + n);
  2945. }
  2946. },
  2947. "getInnerStyles": function () {
  2948. var styles = {};
  2949. style = this.get("style");
  2950. if (style) {
  2951. var styleArr = style.split(/\s*\;\s*/g);
  2952. styleArr.each(function (s) {
  2953. if (s) {
  2954. var sarr = s.split(/\s*\:\s*/g);
  2955. styles[sarr[0]] = (sarr.length > 1) ? sarr[1] : ""
  2956. }
  2957. }.bind(this));
  2958. }
  2959. return styles;
  2960. },
  2961. "getInnerProperties": function () {
  2962. var properties = {};
  2963. if (this.attributes.length) {
  2964. for (var i = 0; i < this.attributes.length; i++) {
  2965. properties[this.attributes[i].nodeName] = this.attributes[i].nodeValue;
  2966. }
  2967. }
  2968. return properties;
  2969. },
  2970. "getZIndex": function () {
  2971. var n = this;
  2972. var i = 0;
  2973. while (n) {
  2974. if (n.getStyle("position") === "absolute") {
  2975. var idx = n.getStyle("z-index");
  2976. i = (idx && idx.toFloat() > i) ? idx.toFloat() + 1 : 0;
  2977. break;
  2978. }
  2979. n = n.getParent();
  2980. }
  2981. return i;
  2982. },
  2983. "getParentSrcollNode": function () {
  2984. var node = this.getParent();
  2985. while (node && (node.getScrollSize().y - 2 <= node.getSize().y || (node.getStyle("overflow") !== "auto" && node.getStyle("overflow-y") !== "auto"))) {
  2986. node = node.getParent();
  2987. }
  2988. return node || null;
  2989. },
  2990. "getEdgeHeight": function (notMargin) {
  2991. var h = 0;
  2992. h += (this.getStyle("border-top-width").toFloat() || 0) + (this.getStyle("border-bottom-width").toFloat() || 0);
  2993. h += (this.getStyle("padding-top").toFloat() || 0) + (this.getStyle("padding-bottom").toFloat() || 0);
  2994. if (!notMargin) h += (this.getStyle("margin-top").toFloat() || 0) + (this.getStyle("margin-bottom").toFloat() || 0);
  2995. return h;
  2996. },
  2997. "getEdgeWidth": function (notMargin) {
  2998. var h = 0;
  2999. h += (this.getStyle("border-left-width").toFloat() || 0) + (this.getStyle("border-right-width").toFloat() || 0);
  3000. h += (this.getStyle("padding-left").toFloat() || 0) + (this.getStyle("padding-right").toFloat() || 0);
  3001. if (!notMargin) h += (this.getStyle("margin-left").toFloat() || 0) + (this.getStyle("margin-right").toFloat() || 0);
  3002. return h;
  3003. },
  3004. "getSize": function () {
  3005. if ((/^(?:body|html)$/i).test(this.tagName)) return this.getWindow().getSize();
  3006. if (!window.getComputedStyle) return {x: this.offsetWidth, y: this.offsetHeight};
  3007. if (this.get('tag') == 'svg') return svgCalculateSize(this);
  3008. try {
  3009. if (!layout || !layout.userLayout || !layout.userLayout.scale || layout.userLayout.scale == 1) {
  3010. var bounds = this.getBoundingClientRect();
  3011. return {x: bounds.width, y: bounds.height};
  3012. } else {
  3013. return {"x": this.offsetWidth.toFloat(), "y": this.offsetHeight.toFloat()};
  3014. }
  3015. } catch (e) {
  3016. return {x: 0, y: 0};
  3017. }
  3018. },
  3019. "getScaleOffsets": function () {
  3020. var hasGetBoundingClientRect = this.getBoundingClientRect;
  3021. //<1.4compat>
  3022. //hasGetBoundingClientRect = hasGetBoundingClientRect && !Browser.Platform.ios;
  3023. //</1.4compat>
  3024. if (hasGetBoundingClientRect) {
  3025. var bound = this.getBoundingClientRect();
  3026. var boundLeft = bound.left;
  3027. var boundTop = bound.top;
  3028. if (!layout || !layout.userLayout || !layout.userLayout.scale || layout.userLayout.scale == 1) {
  3029. } else {
  3030. // boundLeft = boundLeft / layout.userLayout.scale;
  3031. // boundTop = boundTop / layout.userLayout.scale;
  3032. }
  3033. var html = document.id(this.getDocument().documentElement);
  3034. var htmlScroll = html.getScroll();
  3035. var elemScrolls = this.getScrolls();
  3036. var isFixed = (Element.getComputedStyle(this, 'position') == 'fixed');
  3037. return {
  3038. x: boundLeft.toFloat() + elemScrolls.x + ((isFixed) ? 0 : htmlScroll.x) - html.clientLeft,
  3039. y: boundTop.toFloat() + elemScrolls.y + ((isFixed) ? 0 : htmlScroll.y) - html.clientTop
  3040. };
  3041. }
  3042. var element = this, position = {x: 0, y: 0};
  3043. if (isBody(this)) return position;
  3044. while (element && !isBody(element)) {
  3045. position.x += element.offsetLeft;
  3046. position.y += element.offsetTop;
  3047. //<1.4compat>
  3048. if (Browser.firefox) {
  3049. if (!borderBox(element)) {
  3050. position.x += leftBorder(element);
  3051. position.y += topBorder(element);
  3052. }
  3053. var parent = element.parentNode;
  3054. if (parent && styleString(parent, 'overflow') != 'visible') {
  3055. position.x += leftBorder(parent);
  3056. position.y += topBorder(parent);
  3057. }
  3058. } else if (element != this && Browser.safari) {
  3059. position.x += leftBorder(element);
  3060. position.y += topBorder(element);
  3061. }
  3062. //</1.4compat>
  3063. element = element.offsetParent;
  3064. }
  3065. //<1.4compat>
  3066. if (Browser.firefox && !borderBox(this)) {
  3067. position.x -= leftBorder(this);
  3068. position.y -= topBorder(this);
  3069. }
  3070. //</1.4compat>
  3071. return position;
  3072. },
  3073. getPosition: function (relative) {
  3074. var offset = this.getScaleOffsets(),
  3075. scroll = this.getScrolls();
  3076. var position = {
  3077. x: offset.x - scroll.x,
  3078. y: offset.y - scroll.y
  3079. };
  3080. if (relative && (relative = document.id(relative))) {
  3081. var relativePosition = relative.getPosition();
  3082. return {
  3083. x: position.x - relativePosition.x - leftBorder(relative),
  3084. y: position.y - relativePosition.y - topBorder(relative)
  3085. };
  3086. }
  3087. return position;
  3088. }
  3089. });
  3090. Object.copy = function (from, to) {
  3091. Object.each(from, function (value, key) {
  3092. switch (typeOf(value)) {
  3093. case "object":
  3094. if (!to[key]) to[key] = {};
  3095. Object.copy(value, to[key]);
  3096. break;
  3097. default:
  3098. to[key] = value;
  3099. }
  3100. });
  3101. };
  3102. if (window.JSON) JSON.format = JSON.encode;
  3103. if (window.Slick) {
  3104. Slick.definePseudo('src', function (value) {
  3105. return Element.get(this, "src").indexOf(value) !== -1;
  3106. });
  3107. Slick.definePseudo('srcarr', function (value) {
  3108. var vList = value.split(",");
  3109. var src = Element.get(this, "src");
  3110. var flag = false;
  3111. for (var i = 0; i < vList.length; i++) {
  3112. if (src.indexOf(vList[i]) !== -1) {
  3113. flag = true;
  3114. break;
  3115. }
  3116. }
  3117. return flag;
  3118. });
  3119. Slick.definePseudo('ahref', function (value) {
  3120. var href = Element.get(this, "href");
  3121. if (!href) href = "";
  3122. href = href.toString().toLowerCase();
  3123. return (href.indexOf(value) !== -1);
  3124. });
  3125. Slick.definePseudo('rowspanBefore', function (line) {
  3126. var tr = MWF.getParent(this, "tr");
  3127. var rowspan = this.get("rowspan").toInt() || 1;
  3128. var currentRowIndex = tr.rowIndex.toInt();
  3129. return rowspan > 1 && currentRowIndex < line.toInt() && currentRowIndex + rowspan - 1 >= line;
  3130. });
  3131. Slick.definePseudo('rowspan', function () {
  3132. var rowspan = this.get("rowspan").toInt() || 1;
  3133. return rowspan > 1;
  3134. });
  3135. Slick.definePseudo('colspanBefore', function (col) {
  3136. var tr = MWF.getParent(this, "tr");
  3137. var colspan = this.get("colspan").toInt() || 1;
  3138. var currentColIndex = this.cellIndex.toInt();
  3139. return colspan > 1 && currentColIndex < col.toInt() && currentColIndex + colspan - 1 >= col.toInt();
  3140. });
  3141. Slick.definePseudo('colspan', function () {
  3142. var colspan = this.get("colspan").toInt() || 1;
  3143. return colspan > 1;
  3144. });
  3145. }
  3146. // 第三方扩展用的函数
  3147. o2.thirdparty = o2.thirdparty || {};
  3148. // 是否手机端
  3149. o2.thirdparty.isMobile = function(){
  3150. return /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i.test(navigator.userAgent.toLowerCase());
  3151. }
  3152. function alwaysFalse() {
  3153. return false;
  3154. }
  3155. if (o2.thirdparty.isMobile()) {
  3156. // 手机端钉钉
  3157. o2.thirdparty.isDingdingMobile = function() {
  3158. var isDingding = /dingtalk/i.test(navigator.userAgent.toLowerCase())
  3159. return isDingding && o2.thirdparty.isMobile();
  3160. }
  3161. //手机端企业微信
  3162. o2.thirdparty.isQywxMobile = function() {
  3163. var isComWx = /wxwork/i.test(navigator.userAgent); // 是否企业微信
  3164. return (isComWx && o2.thirdparty.isMobile());
  3165. }
  3166. //手机端微信
  3167. o2.thirdparty.isWeiXinMobile = function() {
  3168. var isWx = /micromessenger/i.test(navigator.userAgent); // 是否微信
  3169. return (isWx && o2.thirdparty.isMobile());
  3170. }
  3171. o2.thirdparty.isDingdingPC = alwaysFalse;
  3172. o2.thirdparty.isQywxPC = alwaysFalse;
  3173. o2.thirdparty.isWeiXinPC = alwaysFalse;
  3174. } else {
  3175. o2.thirdparty.isDingdingMobile = alwaysFalse;
  3176. o2.thirdparty.isQywxMobile = alwaysFalse;
  3177. o2.thirdparty.isWeiXinMobile = alwaysFalse;
  3178. // pc端钉钉
  3179. o2.thirdparty.isDingdingPC = function() {
  3180. var isDingding = /dingtalk/i.test(navigator.userAgent.toLowerCase())
  3181. return isDingding && !o2.thirdparty.isMobile();
  3182. }
  3183. //PC端企业微信
  3184. o2.thirdparty.isQywxPC = function() {
  3185. var isComWx = /wxwork/i.test(navigator.userAgent); // 是否企业微信
  3186. return (isComWx && !o2.thirdparty.isMobile());
  3187. }
  3188. //PC端微信
  3189. o2.thirdparty.isWeiXinPC = function() {
  3190. var isWx = /micromessenger/i.test(navigator.userAgent); // 是否微信
  3191. return (isWx && !o2.thirdparty.isMobile());
  3192. }
  3193. }
  3194. o2.common = o2.common || {};
  3195. o2.common.encodeHtml = function (str) {
  3196. str = str.toString();
  3197. str = str.replace(/\&/g, "&amp;");
  3198. str = str.replace(/>/g, "&gt;");
  3199. str = str.replace(/</g, "&lt;");
  3200. return str.replace(/\"/g, "&quot;");
  3201. };
  3202. o2.common.getResponseTextPost = function (path, body, contentType) {
  3203. var returnText = "";
  3204. var options = {
  3205. url: path,
  3206. async: false,
  3207. data: body,
  3208. method: "post",
  3209. onSuccess: function (esponseTree, responseElements, responseHTML, responseJavaScript) {
  3210. returnText = responseHTML;
  3211. }
  3212. };
  3213. var r = new Request.HTML(options);
  3214. r.send();
  3215. return returnText;
  3216. };
  3217. o2.common.getResponseText = function (path) {
  3218. var returnText = "";
  3219. var options = {
  3220. url: path,
  3221. async: false,
  3222. method: "get",
  3223. onSuccess: function (esponseTree, responseElements, responseHTML, responseJavaScript) {
  3224. returnText = responseHTML;
  3225. }
  3226. };
  3227. var r = new Request.HTML(options);
  3228. r.send();
  3229. return returnText;
  3230. };
  3231. o2.common.toDate = function (str) {
  3232. var tmpArr = str.split(" ");
  3233. if (!tmpArr[1]) tmpArr.push("0:0:0");
  3234. var dateArr = tmpArr[0].split("-");
  3235. var timeArr = tmpArr[1].split(":");
  3236. return new Date(dateArr[0], parseInt(dateArr[1]) - 1, dateArr[2], timeArr[0], timeArr[1], timeArr[2]);
  3237. };
  3238. o2.common.toDate = function (str) {
  3239. var tmpArr = str.split(" ");
  3240. if (!tmpArr[1]) tmpArr.push("0:0:0");
  3241. var dateArr = tmpArr[0].split("-");
  3242. var timeArr = tmpArr[1].split(":");
  3243. return new Date(dateArr[0], parseInt(dateArr[1]) - 1, dateArr[2], timeArr[0], timeArr[1], timeArr[2]);
  3244. };
  3245. o2.grayscale = function (src, width, height, callback) {
  3246. try {
  3247. var canvas = document.createElement('canvas');
  3248. var ctx = canvas.getContext('2d');
  3249. var imgObj = new Image();
  3250. imgObj.src = src;
  3251. canvas.width = width || imgObj.width;
  3252. canvas.height = height || imgObj.height;
  3253. ctx.drawImage(imgObj, 0, 0);
  3254. var imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height);
  3255. for (var y = 0; y < imgPixels.height; y++) {
  3256. for (var x = 0; x < imgPixels.width; x++) {
  3257. var i = (y * 4) * imgPixels.width + x * 4;
  3258. var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
  3259. imgPixels.data[i] = avg;
  3260. imgPixels.data[i + 1] = avg;
  3261. imgPixels.data[i + 2] = avg;
  3262. }
  3263. }
  3264. ctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
  3265. var src1 = canvas.toDataURL();
  3266. //var blob = canvas.toBlob();
  3267. canvas.destroy();
  3268. return {"status": "success", "src": src1};
  3269. } catch (e) {
  3270. return {"status": "error", "src": src}
  3271. }
  3272. };
  3273. o2.eventPosition = function (e) {
  3274. var x = 0;
  3275. var y = 0;
  3276. if (Browser.name == "firefox") {
  3277. x = parseFloat(e.event.clientX || e.event.x);
  3278. y = parseFloat(e.event.clientY || e.event.y);
  3279. } else {
  3280. x = parseFloat(e.event.x);
  3281. y = parseFloat(e.event.y);
  3282. }
  3283. return {"x": x, "y": y};
  3284. };
  3285. o2.dlgPosition = function (e, content, width, height) {
  3286. var size = content.getSize();
  3287. var x = 0;
  3288. var y = 0;
  3289. var fromx = 0;
  3290. var fromy = 0;
  3291. if (typeOf(e) == "element") {
  3292. var position = e.getPosition(content);
  3293. fromx = position.x;
  3294. fromy = position.y;
  3295. } else {
  3296. if (Browser.name == "firefox") {
  3297. fromx = parseFloat(e.clientX || e.x);
  3298. fromy = parseFloat(e.clientY || e.y);
  3299. } else {
  3300. fromx = parseFloat(e.x);
  3301. fromy = parseFloat(e.y);
  3302. }
  3303. if (e.target) {
  3304. var position = e.target.getPosition(content);
  3305. fromx = position.x;
  3306. fromy = position.y;
  3307. }
  3308. }
  3309. if (fromx + parseFloat(width) > size.x) {
  3310. //fromx = fromx + 20;
  3311. x = fromx - parseFloat(width);
  3312. }else{
  3313. fromx = x;
  3314. //if (x < 0) x = 20;
  3315. }
  3316. if (fromy + parseFloat(height) > size.y) {
  3317. y = fromy - parseFloat(height);
  3318. //y = y - 20;
  3319. }else{
  3320. y = fromy;
  3321. // if (y < 0) y = 0;
  3322. // y = y + 20;
  3323. }
  3324. return {
  3325. "x": x,
  3326. "y": y,
  3327. "fromx": fromx,
  3328. "fromy": fromy
  3329. }
  3330. };
  3331. if (window.Browser) {
  3332. if (Browser.name === "ie" && Browser.version < 9) {
  3333. Browser.ieuns = true;
  3334. } else if (Browser.name === "ie" && Browser.version < 10) {
  3335. Browser.iecomp = true;
  3336. }
  3337. if (Browser.iecomp) {
  3338. o2.load("ie_adapter", null, false);
  3339. o2.session.isDebugger = true;
  3340. }
  3341. o2.session.isMobile = (["mac", "win", "linux"].indexOf(Browser.Platform.name) === -1);
  3342. }
  3343. })();
  3344. o2.more = true;
  3345. //o2.addReady
  3346. (function () {
  3347. //dom ready
  3348. var _dom;
  3349. if (window.document) {
  3350. _dom = {
  3351. ready: false,
  3352. loaded: false,
  3353. checks: [],
  3354. shouldPoll: false,
  3355. timer: null,
  3356. testElement: document.createElement('div'),
  3357. readys: [],
  3358. domready: function () {
  3359. clearTimeout(_dom.timer);
  3360. if (_dom.ready) return;
  3361. _dom.loaded = _dom.ready = true;
  3362. o2.removeListener(document, 'DOMContentLoaded', _dom.checkReady);
  3363. o2.removeListener(document, 'readystatechange', _dom.check);
  3364. _dom.onReady();
  3365. },
  3366. check: function () {
  3367. for (var i = _dom.checks.length; i--;) if (_dom.checks[i]() && window.MooTools && o2.core && o2.more) {
  3368. _dom.domready();
  3369. return true;
  3370. }
  3371. return false;
  3372. },
  3373. poll: function () {
  3374. clearTimeout(_dom.timer);
  3375. if (!_dom.check()) _dom.timer = setTimeout(_dom.poll, 10);
  3376. },
  3377. /*<ltIE8>*/
  3378. // doScroll technique by Diego Perini http://javascript.nwbox.com/IEContentLoaded/
  3379. // testElement.doScroll() throws when the DOM is not ready, only in the top window
  3380. doScrollWorks: function () {
  3381. try {
  3382. _dom.testElement.doScroll();
  3383. return true;
  3384. } catch (e) {
  3385. }
  3386. return false;
  3387. },
  3388. /*</ltIE8>*/
  3389. onReady: function () {
  3390. for (var i = 0; i < _dom.readys.length; i++) {
  3391. this.readys[i].apply(window);
  3392. }
  3393. },
  3394. addReady: function (fn) {
  3395. if (_dom.loaded) {
  3396. if (fn) fn.apply(window);
  3397. } else {
  3398. if (fn) _dom.readys.push(fn);
  3399. }
  3400. return _dom;
  3401. },
  3402. checkReady: function () {
  3403. _dom.checks.push(function () {
  3404. return true
  3405. });
  3406. _dom.check();
  3407. }
  3408. };
  3409. o2.addListener(document, 'DOMContentLoaded', _dom.checkReady);
  3410. /*<ltIE8>*/
  3411. // If doScroll works already, it can't be used to determine domready
  3412. // e.g. in an iframe
  3413. if (_dom.testElement.doScroll && !_dom.doScrollWorks()) {
  3414. _dom.checks.push(_dom.doScrollWorks);
  3415. _dom.shouldPoll = true;
  3416. }
  3417. /*</ltIE8>*/
  3418. if (document.readyState) _dom.checks.push(function () {
  3419. var state = document.readyState;
  3420. return (state == 'loaded' || state == 'complete');
  3421. });
  3422. if ('onreadystatechange' in document) o2.addListener(document, 'readystatechange', _dom.check);
  3423. else _dom.shouldPoll = true;
  3424. if (_dom.shouldPoll) _dom.poll();
  3425. } else {
  3426. _dom = {
  3427. ready: false,
  3428. loaded: false,
  3429. checks: [],
  3430. shouldPoll: false,
  3431. timer: null,
  3432. readys: [],
  3433. domready: function () {
  3434. clearTimeout(_dom.timer);
  3435. if (_dom.ready) return;
  3436. _dom.loaded = _dom.ready = true;
  3437. _dom.onReady();
  3438. },
  3439. check: function () {
  3440. if (window.MooTools && o2.core && o2.more) {
  3441. _dom.domready();
  3442. return true;
  3443. }
  3444. return false;
  3445. },
  3446. onReady: function () {
  3447. for (var i = 0; i < _dom.readys.length; i++) {
  3448. this.readys[i].apply(window);
  3449. }
  3450. },
  3451. addReady: function (fn) {
  3452. if (_dom.loaded) {
  3453. if (fn) fn.apply(window);
  3454. } else {
  3455. if (fn) _dom.readys.push(fn);
  3456. }
  3457. return _dom;
  3458. },
  3459. checkReady: function () {
  3460. _dom.checks.push(function () {
  3461. return true
  3462. });
  3463. _dom.check();
  3464. }
  3465. };
  3466. }
  3467. var _loadO2 = function () {
  3468. (!o2.core) ? this.o2.load("o2.core", _dom.check) : _dom.check();
  3469. (!o2.more) ? this.o2.load("o2.more", _dom.check) : _dom.check();
  3470. };
  3471. if (!window.MooTools) {
  3472. this.o2.load("mootools", function () {
  3473. _loadO2();
  3474. _dom.check();
  3475. });
  3476. } else {
  3477. _loadO2();
  3478. }
  3479. this.o2.addReady = function (fn) {
  3480. _dom.addReady.call(_dom, fn);
  3481. };
  3482. })();
  3483. //compatible
  3484. COMMON = {
  3485. "DOM": {},
  3486. "setContentPath": function (path) {
  3487. COMMON.contentPath = path;
  3488. },
  3489. "JSON": o2.JSON,
  3490. "Browser": window.Browser,
  3491. "Class": o2.Class,
  3492. "XML": o2.xml,
  3493. "AjaxModule": {
  3494. "load": function (urls, callback, async, reload) {
  3495. o2.load(urls, callback, reload, document);
  3496. },
  3497. "loadDom": function (urls, callback, async, reload) {
  3498. o2.load(urls, callback, reload, document);
  3499. },
  3500. "loadCss": function (urls, callback, async, reload, sourceDoc) {
  3501. o2.loadCss(urls, document.body, callback, reload, sourceDoc);
  3502. }
  3503. },
  3504. "Request": Request,
  3505. "typeOf": o2.typeOf
  3506. };
  3507. if (COMMON.Browser) COMMON.Browser.Platform.isMobile = o2.session.isMobile;
  3508. COMMON.DOM.addReady = o2.addReady;
  3509. MWF = o2;
  3510. MWF.getJSON = o2.JSON.get;
  3511. MWF.getJSONP = o2.JSON.getJsonp;
  3512. MWF.defaultPath = o2.session.path;
  3513. }