kindeditor.js 153 KB

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