kindeditor.js 157 KB

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