summernote-wysiwyg.js 153 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284
  1. /**
  2. * Super simple wysiwyg editor on Bootstrap v0.5.3
  3. * http://hackerwins.github.io/summernote/
  4. *
  5. * summernote.js
  6. * Copyright 2013 Alan Hong. and outher contributors
  7. * summernote may be freely distributed under the MIT license./
  8. *
  9. * Date: 2014-07-27T05:15Z
  10. */
  11. (function (factory) {
  12. /* global define */
  13. if (typeof define === 'function' && define.amd) {
  14. // AMD. Register as an anonymous module.
  15. define(['jquery'], factory);
  16. } else {
  17. // Browser globals: jQuery
  18. factory(window.jQuery);
  19. }
  20. }(function ($) {
  21. if ('function' !== typeof Array.prototype.reduce) {
  22. /**
  23. * Array.prototype.reduce fallback
  24. *
  25. * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
  26. */
  27. Array.prototype.reduce = function (callback, optInitialValue) {
  28. var idx, value, length = this.length >>> 0, isValueSet = false;
  29. if (1 < arguments.length) {
  30. value = optInitialValue;
  31. isValueSet = true;
  32. }
  33. for (idx = 0; length > idx; ++idx) {
  34. if (this.hasOwnProperty(idx)) {
  35. if (isValueSet) {
  36. value = callback(value, this[idx], idx, this);
  37. } else {
  38. value = this[idx];
  39. isValueSet = true;
  40. }
  41. }
  42. }
  43. if (!isValueSet) {
  44. throw new TypeError('Reduce of empty array with no initial value');
  45. }
  46. return value;
  47. };
  48. }
  49. var isSupportAmd = typeof define === 'function' && define.amd;
  50. /**
  51. * returns whether font is installed or not.
  52. * @param {String} fontName
  53. * @return {Boolean}
  54. */
  55. var isFontInstalled = function (fontName) {
  56. var testFontName = fontName === 'Comic Sans MS' ? 'Courier New' : 'Comic Sans MS';
  57. var $tester = $('<div>').css({
  58. position: 'absolute',
  59. left: '-9999px',
  60. top: '-9999px',
  61. fontSize: '200px'
  62. }).text('mmmmmmmmmwwwwwww').appendTo(document.body);
  63. var originalWidth = $tester.css('fontFamily', testFontName).width();
  64. var width = $tester.css('fontFamily', fontName + ',' + testFontName).width();
  65. $tester.remove();
  66. return originalWidth !== width;
  67. };
  68. /**
  69. * Object which check platform and agent
  70. */
  71. var agent = {
  72. isMac: navigator.appVersion.indexOf('Mac') > -1,
  73. isMSIE: navigator.userAgent.indexOf('MSIE') > -1 || navigator.userAgent.indexOf('Trident') > -1,
  74. isFF: navigator.userAgent.indexOf('Firefox') > -1,
  75. jqueryVersion: parseFloat($.fn.jquery),
  76. isSupportAmd: isSupportAmd,
  77. hasCodeMirror: isSupportAmd ? require.specified('CodeMirror') : !!window.CodeMirror,
  78. isFontInstalled: isFontInstalled
  79. };
  80. /**
  81. * func utils (for high-order func's arg)
  82. */
  83. var func = (function () {
  84. var eq = function (elA) {
  85. return function (elB) {
  86. return elA === elB;
  87. };
  88. };
  89. var eq2 = function (elA, elB) {
  90. return elA === elB;
  91. };
  92. var ok = function () {
  93. return true;
  94. };
  95. var fail = function () {
  96. return false;
  97. };
  98. var not = function (f) {
  99. return function () {
  100. return !f.apply(f, arguments);
  101. };
  102. };
  103. var self = function (a) {
  104. return a;
  105. };
  106. var idCounter = 0;
  107. /**
  108. * generate a globally-unique id
  109. *
  110. * @param {String} [prefix]
  111. */
  112. var uniqueId = function (prefix) {
  113. var id = ++idCounter + '';
  114. return prefix ? prefix + id : id;
  115. };
  116. /**
  117. * returns bnd (bounds) from rect
  118. *
  119. * - IE Compatability Issue: http://goo.gl/sRLOAo
  120. * - Scroll Issue: http://goo.gl/sNjUc
  121. *
  122. * @param {Rect} rect
  123. * @return {Object} bounds
  124. * @return {Number} bounds.top
  125. * @return {Number} bounds.left
  126. * @return {Number} bounds.width
  127. * @return {Number} bounds.height
  128. */
  129. var rect2bnd = function (rect) {
  130. var $document = $(document);
  131. return {
  132. top: rect.top + $document.scrollTop(),
  133. left: rect.left + $document.scrollLeft(),
  134. width: rect.right - rect.left,
  135. height: rect.bottom - rect.top
  136. };
  137. };
  138. /**
  139. * returns a copy of the object where the keys have become the values and the values the keys.
  140. * @param {Object} obj
  141. * @return {Object}
  142. */
  143. var invertObject = function (obj) {
  144. var inverted = {};
  145. for (var key in obj) {
  146. if (obj.hasOwnProperty(key)) {
  147. inverted[obj[key]] = key;
  148. }
  149. }
  150. return inverted;
  151. };
  152. return {
  153. eq: eq,
  154. eq2: eq2,
  155. ok: ok,
  156. fail: fail,
  157. not: not,
  158. self: self,
  159. uniqueId: uniqueId,
  160. rect2bnd: rect2bnd,
  161. invertObject: invertObject
  162. };
  163. })();
  164. /**
  165. * list utils
  166. */
  167. var list = (function () {
  168. /**
  169. * returns the first element of an array.
  170. * @param {Array} array
  171. */
  172. var head = function (array) {
  173. return array[0];
  174. };
  175. /**
  176. * returns the last element of an array.
  177. * @param {Array} array
  178. */
  179. var last = function (array) {
  180. return array[array.length - 1];
  181. };
  182. /**
  183. * returns everything but the last entry of the array.
  184. * @param {Array} array
  185. */
  186. var initial = function (array) {
  187. return array.slice(0, array.length - 1);
  188. };
  189. /**
  190. * returns the rest of the elements in an array.
  191. * @param {Array} array
  192. */
  193. var tail = function (array) {
  194. return array.slice(1);
  195. };
  196. /**
  197. * returns next item.
  198. * @param {Array} array
  199. */
  200. var next = function (array, item) {
  201. var idx = array.indexOf(item);
  202. if (idx === -1) { return null; }
  203. return array[idx + 1];
  204. };
  205. /**
  206. * returns prev item.
  207. * @param {Array} array
  208. */
  209. var prev = function (array, item) {
  210. var idx = array.indexOf(item);
  211. if (idx === -1) { return null; }
  212. return array[idx - 1];
  213. };
  214. /**
  215. * get sum from a list
  216. * @param {Array} array - array
  217. * @param {Function} fn - iterator
  218. */
  219. var sum = function (array, fn) {
  220. fn = fn || func.self;
  221. return array.reduce(function (memo, v) {
  222. return memo + fn(v);
  223. }, 0);
  224. };
  225. /**
  226. * returns a copy of the collection with array type.
  227. * @param {Collection} collection - collection eg) node.childNodes, ...
  228. */
  229. var from = function (collection) {
  230. var result = [], idx = -1, length = collection.length;
  231. while (++idx < length) {
  232. result[idx] = collection[idx];
  233. }
  234. return result;
  235. };
  236. /**
  237. * cluster elements by predicate function.
  238. * @param {Array} array - array
  239. * @param {Function} fn - predicate function for cluster rule
  240. * @param {Array[]}
  241. */
  242. var clusterBy = function (array, fn) {
  243. if (!array.length) { return []; }
  244. var aTail = tail(array);
  245. return aTail.reduce(function (memo, v) {
  246. var aLast = last(memo);
  247. if (fn(last(aLast), v)) {
  248. aLast[aLast.length] = v;
  249. } else {
  250. memo[memo.length] = [v];
  251. }
  252. return memo;
  253. }, [[head(array)]]);
  254. };
  255. /**
  256. * returns a copy of the array with all falsy values removed
  257. * @param {Array} array - array
  258. * @param {Function} fn - predicate function for cluster rule
  259. */
  260. var compact = function (array) {
  261. var aResult = [];
  262. for (var idx = 0, sz = array.length; idx < sz; idx ++) {
  263. if (array[idx]) { aResult.push(array[idx]); }
  264. }
  265. return aResult;
  266. };
  267. return { head: head, last: last, initial: initial, tail: tail,
  268. prev: prev, next: next, sum: sum, from: from,
  269. compact: compact, clusterBy: clusterBy };
  270. })();
  271. /**
  272. * Dom functions
  273. */
  274. var dom = (function () {
  275. /**
  276. * returns whether node is `note-editable` or not.
  277. *
  278. * @param {Element} node
  279. * @return {Boolean}
  280. */
  281. var isEditable = function (node) {
  282. return node && $(node).hasClass('note-editable');
  283. };
  284. var isControlSizing = function (node) {
  285. return node && $(node).hasClass('note-control-sizing');
  286. };
  287. /**
  288. * build layoutInfo from $editor(.note-editor)
  289. *
  290. * @param {jQuery} $editor
  291. * @return {Object}
  292. */
  293. var buildLayoutInfo = function ($editor) {
  294. var makeFinder;
  295. // air mode
  296. if ($editor.hasClass('note-air-editor')) {
  297. var id = list.last($editor.attr('id').split('-'));
  298. makeFinder = function (sIdPrefix) {
  299. return function () { return $(sIdPrefix + id); };
  300. };
  301. return {
  302. editor: function () { return $editor; },
  303. editable: function () { return $editor; },
  304. popover: makeFinder('#note-popover-'),
  305. handle: makeFinder('#note-handle-'),
  306. dialog: makeFinder('#note-dialog-')
  307. };
  308. // frame mode
  309. } else {
  310. makeFinder = function (sClassName) {
  311. return function () { return $editor.find(sClassName); };
  312. };
  313. return {
  314. editor: function () { return $editor; },
  315. dropzone: makeFinder('.note-dropzone'),
  316. toolbar: makeFinder('.note-toolbar'),
  317. editable: makeFinder('.note-editable'),
  318. codable: makeFinder('.note-codable'),
  319. statusbar: makeFinder('.note-statusbar'),
  320. popover: makeFinder('.note-popover'),
  321. handle: makeFinder('.note-handle'),
  322. dialog: makeFinder('.note-dialog')
  323. };
  324. }
  325. };
  326. /**
  327. * returns predicate which judge whether nodeName is same
  328. * @param {String} sNodeName
  329. */
  330. var makePredByNodeName = function (sNodeName) {
  331. // nodeName is always uppercase.
  332. return function (node) {
  333. return node && node.nodeName === sNodeName;
  334. };
  335. };
  336. var isPara = function (node) {
  337. // Chrome(v31.0), FF(v25.0.1) use DIV for paragraph
  338. return node && /^DIV|^P|^LI|^H[1-7]/.test(node.nodeName);
  339. };
  340. var isList = function (node) {
  341. return node && /^UL|^OL/.test(node.nodeName);
  342. };
  343. var isCell = function (node) {
  344. return node && /^TD|^TH/.test(node.nodeName);
  345. };
  346. /**
  347. * find nearest ancestor predicate hit
  348. *
  349. * @param {Element} node
  350. * @param {Function} pred - predicate function
  351. */
  352. var ancestor = function (node, pred) {
  353. while (node) {
  354. if (pred(node)) { return node; }
  355. if (isEditable(node)) { break; }
  356. node = node.parentNode;
  357. }
  358. return null;
  359. };
  360. /**
  361. * returns new array of ancestor nodes (until predicate hit).
  362. *
  363. * @param {Element} node
  364. * @param {Function} [optional] pred - predicate function
  365. */
  366. var listAncestor = function (node, pred) {
  367. pred = pred || func.fail;
  368. var aAncestor = [];
  369. ancestor(node, function (el) {
  370. aAncestor.push(el);
  371. return pred(el);
  372. });
  373. return aAncestor;
  374. };
  375. /**
  376. * returns common ancestor node between two nodes.
  377. *
  378. * @param {Element} nodeA
  379. * @param {Element} nodeB
  380. */
  381. var commonAncestor = function (nodeA, nodeB) {
  382. var aAncestor = listAncestor(nodeA);
  383. for (var n = nodeB; n; n = n.parentNode) {
  384. if ($.inArray(n, aAncestor) > -1) { return n; }
  385. }
  386. return null; // difference document area
  387. };
  388. /**
  389. * listing all Nodes between two nodes.
  390. * FIXME: nodeA and nodeB must be sorted, use comparePoints later.
  391. *
  392. * @param {Element} nodeA
  393. * @param {Element} nodeB
  394. */
  395. var listBetween = function (nodeA, nodeB) {
  396. var aNode = [];
  397. var isStart = false, isEnd = false;
  398. // DFS(depth first search) with commonAcestor.
  399. (function fnWalk(node) {
  400. if (!node) { return; } // traverse fisnish
  401. if (node === nodeA) { isStart = true; } // start point
  402. if (isStart && !isEnd) { aNode.push(node); } // between
  403. if (node === nodeB) { isEnd = true; return; } // end point
  404. for (var idx = 0, sz = node.childNodes.length; idx < sz; idx++) {
  405. fnWalk(node.childNodes[idx]);
  406. }
  407. })(commonAncestor(nodeA, nodeB));
  408. return aNode;
  409. };
  410. /**
  411. * listing all previous siblings (until predicate hit).
  412. * @param {Element} node
  413. * @param {Function} [optional] pred - predicate function
  414. */
  415. var listPrev = function (node, pred) {
  416. pred = pred || func.fail;
  417. var aNext = [];
  418. while (node) {
  419. aNext.push(node);
  420. if (pred(node)) { break; }
  421. node = node.previousSibling;
  422. }
  423. return aNext;
  424. };
  425. /**
  426. * listing next siblings (until predicate hit).
  427. *
  428. * @param {Element} node
  429. * @param {Function} [pred] - predicate function
  430. */
  431. var listNext = function (node, pred) {
  432. pred = pred || func.fail;
  433. var aNext = [];
  434. while (node) {
  435. aNext.push(node);
  436. if (pred(node)) { break; }
  437. node = node.nextSibling;
  438. }
  439. return aNext;
  440. };
  441. /**
  442. * listing descendant nodes
  443. *
  444. * @param {Element} node
  445. * @param {Function} [pred] - predicate function
  446. */
  447. var listDescendant = function (node, pred) {
  448. var aDescendant = [];
  449. pred = pred || func.ok;
  450. // start DFS(depth first search) with node
  451. (function fnWalk(current) {
  452. if (node !== current && pred(current)) {
  453. aDescendant.push(current);
  454. }
  455. for (var idx = 0, sz = current.childNodes.length; idx < sz; idx++) {
  456. fnWalk(current.childNodes[idx]);
  457. }
  458. })(node);
  459. return aDescendant;
  460. };
  461. /**
  462. * insert node after preceding
  463. *
  464. * @param {Element} node
  465. * @param {Element} preceding - predicate function
  466. */
  467. var insertAfter = function (node, preceding) {
  468. var next = preceding.nextSibling, parent = preceding.parentNode;
  469. if (next) {
  470. parent.insertBefore(node, next);
  471. } else {
  472. parent.appendChild(node);
  473. }
  474. return node;
  475. };
  476. /**
  477. * append elements.
  478. *
  479. * @param {Element} node
  480. * @param {Collection} aChild
  481. */
  482. var appends = function (node, aChild) {
  483. $.each(aChild, function (idx, child) {
  484. node.appendChild(child);
  485. });
  486. return node;
  487. };
  488. var isText = makePredByNodeName('#text');
  489. /**
  490. * returns #text's text size or element's childNodes size
  491. *
  492. * @param {Element} node
  493. */
  494. var length = function (node) {
  495. if (isText(node)) { return node.nodeValue.length; }
  496. return node.childNodes.length;
  497. };
  498. /**
  499. * returns whether boundaryPoint is edge or not.
  500. *
  501. * @param {BoundaryPoint} boundaryPoitn
  502. * @return {Boolean}
  503. */
  504. var isEdgeBP = function (boundaryPoint) {
  505. return boundaryPoint.offset === 0 ||
  506. boundaryPoint.offset === length(boundaryPoint.node);
  507. };
  508. /**
  509. * returns offset from parent.
  510. *
  511. * @param {Element} node
  512. */
  513. var position = function (node) {
  514. var offset = 0;
  515. while ((node = node.previousSibling)) { offset += 1; }
  516. return offset;
  517. };
  518. var hasChildren = function (node) {
  519. return node && node.childNodes && node.childNodes.length;
  520. };
  521. /**
  522. * returns previous boundaryPoint
  523. *
  524. * @param {BoundaryPoint} boundaryPoitn
  525. * @return {BoundaryPoint}
  526. */
  527. var prevBP = function (boundaryPoint) {
  528. var node = boundaryPoint.node,
  529. offset = boundaryPoint.offset;
  530. if (offset === 0) {
  531. if (isEditable(node)) { return null; }
  532. return {node: node.parentNode, offset: position(node)};
  533. } else {
  534. if (hasChildren(node)) {
  535. var child = node.childNodes[offset - 1];
  536. return {node: child, offset: length(child)};
  537. } else {
  538. return {node: node, offset: offset - 1};
  539. }
  540. }
  541. };
  542. /**
  543. * return offsetPath(array of offset) from ancestor
  544. *
  545. * @param {Element} ancestor - ancestor node
  546. * @param {Element} node
  547. */
  548. var makeOffsetPath = function (ancestor, node) {
  549. var aAncestor = list.initial(listAncestor(node, func.eq(ancestor)));
  550. return $.map(aAncestor, position).reverse();
  551. };
  552. /**
  553. * return element from offsetPath(array of offset)
  554. *
  555. * @param {Element} ancestor - ancestor node
  556. * @param {array} aOffset - offsetPath
  557. */
  558. var fromOffsetPath = function (ancestor, aOffset) {
  559. var current = ancestor;
  560. for (var i = 0, sz = aOffset.length; i < sz; i++) {
  561. current = current.childNodes[aOffset[i]];
  562. }
  563. return current;
  564. };
  565. /**
  566. * split element or #text
  567. *
  568. * @param {Element} node
  569. * @param {Number} offset
  570. */
  571. var split = function (node, offset) {
  572. if (offset === 0) { return node; }
  573. if (offset >= length(node)) { return node.nextSibling; }
  574. // splitText
  575. if (isText(node)) { return node.splitText(offset); }
  576. // splitElement
  577. var child = node.childNodes[offset];
  578. node = insertAfter(node.cloneNode(false), node);
  579. return appends(node, listNext(child));
  580. };
  581. /**
  582. * split dom tree by boundaryPoint(pivot and offset)
  583. *
  584. * @param {Element} root
  585. * @param {Element} pivot - this will be boundaryPoint's node
  586. * @param {Number} offset - this will be boundaryPoint's offset
  587. */
  588. var splitTree = function (root, pivot, offset) {
  589. var aAncestor = listAncestor(pivot, func.eq(root));
  590. if (aAncestor.length === 1) { return split(pivot, offset); }
  591. return aAncestor.reduce(function (node, parent) {
  592. var clone = parent.cloneNode(false);
  593. insertAfter(clone, parent);
  594. if (node === pivot) {
  595. node = split(node, offset);
  596. }
  597. appends(clone, listNext(node));
  598. return clone;
  599. });
  600. };
  601. /**
  602. * remove node, (bRemoveChild: remove child or not)
  603. * @param {Element} node
  604. * @param {Boolean} bRemoveChild
  605. */
  606. var remove = function (node, bRemoveChild) {
  607. if (!node || !node.parentNode) { return; }
  608. if (node.removeNode) { return node.removeNode(bRemoveChild); }
  609. var elParent = node.parentNode;
  610. if (!bRemoveChild) {
  611. var aNode = [];
  612. var i, sz;
  613. for (i = 0, sz = node.childNodes.length; i < sz; i++) {
  614. aNode.push(node.childNodes[i]);
  615. }
  616. for (i = 0, sz = aNode.length; i < sz; i++) {
  617. elParent.insertBefore(aNode[i], node);
  618. }
  619. }
  620. elParent.removeChild(node);
  621. };
  622. var html = function ($node) {
  623. return dom.isTextarea($node[0]) ? $node.val() : $node.html();
  624. };
  625. return {
  626. blank: agent.isMSIE ? '&nbsp;' : '<br/>',
  627. emptyPara: '<p><br/></p>',
  628. isEditable: isEditable,
  629. isControlSizing: isControlSizing,
  630. buildLayoutInfo: buildLayoutInfo,
  631. isText: isText,
  632. isPara: isPara,
  633. isList: isList,
  634. isTable: makePredByNodeName('TABLE'),
  635. isCell: isCell,
  636. isAnchor: makePredByNodeName('A'),
  637. isDiv: makePredByNodeName('DIV'),
  638. isLi: makePredByNodeName('LI'),
  639. isSpan: makePredByNodeName('SPAN'),
  640. isB: makePredByNodeName('B'),
  641. isU: makePredByNodeName('U'),
  642. isS: makePredByNodeName('S'),
  643. isI: makePredByNodeName('I'),
  644. isImg: makePredByNodeName('IMG'),
  645. isTextarea: makePredByNodeName('TEXTAREA'),
  646. length: length,
  647. isEdgeBP: isEdgeBP,
  648. prevBP: prevBP,
  649. ancestor: ancestor,
  650. listAncestor: listAncestor,
  651. listNext: listNext,
  652. listPrev: listPrev,
  653. listDescendant: listDescendant,
  654. commonAncestor: commonAncestor,
  655. listBetween: listBetween,
  656. insertAfter: insertAfter,
  657. position: position,
  658. makeOffsetPath: makeOffsetPath,
  659. fromOffsetPath: fromOffsetPath,
  660. splitTree: splitTree,
  661. remove: remove,
  662. html: html
  663. };
  664. })();
  665. var settings = {
  666. // version
  667. version: '0.5.3',
  668. /**
  669. * options
  670. */
  671. options: {
  672. width: null, // set editor width
  673. height: null, // set editor height, ex) 300
  674. minHeight: null, // set minimum height of editor
  675. maxHeight: null, // set maximum height of editor
  676. focus: false, // set focus to editable area after initializing summernote
  677. tabsize: 4, // size of tab ex) 2 or 4
  678. styleWithSpan: true, // style with span (Chrome and FF only)
  679. disableLinkTarget: false, // hide link Target Checkbox
  680. disableDragAndDrop: false, // disable drag and drop event
  681. disableResizeEditor: false, // disable resizing editor
  682. codemirror: { // codemirror options
  683. mode: 'text/html',
  684. htmlMode: true,
  685. lineNumbers: true,
  686. autoFormatOnStart: false
  687. },
  688. // language
  689. lang: 'en-US', // language 'en-US', 'ko-KR', ...
  690. direction: null, // text direction, ex) 'rtl'
  691. // toolbar
  692. toolbar: [
  693. ['style', ['style']],
  694. ['font', ['bold', 'italic', 'underline', 'superscript', 'subscript', 'strikethrough', 'clear']],
  695. ['fontname', ['fontname']],
  696. // ['fontsize', ['fontsize']], // Still buggy
  697. ['color', ['color']],
  698. ['para', ['ul', 'ol', 'paragraph']],
  699. ['height', ['height']],
  700. ['table', ['table']],
  701. ['insert', ['link', 'picture', 'video', 'hr']],
  702. ['view', ['fullscreen', 'codeview']],
  703. ['help', ['help']]
  704. ],
  705. // air mode: inline editor
  706. airMode: false,
  707. // airPopover: [
  708. // ['style', ['style']],
  709. // ['font', ['bold', 'italic', 'underline', 'clear']],
  710. // ['fontname', ['fontname']],
  711. // ['fontsize', ['fontsize']], // Still buggy
  712. // ['color', ['color']],
  713. // ['para', ['ul', 'ol', 'paragraph']],
  714. // ['height', ['height']],
  715. // ['table', ['table']],
  716. // ['insert', ['link', 'picture', 'video']],
  717. // ['help', ['help']]
  718. // ],
  719. airPopover: [
  720. ['color', ['color']],
  721. ['font', ['bold', 'underline', 'clear']],
  722. ['para', ['ul', 'paragraph']],
  723. ['table', ['table']],
  724. ['insert', ['link', 'picture']]
  725. ],
  726. // style tag
  727. styleTags: ['p', 'blockquote', 'pre', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'],
  728. // default fontName
  729. defaultFontName: 'Helvetica Neue',
  730. // fontName
  731. fontNames: [
  732. 'Arial', 'Arial Black', 'Comic Sans MS', 'Courier New',
  733. 'Helvetica Neue', 'Impact', 'Lucida Grande',
  734. 'Tahoma', 'Times New Roman', 'Verdana'
  735. ],
  736. // pallete colors(n x n)
  737. colors: [
  738. ['#000000', '#424242', '#636363', '#9C9C94', '#CEC6CE', '#EFEFEF', '#F7F7F7', '#FFFFFF'],
  739. ['#FF0000', '#FF9C00', '#FFFF00', '#00FF00', '#00FFFF', '#0000FF', '#9C00FF', '#FF00FF'],
  740. ['#F7C6CE', '#FFE7CE', '#FFEFC6', '#D6EFD6', '#CEDEE7', '#CEE7F7', '#D6D6E7', '#E7D6DE'],
  741. ['#E79C9C', '#FFC69C', '#FFE79C', '#B5D6A5', '#A5C6CE', '#9CC6EF', '#B5A5D6', '#D6A5BD'],
  742. ['#E76363', '#F7AD6B', '#FFD663', '#94BD7B', '#73A5AD', '#6BADDE', '#8C7BC6', '#C67BA5'],
  743. ['#CE0000', '#E79439', '#EFC631', '#6BA54A', '#4A7B8C', '#3984C6', '#634AA5', '#A54A7B'],
  744. ['#9C0000', '#B56308', '#BD9400', '#397B21', '#104A5A', '#085294', '#311873', '#731842'],
  745. ['#630000', '#7B3900', '#846300', '#295218', '#083139', '#003163', '#21104A', '#4A1031']
  746. ],
  747. // fontSize
  748. fontSizes: ['8', '9', '10', '11', '12', '14', '18', '24', '36'],
  749. // lineHeight
  750. lineHeights: ['1.0', '1.2', '1.4', '1.5', '1.6', '1.8', '2.0', '3.0'],
  751. // insertTable max size
  752. insertTableMaxSize: {
  753. col: 10,
  754. row: 10
  755. },
  756. // callbacks
  757. oninit: null, // initialize
  758. onfocus: null, // editable has focus
  759. onblur: null, // editable out of focus
  760. onenter: null, // enter key pressed
  761. onkeyup: null, // keyup
  762. onkeydown: null, // keydown
  763. onImageUpload: null, // imageUpload
  764. onImageUploadError: null, // imageUploadError
  765. onToolbarClick: null,
  766. /**
  767. * manipulate link address when user create link
  768. * @param {String} sLinkUrl
  769. * @return {String}
  770. */
  771. onCreateLink: function (sLinkUrl) {
  772. if (sLinkUrl.indexOf('@') !== -1 && sLinkUrl.indexOf(':') === -1) {
  773. sLinkUrl = 'mailto:' + sLinkUrl;
  774. } else if (sLinkUrl.indexOf('://') === -1) {
  775. sLinkUrl = 'http://' + sLinkUrl;
  776. }
  777. return sLinkUrl;
  778. },
  779. keyMap: {
  780. pc: {
  781. 'CTRL+Z': 'undo',
  782. 'CTRL+Y': 'redo',
  783. 'TAB': 'tab',
  784. 'SHIFT+TAB': 'untab',
  785. 'CTRL+B': 'bold',
  786. 'CTRL+I': 'italic',
  787. 'CTRL+U': 'underline',
  788. 'CTRL+SHIFT+S': 'strikethrough',
  789. 'CTRL+BACKSLASH': 'removeFormat',
  790. 'CTRL+SHIFT+L': 'justifyLeft',
  791. 'CTRL+SHIFT+E': 'justifyCenter',
  792. 'CTRL+SHIFT+R': 'justifyRight',
  793. 'CTRL+SHIFT+J': 'justifyFull',
  794. 'CTRL+SHIFT+NUM7': 'insertUnorderedList',
  795. 'CTRL+SHIFT+NUM8': 'insertOrderedList',
  796. 'CTRL+LEFTBRACKET': 'outdent',
  797. 'CTRL+RIGHTBRACKET': 'indent',
  798. 'CTRL+NUM0': 'formatPara',
  799. 'CTRL+NUM1': 'formatH1',
  800. 'CTRL+NUM2': 'formatH2',
  801. 'CTRL+NUM3': 'formatH3',
  802. 'CTRL+NUM4': 'formatH4',
  803. 'CTRL+NUM5': 'formatH5',
  804. 'CTRL+NUM6': 'formatH6',
  805. 'CTRL+ENTER': 'insertHorizontalRule',
  806. 'CTRL+K': 'showLinkDialog'
  807. },
  808. mac: {
  809. 'CMD+Z': 'undo',
  810. 'CMD+SHIFT+Z': 'redo',
  811. 'TAB': 'tab',
  812. 'SHIFT+TAB': 'untab',
  813. 'CMD+B': 'bold',
  814. 'CMD+I': 'italic',
  815. 'CMD+U': 'underline',
  816. 'CMD+SHIFT+S': 'strikethrough',
  817. 'CMD+BACKSLASH': 'removeFormat',
  818. 'CMD+SHIFT+L': 'justifyLeft',
  819. 'CMD+SHIFT+E': 'justifyCenter',
  820. 'CMD+SHIFT+R': 'justifyRight',
  821. 'CMD+SHIFT+J': 'justifyFull',
  822. 'CMD+SHIFT+NUM7': 'insertUnorderedList',
  823. 'CMD+SHIFT+NUM8': 'insertOrderedList',
  824. 'CMD+LEFTBRACKET': 'outdent',
  825. 'CMD+RIGHTBRACKET': 'indent',
  826. 'CMD+NUM0': 'formatPara',
  827. 'CMD+NUM1': 'formatH1',
  828. 'CMD+NUM2': 'formatH2',
  829. 'CMD+NUM3': 'formatH3',
  830. 'CMD+NUM4': 'formatH4',
  831. 'CMD+NUM5': 'formatH5',
  832. 'CMD+NUM6': 'formatH6',
  833. 'CMD+ENTER': 'insertHorizontalRule',
  834. 'CMD+K': 'showLinkDialog'
  835. }
  836. }
  837. },
  838. // default language: en-US
  839. lang: {
  840. 'en-US': {
  841. font: {
  842. bold: 'Bold',
  843. italic: 'Italic',
  844. underline: 'Underline',
  845. strikethrough: 'Strikethrough',
  846. subscript: 'Subscript',
  847. superscript: 'Superscript',
  848. clear: 'Remove Font Style',
  849. height: 'Line Height',
  850. name: 'Font Family',
  851. size: 'Font Size'
  852. },
  853. image: {
  854. image: 'Picture',
  855. insert: 'Insert Image',
  856. resizeFull: 'Resize Full',
  857. resizeHalf: 'Resize Half',
  858. resizeQuarter: 'Resize Quarter',
  859. floatLeft: 'Float Left',
  860. floatRight: 'Float Right',
  861. floatNone: 'Float None',
  862. dragImageHere: 'Drag an image here',
  863. selectFromFiles: 'Select from files',
  864. url: 'Image URL',
  865. remove: 'Remove Image'
  866. },
  867. link: {
  868. link: 'Link',
  869. insert: 'Insert Link',
  870. unlink: 'Unlink',
  871. edit: 'Edit',
  872. textToDisplay: 'Text to display',
  873. url: 'To what URL should this link go?',
  874. openInNewWindow: 'Open in new window'
  875. },
  876. video: {
  877. video: 'Video',
  878. videoLink: 'Video Link',
  879. insert: 'Insert Video',
  880. url: 'Video URL?',
  881. providers: '(YouTube, Vimeo, Vine, Instagram, DailyMotion or Youku)'
  882. },
  883. table: {
  884. table: 'Table'
  885. },
  886. hr: {
  887. insert: 'Insert Horizontal Rule'
  888. },
  889. style: {
  890. style: 'Style',
  891. normal: 'Normal',
  892. blockquote: 'Quote',
  893. pre: 'Code',
  894. h1: 'Header 1',
  895. h2: 'Header 2',
  896. h3: 'Header 3',
  897. h4: 'Header 4',
  898. h5: 'Header 5',
  899. h6: 'Header 6'
  900. },
  901. lists: {
  902. unordered: 'Unordered list',
  903. ordered: 'Ordered list'
  904. },
  905. options: {
  906. help: 'Help',
  907. fullscreen: 'Full Screen',
  908. codeview: 'Code View'
  909. },
  910. paragraph: {
  911. paragraph: 'Paragraph',
  912. outdent: 'Outdent',
  913. indent: 'Indent',
  914. left: 'Align left',
  915. center: 'Align center',
  916. right: 'Align right',
  917. justify: 'Justify full'
  918. },
  919. color: {
  920. recent: 'Recent Color',
  921. more: 'More Color',
  922. background: 'Background Color',
  923. foreground: 'Foreground Color',
  924. transparent: 'Transparent',
  925. setTransparent: 'Set transparent',
  926. reset: 'Reset',
  927. resetToDefault: 'Reset to default'
  928. },
  929. shortcut: {
  930. shortcuts: 'Keyboard shortcuts',
  931. close: 'Close',
  932. textFormatting: 'Text formatting',
  933. action: 'Action',
  934. paragraphFormatting: 'Paragraph formatting',
  935. documentStyle: 'Document Style'
  936. },
  937. history: {
  938. undo: 'Undo',
  939. redo: 'Redo'
  940. }
  941. }
  942. }
  943. };
  944. /**
  945. * Async functions which returns `Promise`
  946. */
  947. var async = (function () {
  948. /**
  949. * read contents of file as representing URL
  950. *
  951. * @param {File} file
  952. * @return {Promise} - then: sDataUrl
  953. */
  954. var readFileAsDataURL = function (file) {
  955. return $.Deferred(function (deferred) {
  956. $.extend(new FileReader(), {
  957. onload: function (e) {
  958. var sDataURL = e.target.result;
  959. deferred.resolve(sDataURL);
  960. },
  961. onerror: function () {
  962. deferred.reject(this);
  963. }
  964. }).readAsDataURL(file);
  965. }).promise();
  966. };
  967. /**
  968. * create `<image>` from url string
  969. *
  970. * @param {String} sUrl
  971. * @return {Promise} - then: $image
  972. */
  973. var createImage = function (sUrl) {
  974. return $.Deferred(function (deferred) {
  975. $('<img>').one('load', function () {
  976. deferred.resolve($(this));
  977. }).one('error abort', function () {
  978. deferred.reject($(this));
  979. }).css({
  980. display: 'none'
  981. }).appendTo(document.body).attr('src', sUrl);
  982. }).promise();
  983. };
  984. return {
  985. readFileAsDataURL: readFileAsDataURL,
  986. createImage: createImage
  987. };
  988. })();
  989. /**
  990. * Object for keycodes.
  991. */
  992. var key = {
  993. isEdit: function (keyCode) {
  994. return [8, 9, 13, 32].indexOf(keyCode) !== -1;
  995. },
  996. nameFromCode: {
  997. '8': 'BACKSPACE',
  998. '9': 'TAB',
  999. '13': 'ENTER',
  1000. '32': 'SPACE',
  1001. // Number: 0-9
  1002. '48': 'NUM0',
  1003. '49': 'NUM1',
  1004. '50': 'NUM2',
  1005. '51': 'NUM3',
  1006. '52': 'NUM4',
  1007. '53': 'NUM5',
  1008. '54': 'NUM6',
  1009. '55': 'NUM7',
  1010. '56': 'NUM8',
  1011. // Alphabet: a-z
  1012. '66': 'B',
  1013. '69': 'E',
  1014. '73': 'I',
  1015. '74': 'J',
  1016. '75': 'K',
  1017. '76': 'L',
  1018. '82': 'R',
  1019. '83': 'S',
  1020. '85': 'U',
  1021. '89': 'Y',
  1022. '90': 'Z',
  1023. '191': 'SLASH',
  1024. '219': 'LEFTBRACKET',
  1025. '220': 'BACKSLASH',
  1026. '221': 'RIGHTBRACKET'
  1027. }
  1028. };
  1029. /**
  1030. * Style
  1031. * @class
  1032. */
  1033. var Style = function () {
  1034. /**
  1035. * passing an array of style properties to .css()
  1036. * will result in an object of property-value pairs.
  1037. * (compability with version < 1.9)
  1038. *
  1039. * @param {jQuery} $obj
  1040. * @param {Array} propertyNames - An array of one or more CSS properties.
  1041. * @returns {Object}
  1042. */
  1043. var jQueryCSS = function ($obj, propertyNames) {
  1044. if (agent.jqueryVersion < 1.9) {
  1045. var result = {};
  1046. $.each(propertyNames, function (idx, propertyName) {
  1047. result[propertyName] = $obj.css(propertyName);
  1048. });
  1049. return result;
  1050. }
  1051. return $obj.css.call($obj, propertyNames);
  1052. };
  1053. /**
  1054. * paragraph level style
  1055. *
  1056. * @param {WrappedRange} rng
  1057. * @param {Object} oStyle
  1058. */
  1059. this.stylePara = function (rng, oStyle) {
  1060. $.each(rng.nodes(dom.isPara), function (idx, elPara) {
  1061. $(elPara).css(oStyle);
  1062. });
  1063. };
  1064. /**
  1065. * get current style on cursor
  1066. *
  1067. * @param {WrappedRange} rng
  1068. * @param {Element} elTarget - target element on event
  1069. * @return {Object} - object contains style properties.
  1070. */
  1071. this.current = function (rng, elTarget) {
  1072. var $cont = $(dom.isText(rng.sc) ? rng.sc.parentNode : rng.sc);
  1073. var properties = ['font-family', 'font-size', 'text-align', 'list-style-type', 'line-height'];
  1074. var oStyle = jQueryCSS($cont, properties) || {};
  1075. oStyle['font-size'] = parseInt(oStyle['font-size'], 10);
  1076. // document.queryCommandState for toggle state
  1077. oStyle['font-bold'] = document.queryCommandState('bold') ? 'bold' : 'normal';
  1078. oStyle['font-italic'] = document.queryCommandState('italic') ? 'italic' : 'normal';
  1079. oStyle['font-underline'] = document.queryCommandState('underline') ? 'underline' : 'normal';
  1080. oStyle['font-strikethrough'] = document.queryCommandState('strikeThrough') ? 'strikethrough' : 'normal';
  1081. oStyle['font-superscript'] = document.queryCommandState('superscript') ? 'superscript' : 'normal';
  1082. oStyle['font-subscript'] = document.queryCommandState('subscript') ? 'subscript' : 'normal';
  1083. // list-style-type to list-style(unordered, ordered)
  1084. if (!rng.isOnList()) {
  1085. oStyle['list-style'] = 'none';
  1086. } else {
  1087. var aOrderedType = ['circle', 'disc', 'disc-leading-zero', 'square'];
  1088. var isUnordered = $.inArray(oStyle['list-style-type'], aOrderedType) > -1;
  1089. oStyle['list-style'] = isUnordered ? 'unordered' : 'ordered';
  1090. }
  1091. var elPara = dom.ancestor(rng.sc, dom.isPara);
  1092. if (elPara && elPara.style['line-height']) {
  1093. oStyle['line-height'] = elPara.style.lineHeight;
  1094. } else {
  1095. var lineHeight = parseInt(oStyle['line-height'], 10) / parseInt(oStyle['font-size'], 10);
  1096. oStyle['line-height'] = lineHeight.toFixed(1);
  1097. }
  1098. oStyle.image = dom.isImg(elTarget) && elTarget;
  1099. oStyle.anchor = rng.isOnAnchor() && dom.ancestor(rng.sc, dom.isAnchor);
  1100. oStyle.aAncestor = dom.listAncestor(rng.sc, dom.isEditable);
  1101. oStyle.range = rng;
  1102. return oStyle;
  1103. };
  1104. };
  1105. /**
  1106. * range module
  1107. */
  1108. var range = (function () {
  1109. var isW3CRangeSupport = !!document.createRange;
  1110. /**
  1111. * return boundaryPoint from TextRange, inspired by Andy Na's HuskyRange.js
  1112. * @param {TextRange} textRange
  1113. * @param {Boolean} isStart
  1114. * @return {BoundaryPoint}
  1115. */
  1116. var textRange2bp = function (textRange, isStart) {
  1117. var elCont = textRange.parentElement(), nOffset;
  1118. var tester = document.body.createTextRange(), elPrevCont;
  1119. var aChild = list.from(elCont.childNodes);
  1120. for (nOffset = 0; nOffset < aChild.length; nOffset++) {
  1121. if (dom.isText(aChild[nOffset])) { continue; }
  1122. tester.moveToElementText(aChild[nOffset]);
  1123. if (tester.compareEndPoints('StartToStart', textRange) >= 0) { break; }
  1124. elPrevCont = aChild[nOffset];
  1125. }
  1126. if (nOffset !== 0 && dom.isText(aChild[nOffset - 1])) {
  1127. var textRangeStart = document.body.createTextRange(), elCurText = null;
  1128. textRangeStart.moveToElementText(elPrevCont || elCont);
  1129. textRangeStart.collapse(!elPrevCont);
  1130. elCurText = elPrevCont ? elPrevCont.nextSibling : elCont.firstChild;
  1131. var pointTester = textRange.duplicate();
  1132. pointTester.setEndPoint('StartToStart', textRangeStart);
  1133. var nTextCount = pointTester.text.replace(/[\r\n]/g, '').length;
  1134. while (nTextCount > elCurText.nodeValue.length && elCurText.nextSibling) {
  1135. nTextCount -= elCurText.nodeValue.length;
  1136. elCurText = elCurText.nextSibling;
  1137. }
  1138. /* jshint ignore:start */
  1139. var sDummy = elCurText.nodeValue; //enforce IE to re-reference elCurText, hack
  1140. /* jshint ignore:end */
  1141. if (isStart && elCurText.nextSibling && dom.isText(elCurText.nextSibling) &&
  1142. nTextCount === elCurText.nodeValue.length) {
  1143. nTextCount -= elCurText.nodeValue.length;
  1144. elCurText = elCurText.nextSibling;
  1145. }
  1146. elCont = elCurText;
  1147. nOffset = nTextCount;
  1148. }
  1149. return {cont: elCont, offset: nOffset};
  1150. };
  1151. /**
  1152. * return TextRange from boundary point (inspired by google closure-library)
  1153. * @param {BoundaryPoint} bp
  1154. * @return {TextRange}
  1155. */
  1156. var bp2textRange = function (bp) {
  1157. var textRangeInfo = function (elCont, nOffset) {
  1158. var elNode, isCollapseToStart;
  1159. if (dom.isText(elCont)) {
  1160. var aPrevText = dom.listPrev(elCont, func.not(dom.isText));
  1161. var elPrevCont = list.last(aPrevText).previousSibling;
  1162. elNode = elPrevCont || elCont.parentNode;
  1163. nOffset += list.sum(list.tail(aPrevText), dom.length);
  1164. isCollapseToStart = !elPrevCont;
  1165. } else {
  1166. elNode = elCont.childNodes[nOffset] || elCont;
  1167. if (dom.isText(elNode)) {
  1168. return textRangeInfo(elNode, nOffset);
  1169. }
  1170. nOffset = 0;
  1171. isCollapseToStart = false;
  1172. }
  1173. return {cont: elNode, collapseToStart: isCollapseToStart, offset: nOffset};
  1174. };
  1175. var textRange = document.body.createTextRange();
  1176. var info = textRangeInfo(bp.cont, bp.offset);
  1177. textRange.moveToElementText(info.cont);
  1178. textRange.collapse(info.collapseToStart);
  1179. textRange.moveStart('character', info.offset);
  1180. return textRange;
  1181. };
  1182. /**
  1183. * Wrapped Range
  1184. *
  1185. * @param {Element} sc - start container
  1186. * @param {Number} so - start offset
  1187. * @param {Element} ec - end container
  1188. * @param {Number} eo - end offset
  1189. */
  1190. var WrappedRange = function (sc, so, ec, eo) {
  1191. this.sc = sc;
  1192. this.so = so;
  1193. this.ec = ec;
  1194. this.eo = eo;
  1195. // nativeRange: get nativeRange from sc, so, ec, eo
  1196. var nativeRange = function () {
  1197. if (isW3CRangeSupport) {
  1198. var w3cRange = document.createRange();
  1199. w3cRange.setStart(sc, so);
  1200. w3cRange.setEnd(ec, eo);
  1201. return w3cRange;
  1202. } else {
  1203. var textRange = bp2textRange({cont: sc, offset: so});
  1204. textRange.setEndPoint('EndToEnd', bp2textRange({cont: ec, offset: eo}));
  1205. return textRange;
  1206. }
  1207. };
  1208. this.getBPs = function () {
  1209. return {
  1210. sc: sc,
  1211. so: so,
  1212. ec: ec,
  1213. eo: eo
  1214. };
  1215. };
  1216. this.getStartBP = function () {
  1217. return {
  1218. node: sc,
  1219. offset: so
  1220. };
  1221. };
  1222. this.getEndBP = function () {
  1223. return {
  1224. node: ec,
  1225. offset: eo
  1226. };
  1227. };
  1228. /**
  1229. * select update visible range
  1230. */
  1231. this.select = function () {
  1232. var nativeRng = nativeRange();
  1233. if (isW3CRangeSupport) {
  1234. var selection = document.getSelection();
  1235. if (selection.rangeCount > 0) { selection.removeAllRanges(); }
  1236. selection.addRange(nativeRng);
  1237. } else {
  1238. nativeRng.select();
  1239. }
  1240. };
  1241. /**
  1242. * returns matched nodes on range
  1243. *
  1244. * @param {Function} [pred] - predicate function
  1245. * @return {Element[]}
  1246. */
  1247. this.nodes = function (pred) {
  1248. pred = pred || func.ok;
  1249. var aNode = dom.listBetween(sc, ec);
  1250. var aMatched = list.compact($.map(aNode, function (node) {
  1251. return dom.ancestor(node, pred);
  1252. }));
  1253. return $.map(list.clusterBy(aMatched, func.eq2), list.head);
  1254. };
  1255. /**
  1256. * returns commonAncestor of range
  1257. * @return {Element} - commonAncestor
  1258. */
  1259. this.commonAncestor = function () {
  1260. return dom.commonAncestor(sc, ec);
  1261. };
  1262. /**
  1263. * returns expanded range by pred
  1264. *
  1265. * @param {Function} pred - predicate function
  1266. * @return {WrappedRange}
  1267. */
  1268. this.expand = function (pred) {
  1269. var startAncestor = dom.ancestor(sc, pred);
  1270. var endAncestor = dom.ancestor(ec, pred);
  1271. if (!startAncestor && !endAncestor) {
  1272. return new WrappedRange(sc, so, ec, eo);
  1273. }
  1274. var boundaryPoints = this.getBPs();
  1275. if (startAncestor) {
  1276. boundaryPoints.sc = startAncestor;
  1277. boundaryPoints.so = 0;
  1278. }
  1279. if (endAncestor) {
  1280. boundaryPoints.ec = endAncestor;
  1281. boundaryPoints.eo = dom.length(endAncestor);
  1282. }
  1283. return new WrappedRange(
  1284. boundaryPoints.sc,
  1285. boundaryPoints.so,
  1286. boundaryPoints.ec,
  1287. boundaryPoints.eo
  1288. );
  1289. };
  1290. /**
  1291. * @param {Boolean} isCollapseToStart
  1292. * @return {WrappedRange}
  1293. */
  1294. this.collapse = function (isCollapseToStart) {
  1295. if (isCollapseToStart) {
  1296. return new WrappedRange(sc, so, sc, so);
  1297. } else {
  1298. return new WrappedRange(ec, eo, ec, eo);
  1299. }
  1300. };
  1301. /**
  1302. * splitText on range
  1303. */
  1304. this.splitText = function () {
  1305. var isSameContainer = sc === ec;
  1306. var boundaryPoints = this.getBPs();
  1307. if (dom.isText(ec) && !dom.isEdgeBP(this.getEndBP())) {
  1308. ec.splitText(eo);
  1309. }
  1310. if (dom.isText(sc) && !dom.isEdgeBP(this.getStartBP())) {
  1311. boundaryPoints.sc = sc.splitText(so);
  1312. boundaryPoints.so = 0;
  1313. if (isSameContainer) {
  1314. boundaryPoints.ec = boundaryPoints.sc;
  1315. boundaryPoints.eo = eo - so;
  1316. }
  1317. }
  1318. return new WrappedRange(
  1319. boundaryPoints.sc,
  1320. boundaryPoints.so,
  1321. boundaryPoints.ec,
  1322. boundaryPoints.eo
  1323. );
  1324. };
  1325. /**
  1326. * delete contents on range
  1327. * @return {WrappedRange}
  1328. */
  1329. this.deleteContents = function () {
  1330. if (this.isCollapsed()) {
  1331. return this;
  1332. }
  1333. var rng = this.splitText();
  1334. var prevBP = dom.prevBP(rng.getStartBP());
  1335. $.each(rng.nodes(), function (idx, node) {
  1336. dom.remove(node, !dom.isPara(node));
  1337. });
  1338. return new WrappedRange(
  1339. prevBP.node,
  1340. prevBP.offset,
  1341. prevBP.node,
  1342. prevBP.offset
  1343. );
  1344. };
  1345. /**
  1346. * makeIsOn: return isOn(pred) function
  1347. */
  1348. var makeIsOn = function (pred) {
  1349. return function () {
  1350. var elAncestor = dom.ancestor(sc, pred);
  1351. return !!elAncestor && (elAncestor === dom.ancestor(ec, pred));
  1352. };
  1353. };
  1354. // isOnEditable: judge whether range is on editable or not
  1355. this.isOnEditable = makeIsOn(dom.isEditable);
  1356. // isOnList: judge whether range is on list node or not
  1357. this.isOnList = makeIsOn(dom.isList);
  1358. // isOnAnchor: judge whether range is on anchor node or not
  1359. this.isOnAnchor = makeIsOn(dom.isAnchor);
  1360. // isOnAnchor: judge whether range is on cell node or not
  1361. this.isOnCell = makeIsOn(dom.isCell);
  1362. // isCollapsed: judge whether range was collapsed
  1363. this.isCollapsed = function () { return sc === ec && so === eo; };
  1364. /**
  1365. * insert node at current cursor
  1366. * @param {Element} node
  1367. */
  1368. this.insertNode = function (node) {
  1369. var nativeRng = nativeRange();
  1370. if (isW3CRangeSupport) {
  1371. nativeRng.insertNode(node);
  1372. } else {
  1373. var tmpId = 'node-insert-node-target';
  1374. node.id = tmpId;
  1375. // NOTE: missing node reference.
  1376. nativeRng.pasteHTML(node.outerHTML);
  1377. node = $('#' + tmpId)[0];
  1378. }
  1379. return node;
  1380. };
  1381. this.toString = function () {
  1382. var nativeRng = nativeRange();
  1383. return isW3CRangeSupport ? nativeRng.toString() : nativeRng.text;
  1384. };
  1385. /**
  1386. * create offsetPath bookmark
  1387. * @param {Element} elEditable
  1388. */
  1389. this.bookmark = function (elEditable) {
  1390. return {
  1391. s: { path: dom.makeOffsetPath(elEditable, sc), offset: so },
  1392. e: { path: dom.makeOffsetPath(elEditable, ec), offset: eo }
  1393. };
  1394. };
  1395. /**
  1396. * getClientRects
  1397. * @return {Rect[]}
  1398. */
  1399. this.getClientRects = function () {
  1400. var nativeRng = nativeRange();
  1401. return nativeRng.getClientRects();
  1402. };
  1403. };
  1404. return {
  1405. /**
  1406. * create Range Object From arguments or Browser Selection
  1407. *
  1408. * @param {Element} sc - start container
  1409. * @param {Number} so - start offset
  1410. * @param {Element} ec - end container
  1411. * @param {Number} eo - end offset
  1412. */
  1413. create : function (sc, so, ec, eo) {
  1414. if (!arguments.length) { // from Browser Selection
  1415. if (isW3CRangeSupport) { // webkit, firefox
  1416. var selection = document.getSelection();
  1417. if (selection.rangeCount === 0) { return null; }
  1418. var nativeRng = selection.getRangeAt(0);
  1419. sc = nativeRng.startContainer;
  1420. so = nativeRng.startOffset;
  1421. ec = nativeRng.endContainer;
  1422. eo = nativeRng.endOffset;
  1423. } else { // IE8: TextRange
  1424. var textRange = document.selection.createRange();
  1425. var textRangeEnd = textRange.duplicate();
  1426. textRangeEnd.collapse(false);
  1427. var textRangeStart = textRange;
  1428. textRangeStart.collapse(true);
  1429. var bpStart = textRange2bp(textRangeStart, true),
  1430. bpEnd = textRange2bp(textRangeEnd, false);
  1431. sc = bpStart.cont;
  1432. so = bpStart.offset;
  1433. ec = bpEnd.cont;
  1434. eo = bpEnd.offset;
  1435. }
  1436. } else if (arguments.length === 2) { //collapsed
  1437. ec = sc;
  1438. eo = so;
  1439. }
  1440. return new WrappedRange(sc, so, ec, eo);
  1441. },
  1442. /**
  1443. * create WrappedRange from node
  1444. *
  1445. * @param {Element} node
  1446. * @return {WrappedRange}
  1447. */
  1448. createFromNode: function (node) {
  1449. return this.create(node, 0, node, 1);
  1450. },
  1451. /**
  1452. * create WrappedRange from Bookmark
  1453. *
  1454. * @param {Element} elEditable
  1455. * @param {Obkect} bookmark
  1456. * @return {WrappedRange}
  1457. */
  1458. createFromBookmark : function (elEditable, bookmark) {
  1459. var sc = dom.fromOffsetPath(elEditable, bookmark.s.path);
  1460. var so = bookmark.s.offset;
  1461. var ec = dom.fromOffsetPath(elEditable, bookmark.e.path);
  1462. var eo = bookmark.e.offset;
  1463. return new WrappedRange(sc, so, ec, eo);
  1464. }
  1465. };
  1466. })();
  1467. /**
  1468. * Table
  1469. * @class
  1470. */
  1471. var Table = function () {
  1472. /**
  1473. * handle tab key
  1474. *
  1475. * @param {WrappedRange} rng
  1476. * @param {Boolean} isShift
  1477. */
  1478. this.tab = function (rng, isShift) {
  1479. var elCell = dom.ancestor(rng.commonAncestor(), dom.isCell);
  1480. var elTable = dom.ancestor(elCell, dom.isTable);
  1481. var aCell = dom.listDescendant(elTable, dom.isCell);
  1482. var elNext = list[isShift ? 'prev' : 'next'](aCell, elCell);
  1483. if (elNext) {
  1484. range.create(elNext, 0).select();
  1485. }
  1486. };
  1487. /**
  1488. * create empty table element
  1489. *
  1490. * @param {Number} nRow
  1491. * @param {Number} nCol
  1492. */
  1493. this.createTable = function (nCol, nRow) {
  1494. var aTD = [], sTD;
  1495. for (var idxCol = 0; idxCol < nCol; idxCol++) {
  1496. aTD.push('<td>' + dom.blank + '</td>');
  1497. }
  1498. sTD = aTD.join('');
  1499. var aTR = [], sTR;
  1500. for (var idxRow = 0; idxRow < nRow; idxRow++) {
  1501. aTR.push('<tr>' + sTD + '</tr>');
  1502. }
  1503. sTR = aTR.join('');
  1504. var sTable = '<table class="table table-bordered">' + sTR + '</table>';
  1505. return $(sTable)[0];
  1506. };
  1507. };
  1508. /**
  1509. * Editor
  1510. * @class
  1511. */
  1512. var Editor = function () {
  1513. var style = new Style();
  1514. var table = new Table();
  1515. /**
  1516. * save current range
  1517. *
  1518. * @param {jQuery} $editable
  1519. */
  1520. this.saveRange = function ($editable) {
  1521. $editable.focus();
  1522. $editable.data('range', range.create());
  1523. };
  1524. /**
  1525. * restore lately range
  1526. *
  1527. * @param {jQuery} $editable
  1528. */
  1529. this.restoreRange = function ($editable) {
  1530. var rng = $editable.data('range');
  1531. if (rng) {
  1532. rng.select();
  1533. $editable.focus();
  1534. }
  1535. };
  1536. /**
  1537. * current style
  1538. * @param {Element} elTarget
  1539. */
  1540. this.currentStyle = function (elTarget) {
  1541. var rng = range.create();
  1542. return rng ? rng.isOnEditable() && style.current(rng, elTarget) : false;
  1543. };
  1544. /**
  1545. * undo
  1546. * @param {jQuery} $editable
  1547. */
  1548. this.undo = function ($editable) {
  1549. $editable.data('NoteHistory').undo($editable);
  1550. };
  1551. /**
  1552. * redo
  1553. * @param {jQuery} $editable
  1554. */
  1555. this.redo = function ($editable) {
  1556. $editable.data('NoteHistory').redo($editable);
  1557. };
  1558. /**
  1559. * record Undo
  1560. * @param {jQuery} $editable
  1561. */
  1562. var recordUndo = this.recordUndo = function ($editable) {
  1563. $editable.data('NoteHistory').recordUndo($editable);
  1564. };
  1565. /* jshint ignore:start */
  1566. // native commands(with execCommand), generate function for execCommand
  1567. var aCmd = ['bold', 'italic', 'underline', 'strikethrough', 'superscript', 'subscript',
  1568. 'justifyLeft', 'justifyCenter', 'justifyRight', 'justifyFull',
  1569. 'insertOrderedList', 'insertUnorderedList',
  1570. 'indent', 'outdent', 'formatBlock', 'removeFormat',
  1571. 'backColor', 'foreColor', 'insertHorizontalRule', 'fontName'];
  1572. for (var idx = 0, len = aCmd.length; idx < len; idx ++) {
  1573. this[aCmd[idx]] = (function (sCmd) {
  1574. return function ($editable, sValue) {
  1575. recordUndo($editable);
  1576. document.execCommand(sCmd, false, sValue);
  1577. };
  1578. })(aCmd[idx]);
  1579. }
  1580. /* jshint ignore:end */
  1581. /**
  1582. * @param {jQuery} $editable
  1583. * @param {WrappedRange} rng
  1584. * @param {Number} nTabsize
  1585. */
  1586. var insertTab = function ($editable, rng, nTabsize) {
  1587. recordUndo($editable);
  1588. var sNbsp = new Array(nTabsize + 1).join('&nbsp;');
  1589. rng.insertNode($('<span id="noteTab">' + sNbsp + '</span>')[0]);
  1590. var $tab = $('#noteTab').removeAttr('id');
  1591. rng = range.create($tab[0], 1);
  1592. rng.select();
  1593. dom.remove($tab[0]);
  1594. };
  1595. /**
  1596. * handle tab key
  1597. * @param {jQuery} $editable
  1598. * @param {Object} options
  1599. */
  1600. this.tab = function ($editable, options) {
  1601. var rng = range.create();
  1602. if (rng.isCollapsed() && rng.isOnCell()) {
  1603. table.tab(rng);
  1604. } else {
  1605. insertTab($editable, rng, options.tabsize);
  1606. }
  1607. };
  1608. /**
  1609. * handle shift+tab key
  1610. */
  1611. this.untab = function () {
  1612. var rng = range.create();
  1613. if (rng.isCollapsed() && rng.isOnCell()) {
  1614. table.tab(rng, true);
  1615. }
  1616. };
  1617. /**
  1618. * insert image
  1619. *
  1620. * @param {jQuery} $editable
  1621. * @param {String} sUrl
  1622. */
  1623. this.insertImage = function ($editable, sUrl) {
  1624. async.createImage(sUrl).then(function ($image) {
  1625. recordUndo($editable);
  1626. $image.css({
  1627. display: '',
  1628. width: Math.min($editable.width(), $image.width())
  1629. });
  1630. range.create().insertNode($image[0]);
  1631. }).fail(function () {
  1632. var callbacks = $editable.data('callbacks');
  1633. if (callbacks.onImageUploadError) {
  1634. callbacks.onImageUploadError();
  1635. }
  1636. });
  1637. };
  1638. /**
  1639. * insert video
  1640. * @param {jQuery} $editable
  1641. * @param {String} sUrl
  1642. */
  1643. this.insertVideo = function ($editable, sUrl) {
  1644. recordUndo($editable);
  1645. // video url patterns(youtube, instagram, vimeo, dailymotion, youku)
  1646. var ytRegExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
  1647. var ytMatch = sUrl.match(ytRegExp);
  1648. var igRegExp = /\/\/instagram.com\/p\/(.[a-zA-Z0-9]*)/;
  1649. var igMatch = sUrl.match(igRegExp);
  1650. var vRegExp = /\/\/vine.co\/v\/(.[a-zA-Z0-9]*)/;
  1651. var vMatch = sUrl.match(vRegExp);
  1652. var vimRegExp = /\/\/(player.)?vimeo.com\/([a-z]*\/)*([0-9]{6,11})[?]?.*/;
  1653. var vimMatch = sUrl.match(vimRegExp);
  1654. var dmRegExp = /.+dailymotion.com\/(video|hub)\/([^_]+)[^#]*(#video=([^_&]+))?/;
  1655. var dmMatch = sUrl.match(dmRegExp);
  1656. var youkuRegExp = /\/\/v\.youku\.com\/v_show\/id_(\w+)\.html/;
  1657. var youkuMatch = sUrl.match(youkuRegExp);
  1658. var $video;
  1659. if (ytMatch && ytMatch[2].length === 11) {
  1660. var youtubeId = ytMatch[2];
  1661. $video = $('<iframe>')
  1662. .attr('src', '//www.youtube.com/embed/' + youtubeId)
  1663. .attr('width', '640').attr('height', '360');
  1664. } else if (igMatch && igMatch[0].length) {
  1665. $video = $('<iframe>')
  1666. .attr('src', igMatch[0] + '/embed/')
  1667. .attr('width', '612').attr('height', '710')
  1668. .attr('scrolling', 'no')
  1669. .attr('allowtransparency', 'true');
  1670. } else if (vMatch && vMatch[0].length) {
  1671. $video = $('<iframe>')
  1672. .attr('src', vMatch[0] + '/embed/simple')
  1673. .attr('width', '600').attr('height', '600')
  1674. .attr('class', 'vine-embed');
  1675. } else if (vimMatch && vimMatch[3].length) {
  1676. $video = $('<iframe webkitallowfullscreen mozallowfullscreen allowfullscreen>')
  1677. .attr('src', '//player.vimeo.com/video/' + vimMatch[3])
  1678. .attr('width', '640').attr('height', '360');
  1679. } else if (dmMatch && dmMatch[2].length) {
  1680. $video = $('<iframe>')
  1681. .attr('src', '//www.dailymotion.com/embed/video/' + dmMatch[2])
  1682. .attr('width', '640').attr('height', '360');
  1683. } else if (youkuMatch && youkuMatch[1].length) {
  1684. $video = $('<iframe webkitallowfullscreen mozallowfullscreen allowfullscreen>')
  1685. .attr('height', '498')
  1686. .attr('width', '510')
  1687. .attr('src', '//player.youku.com/embed/' + youkuMatch[1]);
  1688. } else {
  1689. // this is not a known video link. Now what, Cat? Now what?
  1690. }
  1691. if ($video) {
  1692. $video.attr('frameborder', 0);
  1693. range.create().insertNode($video[0]);
  1694. }
  1695. };
  1696. /**
  1697. * formatBlock
  1698. *
  1699. * @param {jQuery} $editable
  1700. * @param {String} sTagName
  1701. */
  1702. this.formatBlock = function ($editable, sTagName) {
  1703. recordUndo($editable);
  1704. sTagName = agent.isMSIE ? '<' + sTagName + '>' : sTagName;
  1705. document.execCommand('FormatBlock', false, sTagName);
  1706. };
  1707. this.formatPara = function ($editable) {
  1708. this.formatBlock($editable, 'P');
  1709. };
  1710. /* jshint ignore:start */
  1711. for (var idx = 1; idx <= 6; idx ++) {
  1712. this['formatH' + idx] = function (idx) {
  1713. return function ($editable) {
  1714. this.formatBlock($editable, 'H' + idx);
  1715. };
  1716. }(idx);
  1717. };
  1718. /* jshint ignore:end */
  1719. /**
  1720. * fontsize
  1721. * FIXME: Still buggy
  1722. *
  1723. * @param {jQuery} $editable
  1724. * @param {String} sValue - px
  1725. */
  1726. this.fontSize = function ($editable, sValue) {
  1727. recordUndo($editable);
  1728. document.execCommand('fontSize', false, 3);
  1729. if (agent.isFF) {
  1730. // firefox: <font size="3"> to <span style='font-size={sValue}px;'>, buggy
  1731. $editable.find('font[size=3]').removeAttr('size').css('font-size', sValue + 'px');
  1732. } else {
  1733. // chrome: <span style="font-size: medium"> to <span style='font-size={sValue}px;'>
  1734. $editable.find('span').filter(function () {
  1735. return this.style.fontSize === 'medium';
  1736. }).css('font-size', sValue + 'px');
  1737. }
  1738. };
  1739. /**
  1740. * lineHeight
  1741. * @param {jQuery} $editable
  1742. * @param {String} sValue
  1743. */
  1744. this.lineHeight = function ($editable, sValue) {
  1745. recordUndo($editable);
  1746. style.stylePara(range.create(), {lineHeight: sValue});
  1747. };
  1748. /**
  1749. * unlink
  1750. * @param {jQuery} $editable
  1751. */
  1752. this.unlink = function ($editable) {
  1753. var rng = range.create();
  1754. if (rng.isOnAnchor()) {
  1755. recordUndo($editable);
  1756. var elAnchor = dom.ancestor(rng.sc, dom.isAnchor);
  1757. rng = range.createFromNode(elAnchor);
  1758. rng.select();
  1759. document.execCommand('unlink');
  1760. }
  1761. };
  1762. /**
  1763. * create link
  1764. *
  1765. * @param {jQuery} $editable
  1766. * @param {Object} linkInfo
  1767. * @param {Object} options
  1768. */
  1769. this.createLink = function ($editable, linkInfo, options) {
  1770. var sLinkUrl = linkInfo.url;
  1771. var sLinkText = linkInfo.text;
  1772. var isNewWindow = linkInfo.newWindow;
  1773. var rng = linkInfo.range;
  1774. recordUndo($editable);
  1775. if (options.onCreateLink) {
  1776. sLinkUrl = options.onCreateLink(sLinkUrl);
  1777. }
  1778. rng = rng.deleteContents();
  1779. // Create a new link when there is no anchor on range.
  1780. var anchor = rng.insertNode($('<A>' + sLinkText + '</A>')[0]);
  1781. $(anchor).attr({
  1782. href: sLinkUrl,
  1783. target: isNewWindow ? '_blank' : ''
  1784. });
  1785. rng = range.createFromNode(anchor);
  1786. rng.select();
  1787. };
  1788. /**
  1789. * returns link info
  1790. *
  1791. * @return {Object}
  1792. */
  1793. this.getLinkInfo = function ($editable) {
  1794. $editable.focus();
  1795. var rng = range.create().expand(dom.isAnchor);
  1796. // Get the first anchor on range(for edit).
  1797. var $anchor = $(list.head(rng.nodes(dom.isAnchor)));
  1798. return {
  1799. range: rng,
  1800. text: rng.toString(),
  1801. isNewWindow: $anchor.length ? $anchor.attr('target') === '_blank' : true,
  1802. url: $anchor.length ? $anchor.attr('href') : ''
  1803. };
  1804. };
  1805. /**
  1806. * get video info
  1807. *
  1808. * @param {jQuery} $editable
  1809. * @return {Object}
  1810. */
  1811. this.getVideoInfo = function ($editable) {
  1812. $editable.focus();
  1813. var rng = range.create();
  1814. if (rng.isOnAnchor()) {
  1815. var elAnchor = dom.ancestor(rng.sc, dom.isAnchor);
  1816. rng = range.createFromNode(elAnchor);
  1817. }
  1818. return {
  1819. text: rng.toString()
  1820. };
  1821. };
  1822. this.color = function ($editable, sObjColor) {
  1823. var oColor = JSON.parse(sObjColor);
  1824. var foreColor = oColor.foreColor, backColor = oColor.backColor;
  1825. recordUndo($editable);
  1826. if (foreColor) { document.execCommand('foreColor', false, foreColor); }
  1827. if (backColor) { document.execCommand('backColor', false, backColor); }
  1828. };
  1829. this.insertTable = function ($editable, sDim) {
  1830. recordUndo($editable);
  1831. var aDim = sDim.split('x');
  1832. range.create().insertNode(table.createTable(aDim[0], aDim[1]));
  1833. };
  1834. /**
  1835. * @param {jQuery} $editable
  1836. * @param {String} sValue
  1837. * @param {jQuery} $target
  1838. */
  1839. this.floatMe = function ($editable, sValue, $target) {
  1840. recordUndo($editable);
  1841. $target.css('float', sValue);
  1842. };
  1843. /**
  1844. * resize overlay element
  1845. * @param {jQuery} $editable
  1846. * @param {String} sValue
  1847. * @param {jQuery} $target - target element
  1848. */
  1849. this.resize = function ($editable, sValue, $target) {
  1850. recordUndo($editable);
  1851. $target.css({
  1852. width: $editable.width() * sValue + 'px',
  1853. height: ''
  1854. });
  1855. };
  1856. /**
  1857. * @param {Position} pos
  1858. * @param {jQuery} $target - target element
  1859. * @param {Boolean} [bKeepRatio] - keep ratio
  1860. */
  1861. this.resizeTo = function (pos, $target, bKeepRatio) {
  1862. var szImage;
  1863. if (bKeepRatio) {
  1864. var newRatio = pos.y / pos.x;
  1865. var ratio = $target.data('ratio');
  1866. szImage = {
  1867. width: ratio > newRatio ? pos.x : pos.y / ratio,
  1868. height: ratio > newRatio ? pos.x * ratio : pos.y
  1869. };
  1870. } else {
  1871. szImage = {
  1872. width: pos.x,
  1873. height: pos.y
  1874. };
  1875. }
  1876. $target.css(szImage);
  1877. };
  1878. /**
  1879. * remove media object
  1880. *
  1881. * @param {jQuery} $editable
  1882. * @param {String} sValue - dummy argument (for keep interface)
  1883. * @param {jQuery} $target - target element
  1884. */
  1885. this.removeMedia = function ($editable, sValue, $target) {
  1886. recordUndo($editable);
  1887. $target.detach();
  1888. };
  1889. };
  1890. /**
  1891. * History
  1892. * @class
  1893. */
  1894. var History = function () {
  1895. var aUndo = [], aRedo = [];
  1896. var makeSnap = function ($editable) {
  1897. var elEditable = $editable[0], rng = range.create();
  1898. return {
  1899. contents: $editable.html(),
  1900. bookmark: rng.bookmark(elEditable),
  1901. scrollTop: $editable.scrollTop()
  1902. };
  1903. };
  1904. var applySnap = function ($editable, oSnap) {
  1905. $editable.html(oSnap.contents).scrollTop(oSnap.scrollTop);
  1906. range.createFromBookmark($editable[0], oSnap.bookmark).select();
  1907. };
  1908. this.undo = function ($editable) {
  1909. var oSnap = makeSnap($editable);
  1910. if (!aUndo.length) { return; }
  1911. applySnap($editable, aUndo.pop());
  1912. aRedo.push(oSnap);
  1913. };
  1914. this.redo = function ($editable) {
  1915. var oSnap = makeSnap($editable);
  1916. if (!aRedo.length) { return; }
  1917. applySnap($editable, aRedo.pop());
  1918. aUndo.push(oSnap);
  1919. };
  1920. this.recordUndo = function ($editable) {
  1921. aRedo = [];
  1922. aUndo.push(makeSnap($editable));
  1923. };
  1924. };
  1925. /**
  1926. * Button
  1927. */
  1928. var Button = function () {
  1929. /**
  1930. * update button status
  1931. *
  1932. * @param {jQuery} $container
  1933. * @param {Object} oStyle
  1934. */
  1935. this.update = function ($container, oStyle) {
  1936. /**
  1937. * handle dropdown's check mark (for fontname, fontsize, lineHeight).
  1938. * @param {jQuery} $btn
  1939. * @param {Number} nValue
  1940. */
  1941. var checkDropdownMenu = function ($btn, nValue) {
  1942. $btn.find('.dropdown-menu li a').each(function () {
  1943. // always compare string to avoid creating another func.
  1944. var isChecked = ($(this).data('value') + '') === (nValue + '');
  1945. this.className = isChecked ? 'checked' : '';
  1946. });
  1947. };
  1948. /**
  1949. * update button state(active or not).
  1950. *
  1951. * @param {String} sSelector
  1952. * @param {Function} pred
  1953. */
  1954. var btnState = function (sSelector, pred) {
  1955. var $btn = $container.find(sSelector);
  1956. $btn.toggleClass('active', pred());
  1957. };
  1958. // fontname
  1959. var $fontname = $container.find('.note-fontname');
  1960. if ($fontname.length) {
  1961. var selectedFont = oStyle['font-family'];
  1962. if (!!selectedFont) {
  1963. selectedFont = list.head(selectedFont.split(','));
  1964. selectedFont = selectedFont.replace(/\'/g, '');
  1965. $fontname.find('.note-current-fontname').text(selectedFont);
  1966. checkDropdownMenu($fontname, selectedFont);
  1967. }
  1968. }
  1969. // fontsize
  1970. var $fontsize = $container.find('.note-fontsize');
  1971. $fontsize.find('.note-current-fontsize').text(oStyle['font-size']);
  1972. checkDropdownMenu($fontsize, parseFloat(oStyle['font-size']));
  1973. // lineheight
  1974. var $lineHeight = $container.find('.note-height');
  1975. checkDropdownMenu($lineHeight, parseFloat(oStyle['line-height']));
  1976. btnState('button[data-event="bold"]', function () {
  1977. return oStyle['font-bold'] === 'bold';
  1978. });
  1979. btnState('button[data-event="italic"]', function () {
  1980. return oStyle['font-italic'] === 'italic';
  1981. });
  1982. btnState('button[data-event="underline"]', function () {
  1983. return oStyle['font-underline'] === 'underline';
  1984. });
  1985. btnState('button[data-event="strikethrough"]', function () {
  1986. return oStyle['font-strikethrough'] === 'strikethrough';
  1987. });
  1988. btnState('button[data-event="superscript"]', function () {
  1989. return oStyle['font-superscript'] === 'superscript';
  1990. });
  1991. btnState('button[data-event="subscript"]', function () {
  1992. return oStyle['font-subscript'] === 'subscript';
  1993. });
  1994. btnState('button[data-event="justifyLeft"]', function () {
  1995. return oStyle['text-align'] === 'left' || oStyle['text-align'] === 'start';
  1996. });
  1997. btnState('button[data-event="justifyCenter"]', function () {
  1998. return oStyle['text-align'] === 'center';
  1999. });
  2000. btnState('button[data-event="justifyRight"]', function () {
  2001. return oStyle['text-align'] === 'right';
  2002. });
  2003. btnState('button[data-event="justifyFull"]', function () {
  2004. return oStyle['text-align'] === 'justify';
  2005. });
  2006. btnState('button[data-event="insertUnorderedList"]', function () {
  2007. return oStyle['list-style'] === 'unordered';
  2008. });
  2009. btnState('button[data-event="insertOrderedList"]', function () {
  2010. return oStyle['list-style'] === 'ordered';
  2011. });
  2012. };
  2013. /**
  2014. * update recent color
  2015. *
  2016. * @param {Element} elBtn
  2017. * @param {String} sEvent
  2018. * @param {sValue} sValue
  2019. */
  2020. this.updateRecentColor = function (elBtn, sEvent, sValue) {
  2021. var $color = $(elBtn).closest('.note-color');
  2022. var $recentColor = $color.find('.note-recent-color');
  2023. var oColor = JSON.parse($recentColor.attr('data-value'));
  2024. oColor[sEvent] = sValue;
  2025. $recentColor.attr('data-value', JSON.stringify(oColor));
  2026. var sKey = sEvent === 'backColor' ? 'background-color' : 'color';
  2027. $recentColor.find('i').css(sKey, sValue);
  2028. };
  2029. };
  2030. /**
  2031. * Toolbar
  2032. */
  2033. var Toolbar = function () {
  2034. var button = new Button();
  2035. this.update = function ($toolbar, oStyle) {
  2036. button.update($toolbar, oStyle);
  2037. };
  2038. this.updateRecentColor = function (elBtn, sEvent, sValue) {
  2039. button.updateRecentColor(elBtn, sEvent, sValue);
  2040. };
  2041. /**
  2042. * activate buttons exclude codeview
  2043. * @param {jQuery} $toolbar
  2044. */
  2045. this.activate = function ($toolbar) {
  2046. $toolbar.find('button').not('button[data-event="codeview"]').removeClass('disabled');
  2047. };
  2048. /**
  2049. * deactivate buttons exclude codeview
  2050. * @param {jQuery} $toolbar
  2051. */
  2052. this.deactivate = function ($toolbar) {
  2053. $toolbar.find('button').not('button[data-event="codeview"]').addClass('disabled');
  2054. };
  2055. this.updateFullscreen = function ($container, bFullscreen) {
  2056. var $btn = $container.find('button[data-event="fullscreen"]');
  2057. $btn.toggleClass('active', bFullscreen);
  2058. };
  2059. this.updateCodeview = function ($container, isCodeview) {
  2060. var $btn = $container.find('button[data-event="codeview"]');
  2061. $btn.toggleClass('active', isCodeview);
  2062. };
  2063. };
  2064. /**
  2065. * Popover (http://getbootstrap.com/javascript/#popovers)
  2066. */
  2067. var Popover = function () {
  2068. var button = new Button();
  2069. /**
  2070. * returns position from placeholder
  2071. * @param {Element} placeholder
  2072. * @param {Boolean} isAirMode
  2073. */
  2074. var posFromPlaceholder = function (placeholder, isAirMode) {
  2075. var $placeholder = $(placeholder);
  2076. var pos = isAirMode ? $placeholder.offset() : $placeholder.position();
  2077. var height = $placeholder.outerHeight(true); // include margin
  2078. // popover below placeholder.
  2079. return {
  2080. left: pos.left,
  2081. top: pos.top + height
  2082. };
  2083. };
  2084. /**
  2085. * show popover
  2086. * @param {jQuery} popover
  2087. * @param {Position} pos
  2088. */
  2089. var showPopover = function ($popover, pos) {
  2090. $popover.css({
  2091. display: 'block',
  2092. left: pos.left,
  2093. top: pos.top
  2094. });
  2095. };
  2096. var PX_POPOVER_ARROW_OFFSET_X = 20;
  2097. /**
  2098. * update current state
  2099. * @param {jQuery} $popover - popover container
  2100. * @param {Object} oStyle - style object
  2101. * @param {Boolean} isAirMode
  2102. */
  2103. this.update = function ($popover, oStyle, isAirMode) {
  2104. button.update($popover, oStyle);
  2105. var $linkPopover = $popover.find('.note-link-popover');
  2106. if (oStyle.anchor) {
  2107. var $anchor = $linkPopover.find('a');
  2108. var href = $(oStyle.anchor).attr('href');
  2109. $anchor.attr('href', href).html(href);
  2110. showPopover($linkPopover, posFromPlaceholder(oStyle.anchor, isAirMode));
  2111. } else {
  2112. $linkPopover.hide();
  2113. }
  2114. var $imagePopover = $popover.find('.note-image-popover');
  2115. if (oStyle.image) {
  2116. showPopover($imagePopover, posFromPlaceholder(oStyle.image, isAirMode));
  2117. } else {
  2118. $imagePopover.hide();
  2119. }
  2120. var $airPopover = $popover.find('.note-air-popover');
  2121. if (isAirMode && !oStyle.range.isCollapsed()) {
  2122. var bnd = func.rect2bnd(list.last(oStyle.range.getClientRects()));
  2123. showPopover($airPopover, {
  2124. left: Math.max(bnd.left + bnd.width / 2 - PX_POPOVER_ARROW_OFFSET_X, 0),
  2125. top: bnd.top + bnd.height
  2126. });
  2127. } else {
  2128. $airPopover.hide();
  2129. }
  2130. };
  2131. this.updateRecentColor = function (elBtn, sEvent, sValue) {
  2132. button.updateRecentColor(elBtn, sEvent, sValue);
  2133. };
  2134. /**
  2135. * hide all popovers
  2136. * @param {jQuery} $popover - popover contaienr
  2137. */
  2138. this.hide = function ($popover) {
  2139. $popover.children().hide();
  2140. };
  2141. };
  2142. /**
  2143. * Handle
  2144. */
  2145. var Handle = function () {
  2146. /**
  2147. * update handle
  2148. * @param {jQuery} $handle
  2149. * @param {Object} oStyle
  2150. * @param {Boolean} isAirMode
  2151. */
  2152. this.update = function ($handle, oStyle, isAirMode) {
  2153. var $selection = $handle.find('.note-control-selection');
  2154. if (oStyle.image) {
  2155. var $image = $(oStyle.image);
  2156. var pos = isAirMode ? $image.offset() : $image.position();
  2157. // include margin
  2158. var szImage = {
  2159. w: $image.outerWidth(true),
  2160. h: $image.outerHeight(true)
  2161. };
  2162. $selection.css({
  2163. display: 'block',
  2164. left: pos.left,
  2165. top: pos.top,
  2166. width: szImage.w,
  2167. height: szImage.h
  2168. }).data('target', oStyle.image); // save current image element.
  2169. var sSizing = szImage.w + 'x' + szImage.h;
  2170. $selection.find('.note-control-selection-info').text(sSizing);
  2171. } else {
  2172. $selection.hide();
  2173. }
  2174. };
  2175. this.hide = function ($handle) {
  2176. $handle.children().hide();
  2177. };
  2178. };
  2179. /**
  2180. * Dialog
  2181. *
  2182. * @class
  2183. */
  2184. var Dialog = function () {
  2185. /**
  2186. * toggle button status
  2187. *
  2188. * @param {jQuery} $btn
  2189. * @param {Boolean} isEnable
  2190. */
  2191. var toggleBtn = function ($btn, isEnable) {
  2192. $btn.toggleClass('disabled', !isEnable);
  2193. $btn.attr('disabled', !isEnable);
  2194. };
  2195. /**
  2196. * show image dialog
  2197. *
  2198. * @param {jQuery} $editable
  2199. * @param {jQuery} $dialog
  2200. * @return {Promise}
  2201. */
  2202. this.showImageDialog = function ($editable, $dialog) {
  2203. return $.Deferred(function (deferred) {
  2204. var $imageDialog = $dialog.find('.note-image-dialog');
  2205. var $imageInput = $dialog.find('.note-image-input'),
  2206. $imageUrl = $dialog.find('.note-image-url'),
  2207. $imageBtn = $dialog.find('.note-image-btn');
  2208. $imageDialog.one('shown.bs.modal', function () {
  2209. // Cloning imageInput to clear element.
  2210. $imageInput.replaceWith($imageInput.clone()
  2211. .on('change', function () {
  2212. deferred.resolve(this.files);
  2213. $imageDialog.modal('hide');
  2214. })
  2215. );
  2216. $imageBtn.click(function (event) {
  2217. event.preventDefault();
  2218. deferred.resolve($imageUrl.val());
  2219. $imageDialog.modal('hide');
  2220. });
  2221. $imageUrl.on('keyup paste', function (event) {
  2222. var url;
  2223. if (event.type === 'paste') {
  2224. url = event.originalEvent.clipboardData.getData('text');
  2225. } else {
  2226. url = $imageUrl.val();
  2227. }
  2228. toggleBtn($imageBtn, url);
  2229. }).val('').trigger('focus');
  2230. }).one('hidden.bs.modal', function () {
  2231. $imageInput.off('change');
  2232. $imageUrl.off('keyup paste');
  2233. $imageBtn.off('click');
  2234. if (deferred.state() === 'pending') {
  2235. deferred.reject();
  2236. }
  2237. }).modal('show');
  2238. });
  2239. };
  2240. /**
  2241. * Show video dialog and set event handlers on dialog controls.
  2242. *
  2243. * @param {jQuery} $dialog
  2244. * @param {Object} videoInfo
  2245. * @return {Promise}
  2246. */
  2247. this.showVideoDialog = function ($editable, $dialog, videoInfo) {
  2248. return $.Deferred(function (deferred) {
  2249. var $videoDialog = $dialog.find('.note-video-dialog');
  2250. var $videoUrl = $videoDialog.find('.note-video-url'),
  2251. $videoBtn = $videoDialog.find('.note-video-btn');
  2252. $videoDialog.one('shown.bs.modal', function () {
  2253. $videoUrl.val(videoInfo.text).keyup(function () {
  2254. toggleBtn($videoBtn, $videoUrl.val());
  2255. }).trigger('keyup').trigger('focus');
  2256. $videoBtn.click(function (event) {
  2257. event.preventDefault();
  2258. deferred.resolve($videoUrl.val());
  2259. $videoDialog.modal('hide');
  2260. });
  2261. }).one('hidden.bs.modal', function () {
  2262. // dettach events
  2263. $videoUrl.off('keyup');
  2264. $videoBtn.off('click');
  2265. if (deferred.state() === 'pending') {
  2266. deferred.reject();
  2267. }
  2268. }).modal('show');
  2269. });
  2270. };
  2271. /**
  2272. * Show link dialog and set event handlers on dialog controls.
  2273. *
  2274. * @param {jQuery} $dialog
  2275. * @param {Object} linkInfo
  2276. * @return {Promise}
  2277. */
  2278. this.showLinkDialog = function ($editable, $dialog, linkInfo) {
  2279. return $.Deferred(function (deferred) {
  2280. var $linkDialog = $dialog.find('.note-link-dialog');
  2281. var $linkText = $linkDialog.find('.note-link-text'),
  2282. $linkUrl = $linkDialog.find('.note-link-url'),
  2283. $linkBtn = $linkDialog.find('.note-link-btn'),
  2284. $openInNewWindow = $linkDialog.find('input[type=checkbox]');
  2285. $linkDialog.one('shown.bs.modal', function () {
  2286. $linkText.val(linkInfo.text);
  2287. $linkText.keyup(function () {
  2288. // if linktext was modified by keyup,
  2289. // stop cloning text from linkUrl
  2290. linkInfo.text = $linkText.val();
  2291. });
  2292. // if no url was given, copy text to url
  2293. if (!linkInfo.url) {
  2294. linkInfo.url = linkInfo.text;
  2295. toggleBtn($linkBtn, linkInfo.text);
  2296. }
  2297. $linkUrl.keyup(function () {
  2298. toggleBtn($linkBtn, $linkUrl.val());
  2299. // display same link on `Text to display` input
  2300. // when create a new link
  2301. if (!linkInfo.text) {
  2302. $linkText.val($linkUrl.val());
  2303. }
  2304. }).val(linkInfo.url).trigger('focus').trigger('select');
  2305. $openInNewWindow.prop('checked', linkInfo.newWindow);
  2306. $linkBtn.one('click', function (event) {
  2307. event.preventDefault();
  2308. deferred.resolve({
  2309. range: linkInfo.range,
  2310. url: $linkUrl.val(),
  2311. text: $linkText.val(),
  2312. newWindow: $openInNewWindow.is(':checked')
  2313. });
  2314. $linkDialog.modal('hide');
  2315. });
  2316. }).one('hidden.bs.modal', function () {
  2317. // dettach events
  2318. $linkText.off('keyup');
  2319. $linkUrl.off('keyup');
  2320. $linkBtn.off('click');
  2321. if (deferred.state() === 'pending') {
  2322. deferred.reject();
  2323. }
  2324. }).modal('show');
  2325. }).promise();
  2326. };
  2327. /**
  2328. * show help dialog
  2329. *
  2330. * @param {jQuery} $dialog
  2331. */
  2332. this.showHelpDialog = function ($editable, $dialog) {
  2333. return $.Deferred(function (deferred) {
  2334. var $helpDialog = $dialog.find('.note-help-dialog');
  2335. $helpDialog.one('hidden.bs.modal', function () {
  2336. deferred.resolve();
  2337. }).modal('show');
  2338. }).promise();
  2339. };
  2340. };
  2341. var CodeMirror;
  2342. if (agent.hasCodeMirror) {
  2343. if (agent.isSupportAmd) {
  2344. require(['CodeMirror'], function (cm) {
  2345. CodeMirror = cm;
  2346. });
  2347. } else {
  2348. CodeMirror = window.CodeMirror;
  2349. }
  2350. }
  2351. /**
  2352. * EventHandler
  2353. */
  2354. var EventHandler = function () {
  2355. var $window = $(window);
  2356. var $document = $(document);
  2357. var $scrollbar = $('html, body');
  2358. var editor = new Editor();
  2359. var toolbar = new Toolbar(), popover = new Popover();
  2360. var handle = new Handle(), dialog = new Dialog();
  2361. /**
  2362. * returns makeLayoutInfo from editor's descendant node.
  2363. *
  2364. * @param {Element} descendant
  2365. * @returns {Object}
  2366. */
  2367. var makeLayoutInfo = function (descendant) {
  2368. var $target = $(descendant).closest('.note-editor, .note-air-editor, .note-air-layout');
  2369. if (!$target.length) { return null; }
  2370. var $editor;
  2371. if ($target.is('.note-editor, .note-air-editor')) {
  2372. $editor = $target;
  2373. } else {
  2374. $editor = $('#note-editor-' + list.last($target.attr('id').split('-')));
  2375. }
  2376. return dom.buildLayoutInfo($editor);
  2377. };
  2378. /**
  2379. * insert Images from file array.
  2380. *
  2381. * @param {jQuery} $editable
  2382. * @param {File[]} files
  2383. */
  2384. var insertImages = function ($editable, files) {
  2385. editor.restoreRange($editable);
  2386. var callbacks = $editable.data('callbacks');
  2387. // If onImageUpload options setted
  2388. if (callbacks.onImageUpload) {
  2389. callbacks.onImageUpload(files, editor, $editable);
  2390. // else insert Image as dataURL
  2391. } else {
  2392. $.each(files, function (idx, file) {
  2393. async.readFileAsDataURL(file).then(function (sDataURL) {
  2394. editor.insertImage($editable, sDataURL);
  2395. }).fail(function () {
  2396. if (callbacks.onImageUploadError) {
  2397. callbacks.onImageUploadError();
  2398. }
  2399. });
  2400. });
  2401. }
  2402. };
  2403. var commands = {
  2404. /**
  2405. * @param {Object} oLayoutInfo
  2406. */
  2407. showLinkDialog: function (oLayoutInfo) {
  2408. var $editor = oLayoutInfo.editor(),
  2409. $dialog = oLayoutInfo.dialog(),
  2410. $editable = oLayoutInfo.editable(),
  2411. linkInfo = editor.getLinkInfo($editable);
  2412. var options = $editor.data('options');
  2413. editor.saveRange($editable);
  2414. dialog.showLinkDialog($editable, $dialog, linkInfo).then(function (linkInfo) {
  2415. editor.restoreRange($editable);
  2416. editor.createLink($editable, linkInfo, options);
  2417. // hide popover after creating link
  2418. popover.hide(oLayoutInfo.popover());
  2419. }).fail(function () {
  2420. editor.restoreRange($editable);
  2421. });
  2422. },
  2423. /**
  2424. * @param {Object} oLayoutInfo
  2425. */
  2426. showImageDialog: function (oLayoutInfo) {
  2427. var $dialog = oLayoutInfo.dialog(),
  2428. $editable = oLayoutInfo.editable();
  2429. editor.saveRange($editable);
  2430. dialog.showImageDialog($editable, $dialog).then(function (data) {
  2431. editor.restoreRange($editable);
  2432. if (typeof data === 'string') {
  2433. // image url
  2434. editor.insertImage($editable, data);
  2435. } else {
  2436. // array of files
  2437. insertImages($editable, data);
  2438. }
  2439. }).fail(function () {
  2440. editor.restoreRange($editable);
  2441. });
  2442. },
  2443. /**
  2444. * @param {Object} oLayoutInfo
  2445. */
  2446. showVideoDialog: function (oLayoutInfo) {
  2447. var $dialog = oLayoutInfo.dialog(),
  2448. $editable = oLayoutInfo.editable(),
  2449. videoInfo = editor.getVideoInfo($editable);
  2450. editor.saveRange($editable);
  2451. dialog.showVideoDialog($editable, $dialog, videoInfo).then(function (sUrl) {
  2452. editor.restoreRange($editable);
  2453. editor.insertVideo($editable, sUrl);
  2454. }).fail(function () {
  2455. editor.restoreRange($editable);
  2456. });
  2457. },
  2458. /**
  2459. * @param {Object} oLayoutInfo
  2460. */
  2461. showHelpDialog: function (oLayoutInfo) {
  2462. var $dialog = oLayoutInfo.dialog(),
  2463. $editable = oLayoutInfo.editable();
  2464. editor.saveRange($editable);
  2465. dialog.showHelpDialog($editable, $dialog).then(function () {
  2466. editor.restoreRange($editable);
  2467. });
  2468. },
  2469. fullscreen: function (oLayoutInfo) {
  2470. var $editor = oLayoutInfo.editor(),
  2471. $toolbar = oLayoutInfo.toolbar(),
  2472. $editable = oLayoutInfo.editable(),
  2473. $codable = oLayoutInfo.codable();
  2474. var options = $editor.data('options');
  2475. var resize = function (size) {
  2476. $editor.css('width', size.w);
  2477. $editable.css('height', size.h);
  2478. $codable.css('height', size.h);
  2479. if ($codable.data('cmeditor')) {
  2480. $codable.data('cmeditor').setsize(null, size.h);
  2481. }
  2482. };
  2483. $editor.toggleClass('fullscreen');
  2484. var isFullscreen = $editor.hasClass('fullscreen');
  2485. if (isFullscreen) {
  2486. $editable.data('orgheight', $editable.css('height'));
  2487. $window.on('resize', function () {
  2488. resize({
  2489. w: $window.width(),
  2490. h: $window.height() - $toolbar.outerHeight()
  2491. });
  2492. }).trigger('resize');
  2493. $scrollbar.css('overflow', 'hidden');
  2494. } else {
  2495. $window.off('resize');
  2496. resize({
  2497. w: options.width || '',
  2498. h: $editable.data('orgheight')
  2499. });
  2500. $scrollbar.css('overflow', 'visible');
  2501. }
  2502. toolbar.updateFullscreen($toolbar, isFullscreen);
  2503. },
  2504. codeview: function (oLayoutInfo) {
  2505. var $editor = oLayoutInfo.editor(),
  2506. $toolbar = oLayoutInfo.toolbar(),
  2507. $editable = oLayoutInfo.editable(),
  2508. $codable = oLayoutInfo.codable(),
  2509. $popover = oLayoutInfo.popover();
  2510. var options = $editor.data('options');
  2511. var cmEditor, server;
  2512. $editor.toggleClass('codeview');
  2513. var isCodeview = $editor.hasClass('codeview');
  2514. if (isCodeview) {
  2515. $codable.val($editable.html());
  2516. $codable.height($editable.height());
  2517. toolbar.deactivate($toolbar);
  2518. popover.hide($popover);
  2519. $codable.focus();
  2520. // activate CodeMirror as codable
  2521. if (agent.hasCodeMirror) {
  2522. cmEditor = CodeMirror.fromTextArea($codable[0], options.codemirror);
  2523. // CodeMirror TernServer
  2524. if (options.codemirror.tern) {
  2525. server = new CodeMirror.TernServer(options.codemirror.tern);
  2526. cmEditor.ternServer = server;
  2527. cmEditor.on('cursorActivity', function (cm) {
  2528. server.updateArgHints(cm);
  2529. });
  2530. }
  2531. // CodeMirror hasn't Padding.
  2532. cmEditor.setSize(null, $editable.outerHeight());
  2533. // autoFormatRange If formatting included
  2534. if (options.codemirror.autoFormatOnStart && cmEditor.autoFormatRange) {
  2535. cmEditor.autoFormatRange({line: 0, ch: 0}, {
  2536. line: cmEditor.lineCount(),
  2537. ch: cmEditor.getTextArea().value.length
  2538. });
  2539. }
  2540. $codable.data('cmEditor', cmEditor);
  2541. }
  2542. } else {
  2543. // deactivate CodeMirror as codable
  2544. if (agent.hasCodeMirror) {
  2545. cmEditor = $codable.data('cmEditor');
  2546. $codable.val(cmEditor.getValue());
  2547. cmEditor.toTextArea();
  2548. }
  2549. $editable.html($codable.val() || dom.emptyPara);
  2550. $editable.height(options.height ? $codable.height() : 'auto');
  2551. toolbar.activate($toolbar);
  2552. $editable.focus();
  2553. }
  2554. toolbar.updateCodeview(oLayoutInfo.toolbar(), isCodeview);
  2555. }
  2556. };
  2557. var hMousedown = function (event) {
  2558. //preventDefault Selection for FF, IE8+
  2559. if (dom.isImg(event.target)) {
  2560. event.preventDefault();
  2561. }
  2562. };
  2563. var hToolbarAndPopoverUpdate = function (event) {
  2564. // delay for range after mouseup
  2565. setTimeout(function () {
  2566. var oLayoutInfo = makeLayoutInfo(event.currentTarget || event.target);
  2567. var oStyle = editor.currentStyle(event.target);
  2568. if (!oStyle) { return; }
  2569. var isAirMode = oLayoutInfo.editor().data('options').airMode;
  2570. if (!isAirMode) {
  2571. toolbar.update(oLayoutInfo.toolbar(), oStyle);
  2572. }
  2573. popover.update(oLayoutInfo.popover(), oStyle, isAirMode);
  2574. handle.update(oLayoutInfo.handle(), oStyle, isAirMode);
  2575. }, 0);
  2576. };
  2577. var hScroll = function (event) {
  2578. var oLayoutInfo = makeLayoutInfo(event.currentTarget || event.target);
  2579. //hide popover and handle when scrolled
  2580. popover.hide(oLayoutInfo.popover());
  2581. handle.hide(oLayoutInfo.handle());
  2582. };
  2583. /**
  2584. * paste clipboard image
  2585. *
  2586. * @param {Event} event
  2587. */
  2588. var hPasteClipboardImage = function (event) {
  2589. var clipboardData = event.originalEvent.clipboardData;
  2590. if (!clipboardData || !clipboardData.items || !clipboardData.items.length) {
  2591. return;
  2592. }
  2593. var oLayoutInfo = makeLayoutInfo(event.currentTarget || event.target);
  2594. var item = list.head(clipboardData.items);
  2595. var isClipboardImage = item.kind === 'file' && item.type.indexOf('image/') !== -1;
  2596. if (isClipboardImage) {
  2597. insertImages(oLayoutInfo.editable(), [item.getAsFile()]);
  2598. }
  2599. };
  2600. /**
  2601. * `mousedown` event handler on $handle
  2602. * - controlSizing: resize image
  2603. *
  2604. * @param {MouseEvent} event
  2605. */
  2606. var hHandleMousedown = function (event) {
  2607. if (dom.isControlSizing(event.target)) {
  2608. event.preventDefault();
  2609. event.stopPropagation();
  2610. var oLayoutInfo = makeLayoutInfo(event.target),
  2611. $handle = oLayoutInfo.handle(), $popover = oLayoutInfo.popover(),
  2612. $editable = oLayoutInfo.editable(),
  2613. $editor = oLayoutInfo.editor();
  2614. var elTarget = $handle.find('.note-control-selection').data('target'),
  2615. $target = $(elTarget), posStart = $target.offset(),
  2616. scrollTop = $document.scrollTop();
  2617. var isAirMode = $editor.data('options').airMode;
  2618. $document.on('mousemove', function (event) {
  2619. editor.resizeTo({
  2620. x: event.clientX - posStart.left,
  2621. y: event.clientY - (posStart.top - scrollTop)
  2622. }, $target, !event.shiftKey);
  2623. handle.update($handle, {image: elTarget}, isAirMode);
  2624. popover.update($popover, {image: elTarget}, isAirMode);
  2625. }).one('mouseup', function () {
  2626. $document.off('mousemove');
  2627. });
  2628. if (!$target.data('ratio')) { // original ratio.
  2629. $target.data('ratio', $target.height() / $target.width());
  2630. }
  2631. editor.recordUndo($editable);
  2632. }
  2633. };
  2634. var hToolbarAndPopoverMousedown = function (event) {
  2635. // prevent default event when insertTable (FF, Webkit)
  2636. var $btn = $(event.target).closest('[data-event]');
  2637. if ($btn.length) {
  2638. event.preventDefault();
  2639. }
  2640. };
  2641. var hToolbarAndPopoverClick = function (event) {
  2642. var $btn = $(event.target).closest('[data-event]');
  2643. if ($btn.length) {
  2644. var sEvent = $btn.attr('data-event'),
  2645. sValue = $btn.attr('data-value');
  2646. var oLayoutInfo = makeLayoutInfo(event.target);
  2647. event.preventDefault();
  2648. // before command: detect control selection element($target)
  2649. var $target;
  2650. if ($.inArray(sEvent, ['resize', 'floatMe', 'removeMedia']) !== -1) {
  2651. var $selection = oLayoutInfo.handle().find('.note-control-selection');
  2652. $target = $($selection.data('target'));
  2653. }
  2654. if (editor[sEvent]) { // on command
  2655. var $editable = oLayoutInfo.editable();
  2656. $editable.trigger('focus');
  2657. editor[sEvent]($editable, sValue, $target);
  2658. } else if (commands[sEvent]) {
  2659. commands[sEvent].call(this, oLayoutInfo);
  2660. }
  2661. // after command
  2662. if ($.inArray(sEvent, ['backColor', 'foreColor']) !== -1) {
  2663. var options = oLayoutInfo.editor().data('options', options);
  2664. var module = options.airMode ? popover : toolbar;
  2665. module.updateRecentColor(list.head($btn), sEvent, sValue);
  2666. }
  2667. hToolbarAndPopoverUpdate(event);
  2668. }
  2669. };
  2670. var EDITABLE_PADDING = 24;
  2671. /**
  2672. * `mousedown` event handler on statusbar
  2673. *
  2674. * @param {MouseEvent} event
  2675. */
  2676. var hStatusbarMousedown = function (event) {
  2677. event.preventDefault();
  2678. event.stopPropagation();
  2679. var $editable = makeLayoutInfo(event.target).editable();
  2680. var nEditableTop = $editable.offset().top - $document.scrollTop();
  2681. var oLayoutInfo = makeLayoutInfo(event.currentTarget || event.target);
  2682. var options = oLayoutInfo.editor().data('options');
  2683. $document.on('mousemove', function (event) {
  2684. var nHeight = event.clientY - (nEditableTop + EDITABLE_PADDING);
  2685. nHeight = (options.minHeight > 0) ? Math.max(nHeight, options.minHeight) : nHeight;
  2686. nHeight = (options.maxHeight > 0) ? Math.min(nHeight, options.maxHeight) : nHeight;
  2687. $editable.height(nHeight);
  2688. }).one('mouseup', function () {
  2689. $document.off('mousemove');
  2690. });
  2691. };
  2692. var PX_PER_EM = 18;
  2693. var hDimensionPickerMove = function (event, options) {
  2694. var $picker = $(event.target.parentNode); // target is mousecatcher
  2695. var $dimensionDisplay = $picker.next();
  2696. var $catcher = $picker.find('.note-dimension-picker-mousecatcher');
  2697. var $highlighted = $picker.find('.note-dimension-picker-highlighted');
  2698. var $unhighlighted = $picker.find('.note-dimension-picker-unhighlighted');
  2699. var posOffset;
  2700. // HTML5 with jQuery - e.offsetX is undefined in Firefox
  2701. if (event.offsetX === undefined) {
  2702. var posCatcher = $(event.target).offset();
  2703. posOffset = {
  2704. x: event.pageX - posCatcher.left,
  2705. y: event.pageY - posCatcher.top
  2706. };
  2707. } else {
  2708. posOffset = {
  2709. x: event.offsetX,
  2710. y: event.offsetY
  2711. };
  2712. }
  2713. var dim = {
  2714. c: Math.ceil(posOffset.x / PX_PER_EM) || 1,
  2715. r: Math.ceil(posOffset.y / PX_PER_EM) || 1
  2716. };
  2717. $highlighted.css({ width: dim.c + 'em', height: dim.r + 'em' });
  2718. $catcher.attr('data-value', dim.c + 'x' + dim.r);
  2719. if (3 < dim.c && dim.c < options.insertTableMaxSize.col) {
  2720. $unhighlighted.css({ width: dim.c + 1 + 'em'});
  2721. }
  2722. if (3 < dim.r && dim.r < options.insertTableMaxSize.row) {
  2723. $unhighlighted.css({ height: dim.r + 1 + 'em'});
  2724. }
  2725. $dimensionDisplay.html(dim.c + ' x ' + dim.r);
  2726. };
  2727. /**
  2728. * attach Drag and Drop Events
  2729. *
  2730. * @param {Object} oLayoutInfo - layout Informations
  2731. */
  2732. var attachDragAndDropEvent = function (oLayoutInfo) {
  2733. var collection = $(), $dropzone = oLayoutInfo.dropzone,
  2734. $dropzoneMessage = oLayoutInfo.dropzone.find('.note-dropzone-message');
  2735. // show dropzone on dragenter when dragging a object to document.
  2736. $document.on('dragenter', function (e) {
  2737. var isCodeview = oLayoutInfo.editor.hasClass('codeview');
  2738. if (!isCodeview && !collection.length) {
  2739. oLayoutInfo.editor.addClass('dragover');
  2740. $dropzone.width(oLayoutInfo.editor.width());
  2741. $dropzone.height(oLayoutInfo.editor.height());
  2742. $dropzoneMessage.text('Drag Image Here');
  2743. }
  2744. collection = collection.add(e.target);
  2745. }).on('dragleave', function (e) {
  2746. collection = collection.not(e.target);
  2747. if (!collection.length) {
  2748. oLayoutInfo.editor.removeClass('dragover');
  2749. }
  2750. }).on('drop', function () {
  2751. collection = $();
  2752. oLayoutInfo.editor.removeClass('dragover');
  2753. });
  2754. // change dropzone's message on hover.
  2755. $dropzone.on('dragenter', function () {
  2756. $dropzone.addClass('hover');
  2757. $dropzoneMessage.text('Drop Image');
  2758. }).on('dragleave', function () {
  2759. $dropzone.removeClass('hover');
  2760. $dropzoneMessage.text('Drag Image Here');
  2761. });
  2762. // attach dropImage
  2763. $dropzone.on('drop', function (event) {
  2764. event.preventDefault();
  2765. var dataTransfer = event.originalEvent.dataTransfer;
  2766. if (dataTransfer && dataTransfer.files) {
  2767. var oLayoutInfo = makeLayoutInfo(event.currentTarget || event.target);
  2768. oLayoutInfo.editable().focus();
  2769. insertImages(oLayoutInfo.editable(), dataTransfer.files);
  2770. }
  2771. }).on('dragover', false); // prevent default dragover event
  2772. };
  2773. /**
  2774. * bind KeyMap on keydown
  2775. *
  2776. * @param {Object} oLayoutInfo
  2777. * @param {Object} keyMap
  2778. */
  2779. this.bindKeyMap = function (oLayoutInfo, keyMap) {
  2780. var $editor = oLayoutInfo.editor;
  2781. var $editable = oLayoutInfo.editable;
  2782. oLayoutInfo = makeLayoutInfo($editable);
  2783. $editable.on('keydown', function (event) {
  2784. var aKey = [];
  2785. // modifier
  2786. if (event.metaKey) { aKey.push('CMD'); }
  2787. if (event.ctrlKey && !event.altKey) { aKey.push('CTRL'); }
  2788. if (event.shiftKey) { aKey.push('SHIFT'); }
  2789. // keycode
  2790. var keyName = key.nameFromCode[event.keyCode];
  2791. if (keyName) { aKey.push(keyName); }
  2792. var sEvent = keyMap[aKey.join('+')];
  2793. if (sEvent) {
  2794. event.preventDefault();
  2795. if (editor[sEvent]) {
  2796. editor[sEvent]($editable, $editor.data('options'));
  2797. } else if (commands[sEvent]) {
  2798. commands[sEvent].call(this, oLayoutInfo);
  2799. }
  2800. } else if (key.isEdit(event.keyCode)) {
  2801. editor.recordUndo($editable);
  2802. }
  2803. });
  2804. };
  2805. /**
  2806. * attach eventhandler
  2807. *
  2808. * @param {Object} oLayoutInfo - layout Informations
  2809. * @param {Object} options - user options include custom event handlers
  2810. * @param {Function} options.enter - enter key handler
  2811. */
  2812. this.attach = function (oLayoutInfo, options) {
  2813. // handlers for editable
  2814. this.bindKeyMap(oLayoutInfo, options.keyMap[agent.isMac ? 'mac' : 'pc']);
  2815. oLayoutInfo.editable.on('mousedown', hMousedown);
  2816. oLayoutInfo.editable.on('keyup mouseup', hToolbarAndPopoverUpdate);
  2817. oLayoutInfo.editable.on('scroll', hScroll);
  2818. oLayoutInfo.editable.on('paste', hPasteClipboardImage);
  2819. // handler for handle and popover
  2820. oLayoutInfo.handle.on('mousedown', hHandleMousedown);
  2821. oLayoutInfo.popover.on('click', hToolbarAndPopoverClick);
  2822. oLayoutInfo.popover.on('mousedown', hToolbarAndPopoverMousedown);
  2823. // handlers for frame mode (toolbar, statusbar)
  2824. if (!options.airMode) {
  2825. // handler for drag and drop
  2826. if (!options.disableDragAndDrop) {
  2827. attachDragAndDropEvent(oLayoutInfo);
  2828. }
  2829. // handler for toolbar
  2830. oLayoutInfo.toolbar.on('click', hToolbarAndPopoverClick);
  2831. oLayoutInfo.toolbar.on('mousedown', hToolbarAndPopoverMousedown);
  2832. // handler for statusbar
  2833. if (!options.disableResizeEditor) {
  2834. oLayoutInfo.statusbar.on('mousedown', hStatusbarMousedown);
  2835. }
  2836. }
  2837. // handler for table dimension
  2838. var $catcherContainer = options.airMode ? oLayoutInfo.popover :
  2839. oLayoutInfo.toolbar;
  2840. var $catcher = $catcherContainer.find('.note-dimension-picker-mousecatcher');
  2841. $catcher.css({
  2842. width: options.insertTableMaxSize.col + 'em',
  2843. height: options.insertTableMaxSize.row + 'em'
  2844. }).on('mousemove', function (event) {
  2845. hDimensionPickerMove(event, options);
  2846. });
  2847. // save options on editor
  2848. oLayoutInfo.editor.data('options', options);
  2849. // ret styleWithCSS for backColor / foreColor clearing with 'inherit'.
  2850. if (options.styleWithSpan && !agent.isMSIE) {
  2851. // protect FF Error: NS_ERROR_FAILURE: Failure
  2852. setTimeout(function () {
  2853. document.execCommand('styleWithCSS', 0, true);
  2854. }, 0);
  2855. }
  2856. // History
  2857. oLayoutInfo.editable.data('NoteHistory', new History());
  2858. // basic event callbacks (lowercase)
  2859. // enter, focus, blur, keyup, keydown
  2860. if (options.onenter) {
  2861. oLayoutInfo.editable.keypress(function (event) {
  2862. if (event.keyCode === key.ENTER) { options.onenter(event); }
  2863. });
  2864. }
  2865. if (options.onfocus) { oLayoutInfo.editable.focus(options.onfocus); }
  2866. if (options.onblur) { oLayoutInfo.editable.blur(options.onblur); }
  2867. if (options.onkeyup) { oLayoutInfo.editable.keyup(options.onkeyup); }
  2868. if (options.onkeydown) { oLayoutInfo.editable.keydown(options.onkeydown); }
  2869. if (options.onpaste) { oLayoutInfo.editable.on('paste', options.onpaste); }
  2870. // callbacks for advanced features (camel)
  2871. if (options.onToolbarClick) { oLayoutInfo.toolbar.click(options.onToolbarClick); }
  2872. if (options.onChange) {
  2873. var hChange = function () {
  2874. options.onChange(oLayoutInfo.editable, oLayoutInfo.editable.html());
  2875. };
  2876. if (agent.isMSIE) {
  2877. var sDomEvents = 'DOMCharacterDataModified DOMSubtreeModified DOMNodeInserted';
  2878. oLayoutInfo.editable.on(sDomEvents, hChange);
  2879. } else {
  2880. oLayoutInfo.editable.on('input', hChange);
  2881. }
  2882. }
  2883. // All editor status will be saved on editable with jquery's data
  2884. // for support multiple editor with singleton object.
  2885. oLayoutInfo.editable.data('callbacks', {
  2886. onAutoSave: options.onAutoSave,
  2887. onImageUpload: options.onImageUpload,
  2888. onImageUploadError: options.onImageUploadError,
  2889. onFileUpload: options.onFileUpload,
  2890. onFileUploadError: options.onFileUpload
  2891. });
  2892. };
  2893. this.dettach = function (oLayoutInfo, options) {
  2894. oLayoutInfo.editable.off();
  2895. oLayoutInfo.popover.off();
  2896. oLayoutInfo.handle.off();
  2897. oLayoutInfo.dialog.off();
  2898. if (!options.airMode) {
  2899. oLayoutInfo.dropzone.off();
  2900. oLayoutInfo.toolbar.off();
  2901. oLayoutInfo.statusbar.off();
  2902. }
  2903. };
  2904. };
  2905. /**
  2906. * renderer
  2907. *
  2908. * rendering toolbar and editable
  2909. */
  2910. var Renderer = function () {
  2911. /**
  2912. * bootstrap button template
  2913. *
  2914. * @param {String} sLabel
  2915. * @param {Object} [options]
  2916. * @param {String} [options.event]
  2917. * @param {String} [options.value]
  2918. * @param {String} [options.title]
  2919. * @param {String} [options.dropdown]
  2920. */
  2921. var tplButton = function (sLabel, options) {
  2922. var event = options.event;
  2923. var value = options.value;
  2924. var title = options.title;
  2925. var className = options.className;
  2926. var dropdown = options.dropdown;
  2927. return '<button type="button"' +
  2928. ' class="btn btn-default btn-sm btn-small' +
  2929. (className ? ' ' + className : '') +
  2930. (dropdown ? ' dropdown-toggle' : '') +
  2931. '"' +
  2932. (dropdown ? ' data-toggle="dropdown"' : '') +
  2933. (title ? ' title="' + title + '"' : '') +
  2934. (event ? ' data-event="' + event + '"' : '') +
  2935. (value ? ' data-value=\'' + value + '\'' : '') +
  2936. ' tabindex="-1">' +
  2937. sLabel +
  2938. (dropdown ? ' <span class="caret"></span>' : '') +
  2939. '</button>' +
  2940. (dropdown || '');
  2941. };
  2942. /**
  2943. * bootstrap icon button template
  2944. *
  2945. * @param {String} sIconClass
  2946. * @param {Object} [options]
  2947. * @param {String} [options.event]
  2948. * @param {String} [options.value]
  2949. * @param {String} [options.title]
  2950. * @param {String} [options.dropdown]
  2951. */
  2952. var tplIconButton = function (sIconClass, options) {
  2953. var sLabel = '<i class="' + sIconClass + '"></i>';
  2954. return tplButton(sLabel, options);
  2955. };
  2956. /**
  2957. * bootstrap popover template
  2958. *
  2959. * @param {String} className
  2960. * @param {String} content
  2961. */
  2962. var tplPopover = function (className, content) {
  2963. return '<div class="' + className + ' popover bottom in" style="display: none;">' +
  2964. '<div class="arrow"></div>' +
  2965. '<div class="popover-content">' +
  2966. content +
  2967. '</div>' +
  2968. '</div>';
  2969. };
  2970. /**
  2971. * bootstrap dialog template
  2972. *
  2973. * @param {String} className
  2974. * @param {String} [title]
  2975. * @param {String} body
  2976. * @param {String} [footer]
  2977. */
  2978. var tplDialog = function (className, title, body, footer) {
  2979. return '<div class="' + className + ' modal" aria-hidden="false">' +
  2980. '<div class="modal-dialog">' +
  2981. '<div class="modal-content">' +
  2982. (title ?
  2983. '<div class="modal-header">' +
  2984. '<button type="button" class="close" aria-hidden="true" tabindex="-1">&times;</button>' +
  2985. '<h4 class="modal-title">' + title + '</h4>' +
  2986. '</div>' : ''
  2987. ) +
  2988. '<form class="note-modal-form">' +
  2989. '<div class="modal-body">' +
  2990. '<div class="row-fluid">' + body + '</div>' +
  2991. '</div>' +
  2992. (footer ?
  2993. '<div class="modal-footer">' + footer + '</div>' : ''
  2994. ) +
  2995. '</form>' +
  2996. '</div>' +
  2997. '</div>' +
  2998. '</div>';
  2999. };
  3000. var tplButtonInfo = {
  3001. picture: function (lang) {
  3002. return tplIconButton('glyph-icon icon-picture-o icon-picture', {
  3003. event: 'showImageDialog',
  3004. title: lang.image.image
  3005. });
  3006. },
  3007. link: function (lang) {
  3008. return tplIconButton('glyph-icon icon-link icon-link', {
  3009. event: 'showLinkDialog',
  3010. title: lang.link.link
  3011. });
  3012. },
  3013. video: function (lang) {
  3014. return tplIconButton('glyph-icon icon-youtube-play icon-play', {
  3015. event: 'showVideoDialog',
  3016. title: lang.video.video
  3017. });
  3018. },
  3019. table: function (lang) {
  3020. var dropdown = '<ul class="dropdown-menu">' +
  3021. '<div class="note-dimension-picker">' +
  3022. '<div class="note-dimension-picker-mousecatcher" data-event="insertTable" data-value="1x1"></div>' +
  3023. '<div class="note-dimension-picker-highlighted"></div>' +
  3024. '<div class="note-dimension-picker-unhighlighted"></div>' +
  3025. '</div>' +
  3026. '<div class="note-dimension-display"> 1 x 1 </div>' +
  3027. '</ul>';
  3028. return tplIconButton('glyph-icon icon-table icon-table', {
  3029. title: lang.table.table,
  3030. dropdown: dropdown
  3031. });
  3032. },
  3033. style: function (lang, options) {
  3034. var items = options.styleTags.reduce(function (memo, v) {
  3035. var label = lang.style[v === 'p' ? 'normal' : v];
  3036. return memo + '<li><a data-event="formatBlock" href="#" data-value="' + v + '">' +
  3037. (
  3038. (v === 'p' || v === 'pre') ? label :
  3039. '<' + v + '>' + label + '</' + v + '>'
  3040. ) +
  3041. '</a></li>';
  3042. }, '');
  3043. return tplIconButton('glyph-icon icon-magic icon-magic', {
  3044. title: lang.style.style,
  3045. dropdown: '<ul class="dropdown-menu">' + items + '</ul>'
  3046. });
  3047. },
  3048. fontname: function (lang, options) {
  3049. var items = options.fontNames.reduce(function (memo, v) {
  3050. if (!agent.isFontInstalled(v)) { return memo; }
  3051. return memo + '<li><a data-event="fontName" href="#" data-value="' + v + '">' +
  3052. '<i class="glyph-icon icon-check icon-ok"></i> ' + v +
  3053. '</a></li>';
  3054. }, '');
  3055. var sLabel = '<span class="note-current-fontname">' +
  3056. options.defaultFontName +
  3057. '</span>';
  3058. return tplButton(sLabel, {
  3059. title: lang.font.name,
  3060. dropdown: '<ul class="dropdown-menu">' + items + '</ul>'
  3061. });
  3062. },
  3063. fontsize: function (lang, options) {
  3064. var items = options.fontSizes.reduce(function (memo, v) {
  3065. return memo + '<li><a data-event="fontSize" href="#" data-value="' + v + '">' +
  3066. '<i class="glyph-icon icon-check icon-ok"></i> ' + v +
  3067. '</a></li>';
  3068. }, '');
  3069. var sLabel = '<span class="note-current-fontsize">11</span>';
  3070. return tplButton(sLabel, {
  3071. title: lang.font.size,
  3072. dropdown: '<ul class="dropdown-menu">' + items + '</ul>'
  3073. });
  3074. },
  3075. color: function (lang) {
  3076. var colorButtonLabel = '<i class="glyph-icon icon-font icon-font" style="color:black;background-color:yellow;"></i>';
  3077. var colorButton = tplButton(colorButtonLabel, {
  3078. className: 'note-recent-color',
  3079. title: lang.color.recent,
  3080. event: 'color',
  3081. value: '{"backColor":"yellow"}'
  3082. });
  3083. var dropdown = '<ul class="dropdown-menu">' +
  3084. '<li>' +
  3085. '<div class="btn-group">' +
  3086. '<div class="note-palette-title">' + lang.color.background + '</div>' +
  3087. '<div class="note-color-reset" data-event="backColor"' +
  3088. ' data-value="inherit" title="' + lang.color.transparent + '">' +
  3089. lang.color.setTransparent +
  3090. '</div>' +
  3091. '<div class="note-color-palette" data-target-event="backColor"></div>' +
  3092. '</div>' +
  3093. '<div class="btn-group">' +
  3094. '<div class="note-palette-title">' + lang.color.foreground + '</div>' +
  3095. '<div class="note-color-reset" data-event="foreColor" data-value="inherit" title="' + lang.color.reset + '">' +
  3096. lang.color.resetToDefault +
  3097. '</div>' +
  3098. '<div class="note-color-palette" data-target-event="foreColor"></div>' +
  3099. '</div>' +
  3100. '</li>' +
  3101. '</ul>';
  3102. var moreButton = tplButton('', {
  3103. title: lang.color.more,
  3104. dropdown: dropdown
  3105. });
  3106. return colorButton + moreButton;
  3107. },
  3108. bold: function (lang) {
  3109. return tplIconButton('glyph-icon icon-bold icon-bold', {
  3110. event: 'bold',
  3111. title: lang.font.bold
  3112. });
  3113. },
  3114. italic: function (lang) {
  3115. return tplIconButton('glyph-icon icon-italic icon-italic', {
  3116. event: 'italic',
  3117. title: lang.font.italic
  3118. });
  3119. },
  3120. underline: function (lang) {
  3121. return tplIconButton('glyph-icon icon-underline icon-underline', {
  3122. event: 'underline',
  3123. title: lang.font.underline
  3124. });
  3125. },
  3126. strikethrough: function (lang) {
  3127. return tplIconButton('glyph-icon icon-strikethrough icon-strikethrough', {
  3128. event: 'strikethrough',
  3129. title: lang.font.strikethrough
  3130. });
  3131. },
  3132. superscript: function (lang) {
  3133. return tplIconButton('glyph-icon icon-superscript icon-superscript', {
  3134. event: 'superscript',
  3135. title: lang.font.superscript
  3136. });
  3137. },
  3138. subscript: function (lang) {
  3139. return tplIconButton('glyph-icon icon-subscript icon-subscript', {
  3140. event: 'subscript',
  3141. title: lang.font.subscript
  3142. });
  3143. },
  3144. clear: function (lang) {
  3145. return tplIconButton('glyph-icon icon-eraser icon-eraser', {
  3146. event: 'removeFormat',
  3147. title: lang.font.clear
  3148. });
  3149. },
  3150. ul: function (lang) {
  3151. return tplIconButton('glyph-icon icon-list-ul icon-list-ul', {
  3152. event: 'insertUnorderedList',
  3153. title: lang.lists.unordered
  3154. });
  3155. },
  3156. ol: function (lang) {
  3157. return tplIconButton('glyph-icon icon-list-ol icon-list-ol', {
  3158. event: 'insertOrderedList',
  3159. title: lang.lists.ordered
  3160. });
  3161. },
  3162. paragraph: function (lang) {
  3163. var leftButton = tplIconButton('glyph-icon icon-align-left icon-align-left', {
  3164. title: lang.paragraph.left,
  3165. event: 'justifyLeft'
  3166. });
  3167. var centerButton = tplIconButton('glyph-icon icon-align-center icon-align-center', {
  3168. title: lang.paragraph.center,
  3169. event: 'justifyCenter'
  3170. });
  3171. var rightButton = tplIconButton('glyph-icon icon-align-right icon-align-right', {
  3172. title: lang.paragraph.right,
  3173. event: 'justifyRight'
  3174. });
  3175. var justifyButton = tplIconButton('glyph-icon icon-align-justify icon-align-justify', {
  3176. title: lang.paragraph.justify,
  3177. event: 'justifyFull'
  3178. });
  3179. var outdentButton = tplIconButton('glyph-icon icon-outdent icon-indent-left', {
  3180. title: lang.paragraph.outdent,
  3181. event: 'outdent'
  3182. });
  3183. var indentButton = tplIconButton('glyph-icon icon-indent icon-indent-right', {
  3184. title: lang.paragraph.indent,
  3185. event: 'indent'
  3186. });
  3187. var dropdown = '<div class="dropdown-menu">' +
  3188. '<div class="note-align btn-group">' +
  3189. leftButton + centerButton + rightButton + justifyButton +
  3190. '</div>' +
  3191. '<div class="note-list btn-group">' +
  3192. indentButton + outdentButton +
  3193. '</div>' +
  3194. '</div>';
  3195. return tplIconButton('glyph-icon icon-align-left icon-align-left', {
  3196. title: lang.paragraph.paragraph,
  3197. dropdown: dropdown
  3198. });
  3199. },
  3200. height: function (lang, options) {
  3201. var items = options.lineHeights.reduce(function (memo, v) {
  3202. return memo + '<li><a data-event="lineHeight" href="#" data-value="' + parseFloat(v) + '">' +
  3203. '<i class="glyph-icon icon-check icon-ok"></i> ' + v +
  3204. '</a></li>';
  3205. }, '');
  3206. return tplIconButton('glyph-icon icon-text-height icon-text-height', {
  3207. title: lang.font.height,
  3208. dropdown: '<ul class="dropdown-menu">' + items + '</ul>'
  3209. });
  3210. },
  3211. help: function (lang) {
  3212. return tplIconButton('glyph-icon icon-question icon-question', {
  3213. event: 'showHelpDialog',
  3214. title: lang.options.help
  3215. });
  3216. },
  3217. fullscreen: function (lang) {
  3218. return tplIconButton('glyph-icon icon-arrows-alt icon-fullscreen', {
  3219. event: 'fullscreen',
  3220. title: lang.options.fullscreen
  3221. });
  3222. },
  3223. codeview: function (lang) {
  3224. return tplIconButton('glyph-icon icon-code icon-code', {
  3225. event: 'codeview',
  3226. title: lang.options.codeview
  3227. });
  3228. },
  3229. undo: function (lang) {
  3230. return tplIconButton('glyph-icon icon-undo icon-undo', {
  3231. event: 'undo',
  3232. title: lang.history.undo
  3233. });
  3234. },
  3235. redo: function (lang) {
  3236. return tplIconButton('glyph-icon icon-repeat icon-repeat', {
  3237. event: 'redo',
  3238. title: lang.history.redo
  3239. });
  3240. },
  3241. hr: function (lang) {
  3242. return tplIconButton('glyph-icon icon-minus icon-hr', {
  3243. event: 'insertHorizontalRule',
  3244. title: lang.hr.insert
  3245. });
  3246. }
  3247. };
  3248. var tplPopovers = function (lang, options) {
  3249. var tplLinkPopover = function () {
  3250. var linkButton = tplIconButton('glyph-icon icon-edit icon-edit', {
  3251. title: lang.link.edit,
  3252. event: 'showLinkDialog'
  3253. });
  3254. var unlinkButton = tplIconButton('glyph-icon icon-unlink icon-unlink', {
  3255. title: lang.link.unlink,
  3256. event: 'unlink'
  3257. });
  3258. var content = '<a href="http://www.google.com" target="_blank">www.google.com</a>&nbsp;&nbsp;' +
  3259. '<div class="note-insert btn-group">' +
  3260. linkButton + unlinkButton +
  3261. '</div>';
  3262. return tplPopover('note-link-popover', content);
  3263. };
  3264. var tplImagePopover = function () {
  3265. var fullButton = tplButton('<span class="note-fontsize-10">100%</span>', {
  3266. title: lang.image.resizeFull,
  3267. event: 'resize',
  3268. value: '1'
  3269. });
  3270. var halfButton = tplButton('<span class="note-fontsize-10">50%</span>', {
  3271. title: lang.image.resizeHalf,
  3272. event: 'resize',
  3273. value: '0.5'
  3274. });
  3275. var quarterButton = tplButton('<span class="note-fontsize-10">25%</span>', {
  3276. title: lang.image.resizeQuarter,
  3277. event: 'resize',
  3278. value: '0.25'
  3279. });
  3280. var leftButton = tplIconButton('glyph-icon icon-align-left icon-align-left', {
  3281. title: lang.image.floatLeft,
  3282. event: 'floatMe',
  3283. value: 'left'
  3284. });
  3285. var rightButton = tplIconButton('glyph-icon icon-align-right icon-align-right', {
  3286. title: lang.image.floatRight,
  3287. event: 'floatMe',
  3288. value: 'right'
  3289. });
  3290. var justifyButton = tplIconButton('glyph-icon icon-align-justify icon-align-justify', {
  3291. title: lang.image.floatNone,
  3292. event: 'floatMe',
  3293. value: 'none'
  3294. });
  3295. var removeButton = tplIconButton('glyph-icon icon-trash-o icon-trash', {
  3296. title: lang.image.remove,
  3297. event: 'removeMedia',
  3298. value: 'none'
  3299. });
  3300. var content = '<div class="btn-group">' + fullButton + halfButton + quarterButton + '</div>' +
  3301. '<div class="btn-group">' + leftButton + rightButton + justifyButton + '</div>' +
  3302. '<div class="btn-group">' + removeButton + '</div>';
  3303. return tplPopover('note-image-popover', content);
  3304. };
  3305. var tplAirPopover = function () {
  3306. var content = '';
  3307. for (var idx = 0, sz = options.airPopover.length; idx < sz; idx ++) {
  3308. var group = options.airPopover[idx];
  3309. content += '<div class="note-' + group[0] + ' btn-group">';
  3310. for (var i = 0, szGroup = group[1].length; i < szGroup; i++) {
  3311. content += tplButtonInfo[group[1][i]](lang, options);
  3312. }
  3313. content += '</div>';
  3314. }
  3315. return tplPopover('note-air-popover', content);
  3316. };
  3317. return '<div class="note-popover">' +
  3318. tplLinkPopover() +
  3319. tplImagePopover() +
  3320. (options.airMode ? tplAirPopover() : '') +
  3321. '</div>';
  3322. };
  3323. var tplHandles = function () {
  3324. return '<div class="note-handle">' +
  3325. '<div class="note-control-selection">' +
  3326. '<div class="note-control-selection-bg"></div>' +
  3327. '<div class="note-control-holder note-control-nw"></div>' +
  3328. '<div class="note-control-holder note-control-ne"></div>' +
  3329. '<div class="note-control-holder note-control-sw"></div>' +
  3330. '<div class="note-control-sizing note-control-se"></div>' +
  3331. '<div class="note-control-selection-info"></div>' +
  3332. '</div>' +
  3333. '</div>';
  3334. };
  3335. /**
  3336. * shortcut table template
  3337. * @param {String} title
  3338. * @param {String} body
  3339. */
  3340. var tplShortcut = function (title, body) {
  3341. return '<table class="note-shortcut">' +
  3342. '<thead>' +
  3343. '<tr><th></th><th>' + title + '</th></tr>' +
  3344. '</thead>' +
  3345. '<tbody>' + body + '</tbody>' +
  3346. '</table>';
  3347. };
  3348. var tplShortcutText = function (lang) {
  3349. var body = '<tr><td>⌘ + B</td><td>' + lang.font.bold + '</td></tr>' +
  3350. '<tr><td>⌘ + I</td><td>' + lang.font.italic + '</td></tr>' +
  3351. '<tr><td>⌘ + U</td><td>' + lang.font.underline + '</td></tr>' +
  3352. '<tr><td>⌘ + ⇧ + S</td><td>' + lang.font.strikethrough + '</td></tr>' +
  3353. '<tr><td>⌘ + \\</td><td>' + lang.font.clear + '</td></tr>';
  3354. return tplShortcut(lang.shortcut.textFormatting, body);
  3355. };
  3356. var tplShortcutAction = function (lang) {
  3357. var body = '<tr><td>⌘ + Z</td><td>' + lang.history.undo + '</td></tr>' +
  3358. '<tr><td>⌘ + ⇧ + Z</td><td>' + lang.history.redo + '</td></tr>' +
  3359. '<tr><td>⌘ + ]</td><td>' + lang.paragraph.indent + '</td></tr>' +
  3360. '<tr><td>⌘ + [</td><td>' + lang.paragraph.outdent + '</td></tr>' +
  3361. '<tr><td>⌘ + ENTER</td><td>' + lang.hr.insert + '</td></tr>';
  3362. return tplShortcut(lang.shortcut.action, body);
  3363. };
  3364. var tplShortcutPara = function (lang) {
  3365. var body = '<tr><td>⌘ + ⇧ + L</td><td>' + lang.paragraph.left + '</td></tr>' +
  3366. '<tr><td>⌘ + ⇧ + E</td><td>' + lang.paragraph.center + '</td></tr>' +
  3367. '<tr><td>⌘ + ⇧ + R</td><td>' + lang.paragraph.right + '</td></tr>' +
  3368. '<tr><td>⌘ + ⇧ + J</td><td>' + lang.paragraph.justify + '</td></tr>' +
  3369. '<tr><td>⌘ + ⇧ + NUM7</td><td>' + lang.lists.ordered + '</td></tr>' +
  3370. '<tr><td>⌘ + ⇧ + NUM8</td><td>' + lang.lists.unordered + '</td></tr>';
  3371. return tplShortcut(lang.shortcut.paragraphFormatting, body);
  3372. };
  3373. var tplShortcutStyle = function (lang) {
  3374. var body = '<tr><td>⌘ + NUM0</td><td>' + lang.style.normal + '</td></tr>' +
  3375. '<tr><td>⌘ + NUM1</td><td>' + lang.style.h1 + '</td></tr>' +
  3376. '<tr><td>⌘ + NUM2</td><td>' + lang.style.h2 + '</td></tr>' +
  3377. '<tr><td>⌘ + NUM3</td><td>' + lang.style.h3 + '</td></tr>' +
  3378. '<tr><td>⌘ + NUM4</td><td>' + lang.style.h4 + '</td></tr>' +
  3379. '<tr><td>⌘ + NUM5</td><td>' + lang.style.h5 + '</td></tr>' +
  3380. '<tr><td>⌘ + NUM6</td><td>' + lang.style.h6 + '</td></tr>';
  3381. return tplShortcut(lang.shortcut.documentStyle, body);
  3382. };
  3383. var tplExtraShortcuts = function (lang, options) {
  3384. var extraKeys = options.extraKeys;
  3385. var body = '';
  3386. for (var key in extraKeys) {
  3387. if (extraKeys.hasOwnProperty(key)) {
  3388. body += '<tr><td>' + key + '</td><td>' + extraKeys[key] + '</td></tr>';
  3389. }
  3390. }
  3391. return tplShortcut(lang.shortcut.extraKeys, body);
  3392. };
  3393. var tplShortcutTable = function (lang, options) {
  3394. var template = '<table class="note-shortcut-layout">' +
  3395. '<tbody>' +
  3396. '<tr><td>' + tplShortcutAction(lang, options) + '</td><td>' + tplShortcutText(lang, options) + '</td></tr>' +
  3397. '<tr><td>' + tplShortcutStyle(lang, options) + '</td><td>' + tplShortcutPara(lang, options) + '</td></tr>';
  3398. if (options.extraKeys) {
  3399. template += '<tr><td colspan="2">' + tplExtraShortcuts(lang, options) + '</td></tr>';
  3400. }
  3401. template += '</tbody</table>';
  3402. return template;
  3403. };
  3404. var replaceMacKeys = function (sHtml) {
  3405. return sHtml.replace(/⌘/g, 'Ctrl').replace(/⇧/g, 'Shift');
  3406. };
  3407. var tplDialogs = function (lang, options) {
  3408. var tplImageDialog = function () {
  3409. var body = '<h5>' + lang.image.selectFromFiles + '</h5>' +
  3410. '<input class="note-image-input" type="file" name="files" accept="image/*" />' +
  3411. '<h5>' + lang.image.url + '</h5>' +
  3412. '<input class="note-image-url form-control span12" type="text" />';
  3413. var footer = '<button href="#" class="btn btn-primary note-image-btn disabled" disabled>' + lang.image.insert + '</button>';
  3414. return tplDialog('note-image-dialog', lang.image.insert, body, footer);
  3415. };
  3416. var tplLinkDialog = function () {
  3417. var body = '<div class="form-group">' +
  3418. '<label>' + lang.link.textToDisplay + '</label>' +
  3419. '<input class="note-link-text form-control span12" type="text" />' +
  3420. '</div>' +
  3421. '<div class="form-group">' +
  3422. '<label>' + lang.link.url + '</label>' +
  3423. '<input class="note-link-url form-control span12" type="text" />' +
  3424. '</div>' +
  3425. (!options.disableLinkTarget ?
  3426. '<div class="checkbox">' +
  3427. '<label>' + '<input type="checkbox" checked> ' +
  3428. lang.link.openInNewWindow +
  3429. '</label>' +
  3430. '</div>' : ''
  3431. );
  3432. var footer = '<button href="#" class="btn btn-primary note-link-btn disabled" disabled>' + lang.link.insert + '</button>';
  3433. return tplDialog('note-link-dialog', lang.link.insert, body, footer);
  3434. };
  3435. var tplVideoDialog = function () {
  3436. var body = '<div class="form-group">' +
  3437. '<label>' + lang.video.url + '</label>&nbsp;<small class="text-muted">' + lang.video.providers + '</small>' +
  3438. '<input class="note-video-url form-control span12" type="text" />' +
  3439. '</div>';
  3440. var footer = '<button href="#" class="btn btn-primary note-video-btn disabled" disabled>' + lang.video.insert + '</button>';
  3441. return tplDialog('note-video-dialog', lang.video.insert, body, footer);
  3442. };
  3443. var tplHelpDialog = function () {
  3444. var body = '<a class="modal-close pull-right" aria-hidden="true" tabindex="-1">' + lang.shortcut.close + '</a>' +
  3445. '<div class="title">' + lang.shortcut.shortcuts + '</div>' +
  3446. (agent.isMac ? tplShortcutTable(lang, options) : replaceMacKeys(tplShortcutTable(lang, options))) +
  3447. '<p class="text-center">' +
  3448. '<a href="//hackerwins.github.io/summernote/" target="_blank">Summernote 0.5.3</a> · ' +
  3449. '<a href="//github.com/HackerWins/summernote" target="_blank">Project</a> · ' +
  3450. '<a href="//github.com/HackerWins/summernote/issues" target="_blank">Issues</a>' +
  3451. '</p>';
  3452. return tplDialog('note-help-dialog', '', body, '');
  3453. };
  3454. return '<div class="note-dialog">' +
  3455. tplImageDialog() +
  3456. tplLinkDialog() +
  3457. tplVideoDialog() +
  3458. tplHelpDialog() +
  3459. '</div>';
  3460. };
  3461. var tplStatusbar = function () {
  3462. return '<div class="note-resizebar">' +
  3463. '<div class="note-icon-bar"></div>' +
  3464. '<div class="note-icon-bar"></div>' +
  3465. '<div class="note-icon-bar"></div>' +
  3466. '</div>';
  3467. };
  3468. var representShortcut = function (str) {
  3469. if (agent.isMac) {
  3470. str = str.replace('CMD', '⌘').replace('SHIFT', '⇧');
  3471. }
  3472. return str.replace('BACKSLASH', '\\')
  3473. .replace('SLASH', '/')
  3474. .replace('LEFTBRACKET', '[')
  3475. .replace('RIGHTBRACKET', ']');
  3476. };
  3477. /**
  3478. * createTooltip
  3479. *
  3480. * @param {jQuery} $container
  3481. * @param {Object} keyMap
  3482. * @param {String} [sPlacement]
  3483. */
  3484. var createTooltip = function ($container, keyMap, sPlacement) {
  3485. var invertedKeyMap = func.invertObject(keyMap);
  3486. var $buttons = $container.find('button');
  3487. $buttons.each(function (i, elBtn) {
  3488. var $btn = $(elBtn);
  3489. var sShortcut = invertedKeyMap[$btn.data('event')];
  3490. if (sShortcut) {
  3491. $btn.attr('title', function (i, v) {
  3492. return v + ' (' + representShortcut(sShortcut) + ')';
  3493. });
  3494. }
  3495. // bootstrap tooltip on btn-group bug
  3496. // https://github.com/twbs/bootstrap/issues/5687
  3497. }).tooltip({
  3498. container: 'body',
  3499. trigger: 'hover',
  3500. placement: sPlacement || 'top'
  3501. }).on('click', function () {
  3502. $(this).tooltip('hide');
  3503. });
  3504. };
  3505. // createPalette
  3506. var createPalette = function ($container, options) {
  3507. var aaColor = options.colors;
  3508. $container.find('.note-color-palette').each(function () {
  3509. var $palette = $(this), sEvent = $palette.attr('data-target-event');
  3510. var aPaletteContents = [];
  3511. for (var row = 0, szRow = aaColor.length; row < szRow; row++) {
  3512. var aColor = aaColor[row];
  3513. var aButton = [];
  3514. for (var col = 0, szCol = aColor.length; col < szCol; col++) {
  3515. var sColor = aColor[col];
  3516. aButton.push(['<button type="button" class="note-color-btn" style="background-color:', sColor,
  3517. ';" data-event="', sEvent,
  3518. '" data-value="', sColor,
  3519. '" title="', sColor,
  3520. '" data-toggle="button" tabindex="-1"></button>'].join(''));
  3521. }
  3522. aPaletteContents.push('<div class="note-color-row">' + aButton.join('') + '</div>');
  3523. }
  3524. $palette.html(aPaletteContents.join(''));
  3525. });
  3526. };
  3527. /**
  3528. * create summernote layout (air mode)
  3529. *
  3530. * @param {jQuery} $holder
  3531. * @param {Object} options
  3532. */
  3533. this.createLayoutByAirMode = function ($holder, options) {
  3534. var keyMap = options.keyMap[agent.isMac ? 'mac' : 'pc'];
  3535. var langInfo = $.summernote.lang[options.lang];
  3536. var id = func.uniqueId();
  3537. $holder.addClass('note-air-editor note-editable');
  3538. $holder.attr({
  3539. 'id': 'note-editor-' + id,
  3540. 'contentEditable': true
  3541. });
  3542. var body = document.body;
  3543. // create Popover
  3544. var $popover = $(tplPopovers(langInfo, options));
  3545. $popover.addClass('note-air-layout');
  3546. $popover.attr('id', 'note-popover-' + id);
  3547. $popover.appendTo(body);
  3548. createTooltip($popover, keyMap);
  3549. createPalette($popover, options);
  3550. // create Handle
  3551. var $handle = $(tplHandles());
  3552. $handle.addClass('note-air-layout');
  3553. $handle.attr('id', 'note-handle-' + id);
  3554. $handle.appendTo(body);
  3555. // create Dialog
  3556. var $dialog = $(tplDialogs(langInfo, options));
  3557. $dialog.addClass('note-air-layout');
  3558. $dialog.attr('id', 'note-dialog-' + id);
  3559. $dialog.find('button.close, a.modal-close').click(function () {
  3560. $(this).closest('.modal').modal('hide');
  3561. });
  3562. $dialog.appendTo(body);
  3563. };
  3564. /**
  3565. * create summernote layout (normal mode)
  3566. *
  3567. * @param {jQuery} $holder
  3568. * @param {Object} options
  3569. */
  3570. this.createLayoutByFrame = function ($holder, options) {
  3571. //01. create Editor
  3572. var $editor = $('<div class="note-editor"></div>');
  3573. if (options.width) {
  3574. $editor.width(options.width);
  3575. }
  3576. //02. statusbar (resizebar)
  3577. if (options.height > 0) {
  3578. $('<div class="note-statusbar">' + (options.disableResizeEditor ? '' : tplStatusbar()) + '</div>').prependTo($editor);
  3579. }
  3580. //03. create Editable
  3581. var isContentEditable = !$holder.is(':disabled');
  3582. var $editable = $('<div class="note-editable" contentEditable="' + isContentEditable + '"></div>')
  3583. .prependTo($editor);
  3584. if (options.height) {
  3585. $editable.height(options.height);
  3586. }
  3587. if (options.direction) {
  3588. $editable.attr('dir', options.direction);
  3589. }
  3590. $editable.html(dom.html($holder) || dom.emptyPara);
  3591. //031. create codable
  3592. $('<textarea class="note-codable"></textarea>').prependTo($editor);
  3593. var langInfo = $.summernote.lang[options.lang];
  3594. //04. create Toolbar
  3595. var sToolbar = '';
  3596. for (var idx = 0, sz = options.toolbar.length; idx < sz; idx ++) {
  3597. var groupName = options.toolbar[idx][0];
  3598. var groupButtons = options.toolbar[idx][1];
  3599. sToolbar += '<div class="note-' + groupName + ' btn-group">';
  3600. for (var i = 0, btnLength = groupButtons.length; i < btnLength; i++) {
  3601. // continue When a toolbar button does'nt exist
  3602. if (!$.isFunction(tplButtonInfo[groupButtons[i]])) { continue; }
  3603. sToolbar += tplButtonInfo[groupButtons[i]](langInfo, options);
  3604. }
  3605. sToolbar += '</div>';
  3606. }
  3607. sToolbar = '<div class="note-toolbar btn-toolbar">' + sToolbar + '</div>';
  3608. var $toolbar = $(sToolbar).prependTo($editor);
  3609. var keyMap = options.keyMap[agent.isMac ? 'mac' : 'pc'];
  3610. createPalette($toolbar, options);
  3611. createTooltip($toolbar, keyMap, 'bottom');
  3612. //05. create Popover
  3613. var $popover = $(tplPopovers(langInfo, options)).prependTo($editor);
  3614. createPalette($popover, options);
  3615. createTooltip($popover, keyMap);
  3616. //06. handle(control selection, ...)
  3617. $(tplHandles()).prependTo($editor);
  3618. //07. create Dialog
  3619. var $dialog = $(tplDialogs(langInfo, options)).prependTo($editor);
  3620. $dialog.find('button.close, a.modal-close').click(function () {
  3621. $(this).closest('.modal').modal('hide');
  3622. });
  3623. //08. create Dropzone
  3624. $('<div class="note-dropzone"><div class="note-dropzone-message"></div></div>').prependTo($editor);
  3625. //09. Editor/Holder switch
  3626. $editor.insertAfter($holder);
  3627. $holder.hide();
  3628. };
  3629. this.noteEditorFromHolder = function ($holder) {
  3630. if ($holder.hasClass('note-air-editor')) {
  3631. return $holder;
  3632. } else if ($holder.next().hasClass('note-editor')) {
  3633. return $holder.next();
  3634. } else {
  3635. return $();
  3636. }
  3637. };
  3638. /**
  3639. * create summernote layout
  3640. *
  3641. * @param {jQuery} $holder
  3642. * @param {Object} options
  3643. */
  3644. this.createLayout = function ($holder, options) {
  3645. if (this.noteEditorFromHolder($holder).length) {
  3646. return;
  3647. }
  3648. if (options.airMode) {
  3649. this.createLayoutByAirMode($holder, options);
  3650. } else {
  3651. this.createLayoutByFrame($holder, options);
  3652. }
  3653. };
  3654. /**
  3655. * returns layoutInfo from holder
  3656. *
  3657. * @param {jQuery} $holder - placeholder
  3658. * @returns {Object}
  3659. */
  3660. this.layoutInfoFromHolder = function ($holder) {
  3661. var $editor = this.noteEditorFromHolder($holder);
  3662. if (!$editor.length) { return; }
  3663. var layoutInfo = dom.buildLayoutInfo($editor);
  3664. // cache all properties.
  3665. for (var key in layoutInfo) {
  3666. if (layoutInfo.hasOwnProperty(key)) {
  3667. layoutInfo[key] = layoutInfo[key].call();
  3668. }
  3669. }
  3670. return layoutInfo;
  3671. };
  3672. /**
  3673. * removeLayout
  3674. *
  3675. * @param {jQuery} $holder - placeholder
  3676. * @param {Object} oLayoutInfo
  3677. * @param {Object} options
  3678. *
  3679. */
  3680. this.removeLayout = function ($holder, oLayoutInfo, options) {
  3681. if (options.airMode) {
  3682. $holder.removeClass('note-air-editor note-editable')
  3683. .removeAttr('id contentEditable');
  3684. oLayoutInfo.popover.remove();
  3685. oLayoutInfo.handle.remove();
  3686. oLayoutInfo.dialog.remove();
  3687. } else {
  3688. $holder.html(oLayoutInfo.editable.html());
  3689. oLayoutInfo.editor.remove();
  3690. $holder.show();
  3691. }
  3692. };
  3693. };
  3694. // jQuery namespace for summernote
  3695. $.summernote = $.summernote || {};
  3696. // extends default `settings`
  3697. $.extend($.summernote, settings);
  3698. var renderer = new Renderer();
  3699. var eventHandler = new EventHandler();
  3700. /**
  3701. * extend jquery fn
  3702. */
  3703. $.fn.extend({
  3704. /**
  3705. * initialize summernote
  3706. * - create editor layout and attach Mouse and keyboard events.
  3707. *
  3708. * @param {Object} options
  3709. * @returns {this}
  3710. */
  3711. summernote: function (options) {
  3712. // extend default options
  3713. options = $.extend({}, $.summernote.options, options);
  3714. this.each(function (idx, elHolder) {
  3715. var $holder = $(elHolder);
  3716. // createLayout with options
  3717. renderer.createLayout($holder, options);
  3718. var info = renderer.layoutInfoFromHolder($holder);
  3719. eventHandler.attach(info, options);
  3720. // Textarea: auto filling the code before form submit.
  3721. if (dom.isTextarea($holder[0])) {
  3722. $holder.closest('form').submit(function () {
  3723. $holder.val($holder.code());
  3724. });
  3725. }
  3726. });
  3727. // focus on first editable element
  3728. if (this.first().length && options.focus) {
  3729. var info = renderer.layoutInfoFromHolder(this.first());
  3730. info.editable.focus();
  3731. }
  3732. // callback on init
  3733. if (this.length && options.oninit) {
  3734. options.oninit();
  3735. }
  3736. return this;
  3737. },
  3738. //
  3739. /**
  3740. * get the HTML contents of note or set the HTML contents of note.
  3741. *
  3742. * @param {String} [sHTML] - HTML contents(optional, set)
  3743. * @returns {this|String} - context(set) or HTML contents of note(get).
  3744. */
  3745. code: function (sHTML) {
  3746. // get the HTML contents of note
  3747. if (sHTML === undefined) {
  3748. var $holder = this.first();
  3749. if (!$holder.length) { return; }
  3750. var info = renderer.layoutInfoFromHolder($holder);
  3751. if (!!(info && info.editable)) {
  3752. var isCodeview = info.editor.hasClass('codeview');
  3753. if (isCodeview && agent.hasCodeMirror) {
  3754. info.codable.data('cmEditor').save();
  3755. }
  3756. return isCodeview ? info.codable.val() : info.editable.html();
  3757. }
  3758. return dom.isTextarea($holder[0]) ? $holder.val() : $holder.html();
  3759. }
  3760. // set the HTML contents of note
  3761. this.each(function (i, elHolder) {
  3762. var info = renderer.layoutInfoFromHolder($(elHolder));
  3763. if (info && info.editable) { info.editable.html(sHTML); }
  3764. });
  3765. return this;
  3766. },
  3767. /**
  3768. * destroy Editor Layout and dettach Key and Mouse Event
  3769. * @returns {this}
  3770. */
  3771. destroy: function () {
  3772. this.each(function (idx, elHolder) {
  3773. var $holder = $(elHolder);
  3774. var info = renderer.layoutInfoFromHolder($holder);
  3775. if (!info || !info.editable) { return; }
  3776. var options = info.editor.data('options');
  3777. eventHandler.dettach(info, options);
  3778. renderer.removeLayout($holder, info, options);
  3779. });
  3780. return this;
  3781. }
  3782. });
  3783. }));