Brak opisu

kindeditor.js 156KB

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