kindeditor.js 163 KB

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