kindeditor.js 155 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889
  1. /*******************************************************************************
  2. * KindEditor - WYSIWYG HTML Editor for Internet
  3. * Copyright (C) 2006-2013 kindsoft.net
  4. *
  5. * @author Roddy <luolonghao@gmail.com>
  6. * @website http://www.kindsoft.net/
  7. * @licence http://www.kindsoft.net/license.php
  8. * @version 4.1.7 (2013-04-21)
  9. *******************************************************************************/
  10. (function (window, undefined) {
  11. if (window.KindEditor) {
  12. return;
  13. }
  14. if (!window.console) {
  15. window.console = {};
  16. }
  17. if (!console.log) {
  18. console.log = function () {};
  19. }
  20. var _VERSION = '4.1.7 (2013-04-21)',
  21. _ua = navigator.userAgent.toLowerCase(),
  22. _IE = _ua.indexOf('msie') > -1 && _ua.indexOf('opera') == -1,
  23. _GECKO = _ua.indexOf('gecko') > -1 && _ua.indexOf('khtml') == -1,
  24. _WEBKIT = _ua.indexOf('applewebkit') > -1,
  25. _OPERA = _ua.indexOf('opera') > -1,
  26. _MOBILE = _ua.indexOf('mobile') > -1,
  27. _IOS = /ipad|iphone|ipod/.test(_ua),
  28. _QUIRKS = document.compatMode != 'CSS1Compat',
  29. _matches = /(?:msie|firefox|webkit|opera)[\/:\s](\d+)/.exec(_ua),
  30. _V = _matches ? _matches[1] : '0',
  31. _TIME = new Date().getTime();
  32. function _isArray(val) {
  33. if (!val) {
  34. return false;
  35. }
  36. return Object.prototype.toString.call(val) === '[object Array]';
  37. }
  38. function _isFunction(val) {
  39. if (!val) {
  40. return false;
  41. }
  42. return Object.prototype.toString.call(val) === '[object Function]';
  43. }
  44. function _inArray(val, arr) {
  45. for (var i = 0, len = arr.length; i < len; i++) {
  46. if (val === arr[i]) {
  47. return i;
  48. }
  49. }
  50. return -1;
  51. }
  52. function _each(obj, fn) {
  53. if (_isArray(obj)) {
  54. for (var i = 0, len = obj.length; i < len; i++) {
  55. if (fn.call(obj[i], i, obj[i]) === false) {
  56. break;
  57. }
  58. }
  59. } else {
  60. for (var key in obj) {
  61. if (obj.hasOwnProperty(key)) {
  62. if (fn.call(obj[key], key, obj[key]) === false) {
  63. break;
  64. }
  65. }
  66. }
  67. }
  68. }
  69. function _trim(str) {
  70. return str.replace(/(?:^[ \t\n\r]+)|(?:[ \t\n\r]+$)/g, '');
  71. }
  72. function _inString(val, str, delimiter) {
  73. delimiter = delimiter === undefined ? ',' : delimiter;
  74. return (delimiter + str + delimiter).indexOf(delimiter + val + delimiter) >= 0;
  75. }
  76. function _addUnit(val, unit) {
  77. unit = unit || 'px';
  78. return val && /^\d+$/.test(val) ? val + unit : val;
  79. }
  80. function _removeUnit(val) {
  81. var match;
  82. return val && (match = /(\d+)/.exec(val)) ? parseInt(match[1], 10) : 0;
  83. }
  84. function _escape(val) {
  85. return val.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
  86. }
  87. function _unescape(val) {
  88. return val.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&amp;/g, '&');
  89. }
  90. function _toCamel(str) {
  91. var arr = str.split('-');
  92. str = '';
  93. _each(arr, function(key, val) {
  94. str += (key > 0) ? val.charAt(0).toUpperCase() + val.substr(1) : val;
  95. });
  96. return str;
  97. }
  98. function _toHex(val) {
  99. function hex(d) {
  100. var s = parseInt(d, 10).toString(16).toUpperCase();
  101. return s.length > 1 ? s : '0' + s;
  102. }
  103. return val.replace(/rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/ig,
  104. function($0, $1, $2, $3) {
  105. return '#' + hex($1) + hex($2) + hex($3);
  106. }
  107. );
  108. }
  109. function _toMap(val, delimiter) {
  110. delimiter = delimiter === undefined ? ',' : delimiter;
  111. var map = {}, arr = _isArray(val) ? val : val.split(delimiter), match;
  112. _each(arr, function(key, val) {
  113. if ((match = /^(\d+)\.\.(\d+)$/.exec(val))) {
  114. for (var i = parseInt(match[1], 10); i <= parseInt(match[2], 10); i++) {
  115. map[i.toString()] = true;
  116. }
  117. } else {
  118. map[val] = true;
  119. }
  120. });
  121. return map;
  122. }
  123. function _toArray(obj, offset) {
  124. return Array.prototype.slice.call(obj, offset || 0);
  125. }
  126. function _undef(val, defaultVal) {
  127. return val === undefined ? defaultVal : val;
  128. }
  129. function _invalidUrl(url) {
  130. return !url || /[<>"]/.test(url);
  131. }
  132. function _addParam(url, param) {
  133. return url.indexOf('?') >= 0 ? url + '&' + param : url + '?' + param;
  134. }
  135. function _extend(child, parent, proto) {
  136. if (!proto) {
  137. proto = parent;
  138. parent = null;
  139. }
  140. var childProto;
  141. if (parent) {
  142. var fn = function () {};
  143. fn.prototype = parent.prototype;
  144. childProto = new fn();
  145. _each(proto, function(key, val) {
  146. childProto[key] = val;
  147. });
  148. } else {
  149. childProto = proto;
  150. }
  151. childProto.constructor = child;
  152. child.prototype = childProto;
  153. child.parent = parent ? parent.prototype : null;
  154. }
  155. function _json(text) {
  156. var match;
  157. if ((match = /\{[\s\S]*\}|\[[\s\S]*\]/.exec(text))) {
  158. text = match[0];
  159. }
  160. var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
  161. cx.lastIndex = 0;
  162. if (cx.test(text)) {
  163. text = text.replace(cx, function (a) {
  164. return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
  165. });
  166. }
  167. if (/^[\],:{}\s]*$/.
  168. test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
  169. replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
  170. replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
  171. return eval('(' + text + ')');
  172. }
  173. throw 'JSON parse error';
  174. }
  175. var _round = Math.round;
  176. var K = {
  177. DEBUG : false,
  178. VERSION : _VERSION,
  179. IE : _IE,
  180. GECKO : _GECKO,
  181. WEBKIT : _WEBKIT,
  182. OPERA : _OPERA,
  183. V : _V,
  184. TIME : _TIME,
  185. each : _each,
  186. isArray : _isArray,
  187. isFunction : _isFunction,
  188. inArray : _inArray,
  189. inString : _inString,
  190. trim : _trim,
  191. addUnit : _addUnit,
  192. removeUnit : _removeUnit,
  193. escape : _escape,
  194. unescape : _unescape,
  195. toCamel : _toCamel,
  196. toHex : _toHex,
  197. toMap : _toMap,
  198. toArray : _toArray,
  199. undef : _undef,
  200. invalidUrl : _invalidUrl,
  201. addParam : _addParam,
  202. extend : _extend,
  203. json : _json
  204. };
  205. var _INLINE_TAG_MAP = _toMap('a,abbr,acronym,b,basefont,bdo,big,br,button,cite,code,del,dfn,em,font,i,img,input,ins,kbd,label,map,q,s,samp,select,small,span,strike,strong,sub,sup,textarea,tt,u,var'),
  206. _BLOCK_TAG_MAP = _toMap('address,applet,blockquote,body,center,dd,dir,div,dl,dt,fieldset,form,frameset,h1,h2,h3,h4,h5,h6,head,hr,html,iframe,ins,isindex,li,map,menu,meta,noframes,noscript,object,ol,p,pre,script,style,table,tbody,td,tfoot,th,thead,title,tr,ul'),
  207. _SINGLE_TAG_MAP = _toMap('area,base,basefont,br,col,frame,hr,img,input,isindex,link,meta,param,embed'),
  208. _STYLE_TAG_MAP = _toMap('b,basefont,big,del,em,font,i,s,small,span,strike,strong,sub,sup,u'),
  209. _CONTROL_TAG_MAP = _toMap('img,table,input,textarea,button'),
  210. _PRE_TAG_MAP = _toMap('pre,style,script'),
  211. _NOSPLIT_TAG_MAP = _toMap('html,head,body,td,tr,table,ol,ul,li'),
  212. _AUTOCLOSE_TAG_MAP = _toMap('colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr'),
  213. _FILL_ATTR_MAP = _toMap('checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected'),
  214. _VALUE_TAG_MAP = _toMap('input,button,textarea,select');
  215. function _getBasePath() {
  216. var els = document.getElementsByTagName('script'), src;
  217. for (var i = 0, len = els.length; i < len; i++) {
  218. src = els[i].src || '';
  219. if (/kindeditor[\w\-\.]*\.js/.test(src)) {
  220. return src.substring(0, src.lastIndexOf('/') + 1);
  221. }
  222. }
  223. return '';
  224. }
  225. K.basePath = _getBasePath();
  226. K.options = {
  227. designMode : true,
  228. fullscreenMode : false,
  229. filterMode : true,
  230. wellFormatMode : true,
  231. shadowMode : true,
  232. loadStyleMode : true,
  233. basePath : K.basePath,
  234. themesPath : K.basePath + 'themes/',
  235. langPath : K.basePath + 'lang/',
  236. pluginsPath : K.basePath + 'plugins/',
  237. themeType : 'default',
  238. langType : 'zh_CN',
  239. urlType : '',
  240. newlineTag : 'p',
  241. resizeType : 2,
  242. syncType : 'form',
  243. pasteType : 2,
  244. dialogAlignType : 'page',
  245. useContextmenu : true,
  246. fullscreenShortcut : false,
  247. bodyClass : 'ke-content',
  248. indentChar : '\t',
  249. cssPath : '',
  250. cssData : '',
  251. minWidth : 650,
  252. minHeight : 100,
  253. minChangeSize : 50,
  254. zIndex : 811213,
  255. items : [
  256. 'source', '|', 'undo', 'redo', '|', 'preview', 'print', 'template', 'code', 'cut', 'copy', 'paste',
  257. 'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright',
  258. 'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',
  259. 'superscript', 'clearhtml', 'quickformat', 'selectall', '|', 'fullscreen', '/',
  260. 'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold',
  261. 'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'image', 'multiimage',
  262. 'flash', 'media', 'insertfile', 'table', 'hr', 'emoticons', 'baidumap', 'pagebreak',
  263. 'anchor', 'link', 'unlink', '|', 'about'
  264. ],
  265. noDisableItems : ['source', 'fullscreen'],
  266. colorTable : [
  267. ['#E53333', '#E56600', '#FF9900', '#64451D', '#DFC5A4', '#FFE500'],
  268. ['#009900', '#006600', '#99BB00', '#B8D100', '#60D978', '#00D5FF'],
  269. ['#337FE5', '#003399', '#4C33E5', '#9933E5', '#CC33E5', '#EE33EE'],
  270. ['#FFFFFF', '#CCCCCC', '#999999', '#666666', '#333333', '#000000']
  271. ],
  272. fontSizeTable : ['9px', '10px', '12px', '14px', '16px', '18px', '24px', '32px'],
  273. htmlTags : {
  274. font : ['id', 'class', 'color', 'size', 'face', '.background-color'],
  275. span : [
  276. 'id', 'class', '.color', '.background-color', '.font-size', '.font-family', '.background',
  277. '.font-weight', '.font-style', '.text-decoration', '.vertical-align', '.line-height'
  278. ],
  279. div : [
  280. 'id', 'class', 'align', '.border', '.margin', '.padding', '.text-align', '.color',
  281. '.background-color', '.font-size', '.font-family', '.font-weight', '.background',
  282. '.font-style', '.text-decoration', '.vertical-align', '.margin-left'
  283. ],
  284. table: [
  285. 'id', 'class', 'border', 'cellspacing', 'cellpadding', 'width', 'height', 'align', 'bordercolor',
  286. '.padding', '.margin', '.border', 'bgcolor', '.text-align', '.color', '.background-color',
  287. '.font-size', '.font-family', '.font-weight', '.font-style', '.text-decoration', '.background',
  288. '.width', '.height', '.border-collapse'
  289. ],
  290. 'td,th': [
  291. 'id', 'class', 'align', 'valign', 'width', 'height', 'colspan', 'rowspan', 'bgcolor',
  292. '.text-align', '.color', '.background-color', '.font-size', '.font-family', '.font-weight',
  293. '.font-style', '.text-decoration', '.vertical-align', '.background', '.border'
  294. ],
  295. a : ['id', 'class', 'href', 'target', 'name'],
  296. embed : ['id', 'class', 'src', 'width', 'height', 'type', 'loop', 'autostart', 'quality', '.width', '.height', 'align', 'allowscriptaccess'],
  297. img : ['id', 'class', 'src', 'width', 'height', 'border', 'alt', 'title', 'align', '.width', '.height', '.border'],
  298. 'p,ol,ul,li,blockquote,h1,h2,h3,h4,h5,h6' : [
  299. 'id', 'class', 'align', '.text-align', '.color', '.background-color', '.font-size', '.font-family', '.background',
  300. '.font-weight', '.font-style', '.text-decoration', '.vertical-align', '.text-indent', '.margin-left'
  301. ],
  302. pre : ['id', 'class'],
  303. hr : ['id', 'class', '.page-break-after'],
  304. 'br,tbody,tr,strong,b,sub,sup,em,i,u,strike,s,del' : ['id', 'class'],
  305. iframe : ['id', 'class', 'src', 'frameborder', 'width', 'height', '.width', '.height']
  306. },
  307. layout : '<div class="container"><div class="toolbar"></div><div class="edit"></div><div class="statusbar"></div></div>'
  308. };
  309. var _useCapture = false;
  310. var _INPUT_KEY_MAP = _toMap('8,9,13,32,46,48..57,59,61,65..90,106,109..111,188,190..192,219..222');
  311. var _CURSORMOVE_KEY_MAP = _toMap('33..40');
  312. var _CHANGE_KEY_MAP = {};
  313. _each(_INPUT_KEY_MAP, function(key, val) {
  314. _CHANGE_KEY_MAP[key] = val;
  315. });
  316. _each(_CURSORMOVE_KEY_MAP, function(key, val) {
  317. _CHANGE_KEY_MAP[key] = val;
  318. });
  319. function _bindEvent(el, type, fn) {
  320. if (el.addEventListener){
  321. el.addEventListener(type, fn, _useCapture);
  322. } else if (el.attachEvent){
  323. el.attachEvent('on' + type, fn);
  324. }
  325. }
  326. function _unbindEvent(el, type, fn) {
  327. if (el.removeEventListener){
  328. el.removeEventListener(type, fn, _useCapture);
  329. } else if (el.detachEvent){
  330. el.detachEvent('on' + type, fn);
  331. }
  332. }
  333. var _EVENT_PROPS = ('altKey,attrChange,attrName,bubbles,button,cancelable,charCode,clientX,clientY,ctrlKey,currentTarget,' +
  334. 'data,detail,eventPhase,fromElement,handler,keyCode,metaKey,newValue,offsetX,offsetY,originalTarget,pageX,' +
  335. 'pageY,prevValue,relatedNode,relatedTarget,screenX,screenY,shiftKey,srcElement,target,toElement,view,wheelDelta,which').split(',');
  336. function KEvent(el, event) {
  337. this.init(el, event);
  338. }
  339. _extend(KEvent, {
  340. init : function(el, event) {
  341. var self = this, doc = el.ownerDocument || el.document || el;
  342. self.event = event;
  343. _each(_EVENT_PROPS, function(key, val) {
  344. self[val] = event[val];
  345. });
  346. if (!self.target) {
  347. self.target = self.srcElement || doc;
  348. }
  349. if (self.target.nodeType === 3) {
  350. self.target = self.target.parentNode;
  351. }
  352. if (!self.relatedTarget && self.fromElement) {
  353. self.relatedTarget = self.fromElement === self.target ? self.toElement : self.fromElement;
  354. }
  355. if (self.pageX == null && self.clientX != null) {
  356. var d = doc.documentElement, body = doc.body;
  357. self.pageX = self.clientX + (d && d.scrollLeft || body && body.scrollLeft || 0) - (d && d.clientLeft || body && body.clientLeft || 0);
  358. self.pageY = self.clientY + (d && d.scrollTop || body && body.scrollTop || 0) - (d && d.clientTop || body && body.clientTop || 0);
  359. }
  360. if (!self.which && ((self.charCode || self.charCode === 0) ? self.charCode : self.keyCode)) {
  361. self.which = self.charCode || self.keyCode;
  362. }
  363. if (!self.metaKey && self.ctrlKey) {
  364. self.metaKey = self.ctrlKey;
  365. }
  366. if (!self.which && self.button !== undefined) {
  367. self.which = (self.button & 1 ? 1 : (self.button & 2 ? 3 : (self.button & 4 ? 2 : 0)));
  368. }
  369. switch (self.which) {
  370. case 186 :
  371. self.which = 59;
  372. break;
  373. case 187 :
  374. case 107 :
  375. case 43 :
  376. self.which = 61;
  377. break;
  378. case 189 :
  379. case 45 :
  380. self.which = 109;
  381. break;
  382. case 42 :
  383. self.which = 106;
  384. break;
  385. case 47 :
  386. self.which = 111;
  387. break;
  388. case 78 :
  389. self.which = 110;
  390. break;
  391. }
  392. if (self.which >= 96 && self.which <= 105) {
  393. self.which -= 48;
  394. }
  395. },
  396. preventDefault : function() {
  397. var ev = this.event;
  398. if (ev.preventDefault) {
  399. ev.preventDefault();
  400. }
  401. ev.returnValue = false;
  402. },
  403. stopPropagation : function() {
  404. var ev = this.event;
  405. if (ev.stopPropagation) {
  406. ev.stopPropagation();
  407. }
  408. ev.cancelBubble = true;
  409. },
  410. stop : function() {
  411. this.preventDefault();
  412. this.stopPropagation();
  413. }
  414. });
  415. var _eventExpendo = 'kindeditor_' + _TIME, _eventId = 0, _eventData = {};
  416. function _getId(el) {
  417. return el[_eventExpendo] || null;
  418. }
  419. function _setId(el) {
  420. el[_eventExpendo] = ++_eventId;
  421. return _eventId;
  422. }
  423. function _removeId(el) {
  424. try {
  425. delete el[_eventExpendo];
  426. } catch(e) {
  427. if (el.removeAttribute) {
  428. el.removeAttribute(_eventExpendo);
  429. }
  430. }
  431. }
  432. function _bind(el, type, fn) {
  433. if (type.indexOf(',') >= 0) {
  434. _each(type.split(','), function() {
  435. _bind(el, this, fn);
  436. });
  437. return;
  438. }
  439. var id = _getId(el);
  440. if (!id) {
  441. id = _setId(el);
  442. }
  443. if (_eventData[id] === undefined) {
  444. _eventData[id] = {};
  445. }
  446. var events = _eventData[id][type];
  447. if (events && events.length > 0) {
  448. _unbindEvent(el, type, events[0]);
  449. } else {
  450. _eventData[id][type] = [];
  451. _eventData[id].el = el;
  452. }
  453. events = _eventData[id][type];
  454. if (events.length === 0) {
  455. events[0] = function(e) {
  456. var kevent = e ? new KEvent(el, e) : undefined;
  457. _each(events, function(i, event) {
  458. if (i > 0 && event) {
  459. event.call(el, kevent);
  460. }
  461. });
  462. };
  463. }
  464. if (_inArray(fn, events) < 0) {
  465. events.push(fn);
  466. }
  467. _bindEvent(el, type, events[0]);
  468. }
  469. function _unbind(el, type, fn) {
  470. if (type && type.indexOf(',') >= 0) {
  471. _each(type.split(','), function() {
  472. _unbind(el, this, fn);
  473. });
  474. return;
  475. }
  476. var id = _getId(el);
  477. if (!id) {
  478. return;
  479. }
  480. if (type === undefined) {
  481. if (id in _eventData) {
  482. _each(_eventData[id], function(key, events) {
  483. if (key != 'el' && events.length > 0) {
  484. _unbindEvent(el, key, events[0]);
  485. }
  486. });
  487. delete _eventData[id];
  488. _removeId(el);
  489. }
  490. return;
  491. }
  492. if (!_eventData[id]) {
  493. return;
  494. }
  495. var events = _eventData[id][type];
  496. if (events && events.length > 0) {
  497. if (fn === undefined) {
  498. _unbindEvent(el, type, events[0]);
  499. delete _eventData[id][type];
  500. } else {
  501. _each(events, function(i, event) {
  502. if (i > 0 && event === fn) {
  503. events.splice(i, 1);
  504. }
  505. });
  506. if (events.length == 1) {
  507. _unbindEvent(el, type, events[0]);
  508. delete _eventData[id][type];
  509. }
  510. }
  511. var count = 0;
  512. _each(_eventData[id], function() {
  513. count++;
  514. });
  515. if (count < 2) {
  516. delete _eventData[id];
  517. _removeId(el);
  518. }
  519. }
  520. }
  521. function _fire(el, type) {
  522. if (type.indexOf(',') >= 0) {
  523. _each(type.split(','), function() {
  524. _fire(el, this);
  525. });
  526. return;
  527. }
  528. var id = _getId(el);
  529. if (!id) {
  530. return;
  531. }
  532. var events = _eventData[id][type];
  533. if (_eventData[id] && events && events.length > 0) {
  534. events[0]();
  535. }
  536. }
  537. function _ctrl(el, key, fn) {
  538. var self = this;
  539. key = /^\d{2,}$/.test(key) ? key : key.toUpperCase().charCodeAt(0);
  540. _bind(el, 'keydown', function(e) {
  541. if (e.ctrlKey && e.which == key && !e.shiftKey && !e.altKey) {
  542. fn.call(el);
  543. e.stop();
  544. }
  545. });
  546. }
  547. function _ready(fn) {
  548. var loaded = false;
  549. function readyFunc() {
  550. if (!loaded) {
  551. loaded = true;
  552. fn(KindEditor);
  553. }
  554. }
  555. function ieReadyFunc() {
  556. if (!loaded) {
  557. try {
  558. document.documentElement.doScroll('left');
  559. } catch(e) {
  560. setTimeout(ieReadyFunc, 100);
  561. return;
  562. }
  563. readyFunc();
  564. }
  565. }
  566. function ieReadyStateFunc() {
  567. if (document.readyState === 'complete') {
  568. readyFunc();
  569. }
  570. }
  571. if (document.addEventListener) {
  572. _bind(document, 'DOMContentLoaded', readyFunc);
  573. } else if (document.attachEvent) {
  574. _bind(document, 'readystatechange', ieReadyStateFunc);
  575. var toplevel = false;
  576. try {
  577. toplevel = window.frameElement == null;
  578. } catch(e) {}
  579. if (document.documentElement.doScroll && toplevel) {
  580. ieReadyFunc();
  581. }
  582. }
  583. _bind(window, 'load', readyFunc);
  584. }
  585. if (_IE) {
  586. window.attachEvent('onunload', function() {
  587. _each(_eventData, function(key, events) {
  588. if (events.el) {
  589. _unbind(events.el);
  590. }
  591. });
  592. });
  593. }
  594. K.ctrl = _ctrl;
  595. K.ready = _ready;
  596. function _getCssList(css) {
  597. var list = {},
  598. reg = /\s*([\w\-]+)\s*:([^;]*)(;|$)/g,
  599. match;
  600. while ((match = reg.exec(css))) {
  601. var key = _trim(match[1].toLowerCase()),
  602. val = _trim(_toHex(match[2]));
  603. list[key] = val;
  604. }
  605. return list;
  606. }
  607. function _getAttrList(tag) {
  608. var list = {},
  609. reg = /\s+(?:([\w\-:]+)|(?:([\w\-:]+)=([^\s"'<>]+))|(?:([\w\-:"]+)="([^"]*)")|(?:([\w\-:"]+)='([^']*)'))(?=(?:\s|\/|>)+)/g,
  610. match;
  611. while ((match = reg.exec(tag))) {
  612. var key = (match[1] || match[2] || match[4] || match[6]).toLowerCase(),
  613. val = (match[2] ? match[3] : (match[4] ? match[5] : match[7])) || '';
  614. list[key] = val;
  615. }
  616. return list;
  617. }
  618. function _addClassToTag(tag, className) {
  619. if (/\s+class\s*=/.test(tag)) {
  620. tag = tag.replace(/(\s+class=["']?)([^"']*)(["']?[\s>])/, function($0, $1, $2, $3) {
  621. if ((' ' + $2 + ' ').indexOf(' ' + className + ' ') < 0) {
  622. return $2 === '' ? $1 + className + $3 : $1 + $2 + ' ' + className + $3;
  623. } else {
  624. return $0;
  625. }
  626. });
  627. } else {
  628. tag = tag.substr(0, tag.length - 1) + ' class="' + className + '">';
  629. }
  630. return tag;
  631. }
  632. function _formatCss(css) {
  633. var str = '';
  634. _each(_getCssList(css), function(key, val) {
  635. str += key + ':' + val + ';';
  636. });
  637. return str;
  638. }
  639. function _formatUrl(url, mode, host, pathname) {
  640. mode = _undef(mode, '').toLowerCase();
  641. if (url.substr(0, 5) != 'data:') {
  642. url = url.replace(/([^:])\/\//g, '$1/');
  643. }
  644. if (_inArray(mode, ['absolute', 'relative', 'domain']) < 0) {
  645. return url;
  646. }
  647. host = host || location.protocol + '//' + location.host;
  648. if (pathname === undefined) {
  649. var m = location.pathname.match(/^(\/.*)\//);
  650. pathname = m ? m[1] : '';
  651. }
  652. var match;
  653. if ((match = /^(\w+:\/\/[^\/]*)/.exec(url))) {
  654. if (match[1] !== host) {
  655. return url;
  656. }
  657. } else if (/^\w+:/.test(url)) {
  658. return url;
  659. }
  660. function getRealPath(path) {
  661. var parts = path.split('/'), paths = [];
  662. for (var i = 0, len = parts.length; i < len; i++) {
  663. var part = parts[i];
  664. if (part == '..') {
  665. if (paths.length > 0) {
  666. paths.pop();
  667. }
  668. } else if (part !== '' && part != '.') {
  669. paths.push(part);
  670. }
  671. }
  672. return '/' + paths.join('/');
  673. }
  674. if (/^\//.test(url)) {
  675. url = host + getRealPath(url.substr(1));
  676. } else if (!/^\w+:\/\//.test(url)) {
  677. url = host + getRealPath(pathname + '/' + url);
  678. }
  679. function getRelativePath(path, depth) {
  680. if (url.substr(0, path.length) === path) {
  681. var arr = [];
  682. for (var i = 0; i < depth; i++) {
  683. arr.push('..');
  684. }
  685. var prefix = '.';
  686. if (arr.length > 0) {
  687. prefix += '/' + arr.join('/');
  688. }
  689. if (pathname == '/') {
  690. prefix += '/';
  691. }
  692. return prefix + url.substr(path.length);
  693. } else {
  694. if ((match = /^(.*)\//.exec(path))) {
  695. return getRelativePath(match[1], ++depth);
  696. }
  697. }
  698. }
  699. if (mode === 'relative') {
  700. url = getRelativePath(host + pathname, 0).substr(2);
  701. } else if (mode === 'absolute') {
  702. if (url.substr(0, host.length) === host) {
  703. url = url.substr(host.length);
  704. }
  705. }
  706. return url;
  707. }
  708. function _formatHtml(html, htmlTags, urlType, wellFormatted, indentChar) {
  709. urlType = urlType || '';
  710. wellFormatted = _undef(wellFormatted, false);
  711. indentChar = _undef(indentChar, '\t');
  712. var fontSizeList = 'xx-small,x-small,small,medium,large,x-large,xx-large'.split(',');
  713. html = html.replace(/(<(?:pre|pre\s[^>]*)>)([\s\S]*?)(<\/pre>)/ig, function($0, $1, $2, $3) {
  714. return $1 + $2.replace(/<(?:br|br\s[^>]*)>/ig, '\n') + $3;
  715. });
  716. html = html.replace(/<(?:br|br\s[^>]*)\s*\/?>\s*<\/p>/ig, '</p>');
  717. html = html.replace(/(<(?:p|p\s[^>]*)>)\s*(<\/p>)/ig, '$1<br />$2');
  718. html = html.replace(/\u200B/g, '');
  719. html = html.replace(/\u00A9/g, '&copy;');
  720. var htmlTagMap = {};
  721. if (htmlTags) {
  722. _each(htmlTags, function(key, val) {
  723. var arr = key.split(',');
  724. for (var i = 0, len = arr.length; i < len; i++) {
  725. htmlTagMap[arr[i]] = _toMap(val);
  726. }
  727. });
  728. if (!htmlTagMap.script) {
  729. html = html.replace(/(<(?:script|script\s[^>]*)>)([\s\S]*?)(<\/script>)/ig, '');
  730. }
  731. if (!htmlTagMap.style) {
  732. html = html.replace(/(<(?:style|style\s[^>]*)>)([\s\S]*?)(<\/style>)/ig, '');
  733. }
  734. }
  735. var re = /([ \t\n\r]*)<(\/)?([\w\-:]+)((?:\s+|(?:\s+[\w\-:]+)|(?:\s+[\w\-:]+=[^\s"'<>]+)|(?:\s+[\w\-:"]+="[^"]*")|(?:\s+[\w\-:"]+='[^']*'))*)(\/)?>([ \t\n\r]*)/g;
  736. var tagStack = [];
  737. html = html.replace(re, function($0, $1, $2, $3, $4, $5, $6) {
  738. var full = $0,
  739. startNewline = $1 || '',
  740. startSlash = $2 || '',
  741. tagName = $3.toLowerCase(),
  742. attr = $4 || '',
  743. endSlash = $5 ? ' ' + $5 : '',
  744. endNewline = $6 || '';
  745. if (htmlTags && !htmlTagMap[tagName]) {
  746. return '';
  747. }
  748. if (endSlash === '' && _SINGLE_TAG_MAP[tagName]) {
  749. endSlash = ' /';
  750. }
  751. if (_INLINE_TAG_MAP[tagName]) {
  752. if (startNewline) {
  753. startNewline = ' ';
  754. }
  755. if (endNewline) {
  756. endNewline = ' ';
  757. }
  758. }
  759. if (_PRE_TAG_MAP[tagName]) {
  760. if (startSlash) {
  761. endNewline = '\n';
  762. } else {
  763. startNewline = '\n';
  764. }
  765. }
  766. if (wellFormatted && tagName == 'br') {
  767. endNewline = '\n';
  768. }
  769. if (_BLOCK_TAG_MAP[tagName] && !_PRE_TAG_MAP[tagName]) {
  770. if (wellFormatted) {
  771. if (startSlash && tagStack.length > 0 && tagStack[tagStack.length - 1] === tagName) {
  772. tagStack.pop();
  773. } else {
  774. tagStack.push(tagName);
  775. }
  776. startNewline = '\n';
  777. endNewline = '\n';
  778. for (var i = 0, len = startSlash ? tagStack.length : tagStack.length - 1; i < len; i++) {
  779. startNewline += indentChar;
  780. if (!startSlash) {
  781. endNewline += indentChar;
  782. }
  783. }
  784. if (endSlash) {
  785. tagStack.pop();
  786. } else if (!startSlash) {
  787. endNewline += indentChar;
  788. }
  789. } else {
  790. startNewline = endNewline = '';
  791. }
  792. }
  793. if (attr !== '') {
  794. var attrMap = _getAttrList(full);
  795. if (tagName === 'font') {
  796. var fontStyleMap = {}, fontStyle = '';
  797. _each(attrMap, function(key, val) {
  798. if (key === 'color') {
  799. fontStyleMap.color = val;
  800. delete attrMap[key];
  801. }
  802. if (key === 'size') {
  803. fontStyleMap['font-size'] = fontSizeList[parseInt(val, 10) - 1] || '';
  804. delete attrMap[key];
  805. }
  806. if (key === 'face') {
  807. fontStyleMap['font-family'] = val;
  808. delete attrMap[key];
  809. }
  810. if (key === 'style') {
  811. fontStyle = val;
  812. }
  813. });
  814. if (fontStyle && !/;$/.test(fontStyle)) {
  815. fontStyle += ';';
  816. }
  817. _each(fontStyleMap, function(key, val) {
  818. if (val === '') {
  819. return;
  820. }
  821. if (/\s/.test(val)) {
  822. val = "'" + val + "'";
  823. }
  824. fontStyle += key + ':' + val + ';';
  825. });
  826. attrMap.style = fontStyle;
  827. }
  828. _each(attrMap, function(key, val) {
  829. if (_FILL_ATTR_MAP[key]) {
  830. attrMap[key] = key;
  831. }
  832. if (_inArray(key, ['src', 'href']) >= 0) {
  833. attrMap[key] = _formatUrl(val, urlType);
  834. }
  835. if (htmlTags && key !== 'style' && !htmlTagMap[tagName]['*'] && !htmlTagMap[tagName][key] ||
  836. tagName === 'body' && key === 'contenteditable' ||
  837. /^kindeditor_\d+$/.test(key)) {
  838. delete attrMap[key];
  839. }
  840. if (key === 'style' && val !== '') {
  841. var styleMap = _getCssList(val);
  842. _each(styleMap, function(k, v) {
  843. if (htmlTags && !htmlTagMap[tagName].style && !htmlTagMap[tagName]['.' + k]) {
  844. delete styleMap[k];
  845. }
  846. });
  847. var style = '';
  848. _each(styleMap, function(k, v) {
  849. style += k + ':' + v + ';';
  850. });
  851. attrMap.style = style;
  852. }
  853. });
  854. attr = '';
  855. _each(attrMap, function(key, val) {
  856. if (key === 'style' && val === '') {
  857. return;
  858. }
  859. val = val.replace(/"/g, '&quot;');
  860. attr += ' ' + key + '="' + val + '"';
  861. });
  862. }
  863. if (tagName === 'font') {
  864. tagName = 'span';
  865. }
  866. return startNewline + '<' + startSlash + tagName + attr + endSlash + '>' + endNewline;
  867. });
  868. html = html.replace(/(<(?:pre|pre\s[^>]*)>)([\s\S]*?)(<\/pre>)/ig, function($0, $1, $2, $3) {
  869. return $1 + $2.replace(/\n/g, '<span id="__kindeditor_pre_newline__">\n') + $3;
  870. });
  871. html = html.replace(/\n\s*\n/g, '\n');
  872. html = html.replace(/<span id="__kindeditor_pre_newline__">\n/g, '\n');
  873. return _trim(html);
  874. }
  875. function _clearMsWord(html, htmlTags) {
  876. html = html.replace(/<meta[\s\S]*?>/ig, '')
  877. .replace(/<![\s\S]*?>/ig, '')
  878. .replace(/<style[^>]*>[\s\S]*?<\/style>/ig, '')
  879. .replace(/<script[^>]*>[\s\S]*?<\/script>/ig, '')
  880. .replace(/<w:[^>]+>[\s\S]*?<\/w:[^>]+>/ig, '')
  881. .replace(/<o:[^>]+>[\s\S]*?<\/o:[^>]+>/ig, '')
  882. .replace(/<xml>[\s\S]*?<\/xml>/ig, '')
  883. .replace(/<(?:table|td)[^>]*>/ig, function(full) {
  884. return full.replace(/border-bottom:([#\w\s]+)/ig, 'border:$1');
  885. });
  886. return _formatHtml(html, htmlTags);
  887. }
  888. function _mediaType(src) {
  889. if (/\.(rm|rmvb)(\?|$)/i.test(src)) {
  890. return 'audio/x-pn-realaudio-plugin';
  891. }
  892. if (/\.(swf|flv)(\?|$)/i.test(src)) {
  893. return 'application/x-shockwave-flash';
  894. }
  895. return 'video/x-ms-asf-plugin';
  896. }
  897. function _mediaClass(type) {
  898. if (/realaudio/i.test(type)) {
  899. return 'ke-rm';
  900. }
  901. if (/flash/i.test(type)) {
  902. return 'ke-flash';
  903. }
  904. return 'ke-media';
  905. }
  906. function _mediaAttrs(srcTag) {
  907. return _getAttrList(unescape(srcTag));
  908. }
  909. function _mediaEmbed(attrs) {
  910. var html = '<embed ';
  911. _each(attrs, function(key, val) {
  912. html += key + '="' + val + '" ';
  913. });
  914. html += '/>';
  915. return html;
  916. }
  917. function _mediaImg(blankPath, attrs) {
  918. var width = attrs.width,
  919. height = attrs.height,
  920. type = attrs.type || _mediaType(attrs.src),
  921. srcTag = _mediaEmbed(attrs),
  922. style = '';
  923. if (width > 0) {
  924. style += 'width:' + width + 'px;';
  925. }
  926. if (height > 0) {
  927. style += 'height:' + height + 'px;';
  928. }
  929. var html = '<img class="' + _mediaClass(type) + '" src="' + blankPath + '" ';
  930. if (style !== '') {
  931. html += 'style="' + style + '" ';
  932. }
  933. html += 'data-ke-tag="' + escape(srcTag) + '" alt="" />';
  934. return html;
  935. }
  936. function _tmpl(str, data) {
  937. var fn = new Function("obj",
  938. "var p=[],print=function(){p.push.apply(p,arguments);};" +
  939. "with(obj){p.push('" +
  940. str.replace(/[\r\t\n]/g, " ")
  941. .split("<%").join("\t")
  942. .replace(/((^|%>)[^\t]*)'/g, "$1\r")
  943. .replace(/\t=(.*?)%>/g, "',$1,'")
  944. .split("\t").join("');")
  945. .split("%>").join("p.push('")
  946. .split("\r").join("\\'") + "');}return p.join('');");
  947. return data ? fn(data) : fn;
  948. }
  949. K.formatUrl = _formatUrl;
  950. K.formatHtml = _formatHtml;
  951. K.getCssList = _getCssList;
  952. K.getAttrList = _getAttrList;
  953. K.mediaType = _mediaType;
  954. K.mediaAttrs = _mediaAttrs;
  955. K.mediaEmbed = _mediaEmbed;
  956. K.mediaImg = _mediaImg;
  957. K.clearMsWord = _clearMsWord;
  958. K.tmpl = _tmpl;
  959. function _contains(nodeA, nodeB) {
  960. if (nodeA.nodeType == 9 && nodeB.nodeType != 9) {
  961. return true;
  962. }
  963. while ((nodeB = nodeB.parentNode)) {
  964. if (nodeB == nodeA) {
  965. return true;
  966. }
  967. }
  968. return false;
  969. }
  970. var _getSetAttrDiv = document.createElement('div');
  971. _getSetAttrDiv.setAttribute('className', 't');
  972. var _GET_SET_ATTRIBUTE = _getSetAttrDiv.className !== 't';
  973. function _getAttr(el, key) {
  974. key = key.toLowerCase();
  975. var val = null;
  976. if (!_GET_SET_ATTRIBUTE && el.nodeName.toLowerCase() != 'script') {
  977. var div = el.ownerDocument.createElement('div');
  978. div.appendChild(el.cloneNode(false));
  979. var list = _getAttrList(_unescape(div.innerHTML));
  980. if (key in list) {
  981. val = list[key];
  982. }
  983. } else {
  984. try {
  985. val = el.getAttribute(key, 2);
  986. } catch(e) {
  987. val = el.getAttribute(key, 1);
  988. }
  989. }
  990. if (key === 'style' && val !== null) {
  991. val = _formatCss(val);
  992. }
  993. return val;
  994. }
  995. function _queryAll(expr, root) {
  996. var exprList = expr.split(',');
  997. if (exprList.length > 1) {
  998. var mergedResults = [];
  999. _each(exprList, function() {
  1000. _each(_queryAll(this, root), function() {
  1001. if (_inArray(this, mergedResults) < 0) {
  1002. mergedResults.push(this);
  1003. }
  1004. });
  1005. });
  1006. return mergedResults;
  1007. }
  1008. root = root || document;
  1009. function escape(str) {
  1010. if (typeof str != 'string') {
  1011. return str;
  1012. }
  1013. return str.replace(/([^\w\-])/g, '\\$1');
  1014. }
  1015. function stripslashes(str) {
  1016. return str.replace(/\\/g, '');
  1017. }
  1018. function cmpTag(tagA, tagB) {
  1019. return tagA === '*' || tagA.toLowerCase() === escape(tagB.toLowerCase());
  1020. }
  1021. function byId(id, tag, root) {
  1022. var arr = [],
  1023. doc = root.ownerDocument || root,
  1024. el = doc.getElementById(stripslashes(id));
  1025. if (el) {
  1026. if (cmpTag(tag, el.nodeName) && _contains(root, el)) {
  1027. arr.push(el);
  1028. }
  1029. }
  1030. return arr;
  1031. }
  1032. function byClass(className, tag, root) {
  1033. var doc = root.ownerDocument || root, arr = [], els, i, len, el;
  1034. if (root.getElementsByClassName) {
  1035. els = root.getElementsByClassName(stripslashes(className));
  1036. for (i = 0, len = els.length; i < len; i++) {
  1037. el = els[i];
  1038. if (cmpTag(tag, el.nodeName)) {
  1039. arr.push(el);
  1040. }
  1041. }
  1042. } else if (doc.querySelectorAll) {
  1043. els = doc.querySelectorAll((root.nodeName !== '#document' ? root.nodeName + ' ' : '') + tag + '.' + className);
  1044. for (i = 0, len = els.length; i < len; i++) {
  1045. el = els[i];
  1046. if (_contains(root, el)) {
  1047. arr.push(el);
  1048. }
  1049. }
  1050. } else {
  1051. els = root.getElementsByTagName(tag);
  1052. className = ' ' + className + ' ';
  1053. for (i = 0, len = els.length; i < len; i++) {
  1054. el = els[i];
  1055. if (el.nodeType == 1) {
  1056. var cls = el.className;
  1057. if (cls && (' ' + cls + ' ').indexOf(className) > -1) {
  1058. arr.push(el);
  1059. }
  1060. }
  1061. }
  1062. }
  1063. return arr;
  1064. }
  1065. function byName(name, tag, root) {
  1066. var arr = [], doc = root.ownerDocument || root,
  1067. els = doc.getElementsByName(stripslashes(name)), el;
  1068. for (var i = 0, len = els.length; i < len; i++) {
  1069. el = els[i];
  1070. if (cmpTag(tag, el.nodeName) && _contains(root, el)) {
  1071. if (el.getAttributeNode('name')) {
  1072. arr.push(el);
  1073. }
  1074. }
  1075. }
  1076. return arr;
  1077. }
  1078. function byAttr(key, val, tag, root) {
  1079. var arr = [], els = root.getElementsByTagName(tag), el;
  1080. for (var i = 0, len = els.length; i < len; i++) {
  1081. el = els[i];
  1082. if (el.nodeType == 1) {
  1083. if (val === null) {
  1084. if (_getAttr(el, key) !== null) {
  1085. arr.push(el);
  1086. }
  1087. } else {
  1088. if (val === escape(_getAttr(el, key))) {
  1089. arr.push(el);
  1090. }
  1091. }
  1092. }
  1093. }
  1094. return arr;
  1095. }
  1096. function select(expr, root) {
  1097. var arr = [], matches;
  1098. matches = /^((?:\\.|[^.#\s\[<>])+)/.exec(expr);
  1099. var tag = matches ? matches[1] : '*';
  1100. if ((matches = /#((?:[\w\-]|\\.)+)$/.exec(expr))) {
  1101. arr = byId(matches[1], tag, root);
  1102. } else if ((matches = /\.((?:[\w\-]|\\.)+)$/.exec(expr))) {
  1103. arr = byClass(matches[1], tag, root);
  1104. } else if ((matches = /\[((?:[\w\-]|\\.)+)\]/.exec(expr))) {
  1105. arr = byAttr(matches[1].toLowerCase(), null, tag, root);
  1106. } else if ((matches = /\[((?:[\w\-]|\\.)+)\s*=\s*['"]?((?:\\.|[^'"]+)+)['"]?\]/.exec(expr))) {
  1107. var key = matches[1].toLowerCase(), val = matches[2];
  1108. if (key === 'id') {
  1109. arr = byId(val, tag, root);
  1110. } else if (key === 'class') {
  1111. arr = byClass(val, tag, root);
  1112. } else if (key === 'name') {
  1113. arr = byName(val, tag, root);
  1114. } else {
  1115. arr = byAttr(key, val, tag, root);
  1116. }
  1117. } else {
  1118. var els = root.getElementsByTagName(tag), el;
  1119. for (var i = 0, len = els.length; i < len; i++) {
  1120. el = els[i];
  1121. if (el.nodeType == 1) {
  1122. arr.push(el);
  1123. }
  1124. }
  1125. }
  1126. return arr;
  1127. }
  1128. var parts = [], arr, re = /((?:\\.|[^\s>])+|[\s>])/g;
  1129. while ((arr = re.exec(expr))) {
  1130. if (arr[1] !== ' ') {
  1131. parts.push(arr[1]);
  1132. }
  1133. }
  1134. var results = [];
  1135. if (parts.length == 1) {
  1136. return select(parts[0], root);
  1137. }
  1138. var isChild = false, part, els, subResults, val, v, i, j, k, length, len, l;
  1139. for (i = 0, lenth = parts.length; i < lenth; i++) {
  1140. part = parts[i];
  1141. if (part === '>') {
  1142. isChild = true;
  1143. continue;
  1144. }
  1145. if (i > 0) {
  1146. els = [];
  1147. for (j = 0, len = results.length; j < len; j++) {
  1148. val = results[j];
  1149. subResults = select(part, val);
  1150. for (k = 0, l = subResults.length; k < l; k++) {
  1151. v = subResults[k];
  1152. if (isChild) {
  1153. if (val === v.parentNode) {
  1154. els.push(v);
  1155. }
  1156. } else {
  1157. els.push(v);
  1158. }
  1159. }
  1160. }
  1161. results = els;
  1162. } else {
  1163. results = select(part, root);
  1164. }
  1165. if (results.length === 0) {
  1166. return [];
  1167. }
  1168. }
  1169. return results;
  1170. }
  1171. function _query(expr, root) {
  1172. var arr = _queryAll(expr, root);
  1173. return arr.length > 0 ? arr[0] : null;
  1174. }
  1175. K.query = _query;
  1176. K.queryAll = _queryAll;
  1177. function _get(val) {
  1178. return K(val)[0];
  1179. }
  1180. function _getDoc(node) {
  1181. if (!node) {
  1182. return document;
  1183. }
  1184. return node.ownerDocument || node.document || node;
  1185. }
  1186. function _getWin(node) {
  1187. if (!node) {
  1188. return window;
  1189. }
  1190. var doc = _getDoc(node);
  1191. return doc.parentWindow || doc.defaultView;
  1192. }
  1193. function _setHtml(el, html) {
  1194. if (el.nodeType != 1) {
  1195. return;
  1196. }
  1197. var doc = _getDoc(el);
  1198. try {
  1199. el.innerHTML = '<img id="__kindeditor_temp_tag__" width="0" height="0" style="display:none;" />' + html;
  1200. var temp = doc.getElementById('__kindeditor_temp_tag__');
  1201. temp.parentNode.removeChild(temp);
  1202. } catch(e) {
  1203. K(el).empty();
  1204. K('@' + html, doc).each(function() {
  1205. el.appendChild(this);
  1206. });
  1207. }
  1208. }
  1209. function _hasClass(el, cls) {
  1210. return _inString(cls, el.className, ' ');
  1211. }
  1212. function _setAttr(el, key, val) {
  1213. if (_IE && _V < 8 && key.toLowerCase() == 'class') {
  1214. key = 'className';
  1215. }
  1216. el.setAttribute(key, '' + val);
  1217. }
  1218. function _removeAttr(el, key) {
  1219. if (_IE && _V < 8 && key.toLowerCase() == 'class') {
  1220. key = 'className';
  1221. }
  1222. _setAttr(el, key, '');
  1223. el.removeAttribute(key);
  1224. }
  1225. function _getNodeName(node) {
  1226. if (!node || !node.nodeName) {
  1227. return '';
  1228. }
  1229. return node.nodeName.toLowerCase();
  1230. }
  1231. function _computedCss(el, key) {
  1232. var self = this, win = _getWin(el), camelKey = _toCamel(key), val = '';
  1233. if (win.getComputedStyle) {
  1234. var style = win.getComputedStyle(el, null);
  1235. val = style[camelKey] || style.getPropertyValue(key) || el.style[camelKey];
  1236. } else if (el.currentStyle) {
  1237. val = el.currentStyle[camelKey] || el.style[camelKey];
  1238. }
  1239. return val;
  1240. }
  1241. function _hasVal(node) {
  1242. return !!_VALUE_TAG_MAP[_getNodeName(node)];
  1243. }
  1244. function _docElement(doc) {
  1245. doc = doc || document;
  1246. return _QUIRKS ? doc.body : doc.documentElement;
  1247. }
  1248. function _docHeight(doc) {
  1249. var el = _docElement(doc);
  1250. return Math.max(el.scrollHeight, el.clientHeight);
  1251. }
  1252. function _docWidth(doc) {
  1253. var el = _docElement(doc);
  1254. return Math.max(el.scrollWidth, el.clientWidth);
  1255. }
  1256. function _getScrollPos(doc) {
  1257. doc = doc || document;
  1258. var x, y;
  1259. if (_IE || _OPERA) {
  1260. x = _docElement(doc).scrollLeft;
  1261. y = _docElement(doc).scrollTop;
  1262. } else {
  1263. x = _getWin(doc).scrollX;
  1264. y = _getWin(doc).scrollY;
  1265. }
  1266. return {x : x, y : y};
  1267. }
  1268. function KNode(node) {
  1269. this.init(node);
  1270. }
  1271. _extend(KNode, {
  1272. init : function(node) {
  1273. var self = this;
  1274. node = _isArray(node) ? node : [node];
  1275. var length = 0;
  1276. for (var i = 0, len = node.length; i < len; i++) {
  1277. if (node[i]) {
  1278. self[i] = node[i].constructor === KNode ? node[i][0] : node[i];
  1279. length++;
  1280. }
  1281. }
  1282. self.length = length;
  1283. self.doc = _getDoc(self[0]);
  1284. self.name = _getNodeName(self[0]);
  1285. self.type = self.length > 0 ? self[0].nodeType : null;
  1286. self.win = _getWin(self[0]);
  1287. },
  1288. each : function(fn) {
  1289. var self = this;
  1290. for (var i = 0; i < self.length; i++) {
  1291. if (fn.call(self[i], i, self[i]) === false) {
  1292. return self;
  1293. }
  1294. }
  1295. return self;
  1296. },
  1297. bind : function(type, fn) {
  1298. this.each(function() {
  1299. _bind(this, type, fn);
  1300. });
  1301. return this;
  1302. },
  1303. unbind : function(type, fn) {
  1304. this.each(function() {
  1305. _unbind(this, type, fn);
  1306. });
  1307. return this;
  1308. },
  1309. fire : function(type) {
  1310. if (this.length < 1) {
  1311. return this;
  1312. }
  1313. _fire(this[0], type);
  1314. return this;
  1315. },
  1316. hasAttr : function(key) {
  1317. if (this.length < 1) {
  1318. return false;
  1319. }
  1320. return !!_getAttr(this[0], key);
  1321. },
  1322. attr : function(key, val) {
  1323. var self = this;
  1324. if (key === undefined) {
  1325. return _getAttrList(self.outer());
  1326. }
  1327. if (typeof key === 'object') {
  1328. _each(key, function(k, v) {
  1329. self.attr(k, v);
  1330. });
  1331. return self;
  1332. }
  1333. if (val === undefined) {
  1334. val = self.length < 1 ? null : _getAttr(self[0], key);
  1335. return val === null ? '' : val;
  1336. }
  1337. self.each(function() {
  1338. _setAttr(this, key, val);
  1339. });
  1340. return self;
  1341. },
  1342. removeAttr : function(key) {
  1343. this.each(function() {
  1344. _removeAttr(this, key);
  1345. });
  1346. return this;
  1347. },
  1348. get : function(i) {
  1349. if (this.length < 1) {
  1350. return null;
  1351. }
  1352. return this[i || 0];
  1353. },
  1354. eq : function(i) {
  1355. if (this.length < 1) {
  1356. return null;
  1357. }
  1358. return this[i] ? new KNode(this[i]) : null;
  1359. },
  1360. hasClass : function(cls) {
  1361. if (this.length < 1) {
  1362. return false;
  1363. }
  1364. return _hasClass(this[0], cls);
  1365. },
  1366. addClass : function(cls) {
  1367. this.each(function() {
  1368. if (!_hasClass(this, cls)) {
  1369. this.className = _trim(this.className + ' ' + cls);
  1370. }
  1371. });
  1372. return this;
  1373. },
  1374. removeClass : function(cls) {
  1375. this.each(function() {
  1376. if (_hasClass(this, cls)) {
  1377. this.className = _trim(this.className.replace(new RegExp('(^|\\s)' + cls + '(\\s|$)'), ' '));
  1378. }
  1379. });
  1380. return this;
  1381. },
  1382. html : function(val) {
  1383. var self = this;
  1384. if (val === undefined) {
  1385. if (self.length < 1 || self.type != 1) {
  1386. return '';
  1387. }
  1388. return _formatHtml(self[0].innerHTML);
  1389. }
  1390. self.each(function() {
  1391. _setHtml(this, val);
  1392. });
  1393. return self;
  1394. },
  1395. text : function() {
  1396. var self = this;
  1397. if (self.length < 1) {
  1398. return '';
  1399. }
  1400. return _IE ? self[0].innerText : self[0].textContent;
  1401. },
  1402. hasVal : function() {
  1403. if (this.length < 1) {
  1404. return false;
  1405. }
  1406. return _hasVal(this[0]);
  1407. },
  1408. val : function(val) {
  1409. var self = this;
  1410. if (val === undefined) {
  1411. if (self.length < 1) {
  1412. return '';
  1413. }
  1414. return self.hasVal() ? self[0].value : self.attr('value');
  1415. } else {
  1416. self.each(function() {
  1417. if (_hasVal(this)) {
  1418. this.value = val;
  1419. } else {
  1420. _setAttr(this, 'value' , val);
  1421. }
  1422. });
  1423. return self;
  1424. }
  1425. },
  1426. css : function(key, val) {
  1427. var self = this;
  1428. if (key === undefined) {
  1429. return _getCssList(self.attr('style'));
  1430. }
  1431. if (typeof key === 'object') {
  1432. _each(key, function(k, v) {
  1433. self.css(k, v);
  1434. });
  1435. return self;
  1436. }
  1437. if (val === undefined) {
  1438. if (self.length < 1) {
  1439. return '';
  1440. }
  1441. return self[0].style[_toCamel(key)] || _computedCss(self[0], key) || '';
  1442. }
  1443. self.each(function() {
  1444. this.style[_toCamel(key)] = val;
  1445. });
  1446. return self;
  1447. },
  1448. width : function(val) {
  1449. var self = this;
  1450. if (val === undefined) {
  1451. if (self.length < 1) {
  1452. return 0;
  1453. }
  1454. return self[0].offsetWidth;
  1455. }
  1456. return self.css('width', _addUnit(val));
  1457. },
  1458. height : function(val) {
  1459. var self = this;
  1460. if (val === undefined) {
  1461. if (self.length < 1) {
  1462. return 0;
  1463. }
  1464. return self[0].offsetHeight;
  1465. }
  1466. return self.css('height', _addUnit(val));
  1467. },
  1468. opacity : function(val) {
  1469. this.each(function() {
  1470. if (this.style.opacity === undefined) {
  1471. this.style.filter = val == 1 ? '' : 'alpha(opacity=' + (val * 100) + ')';
  1472. } else {
  1473. this.style.opacity = val == 1 ? '' : val;
  1474. }
  1475. });
  1476. return this;
  1477. },
  1478. data : function(key, val) {
  1479. var self = this;
  1480. key = 'kindeditor_data_' + key;
  1481. if (val === undefined) {
  1482. if (self.length < 1) {
  1483. return null;
  1484. }
  1485. return self[0][key];
  1486. }
  1487. this.each(function() {
  1488. this[key] = val;
  1489. });
  1490. return self;
  1491. },
  1492. pos : function() {
  1493. var self = this, node = self[0], x = 0, y = 0;
  1494. if (node) {
  1495. if (node.getBoundingClientRect) {
  1496. var box = node.getBoundingClientRect(),
  1497. pos = _getScrollPos(self.doc);
  1498. x = box.left + pos.x;
  1499. y = box.top + pos.y;
  1500. } else {
  1501. while (node) {
  1502. x += node.offsetLeft;
  1503. y += node.offsetTop;
  1504. node = node.offsetParent;
  1505. }
  1506. }
  1507. }
  1508. return {x : _round(x), y : _round(y)};
  1509. },
  1510. clone : function(bool) {
  1511. if (this.length < 1) {
  1512. return new KNode([]);
  1513. }
  1514. return new KNode(this[0].cloneNode(bool));
  1515. },
  1516. append : function(expr) {
  1517. this.each(function() {
  1518. if (this.appendChild) {
  1519. this.appendChild(_get(expr));
  1520. }
  1521. });
  1522. return this;
  1523. },
  1524. appendTo : function(expr) {
  1525. this.each(function() {
  1526. _get(expr).appendChild(this);
  1527. });
  1528. return this;
  1529. },
  1530. before : function(expr) {
  1531. this.each(function() {
  1532. this.parentNode.insertBefore(_get(expr), this);
  1533. });
  1534. return this;
  1535. },
  1536. after : function(expr) {
  1537. this.each(function() {
  1538. if (this.nextSibling) {
  1539. this.parentNode.insertBefore(_get(expr), this.nextSibling);
  1540. } else {
  1541. this.parentNode.appendChild(_get(expr));
  1542. }
  1543. });
  1544. return this;
  1545. },
  1546. replaceWith : function(expr) {
  1547. var nodes = [];
  1548. this.each(function(i, node) {
  1549. _unbind(node);
  1550. var newNode = _get(expr);
  1551. node.parentNode.replaceChild(newNode, node);
  1552. nodes.push(newNode);
  1553. });
  1554. return K(nodes);
  1555. },
  1556. empty : function() {
  1557. var self = this;
  1558. self.each(function(i, node) {
  1559. var child = node.firstChild;
  1560. while (child) {
  1561. if (!node.parentNode) {
  1562. return;
  1563. }
  1564. var next = child.nextSibling;
  1565. child.parentNode.removeChild(child);
  1566. child = next;
  1567. }
  1568. });
  1569. return self;
  1570. },
  1571. remove : function(keepChilds) {
  1572. var self = this;
  1573. self.each(function(i, node) {
  1574. if (!node.parentNode) {
  1575. return;
  1576. }
  1577. _unbind(node);
  1578. if (keepChilds) {
  1579. var child = node.firstChild;
  1580. while (child) {
  1581. var next = child.nextSibling;
  1582. node.parentNode.insertBefore(child, node);
  1583. child = next;
  1584. }
  1585. }
  1586. node.parentNode.removeChild(node);
  1587. delete self[i];
  1588. });
  1589. self.length = 0;
  1590. return self;
  1591. },
  1592. show : function(val) {
  1593. var self = this;
  1594. if (val === undefined) {
  1595. val = self._originDisplay || '';
  1596. }
  1597. if (self.css('display') != 'none') {
  1598. return self;
  1599. }
  1600. return self.css('display', val);
  1601. },
  1602. hide : function() {
  1603. var self = this;
  1604. if (self.length < 1) {
  1605. return self;
  1606. }
  1607. self._originDisplay = self[0].style.display;
  1608. return self.css('display', 'none');
  1609. },
  1610. outer : function() {
  1611. var self = this;
  1612. if (self.length < 1) {
  1613. return '';
  1614. }
  1615. var div = self.doc.createElement('div'), html;
  1616. div.appendChild(self[0].cloneNode(true));
  1617. html = _formatHtml(div.innerHTML);
  1618. div = null;
  1619. return html;
  1620. },
  1621. isSingle : function() {
  1622. return !!_SINGLE_TAG_MAP[this.name];
  1623. },
  1624. isInline : function() {
  1625. return !!_INLINE_TAG_MAP[this.name];
  1626. },
  1627. isBlock : function() {
  1628. return !!_BLOCK_TAG_MAP[this.name];
  1629. },
  1630. isStyle : function() {
  1631. return !!_STYLE_TAG_MAP[this.name];
  1632. },
  1633. isControl : function() {
  1634. return !!_CONTROL_TAG_MAP[this.name];
  1635. },
  1636. contains : function(otherNode) {
  1637. if (this.length < 1) {
  1638. return false;
  1639. }
  1640. return _contains(this[0], _get(otherNode));
  1641. },
  1642. parent : function() {
  1643. if (this.length < 1) {
  1644. return null;
  1645. }
  1646. var node = this[0].parentNode;
  1647. return node ? new KNode(node) : null;
  1648. },
  1649. children : function() {
  1650. if (this.length < 1) {
  1651. return new KNode([]);
  1652. }
  1653. var list = [], child = this[0].firstChild;
  1654. while (child) {
  1655. if (child.nodeType != 3 || _trim(child.nodeValue) !== '') {
  1656. list.push(child);
  1657. }
  1658. child = child.nextSibling;
  1659. }
  1660. return new KNode(list);
  1661. },
  1662. first : function() {
  1663. var list = this.children();
  1664. return list.length > 0 ? list.eq(0) : null;
  1665. },
  1666. last : function() {
  1667. var list = this.children();
  1668. return list.length > 0 ? list.eq(list.length - 1) : null;
  1669. },
  1670. index : function() {
  1671. if (this.length < 1) {
  1672. return -1;
  1673. }
  1674. var i = -1, sibling = this[0];
  1675. while (sibling) {
  1676. i++;
  1677. sibling = sibling.previousSibling;
  1678. }
  1679. return i;
  1680. },
  1681. prev : function() {
  1682. if (this.length < 1) {
  1683. return null;
  1684. }
  1685. var node = this[0].previousSibling;
  1686. return node ? new KNode(node) : null;
  1687. },
  1688. next : function() {
  1689. if (this.length < 1) {
  1690. return null;
  1691. }
  1692. var node = this[0].nextSibling;
  1693. return node ? new KNode(node) : null;
  1694. },
  1695. scan : function(fn, order) {
  1696. if (this.length < 1) {
  1697. return;
  1698. }
  1699. order = (order === undefined) ? true : order;
  1700. function walk(node) {
  1701. var n = order ? node.firstChild : node.lastChild;
  1702. while (n) {
  1703. var next = order ? n.nextSibling : n.previousSibling;
  1704. if (fn(n) === false) {
  1705. return false;
  1706. }
  1707. if (walk(n) === false) {
  1708. return false;
  1709. }
  1710. n = next;
  1711. }
  1712. }
  1713. walk(this[0]);
  1714. return this;
  1715. }
  1716. });
  1717. _each(('blur,focus,focusin,focusout,load,resize,scroll,unload,click,dblclick,' +
  1718. 'mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave,' +
  1719. 'change,select,submit,keydown,keypress,keyup,error,contextmenu').split(','), function(i, type) {
  1720. KNode.prototype[type] = function(fn) {
  1721. return fn ? this.bind(type, fn) : this.fire(type);
  1722. };
  1723. });
  1724. var _K = K;
  1725. K = function(expr, root) {
  1726. if (expr === undefined || expr === null) {
  1727. return;
  1728. }
  1729. function newNode(node) {
  1730. if (!node[0]) {
  1731. node = [];
  1732. }
  1733. return new KNode(node);
  1734. }
  1735. if (typeof expr === 'string') {
  1736. if (root) {
  1737. root = _get(root);
  1738. }
  1739. var length = expr.length;
  1740. if (expr.charAt(0) === '@') {
  1741. expr = expr.substr(1);
  1742. }
  1743. if (expr.length !== length || /<.+>/.test(expr)) {
  1744. var doc = root ? root.ownerDocument || root : document,
  1745. div = doc.createElement('div'), list = [];
  1746. div.innerHTML = '<img id="__kindeditor_temp_tag__" width="0" height="0" style="display:none;" />' + expr;
  1747. for (var i = 0, len = div.childNodes.length; i < len; i++) {
  1748. var child = div.childNodes[i];
  1749. if (child.id == '__kindeditor_temp_tag__') {
  1750. continue;
  1751. }
  1752. list.push(child);
  1753. }
  1754. return newNode(list);
  1755. }
  1756. return newNode(_queryAll(expr, root));
  1757. }
  1758. if (expr && expr.constructor === KNode) {
  1759. return expr;
  1760. }
  1761. if (expr.toArray) {
  1762. expr = expr.toArray();
  1763. }
  1764. if (_isArray(expr)) {
  1765. return newNode(expr);
  1766. }
  1767. return newNode(_toArray(arguments));
  1768. };
  1769. _each(_K, function(key, val) {
  1770. K[key] = val;
  1771. });
  1772. K.NodeClass = KNode;
  1773. window.KindEditor = K;
  1774. var _START_TO_START = 0,
  1775. _START_TO_END = 1,
  1776. _END_TO_END = 2,
  1777. _END_TO_START = 3,
  1778. _BOOKMARK_ID = 0;
  1779. function _updateCollapsed(range) {
  1780. range.collapsed = (range.startContainer === range.endContainer && range.startOffset === range.endOffset);
  1781. return range;
  1782. }
  1783. function _copyAndDelete(range, isCopy, isDelete) {
  1784. var doc = range.doc, nodeList = [];
  1785. function splitTextNode(node, startOffset, endOffset) {
  1786. var length = node.nodeValue.length, centerNode;
  1787. if (isCopy) {
  1788. var cloneNode = node.cloneNode(true);
  1789. if (startOffset > 0) {
  1790. centerNode = cloneNode.splitText(startOffset);
  1791. } else {
  1792. centerNode = cloneNode;
  1793. }
  1794. if (endOffset < length) {
  1795. centerNode.splitText(endOffset - startOffset);
  1796. }
  1797. }
  1798. if (isDelete) {
  1799. var center = node;
  1800. if (startOffset > 0) {
  1801. center = node.splitText(startOffset);
  1802. range.setStart(node, startOffset);
  1803. }
  1804. if (endOffset < length) {
  1805. var right = center.splitText(endOffset - startOffset);
  1806. range.setEnd(right, 0);
  1807. }
  1808. nodeList.push(center);
  1809. }
  1810. return centerNode;
  1811. }
  1812. function removeNodes() {
  1813. if (isDelete) {
  1814. range.up().collapse(true);
  1815. }
  1816. for (var i = 0, len = nodeList.length; i < len; i++) {
  1817. var node = nodeList[i];
  1818. if (node.parentNode) {
  1819. node.parentNode.removeChild(node);
  1820. }
  1821. }
  1822. }
  1823. var copyRange = range.cloneRange().down();
  1824. var start = -1, incStart = -1, incEnd = -1, end = -1,
  1825. ancestor = range.commonAncestor(), frag = doc.createDocumentFragment();
  1826. if (ancestor.nodeType == 3) {
  1827. var textNode = splitTextNode(ancestor, range.startOffset, range.endOffset);
  1828. if (isCopy) {
  1829. frag.appendChild(textNode);
  1830. }
  1831. removeNodes();
  1832. return isCopy ? frag : range;
  1833. }
  1834. function extractNodes(parent, frag) {
  1835. var node = parent.firstChild, nextNode;
  1836. while (node) {
  1837. var testRange = new KRange(doc).selectNode(node);
  1838. start = testRange.compareBoundaryPoints(_START_TO_END, range);
  1839. if (start >= 0 && incStart <= 0) {
  1840. incStart = testRange.compareBoundaryPoints(_START_TO_START, range);
  1841. }
  1842. if (incStart >= 0 && incEnd <= 0) {
  1843. incEnd = testRange.compareBoundaryPoints(_END_TO_END, range);
  1844. }
  1845. if (incEnd >= 0 && end <= 0) {
  1846. end = testRange.compareBoundaryPoints(_END_TO_START, range);
  1847. }
  1848. if (end >= 0) {
  1849. return false;
  1850. }
  1851. nextNode = node.nextSibling;
  1852. if (start > 0) {
  1853. if (node.nodeType == 1) {
  1854. if (incStart >= 0 && incEnd <= 0) {
  1855. if (isCopy) {
  1856. frag.appendChild(node.cloneNode(true));
  1857. }
  1858. if (isDelete) {
  1859. nodeList.push(node);
  1860. }
  1861. } else {
  1862. var childFlag;
  1863. if (isCopy) {
  1864. childFlag = node.cloneNode(false);
  1865. frag.appendChild(childFlag);
  1866. }
  1867. if (extractNodes(node, childFlag) === false) {
  1868. return false;
  1869. }
  1870. }
  1871. } else if (node.nodeType == 3) {
  1872. var textNode;
  1873. if (node == copyRange.startContainer) {
  1874. textNode = splitTextNode(node, copyRange.startOffset, node.nodeValue.length);
  1875. } else if (node == copyRange.endContainer) {
  1876. textNode = splitTextNode(node, 0, copyRange.endOffset);
  1877. } else {
  1878. textNode = splitTextNode(node, 0, node.nodeValue.length);
  1879. }
  1880. if (isCopy) {
  1881. try {
  1882. frag.appendChild(textNode);
  1883. } catch(e) {}
  1884. }
  1885. }
  1886. }
  1887. node = nextNode;
  1888. }
  1889. }
  1890. extractNodes(ancestor, frag);
  1891. if (isDelete) {
  1892. range.up().collapse(true);
  1893. }
  1894. for (var i = 0, len = nodeList.length; i < len; i++) {
  1895. var node = nodeList[i];
  1896. if (node.parentNode) {
  1897. node.parentNode.removeChild(node);
  1898. }
  1899. }
  1900. return isCopy ? frag : range;
  1901. }
  1902. function _moveToElementText(range, el) {
  1903. var node = el;
  1904. while (node) {
  1905. var knode = K(node);
  1906. if (knode.name == 'marquee' || knode.name == 'select') {
  1907. return;
  1908. }
  1909. node = node.parentNode;
  1910. }
  1911. try {
  1912. range.moveToElementText(el);
  1913. } catch(e) {}
  1914. }
  1915. function _getStartEnd(rng, isStart) {
  1916. var doc = rng.parentElement().ownerDocument,
  1917. pointRange = rng.duplicate();
  1918. pointRange.collapse(isStart);
  1919. var parent = pointRange.parentElement(),
  1920. nodes = parent.childNodes;
  1921. if (nodes.length === 0) {
  1922. return {node: parent.parentNode, offset: K(parent).index()};
  1923. }
  1924. var startNode = doc, startPos = 0, cmp = -1;
  1925. var testRange = rng.duplicate();
  1926. _moveToElementText(testRange, parent);
  1927. for (var i = 0, len = nodes.length; i < len; i++) {
  1928. var node = nodes[i];
  1929. cmp = testRange.compareEndPoints('StartToStart', pointRange);
  1930. if (cmp === 0) {
  1931. return {node: node.parentNode, offset: i};
  1932. }
  1933. if (node.nodeType == 1) {
  1934. var nodeRange = rng.duplicate(), dummy, knode = K(node), newNode = node;
  1935. if (knode.isControl()) {
  1936. dummy = doc.createElement('span');
  1937. knode.after(dummy);
  1938. newNode = dummy;
  1939. startPos += knode.text().replace(/\r\n|\n|\r/g, '').length;
  1940. }
  1941. _moveToElementText(nodeRange, newNode);
  1942. testRange.setEndPoint('StartToEnd', nodeRange);
  1943. if (cmp > 0) {
  1944. startPos += nodeRange.text.replace(/\r\n|\n|\r/g, '').length;
  1945. } else {
  1946. startPos = 0;
  1947. }
  1948. if (dummy) {
  1949. K(dummy).remove();
  1950. }
  1951. } else if (node.nodeType == 3) {
  1952. testRange.moveStart('character', node.nodeValue.length);
  1953. startPos += node.nodeValue.length;
  1954. }
  1955. if (cmp < 0) {
  1956. startNode = node;
  1957. }
  1958. }
  1959. if (cmp < 0 && startNode.nodeType == 1) {
  1960. return {node: parent, offset: K(parent.lastChild).index() + 1};
  1961. }
  1962. if (cmp > 0) {
  1963. while (startNode.nextSibling && startNode.nodeType == 1) {
  1964. startNode = startNode.nextSibling;
  1965. }
  1966. }
  1967. testRange = rng.duplicate();
  1968. _moveToElementText(testRange, parent);
  1969. testRange.setEndPoint('StartToEnd', pointRange);
  1970. startPos -= testRange.text.replace(/\r\n|\n|\r/g, '').length;
  1971. if (cmp > 0 && startNode.nodeType == 3) {
  1972. var prevNode = startNode.previousSibling;
  1973. while (prevNode && prevNode.nodeType == 3) {
  1974. startPos -= prevNode.nodeValue.length;
  1975. prevNode = prevNode.previousSibling;
  1976. }
  1977. }
  1978. return {node: startNode, offset: startPos};
  1979. }
  1980. function _getEndRange(node, offset) {
  1981. var doc = node.ownerDocument || node,
  1982. range = doc.body.createTextRange();
  1983. if (doc == node) {
  1984. range.collapse(true);
  1985. return range;
  1986. }
  1987. if (node.nodeType == 1 && node.childNodes.length > 0) {
  1988. var children = node.childNodes, isStart, child;
  1989. if (offset === 0) {
  1990. child = children[0];
  1991. isStart = true;
  1992. } else {
  1993. child = children[offset - 1];
  1994. isStart = false;
  1995. }
  1996. if (!child) {
  1997. return range;
  1998. }
  1999. if (K(child).name === 'head') {
  2000. if (offset === 1) {
  2001. isStart = true;
  2002. }
  2003. if (offset === 2) {
  2004. isStart = false;
  2005. }
  2006. range.collapse(isStart);
  2007. return range;
  2008. }
  2009. if (child.nodeType == 1) {
  2010. var kchild = K(child), span;
  2011. if (kchild.isControl()) {
  2012. span = doc.createElement('span');
  2013. if (isStart) {
  2014. kchild.before(span);
  2015. } else {
  2016. kchild.after(span);
  2017. }
  2018. child = span;
  2019. }
  2020. _moveToElementText(range, child);
  2021. range.collapse(isStart);
  2022. if (span) {
  2023. K(span).remove();
  2024. }
  2025. return range;
  2026. }
  2027. node = child;
  2028. offset = isStart ? 0 : child.nodeValue.length;
  2029. }
  2030. var dummy = doc.createElement('span');
  2031. K(node).before(dummy);
  2032. _moveToElementText(range, dummy);
  2033. range.moveStart('character', offset);
  2034. K(dummy).remove();
  2035. return range;
  2036. }
  2037. function _toRange(rng) {
  2038. var doc, range;
  2039. function tr2td(start) {
  2040. if (K(start.node).name == 'tr') {
  2041. start.node = start.node.cells[start.offset];
  2042. start.offset = 0;
  2043. }
  2044. }
  2045. if (_IE) {
  2046. if (rng.item) {
  2047. doc = _getDoc(rng.item(0));
  2048. range = new KRange(doc);
  2049. range.selectNode(rng.item(0));
  2050. return range;
  2051. }
  2052. doc = rng.parentElement().ownerDocument;
  2053. var start = _getStartEnd(rng, true),
  2054. end = _getStartEnd(rng, false);
  2055. tr2td(start);
  2056. tr2td(end);
  2057. range = new KRange(doc);
  2058. range.setStart(start.node, start.offset);
  2059. range.setEnd(end.node, end.offset);
  2060. return range;
  2061. }
  2062. var startContainer = rng.startContainer;
  2063. doc = startContainer.ownerDocument || startContainer;
  2064. range = new KRange(doc);
  2065. range.setStart(startContainer, rng.startOffset);
  2066. range.setEnd(rng.endContainer, rng.endOffset);
  2067. return range;
  2068. }
  2069. function KRange(doc) {
  2070. this.init(doc);
  2071. }
  2072. _extend(KRange, {
  2073. init : function(doc) {
  2074. var self = this;
  2075. self.startContainer = doc;
  2076. self.startOffset = 0;
  2077. self.endContainer = doc;
  2078. self.endOffset = 0;
  2079. self.collapsed = true;
  2080. self.doc = doc;
  2081. },
  2082. commonAncestor : function() {
  2083. function getParents(node) {
  2084. var parents = [];
  2085. while (node) {
  2086. parents.push(node);
  2087. node = node.parentNode;
  2088. }
  2089. return parents;
  2090. }
  2091. var parentsA = getParents(this.startContainer),
  2092. parentsB = getParents(this.endContainer),
  2093. i = 0, lenA = parentsA.length, lenB = parentsB.length, parentA, parentB;
  2094. while (++i) {
  2095. parentA = parentsA[lenA - i];
  2096. parentB = parentsB[lenB - i];
  2097. if (!parentA || !parentB || parentA !== parentB) {
  2098. break;
  2099. }
  2100. }
  2101. return parentsA[lenA - i + 1];
  2102. },
  2103. setStart : function(node, offset) {
  2104. var self = this, doc = self.doc;
  2105. self.startContainer = node;
  2106. self.startOffset = offset;
  2107. if (self.endContainer === doc) {
  2108. self.endContainer = node;
  2109. self.endOffset = offset;
  2110. }
  2111. return _updateCollapsed(this);
  2112. },
  2113. setEnd : function(node, offset) {
  2114. var self = this, doc = self.doc;
  2115. self.endContainer = node;
  2116. self.endOffset = offset;
  2117. if (self.startContainer === doc) {
  2118. self.startContainer = node;
  2119. self.startOffset = offset;
  2120. }
  2121. return _updateCollapsed(this);
  2122. },
  2123. setStartBefore : function(node) {
  2124. return this.setStart(node.parentNode || this.doc, K(node).index());
  2125. },
  2126. setStartAfter : function(node) {
  2127. return this.setStart(node.parentNode || this.doc, K(node).index() + 1);
  2128. },
  2129. setEndBefore : function(node) {
  2130. return this.setEnd(node.parentNode || this.doc, K(node).index());
  2131. },
  2132. setEndAfter : function(node) {
  2133. return this.setEnd(node.parentNode || this.doc, K(node).index() + 1);
  2134. },
  2135. selectNode : function(node) {
  2136. return this.setStartBefore(node).setEndAfter(node);
  2137. },
  2138. selectNodeContents : function(node) {
  2139. var knode = K(node);
  2140. if (knode.type == 3 || knode.isSingle()) {
  2141. return this.selectNode(node);
  2142. }
  2143. var children = knode.children();
  2144. if (children.length > 0) {
  2145. return this.setStartBefore(children[0]).setEndAfter(children[children.length - 1]);
  2146. }
  2147. return this.setStart(node, 0).setEnd(node, 0);
  2148. },
  2149. collapse : function(toStart) {
  2150. if (toStart) {
  2151. return this.setEnd(this.startContainer, this.startOffset);
  2152. }
  2153. return this.setStart(this.endContainer, this.endOffset);
  2154. },
  2155. compareBoundaryPoints : function(how, range) {
  2156. var rangeA = this.get(), rangeB = range.get();
  2157. if (_IE) {
  2158. var arr = {};
  2159. arr[_START_TO_START] = 'StartToStart';
  2160. arr[_START_TO_END] = 'EndToStart';
  2161. arr[_END_TO_END] = 'EndToEnd';
  2162. arr[_END_TO_START] = 'StartToEnd';
  2163. var cmp = rangeA.compareEndPoints(arr[how], rangeB);
  2164. if (cmp !== 0) {
  2165. return cmp;
  2166. }
  2167. var nodeA, nodeB, nodeC, posA, posB;
  2168. if (how === _START_TO_START || how === _END_TO_START) {
  2169. nodeA = this.startContainer;
  2170. posA = this.startOffset;
  2171. }
  2172. if (how === _START_TO_END || how === _END_TO_END) {
  2173. nodeA = this.endContainer;
  2174. posA = this.endOffset;
  2175. }
  2176. if (how === _START_TO_START || how === _START_TO_END) {
  2177. nodeB = range.startContainer;
  2178. posB = range.startOffset;
  2179. }
  2180. if (how === _END_TO_END || how === _END_TO_START) {
  2181. nodeB = range.endContainer;
  2182. posB = range.endOffset;
  2183. }
  2184. if (nodeA === nodeB) {
  2185. var diff = posA - posB;
  2186. return diff > 0 ? 1 : (diff < 0 ? -1 : 0);
  2187. }
  2188. nodeC = nodeB;
  2189. while (nodeC && nodeC.parentNode !== nodeA) {
  2190. nodeC = nodeC.parentNode;
  2191. }
  2192. if (nodeC) {
  2193. return K(nodeC).index() >= posA ? -1 : 1;
  2194. }
  2195. nodeC = nodeA;
  2196. while (nodeC && nodeC.parentNode !== nodeB) {
  2197. nodeC = nodeC.parentNode;
  2198. }
  2199. if (nodeC) {
  2200. return K(nodeC).index() >= posB ? 1 : -1;
  2201. }
  2202. nodeC = K(nodeB).next();
  2203. if (nodeC && nodeC.contains(nodeA)) {
  2204. return 1;
  2205. }
  2206. nodeC = K(nodeA).next();
  2207. if (nodeC && nodeC.contains(nodeB)) {
  2208. return -1;
  2209. }
  2210. } else {
  2211. return rangeA.compareBoundaryPoints(how, rangeB);
  2212. }
  2213. },
  2214. cloneRange : function() {
  2215. return new KRange(this.doc).setStart(this.startContainer, this.startOffset).setEnd(this.endContainer, this.endOffset);
  2216. },
  2217. toString : function() {
  2218. var rng = this.get(), str = _IE ? rng.text : rng.toString();
  2219. return str.replace(/\r\n|\n|\r/g, '');
  2220. },
  2221. cloneContents : function() {
  2222. return _copyAndDelete(this, true, false);
  2223. },
  2224. deleteContents : function() {
  2225. return _copyAndDelete(this, false, true);
  2226. },
  2227. extractContents : function() {
  2228. return _copyAndDelete(this, true, true);
  2229. },
  2230. insertNode : function(node) {
  2231. var self = this,
  2232. sc = self.startContainer, so = self.startOffset,
  2233. ec = self.endContainer, eo = self.endOffset,
  2234. firstChild, lastChild, c, nodeCount = 1;
  2235. if (node.nodeName.toLowerCase() === '#document-fragment') {
  2236. firstChild = node.firstChild;
  2237. lastChild = node.lastChild;
  2238. nodeCount = node.childNodes.length;
  2239. }
  2240. if (sc.nodeType == 1) {
  2241. c = sc.childNodes[so];
  2242. if (c) {
  2243. sc.insertBefore(node, c);
  2244. if (sc === ec) {
  2245. eo += nodeCount;
  2246. }
  2247. } else {
  2248. sc.appendChild(node);
  2249. }
  2250. } else if (sc.nodeType == 3) {
  2251. if (so === 0) {
  2252. sc.parentNode.insertBefore(node, sc);
  2253. if (sc.parentNode === ec) {
  2254. eo += nodeCount;
  2255. }
  2256. } else if (so >= sc.nodeValue.length) {
  2257. if (sc.nextSibling) {
  2258. sc.parentNode.insertBefore(node, sc.nextSibling);
  2259. } else {
  2260. sc.parentNode.appendChild(node);
  2261. }
  2262. } else {
  2263. if (so > 0) {
  2264. c = sc.splitText(so);
  2265. } else {
  2266. c = sc;
  2267. }
  2268. sc.parentNode.insertBefore(node, c);
  2269. if (sc === ec) {
  2270. ec = c;
  2271. eo -= so;
  2272. }
  2273. }
  2274. }
  2275. if (firstChild) {
  2276. self.setStartBefore(firstChild).setEndAfter(lastChild);
  2277. } else {
  2278. self.selectNode(node);
  2279. }
  2280. if (self.compareBoundaryPoints(_END_TO_END, self.cloneRange().setEnd(ec, eo)) >= 1) {
  2281. return self;
  2282. }
  2283. return self.setEnd(ec, eo);
  2284. },
  2285. surroundContents : function(node) {
  2286. node.appendChild(this.extractContents());
  2287. return this.insertNode(node).selectNode(node);
  2288. },
  2289. isControl : function() {
  2290. var self = this,
  2291. sc = self.startContainer, so = self.startOffset,
  2292. ec = self.endContainer, eo = self.endOffset, rng;
  2293. return sc.nodeType == 1 && sc === ec && so + 1 === eo && K(sc.childNodes[so]).isControl();
  2294. },
  2295. get : function(hasControlRange) {
  2296. var self = this, doc = self.doc, node, rng;
  2297. if (!_IE) {
  2298. rng = doc.createRange();
  2299. try {
  2300. rng.setStart(self.startContainer, self.startOffset);
  2301. rng.setEnd(self.endContainer, self.endOffset);
  2302. } catch (e) {}
  2303. return rng;
  2304. }
  2305. if (hasControlRange && self.isControl()) {
  2306. rng = doc.body.createControlRange();
  2307. rng.addElement(self.startContainer.childNodes[self.startOffset]);
  2308. return rng;
  2309. }
  2310. var range = self.cloneRange().down();
  2311. rng = doc.body.createTextRange();
  2312. rng.setEndPoint('StartToStart', _getEndRange(range.startContainer, range.startOffset));
  2313. rng.setEndPoint('EndToStart', _getEndRange(range.endContainer, range.endOffset));
  2314. return rng;
  2315. },
  2316. html : function() {
  2317. return K(this.cloneContents()).outer();
  2318. },
  2319. down : function() {
  2320. var self = this;
  2321. function downPos(node, pos, isStart) {
  2322. if (node.nodeType != 1) {
  2323. return;
  2324. }
  2325. var children = K(node).children();
  2326. if (children.length === 0) {
  2327. return;
  2328. }
  2329. var left, right, child, offset;
  2330. if (pos > 0) {
  2331. left = children.eq(pos - 1);
  2332. }
  2333. if (pos < children.length) {
  2334. right = children.eq(pos);
  2335. }
  2336. if (left && left.type == 3) {
  2337. child = left[0];
  2338. offset = child.nodeValue.length;
  2339. }
  2340. if (right && right.type == 3) {
  2341. child = right[0];
  2342. offset = 0;
  2343. }
  2344. if (!child) {
  2345. return;
  2346. }
  2347. if (isStart) {
  2348. self.setStart(child, offset);
  2349. } else {
  2350. self.setEnd(child, offset);
  2351. }
  2352. }
  2353. downPos(self.startContainer, self.startOffset, true);
  2354. downPos(self.endContainer, self.endOffset, false);
  2355. return self;
  2356. },
  2357. up : function() {
  2358. var self = this;
  2359. function upPos(node, pos, isStart) {
  2360. if (node.nodeType != 3) {
  2361. return;
  2362. }
  2363. if (pos === 0) {
  2364. if (isStart) {
  2365. self.setStartBefore(node);
  2366. } else {
  2367. self.setEndBefore(node);
  2368. }
  2369. } else if (pos == node.nodeValue.length) {
  2370. if (isStart) {
  2371. self.setStartAfter(node);
  2372. } else {
  2373. self.setEndAfter(node);
  2374. }
  2375. }
  2376. }
  2377. upPos(self.startContainer, self.startOffset, true);
  2378. upPos(self.endContainer, self.endOffset, false);
  2379. return self;
  2380. },
  2381. enlarge : function(toBlock) {
  2382. var self = this;
  2383. self.up();
  2384. function enlargePos(node, pos, isStart) {
  2385. var knode = K(node), parent;
  2386. if (knode.type == 3 || _NOSPLIT_TAG_MAP[knode.name] || !toBlock && knode.isBlock()) {
  2387. return;
  2388. }
  2389. if (pos === 0) {
  2390. while (!knode.prev()) {
  2391. parent = knode.parent();
  2392. if (!parent || _NOSPLIT_TAG_MAP[parent.name] || !toBlock && parent.isBlock()) {
  2393. break;
  2394. }
  2395. knode = parent;
  2396. }
  2397. if (isStart) {
  2398. self.setStartBefore(knode[0]);
  2399. } else {
  2400. self.setEndBefore(knode[0]);
  2401. }
  2402. } else if (pos == knode.children().length) {
  2403. while (!knode.next()) {
  2404. parent = knode.parent();
  2405. if (!parent || _NOSPLIT_TAG_MAP[parent.name] || !toBlock && parent.isBlock()) {
  2406. break;
  2407. }
  2408. knode = parent;
  2409. }
  2410. if (isStart) {
  2411. self.setStartAfter(knode[0]);
  2412. } else {
  2413. self.setEndAfter(knode[0]);
  2414. }
  2415. }
  2416. }
  2417. enlargePos(self.startContainer, self.startOffset, true);
  2418. enlargePos(self.endContainer, self.endOffset, false);
  2419. return self;
  2420. },
  2421. shrink : function() {
  2422. var self = this, child, collapsed = self.collapsed;
  2423. while (self.startContainer.nodeType == 1 && (child = self.startContainer.childNodes[self.startOffset]) && child.nodeType == 1 && !K(child).isSingle()) {
  2424. self.setStart(child, 0);
  2425. }
  2426. if (collapsed) {
  2427. return self.collapse(collapsed);
  2428. }
  2429. while (self.endContainer.nodeType == 1 && self.endOffset > 0 && (child = self.endContainer.childNodes[self.endOffset - 1]) && child.nodeType == 1 && !K(child).isSingle()) {
  2430. self.setEnd(child, child.childNodes.length);
  2431. }
  2432. return self;
  2433. },
  2434. createBookmark : function(serialize) {
  2435. var self = this, doc = self.doc, endNode,
  2436. startNode = K('<span style="display:none;"></span>', doc)[0];
  2437. startNode.id = '__kindeditor_bookmark_start_' + (_BOOKMARK_ID++) + '__';
  2438. if (!self.collapsed) {
  2439. endNode = startNode.cloneNode(true);
  2440. endNode.id = '__kindeditor_bookmark_end_' + (_BOOKMARK_ID++) + '__';
  2441. }
  2442. if (endNode) {
  2443. self.cloneRange().collapse(false).insertNode(endNode).setEndBefore(endNode);
  2444. }
  2445. self.insertNode(startNode).setStartAfter(startNode);
  2446. return {
  2447. start : serialize ? '#' + startNode.id : startNode,
  2448. end : endNode ? (serialize ? '#' + endNode.id : endNode) : null
  2449. };
  2450. },
  2451. moveToBookmark : function(bookmark) {
  2452. var self = this, doc = self.doc,
  2453. start = K(bookmark.start, doc), end = bookmark.end ? K(bookmark.end, doc) : null;
  2454. if (!start || start.length < 1) {
  2455. return self;
  2456. }
  2457. self.setStartBefore(start[0]);
  2458. start.remove();
  2459. if (end && end.length > 0) {
  2460. self.setEndBefore(end[0]);
  2461. end.remove();
  2462. } else {
  2463. self.collapse(true);
  2464. }
  2465. return self;
  2466. },
  2467. dump : function() {
  2468. console.log('--------------------');
  2469. console.log(this.startContainer.nodeType == 3 ? this.startContainer.nodeValue : this.startContainer, this.startOffset);
  2470. console.log(this.endContainer.nodeType == 3 ? this.endContainer.nodeValue : this.endContainer, this.endOffset);
  2471. }
  2472. });
  2473. function _range(mixed) {
  2474. if (!mixed.nodeName) {
  2475. return mixed.constructor === KRange ? mixed : _toRange(mixed);
  2476. }
  2477. return new KRange(mixed);
  2478. }
  2479. K.RangeClass = KRange;
  2480. K.range = _range;
  2481. K.START_TO_START = _START_TO_START;
  2482. K.START_TO_END = _START_TO_END;
  2483. K.END_TO_END = _END_TO_END;
  2484. K.END_TO_START = _END_TO_START;
  2485. function _nativeCommand(doc, key, val) {
  2486. try {
  2487. doc.execCommand(key, false, val);
  2488. } catch(e) {}
  2489. }
  2490. function _nativeCommandValue(doc, key) {
  2491. var val = '';
  2492. try {
  2493. val = doc.queryCommandValue(key);
  2494. } catch (e) {}
  2495. if (typeof val !== 'string') {
  2496. val = '';
  2497. }
  2498. return val;
  2499. }
  2500. function _getSel(doc) {
  2501. var win = _getWin(doc);
  2502. return doc.selection || win.getSelection();
  2503. }
  2504. function _getRng(doc) {
  2505. var sel = _getSel(doc), rng;
  2506. try {
  2507. if (sel.rangeCount > 0) {
  2508. rng = sel.getRangeAt(0);
  2509. } else {
  2510. rng = sel.createRange();
  2511. }
  2512. } catch(e) {}
  2513. if (_IE && (!rng || (!rng.item && rng.parentElement().ownerDocument !== doc))) {
  2514. return null;
  2515. }
  2516. return rng;
  2517. }
  2518. function _singleKeyMap(map) {
  2519. var newMap = {}, arr, v;
  2520. _each(map, function(key, val) {
  2521. arr = key.split(',');
  2522. for (var i = 0, len = arr.length; i < len; i++) {
  2523. v = arr[i];
  2524. newMap[v] = val;
  2525. }
  2526. });
  2527. return newMap;
  2528. }
  2529. function _hasAttrOrCss(knode, map) {
  2530. return _hasAttrOrCssByKey(knode, map, '*') || _hasAttrOrCssByKey(knode, map);
  2531. }
  2532. function _hasAttrOrCssByKey(knode, map, mapKey) {
  2533. mapKey = mapKey || knode.name;
  2534. if (knode.type !== 1) {
  2535. return false;
  2536. }
  2537. var newMap = _singleKeyMap(map);
  2538. if (!newMap[mapKey]) {
  2539. return false;
  2540. }
  2541. var arr = newMap[mapKey].split(',');
  2542. for (var i = 0, len = arr.length; i < len; i++) {
  2543. var key = arr[i];
  2544. if (key === '*') {
  2545. return true;
  2546. }
  2547. var match = /^(\.?)([^=]+)(?:=([^=]*))?$/.exec(key);
  2548. var method = match[1] ? 'css' : 'attr';
  2549. key = match[2];
  2550. var val = match[3] || '';
  2551. if (val === '' && knode[method](key) !== '') {
  2552. return true;
  2553. }
  2554. if (val !== '' && knode[method](key) === val) {
  2555. return true;
  2556. }
  2557. }
  2558. return false;
  2559. }
  2560. function _removeAttrOrCss(knode, map) {
  2561. if (knode.type != 1) {
  2562. return;
  2563. }
  2564. _removeAttrOrCssByKey(knode, map, '*');
  2565. _removeAttrOrCssByKey(knode, map);
  2566. }
  2567. function _removeAttrOrCssByKey(knode, map, mapKey) {
  2568. mapKey = mapKey || knode.name;
  2569. if (knode.type !== 1) {
  2570. return;
  2571. }
  2572. var newMap = _singleKeyMap(map);
  2573. if (!newMap[mapKey]) {
  2574. return;
  2575. }
  2576. var arr = newMap[mapKey].split(','), allFlag = false;
  2577. for (var i = 0, len = arr.length; i < len; i++) {
  2578. var key = arr[i];
  2579. if (key === '*') {
  2580. allFlag = true;
  2581. break;
  2582. }
  2583. var match = /^(\.?)([^=]+)(?:=([^=]*))?$/.exec(key);
  2584. key = match[2];
  2585. if (match[1]) {
  2586. key = _toCamel(key);
  2587. if (knode[0].style[key]) {
  2588. knode[0].style[key] = '';
  2589. }
  2590. } else {
  2591. knode.removeAttr(key);
  2592. }
  2593. }
  2594. if (allFlag) {
  2595. knode.remove(true);
  2596. }
  2597. }
  2598. function _getInnerNode(knode) {
  2599. var inner = knode;
  2600. while (inner.first()) {
  2601. inner = inner.first();
  2602. }
  2603. return inner;
  2604. }
  2605. function _isEmptyNode(knode) {
  2606. if (knode.type != 1 || knode.isSingle()) {
  2607. return false;
  2608. }
  2609. return knode.html().replace(/<[^>]+>/g, '') === '';
  2610. }
  2611. function _mergeWrapper(a, b) {
  2612. a = a.clone(true);
  2613. var lastA = _getInnerNode(a), childA = a, merged = false;
  2614. while (b) {
  2615. while (childA) {
  2616. if (childA.name === b.name) {
  2617. _mergeAttrs(childA, b.attr(), b.css());
  2618. merged = true;
  2619. }
  2620. childA = childA.first();
  2621. }
  2622. if (!merged) {
  2623. lastA.append(b.clone(false));
  2624. }
  2625. merged = false;
  2626. b = b.first();
  2627. }
  2628. return a;
  2629. }
  2630. function _wrapNode(knode, wrapper) {
  2631. wrapper = wrapper.clone(true);
  2632. if (knode.type == 3) {
  2633. _getInnerNode(wrapper).append(knode.clone(false));
  2634. knode.replaceWith(wrapper);
  2635. return wrapper;
  2636. }
  2637. var nodeWrapper = knode, child;
  2638. while ((child = knode.first()) && child.children().length == 1) {
  2639. knode = child;
  2640. }
  2641. child = knode.first();
  2642. var frag = knode.doc.createDocumentFragment();
  2643. while (child) {
  2644. frag.appendChild(child[0]);
  2645. child = child.next();
  2646. }
  2647. wrapper = _mergeWrapper(nodeWrapper, wrapper);
  2648. if (frag.firstChild) {
  2649. _getInnerNode(wrapper).append(frag);
  2650. }
  2651. nodeWrapper.replaceWith(wrapper);
  2652. return wrapper;
  2653. }
  2654. function _mergeAttrs(knode, attrs, styles) {
  2655. _each(attrs, function(key, val) {
  2656. if (key !== 'style') {
  2657. knode.attr(key, val);
  2658. }
  2659. });
  2660. _each(styles, function(key, val) {
  2661. knode.css(key, val);
  2662. });
  2663. }
  2664. function _inPreElement(knode) {
  2665. while (knode && knode.name != 'body') {
  2666. if (_PRE_TAG_MAP[knode.name] || knode.name == 'div' && knode.hasClass('ke-script')) {
  2667. return true;
  2668. }
  2669. knode = knode.parent();
  2670. }
  2671. return false;
  2672. }
  2673. function KCmd(range) {
  2674. this.init(range);
  2675. }
  2676. _extend(KCmd, {
  2677. init : function(range) {
  2678. var self = this, doc = range.doc;
  2679. self.doc = doc;
  2680. self.win = _getWin(doc);
  2681. self.sel = _getSel(doc);
  2682. self.range = range;
  2683. },
  2684. selection : function(forceReset) {
  2685. var self = this, doc = self.doc, rng = _getRng(doc);
  2686. self.sel = _getSel(doc);
  2687. if (rng) {
  2688. self.range = _range(rng);
  2689. if (K(self.range.startContainer).name == 'html') {
  2690. self.range.selectNodeContents(doc.body).collapse(false);
  2691. }
  2692. return self;
  2693. }
  2694. if (forceReset) {
  2695. self.range.selectNodeContents(doc.body).collapse(false);
  2696. }
  2697. return self;
  2698. },
  2699. select : function(hasDummy) {
  2700. hasDummy = _undef(hasDummy, true);
  2701. var self = this, sel = self.sel, range = self.range.cloneRange().shrink(),
  2702. sc = range.startContainer, so = range.startOffset,
  2703. ec = range.endContainer, eo = range.endOffset,
  2704. doc = _getDoc(sc), win = self.win, rng, hasU200b = false;
  2705. if (hasDummy && sc.nodeType == 1 && range.collapsed) {
  2706. if (_IE) {
  2707. var dummy = K('<span>&nbsp;</span>', doc);
  2708. range.insertNode(dummy[0]);
  2709. rng = doc.body.createTextRange();
  2710. try {
  2711. rng.moveToElementText(dummy[0]);
  2712. } catch(ex) {}
  2713. rng.collapse(false);
  2714. rng.select();
  2715. dummy.remove();
  2716. win.focus();
  2717. return self;
  2718. }
  2719. if (_WEBKIT) {
  2720. var children = sc.childNodes;
  2721. if (K(sc).isInline() || so > 0 && K(children[so - 1]).isInline() || children[so] && K(children[so]).isInline()) {
  2722. range.insertNode(doc.createTextNode('\u200B'));
  2723. hasU200b = true;
  2724. }
  2725. }
  2726. }
  2727. if (_IE) {
  2728. try {
  2729. rng = range.get(true);
  2730. rng.select();
  2731. } catch(e) {}
  2732. } else {
  2733. if (hasU200b) {
  2734. range.collapse(false);
  2735. }
  2736. rng = range.get(true);
  2737. sel.removeAllRanges();
  2738. sel.addRange(rng);
  2739. if (doc !== document) {
  2740. var pos = K(rng.endContainer).pos();
  2741. win.scrollTo(pos.x, pos.y);
  2742. }
  2743. }
  2744. win.focus();
  2745. return self;
  2746. },
  2747. wrap : function(val) {
  2748. var self = this, doc = self.doc, range = self.range, wrapper;
  2749. wrapper = K(val, doc);
  2750. if (range.collapsed) {
  2751. range.shrink();
  2752. range.insertNode(wrapper[0]).selectNodeContents(wrapper[0]);
  2753. return self;
  2754. }
  2755. if (wrapper.isBlock()) {
  2756. var copyWrapper = wrapper.clone(true), child = copyWrapper;
  2757. while (child.first()) {
  2758. child = child.first();
  2759. }
  2760. child.append(range.extractContents());
  2761. range.insertNode(copyWrapper[0]).selectNode(copyWrapper[0]);
  2762. return self;
  2763. }
  2764. range.enlarge();
  2765. var bookmark = range.createBookmark(), ancestor = range.commonAncestor(), isStart = false;
  2766. K(ancestor).scan(function(node) {
  2767. if (!isStart && node == bookmark.start) {
  2768. isStart = true;
  2769. return;
  2770. }
  2771. if (isStart) {
  2772. if (node == bookmark.end) {
  2773. return false;
  2774. }
  2775. var knode = K(node);
  2776. if (_inPreElement(knode)) {
  2777. return;
  2778. }
  2779. if (knode.type == 3 && _trim(node.nodeValue).length > 0) {
  2780. var parent;
  2781. while ((parent = knode.parent()) && parent.isStyle() && parent.children().length == 1) {
  2782. knode = parent;
  2783. }
  2784. _wrapNode(knode, wrapper);
  2785. }
  2786. }
  2787. });
  2788. range.moveToBookmark(bookmark);
  2789. return self;
  2790. },
  2791. split : function(isStart, map) {
  2792. var range = this.range, doc = range.doc;
  2793. var tempRange = range.cloneRange().collapse(isStart);
  2794. var node = tempRange.startContainer, pos = tempRange.startOffset,
  2795. parent = node.nodeType == 3 ? node.parentNode : node,
  2796. needSplit = false, knode;
  2797. while (parent && parent.parentNode) {
  2798. knode = K(parent);
  2799. if (map) {
  2800. if (!knode.isStyle()) {
  2801. break;
  2802. }
  2803. if (!_hasAttrOrCss(knode, map)) {
  2804. break;
  2805. }
  2806. } else {
  2807. if (_NOSPLIT_TAG_MAP[knode.name]) {
  2808. break;
  2809. }
  2810. }
  2811. needSplit = true;
  2812. parent = parent.parentNode;
  2813. }
  2814. if (needSplit) {
  2815. var dummy = doc.createElement('span');
  2816. range.cloneRange().collapse(!isStart).insertNode(dummy);
  2817. if (isStart) {
  2818. tempRange.setStartBefore(parent.firstChild).setEnd(node, pos);
  2819. } else {
  2820. tempRange.setStart(node, pos).setEndAfter(parent.lastChild);
  2821. }
  2822. var frag = tempRange.extractContents(),
  2823. first = frag.firstChild, last = frag.lastChild;
  2824. if (isStart) {
  2825. tempRange.insertNode(frag);
  2826. range.setStartAfter(last).setEndBefore(dummy);
  2827. } else {
  2828. parent.appendChild(frag);
  2829. range.setStartBefore(dummy).setEndBefore(first);
  2830. }
  2831. var dummyParent = dummy.parentNode;
  2832. if (dummyParent == range.endContainer) {
  2833. var prev = K(dummy).prev(), next = K(dummy).next();
  2834. if (prev && next && prev.type == 3 && next.type == 3) {
  2835. range.setEnd(prev[0], prev[0].nodeValue.length);
  2836. } else if (!isStart) {
  2837. range.setEnd(range.endContainer, range.endOffset - 1);
  2838. }
  2839. }
  2840. dummyParent.removeChild(dummy);
  2841. }
  2842. return this;
  2843. },
  2844. remove : function(map) {
  2845. var self = this, doc = self.doc, range = self.range;
  2846. range.enlarge();
  2847. if (range.startOffset === 0) {
  2848. var ksc = K(range.startContainer), parent;
  2849. while ((parent = ksc.parent()) && parent.isStyle() && parent.children().length == 1) {
  2850. ksc = parent;
  2851. }
  2852. range.setStart(ksc[0], 0);
  2853. ksc = K(range.startContainer);
  2854. if (ksc.isBlock()) {
  2855. _removeAttrOrCss(ksc, map);
  2856. }
  2857. var kscp = ksc.parent();
  2858. if (kscp && kscp.isBlock()) {
  2859. _removeAttrOrCss(kscp, map);
  2860. }
  2861. }
  2862. var sc, so;
  2863. if (range.collapsed) {
  2864. self.split(true, map);
  2865. sc = range.startContainer;
  2866. so = range.startOffset;
  2867. if (so > 0) {
  2868. var sb = K(sc.childNodes[so - 1]);
  2869. if (sb && _isEmptyNode(sb)) {
  2870. sb.remove();
  2871. range.setStart(sc, so - 1);
  2872. }
  2873. }
  2874. var sa = K(sc.childNodes[so]);
  2875. if (sa && _isEmptyNode(sa)) {
  2876. sa.remove();
  2877. }
  2878. if (_isEmptyNode(sc)) {
  2879. range.startBefore(sc);
  2880. sc.remove();
  2881. }
  2882. range.collapse(true);
  2883. return self;
  2884. }
  2885. self.split(true, map);
  2886. self.split(false, map);
  2887. var startDummy = doc.createElement('span'), endDummy = doc.createElement('span');
  2888. range.cloneRange().collapse(false).insertNode(endDummy);
  2889. range.cloneRange().collapse(true).insertNode(startDummy);
  2890. var nodeList = [], cmpStart = false;
  2891. K(range.commonAncestor()).scan(function(node) {
  2892. if (!cmpStart && node == startDummy) {
  2893. cmpStart = true;
  2894. return;
  2895. }
  2896. if (node == endDummy) {
  2897. return false;
  2898. }
  2899. if (cmpStart) {
  2900. nodeList.push(node);
  2901. }
  2902. });
  2903. K(startDummy).remove();
  2904. K(endDummy).remove();
  2905. sc = range.startContainer;
  2906. so = range.startOffset;
  2907. var ec = range.endContainer, eo = range.endOffset;
  2908. if (so > 0) {
  2909. var startBefore = K(sc.childNodes[so - 1]);
  2910. if (startBefore && _isEmptyNode(startBefore)) {
  2911. startBefore.remove();
  2912. range.setStart(sc, so - 1);
  2913. if (sc == ec) {
  2914. range.setEnd(ec, eo - 1);
  2915. }
  2916. }
  2917. var startAfter = K(sc.childNodes[so]);
  2918. if (startAfter && _isEmptyNode(startAfter)) {
  2919. startAfter.remove();
  2920. if (sc == ec) {
  2921. range.setEnd(ec, eo - 1);
  2922. }
  2923. }
  2924. }
  2925. var endAfter = K(ec.childNodes[range.endOffset]);
  2926. if (endAfter && _isEmptyNode(endAfter)) {
  2927. endAfter.remove();
  2928. }
  2929. var bookmark = range.createBookmark(true);
  2930. _each(nodeList, function(i, node) {
  2931. _removeAttrOrCss(K(node), map);
  2932. });
  2933. range.moveToBookmark(bookmark);
  2934. return self;
  2935. },
  2936. commonNode : function(map) {
  2937. var range = this.range;
  2938. var ec = range.endContainer, eo = range.endOffset,
  2939. node = (ec.nodeType == 3 || eo === 0) ? ec : ec.childNodes[eo - 1];
  2940. function find(node) {
  2941. var child = node, parent = node;
  2942. while (parent) {
  2943. if (_hasAttrOrCss(K(parent), map)) {
  2944. return K(parent);
  2945. }
  2946. parent = parent.parentNode;
  2947. }
  2948. while (child && (child = child.lastChild)) {
  2949. if (_hasAttrOrCss(K(child), map)) {
  2950. return K(child);
  2951. }
  2952. }
  2953. return null;
  2954. }
  2955. var cNode = find(node);
  2956. if (cNode) {
  2957. return cNode;
  2958. }
  2959. if (node.nodeType == 1 || (ec.nodeType == 3 && eo === 0)) {
  2960. var prev = K(node).prev();
  2961. if (prev) {
  2962. return find(prev);
  2963. }
  2964. }
  2965. return null;
  2966. },
  2967. commonAncestor : function(tagName) {
  2968. var range = this.range,
  2969. sc = range.startContainer, so = range.startOffset,
  2970. ec = range.endContainer, eo = range.endOffset,
  2971. startNode = (sc.nodeType == 3 || so === 0) ? sc : sc.childNodes[so - 1],
  2972. endNode = (ec.nodeType == 3 || eo === 0) ? ec : ec.childNodes[eo - 1];
  2973. function find(node) {
  2974. while (node) {
  2975. if (node.nodeType == 1) {
  2976. if (node.tagName.toLowerCase() === tagName) {
  2977. return node;
  2978. }
  2979. }
  2980. node = node.parentNode;
  2981. }
  2982. return null;
  2983. }
  2984. var start = find(startNode), end = find(endNode);
  2985. if (start && end && start === end) {
  2986. return K(start);
  2987. }
  2988. return null;
  2989. },
  2990. state : function(key) {
  2991. var self = this, doc = self.doc, bool = false;
  2992. try {
  2993. bool = doc.queryCommandState(key);
  2994. } catch (e) {}
  2995. return bool;
  2996. },
  2997. val : function(key) {
  2998. var self = this, doc = self.doc, range = self.range;
  2999. function lc(val) {
  3000. return val.toLowerCase();
  3001. }
  3002. key = lc(key);
  3003. var val = '', knode;
  3004. if (key === 'fontfamily' || key === 'fontname') {
  3005. val = _nativeCommandValue(doc, 'fontname');
  3006. val = val.replace(/['"]/g, '');
  3007. return lc(val);
  3008. }
  3009. if (key === 'formatblock') {
  3010. val = _nativeCommandValue(doc, key);
  3011. if (val === '') {
  3012. knode = self.commonNode({'h1,h2,h3,h4,h5,h6,p,div,pre,address' : '*'});
  3013. if (knode) {
  3014. val = knode.name;
  3015. }
  3016. }
  3017. if (val === 'Normal') {
  3018. val = 'p';
  3019. }
  3020. return lc(val);
  3021. }
  3022. if (key === 'fontsize') {
  3023. knode = self.commonNode({'*' : '.font-size'});
  3024. if (knode) {
  3025. val = knode.css('font-size');
  3026. }
  3027. return lc(val);
  3028. }
  3029. if (key === 'forecolor') {
  3030. knode = self.commonNode({'*' : '.color'});
  3031. if (knode) {
  3032. val = knode.css('color');
  3033. }
  3034. val = _toHex(val);
  3035. if (val === '') {
  3036. val = 'default';
  3037. }
  3038. return lc(val);
  3039. }
  3040. if (key === 'hilitecolor') {
  3041. knode = self.commonNode({'*' : '.background-color'});
  3042. if (knode) {
  3043. val = knode.css('background-color');
  3044. }
  3045. val = _toHex(val);
  3046. if (val === '') {
  3047. val = 'default';
  3048. }
  3049. return lc(val);
  3050. }
  3051. return val;
  3052. },
  3053. toggle : function(wrapper, map) {
  3054. var self = this;
  3055. if (self.commonNode(map)) {
  3056. self.remove(map);
  3057. } else {
  3058. self.wrap(wrapper);
  3059. }
  3060. return self.select();
  3061. },
  3062. bold : function() {
  3063. return this.toggle('<strong></strong>', {
  3064. span : '.font-weight=bold',
  3065. strong : '*',
  3066. b : '*'
  3067. });
  3068. },
  3069. italic : function() {
  3070. return this.toggle('<em></em>', {
  3071. span : '.font-style=italic',
  3072. em : '*',
  3073. i : '*'
  3074. });
  3075. },
  3076. underline : function() {
  3077. return this.toggle('<u></u>', {
  3078. span : '.text-decoration=underline',
  3079. u : '*'
  3080. });
  3081. },
  3082. strikethrough : function() {
  3083. return this.toggle('<s></s>', {
  3084. span : '.text-decoration=line-through',
  3085. s : '*'
  3086. });
  3087. },
  3088. forecolor : function(val) {
  3089. return this.toggle('<span style="color:' + val + ';"></span>', {
  3090. span : '.color=' + val,
  3091. font : 'color'
  3092. });
  3093. },
  3094. hilitecolor : function(val) {
  3095. return this.toggle('<span style="background-color:' + val + ';"></span>', {
  3096. span : '.background-color=' + val
  3097. });
  3098. },
  3099. fontsize : function(val) {
  3100. return this.toggle('<span style="font-size:' + val + ';"></span>', {
  3101. span : '.font-size=' + val,
  3102. font : 'size'
  3103. });
  3104. },
  3105. fontname : function(val) {
  3106. return this.fontfamily(val);
  3107. },
  3108. fontfamily : function(val) {
  3109. return this.toggle('<span style="font-family:' + val + ';"></span>', {
  3110. span : '.font-family=' + val,
  3111. font : 'face'
  3112. });
  3113. },
  3114. removeformat : function() {
  3115. var map = {
  3116. '*' : '.font-weight,.font-style,.text-decoration,.color,.background-color,.font-size,.font-family,.text-indent'
  3117. },
  3118. tags = _STYLE_TAG_MAP;
  3119. _each(tags, function(key, val) {
  3120. map[key] = '*';
  3121. });
  3122. this.remove(map);
  3123. return this.select();
  3124. },
  3125. inserthtml : function(val, quickMode) {
  3126. var self = this, range = self.range;
  3127. if (val === '') {
  3128. return self;
  3129. }
  3130. function pasteHtml(range, val) {
  3131. val = '<img id="__kindeditor_temp_tag__" width="0" height="0" style="display:none;" />' + val;
  3132. var rng = range.get();
  3133. if (rng.item) {
  3134. rng.item(0).outerHTML = val;
  3135. } else {
  3136. rng.pasteHTML(val);
  3137. }
  3138. var temp = range.doc.getElementById('__kindeditor_temp_tag__');
  3139. temp.parentNode.removeChild(temp);
  3140. var newRange = _toRange(rng);
  3141. range.setEnd(newRange.endContainer, newRange.endOffset);
  3142. range.collapse(false);
  3143. self.select(false);
  3144. }
  3145. function insertHtml(range, val) {
  3146. var doc = range.doc,
  3147. frag = doc.createDocumentFragment();
  3148. K('@' + val, doc).each(function() {
  3149. frag.appendChild(this);
  3150. });
  3151. range.deleteContents();
  3152. range.insertNode(frag);
  3153. range.collapse(false);
  3154. self.select(false);
  3155. }
  3156. if (_IE && quickMode) {
  3157. try {
  3158. pasteHtml(range, val);
  3159. } catch(e) {
  3160. insertHtml(range, val);
  3161. }
  3162. return self;
  3163. }
  3164. insertHtml(range, val);
  3165. return self;
  3166. },
  3167. hr : function() {
  3168. return this.inserthtml('<hr />');
  3169. },
  3170. print : function() {
  3171. this.win.print();
  3172. return this;
  3173. },
  3174. insertimage : function(url, title, width, height, border, align) {
  3175. title = _undef(title, '');
  3176. border = _undef(border, 0);
  3177. var html = '<img src="' + _escape(url) + '" data-ke-src="' + _escape(url) + '" ';
  3178. if (width) {
  3179. html += 'width="' + _escape(width) + '" ';
  3180. }
  3181. if (height) {
  3182. html += 'height="' + _escape(height) + '" ';
  3183. }
  3184. if (title) {
  3185. html += 'title="' + _escape(title) + '" ';
  3186. }
  3187. if (align) {
  3188. html += 'align="' + _escape(align) + '" ';
  3189. }
  3190. html += 'alt="' + _escape(title) + '" ';
  3191. html += '/>';
  3192. return this.inserthtml(html);
  3193. },
  3194. createlink : function(url, type) {
  3195. var self = this, doc = self.doc, range = self.range;
  3196. self.select();
  3197. var a = self.commonNode({ a : '*' });
  3198. if (a && !range.isControl()) {
  3199. range.selectNode(a.get());
  3200. self.select();
  3201. }
  3202. var html = '<a href="' + _escape(url) + '" data-ke-src="' + _escape(url) + '" ';
  3203. if (type) {
  3204. html += ' target="' + _escape(type) + '"';
  3205. }
  3206. if (range.collapsed) {
  3207. html += '>' + _escape(url) + '</a>';
  3208. return self.inserthtml(html);
  3209. }
  3210. if (range.isControl()) {
  3211. var node = K(range.startContainer.childNodes[range.startOffset]);
  3212. html += '></a>';
  3213. node.after(K(html, doc));
  3214. node.next().append(node);
  3215. range.selectNode(node[0]);
  3216. return self.select();
  3217. }
  3218. _nativeCommand(doc, 'createlink', '__kindeditor_temp_url__');
  3219. K('a[href="__kindeditor_temp_url__"]', doc).each(function() {
  3220. K(this).attr('href', url).attr('data-ke-src', url);
  3221. if (type) {
  3222. K(this).attr('target', type);
  3223. } else {
  3224. K(this).removeAttr('target');
  3225. }
  3226. });
  3227. return self;
  3228. },
  3229. unlink : function() {
  3230. var self = this, doc = self.doc, range = self.range;
  3231. self.select();
  3232. if (range.collapsed) {
  3233. var a = self.commonNode({ a : '*' });
  3234. if (a) {
  3235. range.selectNode(a.get());
  3236. self.select();
  3237. }
  3238. _nativeCommand(doc, 'unlink', null);
  3239. if (_WEBKIT && K(range.startContainer).name === 'img') {
  3240. var parent = K(range.startContainer).parent();
  3241. if (parent.name === 'a') {
  3242. parent.remove(true);
  3243. }
  3244. }
  3245. } else {
  3246. _nativeCommand(doc, 'unlink', null);
  3247. }
  3248. return self;
  3249. }
  3250. });
  3251. _each(('formatblock,selectall,justifyleft,justifycenter,justifyright,justifyfull,insertorderedlist,' +
  3252. 'insertunorderedlist,indent,outdent,subscript,superscript').split(','), function(i, name) {
  3253. KCmd.prototype[name] = function(val) {
  3254. var self = this;
  3255. self.select();
  3256. _nativeCommand(self.doc, name, val);
  3257. if (!_IE || _inArray(name, 'formatblock,selectall,insertorderedlist,insertunorderedlist'.split(',')) >= 0) {
  3258. self.selection();
  3259. }
  3260. return self;
  3261. };
  3262. });
  3263. _each('cut,copy,paste'.split(','), function(i, name) {
  3264. KCmd.prototype[name] = function() {
  3265. var self = this;
  3266. if (!self.doc.queryCommandSupported(name)) {
  3267. throw 'not supported';
  3268. }
  3269. self.select();
  3270. _nativeCommand(self.doc, name, null);
  3271. return self;
  3272. };
  3273. });
  3274. function _cmd(mixed) {
  3275. if (mixed.nodeName) {
  3276. var doc = _getDoc(mixed);
  3277. mixed = _range(doc).selectNodeContents(doc.body).collapse(false);
  3278. }
  3279. return new KCmd(mixed);
  3280. }
  3281. K.CmdClass = KCmd;
  3282. K.cmd = _cmd;
  3283. function _drag(options) {
  3284. var moveEl = options.moveEl,
  3285. moveFn = options.moveFn,
  3286. clickEl = options.clickEl || moveEl,
  3287. beforeDrag = options.beforeDrag,
  3288. iframeFix = options.iframeFix === undefined ? true : options.iframeFix;
  3289. var docs = [document];
  3290. if (iframeFix) {
  3291. K('iframe').each(function() {
  3292. var src = _formatUrl(this.src || '', 'absolute');
  3293. if (/^https?:\/\//.test(src)) {
  3294. return;
  3295. }
  3296. var doc;
  3297. try {
  3298. doc = _iframeDoc(this);
  3299. } catch(e) {}
  3300. if (doc) {
  3301. var pos = K(this).pos();
  3302. K(doc).data('pos-x', pos.x);
  3303. K(doc).data('pos-y', pos.y);
  3304. docs.push(doc);
  3305. }
  3306. });
  3307. }
  3308. clickEl.mousedown(function(e) {
  3309. e.stopPropagation();
  3310. var self = clickEl.get(),
  3311. x = _removeUnit(moveEl.css('left')),
  3312. y = _removeUnit(moveEl.css('top')),
  3313. width = moveEl.width(),
  3314. height = moveEl.height(),
  3315. pageX = e.pageX,
  3316. pageY = e.pageY;
  3317. if (beforeDrag) {
  3318. beforeDrag();
  3319. }
  3320. function moveListener(e) {
  3321. e.preventDefault();
  3322. var kdoc = K(_getDoc(e.target));
  3323. var diffX = _round((kdoc.data('pos-x') || 0) + e.pageX - pageX);
  3324. var diffY = _round((kdoc.data('pos-y') || 0) + e.pageY - pageY);
  3325. moveFn.call(clickEl, x, y, width, height, diffX, diffY);
  3326. }
  3327. function selectListener(e) {
  3328. e.preventDefault();
  3329. }
  3330. function upListener(e) {
  3331. e.preventDefault();
  3332. K(docs).unbind('mousemove', moveListener)
  3333. .unbind('mouseup', upListener)
  3334. .unbind('selectstart', selectListener);
  3335. if (self.releaseCapture) {
  3336. self.releaseCapture();
  3337. }
  3338. }
  3339. K(docs).mousemove(moveListener)
  3340. .mouseup(upListener)
  3341. .bind('selectstart', selectListener);
  3342. if (self.setCapture) {
  3343. self.setCapture();
  3344. }
  3345. });
  3346. }
  3347. function KWidget(options) {
  3348. this.init(options);
  3349. }
  3350. _extend(KWidget, {
  3351. init : function(options) {
  3352. var self = this;
  3353. self.name = options.name || '';
  3354. self.doc = options.doc || document;
  3355. self.win = _getWin(self.doc);
  3356. self.x = _addUnit(options.x);
  3357. self.y = _addUnit(options.y);
  3358. self.z = options.z;
  3359. self.width = _addUnit(options.width);
  3360. self.height = _addUnit(options.height);
  3361. self.div = K('<div style="display:block;"></div>');
  3362. self.options = options;
  3363. self._alignEl = options.alignEl;
  3364. if (self.width) {
  3365. self.div.css('width', self.width);
  3366. }
  3367. if (self.height) {
  3368. self.div.css('height', self.height);
  3369. }
  3370. if (self.z) {
  3371. self.div.css({
  3372. position : 'absolute',
  3373. left : self.x,
  3374. top : self.y,
  3375. 'z-index' : self.z
  3376. });
  3377. }
  3378. if (self.z && (self.x === undefined || self.y === undefined)) {
  3379. self.autoPos(self.width, self.height);
  3380. }
  3381. if (options.cls) {
  3382. self.div.addClass(options.cls);
  3383. }
  3384. if (options.shadowMode) {
  3385. self.div.addClass('ke-shadow');
  3386. }
  3387. if (options.css) {
  3388. self.div.css(options.css);
  3389. }
  3390. if (options.src) {
  3391. K(options.src).replaceWith(self.div);
  3392. } else {
  3393. K(self.doc.body).append(self.div);
  3394. }
  3395. if (options.html) {
  3396. self.div.html(options.html);
  3397. }
  3398. if (options.autoScroll) {
  3399. if (_IE && _V < 7 || _QUIRKS) {
  3400. var scrollPos = _getScrollPos();
  3401. K(self.win).bind('scroll', function(e) {
  3402. var pos = _getScrollPos(),
  3403. diffX = pos.x - scrollPos.x,
  3404. diffY = pos.y - scrollPos.y;
  3405. self.pos(_removeUnit(self.x) + diffX, _removeUnit(self.y) + diffY, false);
  3406. });
  3407. } else {
  3408. self.div.css('position', 'fixed');
  3409. }
  3410. }
  3411. },
  3412. pos : function(x, y, updateProp) {
  3413. var self = this;
  3414. updateProp = _undef(updateProp, true);
  3415. if (x !== null) {
  3416. x = x < 0 ? 0 : _addUnit(x);
  3417. self.div.css('left', x);
  3418. if (updateProp) {
  3419. self.x = x;
  3420. }
  3421. }
  3422. if (y !== null) {
  3423. y = y < 0 ? 0 : _addUnit(y);
  3424. self.div.css('top', y);
  3425. if (updateProp) {
  3426. self.y = y;
  3427. }
  3428. }
  3429. return self;
  3430. },
  3431. autoPos : function(width, height) {
  3432. var self = this,
  3433. w = _removeUnit(width) || 0,
  3434. h = _removeUnit(height) || 0,
  3435. scrollPos = _getScrollPos();
  3436. if (self._alignEl) {
  3437. var knode = K(self._alignEl),
  3438. pos = knode.pos(),
  3439. diffX = _round(knode[0].clientWidth / 2 - w / 2),
  3440. diffY = _round(knode[0].clientHeight / 2 - h / 2);
  3441. x = diffX < 0 ? pos.x : pos.x + diffX;
  3442. y = diffY < 0 ? pos.y : pos.y + diffY;
  3443. } else {
  3444. var docEl = _docElement(self.doc);
  3445. x = _round(scrollPos.x + (docEl.clientWidth - w) / 2);
  3446. y = _round(scrollPos.y + (docEl.clientHeight - h) / 2);
  3447. }
  3448. if (!(_IE && _V < 7 || _QUIRKS)) {
  3449. x -= scrollPos.x;
  3450. y -= scrollPos.y;
  3451. }
  3452. return self.pos(x, y);
  3453. },
  3454. remove : function() {
  3455. var self = this;
  3456. if (_IE && _V < 7 || _QUIRKS) {
  3457. K(self.win).unbind('scroll');
  3458. }
  3459. self.div.remove();
  3460. _each(self, function(i) {
  3461. self[i] = null;
  3462. });
  3463. return this;
  3464. },
  3465. show : function() {
  3466. this.div.show();
  3467. return this;
  3468. },
  3469. hide : function() {
  3470. this.div.hide();
  3471. return this;
  3472. },
  3473. draggable : function(options) {
  3474. var self = this;
  3475. options = options || {};
  3476. options.moveEl = self.div;
  3477. options.moveFn = function(x, y, width, height, diffX, diffY) {
  3478. if ((x = x + diffX) < 0) {
  3479. x = 0;
  3480. }
  3481. if ((y = y + diffY) < 0) {
  3482. y = 0;
  3483. }
  3484. self.pos(x, y);
  3485. };
  3486. _drag(options);
  3487. return self;
  3488. }
  3489. });
  3490. function _widget(options) {
  3491. return new KWidget(options);
  3492. }
  3493. K.WidgetClass = KWidget;
  3494. K.widget = _widget;
  3495. function _iframeDoc(iframe) {
  3496. iframe = _get(iframe);
  3497. return iframe.contentDocument || iframe.contentWindow.document;
  3498. }
  3499. var html, _direction = '';
  3500. if ((html = document.getElementsByTagName('html'))) {
  3501. _direction = html[0].dir;
  3502. }
  3503. function _getInitHtml(themesPath, bodyClass, cssPath, cssData) {
  3504. var arr = [
  3505. (_direction === '' ? '<html>' : '<html dir="' + _direction + '">'),
  3506. '<head><meta charset="utf-8" /><title></title>',
  3507. '<style>',
  3508. 'html {margin:0;padding:0;}',
  3509. 'body {margin:0;padding:5px;}',
  3510. 'body, td {font:12px/1.5 "sans serif",tahoma,verdana,helvetica;}',
  3511. 'body, p, div {word-wrap: break-word;}',
  3512. 'p {margin:5px 0;}',
  3513. 'table {border-collapse:collapse;}',
  3514. 'img {border:0;}',
  3515. 'noscript {display:none;}',
  3516. 'table.ke-zeroborder td {border:1px dotted #AAA;}',
  3517. 'img.ke-flash {',
  3518. ' border:1px solid #AAA;',
  3519. ' background-image:url(' + themesPath + 'common/flash.gif);',
  3520. ' background-position:center center;',
  3521. ' background-repeat:no-repeat;',
  3522. ' width:100px;',
  3523. ' height:100px;',
  3524. '}',
  3525. 'img.ke-rm {',
  3526. ' border:1px solid #AAA;',
  3527. ' background-image:url(' + themesPath + 'common/rm.gif);',
  3528. ' background-position:center center;',
  3529. ' background-repeat:no-repeat;',
  3530. ' width:100px;',
  3531. ' height:100px;',
  3532. '}',
  3533. 'img.ke-media {',
  3534. ' border:1px solid #AAA;',
  3535. ' background-image:url(' + themesPath + 'common/media.gif);',
  3536. ' background-position:center center;',
  3537. ' background-repeat:no-repeat;',
  3538. ' width:100px;',
  3539. ' height:100px;',
  3540. '}',
  3541. 'img.ke-anchor {',
  3542. ' border:1px dashed #666;',
  3543. ' width:16px;',
  3544. ' height:16px;',
  3545. '}',
  3546. '.ke-script, .ke-noscript, .ke-display-none {',
  3547. ' display:none;',
  3548. ' font-size:0;',
  3549. ' width:0;',
  3550. ' height:0;',
  3551. '}',
  3552. '.ke-pagebreak {',
  3553. ' border:1px dotted #AAA;',
  3554. ' font-size:0;',
  3555. ' height:2px;',
  3556. '}',
  3557. '</style>'
  3558. ];
  3559. if (!_isArray(cssPath)) {
  3560. cssPath = [cssPath];
  3561. }
  3562. _each(cssPath, function(i, path) {
  3563. if (path) {
  3564. arr.push('<link href="' + path + '" rel="stylesheet" />');
  3565. }
  3566. });
  3567. if (cssData) {
  3568. arr.push('<style>' + cssData + '</style>');
  3569. }
  3570. arr.push('</head><body ' + (bodyClass ? 'class="' + bodyClass + '"' : '') + '></body></html>');
  3571. return arr.join('\n');
  3572. }
  3573. function _elementVal(knode, val) {
  3574. if (knode.hasVal()) {
  3575. if (val === undefined) {
  3576. var html = knode.val();
  3577. html = html.replace(/(<(?:p|p\s[^>]*)>) *(<\/p>)/ig, '');
  3578. return html;
  3579. }
  3580. return knode.val(val);
  3581. }
  3582. return knode.html(val);
  3583. }
  3584. function KEdit(options) {
  3585. this.init(options);
  3586. }
  3587. _extend(KEdit, KWidget, {
  3588. init : function(options) {
  3589. var self = this;
  3590. KEdit.parent.init.call(self, options);
  3591. self.srcElement = K(options.srcElement);
  3592. self.div.addClass('ke-edit');
  3593. self.designMode = _undef(options.designMode, true);
  3594. self.beforeGetHtml = options.beforeGetHtml;
  3595. self.beforeSetHtml = options.beforeSetHtml;
  3596. self.afterSetHtml = options.afterSetHtml;
  3597. var themesPath = _undef(options.themesPath, ''),
  3598. bodyClass = options.bodyClass,
  3599. cssPath = options.cssPath,
  3600. cssData = options.cssData,
  3601. isDocumentDomain = location.host.replace(/:\d+/, '') !== document.domain,
  3602. srcScript = ('document.open();' +
  3603. (isDocumentDomain ? 'document.domain="' + document.domain + '";' : '') +
  3604. 'document.close();'),
  3605. iframeSrc = _IE ? ' src="javascript:void(function(){' + encodeURIComponent(srcScript) + '}())"' : '';
  3606. self.iframe = K('<iframe class="ke-edit-iframe" hidefocus="true" frameborder="0"' + iframeSrc + '></iframe>').css('width', '100%');
  3607. self.textarea = K('<textarea class="ke-edit-textarea" hidefocus="true"></textarea>').css('width', '100%');
  3608. if (self.width) {
  3609. self.setWidth(self.width);
  3610. }
  3611. if (self.height) {
  3612. self.setHeight(self.height);
  3613. }
  3614. if (self.designMode) {
  3615. self.textarea.hide();
  3616. } else {
  3617. self.iframe.hide();
  3618. }
  3619. function ready() {
  3620. var doc = _iframeDoc(self.iframe);
  3621. doc.open();
  3622. if (isDocumentDomain) {
  3623. doc.domain = document.domain;
  3624. }
  3625. doc.write(_getInitHtml(themesPath, bodyClass, cssPath, cssData));
  3626. doc.close();
  3627. self.win = self.iframe[0].contentWindow;
  3628. self.doc = doc;
  3629. var cmd = _cmd(doc);
  3630. self.afterChange(function(e) {
  3631. cmd.selection();
  3632. });
  3633. if (_WEBKIT) {
  3634. K(doc).click(function(e) {
  3635. if (K(e.target).name === 'img') {
  3636. cmd.selection(true);
  3637. cmd.range.selectNode(e.target);
  3638. cmd.select();
  3639. }
  3640. });
  3641. }
  3642. if (_IE) {
  3643. self._mousedownHandler = function() {
  3644. var newRange = cmd.range.cloneRange();
  3645. newRange.shrink();
  3646. if (newRange.isControl()) {
  3647. self.blur();
  3648. }
  3649. };
  3650. K(document).mousedown(self._mousedownHandler);
  3651. K(doc).keydown(function(e) {
  3652. if (e.which == 8) {
  3653. cmd.selection();
  3654. var rng = cmd.range;
  3655. if (rng.isControl()) {
  3656. rng.collapse(true);
  3657. K(rng.startContainer.childNodes[rng.startOffset]).remove();
  3658. e.preventDefault();
  3659. }
  3660. }
  3661. });
  3662. }
  3663. self.cmd = cmd;
  3664. self.html(_elementVal(self.srcElement));
  3665. if (_IE) {
  3666. doc.body.disabled = true;
  3667. doc.body.contentEditable = true;
  3668. doc.body.removeAttribute('disabled');
  3669. } else {
  3670. doc.designMode = 'on';
  3671. }
  3672. if (options.afterCreate) {
  3673. options.afterCreate.call(self);
  3674. }
  3675. }
  3676. if (isDocumentDomain) {
  3677. self.iframe.bind('load', function(e) {
  3678. self.iframe.unbind('load');
  3679. if (_IE) {
  3680. ready();
  3681. } else {
  3682. setTimeout(ready, 0);
  3683. }
  3684. });
  3685. }
  3686. self.div.append(self.iframe);
  3687. self.div.append(self.textarea);
  3688. self.srcElement.hide();
  3689. !isDocumentDomain && ready();
  3690. },
  3691. setWidth : function(val) {
  3692. this.div.css('width', _addUnit(val));
  3693. return this;
  3694. },
  3695. setHeight : function(val) {
  3696. var self = this;
  3697. val = _addUnit(val);
  3698. self.div.css('height', val);
  3699. self.iframe.css('height', val);
  3700. if ((_IE && _V < 8) || _QUIRKS) {
  3701. val = _addUnit(_removeUnit(val) - 2);
  3702. }
  3703. self.textarea.css('height', val);
  3704. return self;
  3705. },
  3706. remove : function() {
  3707. var self = this, doc = self.doc;
  3708. K(doc.body).unbind();
  3709. K(doc).unbind();
  3710. K(self.win).unbind();
  3711. if (self._mousedownHandler) {
  3712. K(document).unbind('mousedown', self._mousedownHandler);
  3713. }
  3714. _elementVal(self.srcElement, self.html());
  3715. self.srcElement.show();
  3716. doc.write('');
  3717. self.iframe.unbind();
  3718. self.textarea.unbind();
  3719. KEdit.parent.remove.call(self);
  3720. },
  3721. html : function(val, isFull) {
  3722. var self = this, doc = self.doc;
  3723. if (self.designMode) {
  3724. var body = doc.body;
  3725. if (val === undefined) {
  3726. if (isFull) {
  3727. val = '<!doctype html><html>' + body.parentNode.innerHTML + '</html>';
  3728. } else {
  3729. val = body.innerHTML;
  3730. }
  3731. if (self.beforeGetHtml) {
  3732. val = self.beforeGetHtml(val);
  3733. }
  3734. if (_GECKO && val == '<br />') {
  3735. val = '';
  3736. }
  3737. return val;
  3738. }
  3739. if (self.beforeSetHtml) {
  3740. val = self.beforeSetHtml(val);
  3741. }
  3742. if (_IE && _V >= 9) {
  3743. val = val.replace(/(<.*?checked=")checked(".*>)/ig, '$1$2');
  3744. }
  3745. K(body).html(val);
  3746. if (self.afterSetHtml) {
  3747. self.afterSetHtml();
  3748. }
  3749. return self;
  3750. }
  3751. if (val === undefined) {
  3752. return self.textarea.val();
  3753. }
  3754. self.textarea.val(val);
  3755. return self;
  3756. },
  3757. design : function(bool) {
  3758. var self = this, val;
  3759. if (bool === undefined ? !self.designMode : bool) {
  3760. if (!self.designMode) {
  3761. val = self.html();
  3762. self.designMode = true;
  3763. self.html(val);
  3764. self.textarea.hide();
  3765. self.iframe.show();
  3766. }
  3767. } else {
  3768. if (self.designMode) {
  3769. val = self.html();
  3770. self.designMode = false;
  3771. self.html(val);
  3772. self.iframe.hide();
  3773. self.textarea.show();
  3774. }
  3775. }
  3776. return self.focus();
  3777. },
  3778. focus : function() {
  3779. var self = this;
  3780. self.designMode ? self.win.focus() : self.textarea[0].focus();
  3781. return self;
  3782. },
  3783. blur : function() {
  3784. var self = this;
  3785. if (_IE) {
  3786. var input = K('<input type="text" style="float:left;width:0;height:0;padding:0;margin:0;border:0;" value="" />', self.div);
  3787. self.div.append(input);
  3788. input[0].focus();
  3789. input.remove();
  3790. } else {
  3791. self.designMode ? self.win.blur() : self.textarea[0].blur();
  3792. }
  3793. return self;
  3794. },
  3795. afterChange : function(fn) {
  3796. var self = this, doc = self.doc, body = doc.body;
  3797. K(doc).keyup(function(e) {
  3798. if (!e.ctrlKey && !e.altKey && _CHANGE_KEY_MAP[e.which]) {
  3799. fn(e);
  3800. }
  3801. });
  3802. K(doc).mouseup(fn).contextmenu(fn);
  3803. K(self.win).blur(fn);
  3804. function timeoutHandler(e) {
  3805. setTimeout(function() {
  3806. fn(e);
  3807. }, 1);
  3808. }
  3809. K(body).bind('paste', timeoutHandler);
  3810. K(body).bind('cut', timeoutHandler);
  3811. return self;
  3812. }
  3813. });
  3814. function _edit(options) {
  3815. return new KEdit(options);
  3816. }
  3817. K.EditClass = KEdit;
  3818. K.edit = _edit;
  3819. K.iframeDoc = _iframeDoc;
  3820. function _selectToolbar(name, fn) {
  3821. var self = this,
  3822. knode = self.get(name);
  3823. if (knode) {
  3824. if (knode.hasClass('ke-disabled')) {
  3825. return;
  3826. }
  3827. fn(knode);
  3828. }
  3829. }
  3830. function KToolbar(options) {
  3831. this.init(options);
  3832. }
  3833. _extend(KToolbar, KWidget, {
  3834. init : function(options) {
  3835. var self = this;
  3836. KToolbar.parent.init.call(self, options);
  3837. self.disableMode = _undef(options.disableMode, false);
  3838. self.noDisableItemMap = _toMap(_undef(options.noDisableItems, []));
  3839. self._itemMap = {};
  3840. self.div.addClass('ke-toolbar').bind('contextmenu,mousedown,mousemove', function(e) {
  3841. e.preventDefault();
  3842. }).attr('unselectable', 'on');
  3843. function find(target) {
  3844. var knode = K(target);
  3845. if (knode.hasClass('ke-outline')) {
  3846. return knode;
  3847. }
  3848. if (knode.hasClass('ke-toolbar-icon')) {
  3849. return knode.parent();
  3850. }
  3851. }
  3852. function hover(e, method) {
  3853. var knode = find(e.target);
  3854. if (knode) {
  3855. if (knode.hasClass('ke-disabled')) {
  3856. return;
  3857. }
  3858. if (knode.hasClass('ke-selected')) {
  3859. return;
  3860. }
  3861. knode[method]('ke-on');
  3862. }
  3863. }
  3864. self.div.mouseover(function(e) {
  3865. hover(e, 'addClass');
  3866. })
  3867. .mouseout(function(e) {
  3868. hover(e, 'removeClass');
  3869. })
  3870. .click(function(e) {
  3871. var knode = find(e.target);
  3872. if (knode) {
  3873. if (knode.hasClass('ke-disabled')) {
  3874. return;
  3875. }
  3876. self.options.click.call(this, e, knode.attr('data-name'));
  3877. }
  3878. });
  3879. },
  3880. get : function(name) {
  3881. if (this._itemMap[name]) {
  3882. return this._itemMap[name];
  3883. }
  3884. return (this._itemMap[name] = K('span.ke-icon-' + name, this.div).parent());
  3885. },
  3886. select : function(name) {
  3887. _selectToolbar.call(this, name, function(knode) {
  3888. knode.addClass('ke-selected');
  3889. });
  3890. return self;
  3891. },
  3892. unselect : function(name) {
  3893. _selectToolbar.call(this, name, function(knode) {
  3894. knode.removeClass('ke-selected').removeClass('ke-on');
  3895. });
  3896. return self;
  3897. },
  3898. enable : function(name) {
  3899. var self = this,
  3900. knode = name.get ? name : self.get(name);
  3901. if (knode) {
  3902. knode.removeClass('ke-disabled');
  3903. knode.opacity(1);
  3904. }
  3905. return self;
  3906. },
  3907. disable : function(name) {
  3908. var self = this,
  3909. knode = name.get ? name : self.get(name);
  3910. if (knode) {
  3911. knode.removeClass('ke-selected').addClass('ke-disabled');
  3912. knode.opacity(0.5);
  3913. }
  3914. return self;
  3915. },
  3916. disableAll : function(bool, noDisableItems) {
  3917. var self = this, map = self.noDisableItemMap, item;
  3918. if (noDisableItems) {
  3919. map = _toMap(noDisableItems);
  3920. }
  3921. if (bool === undefined ? !self.disableMode : bool) {
  3922. K('span.ke-outline', self.div).each(function() {
  3923. var knode = K(this),
  3924. name = knode[0].getAttribute('data-name', 2);
  3925. if (!map[name]) {
  3926. self.disable(knode);
  3927. }
  3928. });
  3929. self.disableMode = true;
  3930. } else {
  3931. K('span.ke-outline', self.div).each(function() {
  3932. var knode = K(this),
  3933. name = knode[0].getAttribute('data-name', 2);
  3934. if (!map[name]) {
  3935. self.enable(knode);
  3936. }
  3937. });
  3938. self.disableMode = false;
  3939. }
  3940. return self;
  3941. }
  3942. });
  3943. function _toolbar(options) {
  3944. return new KToolbar(options);
  3945. }
  3946. K.ToolbarClass = KToolbar;
  3947. K.toolbar = _toolbar;
  3948. function KMenu(options) {
  3949. this.init(options);
  3950. }
  3951. _extend(KMenu, KWidget, {
  3952. init : function(options) {
  3953. var self = this;
  3954. options.z = options.z || 811213;
  3955. KMenu.parent.init.call(self, options);
  3956. self.centerLineMode = _undef(options.centerLineMode, true);
  3957. self.div.addClass('ke-menu').bind('click,mousedown', function(e){
  3958. e.stopPropagation();
  3959. }).attr('unselectable', 'on');
  3960. },
  3961. addItem : function(item) {
  3962. var self = this;
  3963. if (item.title === '-') {
  3964. self.div.append(K('<div class="ke-menu-separator"></div>'));
  3965. return;
  3966. }
  3967. var itemDiv = K('<div class="ke-menu-item" unselectable="on"></div>'),
  3968. leftDiv = K('<div class="ke-inline-block ke-menu-item-left"></div>'),
  3969. rightDiv = K('<div class="ke-inline-block ke-menu-item-right"></div>'),
  3970. height = _addUnit(item.height),
  3971. iconClass = _undef(item.iconClass, '');
  3972. self.div.append(itemDiv);
  3973. if (height) {
  3974. itemDiv.css('height', height);
  3975. rightDiv.css('line-height', height);
  3976. }
  3977. var centerDiv;
  3978. if (self.centerLineMode) {
  3979. centerDiv = K('<div class="ke-inline-block ke-menu-item-center"></div>');
  3980. if (height) {
  3981. centerDiv.css('height', height);
  3982. }
  3983. }
  3984. itemDiv.mouseover(function(e) {
  3985. K(this).addClass('ke-menu-item-on');
  3986. if (centerDiv) {
  3987. centerDiv.addClass('ke-menu-item-center-on');
  3988. }
  3989. })
  3990. .mouseout(function(e) {
  3991. K(this).removeClass('ke-menu-item-on');
  3992. if (centerDiv) {
  3993. centerDiv.removeClass('ke-menu-item-center-on');
  3994. }
  3995. })
  3996. .click(function(e) {
  3997. item.click.call(K(this));
  3998. e.stopPropagation();
  3999. })
  4000. .append(leftDiv);
  4001. if (centerDiv) {
  4002. itemDiv.append(centerDiv);
  4003. }
  4004. itemDiv.append(rightDiv);
  4005. if (item.checked) {
  4006. iconClass = 'ke-icon-checked';
  4007. }
  4008. if (iconClass !== '') {
  4009. leftDiv.html('<span class="ke-inline-block ke-toolbar-icon ke-toolbar-icon-url ' + iconClass + '"></span>');
  4010. }
  4011. rightDiv.html(item.title);
  4012. return self;
  4013. },
  4014. remove : function() {
  4015. var self = this;
  4016. if (self.options.beforeRemove) {
  4017. self.options.beforeRemove.call(self);
  4018. }
  4019. K('.ke-menu-item', self.div[0]).unbind();
  4020. KMenu.parent.remove.call(self);
  4021. return self;
  4022. }
  4023. });
  4024. function _menu(options) {
  4025. return new KMenu(options);
  4026. }
  4027. K.MenuClass = KMenu;
  4028. K.menu = _menu;
  4029. function KColorPicker(options) {
  4030. this.init(options);
  4031. }
  4032. _extend(KColorPicker, KWidget, {
  4033. init : function(options) {
  4034. var self = this;
  4035. options.z = options.z || 811213;
  4036. KColorPicker.parent.init.call(self, options);
  4037. var colors = options.colors || [
  4038. ['#E53333', '#E56600', '#FF9900', '#64451D', '#DFC5A4', '#FFE500'],
  4039. ['#009900', '#006600', '#99BB00', '#B8D100', '#60D978', '#00D5FF'],
  4040. ['#337FE5', '#003399', '#4C33E5', '#9933E5', '#CC33E5', '#EE33EE'],
  4041. ['#FFFFFF', '#CCCCCC', '#999999', '#666666', '#333333', '#000000']
  4042. ];
  4043. self.selectedColor = (options.selectedColor || '').toLowerCase();
  4044. self._cells = [];
  4045. self.div.addClass('ke-colorpicker').bind('click,mousedown', function(e){
  4046. e.stopPropagation();
  4047. }).attr('unselectable', 'on');
  4048. var table = self.doc.createElement('table');
  4049. self.div.append(table);
  4050. table.className = 'ke-colorpicker-table';
  4051. table.cellPadding = 0;
  4052. table.cellSpacing = 0;
  4053. table.border = 0;
  4054. var row = table.insertRow(0), cell = row.insertCell(0);
  4055. cell.colSpan = colors[0].length;
  4056. self._addAttr(cell, '', 'ke-colorpicker-cell-top');
  4057. for (var i = 0; i < colors.length; i++) {
  4058. row = table.insertRow(i + 1);
  4059. for (var j = 0; j < colors[i].length; j++) {
  4060. cell = row.insertCell(j);
  4061. self._addAttr(cell, colors[i][j], 'ke-colorpicker-cell');
  4062. }
  4063. }
  4064. },
  4065. _addAttr : function(cell, color, cls) {
  4066. var self = this;
  4067. cell = K(cell).addClass(cls);
  4068. if (self.selectedColor === color.toLowerCase()) {
  4069. cell.addClass('ke-colorpicker-cell-selected');
  4070. }
  4071. cell.attr('title', color || self.options.noColor);
  4072. cell.mouseover(function(e) {
  4073. K(this).addClass('ke-colorpicker-cell-on');
  4074. });
  4075. cell.mouseout(function(e) {
  4076. K(this).removeClass('ke-colorpicker-cell-on');
  4077. });
  4078. cell.click(function(e) {
  4079. e.stop();
  4080. self.options.click.call(K(this), color);
  4081. });
  4082. if (color) {
  4083. cell.append(K('<div class="ke-colorpicker-cell-color" unselectable="on"></div>').css('background-color', color));
  4084. } else {
  4085. cell.html(self.options.noColor);
  4086. }
  4087. K(cell).attr('unselectable', 'on');
  4088. self._cells.push(cell);
  4089. },
  4090. remove : function() {
  4091. var self = this;
  4092. _each(self._cells, function() {
  4093. this.unbind();
  4094. });
  4095. KColorPicker.parent.remove.call(self);
  4096. return self;
  4097. }
  4098. });
  4099. function _colorpicker(options) {
  4100. return new KColorPicker(options);
  4101. }
  4102. K.ColorPickerClass = KColorPicker;
  4103. K.colorpicker = _colorpicker;
  4104. function KUploadButton(options) {
  4105. this.init(options);
  4106. }
  4107. _extend(KUploadButton, {
  4108. init : function(options) {
  4109. var self = this,
  4110. button = K(options.button),
  4111. fieldName = options.fieldName || 'file',
  4112. url = options.url || '',
  4113. title = button.val(),
  4114. extraParams = options.extraParams || {},
  4115. cls = button[0].className || '',
  4116. target = options.target || 'kindeditor_upload_iframe_' + new Date().getTime();
  4117. options.afterError = options.afterError || function(str) {
  4118. alert(str);
  4119. };
  4120. var hiddenElements = [];
  4121. for(var k in extraParams){
  4122. hiddenElements.push('<input type="hidden" name="' + k + '" value="' + extraParams[k] + '" />');
  4123. }
  4124. var html = [
  4125. '<div class="ke-inline-block ' + cls + '">',
  4126. (options.target ? '' : '<iframe name="' + target + '" style="display:none;"></iframe>'),
  4127. (options.form ? '<div class="ke-upload-area">' : '<form class="ke-upload-area ke-form" method="post" enctype="multipart/form-data" target="' + target + '" action="' + url + '">'),
  4128. '<span class="ke-button-common">',
  4129. hiddenElements.join(''),
  4130. '<input type="button" class="ke-button-common ke-button" value="' + title + '" />',
  4131. '</span>',
  4132. '<input type="file" class="ke-upload-file" name="' + fieldName + '" tabindex="-1" />',
  4133. (options.form ? '</div>' : '</form>'),
  4134. '</div>'].join('');
  4135. var div = K(html, button.doc);
  4136. button.hide();
  4137. button.before(div);
  4138. self.div = div;
  4139. self.button = button;
  4140. self.iframe = options.target ? K('iframe[name="' + target + '"]') : K('iframe', div);
  4141. self.form = options.form ? K(options.form) : K('form', div);
  4142. var width = options.width || K('.ke-button-common', div).width();
  4143. self.fileBox = K('.ke-upload-file', div).width(width);
  4144. self.options = options;
  4145. },
  4146. submit : function() {
  4147. var self = this,
  4148. iframe = self.iframe;
  4149. iframe.bind('load', function() {
  4150. iframe.unbind();
  4151. var tempForm = document.createElement('form');
  4152. self.fileBox.before(tempForm);
  4153. K(tempForm).append(self.fileBox);
  4154. tempForm.reset();
  4155. K(tempForm).remove(true);
  4156. var doc = K.iframeDoc(iframe),
  4157. pre = doc.getElementsByTagName('pre')[0],
  4158. str = '', data;
  4159. if (pre) {
  4160. str = pre.innerHTML;
  4161. } else {
  4162. str = doc.body.innerHTML;
  4163. }
  4164. str = _unescape(str);
  4165. iframe[0].src = 'javascript:false';
  4166. try {
  4167. data = K.json(str);
  4168. } catch (e) {
  4169. self.options.afterError.call(self, '<!doctype html><html>' + doc.body.parentNode.innerHTML + '</html>');
  4170. }
  4171. if (data) {
  4172. self.options.afterUpload.call(self, data);
  4173. }
  4174. });
  4175. self.form[0].submit();
  4176. return self;
  4177. },
  4178. remove : function() {
  4179. var self = this;
  4180. if (self.fileBox) {
  4181. self.fileBox.unbind();
  4182. }
  4183. self.iframe.remove();
  4184. self.div.remove();
  4185. self.button.show();
  4186. return self;
  4187. }
  4188. });
  4189. function _uploadbutton(options) {
  4190. return new KUploadButton(options);
  4191. }
  4192. K.UploadButtonClass = KUploadButton;
  4193. K.uploadbutton = _uploadbutton;
  4194. function _createButton(arg) {
  4195. arg = arg || {};
  4196. var name = arg.name || '',
  4197. span = K('<span class="ke-button-common ke-button-outer" title="' + name + '"></span>'),
  4198. btn = K('<input class="ke-button-common ke-button" type="button" value="' + name + '" />');
  4199. if (arg.click) {
  4200. btn.click(arg.click);
  4201. }
  4202. span.append(btn);
  4203. return span;
  4204. }
  4205. function KDialog(options) {
  4206. this.init(options);
  4207. }
  4208. _extend(KDialog, KWidget, {
  4209. init : function(options) {
  4210. var self = this;
  4211. var shadowMode = _undef(options.shadowMode, true);
  4212. options.z = options.z || 811213;
  4213. options.shadowMode = false;
  4214. options.autoScroll = _undef(options.autoScroll, true);
  4215. KDialog.parent.init.call(self, options);
  4216. var title = options.title,
  4217. body = K(options.body, self.doc),
  4218. previewBtn = options.previewBtn,
  4219. yesBtn = options.yesBtn,
  4220. noBtn = options.noBtn,
  4221. closeBtn = options.closeBtn,
  4222. showMask = _undef(options.showMask, true);
  4223. self.div.addClass('ke-dialog').bind('click,mousedown', function(e){
  4224. e.stopPropagation();
  4225. });
  4226. var contentDiv = K('<div class="ke-dialog-content"></div>').appendTo(self.div);
  4227. if (_IE && _V < 7) {
  4228. self.iframeMask = K('<iframe src="about:blank" class="ke-dialog-shadow"></iframe>').appendTo(self.div);
  4229. } else if (shadowMode) {
  4230. K('<div class="ke-dialog-shadow"></div>').appendTo(self.div);
  4231. }
  4232. var headerDiv = K('<div class="ke-dialog-header"></div>');
  4233. contentDiv.append(headerDiv);
  4234. headerDiv.html(title);
  4235. self.closeIcon = K('<span class="ke-dialog-icon-close" title="' + closeBtn.name + '"></span>').click(closeBtn.click);
  4236. headerDiv.append(self.closeIcon);
  4237. self.draggable({
  4238. clickEl : headerDiv,
  4239. beforeDrag : options.beforeDrag
  4240. });
  4241. var bodyDiv = K('<div class="ke-dialog-body"></div>');
  4242. contentDiv.append(bodyDiv);
  4243. bodyDiv.append(body);
  4244. var footerDiv = K('<div class="ke-dialog-footer"></div>');
  4245. if (previewBtn || yesBtn || noBtn) {
  4246. contentDiv.append(footerDiv);
  4247. }
  4248. _each([
  4249. { btn : previewBtn, name : 'preview' },
  4250. { btn : yesBtn, name : 'yes' },
  4251. { btn : noBtn, name : 'no' }
  4252. ], function() {
  4253. if (this.btn) {
  4254. var button = _createButton(this.btn);
  4255. button.addClass('ke-dialog-' + this.name);
  4256. footerDiv.append(button);
  4257. }
  4258. });
  4259. if (self.height) {
  4260. bodyDiv.height(_removeUnit(self.height) - headerDiv.height() - footerDiv.height());
  4261. }
  4262. self.div.width(self.div.width());
  4263. self.div.height(self.div.height());
  4264. self.mask = null;
  4265. if (showMask) {
  4266. var docEl = _docElement(self.doc),
  4267. docWidth = Math.max(docEl.scrollWidth, docEl.clientWidth),
  4268. docHeight = Math.max(docEl.scrollHeight, docEl.clientHeight);
  4269. self.mask = _widget({
  4270. x : 0,
  4271. y : 0,
  4272. z : self.z - 1,
  4273. cls : 'ke-dialog-mask',
  4274. width : docWidth,
  4275. height : docHeight
  4276. });
  4277. }
  4278. self.autoPos(self.div.width(), self.div.height());
  4279. self.footerDiv = footerDiv;
  4280. self.bodyDiv = bodyDiv;
  4281. self.headerDiv = headerDiv;
  4282. self.isLoading = false;
  4283. },
  4284. setMaskIndex : function(z) {
  4285. var self = this;
  4286. self.mask.div.css('z-index', z);
  4287. },
  4288. showLoading : function(msg) {
  4289. msg = _undef(msg, '');
  4290. var self = this, body = self.bodyDiv;
  4291. self.loading = K('<div class="ke-dialog-loading"><div class="ke-inline-block ke-dialog-loading-content" style="margin-top:' + Math.round(body.height() / 3) + 'px;">' + msg + '</div></div>')
  4292. .width(body.width()).height(body.height())
  4293. .css('top', self.headerDiv.height() + 'px');
  4294. body.css('visibility', 'hidden').after(self.loading);
  4295. self.isLoading = true;
  4296. return self;
  4297. },
  4298. hideLoading : function() {
  4299. this.loading && this.loading.remove();
  4300. this.bodyDiv.css('visibility', 'visible');
  4301. this.isLoading = false;
  4302. return this;
  4303. },
  4304. remove : function() {
  4305. var self = this;
  4306. if (self.options.beforeRemove) {
  4307. self.options.beforeRemove.call(self);
  4308. }
  4309. self.mask && self.mask.remove();
  4310. self.iframeMask && self.iframeMask.remove();
  4311. self.closeIcon.unbind();
  4312. K('input', self.div).unbind();
  4313. K('button', self.div).unbind();
  4314. self.footerDiv.unbind();
  4315. self.bodyDiv.unbind();
  4316. self.headerDiv.unbind();
  4317. K('iframe', self.div).each(function() {
  4318. K(this).remove();
  4319. });
  4320. KDialog.parent.remove.call(self);
  4321. return self;
  4322. }
  4323. });
  4324. function _dialog(options) {
  4325. return new KDialog(options);
  4326. }
  4327. K.DialogClass = KDialog;
  4328. K.dialog = _dialog;
  4329. function _tabs(options) {
  4330. var self = _widget(options),
  4331. remove = self.remove,
  4332. afterSelect = options.afterSelect,
  4333. div = self.div,
  4334. liList = [];
  4335. div.addClass('ke-tabs')
  4336. .bind('contextmenu,mousedown,mousemove', function(e) {
  4337. e.preventDefault();
  4338. });
  4339. var ul = K('<ul class="ke-tabs-ul ke-clearfix"></ul>');
  4340. div.append(ul);
  4341. self.add = function(tab) {
  4342. var li = K('<li class="ke-tabs-li">' + tab.title + '</li>');
  4343. li.data('tab', tab);
  4344. liList.push(li);
  4345. ul.append(li);
  4346. };
  4347. self.selectedIndex = 0;
  4348. self.select = function(index) {
  4349. self.selectedIndex = index;
  4350. _each(liList, function(i, li) {
  4351. li.unbind();
  4352. if (i === index) {
  4353. li.addClass('ke-tabs-li-selected');
  4354. K(li.data('tab').panel).show('');
  4355. } else {
  4356. li.removeClass('ke-tabs-li-selected').removeClass('ke-tabs-li-on')
  4357. .mouseover(function() {
  4358. K(this).addClass('ke-tabs-li-on');
  4359. })
  4360. .mouseout(function() {
  4361. K(this).removeClass('ke-tabs-li-on');
  4362. })
  4363. .click(function() {
  4364. self.select(i);
  4365. });
  4366. K(li.data('tab').panel).hide();
  4367. }
  4368. });
  4369. if (afterSelect) {
  4370. afterSelect.call(self, index);
  4371. }
  4372. };
  4373. self.remove = function() {
  4374. _each(liList, function() {
  4375. this.remove();
  4376. });
  4377. ul.remove();
  4378. remove.call(self);
  4379. };
  4380. return self;
  4381. }
  4382. K.tabs = _tabs;
  4383. function _loadScript(url, fn) {
  4384. var head = document.getElementsByTagName('head')[0] || (_QUIRKS ? document.body : document.documentElement),
  4385. script = document.createElement('script');
  4386. head.appendChild(script);
  4387. script.src = url;
  4388. script.charset = 'utf-8';
  4389. script.onload = script.onreadystatechange = function() {
  4390. if (!this.readyState || this.readyState === 'loaded') {
  4391. if (fn) {
  4392. fn();
  4393. }
  4394. script.onload = script.onreadystatechange = null;
  4395. head.removeChild(script);
  4396. }
  4397. };
  4398. }
  4399. function _chopQuery(url) {
  4400. var index = url.indexOf('?');
  4401. return index > 0 ? url.substr(0, index) : url;
  4402. }
  4403. function _loadStyle(url) {
  4404. var head = document.getElementsByTagName('head')[0] || (_QUIRKS ? document.body : document.documentElement),
  4405. link = document.createElement('link'),
  4406. absoluteUrl = _chopQuery(_formatUrl(url, 'absolute'));
  4407. var links = K('link[rel="stylesheet"]', head);
  4408. for (var i = 0, len = links.length; i < len; i++) {
  4409. if (_chopQuery(_formatUrl(links[i].href, 'absolute')) === absoluteUrl) {
  4410. return;
  4411. }
  4412. }
  4413. head.appendChild(link);
  4414. link.href = url;
  4415. link.rel = 'stylesheet';
  4416. }
  4417. function _ajax(url, fn, method, param, dataType) {
  4418. method = method || 'GET';
  4419. dataType = dataType || 'json';
  4420. var xhr = window.XMLHttpRequest ? new window.XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
  4421. xhr.open(method, url, true);
  4422. xhr.onreadystatechange = function () {
  4423. if (xhr.readyState == 4 && xhr.status == 200) {
  4424. if (fn) {
  4425. var data = _trim(xhr.responseText);
  4426. if (dataType == 'json') {
  4427. data = _json(data);
  4428. }
  4429. fn(data);
  4430. }
  4431. }
  4432. };
  4433. if (method == 'POST') {
  4434. var params = [];
  4435. _each(param, function(key, val) {
  4436. params.push(encodeURIComponent(key) + '=' + encodeURIComponent(val));
  4437. });
  4438. try {
  4439. xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  4440. } catch (e) {}
  4441. xhr.send(params.join('&'));
  4442. } else {
  4443. xhr.send(null);
  4444. }
  4445. }
  4446. K.loadScript = _loadScript;
  4447. K.loadStyle = _loadStyle;
  4448. K.ajax = _ajax;
  4449. var _plugins = {};
  4450. function _plugin(name, fn) {
  4451. if (name === undefined) {
  4452. return _plugins;
  4453. }
  4454. if (!fn) {
  4455. return _plugins[name];
  4456. }
  4457. _plugins[name] = fn;
  4458. }
  4459. var _language = {};
  4460. function _parseLangKey(key) {
  4461. var match, ns = 'core';
  4462. if ((match = /^(\w+)\.(\w+)$/.exec(key))) {
  4463. ns = match[1];
  4464. key = match[2];
  4465. }
  4466. return { ns : ns, key : key };
  4467. }
  4468. function _lang(mixed, langType) {
  4469. langType = langType === undefined ? K.options.langType : langType;
  4470. if (typeof mixed === 'string') {
  4471. if (!_language[langType]) {
  4472. return 'no language';
  4473. }
  4474. var pos = mixed.length - 1;
  4475. if (mixed.substr(pos) === '.') {
  4476. return _language[langType][mixed.substr(0, pos)];
  4477. }
  4478. var obj = _parseLangKey(mixed);
  4479. return _language[langType][obj.ns][obj.key];
  4480. }
  4481. _each(mixed, function(key, val) {
  4482. var obj = _parseLangKey(key);
  4483. if (!_language[langType]) {
  4484. _language[langType] = {};
  4485. }
  4486. if (!_language[langType][obj.ns]) {
  4487. _language[langType][obj.ns] = {};
  4488. }
  4489. _language[langType][obj.ns][obj.key] = val;
  4490. });
  4491. }
  4492. function _getImageFromRange(range, fn) {
  4493. if (range.collapsed) {
  4494. return;
  4495. }
  4496. range = range.cloneRange().up();
  4497. var sc = range.startContainer, so = range.startOffset;
  4498. if (!_WEBKIT && !range.isControl()) {
  4499. return;
  4500. }
  4501. var img = K(sc.childNodes[so]);
  4502. if (!img || img.name != 'img') {
  4503. return;
  4504. }
  4505. if (fn(img)) {
  4506. return img;
  4507. }
  4508. }
  4509. function _bindContextmenuEvent() {
  4510. var self = this, doc = self.edit.doc;
  4511. K(doc).contextmenu(function(e) {
  4512. if (self.menu) {
  4513. self.hideMenu();
  4514. }
  4515. if (!self.useContextmenu) {
  4516. e.preventDefault();
  4517. return;
  4518. }
  4519. if (self._contextmenus.length === 0) {
  4520. return;
  4521. }
  4522. var maxWidth = 0, items = [];
  4523. _each(self._contextmenus, function() {
  4524. if (this.title == '-') {
  4525. items.push(this);
  4526. return;
  4527. }
  4528. if (this.cond && this.cond()) {
  4529. items.push(this);
  4530. if (this.width && this.width > maxWidth) {
  4531. maxWidth = this.width;
  4532. }
  4533. }
  4534. });
  4535. while (items.length > 0 && items[0].title == '-') {
  4536. items.shift();
  4537. }
  4538. while (items.length > 0 && items[items.length - 1].title == '-') {
  4539. items.pop();
  4540. }
  4541. var prevItem = null;
  4542. _each(items, function(i) {
  4543. if (this.title == '-' && prevItem.title == '-') {
  4544. delete items[i];
  4545. }
  4546. prevItem = this;
  4547. });
  4548. if (items.length > 0) {
  4549. e.preventDefault();
  4550. var pos = K(self.edit.iframe).pos(),
  4551. menu = _menu({
  4552. x : pos.x + e.clientX,
  4553. y : pos.y + e.clientY,
  4554. width : maxWidth,
  4555. css : { visibility: 'hidden' },
  4556. shadowMode : self.shadowMode
  4557. });
  4558. _each(items, function() {
  4559. if (this.title) {
  4560. menu.addItem(this);
  4561. }
  4562. });
  4563. var docEl = _docElement(menu.doc),
  4564. menuHeight = menu.div.height();
  4565. if (e.clientY + menuHeight >= docEl.clientHeight - 100) {
  4566. menu.pos(menu.x, _removeUnit(menu.y) - menuHeight);
  4567. }
  4568. menu.div.css('visibility', 'visible');
  4569. self.menu = menu;
  4570. }
  4571. });
  4572. }
  4573. function _bindNewlineEvent() {
  4574. var self = this, doc = self.edit.doc, newlineTag = self.newlineTag;
  4575. if (_IE && newlineTag !== 'br') {
  4576. return;
  4577. }
  4578. if (_GECKO && _V < 3 && newlineTag !== 'p') {
  4579. return;
  4580. }
  4581. if (_OPERA && _V < 9) {
  4582. return;
  4583. }
  4584. var brSkipTagMap = _toMap('h1,h2,h3,h4,h5,h6,pre,li'),
  4585. pSkipTagMap = _toMap('p,h1,h2,h3,h4,h5,h6,pre,li,blockquote');
  4586. function getAncestorTagName(range) {
  4587. var ancestor = K(range.commonAncestor());
  4588. while (ancestor) {
  4589. if (ancestor.type == 1 && !ancestor.isStyle()) {
  4590. break;
  4591. }
  4592. ancestor = ancestor.parent();
  4593. }
  4594. return ancestor.name;
  4595. }
  4596. K(doc).keydown(function(e) {
  4597. if (e.which != 13 || e.shiftKey || e.ctrlKey || e.altKey) {
  4598. return;
  4599. }
  4600. self.cmd.selection();
  4601. var tagName = getAncestorTagName(self.cmd.range);
  4602. if (tagName == 'marquee' || tagName == 'select') {
  4603. return;
  4604. }
  4605. if (newlineTag === 'br' && !brSkipTagMap[tagName]) {
  4606. e.preventDefault();
  4607. self.insertHtml('<br />' + (_IE && _V < 9 ? '' : '\u200B'));
  4608. return;
  4609. }
  4610. if (!pSkipTagMap[tagName]) {
  4611. _nativeCommand(doc, 'formatblock', '<p>');
  4612. }
  4613. });
  4614. K(doc).keyup(function(e) {
  4615. if (e.which != 13 || e.shiftKey || e.ctrlKey || e.altKey) {
  4616. return;
  4617. }
  4618. if (newlineTag == 'br') {
  4619. return;
  4620. }
  4621. if (_GECKO) {
  4622. var root = self.cmd.commonAncestor('p');
  4623. var a = self.cmd.commonAncestor('a');
  4624. if (a && a.text() == '') {
  4625. a.remove(true);
  4626. self.cmd.range.selectNodeContents(root[0]).collapse(true);
  4627. self.cmd.select();
  4628. }
  4629. return;
  4630. }
  4631. self.cmd.selection();
  4632. var tagName = getAncestorTagName(self.cmd.range);
  4633. if (tagName == 'marquee' || tagName == 'select') {
  4634. return;
  4635. }
  4636. if (!pSkipTagMap[tagName]) {
  4637. _nativeCommand(doc, 'formatblock', '<p>');
  4638. }
  4639. var div = self.cmd.commonAncestor('div');
  4640. if (div) {
  4641. var p = K('<p></p>'),
  4642. child = div[0].firstChild;
  4643. while (child) {
  4644. var next = child.nextSibling;
  4645. p.append(child);
  4646. child = next;
  4647. }
  4648. div.before(p);
  4649. div.remove();
  4650. self.cmd.range.selectNodeContents(p[0]);
  4651. self.cmd.select();
  4652. }
  4653. });
  4654. }
  4655. function _bindTabEvent() {
  4656. var self = this, doc = self.edit.doc;
  4657. K(doc).keydown(function(e) {
  4658. if (e.which == 9) {
  4659. e.preventDefault();
  4660. if (self.afterTab) {
  4661. self.afterTab.call(self, e);
  4662. return;
  4663. }
  4664. var cmd = self.cmd, range = cmd.range;
  4665. range.shrink();
  4666. if (range.collapsed && range.startContainer.nodeType == 1) {
  4667. range.insertNode(K('@&nbsp;', doc)[0]);
  4668. cmd.select();
  4669. }
  4670. self.insertHtml('&nbsp;&nbsp;&nbsp;&nbsp;');
  4671. }
  4672. });
  4673. }
  4674. function _bindFocusEvent() {
  4675. var self = this;
  4676. K(self.edit.textarea[0], self.edit.win).focus(function(e) {
  4677. if (self.afterFocus) {
  4678. self.afterFocus.call(self, e);
  4679. }
  4680. }).blur(function(e) {
  4681. if (self.afterBlur) {
  4682. self.afterBlur.call(self, e);
  4683. }
  4684. });
  4685. }
  4686. function _removeBookmarkTag(html) {
  4687. return _trim(html.replace(/<span [^>]*id="?__kindeditor_bookmark_\w+_\d+__"?[^>]*><\/span>/ig, ''));
  4688. }
  4689. function _removeTempTag(html) {
  4690. return html.replace(/<div[^>]+class="?__kindeditor_paste__"?[^>]*>[\s\S]*?<\/div>/ig, '');
  4691. }
  4692. function _addBookmarkToStack(stack, bookmark) {
  4693. if (stack.length === 0) {
  4694. stack.push(bookmark);
  4695. return;
  4696. }
  4697. var prev = stack[stack.length - 1];
  4698. if (_removeBookmarkTag(bookmark.html) !== _removeBookmarkTag(prev.html)) {
  4699. stack.push(bookmark);
  4700. }
  4701. }
  4702. function _undoToRedo(fromStack, toStack) {
  4703. var self = this, edit = self.edit,
  4704. body = edit.doc.body,
  4705. range, bookmark;
  4706. if (fromStack.length === 0) {
  4707. return self;
  4708. }
  4709. if (edit.designMode) {
  4710. range = self.cmd.range;
  4711. bookmark = range.createBookmark(true);
  4712. bookmark.html = body.innerHTML;
  4713. } else {
  4714. bookmark = {
  4715. html : body.innerHTML
  4716. };
  4717. }
  4718. _addBookmarkToStack(toStack, bookmark);
  4719. var prev = fromStack.pop();
  4720. if (_removeBookmarkTag(bookmark.html) === _removeBookmarkTag(prev.html) && fromStack.length > 0) {
  4721. prev = fromStack.pop();
  4722. }
  4723. if (edit.designMode) {
  4724. edit.html(prev.html);
  4725. if (prev.start) {
  4726. range.moveToBookmark(prev);
  4727. self.select();
  4728. }
  4729. } else {
  4730. K(body).html(_removeBookmarkTag(prev.html));
  4731. }
  4732. return self;
  4733. }
  4734. function KEditor(options) {
  4735. var self = this;
  4736. self.options = {};
  4737. function setOption(key, val) {
  4738. if (KEditor.prototype[key] === undefined) {
  4739. self[key] = val;
  4740. }
  4741. self.options[key] = val;
  4742. }
  4743. _each(options, function(key, val) {
  4744. setOption(key, options[key]);
  4745. });
  4746. _each(K.options, function(key, val) {
  4747. if (self[key] === undefined) {
  4748. setOption(key, val);
  4749. }
  4750. });
  4751. var se = K(self.srcElement || '<textarea/>');
  4752. if (!self.width) {
  4753. self.width = se[0].style.width || se.width();
  4754. }
  4755. if (!self.height) {
  4756. self.height = se[0].style.height || se.height();
  4757. }
  4758. setOption('width', _undef(self.width, self.minWidth));
  4759. setOption('height', _undef(self.height, self.minHeight));
  4760. setOption('width', _addUnit(self.width));
  4761. setOption('height', _addUnit(self.height));
  4762. if (_MOBILE && (!_IOS || _V < 534)) {
  4763. self.designMode = false;
  4764. }
  4765. self.srcElement = se;
  4766. self.initContent = '';
  4767. self.plugin = {};
  4768. self.isCreated = false;
  4769. self.isLoading = false;
  4770. self._handlers = {};
  4771. self._contextmenus = [];
  4772. self._undoStack = [];
  4773. self._redoStack = [];
  4774. self._calledPlugins = {};
  4775. self._firstAddBookmark = true;
  4776. self.menu = self.contextmenu = null;
  4777. self.dialogs = [];
  4778. }
  4779. KEditor.prototype = {
  4780. lang : function(mixed) {
  4781. return _lang(mixed, this.langType);
  4782. },
  4783. loadPlugin : function(name, fn) {
  4784. var self = this;
  4785. if (_plugins[name]) {
  4786. if (self._calledPlugins[name]) {
  4787. if (fn) {
  4788. fn.call(self);
  4789. }
  4790. return self;
  4791. }
  4792. _plugins[name].call(self, KindEditor);
  4793. if (fn) {
  4794. fn.call(self);
  4795. }
  4796. self._calledPlugins[name] = true;
  4797. return self;
  4798. }
  4799. if (self.isLoading) {
  4800. return self;
  4801. }
  4802. self.isLoading = true;
  4803. _loadScript(self.pluginsPath + name + '/' + name + '.js?ver=' + encodeURIComponent(K.DEBUG ? _TIME : _VERSION), function() {
  4804. self.isLoading = false;
  4805. if (_plugins[name]) {
  4806. self.loadPlugin(name, fn);
  4807. }
  4808. });
  4809. return self;
  4810. },
  4811. handler : function(key, fn) {
  4812. var self = this;
  4813. if (!self._handlers[key]) {
  4814. self._handlers[key] = [];
  4815. }
  4816. if (_isFunction(fn)) {
  4817. self._handlers[key].push(fn);
  4818. return self;
  4819. }
  4820. _each(self._handlers[key], function() {
  4821. fn = this.call(self, fn);
  4822. });
  4823. return fn;
  4824. },
  4825. clickToolbar : function(name, fn) {
  4826. var self = this, key = 'clickToolbar' + name;
  4827. if (fn === undefined) {
  4828. if (self._handlers[key]) {
  4829. return self.handler(key);
  4830. }
  4831. self.loadPlugin(name, function() {
  4832. self.handler(key);
  4833. });
  4834. return self;
  4835. }
  4836. return self.handler(key, fn);
  4837. },
  4838. updateState : function() {
  4839. var self = this;
  4840. _each(('justifyleft,justifycenter,justifyright,justifyfull,insertorderedlist,insertunorderedlist,' +
  4841. 'subscript,superscript,bold,italic,underline,strikethrough').split(','), function(i, name) {
  4842. self.cmd.state(name) ? self.toolbar.select(name) : self.toolbar.unselect(name);
  4843. });
  4844. return self;
  4845. },
  4846. addContextmenu : function(item) {
  4847. this._contextmenus.push(item);
  4848. return this;
  4849. },
  4850. afterCreate : function(fn) {
  4851. return this.handler('afterCreate', fn);
  4852. },
  4853. beforeRemove : function(fn) {
  4854. return this.handler('beforeRemove', fn);
  4855. },
  4856. beforeGetHtml : function(fn) {
  4857. return this.handler('beforeGetHtml', fn);
  4858. },
  4859. beforeSetHtml : function(fn) {
  4860. return this.handler('beforeSetHtml', fn);
  4861. },
  4862. afterSetHtml : function(fn) {
  4863. return this.handler('afterSetHtml', fn);
  4864. },
  4865. create : function() {
  4866. var self = this, fullscreenMode = self.fullscreenMode;
  4867. if (self.isCreated) {
  4868. return self;
  4869. }
  4870. if (self.srcElement.data('kindeditor')) {
  4871. return self;
  4872. }
  4873. self.srcElement.data('kindeditor', 'true');
  4874. if (fullscreenMode) {
  4875. _docElement().style.overflow = 'hidden';
  4876. } else {
  4877. _docElement().style.overflow = '';
  4878. }
  4879. var width = fullscreenMode ? _docElement().clientWidth + 'px' : self.width,
  4880. height = fullscreenMode ? _docElement().clientHeight + 'px' : self.height;
  4881. if ((_IE && _V < 8) || _QUIRKS) {
  4882. height = _addUnit(_removeUnit(height) + 2);
  4883. }
  4884. var container = self.container = K(self.layout);
  4885. if (fullscreenMode) {
  4886. K(document.body).append(container);
  4887. } else {
  4888. self.srcElement.before(container);
  4889. }
  4890. var toolbarDiv = K('.toolbar', container),
  4891. editDiv = K('.edit', container),
  4892. statusbar = self.statusbar = K('.statusbar', container);
  4893. container.removeClass('container')
  4894. .addClass('ke-container ke-container-' + self.themeType).css('width', width);
  4895. if (fullscreenMode) {
  4896. container.css({
  4897. position : 'absolute',
  4898. left : 0,
  4899. top : 0,
  4900. 'z-index' : 811211
  4901. });
  4902. if (!_GECKO) {
  4903. self._scrollPos = _getScrollPos();
  4904. }
  4905. window.scrollTo(0, 0);
  4906. K(document.body).css({
  4907. 'height' : '1px',
  4908. 'overflow' : 'hidden'
  4909. });
  4910. K(document.body.parentNode).css('overflow', 'hidden');
  4911. self._fullscreenExecuted = true;
  4912. } else {
  4913. if (self._fullscreenExecuted) {
  4914. K(document.body).css({
  4915. 'height' : '',
  4916. 'overflow' : ''
  4917. });
  4918. K(document.body.parentNode).css('overflow', '');
  4919. }
  4920. if (self._scrollPos) {
  4921. window.scrollTo(self._scrollPos.x, self._scrollPos.y);
  4922. }
  4923. }
  4924. var htmlList = [];
  4925. K.each(self.items, function(i, name) {
  4926. if (name == '|') {
  4927. htmlList.push('<span class="ke-inline-block ke-separator"></span>');
  4928. } else if (name == '/') {
  4929. htmlList.push('<div class="ke-hr"></div>');
  4930. } else {
  4931. htmlList.push('<span class="ke-outline" data-name="' + name + '" title="' + self.lang(name) + '" unselectable="on">');
  4932. htmlList.push('<span class="ke-toolbar-icon ke-toolbar-icon-url ke-icon-' + name + '" unselectable="on"></span></span>');
  4933. }
  4934. });
  4935. var toolbar = self.toolbar = _toolbar({
  4936. src : toolbarDiv,
  4937. html : htmlList.join(''),
  4938. noDisableItems : self.noDisableItems,
  4939. click : function(e, name) {
  4940. e.stop();
  4941. if (self.menu) {
  4942. var menuName = self.menu.name;
  4943. self.hideMenu();
  4944. if (menuName === name) {
  4945. return;
  4946. }
  4947. }
  4948. self.clickToolbar(name);
  4949. }
  4950. });
  4951. var editHeight = _removeUnit(height) - toolbar.div.height();
  4952. var edit = self.edit = _edit({
  4953. height : editHeight > 0 && _removeUnit(height) > self.minHeight ? editHeight : self.minHeight,
  4954. src : editDiv,
  4955. srcElement : self.srcElement,
  4956. designMode : self.designMode,
  4957. themesPath : self.themesPath,
  4958. bodyClass : self.bodyClass,
  4959. cssPath : self.cssPath,
  4960. cssData : self.cssData,
  4961. beforeGetHtml : function(html) {
  4962. html = self.beforeGetHtml(html);
  4963. return _formatHtml(html, self.filterMode ? self.htmlTags : null, self.urlType, self.wellFormatMode, self.indentChar);
  4964. },
  4965. beforeSetHtml : function(html) {
  4966. html = _formatHtml(html, self.filterMode ? self.htmlTags : null, '', false);
  4967. return self.beforeSetHtml(html);
  4968. },
  4969. afterSetHtml : function() {
  4970. self.edit = edit = this;
  4971. self.afterSetHtml();
  4972. },
  4973. afterCreate : function() {
  4974. self.edit = edit = this;
  4975. self.cmd = edit.cmd;
  4976. self._docMousedownFn = function(e) {
  4977. if (self.menu) {
  4978. self.hideMenu();
  4979. }
  4980. };
  4981. K(edit.doc, document).mousedown(self._docMousedownFn);
  4982. _bindContextmenuEvent.call(self);
  4983. _bindNewlineEvent.call(self);
  4984. _bindTabEvent.call(self);
  4985. _bindFocusEvent.call(self);
  4986. edit.afterChange(function(e) {
  4987. if (!edit.designMode) {
  4988. return;
  4989. }
  4990. self.updateState();
  4991. self.addBookmark();
  4992. if (self.options.afterChange) {
  4993. self.options.afterChange.call(self);
  4994. }
  4995. });
  4996. edit.textarea.keyup(function(e) {
  4997. if (!e.ctrlKey && !e.altKey && _INPUT_KEY_MAP[e.which]) {
  4998. if (self.options.afterChange) {
  4999. self.options.afterChange.call(self);
  5000. }
  5001. }
  5002. });
  5003. if (self.readonlyMode) {
  5004. self.readonly();
  5005. }
  5006. self.isCreated = true;
  5007. if (self.initContent === '') {
  5008. self.initContent = self.html();
  5009. }
  5010. self.afterCreate();
  5011. if (self.options.afterCreate) {
  5012. self.options.afterCreate.call(self);
  5013. }
  5014. }
  5015. });
  5016. statusbar.removeClass('statusbar').addClass('ke-statusbar')
  5017. .append('<span class="ke-inline-block ke-statusbar-center-icon"></span>')
  5018. .append('<span class="ke-inline-block ke-statusbar-right-icon"></span>');
  5019. if (self._fullscreenResizeHandler) {
  5020. K(window).unbind('resize', self._fullscreenResizeHandler);
  5021. self._fullscreenResizeHandler = null;
  5022. }
  5023. function initResize() {
  5024. if (statusbar.height() === 0) {
  5025. setTimeout(initResize, 100);
  5026. return;
  5027. }
  5028. self.resize(width, height, false);
  5029. }
  5030. initResize();
  5031. if (fullscreenMode) {
  5032. self._fullscreenResizeHandler = function(e) {
  5033. if (self.isCreated) {
  5034. self.resize(_docElement().clientWidth, _docElement().clientHeight, false);
  5035. }
  5036. };
  5037. K(window).bind('resize', self._fullscreenResizeHandler);
  5038. toolbar.select('fullscreen');
  5039. statusbar.first().css('visibility', 'hidden');
  5040. statusbar.last().css('visibility', 'hidden');
  5041. } else {
  5042. if (_GECKO) {
  5043. K(window).bind('scroll', function(e) {
  5044. self._scrollPos = _getScrollPos();
  5045. });
  5046. }
  5047. if (self.resizeType > 0) {
  5048. _drag({
  5049. moveEl : container,
  5050. clickEl : statusbar,
  5051. moveFn : function(x, y, width, height, diffX, diffY) {
  5052. height += diffY;
  5053. self.resize(null, height);
  5054. }
  5055. });
  5056. } else {
  5057. statusbar.first().css('visibility', 'hidden');
  5058. }
  5059. if (self.resizeType === 2) {
  5060. _drag({
  5061. moveEl : container,
  5062. clickEl : statusbar.last(),
  5063. moveFn : function(x, y, width, height, diffX, diffY) {
  5064. width += diffX;
  5065. height += diffY;
  5066. self.resize(width, height);
  5067. }
  5068. });
  5069. } else {
  5070. statusbar.last().css('visibility', 'hidden');
  5071. }
  5072. }
  5073. return self;
  5074. },
  5075. remove : function() {
  5076. var self = this;
  5077. if (!self.isCreated) {
  5078. return self;
  5079. }
  5080. self.beforeRemove();
  5081. self.srcElement.data('kindeditor', '');
  5082. if (self.menu) {
  5083. self.hideMenu();
  5084. }
  5085. _each(self.dialogs, function() {
  5086. self.hideDialog();
  5087. });
  5088. K(document).unbind('mousedown', self._docMousedownFn);
  5089. self.toolbar.remove();
  5090. self.edit.remove();
  5091. self.statusbar.last().unbind();
  5092. self.statusbar.unbind();
  5093. self.container.remove();
  5094. self.container = self.toolbar = self.edit = self.menu = null;
  5095. self.dialogs = [];
  5096. self.isCreated = false;
  5097. return self;
  5098. },
  5099. resize : function(width, height, updateProp) {
  5100. var self = this;
  5101. updateProp = _undef(updateProp, true);
  5102. if (width) {
  5103. if (!/%/.test(width)) {
  5104. width = _removeUnit(width);
  5105. width = width < self.minWidth ? self.minWidth : width;
  5106. }
  5107. self.container.css('width', _addUnit(width));
  5108. if (updateProp) {
  5109. self.width = _addUnit(width);
  5110. }
  5111. }
  5112. if (height) {
  5113. height = _removeUnit(height);
  5114. editHeight = _removeUnit(height) - self.toolbar.div.height() - self.statusbar.height();
  5115. editHeight = editHeight < self.minHeight ? self.minHeight : editHeight;
  5116. self.edit.setHeight(editHeight);
  5117. if (updateProp) {
  5118. self.height = _addUnit(height);
  5119. }
  5120. }
  5121. return self;
  5122. },
  5123. select : function() {
  5124. this.isCreated && this.cmd.select();
  5125. return this;
  5126. },
  5127. html : function(val) {
  5128. var self = this;
  5129. if (val === undefined) {
  5130. return self.isCreated ? self.edit.html() : _elementVal(self.srcElement);
  5131. }
  5132. self.isCreated ? self.edit.html(val) : _elementVal(self.srcElement, val);
  5133. if (self.isCreated) {
  5134. self.cmd.selection();
  5135. }
  5136. return self;
  5137. },
  5138. fullHtml : function() {
  5139. return this.isCreated ? this.edit.html(undefined, true) : '';
  5140. },
  5141. text : function(val) {
  5142. var self = this;
  5143. if (val === undefined) {
  5144. return _trim(self.html().replace(/<(?!img|embed).*?>/ig, '').replace(/&nbsp;/ig, ' '));
  5145. } else {
  5146. return self.html(_escape(val));
  5147. }
  5148. },
  5149. isEmpty : function() {
  5150. return _trim(this.text().replace(/\r\n|\n|\r/, '')) === '';
  5151. },
  5152. isDirty : function() {
  5153. return _trim(this.initContent.replace(/\r\n|\n|\r|t/g, '')) !== _trim(this.html().replace(/\r\n|\n|\r|t/g, ''));
  5154. },
  5155. selectedHtml : function() {
  5156. return this.isCreated ? this.cmd.range.html() : '';
  5157. },
  5158. count : function(mode) {
  5159. var self = this;
  5160. mode = (mode || 'html').toLowerCase();
  5161. if (mode === 'html') {
  5162. return _removeBookmarkTag(_removeTempTag(self.html())).length;
  5163. }
  5164. if (mode === 'text') {
  5165. return self.text().replace(/<(?:img|embed).*?>/ig, 'K').replace(/\r\n|\n|\r/g, '').length;
  5166. }
  5167. return 0;
  5168. },
  5169. exec : function(key) {
  5170. key = key.toLowerCase();
  5171. var self = this, cmd = self.cmd,
  5172. changeFlag = _inArray(key, 'selectall,copy,paste,print'.split(',')) < 0;
  5173. if (changeFlag) {
  5174. self.addBookmark(false);
  5175. }
  5176. cmd[key].apply(cmd, _toArray(arguments, 1));
  5177. if (changeFlag) {
  5178. self.updateState();
  5179. self.addBookmark(false);
  5180. if (self.options.afterChange) {
  5181. self.options.afterChange.call(self);
  5182. }
  5183. }
  5184. return self;
  5185. },
  5186. insertHtml : function(val, quickMode) {
  5187. if (!this.isCreated) {
  5188. return this;
  5189. }
  5190. val = this.beforeSetHtml(val);
  5191. this.exec('inserthtml', val, quickMode);
  5192. return this;
  5193. },
  5194. appendHtml : function(val) {
  5195. this.html(this.html() + val);
  5196. if (this.isCreated) {
  5197. var cmd = this.cmd;
  5198. cmd.range.selectNodeContents(cmd.doc.body).collapse(false);
  5199. cmd.select();
  5200. }
  5201. return this;
  5202. },
  5203. sync : function() {
  5204. _elementVal(this.srcElement, this.html());
  5205. return this;
  5206. },
  5207. focus : function() {
  5208. this.isCreated ? this.edit.focus() : this.srcElement[0].focus();
  5209. return this;
  5210. },
  5211. blur : function() {
  5212. this.isCreated ? this.edit.blur() : this.srcElement[0].blur();
  5213. return this;
  5214. },
  5215. addBookmark : function(checkSize) {
  5216. checkSize = _undef(checkSize, true);
  5217. var self = this, edit = self.edit,
  5218. body = edit.doc.body,
  5219. html = _removeTempTag(body.innerHTML), bookmark;
  5220. if (checkSize && self._undoStack.length > 0) {
  5221. var prev = self._undoStack[self._undoStack.length - 1];
  5222. if (Math.abs(html.length - _removeBookmarkTag(prev.html).length) < self.minChangeSize) {
  5223. return self;
  5224. }
  5225. }
  5226. if (edit.designMode && !self._firstAddBookmark) {
  5227. var range = self.cmd.range;
  5228. bookmark = range.createBookmark(true);
  5229. bookmark.html = _removeTempTag(body.innerHTML);
  5230. range.moveToBookmark(bookmark);
  5231. } else {
  5232. bookmark = {
  5233. html : html
  5234. };
  5235. }
  5236. self._firstAddBookmark = false;
  5237. _addBookmarkToStack(self._undoStack, bookmark);
  5238. return self;
  5239. },
  5240. undo : function() {
  5241. return _undoToRedo.call(this, this._undoStack, this._redoStack);
  5242. },
  5243. redo : function() {
  5244. return _undoToRedo.call(this, this._redoStack, this._undoStack);
  5245. },
  5246. fullscreen : function(bool) {
  5247. this.fullscreenMode = (bool === undefined ? !this.fullscreenMode : bool);
  5248. return this.remove().create();
  5249. },
  5250. readonly : function(isReadonly) {
  5251. isReadonly = _undef(isReadonly, true);
  5252. var self = this, edit = self.edit, doc = edit.doc;
  5253. if (self.designMode) {
  5254. self.toolbar.disableAll(isReadonly, []);
  5255. } else {
  5256. _each(self.noDisableItems, function() {
  5257. self.toolbar[isReadonly ? 'disable' : 'enable'](this);
  5258. });
  5259. }
  5260. if (_IE) {
  5261. doc.body.contentEditable = !isReadonly;
  5262. } else {
  5263. doc.designMode = isReadonly ? 'off' : 'on';
  5264. }
  5265. edit.textarea[0].disabled = isReadonly;
  5266. },
  5267. createMenu : function(options) {
  5268. var self = this,
  5269. name = options.name,
  5270. knode = self.toolbar.get(name),
  5271. pos = knode.pos();
  5272. options.x = pos.x;
  5273. options.y = pos.y + knode.height();
  5274. options.z = self.options.zIndex;
  5275. options.shadowMode = _undef(options.shadowMode, self.shadowMode);
  5276. if (options.selectedColor !== undefined) {
  5277. options.cls = 'ke-colorpicker-' + self.themeType;
  5278. options.noColor = self.lang('noColor');
  5279. self.menu = _colorpicker(options);
  5280. } else {
  5281. options.cls = 'ke-menu-' + self.themeType;
  5282. options.centerLineMode = false;
  5283. self.menu = _menu(options);
  5284. }
  5285. return self.menu;
  5286. },
  5287. hideMenu : function() {
  5288. this.menu.remove();
  5289. this.menu = null;
  5290. return this;
  5291. },
  5292. hideContextmenu : function() {
  5293. this.contextmenu.remove();
  5294. this.contextmenu = null;
  5295. return this;
  5296. },
  5297. createDialog : function(options) {
  5298. var self = this, name = options.name;
  5299. options.z = self.options.zIndex;
  5300. options.shadowMode = _undef(options.shadowMode, self.shadowMode);
  5301. options.closeBtn = _undef(options.closeBtn, {
  5302. name : self.lang('close'),
  5303. click : function(e) {
  5304. self.hideDialog();
  5305. if (_IE && self.cmd) {
  5306. self.cmd.select();
  5307. }
  5308. }
  5309. });
  5310. options.noBtn = _undef(options.noBtn, {
  5311. name : self.lang(options.yesBtn ? 'no' : 'close'),
  5312. click : function(e) {
  5313. self.hideDialog();
  5314. if (_IE && self.cmd) {
  5315. self.cmd.select();
  5316. }
  5317. }
  5318. });
  5319. if (self.dialogAlignType != 'page') {
  5320. options.alignEl = self.container;
  5321. }
  5322. options.cls = 'ke-dialog-' + self.themeType;
  5323. if (self.dialogs.length > 0) {
  5324. var firstDialog = self.dialogs[0],
  5325. parentDialog = self.dialogs[self.dialogs.length - 1];
  5326. firstDialog.setMaskIndex(parentDialog.z + 2);
  5327. options.z = parentDialog.z + 3;
  5328. options.showMask = false;
  5329. }
  5330. var dialog = _dialog(options);
  5331. self.dialogs.push(dialog);
  5332. return dialog;
  5333. },
  5334. hideDialog : function() {
  5335. var self = this;
  5336. if (self.dialogs.length > 0) {
  5337. self.dialogs.pop().remove();
  5338. }
  5339. if (self.dialogs.length > 0) {
  5340. var firstDialog = self.dialogs[0],
  5341. parentDialog = self.dialogs[self.dialogs.length - 1];
  5342. firstDialog.setMaskIndex(parentDialog.z - 1);
  5343. }
  5344. return self;
  5345. },
  5346. errorDialog : function(html) {
  5347. var self = this;
  5348. var dialog = self.createDialog({
  5349. width : 750,
  5350. title : self.lang('uploadError'),
  5351. body : '<div style="padding:10px 20px;"><iframe frameborder="0" style="width:708px;height:400px;"></iframe></div>'
  5352. });
  5353. var iframe = K('iframe', dialog.div), doc = K.iframeDoc(iframe);
  5354. doc.open();
  5355. doc.write(html);
  5356. doc.close();
  5357. K(doc.body).css('background-color', '#FFF');
  5358. iframe[0].contentWindow.focus();
  5359. return self;
  5360. }
  5361. };
  5362. function _editor(options) {
  5363. return new KEditor(options);
  5364. }
  5365. _instances = [];
  5366. function _create(expr, options) {
  5367. options = options || {};
  5368. options.basePath = _undef(options.basePath, K.basePath);
  5369. options.themesPath = _undef(options.themesPath, options.basePath + 'themes/');
  5370. options.langPath = _undef(options.langPath, options.basePath + 'lang/');
  5371. options.pluginsPath = _undef(options.pluginsPath, options.basePath + 'plugins/');
  5372. if (_undef(options.loadStyleMode, K.options.loadStyleMode)) {
  5373. var themeType = _undef(options.themeType, K.options.themeType);
  5374. _loadStyle(options.themesPath + 'default/default.css');
  5375. _loadStyle(options.themesPath + themeType + '/' + themeType + '.css');
  5376. }
  5377. function create(editor) {
  5378. _each(_plugins, function(name, fn) {
  5379. fn.call(editor, KindEditor);
  5380. });
  5381. return editor.create();
  5382. }
  5383. var knode = K(expr);
  5384. if (!knode || knode.length === 0) {
  5385. return;
  5386. }
  5387. if (knode.length > 1) {
  5388. knode.each(function() {
  5389. _create(this, options);
  5390. });
  5391. return _instances[0];
  5392. }
  5393. options.srcElement = knode[0];
  5394. var editor = new KEditor(options);
  5395. _instances.push(editor);
  5396. if (_language[editor.langType]) {
  5397. return create(editor);
  5398. }
  5399. _loadScript(editor.langPath + editor.langType + '.js?ver=' + encodeURIComponent(K.DEBUG ? _TIME : _VERSION), function() {
  5400. create(editor);
  5401. });
  5402. return editor;
  5403. }
  5404. function _eachEditor(expr, fn) {
  5405. K(expr).each(function(i, el) {
  5406. K.each(_instances, function(j, editor) {
  5407. if (editor && editor.srcElement[0] == el) {
  5408. fn.call(editor, j, editor);
  5409. return false;
  5410. }
  5411. });
  5412. });
  5413. }
  5414. K.remove = function(expr) {
  5415. _eachEditor(expr, function(i) {
  5416. this.remove();
  5417. _instances.splice(i, 1);
  5418. });
  5419. };
  5420. K.sync = function(expr) {
  5421. _eachEditor(expr, function() {
  5422. this.sync();
  5423. });
  5424. };
  5425. if (_IE && _V < 7) {
  5426. _nativeCommand(document, 'BackgroundImageCache', true);
  5427. }
  5428. K.EditorClass = KEditor;
  5429. K.editor = _editor;
  5430. K.create = _create;
  5431. K.instances = _instances;
  5432. K.plugin = _plugin;
  5433. K.lang = _lang;
  5434. _plugin('core', function(K) {
  5435. var self = this,
  5436. shortcutKeys = {
  5437. undo : 'Z', redo : 'Y', bold : 'B', italic : 'I', underline : 'U', print : 'P', selectall : 'A'
  5438. };
  5439. self.afterSetHtml(function() {
  5440. if (self.options.afterChange) {
  5441. self.options.afterChange.call(self);
  5442. }
  5443. });
  5444. self.afterCreate(function() {
  5445. if (self.syncType != 'form') {
  5446. return;
  5447. }
  5448. var el = K(self.srcElement), hasForm = false;
  5449. while ((el = el.parent())) {
  5450. if (el.name == 'form') {
  5451. hasForm = true;
  5452. break;
  5453. }
  5454. }
  5455. if (hasForm) {
  5456. el.bind('submit', function(e) {
  5457. self.sync();
  5458. K(window).bind('unload', function() {
  5459. self.edit.textarea.remove();
  5460. });
  5461. });
  5462. var resetBtn = K('[type="reset"]', el);
  5463. resetBtn.click(function() {
  5464. self.html(self.initContent);
  5465. self.cmd.selection();
  5466. });
  5467. self.beforeRemove(function() {
  5468. el.unbind();
  5469. resetBtn.unbind();
  5470. });
  5471. }
  5472. });
  5473. self.clickToolbar('source', function() {
  5474. if (self.edit.designMode) {
  5475. self.toolbar.disableAll(true);
  5476. self.edit.design(false);
  5477. self.toolbar.select('source');
  5478. } else {
  5479. self.toolbar.disableAll(false);
  5480. self.edit.design(true);
  5481. self.toolbar.unselect('source');
  5482. self.cmd.selection();
  5483. }
  5484. self.designMode = self.edit.designMode;
  5485. });
  5486. self.afterCreate(function() {
  5487. if (!self.designMode) {
  5488. self.toolbar.disableAll(true).select('source');
  5489. }
  5490. });
  5491. self.clickToolbar('fullscreen', function() {
  5492. self.fullscreen();
  5493. });
  5494. if (self.fullscreenShortcut) {
  5495. var loaded = false;
  5496. self.afterCreate(function() {
  5497. K(self.edit.doc, self.edit.textarea).keyup(function(e) {
  5498. if (e.which == 27) {
  5499. setTimeout(function() {
  5500. self.fullscreen();
  5501. }, 0);
  5502. }
  5503. });
  5504. if (loaded) {
  5505. if (_IE && !self.designMode) {
  5506. return;
  5507. }
  5508. self.focus();
  5509. }
  5510. if (!loaded) {
  5511. loaded = true;
  5512. }
  5513. });
  5514. }
  5515. _each('undo,redo'.split(','), function(i, name) {
  5516. if (shortcutKeys[name]) {
  5517. self.afterCreate(function() {
  5518. _ctrl(this.edit.doc, shortcutKeys[name], function() {
  5519. self.clickToolbar(name);
  5520. });
  5521. });
  5522. }
  5523. self.clickToolbar(name, function() {
  5524. self[name]();
  5525. });
  5526. });
  5527. self.clickToolbar('formatblock', function() {
  5528. var blocks = self.lang('formatblock.formatBlock'),
  5529. heights = {
  5530. h1 : 28,
  5531. h2 : 24,
  5532. h3 : 18,
  5533. H4 : 14,
  5534. p : 12
  5535. },
  5536. curVal = self.cmd.val('formatblock'),
  5537. menu = self.createMenu({
  5538. name : 'formatblock',
  5539. width : self.langType == 'en' ? 200 : 150
  5540. });
  5541. _each(blocks, function(key, val) {
  5542. var style = 'font-size:' + heights[key] + 'px;';
  5543. if (key.charAt(0) === 'h') {
  5544. style += 'font-weight:bold;';
  5545. }
  5546. menu.addItem({
  5547. title : '<span style="' + style + '" unselectable="on">' + val + '</span>',
  5548. height : heights[key] + 12,
  5549. checked : (curVal === key || curVal === val),
  5550. click : function() {
  5551. self.select().exec('formatblock', '<' + key + '>').hideMenu();
  5552. }
  5553. });
  5554. });
  5555. });
  5556. self.clickToolbar('fontname', function() {
  5557. var curVal = self.cmd.val('fontname'),
  5558. menu = self.createMenu({
  5559. name : 'fontname',
  5560. width : 150
  5561. });
  5562. _each(self.lang('fontname.fontName'), function(key, val) {
  5563. menu.addItem({
  5564. title : '<span style="font-family: ' + key + ';" unselectable="on">' + val + '</span>',
  5565. checked : (curVal === key.toLowerCase() || curVal === val.toLowerCase()),
  5566. click : function() {
  5567. self.exec('fontname', key).hideMenu();
  5568. }
  5569. });
  5570. });
  5571. });
  5572. self.clickToolbar('fontsize', function() {
  5573. var curVal = self.cmd.val('fontsize'),
  5574. menu = self.createMenu({
  5575. name : 'fontsize',
  5576. width : 150
  5577. });
  5578. _each(self.fontSizeTable, function(i, val) {
  5579. menu.addItem({
  5580. title : '<span style="font-size:' + val + ';" unselectable="on">' + val + '</span>',
  5581. height : _removeUnit(val) + 12,
  5582. checked : curVal === val,
  5583. click : function() {
  5584. self.exec('fontsize', val).hideMenu();
  5585. }
  5586. });
  5587. });
  5588. });
  5589. _each('forecolor,hilitecolor'.split(','), function(i, name) {
  5590. self.clickToolbar(name, function() {
  5591. self.createMenu({
  5592. name : name,
  5593. selectedColor : self.cmd.val(name) || 'default',
  5594. colors : self.colorTable,
  5595. click : function(color) {
  5596. self.exec(name, color).hideMenu();
  5597. }
  5598. });
  5599. });
  5600. });
  5601. _each(('cut,copy,paste').split(','), function(i, name) {
  5602. self.clickToolbar(name, function() {
  5603. self.focus();
  5604. try {
  5605. self.exec(name, null);
  5606. } catch(e) {
  5607. alert(self.lang(name + 'Error'));
  5608. }
  5609. });
  5610. });
  5611. self.clickToolbar('about', function() {
  5612. var html = '<div style="margin:20px;">' +
  5613. '<div>KindEditor ' + _VERSION + '</div>' +
  5614. '<div>Copyright &copy; <a href="http://www.kindsoft.net/" target="_blank">kindsoft.net</a> All rights reserved.</div>' +
  5615. '</div>';
  5616. self.createDialog({
  5617. name : 'about',
  5618. width : 350,
  5619. title : self.lang('about'),
  5620. body : html
  5621. });
  5622. });
  5623. self.plugin.getSelectedLink = function() {
  5624. return self.cmd.commonAncestor('a');
  5625. };
  5626. self.plugin.getSelectedImage = function() {
  5627. return _getImageFromRange(self.edit.cmd.range, function(img) {
  5628. return !/^ke-\w+$/i.test(img[0].className);
  5629. });
  5630. };
  5631. self.plugin.getSelectedFlash = function() {
  5632. return _getImageFromRange(self.edit.cmd.range, function(img) {
  5633. return img[0].className == 'ke-flash';
  5634. });
  5635. };
  5636. self.plugin.getSelectedMedia = function() {
  5637. return _getImageFromRange(self.edit.cmd.range, function(img) {
  5638. return img[0].className == 'ke-media' || img[0].className == 'ke-rm';
  5639. });
  5640. };
  5641. self.plugin.getSelectedAnchor = function() {
  5642. return _getImageFromRange(self.edit.cmd.range, function(img) {
  5643. return img[0].className == 'ke-anchor';
  5644. });
  5645. };
  5646. _each('link,image,flash,media,anchor'.split(','), function(i, name) {
  5647. var uName = name.charAt(0).toUpperCase() + name.substr(1);
  5648. _each('edit,delete'.split(','), function(j, val) {
  5649. self.addContextmenu({
  5650. title : self.lang(val + uName),
  5651. click : function() {
  5652. self.loadPlugin(name, function() {
  5653. self.plugin[name][val]();
  5654. self.hideMenu();
  5655. });
  5656. },
  5657. cond : self.plugin['getSelected' + uName],
  5658. width : 150,
  5659. iconClass : val == 'edit' ? 'ke-icon-' + name : undefined
  5660. });
  5661. });
  5662. self.addContextmenu({ title : '-' });
  5663. });
  5664. self.plugin.getSelectedTable = function() {
  5665. return self.cmd.commonAncestor('table');
  5666. };
  5667. self.plugin.getSelectedRow = function() {
  5668. return self.cmd.commonAncestor('tr');
  5669. };
  5670. self.plugin.getSelectedCell = function() {
  5671. return self.cmd.commonAncestor('td');
  5672. };
  5673. _each(('prop,cellprop,colinsertleft,colinsertright,rowinsertabove,rowinsertbelow,rowmerge,colmerge,' +
  5674. 'rowsplit,colsplit,coldelete,rowdelete,insert,delete').split(','), function(i, val) {
  5675. var cond = _inArray(val, ['prop', 'delete']) < 0 ? self.plugin.getSelectedCell : self.plugin.getSelectedTable;
  5676. self.addContextmenu({
  5677. title : self.lang('table' + val),
  5678. click : function() {
  5679. self.loadPlugin('table', function() {
  5680. self.plugin.table[val]();
  5681. self.hideMenu();
  5682. });
  5683. },
  5684. cond : cond,
  5685. width : 170,
  5686. iconClass : 'ke-icon-table' + val
  5687. });
  5688. });
  5689. self.addContextmenu({ title : '-' });
  5690. _each(('selectall,justifyleft,justifycenter,justifyright,justifyfull,insertorderedlist,' +
  5691. 'insertunorderedlist,indent,outdent,subscript,superscript,hr,print,' +
  5692. 'bold,italic,underline,strikethrough,removeformat,unlink').split(','), function(i, name) {
  5693. if (shortcutKeys[name]) {
  5694. self.afterCreate(function() {
  5695. _ctrl(this.edit.doc, shortcutKeys[name], function() {
  5696. self.cmd.selection();
  5697. self.clickToolbar(name);
  5698. });
  5699. });
  5700. }
  5701. self.clickToolbar(name, function() {
  5702. self.focus().exec(name, null);
  5703. });
  5704. });
  5705. self.afterCreate(function() {
  5706. var doc = self.edit.doc, cmd, bookmark, div,
  5707. cls = '__kindeditor_paste__', pasting = false;
  5708. function movePastedData() {
  5709. cmd.range.moveToBookmark(bookmark);
  5710. cmd.select();
  5711. if (_WEBKIT) {
  5712. K('div.' + cls, div).each(function() {
  5713. K(this).after('<br />').remove(true);
  5714. });
  5715. K('span.Apple-style-span', div).remove(true);
  5716. K('span.Apple-tab-span', div).remove(true);
  5717. K('span[style]', div).each(function() {
  5718. if (K(this).css('white-space') == 'nowrap') {
  5719. K(this).remove(true);
  5720. }
  5721. });
  5722. K('meta', div).remove();
  5723. }
  5724. var html = div[0].innerHTML;
  5725. div.remove();
  5726. if (html === '') {
  5727. return;
  5728. }
  5729. if (_WEBKIT) {
  5730. html = html.replace(/(<br>)\1/ig, '$1');
  5731. }
  5732. if (self.pasteType === 2) {
  5733. html = html.replace(/(<(?:p|p\s[^>]*)>) *(<\/p>)/ig, '');
  5734. if (/schemas-microsoft-com|worddocument|mso-\w+/i.test(html)) {
  5735. html = _clearMsWord(html, self.filterMode ? self.htmlTags : K.options.htmlTags);
  5736. } else {
  5737. html = _formatHtml(html, self.filterMode ? self.htmlTags : null);
  5738. html = self.beforeSetHtml(html);
  5739. }
  5740. }
  5741. if (self.pasteType === 1) {
  5742. html = html.replace(/&nbsp;/ig, ' ');
  5743. html = html.replace(/\n\s*\n/g, '\n');
  5744. html = html.replace(/<br[^>]*>/ig, '\n');
  5745. html = html.replace(/<\/p><p[^>]*>/ig, '\n');
  5746. html = html.replace(/<[^>]+>/g, '');
  5747. html = html.replace(/ {2}/g, ' &nbsp;');
  5748. if (self.newlineTag == 'p') {
  5749. if (/\n/.test(html)) {
  5750. html = html.replace(/^/, '<p>').replace(/$/, '<br /></p>').replace(/\n/g, '<br /></p><p>');
  5751. }
  5752. } else {
  5753. html = html.replace(/\n/g, '<br />$&');
  5754. }
  5755. }
  5756. self.insertHtml(html, true);
  5757. }
  5758. K(doc.body).bind('paste', function(e){
  5759. if (self.pasteType === 0) {
  5760. e.stop();
  5761. return;
  5762. }
  5763. if (pasting) {
  5764. return;
  5765. }
  5766. pasting = true;
  5767. K('div.' + cls, doc).remove();
  5768. cmd = self.cmd.selection();
  5769. bookmark = cmd.range.createBookmark();
  5770. div = K('<div class="' + cls + '"></div>', doc).css({
  5771. position : 'absolute',
  5772. width : '1px',
  5773. height : '1px',
  5774. overflow : 'hidden',
  5775. left : '-1981px',
  5776. top : K(bookmark.start).pos().y + 'px',
  5777. 'white-space' : 'nowrap'
  5778. });
  5779. K(doc.body).append(div);
  5780. if (_IE) {
  5781. var rng = cmd.range.get(true);
  5782. rng.moveToElementText(div[0]);
  5783. rng.select();
  5784. rng.execCommand('paste');
  5785. e.preventDefault();
  5786. } else {
  5787. cmd.range.selectNodeContents(div[0]);
  5788. cmd.select();
  5789. }
  5790. setTimeout(function() {
  5791. movePastedData();
  5792. pasting = false;
  5793. }, 0);
  5794. });
  5795. });
  5796. self.beforeGetHtml(function(html) {
  5797. if (_IE && _V <= 8) {
  5798. html = html.replace(/<div\s+[^>]*data-ke-input-tag="([^"]*)"[^>]*>([\s\S]*?)<\/div>/ig, function(full, tag) {
  5799. return unescape(tag);
  5800. });
  5801. html = html.replace(/(<input)((?:\s+[^>]*)?>)/ig, function($0, $1, $2) {
  5802. if (!/\s+type="[^"]+"/i.test($0)) {
  5803. return $1 + ' type="text"' + $2;
  5804. }
  5805. return $0;
  5806. });
  5807. }
  5808. return html.replace(/(<(?:noscript|noscript\s[^>]*)>)([\s\S]*?)(<\/noscript>)/ig, function($0, $1, $2, $3) {
  5809. return $1 + _unescape($2).replace(/\s+/g, ' ') + $3;
  5810. })
  5811. .replace(/<img[^>]*class="?ke-(flash|rm|media)"?[^>]*>/ig, function(full) {
  5812. var imgAttrs = _getAttrList(full),
  5813. styles = _getCssList(imgAttrs.style || ''),
  5814. attrs = _mediaAttrs(imgAttrs['data-ke-tag']);
  5815. attrs.width = _undef(imgAttrs.width, _removeUnit(_undef(styles.width, '')));
  5816. attrs.height = _undef(imgAttrs.height, _removeUnit(_undef(styles.height, '')));
  5817. return _mediaEmbed(attrs);
  5818. })
  5819. .replace(/<img[^>]*class="?ke-anchor"?[^>]*>/ig, function(full) {
  5820. var imgAttrs = _getAttrList(full);
  5821. return '<a name="' + unescape(imgAttrs['data-ke-name']) + '"></a>';
  5822. })
  5823. .replace(/<div\s+[^>]*data-ke-script-attr="([^"]*)"[^>]*>([\s\S]*?)<\/div>/ig, function(full, attr, code) {
  5824. return '<script' + unescape(attr) + '>' + unescape(code) + '</script>';
  5825. })
  5826. .replace(/<div\s+[^>]*data-ke-noscript-attr="([^"]*)"[^>]*>([\s\S]*?)<\/div>/ig, function(full, attr, code) {
  5827. return '<noscript' + unescape(attr) + '>' + unescape(code) + '</noscript>';
  5828. })
  5829. .replace(/(<[^>]*)data-ke-src="([^"]*)"([^>]*>)/ig, function(full, start, src, end) {
  5830. full = full.replace(/(\s+(?:href|src)=")[^"]*(")/i, function($0, $1, $2) {
  5831. return $1 + _unescape(src) + $2;
  5832. });
  5833. full = full.replace(/\s+data-ke-src="[^"]*"/i, '');
  5834. return full;
  5835. })
  5836. .replace(/(<[^>]+\s)data-ke-(on\w+="[^"]*"[^>]*>)/ig, function(full, start, end) {
  5837. return start + end;
  5838. });
  5839. });
  5840. self.beforeSetHtml(function(html) {
  5841. if (_IE && _V <= 8) {
  5842. html = html.replace(/<input[^>]*>|<(select|button)[^>]*>[\s\S]*?<\/\1>/ig, function(full) {
  5843. var attrs = _getAttrList(full);
  5844. var styles = _getCssList(attrs.style || '');
  5845. if (styles.display == 'none') {
  5846. return '<div class="ke-display-none" data-ke-input-tag="' + escape(full) + '"></div>';
  5847. }
  5848. return full;
  5849. });
  5850. }
  5851. return html.replace(/<embed[^>]*type="([^"]+)"[^>]*>(?:<\/embed>)?/ig, function(full) {
  5852. var attrs = _getAttrList(full);
  5853. attrs.src = _undef(attrs.src, '');
  5854. attrs.width = _undef(attrs.width, 0);
  5855. attrs.height = _undef(attrs.height, 0);
  5856. return _mediaImg(self.themesPath + 'common/blank.gif', attrs);
  5857. })
  5858. .replace(/<a[^>]*name="([^"]+)"[^>]*>(?:<\/a>)?/ig, function(full) {
  5859. var attrs = _getAttrList(full);
  5860. if (attrs.href !== undefined) {
  5861. return full;
  5862. }
  5863. return '<img class="ke-anchor" src="' + self.themesPath + 'common/anchor.gif" data-ke-name="' + escape(attrs.name) + '" />';
  5864. })
  5865. .replace(/<script([^>]*)>([\s\S]*?)<\/script>/ig, function(full, attr, code) {
  5866. return '<div class="ke-script" data-ke-script-attr="' + escape(attr) + '">' + escape(code) + '</div>';
  5867. })
  5868. .replace(/<noscript([^>]*)>([\s\S]*?)<\/noscript>/ig, function(full, attr, code) {
  5869. return '<div class="ke-noscript" data-ke-noscript-attr="' + escape(attr) + '">' + escape(code) + '</div>';
  5870. })
  5871. .replace(/(<[^>]*)(href|src)="([^"]*)"([^>]*>)/ig, function(full, start, key, src, end) {
  5872. if (full.match(/\sdata-ke-src="[^"]*"/i)) {
  5873. return full;
  5874. }
  5875. full = start + key + '="' + src + '"' + ' data-ke-src="' + _escape(src) + '"' + end;
  5876. return full;
  5877. })
  5878. .replace(/(<[^>]+\s)(on\w+="[^"]*"[^>]*>)/ig, function(full, start, end) {
  5879. return start + 'data-ke-' + end;
  5880. })
  5881. .replace(/<table[^>]*\s+border="0"[^>]*>/ig, function(full) {
  5882. if (full.indexOf('ke-zeroborder') >= 0) {
  5883. return full;
  5884. }
  5885. return _addClassToTag(full, 'ke-zeroborder');
  5886. });
  5887. });
  5888. });
  5889. })(window);