kindeditor.js 454 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776
  1. /******************************************************************************
  2. * KindEditor - WYSIWYG HTML Editor for Internet
  3. * Copyright (C) 2006-2013 kindsoft.net
  4. *
  5. * @author Roddy <luolonghao@gmail.com>
  6. * @website http://www.kindsoft.net/
  7. * @licence http://www.kindsoft.net/license.php
  8. * @version 4.1.9 (2013-10-08)
  9. *******************************************************************************/
  10. /*! KindEditor Copyright (C) kindsoft.net, Licence: http://kindeditor.net/license.php */
  11. (function(window, undefined) {
  12. if(window.KindEditor) {
  13. return;
  14. }
  15. if(!window.console) {
  16. window.console = {};
  17. }
  18. if(!console.log) {
  19. console.log = function() {};
  20. }
  21. var _VERSION = '4.1.9 (2013-10-08)',
  22. _ua = navigator.userAgent.toLowerCase(),
  23. _IE = _ua.indexOf('msie') > -1 && _ua.indexOf('opera') == -1,
  24. _NEWIE = _ua.indexOf('msie') == -1 && _ua.indexOf('trident') > -1,
  25. _GECKO = _ua.indexOf('gecko') > -1 && _ua.indexOf('khtml') == -1,
  26. _WEBKIT = _ua.indexOf('applewebkit') > -1,
  27. _OPERA = _ua.indexOf('opera') > -1,
  28. _MOBILE = _ua.indexOf('mobile') > -1,
  29. _IOS = /ipad|iphone|ipod/.test(_ua),
  30. _QUIRKS = document.compatMode != 'CSS1Compat',
  31. _IERANGE = !window.getSelection,
  32. _matches = /(?:msie|firefox|webkit|opera)[\/:\s](\d+)/.exec(_ua),
  33. _V = _matches ? _matches[1] : '0',
  34. _TIME = new Date().getTime();
  35. function _isArray(val) {
  36. if(!val) {
  37. return false;
  38. }
  39. return Object.prototype.toString.call(val) === '[object Array]';
  40. }
  41. function _isFunction(val) {
  42. if(!val) {
  43. return false;
  44. }
  45. return Object.prototype.toString.call(val) === '[object Function]';
  46. }
  47. function _inArray(val, arr) {
  48. for(var i = 0, len = arr.length; i < len; i++) {
  49. if(val === arr[i]) {
  50. return i;
  51. }
  52. }
  53. return -1;
  54. }
  55. function _each(obj, fn) {
  56. if(_isArray(obj)) {
  57. for(var i = 0, len = obj.length; i < len; i++) {
  58. if(fn.call(obj[i], i, obj[i]) === false) {
  59. break;
  60. }
  61. }
  62. } else {
  63. for(var key in obj) {
  64. if(obj.hasOwnProperty(key)) {
  65. if(fn.call(obj[key], key, obj[key]) === false) {
  66. break;
  67. }
  68. }
  69. }
  70. }
  71. }
  72. function _trim(str) {
  73. return str.replace(/(?:^[ \t\n\r]+)|(?:[ \t\n\r]+$)/g, '');
  74. }
  75. function _inString(val, str, delimiter) {
  76. delimiter = delimiter === undefined ? ',' : delimiter;
  77. return(delimiter + str + delimiter).indexOf(delimiter + val + delimiter) >= 0;
  78. }
  79. function _addUnit(val, unit) {
  80. unit = unit || 'px';
  81. return val && /^[\d\.]+$/.test(val) ? val + unit : val;
  82. }
  83. function _removeUnit(val) {
  84. var match;
  85. return val && (match = /([\d\.]+)/.exec(val)) ? parseInt(match[1], 10) : 0;
  86. }
  87. function _escape(val) {
  88. return val.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
  89. }
  90. function _unescape(val) {
  91. return val.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&amp;/g, '&');
  92. }
  93. function _toCamel(str) {
  94. var arr = str.split('-');
  95. str = '';
  96. _each(arr, function(key, val) {
  97. str += (key > 0) ? val.charAt(0).toUpperCase() + val.substr(1) : val;
  98. });
  99. return str;
  100. }
  101. function _toHex(val) {
  102. function hex(d) {
  103. var s = parseInt(d, 10).toString(16).toUpperCase();
  104. return s.length > 1 ? s : '0' + s;
  105. }
  106. return val.replace(/rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/ig,
  107. function($0, $1, $2, $3) {
  108. return '#' + hex($1) + hex($2) + hex($3);
  109. }
  110. );
  111. }
  112. function _toMap(val, delimiter) {
  113. delimiter = delimiter === undefined ? ',' : delimiter;
  114. var map = {},
  115. arr = _isArray(val) ? val : val.split(delimiter),
  116. match;
  117. _each(arr, function(key, val) {
  118. if((match = /^(\d+)\.\.(\d+)$/.exec(val))) {
  119. for(var i = parseInt(match[1], 10); i <= parseInt(match[2], 10); i++) {
  120. map[i.toString()] = true;
  121. }
  122. } else {
  123. map[val] = true;
  124. }
  125. });
  126. return map;
  127. }
  128. function _toArray(obj, offset) {
  129. return Array.prototype.slice.call(obj, offset || 0);
  130. }
  131. function _undef(val, defaultVal) {
  132. return val === undefined ? defaultVal : val;
  133. }
  134. function _invalidUrl(url) {
  135. return !url || /[<>"]/.test(url);
  136. }
  137. function _addParam(url, param) {
  138. return url.indexOf('?') >= 0 ? url + '&' + param : url + '?' + param;
  139. }
  140. function _extend(child, parent, proto) {
  141. if(!proto) {
  142. proto = parent;
  143. parent = null;
  144. }
  145. var childProto;
  146. if(parent) {
  147. var fn = function() {};
  148. fn.prototype = parent.prototype;
  149. childProto = new fn();
  150. _each(proto, function(key, val) {
  151. childProto[key] = val;
  152. });
  153. } else {
  154. childProto = proto;
  155. }
  156. childProto.constructor = child;
  157. child.prototype = childProto;
  158. child.parent = parent ? parent.prototype : null;
  159. }
  160. function _json(text) {
  161. var match;
  162. if((match = /\{[\s\S]*\}|\[[\s\S]*\]/.exec(text))) {
  163. text = match[0];
  164. }
  165. var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
  166. cx.lastIndex = 0;
  167. if(cx.test(text)) {
  168. text = text.replace(cx, function(a) {
  169. return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
  170. });
  171. }
  172. if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
  173. return eval('(' + text + ')');
  174. }
  175. throw 'JSON parse error';
  176. }
  177. var _round = Math.round;
  178. var K = {
  179. DEBUG: false,
  180. VERSION: _VERSION,
  181. IE: _IE,
  182. GECKO: _GECKO,
  183. WEBKIT: _WEBKIT,
  184. OPERA: _OPERA,
  185. V: _V,
  186. TIME: _TIME,
  187. each: _each,
  188. isArray: _isArray,
  189. isFunction: _isFunction,
  190. inArray: _inArray,
  191. inString: _inString,
  192. trim: _trim,
  193. addUnit: _addUnit,
  194. removeUnit: _removeUnit,
  195. escape: _escape,
  196. unescape: _unescape,
  197. toCamel: _toCamel,
  198. toHex: _toHex,
  199. toMap: _toMap,
  200. toArray: _toArray,
  201. undef: _undef,
  202. invalidUrl: _invalidUrl,
  203. addParam: _addParam,
  204. extend: _extend,
  205. json: _json
  206. };
  207. var _INLINE_TAG_MAP = _toMap('a,abbr,acronym,b,basefont,bdo,big,br,button,cite,code,del,dfn,em,font,i,img,input,ins,kbd,label,map,q,s,samp,select,small,span,strike,strong,sub,sup,textarea,tt,u,var'),
  208. _BLOCK_TAG_MAP = _toMap('address,applet,blockquote,body,center,dd,dir,div,dl,dt,fieldset,form,frameset,h1,h2,h3,h4,h5,h6,head,hr,html,iframe,ins,isindex,li,map,menu,meta,noframes,noscript,object,ol,p,pre,script,style,table,tbody,td,tfoot,th,thead,title,tr,ul'),
  209. _SINGLE_TAG_MAP = _toMap('area,base,basefont,br,col,frame,hr,img,input,isindex,link,meta,param,embed'),
  210. _STYLE_TAG_MAP = _toMap('b,basefont,big,del,em,font,i,s,small,span,strike,strong,sub,sup,u'),
  211. _CONTROL_TAG_MAP = _toMap('img,table,input,textarea,button'),
  212. _PRE_TAG_MAP = _toMap('pre,style,script'),
  213. _NOSPLIT_TAG_MAP = _toMap('html,head,body,td,tr,table,ol,ul,li'),
  214. _AUTOCLOSE_TAG_MAP = _toMap('colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr'),
  215. _FILL_ATTR_MAP = _toMap('checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected'),
  216. _VALUE_TAG_MAP = _toMap('input,button,textarea,select');
  217. function _getBasePath() {
  218. var els = document.getElementsByTagName('script'),
  219. src;
  220. for(var i = 0, len = els.length; i < len; i++) {
  221. src = els[i].src || '';
  222. if(/kindeditor[\w\-\.]*\.js/.test(src)) {
  223. return src.substring(0, src.lastIndexOf('/') + 1);
  224. }
  225. }
  226. return '';
  227. }
  228. K.basePath = _getBasePath();
  229. K.options = {
  230. designMode: true,
  231. fullscreenMode: false,
  232. filterMode: true,
  233. wellFormatMode: true,
  234. shadowMode: true,
  235. loadStyleMode: true,
  236. basePath: K.basePath,
  237. themesPath: K.basePath + 'themes/',
  238. langPath: K.basePath + 'lang/',
  239. pluginsPath: K.basePath + 'plugins/',
  240. themeType: 'default',
  241. langType: 'zh_CN',
  242. urlType: '',
  243. newlineTag: 'p',
  244. resizeType: 1,
  245. syncType: 'form',
  246. pasteType: 2,
  247. dialogAlignType: 'page',
  248. useContextmenu: true,
  249. fullscreenShortcut: false,
  250. bodyClass: 'ke-content',
  251. indentChar: ' ',
  252. cssPath: '',
  253. cssData: '',
  254. minWidth: 650,
  255. minHeight: 100,
  256. minChangeSize: 50,
  257. simpleWrap: true,
  258. zIndex: 811213,
  259. items: [
  260. 'source', '|', 'undo', 'redo', '|', 'preview', 'print', 'template', 'code', 'cut', 'copy', 'paste',
  261. 'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright',
  262. 'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',
  263. 'superscript', 'clearhtml', 'quickformat', 'selectall', '|', 'fullscreen', '/',
  264. 'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold',
  265. 'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'image', 'multiimage',
  266. 'flash', 'media', 'insertfile', 'table', 'hr', 'emoticons', 'baidumap', 'pagebreak',
  267. 'anchor', 'link', 'unlink', '|', 'about'
  268. ],
  269. noDisableItems: ['source', 'fullscreen'],
  270. colorTable: [
  271. ['#E53333', '#E56600', '#FF9900', '#64451D', '#DFC5A4', '#FFE500'],
  272. ['#009900', '#006600', '#99BB00', '#B8D100', '#60D978', '#00D5FF'],
  273. ['#337FE5', '#003399', '#4C33E5', '#9933E5', '#CC33E5', '#EE33EE'],
  274. ['#FFFFFF', '#CCCCCC', '#999999', '#666666', '#333333', '#000000']
  275. ],
  276. fontSizeTable: ['9px', '10px', '12px', '14px', '16px', '18px', '24px', '32px'],
  277. htmlTags: {
  278. font: ['id', 'class', 'color', 'size', 'face', '.background-color', '.color', '.font-size', '.font-family'],
  279. span: [
  280. 'id', 'class', '.color', '.background-color', '.font-size', '.font-family', '.background',
  281. '.font-weight', '.font-style', '.text-decoration', '.vertical-align', '.line-height'
  282. ],
  283. div: [
  284. 'id', 'class', 'align', '.border', '.margin', '.padding', '.text-align', '.color',
  285. '.background-color', '.font-size', '.font-family', '.font-weight', '.background',
  286. '.font-style', '.text-decoration', '.vertical-align', '.margin-left'
  287. ],
  288. table: [
  289. 'id', 'class', 'border', 'cellspacing', 'cellpadding', 'width', 'height', 'align', 'bordercolor',
  290. '.padding', '.margin', '.border', 'bgcolor', '.text-align', '.color', '.background-color',
  291. '.font-size', '.font-family', '.font-weight', '.font-style', '.text-decoration', '.background',
  292. '.width', '.height', '.border-collapse'
  293. ],
  294. 'td,th': [
  295. 'id', 'class', 'align', 'valign', 'width', 'height', 'colspan', 'rowspan', 'bgcolor',
  296. '.text-align', '.color', '.background-color', '.font-size', '.font-family', '.font-weight',
  297. '.font-style', '.text-decoration', '.vertical-align', '.background', '.border'
  298. ],
  299. tr: ['id', 'class', '.background-color'],
  300. a: ['id', 'class', 'href', 'target', 'name'],
  301. embed: ['id', 'class', 'src', 'width', 'height', 'type', 'loop', 'autostart', 'quality', '.width', '.height', 'align', 'allowscriptaccess'],
  302. audio: ['id', 'class', 'width', 'src', 'height', 'loop', 'preload', 'autoplay', 'controls', 'crossorigin', 'currentTime', 'duration', 'muted'],
  303. video: ['id', 'class', 'width', 'src', 'height', 'loop', 'preload', 'autoplay', 'controls', 'crossorigin', 'currentTime', 'duration', 'muted', 'buffered', 'playsinline', 'played', 'poster'],
  304. source: ['src', 'type'],
  305. img: ['id', 'class', 'src', 'width', 'height', 'border', 'alt', 'title', 'align', '.width', '.height', '.border'],
  306. 'p,ol,ul,li,blockquote,h1,h2,h3,h4,h5,h6': [
  307. 'id', 'class', 'align', '.text-align', '.color', '.background-color', '.font-size', '.font-family', '.background',
  308. '.font-weight', '.font-style', '.text-decoration', '.vertical-align', '.text-indent', '.margin-left'
  309. ],
  310. pre: ['id', 'class'],
  311. hr: ['id', 'class', '.page-break-after'],
  312. 'br,tbody,strong,b,sub,sup,em,i,u,strike,s,del': ['id', 'class'],
  313. iframe: ['id', 'class', 'src', 'frameborder', 'width', 'height', '.width', '.height']
  314. },
  315. layout: '<div class="container ke-loading"><div class="toolbar"></div><div class="edit"></div><div class="statusbar"></div></div>'
  316. };
  317. var _useCapture = false;
  318. var _INPUT_KEY_MAP = _toMap('8,9,13,32,46,48..57,59,61,65..90,106,109..111,188,190..192,219..222');
  319. var _CURSORMOVE_KEY_MAP = _toMap('33..40');
  320. var _CHANGE_KEY_MAP = {};
  321. _each(_INPUT_KEY_MAP, function(key, val) {
  322. _CHANGE_KEY_MAP[key] = val;
  323. });
  324. _each(_CURSORMOVE_KEY_MAP, function(key, val) {
  325. _CHANGE_KEY_MAP[key] = val;
  326. });
  327. function _bindEvent(el, type, fn) {
  328. if(el.addEventListener) {
  329. el.addEventListener(type, fn, _useCapture);
  330. } else if(el.attachEvent) {
  331. el.attachEvent('on' + type, fn);
  332. }
  333. }
  334. function _unbindEvent(el, type, fn) {
  335. if(el.removeEventListener) {
  336. el.removeEventListener(type, fn, _useCapture);
  337. } else if(el.detachEvent) {
  338. el.detachEvent('on' + type, fn);
  339. }
  340. }
  341. var _EVENT_PROPS = ('altKey,attrChange,attrName,bubbles,button,cancelable,charCode,clientX,clientY,ctrlKey,currentTarget,' +
  342. 'data,detail,eventPhase,fromElement,handler,keyCode,metaKey,newValue,offsetX,offsetY,originalTarget,pageX,' +
  343. 'pageY,prevValue,relatedNode,relatedTarget,screenX,screenY,shiftKey,srcElement,target,toElement,view,wheelDelta,which').split(',');
  344. function KEvent(el, event) {
  345. this.init(el, event);
  346. }
  347. _extend(KEvent, {
  348. init: function(el, event) {
  349. var self = this,
  350. doc = el.ownerDocument || el.document || el;
  351. self.event = event;
  352. _each(_EVENT_PROPS, function(key, val) {
  353. self[val] = event[val];
  354. });
  355. if(!self.target) {
  356. self.target = self.srcElement || doc;
  357. }
  358. if(self.target.nodeType === 3) {
  359. self.target = self.target.parentNode;
  360. }
  361. if(!self.relatedTarget && self.fromElement) {
  362. self.relatedTarget = self.fromElement === self.target ? self.toElement : self.fromElement;
  363. }
  364. if(self.pageX == null && self.clientX != null) {
  365. var d = doc.documentElement,
  366. body = doc.body;
  367. self.pageX = self.clientX + (d && d.scrollLeft || body && body.scrollLeft || 0) - (d && d.clientLeft || body && body.clientLeft || 0);
  368. self.pageY = self.clientY + (d && d.scrollTop || body && body.scrollTop || 0) - (d && d.clientTop || body && body.clientTop || 0);
  369. }
  370. if(!self.which && ((self.charCode || self.charCode === 0) ? self.charCode : self.keyCode)) {
  371. self.which = self.charCode || self.keyCode;
  372. }
  373. if(!self.metaKey && self.ctrlKey) {
  374. self.metaKey = self.ctrlKey;
  375. }
  376. if(!self.which && self.button !== undefined) {
  377. self.which = (self.button & 1 ? 1 : (self.button & 2 ? 3 : (self.button & 4 ? 2 : 0)));
  378. }
  379. switch(self.which) {
  380. case 186:
  381. self.which = 59;
  382. break;
  383. case 187:
  384. case 107:
  385. case 43:
  386. self.which = 61;
  387. break;
  388. case 189:
  389. case 45:
  390. self.which = 109;
  391. break;
  392. case 42:
  393. self.which = 106;
  394. break;
  395. case 47:
  396. self.which = 111;
  397. break;
  398. case 78:
  399. self.which = 110;
  400. break;
  401. }
  402. if(self.which >= 96 && self.which <= 105) {
  403. self.which -= 48;
  404. }
  405. },
  406. preventDefault: function() {
  407. var ev = this.event;
  408. if(ev.preventDefault) {
  409. ev.preventDefault();
  410. }
  411. ev.returnValue = false;
  412. },
  413. stopPropagation: function() {
  414. var ev = this.event;
  415. if(ev.stopPropagation) {
  416. ev.stopPropagation();
  417. }
  418. ev.cancelBubble = true;
  419. },
  420. stop: function() {
  421. this.preventDefault();
  422. this.stopPropagation();
  423. }
  424. });
  425. var _eventExpendo = 'kindeditor_' + _TIME,
  426. _eventId = 0,
  427. _eventData = {};
  428. function _getId(el) {
  429. return el[_eventExpendo] || null;
  430. }
  431. function _setId(el) {
  432. el[_eventExpendo] = ++_eventId;
  433. return _eventId;
  434. }
  435. function _removeId(el) {
  436. try {
  437. delete el[_eventExpendo];
  438. } catch(e) {
  439. if(el.removeAttribute) {
  440. el.removeAttribute(_eventExpendo);
  441. }
  442. }
  443. }
  444. function _bind(el, type, fn) {
  445. if(type.indexOf(',') >= 0) {
  446. _each(type.split(','), function() {
  447. _bind(el, this, fn);
  448. });
  449. return;
  450. }
  451. var id = _getId(el);
  452. if(!id) {
  453. id = _setId(el);
  454. }
  455. if(_eventData[id] === undefined) {
  456. _eventData[id] = {};
  457. }
  458. var events = _eventData[id][type];
  459. if(events && events.length > 0) {
  460. _unbindEvent(el, type, events[0]);
  461. } else {
  462. _eventData[id][type] = [];
  463. _eventData[id].el = el;
  464. }
  465. events = _eventData[id][type];
  466. if(events.length === 0) {
  467. events[0] = function(e) {
  468. var kevent = e ? new KEvent(el, e) : undefined;
  469. _each(events, function(i, event) {
  470. if(i > 0 && event) {
  471. event.call(el, kevent);
  472. }
  473. });
  474. };
  475. }
  476. if(_inArray(fn, events) < 0) {
  477. events.push(fn);
  478. }
  479. _bindEvent(el, type, events[0]);
  480. }
  481. function _unbind(el, type, fn) {
  482. if(type && type.indexOf(',') >= 0) {
  483. _each(type.split(','), function() {
  484. _unbind(el, this, fn);
  485. });
  486. return;
  487. }
  488. var id = _getId(el);
  489. if(!id) {
  490. return;
  491. }
  492. if(type === undefined) {
  493. if(id in _eventData) {
  494. _each(_eventData[id], function(key, events) {
  495. if(key != 'el' && events.length > 0) {
  496. _unbindEvent(el, key, events[0]);
  497. }
  498. });
  499. delete _eventData[id];
  500. _removeId(el);
  501. }
  502. return;
  503. }
  504. if(!_eventData[id]) {
  505. return;
  506. }
  507. var events = _eventData[id][type];
  508. if(events && events.length > 0) {
  509. if(fn === undefined) {
  510. _unbindEvent(el, type, events[0]);
  511. delete _eventData[id][type];
  512. } else {
  513. _each(events, function(i, event) {
  514. if(i > 0 && event === fn) {
  515. events.splice(i, 1);
  516. }
  517. });
  518. if(events.length == 1) {
  519. _unbindEvent(el, type, events[0]);
  520. delete _eventData[id][type];
  521. }
  522. }
  523. var count = 0;
  524. _each(_eventData[id], function() {
  525. count++;
  526. });
  527. if(count < 2) {
  528. delete _eventData[id];
  529. _removeId(el);
  530. }
  531. }
  532. }
  533. function _fire(el, type) {
  534. if(type.indexOf(',') >= 0) {
  535. _each(type.split(','), function() {
  536. _fire(el, this);
  537. });
  538. return;
  539. }
  540. var id = _getId(el);
  541. if(!id) {
  542. return;
  543. }
  544. var events = _eventData[id][type];
  545. if(_eventData[id] && events && events.length > 0) {
  546. events[0]();
  547. }
  548. }
  549. function _ctrl(el, key, fn) {
  550. var self = this;
  551. key = /^\d{2,}$/.test(key) ? key : key.toUpperCase().charCodeAt(0);
  552. _bind(el, 'keydown', function(e) {
  553. if(e.ctrlKey && e.which == key && !e.shiftKey && !e.altKey) {
  554. fn.call(el);
  555. e.stop();
  556. }
  557. });
  558. }
  559. var _readyFinished = false;
  560. function _ready(fn) {
  561. if(_readyFinished) {
  562. fn(KindEditor);
  563. return;
  564. }
  565. var loaded = false;
  566. function readyFunc() {
  567. if(!loaded) {
  568. loaded = true;
  569. fn(KindEditor);
  570. _readyFinished = true;
  571. }
  572. }
  573. function ieReadyFunc() {
  574. if(!loaded) {
  575. try {
  576. document.documentElement.doScroll('left');
  577. } catch(e) {
  578. setTimeout(ieReadyFunc, 100);
  579. return;
  580. }
  581. readyFunc();
  582. }
  583. }
  584. function ieReadyStateFunc() {
  585. if(document.readyState === 'complete') {
  586. readyFunc();
  587. }
  588. }
  589. if(document.addEventListener) {
  590. _bind(document, 'DOMContentLoaded', readyFunc);
  591. } else if(document.attachEvent) {
  592. _bind(document, 'readystatechange', ieReadyStateFunc);
  593. var toplevel = false;
  594. try {
  595. toplevel = window.frameElement == null;
  596. } catch(e) {}
  597. if(document.documentElement.doScroll && toplevel) {
  598. ieReadyFunc();
  599. }
  600. }
  601. _bind(window, 'load', readyFunc);
  602. }
  603. if(_IE) {
  604. window[window.attachEvent ? 'attachEvent' : 'addEventListener']('onunload', function() {
  605. _each(_eventData, function(key, events) {
  606. if(events.el) {
  607. _unbind(events.el);
  608. }
  609. });
  610. });
  611. }
  612. K.ctrl = _ctrl;
  613. K.ready = _ready;
  614. function _getCssList(css) {
  615. var list = {},
  616. reg = /\s*([\w\-]+)\s*:([^;]*)(;|$)/g,
  617. match;
  618. while((match = reg.exec(css))) {
  619. var key = _trim(match[1].toLowerCase()),
  620. val = _trim(_toHex(match[2]));
  621. list[key] = val;
  622. }
  623. return list;
  624. }
  625. function _getAttrList(tag, emptyValue) {
  626. var list = {},
  627. reg = /\s+(?:([\w\-:]+)|(?:([\w\-:]+)=([^\s"'<>]+))|(?:([\w\-:"]+)="([^"]*)")|(?:([\w\-:"]+)='([^']*)'))(?=(?:\s|\/|>)+)/g,
  628. match;
  629. if (emptyValue === undefined) emptyValue = '';
  630. while((match = reg.exec(tag))) {
  631. var key = (match[1] || match[2] || match[4] || match[6]).toLowerCase(),
  632. val = (match[2] ? match[3] : (match[4] ? match[5] : match[7])) || emptyValue;
  633. list[key] = val;
  634. }
  635. return list;
  636. }
  637. function _addClassToTag(tag, className) {
  638. if(/\s+class\s*=/.test(tag)) {
  639. tag = tag.replace(/(\s+class=["']?)([^"']*)(["']?[\s>])/, function($0, $1, $2, $3) {
  640. if((' ' + $2 + ' ').indexOf(' ' + className + ' ') < 0) {
  641. return $2 === '' ? $1 + className + $3 : $1 + $2 + ' ' + className + $3;
  642. } else {
  643. return $0;
  644. }
  645. });
  646. } else {
  647. tag = tag.substr(0, tag.length - 1) + ' class="' + className + '">';
  648. }
  649. return tag;
  650. }
  651. function _formatCss(css) {
  652. var str = '';
  653. _each(_getCssList(css), function(key, val) {
  654. str += key + ':' + val + ';';
  655. });
  656. return str;
  657. }
  658. function _formatUrl(url, mode, host, pathname) {
  659. if (url[0] === '#') {
  660. return url;
  661. }
  662. mode = _undef(mode, '').toLowerCase();
  663. if(url.substr(0, 5) != 'data:') {
  664. url = url.replace(/([^:])\/\//g, '$1/');
  665. }
  666. if(_inArray(mode, ['absolute', 'relative', 'domain']) < 0) {
  667. return url;
  668. }
  669. host = host || location.protocol + '//' + location.host;
  670. if(pathname === undefined) {
  671. var m = location.pathname.match(/^(\/.*)\//);
  672. pathname = m ? m[1] : '';
  673. }
  674. var match;
  675. if((match = /^(\w+:\/\/[^\/]*)/.exec(url))) {
  676. if(match[1] !== host) {
  677. return url;
  678. }
  679. } else if(/^\w+:/.test(url)) {
  680. return url;
  681. }
  682. function getRealPath(path) {
  683. var parts = path.split('/'),
  684. paths = [];
  685. for(var i = 0, len = parts.length; i < len; i++) {
  686. var part = parts[i];
  687. if(part == '..') {
  688. if(paths.length > 0) {
  689. paths.pop();
  690. }
  691. } else if(part !== '' && part != '.') {
  692. paths.push(part);
  693. }
  694. }
  695. return '/' + paths.join('/');
  696. }
  697. if(/^\//.test(url)) {
  698. url = host + getRealPath(url.substr(1));
  699. } else if(!/^\w+:\/\//.test(url)) {
  700. url = host + getRealPath(pathname + '/' + url);
  701. }
  702. function getRelativePath(path, depth) {
  703. if(url.substr(0, path.length) === path) {
  704. var arr = [];
  705. for(var i = 0; i < depth; i++) {
  706. arr.push('..');
  707. }
  708. var prefix = '.';
  709. if(arr.length > 0) {
  710. prefix += '/' + arr.join('/');
  711. }
  712. if(pathname == '/') {
  713. prefix += '/';
  714. }
  715. return prefix + url.substr(path.length);
  716. } else {
  717. if((match = /^(.*)\//.exec(path))) {
  718. return getRelativePath(match[1], ++depth);
  719. }
  720. }
  721. }
  722. if(mode === 'relative') {
  723. url = getRelativePath(host + pathname, 0).substr(2);
  724. } else if(mode === 'absolute') {
  725. if(url.substr(0, host.length) === host) {
  726. url = url.substr(host.length);
  727. }
  728. }
  729. return url;
  730. }
  731. function _formatHtml(html, htmlTags, urlType, wellFormatted, indentChar, simpleWrap) {
  732. if(html == null) {
  733. html = '';
  734. }
  735. urlType = urlType || '';
  736. wellFormatted = _undef(wellFormatted, false);
  737. indentChar = _undef(indentChar, '\t');
  738. var fontSizeList = 'xx-small,x-small,small,medium,large,x-large,xx-large'.split(',');
  739. html = html.replace(/(<(?:pre|pre\s[^>]*)>)([\s\S]*?)(<\/pre>)/ig, function($0, $1, $2, $3) {
  740. return $1 + $2.replace(/<(?:br|br\s[^>]*)>/ig, '\n') + $3;
  741. });
  742. html = html.replace(/<(?:br|br\s[^>]*)\s*\/?>\s*<\/p>/ig, '</p>');
  743. html = html.replace(/(<(?:p|p\s[^>]*)>)\s*(<\/p>)/ig, '$1<br />$2');
  744. html = html.replace(/\u200B/g, '');
  745. html = html.replace(/\u00A9/g, '&copy;');
  746. html = html.replace(/<[^>]+>/g, function($0) {
  747. return $0.replace(/\s+/g, ' ');
  748. });
  749. var htmlTagMap = {};
  750. if(htmlTags) {
  751. _each(htmlTags, function(key, val) {
  752. var arr = key.split(',');
  753. for(var i = 0, len = arr.length; i < len; i++) {
  754. htmlTagMap[arr[i]] = _toMap(val);
  755. }
  756. });
  757. if(!htmlTagMap.script) {
  758. html = html.replace(/(<(?:script|script\s[^>]*)>)([\s\S]*?)(<\/script>)/ig, '');
  759. }
  760. if(!htmlTagMap.style) {
  761. html = html.replace(/(<(?:style|style\s[^>]*)>)([\s\S]*?)(<\/style>)/ig, '');
  762. }
  763. }
  764. var re = /(\s*)<(\/)?([\w\-:]+)((?:\s+|(?:\s+[\w\-:]+)|(?:\s+[\w\-:]+=[^\s"'<>]+)|(?:\s+[\w\-:"]+="[^"]*")|(?:\s+[\w\-:"]+='[^']*'))*)(\/)?>(\s*)/g;
  765. var tagStack = [];
  766. var prevTagIsBlockEnd = null;
  767. html = html.replace(re, function($0, $1, $2, $3, $4, $5, $6) {
  768. var full = $0,
  769. startNewline = $1 || '',
  770. startSlash = $2 || '',
  771. tagName = $3.toLowerCase(),
  772. attr = $4 || '',
  773. endSlash = $5 ? ' ' + $5 : '',
  774. endNewline = $6 || '';
  775. if(htmlTags && !htmlTagMap[tagName]) {
  776. return '';
  777. }
  778. if(endSlash === '' && _SINGLE_TAG_MAP[tagName]) {
  779. endSlash = ' /';
  780. }
  781. if(_INLINE_TAG_MAP[tagName]) {
  782. if(startNewline) {
  783. startNewline = ' ';
  784. }
  785. if(endNewline) {
  786. endNewline = ' ';
  787. }
  788. }
  789. if(_PRE_TAG_MAP[tagName]) {
  790. if(startSlash) {
  791. endNewline = '\n';
  792. } else {
  793. startNewline = '\n';
  794. }
  795. }
  796. if(wellFormatted && (tagName == 'br' || tagName === 'hr') && (!simpleWrap || prevTagIsBlockEnd === true)) {
  797. endNewline = '\n';
  798. }
  799. if(_BLOCK_TAG_MAP[tagName] && !_PRE_TAG_MAP[tagName]) {
  800. if(wellFormatted) {
  801. var isEndTag = !!(startSlash && tagStack.length > 0 && tagStack[tagStack.length - 1] === tagName);
  802. if(isEndTag) {
  803. tagStack.pop();
  804. if (simpleWrap) {
  805. startNewline = '';
  806. endNewline = '\n';
  807. }
  808. } else {
  809. tagStack.push(tagName);
  810. if (simpleWrap) {
  811. startNewline = '\n';
  812. endNewline = '';
  813. }
  814. }
  815. if (!simpleWrap) {
  816. startNewline = '\n';
  817. endNewline = '\n';
  818. }
  819. if (!simpleWrap || (prevTagIsBlockEnd === false && !isEndTag) || (prevTagIsBlockEnd === true)) {
  820. for(var i = 0, len = startSlash ? tagStack.length : tagStack.length - 1; i < len; i++) {
  821. startNewline += indentChar;
  822. if(!startSlash && !simpleWrap) {
  823. endNewline += indentChar;
  824. }
  825. }
  826. }
  827. prevTagIsBlockEnd = isEndTag;
  828. if(endSlash) {
  829. tagStack.pop();
  830. } else if(!startSlash && !simpleWrap) {
  831. endNewline += indentChar;
  832. }
  833. } else {
  834. prevTagIsBlockEnd = null;
  835. startNewline = endNewline = '';
  836. }
  837. } else {
  838. prevTagIsBlockEnd = null;
  839. }
  840. if(attr !== '') {
  841. var attrMap = _getAttrList(full, true);
  842. if(tagName === 'font') {
  843. var fontStyleMap = {},
  844. fontStyle = '';
  845. _each(attrMap, function(key, val) {
  846. if(val === true) val = '';
  847. if(key === 'color') {
  848. fontStyleMap.color = val;
  849. delete attrMap[key];
  850. }
  851. if(key === 'size') {
  852. fontStyleMap['font-size'] = fontSizeList[parseInt(val, 10) - 1] || '';
  853. delete attrMap[key];
  854. }
  855. if(key === 'face') {
  856. fontStyleMap['font-family'] = val;
  857. delete attrMap[key];
  858. }
  859. if(key === 'style') {
  860. fontStyle = val;
  861. }
  862. });
  863. if(fontStyle && !/;$/.test(fontStyle)) {
  864. fontStyle += ';';
  865. }
  866. _each(fontStyleMap, function(key, val) {
  867. if(val === '') {
  868. return;
  869. }
  870. if(/\s/.test(val)) {
  871. val = "'" + val + "'";
  872. }
  873. fontStyle += key + ':' + val + ';';
  874. });
  875. attrMap.style = fontStyle;
  876. }
  877. _each(attrMap, function(key, val) {
  878. if (key.indexOf('data-ke-') === 0) {
  879. return;
  880. }
  881. if(val === true) val = '';
  882. if(_FILL_ATTR_MAP[key]) {
  883. attrMap[key] = key;
  884. }
  885. if(_inArray(key, ['src', 'href']) >= 0) {
  886. attrMap[key] = _formatUrl(val, urlType);
  887. }
  888. if(htmlTags && key !== 'style' && !htmlTagMap[tagName]['*'] && !htmlTagMap[tagName][key] ||
  889. tagName === 'body' && key === 'contenteditable' ||
  890. /^kindeditor_\d+$/.test(key)) {
  891. delete attrMap[key];
  892. }
  893. if(key === 'style' && val !== '') {
  894. var styleMap = _getCssList(val);
  895. _each(styleMap, function(k, v) {
  896. if(htmlTags && !htmlTagMap[tagName].style && !htmlTagMap[tagName]['.' + k]) {
  897. delete styleMap[k];
  898. }
  899. });
  900. var style = '';
  901. _each(styleMap, function(k, v) {
  902. style += k + ':' + v + ';';
  903. });
  904. attrMap.style = style;
  905. }
  906. });
  907. attr = '';
  908. _each(attrMap, function(key, val) {
  909. if(val === false || (key === 'style' && val === '')) {
  910. return;
  911. }
  912. if (val === true) {
  913. attr += ' ' + key;
  914. return;
  915. }
  916. val = val.replace(/"/g, '&quot;');
  917. attr += ' ' + key + '="' + val + '"';
  918. });
  919. }
  920. if(tagName === 'font') {
  921. tagName = 'span';
  922. }
  923. return startNewline + '<' + startSlash + tagName + attr + endSlash + '>' + endNewline;
  924. });
  925. html = html.replace(/(<(?:pre|pre\s[^>]*)>)([\s\S]*?)(<\/pre>)/ig, function($0, $1, $2, $3) {
  926. return $1 + $2.replace(/\n/g, '<span id="__kindeditor_pre_newline__">\n') + $3;
  927. });
  928. html = html.replace(/\n\s*\n/g, '\n');
  929. html = html.replace(/<span id="__kindeditor_pre_newline__">\n/g, '\n');
  930. return _trim(html);
  931. }
  932. function _clearMsWord(html, htmlTags) {
  933. html = html.replace(/<meta[\s\S]*?>/ig, '')
  934. .replace(/<![\s\S]*?>/ig, '')
  935. .replace(/<style[^>]*>[\s\S]*?<\/style>/ig, '')
  936. .replace(/<script[^>]*>[\s\S]*?<\/script>/ig, '')
  937. .replace(/<w:[^>]+>[\s\S]*?<\/w:[^>]+>/ig, '')
  938. .replace(/<o:[^>]+>[\s\S]*?<\/o:[^>]+>/ig, '')
  939. .replace(/<xml>[\s\S]*?<\/xml>/ig, '')
  940. .replace(/<(?:table|td)[^>]*>/ig, function(full) {
  941. return full.replace(/border-bottom:([#\w\s]+)/ig, 'border:$1');
  942. });
  943. return _formatHtml(html, htmlTags);
  944. }
  945. function _mediaType(src) {
  946. if(/\.(mp4)(\?|$)/i.test(src)) {
  947. return 'video/mp4';
  948. }
  949. if(/\.(webm)(\?|$)/i.test(src)) {
  950. return 'video/webm';
  951. }
  952. if(/\.(ogg)(\?|$)/i.test(src)) {
  953. return 'video/ogg';
  954. }
  955. if(/\.(mov)(\?|$)/i.test(src)) {
  956. return 'video/quicktime';
  957. }
  958. if(/\.(mp3)(\?|$)/i.test(src)) {
  959. return 'audio/mp3';
  960. }
  961. if(/\.(wav)(\?|$)/i.test(src)) {
  962. return 'audio/wav';
  963. }
  964. if(/\.(flac)(\?|$)/i.test(src)) {
  965. return 'audio/flac';
  966. }
  967. return 'video/application';
  968. }
  969. function _mediaClass(type) {
  970. if(/audio/i.test(type)) {
  971. return 'ke-audio';
  972. }
  973. if(/video/i.test(type)) {
  974. return 'ke-video';
  975. }
  976. return 'ke-media';
  977. }
  978. function _mediaAttrs(srcTag) {
  979. var srcs = [];
  980. srcTag = unescape(srcTag).replace(/<source [^>]*>/ig, function(sourceTag) {
  981. var $source = $(sourceTag);
  982. var src = $source.attr('src');
  983. var type = $source.attr('type');
  984. if(type) src += '#' + type;
  985. srcs.push(src);
  986. return '';
  987. });
  988. var attrs = _getAttrList(srcTag);
  989. if(srcs.length) attrs.src = srcs.join(',');
  990. return attrs;
  991. }
  992. function _mediaEmbed(attrs, mediaType) {
  993. var htmls;
  994. if(mediaType === 'media' || mediaType === 'video' || mediaType === 'audio') {
  995. mediaType = mediaType === 'video' || (attrs.type && attrs.type.indexOf('video') === 0) ? 'video' : 'audio';
  996. htmls = [
  997. '<', mediaType, ' '
  998. ];
  999. var srcs = (attrs.src || '').split(',');
  1000. var autoPlayEnabled;
  1001. var mutedSetted;
  1002. _each(attrs, function(key, val) {
  1003. if (key === 'src' || val === false) {
  1004. return;
  1005. }
  1006. if (val === true || /^(controls|autoplay|loop|muted)$/i.test(key)) {
  1007. if (val !== 'false') {
  1008. htmls.push(key + ' ');
  1009. if (key === 'autoplay') autoPlayEnabled = true;
  1010. else if (key === 'muted') mutedSetted = true;
  1011. }
  1012. } else {
  1013. htmls.push(key, '="', val, '" ');
  1014. }
  1015. });
  1016. if (autoPlayEnabled && !mutedSetted) {
  1017. htmls.push('muted ');
  1018. }
  1019. if (srcs.length > 1) {
  1020. htmls.push('>');
  1021. _each(srcs, function(_, val) {
  1022. var srcType = val.split('#');
  1023. htmls.push('<source src="', srcType[0], '"', srcType.length > 1 ? (' type="' + srcType[1] + '"') : '', ' />');
  1024. });
  1025. htmls.push('</', mediaType, '>');
  1026. } else {
  1027. if(srcs.length) htmls.push('src="', srcs[0], '" ');
  1028. htmls.push('></', mediaType, '>');
  1029. }
  1030. } else {
  1031. htmls = ['<embed '];
  1032. _each(attrs, function(key, val) {
  1033. htmls.push(key, '="', val, '" ');
  1034. });
  1035. htmls.push('/>');
  1036. }
  1037. return htmls.join('');
  1038. }
  1039. function _mediaImg(blankPath, attrs) {
  1040. var width = attrs.width,
  1041. height = attrs.height,
  1042. type = attrs.type || _mediaType(attrs.src),
  1043. srcTag = _mediaEmbed(attrs, type),
  1044. style = '';
  1045. if(/\D/.test(width)) {
  1046. style += 'width:' + width + ';';
  1047. } else if(width > 0) {
  1048. style += 'width:' + width + 'px;';
  1049. }
  1050. if(/\D/.test(height)) {
  1051. style += 'height:' + height + ';';
  1052. } else if(height > 0) {
  1053. style += 'height:' + height + 'px;';
  1054. }
  1055. var html = '<img class="' + _mediaClass(type) + '" src="' + blankPath + '" ';
  1056. if(style !== '') {
  1057. html += 'style="' + style + '" ';
  1058. }
  1059. html += 'data-ke-tag="' + escape(srcTag) + '" alt="" />';
  1060. return html;
  1061. }
  1062. function _tmpl(str, data) {
  1063. var fn = new Function("obj",
  1064. "var p=[],print=function(){p.push.apply(p,arguments);};" +
  1065. "with(obj){p.push('" +
  1066. str.replace(/[\r\t\n]/g, " ")
  1067. .split("<%").join("\t")
  1068. .replace(/((^|%>)[^\t]*)'/g, "$1\r")
  1069. .replace(/\t=(.*?)%>/g, "',$1,'")
  1070. .split("\t").join("');")
  1071. .split("%>").join("p.push('")
  1072. .split("\r").join("\\'") + "');}return p.join('');");
  1073. return data ? fn(data) : fn;
  1074. }
  1075. K.formatUrl = _formatUrl;
  1076. K.formatHtml = _formatHtml;
  1077. K.getCssList = _getCssList;
  1078. K.getAttrList = _getAttrList;
  1079. K.mediaType = _mediaType;
  1080. K.mediaAttrs = _mediaAttrs;
  1081. K.mediaEmbed = _mediaEmbed;
  1082. K.mediaImg = _mediaImg;
  1083. K.clearMsWord = _clearMsWord;
  1084. K.tmpl = _tmpl;
  1085. function _contains(nodeA, nodeB) {
  1086. if(nodeA.nodeType == 9 && nodeB.nodeType != 9) {
  1087. return true;
  1088. }
  1089. while((nodeB = nodeB.parentNode)) {
  1090. if(nodeB == nodeA) {
  1091. return true;
  1092. }
  1093. }
  1094. return false;
  1095. }
  1096. var _getSetAttrDiv = document.createElement('div');
  1097. _getSetAttrDiv.setAttribute('className', 't');
  1098. var _GET_SET_ATTRIBUTE = _getSetAttrDiv.className !== 't';
  1099. function _getAttr(el, key) {
  1100. key = key.toLowerCase();
  1101. var val = null;
  1102. if(!_GET_SET_ATTRIBUTE && el.nodeName.toLowerCase() != 'script') {
  1103. var div = el.ownerDocument.createElement('div');
  1104. div.appendChild(el.cloneNode(false));
  1105. var list = _getAttrList(_unescape(div.innerHTML));
  1106. if(key in list) {
  1107. val = list[key];
  1108. }
  1109. } else {
  1110. try {
  1111. val = el.getAttribute(key, 2);
  1112. } catch(e) {
  1113. val = el.getAttribute(key, 1);
  1114. }
  1115. }
  1116. if(key === 'style' && val !== null) {
  1117. val = _formatCss(val);
  1118. }
  1119. return val;
  1120. }
  1121. function _queryAll(expr, root) {
  1122. var exprList = expr.split(',');
  1123. if(exprList.length > 1) {
  1124. var mergedResults = [];
  1125. _each(exprList, function() {
  1126. _each(_queryAll(this, root), function() {
  1127. if(_inArray(this, mergedResults) < 0) {
  1128. mergedResults.push(this);
  1129. }
  1130. });
  1131. });
  1132. return mergedResults;
  1133. }
  1134. root = root || document;
  1135. function escape(str) {
  1136. if(typeof str != 'string') {
  1137. return str;
  1138. }
  1139. return str.replace(/([^\w\-])/g, '\\$1');
  1140. }
  1141. function stripslashes(str) {
  1142. return str.replace(/\\/g, '');
  1143. }
  1144. function cmpTag(tagA, tagB) {
  1145. return tagA === '*' || tagA.toLowerCase() === escape(tagB.toLowerCase());
  1146. }
  1147. function byId(id, tag, root) {
  1148. var arr = [],
  1149. doc = root.ownerDocument || root,
  1150. el = doc.getElementById(stripslashes(id));
  1151. if(el) {
  1152. if(cmpTag(tag, el.nodeName) && _contains(root, el)) {
  1153. arr.push(el);
  1154. }
  1155. }
  1156. return arr;
  1157. }
  1158. function byClass(className, tag, root) {
  1159. var doc = root.ownerDocument || root,
  1160. arr = [],
  1161. els, i, len, el;
  1162. if(root.getElementsByClassName) {
  1163. els = root.getElementsByClassName(stripslashes(className));
  1164. for(i = 0, len = els.length; i < len; i++) {
  1165. el = els[i];
  1166. if(cmpTag(tag, el.nodeName)) {
  1167. arr.push(el);
  1168. }
  1169. }
  1170. } else if(doc.querySelectorAll) {
  1171. els = doc.querySelectorAll((root.nodeName !== '#document' ? root.nodeName + ' ' : '') + tag + '.' + className);
  1172. for(i = 0, len = els.length; i < len; i++) {
  1173. el = els[i];
  1174. if(_contains(root, el)) {
  1175. arr.push(el);
  1176. }
  1177. }
  1178. } else {
  1179. els = root.getElementsByTagName(tag);
  1180. className = ' ' + className + ' ';
  1181. for(i = 0, len = els.length; i < len; i++) {
  1182. el = els[i];
  1183. if(el.nodeType == 1) {
  1184. var cls = el.className;
  1185. if(cls && (' ' + cls + ' ').indexOf(className) > -1) {
  1186. arr.push(el);
  1187. }
  1188. }
  1189. }
  1190. }
  1191. return arr;
  1192. }
  1193. function byName(name, tag, root) {
  1194. var arr = [],
  1195. doc = root.ownerDocument || root,
  1196. els = doc.getElementsByName(stripslashes(name)),
  1197. el;
  1198. for(var i = 0, len = els.length; i < len; i++) {
  1199. el = els[i];
  1200. if(cmpTag(tag, el.nodeName) && _contains(root, el)) {
  1201. if(el.getAttribute('name') !== null) {
  1202. arr.push(el);
  1203. }
  1204. }
  1205. }
  1206. return arr;
  1207. }
  1208. function byAttr(key, val, tag, root) {
  1209. var arr = [],
  1210. els = root.getElementsByTagName(tag),
  1211. el;
  1212. for(var i = 0, len = els.length; i < len; i++) {
  1213. el = els[i];
  1214. if(el.nodeType == 1) {
  1215. if(val === null) {
  1216. if(_getAttr(el, key) !== null) {
  1217. arr.push(el);
  1218. }
  1219. } else {
  1220. if(val === escape(_getAttr(el, key))) {
  1221. arr.push(el);
  1222. }
  1223. }
  1224. }
  1225. }
  1226. return arr;
  1227. }
  1228. function select(expr, root) {
  1229. var arr = [],
  1230. matches;
  1231. matches = /^((?:\\.|[^.#\s\[<>])+)/.exec(expr);
  1232. var tag = matches ? matches[1] : '*';
  1233. if((matches = /#((?:[\w\-]|\\.)+)$/.exec(expr))) {
  1234. arr = byId(matches[1], tag, root);
  1235. } else if((matches = /\.((?:[\w\-]|\\.)+)$/.exec(expr))) {
  1236. arr = byClass(matches[1], tag, root);
  1237. } else if((matches = /\[((?:[\w\-]|\\.)+)\]/.exec(expr))) {
  1238. arr = byAttr(matches[1].toLowerCase(), null, tag, root);
  1239. } else if((matches = /\[((?:[\w\-]|\\.)+)\s*=\s*['"]?((?:\\.|[^'"]+)+)['"]?\]/.exec(expr))) {
  1240. var key = matches[1].toLowerCase(),
  1241. val = matches[2];
  1242. if(key === 'id') {
  1243. arr = byId(val, tag, root);
  1244. } else if(key === 'class') {
  1245. arr = byClass(val, tag, root);
  1246. } else if(key === 'name') {
  1247. arr = byName(val, tag, root);
  1248. } else {
  1249. arr = byAttr(key, val, tag, root);
  1250. }
  1251. } else {
  1252. var els = root.getElementsByTagName(tag),
  1253. el;
  1254. for(var i = 0, len = els.length; i < len; i++) {
  1255. el = els[i];
  1256. if(el.nodeType == 1) {
  1257. arr.push(el);
  1258. }
  1259. }
  1260. }
  1261. return arr;
  1262. }
  1263. var parts = [],
  1264. arr, re = /((?:\\.|[^\s>])+|[\s>])/g;
  1265. while((arr = re.exec(expr))) {
  1266. if(arr[1] !== ' ') {
  1267. parts.push(arr[1]);
  1268. }
  1269. }
  1270. var results = [];
  1271. if(parts.length == 1) {
  1272. return select(parts[0], root);
  1273. }
  1274. var isChild = false,
  1275. part, els, subResults, val, v, i, j, k, length, len, l;
  1276. for(i = 0, lenth = parts.length; i < lenth; i++) {
  1277. part = parts[i];
  1278. if(part === '>') {
  1279. isChild = true;
  1280. continue;
  1281. }
  1282. if(i > 0) {
  1283. els = [];
  1284. for(j = 0, len = results.length; j < len; j++) {
  1285. val = results[j];
  1286. subResults = select(part, val);
  1287. for(k = 0, l = subResults.length; k < l; k++) {
  1288. v = subResults[k];
  1289. if(isChild) {
  1290. if(val === v.parentNode) {
  1291. els.push(v);
  1292. }
  1293. } else {
  1294. els.push(v);
  1295. }
  1296. }
  1297. }
  1298. results = els;
  1299. } else {
  1300. results = select(part, root);
  1301. }
  1302. if(results.length === 0) {
  1303. return [];
  1304. }
  1305. }
  1306. return results;
  1307. }
  1308. function _query(expr, root) {
  1309. var arr = _queryAll(expr, root);
  1310. return arr.length > 0 ? arr[0] : null;
  1311. }
  1312. K.query = _query;
  1313. K.queryAll = _queryAll;
  1314. function _get(val) {
  1315. return K(val)[0];
  1316. }
  1317. function _getDoc(node) {
  1318. if(!node) {
  1319. return document;
  1320. }
  1321. return node.ownerDocument || node.document || node;
  1322. }
  1323. function _getWin(node) {
  1324. if(!node) {
  1325. return window;
  1326. }
  1327. var doc = _getDoc(node);
  1328. return doc.parentWindow || doc.defaultView;
  1329. }
  1330. function _setHtml(el, html) {
  1331. if(el.nodeType != 1) {
  1332. return;
  1333. }
  1334. var doc = _getDoc(el);
  1335. try {
  1336. el.innerHTML = '<img id="__kindeditor_temp_tag__" width="0" height="0" style="display:none;" />' + html;
  1337. var temp = doc.getElementById('__kindeditor_temp_tag__');
  1338. temp.parentNode.removeChild(temp);
  1339. } catch(e) {
  1340. K(el).empty();
  1341. K('@' + html, doc).each(function() {
  1342. el.appendChild(this);
  1343. });
  1344. }
  1345. }
  1346. function _hasClass(el, cls) {
  1347. return _inString(cls, el.className, ' ');
  1348. }
  1349. function _setAttr(el, key, val) {
  1350. if(_IE && _V < 8 && key.toLowerCase() == 'class') {
  1351. key = 'className';
  1352. }
  1353. el.setAttribute(key, '' + val);
  1354. }
  1355. function _removeAttr(el, key) {
  1356. if(_IE && _V < 8 && key.toLowerCase() == 'class') {
  1357. key = 'className';
  1358. }
  1359. _setAttr(el, key, '');
  1360. el.removeAttribute(key);
  1361. }
  1362. function _getNodeName(node) {
  1363. if(!node || !node.nodeName) {
  1364. return '';
  1365. }
  1366. return node.nodeName.toLowerCase();
  1367. }
  1368. function _computedCss(el, key) {
  1369. var self = this,
  1370. win = _getWin(el),
  1371. camelKey = _toCamel(key),
  1372. val = '';
  1373. if(win.getComputedStyle) {
  1374. var style = win.getComputedStyle(el, null);
  1375. val = style[camelKey] || style.getPropertyValue(key) || el.style[camelKey];
  1376. } else if(el.currentStyle) {
  1377. val = el.currentStyle[camelKey] || el.style[camelKey];
  1378. }
  1379. return val;
  1380. }
  1381. function _hasVal(node) {
  1382. return !!_VALUE_TAG_MAP[_getNodeName(node)];
  1383. }
  1384. function _docElement(doc) {
  1385. doc = doc || document;
  1386. return _QUIRKS ? doc.body : doc.documentElement;
  1387. }
  1388. function _docHeight(doc) {
  1389. var el = _docElement(doc);
  1390. return Math.max(el.scrollHeight, el.clientHeight);
  1391. }
  1392. function _docWidth(doc) {
  1393. var el = _docElement(doc);
  1394. return Math.max(el.scrollWidth, el.clientWidth);
  1395. }
  1396. function _getScrollPos(doc) {
  1397. doc = doc || document;
  1398. var x, y;
  1399. if (_IE || _NEWIE || _OPERA) {
  1400. x = _docElement(doc).scrollLeft;
  1401. y = _docElement(doc).scrollTop;
  1402. } else {
  1403. x = _getWin(doc).scrollX;
  1404. y = _getWin(doc).scrollY;
  1405. }
  1406. return {x : x, y : y};
  1407. }
  1408. function KNode(node) {
  1409. this.init(node);
  1410. }
  1411. _extend(KNode, {
  1412. init: function(node) {
  1413. var self = this;
  1414. node = _isArray(node) ? node : [node];
  1415. var length = 0;
  1416. for(var i = 0, len = node.length; i < len; i++) {
  1417. if(node[i]) {
  1418. self[i] = node[i].constructor === KNode ? node[i][0] : node[i];
  1419. length++;
  1420. }
  1421. }
  1422. self.length = length;
  1423. self.doc = _getDoc(self[0]);
  1424. self.name = _getNodeName(self[0]);
  1425. self.type = self.length > 0 ? self[0].nodeType : null;
  1426. self.win = _getWin(self[0]);
  1427. },
  1428. each: function(fn) {
  1429. var self = this;
  1430. for(var i = 0; i < self.length; i++) {
  1431. if(fn.call(self[i], i, self[i]) === false) {
  1432. return self;
  1433. }
  1434. }
  1435. return self;
  1436. },
  1437. bind: function(type, fn) {
  1438. this.each(function() {
  1439. _bind(this, type, fn);
  1440. });
  1441. return this;
  1442. },
  1443. unbind: function(type, fn) {
  1444. this.each(function() {
  1445. _unbind(this, type, fn);
  1446. });
  1447. return this;
  1448. },
  1449. fire: function(type) {
  1450. if(this.length < 1) {
  1451. return this;
  1452. }
  1453. _fire(this[0], type);
  1454. return this;
  1455. },
  1456. hasAttr: function(key) {
  1457. if(this.length < 1) {
  1458. return false;
  1459. }
  1460. return !!_getAttr(this[0], key);
  1461. },
  1462. attr: function(key, val) {
  1463. var self = this;
  1464. if(key === undefined) {
  1465. return _getAttrList(self.outer());
  1466. }
  1467. if(typeof key === 'object') {
  1468. _each(key, function(k, v) {
  1469. self.attr(k, v);
  1470. });
  1471. return self;
  1472. }
  1473. if(val === undefined) {
  1474. val = self.length < 1 ? null : _getAttr(self[0], key);
  1475. return val === null ? '' : val;
  1476. }
  1477. self.each(function() {
  1478. _setAttr(this, key, val);
  1479. });
  1480. return self;
  1481. },
  1482. removeAttr: function(key) {
  1483. this.each(function() {
  1484. _removeAttr(this, key);
  1485. });
  1486. return this;
  1487. },
  1488. get: function(i) {
  1489. if(this.length < 1) {
  1490. return null;
  1491. }
  1492. return this[i || 0];
  1493. },
  1494. eq: function(i) {
  1495. if(this.length < 1) {
  1496. return null;
  1497. }
  1498. return this[i] ? new KNode(this[i]) : null;
  1499. },
  1500. hasClass: function(cls) {
  1501. if(this.length < 1) {
  1502. return false;
  1503. }
  1504. return _hasClass(this[0], cls);
  1505. },
  1506. addClass: function(cls) {
  1507. this.each(function() {
  1508. if(!_hasClass(this, cls)) {
  1509. this.className = _trim(this.className + ' ' + cls);
  1510. }
  1511. });
  1512. return this;
  1513. },
  1514. removeClass: function(cls) {
  1515. this.each(function() {
  1516. if(_hasClass(this, cls)) {
  1517. this.className = _trim(this.className.replace(new RegExp('(^|\\s)' + cls + '(\\s|$)'), ' '));
  1518. }
  1519. });
  1520. return this;
  1521. },
  1522. html: function(val) {
  1523. var self = this;
  1524. if(val === undefined) {
  1525. if(self.length < 1 || self.type != 1) {
  1526. return '';
  1527. }
  1528. return _formatHtml(self[0].innerHTML);
  1529. }
  1530. self.each(function() {
  1531. _setHtml(this, val);
  1532. });
  1533. return self;
  1534. },
  1535. text: function() {
  1536. var self = this;
  1537. if(self.length < 1) {
  1538. return '';
  1539. }
  1540. return _IE ? self[0].innerText : self[0].textContent;
  1541. },
  1542. hasVal: function() {
  1543. if(this.length < 1) {
  1544. return false;
  1545. }
  1546. return _hasVal(this[0]);
  1547. },
  1548. val: function(val) {
  1549. var self = this;
  1550. if(val === undefined) {
  1551. if(self.length < 1) {
  1552. return '';
  1553. }
  1554. return self.hasVal() ? self[0].value : self.attr('value');
  1555. } else {
  1556. self.each(function() {
  1557. if(_hasVal(this)) {
  1558. this.value = val;
  1559. } else {
  1560. _setAttr(this, 'value', val);
  1561. }
  1562. });
  1563. return self;
  1564. }
  1565. },
  1566. css: function(key, val) {
  1567. var self = this;
  1568. if(key === undefined) {
  1569. return _getCssList(self.attr('style'));
  1570. }
  1571. if(typeof key === 'object') {
  1572. _each(key, function(k, v) {
  1573. self.css(k, v);
  1574. });
  1575. return self;
  1576. }
  1577. if(val === undefined) {
  1578. if(self.length < 1) {
  1579. return '';
  1580. }
  1581. return self[0].style[_toCamel(key)] || _computedCss(self[0], key) || '';
  1582. }
  1583. self.each(function() {
  1584. this.style[_toCamel(key)] = val;
  1585. });
  1586. return self;
  1587. },
  1588. width: function(val) {
  1589. var self = this;
  1590. if(val === undefined) {
  1591. if(self.length < 1) {
  1592. return 0;
  1593. }
  1594. return self[0].offsetWidth;
  1595. }
  1596. return self.css('width', _addUnit(val));
  1597. },
  1598. height: function(val) {
  1599. var self = this;
  1600. if(val === undefined) {
  1601. if(self.length < 1) {
  1602. return 0;
  1603. }
  1604. return self[0].offsetHeight;
  1605. }
  1606. return self.css('height', _addUnit(val));
  1607. },
  1608. opacity: function(val) {
  1609. this.each(function() {
  1610. if(this.style.opacity === undefined) {
  1611. this.style.filter = val == 1 ? '' : 'alpha(opacity=' + (val * 100) + ')';
  1612. } else {
  1613. this.style.opacity = val == 1 ? '' : val;
  1614. }
  1615. });
  1616. return this;
  1617. },
  1618. data: function(key, val) {
  1619. var self = this;
  1620. key = 'kindeditor_data_' + key;
  1621. if(val === undefined) {
  1622. if(self.length < 1) {
  1623. return null;
  1624. }
  1625. return self[0][key];
  1626. }
  1627. this.each(function() {
  1628. this[key] = val;
  1629. });
  1630. return self;
  1631. },
  1632. pos: function() {
  1633. var self = this,
  1634. node = self[0],
  1635. x = 0,
  1636. y = 0;
  1637. if(node) {
  1638. if(node.getBoundingClientRect) {
  1639. var box = node.getBoundingClientRect(),
  1640. pos = _getScrollPos(self.doc);
  1641. x = box.left + pos.x;
  1642. y = box.top + pos.y;
  1643. } else {
  1644. while(node) {
  1645. x += node.offsetLeft;
  1646. y += node.offsetTop;
  1647. node = node.offsetParent;
  1648. }
  1649. }
  1650. }
  1651. return {
  1652. x: _round(x),
  1653. y: _round(y)
  1654. };
  1655. },
  1656. clone: function(bool) {
  1657. if(this.length < 1) {
  1658. return new KNode([]);
  1659. }
  1660. return new KNode(this[0].cloneNode(bool));
  1661. },
  1662. append: function(expr) {
  1663. this.each(function() {
  1664. if(this.appendChild) {
  1665. this.appendChild(_get(expr));
  1666. }
  1667. });
  1668. return this;
  1669. },
  1670. appendTo: function(expr) {
  1671. this.each(function() {
  1672. _get(expr).appendChild(this);
  1673. });
  1674. return this;
  1675. },
  1676. before: function(expr) {
  1677. this.each(function() {
  1678. this.parentNode.insertBefore(_get(expr), this);
  1679. });
  1680. return this;
  1681. },
  1682. after: function(expr) {
  1683. this.each(function() {
  1684. if(this.nextSibling) {
  1685. this.parentNode.insertBefore(_get(expr), this.nextSibling);
  1686. } else {
  1687. this.parentNode.appendChild(_get(expr));
  1688. }
  1689. });
  1690. return this;
  1691. },
  1692. replaceWith: function(expr) {
  1693. var nodes = [];
  1694. this.each(function(i, node) {
  1695. _unbind(node);
  1696. var newNode = _get(expr);
  1697. node.parentNode.replaceChild(newNode, node);
  1698. nodes.push(newNode);
  1699. });
  1700. return K(nodes);
  1701. },
  1702. empty: function() {
  1703. var self = this;
  1704. self.each(function(i, node) {
  1705. var child = node.firstChild;
  1706. while(child) {
  1707. if(!node.parentNode) {
  1708. return;
  1709. }
  1710. var next = child.nextSibling;
  1711. child.parentNode.removeChild(child);
  1712. child = next;
  1713. }
  1714. });
  1715. return self;
  1716. },
  1717. remove: function(keepChilds) {
  1718. var self = this;
  1719. self.each(function(i, node) {
  1720. if(!node.parentNode) {
  1721. return;
  1722. }
  1723. _unbind(node);
  1724. if(keepChilds) {
  1725. var child = node.firstChild;
  1726. while(child) {
  1727. var next = child.nextSibling;
  1728. node.parentNode.insertBefore(child, node);
  1729. child = next;
  1730. }
  1731. }
  1732. node.parentNode.removeChild(node);
  1733. delete self[i];
  1734. });
  1735. self.length = 0;
  1736. return self;
  1737. },
  1738. show: function(val) {
  1739. var self = this;
  1740. if(val === undefined) {
  1741. val = self._originDisplay || '';
  1742. }
  1743. if(self.css('display') != 'none') {
  1744. return self;
  1745. }
  1746. return self.css('display', val);
  1747. },
  1748. hide: function() {
  1749. var self = this;
  1750. if(self.length < 1) {
  1751. return self;
  1752. }
  1753. self._originDisplay = self[0].style.display;
  1754. return self.css('display', 'none');
  1755. },
  1756. outer: function() {
  1757. var self = this;
  1758. if(self.length < 1) {
  1759. return '';
  1760. }
  1761. var div = self.doc.createElement('div'),
  1762. html;
  1763. div.appendChild(self[0].cloneNode(true));
  1764. html = _formatHtml(div.innerHTML);
  1765. div = null;
  1766. return html;
  1767. },
  1768. isSingle: function() {
  1769. return !!_SINGLE_TAG_MAP[this.name];
  1770. },
  1771. isInline: function() {
  1772. return !!_INLINE_TAG_MAP[this.name];
  1773. },
  1774. isBlock: function() {
  1775. return !!_BLOCK_TAG_MAP[this.name];
  1776. },
  1777. isStyle: function() {
  1778. return !!_STYLE_TAG_MAP[this.name];
  1779. },
  1780. isControl: function() {
  1781. return !!_CONTROL_TAG_MAP[this.name];
  1782. },
  1783. contains: function(otherNode) {
  1784. if(this.length < 1) {
  1785. return false;
  1786. }
  1787. return _contains(this[0], _get(otherNode));
  1788. },
  1789. parent: function() {
  1790. if(this.length < 1) {
  1791. return null;
  1792. }
  1793. var node = this[0].parentNode;
  1794. return node ? new KNode(node) : null;
  1795. },
  1796. children: function() {
  1797. if(this.length < 1) {
  1798. return new KNode([]);
  1799. }
  1800. var list = [],
  1801. child = this[0].firstChild;
  1802. while(child) {
  1803. if(child.nodeType != 3 || _trim(child.nodeValue) !== '') {
  1804. list.push(child);
  1805. }
  1806. child = child.nextSibling;
  1807. }
  1808. return new KNode(list);
  1809. },
  1810. first: function() {
  1811. var list = this.children();
  1812. return list.length > 0 ? list.eq(0) : null;
  1813. },
  1814. last: function() {
  1815. var list = this.children();
  1816. return list.length > 0 ? list.eq(list.length - 1) : null;
  1817. },
  1818. index: function() {
  1819. if(this.length < 1) {
  1820. return -1;
  1821. }
  1822. var i = -1,
  1823. sibling = this[0];
  1824. while(sibling) {
  1825. i++;
  1826. sibling = sibling.previousSibling;
  1827. }
  1828. return i;
  1829. },
  1830. prev: function() {
  1831. if(this.length < 1) {
  1832. return null;
  1833. }
  1834. var node = this[0].previousSibling;
  1835. return node ? new KNode(node) : null;
  1836. },
  1837. next: function() {
  1838. if(this.length < 1) {
  1839. return null;
  1840. }
  1841. var node = this[0].nextSibling;
  1842. return node ? new KNode(node) : null;
  1843. },
  1844. scan: function(fn, order) {
  1845. if(this.length < 1) {
  1846. return;
  1847. }
  1848. order = (order === undefined) ? true : order;
  1849. function walk(node) {
  1850. var n = order ? node.firstChild : node.lastChild;
  1851. while(n) {
  1852. var next = order ? n.nextSibling : n.previousSibling;
  1853. if(fn(n) === false) {
  1854. return false;
  1855. }
  1856. if(walk(n) === false) {
  1857. return false;
  1858. }
  1859. n = next;
  1860. }
  1861. }
  1862. walk(this[0]);
  1863. return this;
  1864. }
  1865. });
  1866. _each(('blur,focus,focusin,focusout,load,resize,scroll,unload,click,dblclick,' +
  1867. 'mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave,' +
  1868. 'change,select,submit,keydown,keypress,keyup,error,contextmenu').split(','), function(i, type) {
  1869. KNode.prototype[type] = function(fn) {
  1870. return fn ? this.bind(type, fn) : this.fire(type);
  1871. };
  1872. });
  1873. var _K = K;
  1874. K = function(expr, root) {
  1875. if(expr === undefined || expr === null) {
  1876. return;
  1877. }
  1878. function newNode(node) {
  1879. if(!node[0]) {
  1880. node = [];
  1881. }
  1882. return new KNode(node);
  1883. }
  1884. if(typeof expr === 'string') {
  1885. if(root) {
  1886. root = _get(root);
  1887. }
  1888. var length = expr.length;
  1889. if(expr.charAt(0) === '@') {
  1890. expr = expr.substr(1);
  1891. }
  1892. if(expr.length !== length || /<.+>/.test(expr)) {
  1893. var doc = root ? root.ownerDocument || root : document,
  1894. div = doc.createElement('div'),
  1895. list = [];
  1896. div.innerHTML = '<img id="__kindeditor_temp_tag__" width="0" height="0" style="display:none;" />' + expr;
  1897. for(var i = 0, len = div.childNodes.length; i < len; i++) {
  1898. var child = div.childNodes[i];
  1899. if(child.id == '__kindeditor_temp_tag__') {
  1900. continue;
  1901. }
  1902. list.push(child);
  1903. }
  1904. return newNode(list);
  1905. }
  1906. return newNode(_queryAll(expr, root));
  1907. }
  1908. if(expr && expr.constructor === KNode) {
  1909. return expr;
  1910. }
  1911. if(expr.toArray) {
  1912. expr = expr.toArray();
  1913. }
  1914. if(_isArray(expr)) {
  1915. return newNode(expr);
  1916. }
  1917. return newNode(_toArray(arguments));
  1918. };
  1919. _each(_K, function(key, val) {
  1920. K[key] = val;
  1921. });
  1922. K.NodeClass = KNode;
  1923. window.KindEditor = K;
  1924. var _START_TO_START = 0,
  1925. _START_TO_END = 1,
  1926. _END_TO_END = 2,
  1927. _END_TO_START = 3,
  1928. _BOOKMARK_ID = 0;
  1929. function _updateCollapsed(range) {
  1930. range.collapsed = (range.startContainer === range.endContainer && range.startOffset === range.endOffset);
  1931. return range;
  1932. }
  1933. function _copyAndDelete(range, isCopy, isDelete) {
  1934. var doc = range.doc,
  1935. nodeList = [];
  1936. function splitTextNode(node, startOffset, endOffset) {
  1937. var length = node.nodeValue.length,
  1938. centerNode;
  1939. if(isCopy) {
  1940. var cloneNode = node.cloneNode(true);
  1941. if(startOffset > 0) {
  1942. centerNode = cloneNode.splitText(startOffset);
  1943. } else {
  1944. centerNode = cloneNode;
  1945. }
  1946. if(endOffset < length) {
  1947. centerNode.splitText(endOffset - startOffset);
  1948. }
  1949. }
  1950. if(isDelete) {
  1951. var center = node;
  1952. if(startOffset > 0) {
  1953. center = node.splitText(startOffset);
  1954. range.setStart(node, startOffset);
  1955. }
  1956. if(endOffset < length) {
  1957. var right = center.splitText(endOffset - startOffset);
  1958. range.setEnd(right, 0);
  1959. }
  1960. nodeList.push(center);
  1961. }
  1962. return centerNode;
  1963. }
  1964. function removeNodes() {
  1965. if(isDelete) {
  1966. range.up().collapse(true);
  1967. }
  1968. for(var i = 0, len = nodeList.length; i < len; i++) {
  1969. var node = nodeList[i];
  1970. if(node.parentNode) {
  1971. node.parentNode.removeChild(node);
  1972. }
  1973. }
  1974. }
  1975. var copyRange = range.cloneRange().down();
  1976. var start = -1,
  1977. incStart = -1,
  1978. incEnd = -1,
  1979. end = -1,
  1980. ancestor = range.commonAncestor(),
  1981. frag = doc.createDocumentFragment();
  1982. if(ancestor.nodeType == 3) {
  1983. var textNode = splitTextNode(ancestor, range.startOffset, range.endOffset);
  1984. if(isCopy) {
  1985. frag.appendChild(textNode);
  1986. }
  1987. removeNodes();
  1988. return isCopy ? frag : range;
  1989. }
  1990. function extractNodes(parent, frag) {
  1991. var node = parent.firstChild,
  1992. nextNode;
  1993. while(node) {
  1994. var testRange = new KRange(doc).selectNode(node);
  1995. start = testRange.compareBoundaryPoints(_START_TO_END, range);
  1996. if(start >= 0 && incStart <= 0) {
  1997. incStart = testRange.compareBoundaryPoints(_START_TO_START, range);
  1998. }
  1999. if(incStart >= 0 && incEnd <= 0) {
  2000. incEnd = testRange.compareBoundaryPoints(_END_TO_END, range);
  2001. }
  2002. if(incEnd >= 0 && end <= 0) {
  2003. end = testRange.compareBoundaryPoints(_END_TO_START, range);
  2004. }
  2005. if(end >= 0) {
  2006. return false;
  2007. }
  2008. nextNode = node.nextSibling;
  2009. if(start > 0) {
  2010. if(node.nodeType == 1) {
  2011. if(incStart >= 0 && incEnd <= 0) {
  2012. if(isCopy) {
  2013. frag.appendChild(node.cloneNode(true));
  2014. }
  2015. if(isDelete) {
  2016. nodeList.push(node);
  2017. }
  2018. } else {
  2019. var childFlag;
  2020. if(isCopy) {
  2021. childFlag = node.cloneNode(false);
  2022. frag.appendChild(childFlag);
  2023. }
  2024. if(extractNodes(node, childFlag) === false) {
  2025. return false;
  2026. }
  2027. }
  2028. } else if(node.nodeType == 3) {
  2029. var textNode;
  2030. if(node == copyRange.startContainer) {
  2031. textNode = splitTextNode(node, copyRange.startOffset, node.nodeValue.length);
  2032. } else if(node == copyRange.endContainer) {
  2033. textNode = splitTextNode(node, 0, copyRange.endOffset);
  2034. } else {
  2035. textNode = splitTextNode(node, 0, node.nodeValue.length);
  2036. }
  2037. if(isCopy) {
  2038. try {
  2039. frag.appendChild(textNode);
  2040. } catch(e) {}
  2041. }
  2042. }
  2043. }
  2044. node = nextNode;
  2045. }
  2046. }
  2047. extractNodes(ancestor, frag);
  2048. if(isDelete) {
  2049. range.up().collapse(true);
  2050. }
  2051. for(var i = 0, len = nodeList.length; i < len; i++) {
  2052. var node = nodeList[i];
  2053. if(node.parentNode) {
  2054. node.parentNode.removeChild(node);
  2055. }
  2056. }
  2057. return isCopy ? frag : range;
  2058. }
  2059. function _moveToElementText(range, el) {
  2060. var node = el;
  2061. while(node) {
  2062. var knode = K(node);
  2063. if(knode.name == 'marquee' || knode.name == 'select') {
  2064. return;
  2065. }
  2066. node = node.parentNode;
  2067. }
  2068. try {
  2069. range.moveToElementText(el);
  2070. } catch(e) {}
  2071. }
  2072. function _getStartEnd(rng, isStart) {
  2073. var doc = rng.parentElement().ownerDocument,
  2074. pointRange = rng.duplicate();
  2075. pointRange.collapse(isStart);
  2076. var parent = pointRange.parentElement(),
  2077. nodes = parent.childNodes;
  2078. if(nodes.length === 0) {
  2079. return {
  2080. node: parent.parentNode,
  2081. offset: K(parent).index()
  2082. };
  2083. }
  2084. var startNode = doc,
  2085. startPos = 0,
  2086. cmp = -1;
  2087. var testRange = rng.duplicate();
  2088. _moveToElementText(testRange, parent);
  2089. for(var i = 0, len = nodes.length; i < len; i++) {
  2090. var node = nodes[i];
  2091. cmp = testRange.compareEndPoints('StartToStart', pointRange);
  2092. if(cmp === 0) {
  2093. return {
  2094. node: node.parentNode,
  2095. offset: i
  2096. };
  2097. }
  2098. if(node.nodeType == 1) {
  2099. var nodeRange = rng.duplicate(),
  2100. dummy, knode = K(node),
  2101. newNode = node;
  2102. if(knode.isControl()) {
  2103. dummy = doc.createElement('span');
  2104. knode.after(dummy);
  2105. newNode = dummy;
  2106. startPos += knode.text().replace(/\r\n|\n|\r/g, '').length;
  2107. }
  2108. _moveToElementText(nodeRange, newNode);
  2109. testRange.setEndPoint('StartToEnd', nodeRange);
  2110. if(cmp > 0) {
  2111. startPos += nodeRange.text.replace(/\r\n|\n|\r/g, '').length;
  2112. } else {
  2113. startPos = 0;
  2114. }
  2115. if(dummy) {
  2116. K(dummy).remove();
  2117. }
  2118. } else if(node.nodeType == 3) {
  2119. testRange.moveStart('character', node.nodeValue.length);
  2120. startPos += node.nodeValue.length;
  2121. }
  2122. if(cmp < 0) {
  2123. startNode = node;
  2124. }
  2125. }
  2126. if(cmp < 0 && startNode.nodeType == 1) {
  2127. return {
  2128. node: parent,
  2129. offset: K(parent.lastChild).index() + 1
  2130. };
  2131. }
  2132. if(cmp > 0) {
  2133. while(startNode.nextSibling && startNode.nodeType == 1) {
  2134. startNode = startNode.nextSibling;
  2135. }
  2136. }
  2137. testRange = rng.duplicate();
  2138. _moveToElementText(testRange, parent);
  2139. testRange.setEndPoint('StartToEnd', pointRange);
  2140. startPos -= testRange.text.replace(/\r\n|\n|\r/g, '').length;
  2141. if(cmp > 0 && startNode.nodeType == 3) {
  2142. var prevNode = startNode.previousSibling;
  2143. while(prevNode && prevNode.nodeType == 3) {
  2144. startPos -= prevNode.nodeValue.length;
  2145. prevNode = prevNode.previousSibling;
  2146. }
  2147. }
  2148. return {
  2149. node: startNode,
  2150. offset: startPos
  2151. };
  2152. }
  2153. function _getEndRange(node, offset) {
  2154. var doc = node.ownerDocument || node,
  2155. range = doc.body.createTextRange();
  2156. if(doc == node) {
  2157. range.collapse(true);
  2158. return range;
  2159. }
  2160. if(node.nodeType == 1 && node.childNodes.length > 0) {
  2161. var children = node.childNodes,
  2162. isStart, child;
  2163. if(offset === 0) {
  2164. child = children[0];
  2165. isStart = true;
  2166. } else {
  2167. child = children[offset - 1];
  2168. isStart = false;
  2169. }
  2170. if(!child) {
  2171. return range;
  2172. }
  2173. if(K(child).name === 'head') {
  2174. if(offset === 1) {
  2175. isStart = true;
  2176. }
  2177. if(offset === 2) {
  2178. isStart = false;
  2179. }
  2180. range.collapse(isStart);
  2181. return range;
  2182. }
  2183. if(child.nodeType == 1) {
  2184. var kchild = K(child),
  2185. span;
  2186. if(kchild.isControl()) {
  2187. span = doc.createElement('span');
  2188. if(isStart) {
  2189. kchild.before(span);
  2190. } else {
  2191. kchild.after(span);
  2192. }
  2193. child = span;
  2194. }
  2195. _moveToElementText(range, child);
  2196. range.collapse(isStart);
  2197. if(span) {
  2198. K(span).remove();
  2199. }
  2200. return range;
  2201. }
  2202. node = child;
  2203. offset = isStart ? 0 : child.nodeValue.length;
  2204. }
  2205. var dummy = doc.createElement('span');
  2206. K(node).before(dummy);
  2207. _moveToElementText(range, dummy);
  2208. range.moveStart('character', offset);
  2209. K(dummy).remove();
  2210. return range;
  2211. }
  2212. function _toRange(rng) {
  2213. var doc, range;
  2214. function tr2td(start) {
  2215. if(K(start.node).name == 'tr') {
  2216. start.node = start.node.cells[start.offset];
  2217. start.offset = 0;
  2218. }
  2219. }
  2220. if(_IERANGE) {
  2221. if(rng.item) {
  2222. doc = _getDoc(rng.item(0));
  2223. range = new KRange(doc);
  2224. range.selectNode(rng.item(0));
  2225. return range;
  2226. }
  2227. doc = rng.parentElement().ownerDocument;
  2228. var start = _getStartEnd(rng, true),
  2229. end = _getStartEnd(rng, false);
  2230. tr2td(start);
  2231. tr2td(end);
  2232. range = new KRange(doc);
  2233. range.setStart(start.node, start.offset);
  2234. range.setEnd(end.node, end.offset);
  2235. return range;
  2236. }
  2237. var startContainer = rng.startContainer;
  2238. doc = startContainer.ownerDocument || startContainer;
  2239. range = new KRange(doc);
  2240. range.setStart(startContainer, rng.startOffset);
  2241. range.setEnd(rng.endContainer, rng.endOffset);
  2242. return range;
  2243. }
  2244. function KRange(doc) {
  2245. this.init(doc);
  2246. }
  2247. _extend(KRange, {
  2248. init: function(doc) {
  2249. var self = this;
  2250. self.startContainer = doc;
  2251. self.startOffset = 0;
  2252. self.endContainer = doc;
  2253. self.endOffset = 0;
  2254. self.collapsed = true;
  2255. self.doc = doc;
  2256. },
  2257. commonAncestor: function() {
  2258. function getParents(node) {
  2259. var parents = [];
  2260. while(node) {
  2261. parents.push(node);
  2262. node = node.parentNode;
  2263. }
  2264. return parents;
  2265. }
  2266. var parentsA = getParents(this.startContainer),
  2267. parentsB = getParents(this.endContainer),
  2268. i = 0,
  2269. lenA = parentsA.length,
  2270. lenB = parentsB.length,
  2271. parentA, parentB;
  2272. while(++i) {
  2273. parentA = parentsA[lenA - i];
  2274. parentB = parentsB[lenB - i];
  2275. if(!parentA || !parentB || parentA !== parentB) {
  2276. break;
  2277. }
  2278. }
  2279. return parentsA[lenA - i + 1];
  2280. },
  2281. setStart: function(node, offset) {
  2282. var self = this,
  2283. doc = self.doc;
  2284. self.startContainer = node;
  2285. self.startOffset = offset;
  2286. if(self.endContainer === doc) {
  2287. self.endContainer = node;
  2288. self.endOffset = offset;
  2289. }
  2290. return _updateCollapsed(this);
  2291. },
  2292. setEnd: function(node, offset) {
  2293. var self = this,
  2294. doc = self.doc;
  2295. self.endContainer = node;
  2296. self.endOffset = offset;
  2297. if(self.startContainer === doc) {
  2298. self.startContainer = node;
  2299. self.startOffset = offset;
  2300. }
  2301. return _updateCollapsed(this);
  2302. },
  2303. setStartBefore: function(node) {
  2304. return this.setStart(node.parentNode || this.doc, K(node).index());
  2305. },
  2306. setStartAfter: function(node) {
  2307. return this.setStart(node.parentNode || this.doc, K(node).index() + 1);
  2308. },
  2309. setEndBefore: function(node) {
  2310. return this.setEnd(node.parentNode || this.doc, K(node).index());
  2311. },
  2312. setEndAfter: function(node) {
  2313. return this.setEnd(node.parentNode || this.doc, K(node).index() + 1);
  2314. },
  2315. selectNode: function(node) {
  2316. return this.setStartBefore(node).setEndAfter(node);
  2317. },
  2318. selectNodeContents: function(node) {
  2319. var knode = K(node);
  2320. if(knode.type == 3 || knode.isSingle()) {
  2321. return this.selectNode(node);
  2322. }
  2323. var children = knode.children();
  2324. if(children.length > 0) {
  2325. return this.setStartBefore(children[0]).setEndAfter(children[children.length - 1]);
  2326. }
  2327. return this.setStart(node, 0).setEnd(node, 0);
  2328. },
  2329. collapse: function(toStart) {
  2330. if(toStart) {
  2331. return this.setEnd(this.startContainer, this.startOffset);
  2332. }
  2333. return this.setStart(this.endContainer, this.endOffset);
  2334. },
  2335. compareBoundaryPoints: function(how, range) {
  2336. var rangeA = this.get(),
  2337. rangeB = range.get();
  2338. if(_IERANGE) {
  2339. var arr = {};
  2340. arr[_START_TO_START] = 'StartToStart';
  2341. arr[_START_TO_END] = 'EndToStart';
  2342. arr[_END_TO_END] = 'EndToEnd';
  2343. arr[_END_TO_START] = 'StartToEnd';
  2344. var cmp = rangeA.compareEndPoints(arr[how], rangeB);
  2345. if(cmp !== 0) {
  2346. return cmp;
  2347. }
  2348. var nodeA, nodeB, nodeC, posA, posB;
  2349. if(how === _START_TO_START || how === _END_TO_START) {
  2350. nodeA = this.startContainer;
  2351. posA = this.startOffset;
  2352. }
  2353. if(how === _START_TO_END || how === _END_TO_END) {
  2354. nodeA = this.endContainer;
  2355. posA = this.endOffset;
  2356. }
  2357. if(how === _START_TO_START || how === _START_TO_END) {
  2358. nodeB = range.startContainer;
  2359. posB = range.startOffset;
  2360. }
  2361. if(how === _END_TO_END || how === _END_TO_START) {
  2362. nodeB = range.endContainer;
  2363. posB = range.endOffset;
  2364. }
  2365. if(nodeA === nodeB) {
  2366. var diff = posA - posB;
  2367. return diff > 0 ? 1 : (diff < 0 ? -1 : 0);
  2368. }
  2369. nodeC = nodeB;
  2370. while(nodeC && nodeC.parentNode !== nodeA) {
  2371. nodeC = nodeC.parentNode;
  2372. }
  2373. if(nodeC) {
  2374. return K(nodeC).index() >= posA ? -1 : 1;
  2375. }
  2376. nodeC = nodeA;
  2377. while(nodeC && nodeC.parentNode !== nodeB) {
  2378. nodeC = nodeC.parentNode;
  2379. }
  2380. if(nodeC) {
  2381. return K(nodeC).index() >= posB ? 1 : -1;
  2382. }
  2383. nodeC = K(nodeB).next();
  2384. if(nodeC && nodeC.contains(nodeA)) {
  2385. return 1;
  2386. }
  2387. nodeC = K(nodeA).next();
  2388. if(nodeC && nodeC.contains(nodeB)) {
  2389. return -1;
  2390. }
  2391. } else {
  2392. return rangeA.compareBoundaryPoints(how, rangeB);
  2393. }
  2394. },
  2395. cloneRange: function() {
  2396. return new KRange(this.doc).setStart(this.startContainer, this.startOffset).setEnd(this.endContainer, this.endOffset);
  2397. },
  2398. toString: function() {
  2399. var rng = this.get(),
  2400. str = _IERANGE ? rng.text : rng.toString();
  2401. return str.replace(/\r\n|\n|\r/g, '');
  2402. },
  2403. cloneContents: function() {
  2404. return _copyAndDelete(this, true, false);
  2405. },
  2406. deleteContents: function() {
  2407. return _copyAndDelete(this, false, true);
  2408. },
  2409. extractContents: function() {
  2410. return _copyAndDelete(this, true, true);
  2411. },
  2412. insertNode: function(node) {
  2413. var self = this,
  2414. sc = self.startContainer,
  2415. so = self.startOffset,
  2416. ec = self.endContainer,
  2417. eo = self.endOffset,
  2418. firstChild, lastChild, c, nodeCount = 1;
  2419. if(node.nodeName.toLowerCase() === '#document-fragment') {
  2420. firstChild = node.firstChild;
  2421. lastChild = node.lastChild;
  2422. nodeCount = node.childNodes.length;
  2423. }
  2424. if(sc.nodeType == 1) {
  2425. c = sc.childNodes[so];
  2426. if(c) {
  2427. sc.insertBefore(node, c);
  2428. if(sc === ec) {
  2429. eo += nodeCount;
  2430. }
  2431. } else {
  2432. sc.appendChild(node);
  2433. }
  2434. } else if(sc.nodeType == 3) {
  2435. if(so === 0) {
  2436. sc.parentNode.insertBefore(node, sc);
  2437. if(sc.parentNode === ec) {
  2438. eo += nodeCount;
  2439. }
  2440. } else if(so >= sc.nodeValue.length) {
  2441. if(sc.nextSibling) {
  2442. sc.parentNode.insertBefore(node, sc.nextSibling);
  2443. } else {
  2444. sc.parentNode.appendChild(node);
  2445. }
  2446. } else {
  2447. if(so > 0) {
  2448. c = sc.splitText(so);
  2449. } else {
  2450. c = sc;
  2451. }
  2452. sc.parentNode.insertBefore(node, c);
  2453. if(sc === ec) {
  2454. ec = c;
  2455. eo -= so;
  2456. }
  2457. }
  2458. }
  2459. if(firstChild) {
  2460. self.setStartBefore(firstChild).setEndAfter(lastChild);
  2461. } else {
  2462. self.selectNode(node);
  2463. }
  2464. if(self.compareBoundaryPoints(_END_TO_END, self.cloneRange().setEnd(ec, eo)) >= 1) {
  2465. return self;
  2466. }
  2467. return self.setEnd(ec, eo);
  2468. },
  2469. surroundContents: function(node) {
  2470. node.appendChild(this.extractContents());
  2471. return this.insertNode(node).selectNode(node);
  2472. },
  2473. isControl: function() {
  2474. var self = this,
  2475. sc = self.startContainer,
  2476. so = self.startOffset,
  2477. ec = self.endContainer,
  2478. eo = self.endOffset,
  2479. rng;
  2480. return sc.nodeType == 1 && sc === ec && so + 1 === eo && K(sc.childNodes[so]).isControl();
  2481. },
  2482. get: function(hasControlRange) {
  2483. var self = this,
  2484. doc = self.doc,
  2485. node, rng;
  2486. if(!_IERANGE) {
  2487. rng = doc.createRange();
  2488. try {
  2489. rng.setStart(self.startContainer, self.startOffset);
  2490. rng.setEnd(self.endContainer, self.endOffset);
  2491. } catch(e) {}
  2492. return rng;
  2493. }
  2494. if(hasControlRange && self.isControl()) {
  2495. rng = doc.body.createControlRange();
  2496. rng.addElement(self.startContainer.childNodes[self.startOffset]);
  2497. return rng;
  2498. }
  2499. var range = self.cloneRange().down();
  2500. rng = doc.body.createTextRange();
  2501. rng.setEndPoint('StartToStart', _getEndRange(range.startContainer, range.startOffset));
  2502. rng.setEndPoint('EndToStart', _getEndRange(range.endContainer, range.endOffset));
  2503. return rng;
  2504. },
  2505. html: function() {
  2506. return K(this.cloneContents()).outer();
  2507. },
  2508. down: function() {
  2509. var self = this;
  2510. function downPos(node, pos, isStart) {
  2511. if(node.nodeType != 1) {
  2512. return;
  2513. }
  2514. var children = K(node).children();
  2515. if(children.length === 0) {
  2516. return;
  2517. }
  2518. var left, right, child, offset;
  2519. if(pos > 0) {
  2520. left = children.eq(pos - 1);
  2521. }
  2522. if(pos < children.length) {
  2523. right = children.eq(pos);
  2524. }
  2525. if(left && left.type == 3) {
  2526. child = left[0];
  2527. offset = child.nodeValue.length;
  2528. }
  2529. if(right && right.type == 3) {
  2530. child = right[0];
  2531. offset = 0;
  2532. }
  2533. if(!child) {
  2534. return;
  2535. }
  2536. if(isStart) {
  2537. self.setStart(child, offset);
  2538. } else {
  2539. self.setEnd(child, offset);
  2540. }
  2541. }
  2542. downPos(self.startContainer, self.startOffset, true);
  2543. downPos(self.endContainer, self.endOffset, false);
  2544. return self;
  2545. },
  2546. up: function() {
  2547. var self = this;
  2548. function upPos(node, pos, isStart) {
  2549. if(node.nodeType != 3) {
  2550. return;
  2551. }
  2552. if(pos === 0) {
  2553. if(isStart) {
  2554. self.setStartBefore(node);
  2555. } else {
  2556. self.setEndBefore(node);
  2557. }
  2558. } else if(pos == node.nodeValue.length) {
  2559. if(isStart) {
  2560. self.setStartAfter(node);
  2561. } else {
  2562. self.setEndAfter(node);
  2563. }
  2564. }
  2565. }
  2566. upPos(self.startContainer, self.startOffset, true);
  2567. upPos(self.endContainer, self.endOffset, false);
  2568. return self;
  2569. },
  2570. enlarge: function(toBlock) {
  2571. var self = this;
  2572. self.up();
  2573. function enlargePos(node, pos, isStart) {
  2574. var knode = K(node),
  2575. parent;
  2576. if(knode.type == 3 || _NOSPLIT_TAG_MAP[knode.name] || !toBlock && knode.isBlock()) {
  2577. return;
  2578. }
  2579. if(pos === 0) {
  2580. while(!knode.prev()) {
  2581. parent = knode.parent();
  2582. if(!parent || _NOSPLIT_TAG_MAP[parent.name] || !toBlock && parent.isBlock()) {
  2583. break;
  2584. }
  2585. knode = parent;
  2586. }
  2587. if(isStart) {
  2588. self.setStartBefore(knode[0]);
  2589. } else {
  2590. self.setEndBefore(knode[0]);
  2591. }
  2592. } else if(pos == knode.children().length) {
  2593. while(!knode.next()) {
  2594. parent = knode.parent();
  2595. if(!parent || _NOSPLIT_TAG_MAP[parent.name] || !toBlock && parent.isBlock()) {
  2596. break;
  2597. }
  2598. knode = parent;
  2599. }
  2600. if(isStart) {
  2601. self.setStartAfter(knode[0]);
  2602. } else {
  2603. self.setEndAfter(knode[0]);
  2604. }
  2605. }
  2606. }
  2607. enlargePos(self.startContainer, self.startOffset, true);
  2608. enlargePos(self.endContainer, self.endOffset, false);
  2609. return self;
  2610. },
  2611. shrink: function() {
  2612. var self = this,
  2613. child, collapsed = self.collapsed;
  2614. while(self.startContainer.nodeType == 1 && (child = self.startContainer.childNodes[self.startOffset]) && child.nodeType == 1 && !K(child).isSingle()) {
  2615. self.setStart(child, 0);
  2616. }
  2617. if(collapsed) {
  2618. return self.collapse(collapsed);
  2619. }
  2620. while(self.endContainer.nodeType == 1 && self.endOffset > 0 && (child = self.endContainer.childNodes[self.endOffset - 1]) && child.nodeType == 1 && !K(child).isSingle()) {
  2621. self.setEnd(child, child.childNodes.length);
  2622. }
  2623. return self;
  2624. },
  2625. createBookmark: function(serialize) {
  2626. var self = this,
  2627. doc = self.doc,
  2628. endNode,
  2629. startNode = K('<span style="display:none;"></span>', doc)[0];
  2630. startNode.id = '__kindeditor_bookmark_start_' + (_BOOKMARK_ID++) + '__';
  2631. if(!self.collapsed) {
  2632. endNode = startNode.cloneNode(true);
  2633. endNode.id = '__kindeditor_bookmark_end_' + (_BOOKMARK_ID++) + '__';
  2634. }
  2635. if(endNode) {
  2636. self.cloneRange().collapse(false).insertNode(endNode).setEndBefore(endNode);
  2637. }
  2638. self.insertNode(startNode).setStartAfter(startNode);
  2639. return {
  2640. start: serialize ? '#' + startNode.id : startNode,
  2641. end: endNode ? (serialize ? '#' + endNode.id : endNode) : null
  2642. };
  2643. },
  2644. moveToBookmark: function(bookmark) {
  2645. var self = this,
  2646. doc = self.doc,
  2647. start = K(bookmark.start, doc),
  2648. end = bookmark.end ? K(bookmark.end, doc) : null;
  2649. if(!start || start.length < 1) {
  2650. return self;
  2651. }
  2652. self.setStartBefore(start[0]);
  2653. start.remove();
  2654. if(end && end.length > 0) {
  2655. self.setEndBefore(end[0]);
  2656. end.remove();
  2657. } else {
  2658. self.collapse(true);
  2659. }
  2660. return self;
  2661. },
  2662. dump: function() {
  2663. console.log('--------------------');
  2664. console.log(this.startContainer.nodeType == 3 ? this.startContainer.nodeValue : this.startContainer, this.startOffset);
  2665. console.log(this.endContainer.nodeType == 3 ? this.endContainer.nodeValue : this.endContainer, this.endOffset);
  2666. }
  2667. });
  2668. function _range(mixed) {
  2669. if(!mixed.nodeName) {
  2670. return mixed.constructor === KRange ? mixed : _toRange(mixed);
  2671. }
  2672. return new KRange(mixed);
  2673. }
  2674. K.RangeClass = KRange;
  2675. K.range = _range;
  2676. K.START_TO_START = _START_TO_START;
  2677. K.START_TO_END = _START_TO_END;
  2678. K.END_TO_END = _END_TO_END;
  2679. K.END_TO_START = _END_TO_START;
  2680. function _nativeCommand(doc, key, val) {
  2681. try {
  2682. doc.execCommand(key, false, val);
  2683. } catch(e) {}
  2684. }
  2685. function _nativeCommandValue(doc, key) {
  2686. var val = '';
  2687. try {
  2688. val = doc.queryCommandValue(key);
  2689. } catch(e) {}
  2690. if(typeof val !== 'string') {
  2691. val = '';
  2692. }
  2693. return val;
  2694. }
  2695. function _getSel(doc) {
  2696. var win = _getWin(doc);
  2697. return _IERANGE ? doc.selection : win.getSelection();
  2698. }
  2699. function _getRng(doc) {
  2700. var sel = _getSel(doc),
  2701. rng;
  2702. try {
  2703. if(sel.rangeCount > 0) {
  2704. rng = sel.getRangeAt(0);
  2705. } else {
  2706. rng = sel.createRange();
  2707. }
  2708. } catch(e) {}
  2709. if(_IERANGE && (!rng || (!rng.item && rng.parentElement().ownerDocument !== doc))) {
  2710. return null;
  2711. }
  2712. return rng;
  2713. }
  2714. function _singleKeyMap(map) {
  2715. var newMap = {},
  2716. arr, v;
  2717. _each(map, function(key, val) {
  2718. arr = key.split(',');
  2719. for(var i = 0, len = arr.length; i < len; i++) {
  2720. v = arr[i];
  2721. newMap[v] = val;
  2722. }
  2723. });
  2724. return newMap;
  2725. }
  2726. function _hasAttrOrCss(knode, map) {
  2727. return _hasAttrOrCssByKey(knode, map, '*') || _hasAttrOrCssByKey(knode, map);
  2728. }
  2729. function _hasAttrOrCssByKey(knode, map, mapKey) {
  2730. mapKey = mapKey || knode.name;
  2731. if(knode.type !== 1) {
  2732. return false;
  2733. }
  2734. var newMap = _singleKeyMap(map);
  2735. if(!newMap[mapKey]) {
  2736. return false;
  2737. }
  2738. var arr = newMap[mapKey].split(',');
  2739. for(var i = 0, len = arr.length; i < len; i++) {
  2740. var key = arr[i];
  2741. if(key === '*') {
  2742. return true;
  2743. }
  2744. var match = /^(\.?)([^=]+)(?:=([^=]*))?$/.exec(key);
  2745. var method = match[1] ? 'css' : 'attr';
  2746. key = match[2];
  2747. var val = match[3] || '';
  2748. if(val === '' && knode[method](key) !== '') {
  2749. return true;
  2750. }
  2751. if(val !== '' && knode[method](key) === val) {
  2752. return true;
  2753. }
  2754. }
  2755. return false;
  2756. }
  2757. function _removeAttrOrCss(knode, map) {
  2758. if(knode.type != 1) {
  2759. return;
  2760. }
  2761. _removeAttrOrCssByKey(knode, map, '*');
  2762. _removeAttrOrCssByKey(knode, map);
  2763. }
  2764. function _removeAttrOrCssByKey(knode, map, mapKey) {
  2765. mapKey = mapKey || knode.name;
  2766. if(knode.type !== 1) {
  2767. return;
  2768. }
  2769. var newMap = _singleKeyMap(map);
  2770. if(!newMap[mapKey]) {
  2771. return;
  2772. }
  2773. var arr = newMap[mapKey].split(','),
  2774. allFlag = false;
  2775. for(var i = 0, len = arr.length; i < len; i++) {
  2776. var key = arr[i];
  2777. if(key === '*') {
  2778. allFlag = true;
  2779. break;
  2780. }
  2781. var match = /^(\.?)([^=]+)(?:=([^=]*))?$/.exec(key);
  2782. key = match[2];
  2783. if(match[1]) {
  2784. key = _toCamel(key);
  2785. if(knode[0].style[key]) {
  2786. knode[0].style[key] = '';
  2787. }
  2788. } else {
  2789. knode.removeAttr(key);
  2790. }
  2791. }
  2792. if(allFlag) {
  2793. knode.remove(true);
  2794. }
  2795. }
  2796. function _getInnerNode(knode) {
  2797. var inner = knode;
  2798. while(inner.first()) {
  2799. inner = inner.first();
  2800. }
  2801. return inner;
  2802. }
  2803. function _isEmptyNode(knode) {
  2804. if(knode.type != 1 || knode.isSingle()) {
  2805. return false;
  2806. }
  2807. return knode.html().replace(/<[^>]+>/g, '') === '';
  2808. }
  2809. function _mergeWrapper(a, b) {
  2810. a = a.clone(true);
  2811. var lastA = _getInnerNode(a),
  2812. childA = a,
  2813. merged = false;
  2814. while(b) {
  2815. while(childA) {
  2816. if(childA.name === b.name) {
  2817. _mergeAttrs(childA, b.attr(), b.css());
  2818. merged = true;
  2819. }
  2820. childA = childA.first();
  2821. }
  2822. if(!merged) {
  2823. lastA.append(b.clone(false));
  2824. }
  2825. merged = false;
  2826. b = b.first();
  2827. }
  2828. return a;
  2829. }
  2830. function _wrapNode(knode, wrapper) {
  2831. wrapper = wrapper.clone(true);
  2832. if(knode.type == 3) {
  2833. _getInnerNode(wrapper).append(knode.clone(false));
  2834. knode.replaceWith(wrapper);
  2835. return wrapper;
  2836. }
  2837. var nodeWrapper = knode,
  2838. child;
  2839. while((child = knode.first()) && child.children().length == 1) {
  2840. knode = child;
  2841. }
  2842. child = knode.first();
  2843. var frag = knode.doc.createDocumentFragment();
  2844. while(child) {
  2845. frag.appendChild(child[0]);
  2846. child = child.next();
  2847. }
  2848. wrapper = _mergeWrapper(nodeWrapper, wrapper);
  2849. if(frag.firstChild) {
  2850. _getInnerNode(wrapper).append(frag);
  2851. }
  2852. nodeWrapper.replaceWith(wrapper);
  2853. return wrapper;
  2854. }
  2855. function _mergeAttrs(knode, attrs, styles) {
  2856. _each(attrs, function(key, val) {
  2857. if(key !== 'style') {
  2858. knode.attr(key, val);
  2859. }
  2860. });
  2861. _each(styles, function(key, val) {
  2862. knode.css(key, val);
  2863. });
  2864. }
  2865. function _inPreElement(knode) {
  2866. while(knode && knode.name != 'body') {
  2867. if(_PRE_TAG_MAP[knode.name] || knode.name == 'div' && knode.hasClass('ke-script')) {
  2868. return true;
  2869. }
  2870. knode = knode.parent();
  2871. }
  2872. return false;
  2873. }
  2874. function KCmd(range) {
  2875. this.init(range);
  2876. }
  2877. _extend(KCmd, {
  2878. init: function(range) {
  2879. var self = this,
  2880. doc = range.doc;
  2881. self.doc = doc;
  2882. self.win = _getWin(doc);
  2883. self.sel = _getSel(doc);
  2884. self.range = range;
  2885. },
  2886. selection: function(forceReset) {
  2887. var self = this,
  2888. doc = self.doc,
  2889. rng = _getRng(doc);
  2890. self.sel = _getSel(doc);
  2891. if(rng) {
  2892. self.range = _range(rng);
  2893. if(K(self.range.startContainer).name == 'html') {
  2894. self.range.selectNodeContents(doc.body).collapse(false);
  2895. }
  2896. return self;
  2897. }
  2898. if(forceReset) {
  2899. self.range.selectNodeContents(doc.body).collapse(false);
  2900. }
  2901. return self;
  2902. },
  2903. select: function(hasDummy) {
  2904. hasDummy = _undef(hasDummy, true);
  2905. var self = this,
  2906. sel = self.sel,
  2907. range = self.range.cloneRange().shrink(),
  2908. sc = range.startContainer,
  2909. so = range.startOffset,
  2910. ec = range.endContainer,
  2911. eo = range.endOffset,
  2912. doc = _getDoc(sc),
  2913. win = self.win,
  2914. rng, hasU200b = false;
  2915. if(hasDummy && sc.nodeType == 1 && range.collapsed) {
  2916. if(_IERANGE) {
  2917. var dummy = K('<span>&nbsp;</span>', doc);
  2918. range.insertNode(dummy[0]);
  2919. rng = doc.body.createTextRange();
  2920. try {
  2921. rng.moveToElementText(dummy[0]);
  2922. } catch(ex) {}
  2923. rng.collapse(false);
  2924. rng.select();
  2925. dummy.remove();
  2926. win.focus();
  2927. return self;
  2928. }
  2929. if(_WEBKIT) {
  2930. var children = sc.childNodes;
  2931. if(K(sc).isInline() || so > 0 && K(children[so - 1]).isInline() || children[so] && K(children[so]).isInline()) {
  2932. range.insertNode(doc.createTextNode('\u200B'));
  2933. hasU200b = true;
  2934. }
  2935. }
  2936. }
  2937. if(_IERANGE) {
  2938. try {
  2939. rng = range.get(true);
  2940. rng.select();
  2941. } catch(e) {}
  2942. } else {
  2943. if(hasU200b) {
  2944. range.collapse(false);
  2945. }
  2946. rng = range.get(true);
  2947. sel.removeAllRanges();
  2948. sel.addRange(rng);
  2949. if(doc !== document) {
  2950. var pos = K(rng.endContainer).pos();
  2951. win.scrollTo(pos.x, pos.y);
  2952. }
  2953. }
  2954. win.focus();
  2955. return self;
  2956. },
  2957. wrap: function(val) {
  2958. var self = this,
  2959. doc = self.doc,
  2960. range = self.range,
  2961. wrapper;
  2962. wrapper = K(val, doc);
  2963. if(range.collapsed) {
  2964. range.shrink();
  2965. range.insertNode(wrapper[0]).selectNodeContents(wrapper[0]);
  2966. return self;
  2967. }
  2968. if(wrapper.isBlock()) {
  2969. var copyWrapper = wrapper.clone(true),
  2970. child = copyWrapper;
  2971. while(child.first()) {
  2972. child = child.first();
  2973. }
  2974. child.append(range.extractContents());
  2975. range.insertNode(copyWrapper[0]).selectNode(copyWrapper[0]);
  2976. return self;
  2977. }
  2978. range.enlarge();
  2979. var bookmark = range.createBookmark(),
  2980. ancestor = range.commonAncestor(),
  2981. isStart = false;
  2982. K(ancestor).scan(function(node) {
  2983. if(!isStart && node == bookmark.start) {
  2984. isStart = true;
  2985. return;
  2986. }
  2987. if(isStart) {
  2988. if(node == bookmark.end) {
  2989. return false;
  2990. }
  2991. var knode = K(node);
  2992. if(_inPreElement(knode)) {
  2993. return;
  2994. }
  2995. if(knode.type == 3 && _trim(node.nodeValue).length > 0) {
  2996. var parent;
  2997. while((parent = knode.parent()) && parent.isStyle() && parent.children().length == 1) {
  2998. knode = parent;
  2999. }
  3000. _wrapNode(knode, wrapper);
  3001. }
  3002. }
  3003. });
  3004. range.moveToBookmark(bookmark);
  3005. return self;
  3006. },
  3007. split: function(isStart, map) {
  3008. var range = this.range,
  3009. doc = range.doc;
  3010. var tempRange = range.cloneRange().collapse(isStart);
  3011. var node = tempRange.startContainer,
  3012. pos = tempRange.startOffset,
  3013. parent = node.nodeType == 3 ? node.parentNode : node,
  3014. needSplit = false,
  3015. knode;
  3016. while(parent && parent.parentNode) {
  3017. knode = K(parent);
  3018. if(map) {
  3019. if(!knode.isStyle()) {
  3020. break;
  3021. }
  3022. if(!_hasAttrOrCss(knode, map)) {
  3023. break;
  3024. }
  3025. } else {
  3026. if(_NOSPLIT_TAG_MAP[knode.name]) {
  3027. break;
  3028. }
  3029. }
  3030. needSplit = true;
  3031. parent = parent.parentNode;
  3032. }
  3033. if(needSplit) {
  3034. var dummy = doc.createElement('span');
  3035. range.cloneRange().collapse(!isStart).insertNode(dummy);
  3036. if(isStart) {
  3037. tempRange.setStartBefore(parent.firstChild).setEnd(node, pos);
  3038. } else {
  3039. tempRange.setStart(node, pos).setEndAfter(parent.lastChild);
  3040. }
  3041. var frag = tempRange.extractContents(),
  3042. first = frag.firstChild,
  3043. last = frag.lastChild;
  3044. if(isStart) {
  3045. tempRange.insertNode(frag);
  3046. range.setStartAfter(last).setEndBefore(dummy);
  3047. } else {
  3048. parent.appendChild(frag);
  3049. range.setStartBefore(dummy).setEndBefore(first);
  3050. }
  3051. var dummyParent = dummy.parentNode;
  3052. if(dummyParent == range.endContainer) {
  3053. var prev = K(dummy).prev(),
  3054. next = K(dummy).next();
  3055. if(prev && next && prev.type == 3 && next.type == 3) {
  3056. range.setEnd(prev[0], prev[0].nodeValue.length);
  3057. } else if(!isStart) {
  3058. range.setEnd(range.endContainer, range.endOffset - 1);
  3059. }
  3060. }
  3061. dummyParent.removeChild(dummy);
  3062. }
  3063. return this;
  3064. },
  3065. remove: function(map) {
  3066. var self = this,
  3067. doc = self.doc,
  3068. range = self.range;
  3069. range.enlarge();
  3070. if(range.startOffset === 0) {
  3071. var ksc = K(range.startContainer),
  3072. parent;
  3073. while((parent = ksc.parent()) && parent.isStyle() && parent.children().length == 1) {
  3074. ksc = parent;
  3075. }
  3076. range.setStart(ksc[0], 0);
  3077. ksc = K(range.startContainer);
  3078. if(ksc.isBlock()) {
  3079. _removeAttrOrCss(ksc, map);
  3080. }
  3081. var kscp = ksc.parent();
  3082. if(kscp && kscp.isBlock()) {
  3083. _removeAttrOrCss(kscp, map);
  3084. }
  3085. }
  3086. var sc, so;
  3087. if(range.collapsed) {
  3088. self.split(true, map);
  3089. sc = range.startContainer;
  3090. so = range.startOffset;
  3091. if(so > 0) {
  3092. var sb = K(sc.childNodes[so - 1]);
  3093. if(sb && _isEmptyNode(sb)) {
  3094. sb.remove();
  3095. range.setStart(sc, so - 1);
  3096. }
  3097. }
  3098. var sa = K(sc.childNodes[so]);
  3099. if(sa && _isEmptyNode(sa)) {
  3100. sa.remove();
  3101. }
  3102. if(_isEmptyNode(sc)) {
  3103. range.startBefore(sc);
  3104. sc.remove();
  3105. }
  3106. range.collapse(true);
  3107. return self;
  3108. }
  3109. self.split(true, map);
  3110. self.split(false, map);
  3111. var startDummy = doc.createElement('span'),
  3112. endDummy = doc.createElement('span');
  3113. range.cloneRange().collapse(false).insertNode(endDummy);
  3114. range.cloneRange().collapse(true).insertNode(startDummy);
  3115. var nodeList = [],
  3116. cmpStart = false;
  3117. K(range.commonAncestor()).scan(function(node) {
  3118. if(!cmpStart && node == startDummy) {
  3119. cmpStart = true;
  3120. return;
  3121. }
  3122. if(node == endDummy) {
  3123. return false;
  3124. }
  3125. if(cmpStart) {
  3126. nodeList.push(node);
  3127. }
  3128. });
  3129. K(startDummy).remove();
  3130. K(endDummy).remove();
  3131. sc = range.startContainer;
  3132. so = range.startOffset;
  3133. var ec = range.endContainer,
  3134. eo = range.endOffset;
  3135. if(so > 0) {
  3136. var startBefore = K(sc.childNodes[so - 1]);
  3137. if(startBefore && _isEmptyNode(startBefore)) {
  3138. startBefore.remove();
  3139. range.setStart(sc, so - 1);
  3140. if(sc == ec) {
  3141. range.setEnd(ec, eo - 1);
  3142. }
  3143. }
  3144. var startAfter = K(sc.childNodes[so]);
  3145. if(startAfter && _isEmptyNode(startAfter)) {
  3146. startAfter.remove();
  3147. if(sc == ec) {
  3148. range.setEnd(ec, eo - 1);
  3149. }
  3150. }
  3151. }
  3152. var endAfter = K(ec.childNodes[range.endOffset]);
  3153. if(endAfter && _isEmptyNode(endAfter)) {
  3154. endAfter.remove();
  3155. }
  3156. var bookmark = range.createBookmark(true);
  3157. _each(nodeList, function(i, node) {
  3158. _removeAttrOrCss(K(node), map);
  3159. });
  3160. range.moveToBookmark(bookmark);
  3161. return self;
  3162. },
  3163. commonNode: function(map) {
  3164. var range = this.range;
  3165. var ec = range.endContainer,
  3166. eo = range.endOffset,
  3167. node = (ec.nodeType == 3 || eo === 0) ? ec : ec.childNodes[eo - 1];
  3168. function find(node) {
  3169. var child = node,
  3170. parent = node;
  3171. while(parent) {
  3172. if(_hasAttrOrCss(K(parent), map)) {
  3173. return K(parent);
  3174. }
  3175. parent = parent.parentNode;
  3176. }
  3177. while(child && (child = child.lastChild)) {
  3178. if(_hasAttrOrCss(K(child), map)) {
  3179. return K(child);
  3180. }
  3181. }
  3182. return null;
  3183. }
  3184. var cNode = find(node);
  3185. if(cNode) {
  3186. return cNode;
  3187. }
  3188. if(node.nodeType == 1 || (ec.nodeType == 3 && eo === 0)) {
  3189. var prev = K(node).prev();
  3190. if(prev) {
  3191. return find(prev);
  3192. }
  3193. }
  3194. return null;
  3195. },
  3196. commonAncestor: function(tagName) {
  3197. var range = this.range,
  3198. sc = range.startContainer,
  3199. so = range.startOffset,
  3200. ec = range.endContainer,
  3201. eo = range.endOffset,
  3202. startNode = (sc.nodeType == 3 || so === 0) ? sc : sc.childNodes[so - 1],
  3203. endNode = (ec.nodeType == 3 || eo === 0) ? ec : ec.childNodes[eo - 1];
  3204. function find(node) {
  3205. while(node) {
  3206. if(node.nodeType == 1) {
  3207. if(node.tagName.toLowerCase() === tagName) {
  3208. return node;
  3209. }
  3210. }
  3211. node = node.parentNode;
  3212. }
  3213. return null;
  3214. }
  3215. var start = find(startNode),
  3216. end = find(endNode);
  3217. if(start && end && start === end) {
  3218. return K(start);
  3219. }
  3220. return null;
  3221. },
  3222. state: function(key) {
  3223. var self = this,
  3224. doc = self.doc,
  3225. bool = false;
  3226. try {
  3227. bool = doc.queryCommandState(key);
  3228. } catch(e) {}
  3229. return bool;
  3230. },
  3231. val: function(key) {
  3232. var self = this,
  3233. doc = self.doc,
  3234. range = self.range;
  3235. function lc(val) {
  3236. return val.toLowerCase();
  3237. }
  3238. key = lc(key);
  3239. var val = '',
  3240. knode;
  3241. if(key === 'fontfamily' || key === 'fontname') {
  3242. val = _nativeCommandValue(doc, 'fontname');
  3243. val = val.replace(/['"]/g, '');
  3244. return lc(val);
  3245. }
  3246. if(key === 'formatblock') {
  3247. val = _nativeCommandValue(doc, key);
  3248. if(val === '') {
  3249. knode = self.commonNode({
  3250. 'h1,h2,h3,h4,h5,h6,p,div,pre,address': '*'
  3251. });
  3252. if(knode) {
  3253. val = knode.name;
  3254. }
  3255. }
  3256. if(val === 'Normal') {
  3257. val = 'p';
  3258. }
  3259. return lc(val);
  3260. }
  3261. if(key === 'fontsize') {
  3262. knode = self.commonNode({
  3263. '*': '.font-size'
  3264. });
  3265. if(knode) {
  3266. val = knode.css('font-size');
  3267. }
  3268. return lc(val);
  3269. }
  3270. if(key === 'forecolor') {
  3271. knode = self.commonNode({
  3272. '*': '.color'
  3273. });
  3274. if(knode) {
  3275. val = knode.css('color');
  3276. }
  3277. val = _toHex(val);
  3278. if(val === '') {
  3279. val = 'default';
  3280. }
  3281. return lc(val);
  3282. }
  3283. if(key === 'hilitecolor') {
  3284. knode = self.commonNode({
  3285. '*': '.background-color'
  3286. });
  3287. if(knode) {
  3288. val = knode.css('background-color');
  3289. }
  3290. val = _toHex(val);
  3291. if(val === '') {
  3292. val = 'default';
  3293. }
  3294. return lc(val);
  3295. }
  3296. return val;
  3297. },
  3298. toggle: function(wrapper, map) {
  3299. var self = this;
  3300. if(self.commonNode(map)) {
  3301. self.remove(map);
  3302. } else {
  3303. self.wrap(wrapper);
  3304. }
  3305. return self.select();
  3306. },
  3307. bold: function() {
  3308. return this.toggle('<strong></strong>', {
  3309. span: '.font-weight=bold',
  3310. strong: '*',
  3311. b: '*'
  3312. });
  3313. },
  3314. italic: function() {
  3315. return this.toggle('<em></em>', {
  3316. span: '.font-style=italic',
  3317. em: '*',
  3318. i: '*'
  3319. });
  3320. },
  3321. underline: function() {
  3322. return this.toggle('<u></u>', {
  3323. span: '.text-decoration=underline',
  3324. u: '*'
  3325. });
  3326. },
  3327. strikethrough: function() {
  3328. return this.toggle('<s></s>', {
  3329. span: '.text-decoration=line-through',
  3330. s: '*'
  3331. });
  3332. },
  3333. forecolor: function(val) {
  3334. return this.toggle('<span style="color:' + val + ';"></span>', {
  3335. span: '.color=' + val,
  3336. font: 'color'
  3337. });
  3338. },
  3339. hilitecolor: function(val) {
  3340. return this.toggle('<span style="background-color:' + val + ';"></span>', {
  3341. span: '.background-color=' + val
  3342. });
  3343. },
  3344. fontsize: function(val) {
  3345. return this.toggle('<span style="font-size:' + val + ';"></span>', {
  3346. span: '.font-size=' + val,
  3347. font: 'size'
  3348. });
  3349. },
  3350. fontname: function(val) {
  3351. return this.fontfamily(val);
  3352. },
  3353. fontfamily: function(val) {
  3354. return this.toggle('<span style="font-family:' + val + ';"></span>', {
  3355. span: '.font-family=' + val,
  3356. font: 'face'
  3357. });
  3358. },
  3359. removeformat: function() {
  3360. var map = {
  3361. '*': '.font-weight,.font-style,.text-decoration,.color,.background-color,.font-size,.font-family,.text-indent'
  3362. },
  3363. tags = _STYLE_TAG_MAP;
  3364. _each(tags, function(key, val) {
  3365. map[key] = '*';
  3366. });
  3367. this.remove(map);
  3368. return this.select();
  3369. },
  3370. inserthtml: function(val, quickMode) {
  3371. var self = this,
  3372. range = self.range;
  3373. if(val === '') {
  3374. return self;
  3375. }
  3376. function pasteHtml(range, val) {
  3377. val = '<img id="__kindeditor_temp_tag__" width="0" height="0" style="display:none;" />' + val;
  3378. var rng = range.get();
  3379. if(rng.item) {
  3380. rng.item(0).outerHTML = val;
  3381. } else {
  3382. rng.pasteHTML(val);
  3383. }
  3384. var temp = range.doc.getElementById('__kindeditor_temp_tag__');
  3385. temp.parentNode.removeChild(temp);
  3386. var newRange = _toRange(rng);
  3387. range.setEnd(newRange.endContainer, newRange.endOffset);
  3388. range.collapse(false);
  3389. self.select(false);
  3390. }
  3391. function insertHtml(range, val) {
  3392. var doc = range.doc,
  3393. frag = doc.createDocumentFragment();
  3394. K('@' + val, doc).each(function() {
  3395. frag.appendChild(this);
  3396. });
  3397. range.deleteContents();
  3398. range.insertNode(frag);
  3399. range.collapse(false);
  3400. self.select(false);
  3401. }
  3402. if(_IERANGE && quickMode) {
  3403. try {
  3404. pasteHtml(range, val);
  3405. } catch(e) {
  3406. insertHtml(range, val);
  3407. }
  3408. return self;
  3409. }
  3410. insertHtml(range, val);
  3411. return self;
  3412. },
  3413. hr: function() {
  3414. return this.inserthtml('<hr />');
  3415. },
  3416. print: function() {
  3417. this.win.print();
  3418. return this;
  3419. },
  3420. insertimage: function(url, title, width, height, border, align) {
  3421. title = _undef(title, '');
  3422. border = _undef(border, 0);
  3423. var html = '<img src="' + _escape(url) + '" data-ke-src="' + _escape(url) + '" ';
  3424. if(width) {
  3425. html += 'width="' + _escape(width) + '" ';
  3426. }
  3427. if(height) {
  3428. html += 'height="' + _escape(height) + '" ';
  3429. }
  3430. if(title) {
  3431. html += 'title="' + _escape(title) + '" ';
  3432. }
  3433. if(align) {
  3434. html += 'align="' + _escape(align) + '" ';
  3435. }
  3436. html += 'alt="' + _escape(title) + '" ';
  3437. html += '/>';
  3438. return this.inserthtml(html);
  3439. },
  3440. createlink: function(url, type) {
  3441. var self = this,
  3442. doc = self.doc,
  3443. range = self.range;
  3444. self.select();
  3445. var a = self.commonNode({
  3446. a: '*'
  3447. });
  3448. if(a && !range.isControl()) {
  3449. range.selectNode(a.get());
  3450. self.select();
  3451. }
  3452. var html = '<a href="' + _escape(url) + '" data-ke-src="' + _escape(url) + '" ';
  3453. if(type) {
  3454. html += ' target="' + _escape(type) + '"';
  3455. }
  3456. if(range.collapsed) {
  3457. html += '>' + _escape(url) + '</a>';
  3458. return self.inserthtml(html);
  3459. }
  3460. if(range.isControl()) {
  3461. var node = K(range.startContainer.childNodes[range.startOffset]);
  3462. html += '></a>';
  3463. node.after(K(html, doc));
  3464. node.next().append(node);
  3465. range.selectNode(node[0]);
  3466. return self.select();
  3467. }
  3468. function setAttr(node, url, type) {
  3469. K(node).attr('href', url).attr('data-ke-src', url);
  3470. if(type) {
  3471. K(node).attr('target', type);
  3472. } else {
  3473. K(node).removeAttr('target');
  3474. }
  3475. }
  3476. var sc = range.startContainer,
  3477. so = range.startOffset,
  3478. ec = range.endContainer,
  3479. eo = range.endOffset;
  3480. if(sc.nodeType == 1 && sc === ec && so + 1 === eo) {
  3481. var child = sc.childNodes[so];
  3482. if(child.nodeName.toLowerCase() == 'a') {
  3483. setAttr(child, url, type);
  3484. return self;
  3485. }
  3486. }
  3487. _nativeCommand(doc, 'createlink', '__kindeditor_temp_url__');
  3488. K('a[href="__kindeditor_temp_url__"]', doc).each(function() {
  3489. setAttr(this, url, type);
  3490. });
  3491. return self;
  3492. },
  3493. unlink: function() {
  3494. var self = this,
  3495. doc = self.doc,
  3496. range = self.range;
  3497. self.select();
  3498. if(range.collapsed) {
  3499. var a = self.commonNode({
  3500. a: '*'
  3501. });
  3502. if(a) {
  3503. range.selectNode(a.get());
  3504. self.select();
  3505. }
  3506. _nativeCommand(doc, 'unlink', null);
  3507. if(_WEBKIT && K(range.startContainer).name === 'img') {
  3508. var parent = K(range.startContainer).parent();
  3509. if(parent.name === 'a') {
  3510. parent.remove(true);
  3511. }
  3512. }
  3513. } else {
  3514. _nativeCommand(doc, 'unlink', null);
  3515. }
  3516. return self;
  3517. }
  3518. });
  3519. _each(('formatblock,selectall,justifyleft,justifycenter,justifyright,justifyfull,insertorderedlist,' +
  3520. 'insertunorderedlist,indent,outdent,subscript,superscript').split(','), function(i, name) {
  3521. KCmd.prototype[name] = function(val) {
  3522. var self = this;
  3523. self.select();
  3524. _nativeCommand(self.doc, name, val);
  3525. if(_IERANGE && _inArray(name, 'justifyleft,justifycenter,justifyright,justifyfull'.split(',')) >= 0) {
  3526. self.selection();
  3527. }
  3528. if(!_IERANGE || _inArray(name, 'formatblock,selectall,insertorderedlist,insertunorderedlist'.split(',')) >= 0) {
  3529. self.selection();
  3530. }
  3531. return self;
  3532. };
  3533. });
  3534. _each('cut,copy,paste'.split(','), function(i, name) {
  3535. KCmd.prototype[name] = function() {
  3536. var self = this;
  3537. if(!self.doc.queryCommandSupported(name)) {
  3538. throw 'not supported';
  3539. }
  3540. self.select();
  3541. _nativeCommand(self.doc, name, null);
  3542. return self;
  3543. };
  3544. });
  3545. function _cmd(mixed) {
  3546. if(mixed.nodeName) {
  3547. var doc = _getDoc(mixed);
  3548. mixed = _range(doc).selectNodeContents(doc.body).collapse(false);
  3549. }
  3550. return new KCmd(mixed);
  3551. }
  3552. K.CmdClass = KCmd;
  3553. K.cmd = _cmd;
  3554. function _drag(options) {
  3555. var moveEl = options.moveEl,
  3556. moveFn = options.moveFn,
  3557. clickEl = options.clickEl || moveEl,
  3558. beforeDrag = options.beforeDrag,
  3559. iframeFix = options.iframeFix === undefined ? true : options.iframeFix;
  3560. var docs = [document];
  3561. if(iframeFix) {
  3562. K('iframe').each(function() {
  3563. var src = _formatUrl(this.src || '', 'absolute');
  3564. if(/^https?:\/\//.test(src)) {
  3565. return;
  3566. }
  3567. var doc;
  3568. try {
  3569. doc = _iframeDoc(this);
  3570. } catch(e) {}
  3571. if(doc) {
  3572. var pos = K(this).pos();
  3573. K(doc).data('pos-x', pos.x);
  3574. K(doc).data('pos-y', pos.y);
  3575. docs.push(doc);
  3576. }
  3577. });
  3578. }
  3579. clickEl.mousedown(function(e) {
  3580. e.stopPropagation();
  3581. var self = clickEl.get(),
  3582. x = _removeUnit(moveEl.css('left')),
  3583. y = _removeUnit(moveEl.css('top')),
  3584. width = moveEl.width(),
  3585. height = moveEl.height(),
  3586. pageX = e.pageX,
  3587. pageY = e.pageY;
  3588. K(self).addClass('ke-dragging');
  3589. if(beforeDrag) {
  3590. beforeDrag();
  3591. }
  3592. function moveListener(e) {
  3593. e.preventDefault();
  3594. var kdoc = K(_getDoc(e.target));
  3595. var diffX = _round((kdoc.data('pos-x') || 0) + e.pageX - pageX);
  3596. var diffY = _round((kdoc.data('pos-y') || 0) + e.pageY - pageY);
  3597. moveFn.call(clickEl, x, y, width, height, diffX, diffY);
  3598. }
  3599. function selectListener(e) {
  3600. e.preventDefault();
  3601. }
  3602. function upListener(e) {
  3603. e.preventDefault();
  3604. K(docs).unbind('mousemove', moveListener)
  3605. .unbind('mouseup', upListener)
  3606. .unbind('selectstart', selectListener);
  3607. if(self.releaseCapture) {
  3608. self.releaseCapture();
  3609. }
  3610. K(self).removeClass('ke-dragging');
  3611. }
  3612. K(docs).mousemove(moveListener)
  3613. .mouseup(upListener)
  3614. .bind('selectstart', selectListener);
  3615. if(self.setCapture) {
  3616. self.setCapture();
  3617. }
  3618. });
  3619. }
  3620. function KWidget(options) {
  3621. this.init(options);
  3622. }
  3623. _extend(KWidget, {
  3624. init: function(options) {
  3625. var self = this;
  3626. self.name = options.name || '';
  3627. self.doc = options.doc || document;
  3628. self.win = _getWin(self.doc);
  3629. self.x = _addUnit(options.x);
  3630. self.y = _addUnit(options.y);
  3631. self.z = options.z;
  3632. self.width = _addUnit(options.width);
  3633. self.height = _addUnit(options.height);
  3634. self.div = K('<div style="display:block;"></div>');
  3635. self.options = options;
  3636. self._alignEl = options.alignEl;
  3637. if(self.width) {
  3638. self.div.css('width', self.width);
  3639. }
  3640. if(self.height) {
  3641. self.div.css('height', self.height);
  3642. }
  3643. if(self.z) {
  3644. self.div.css({
  3645. position: 'absolute',
  3646. left: self.x,
  3647. top: self.y,
  3648. 'z-index': self.z
  3649. });
  3650. }
  3651. if(self.z && (self.x === undefined || self.y === undefined)) {
  3652. self.autoPos(self.width, self.height);
  3653. }
  3654. if(options.cls) {
  3655. self.div.addClass(options.cls);
  3656. }
  3657. if(options.shadowMode) {
  3658. self.div.addClass('ke-shadow');
  3659. }
  3660. if(options.css) {
  3661. self.div.css(options.css);
  3662. }
  3663. if(options.src) {
  3664. K(options.src).replaceWith(self.div);
  3665. } else {
  3666. K(self.doc.body).append(self.div);
  3667. }
  3668. if(options.html) {
  3669. self.div.html(options.html);
  3670. }
  3671. if(options.autoScroll) {
  3672. if(_IE && _V < 7 || _QUIRKS) {
  3673. var scrollPos = _getScrollPos();
  3674. K(self.win).bind('scroll', function(e) {
  3675. var pos = _getScrollPos(),
  3676. diffX = pos.x - scrollPos.x,
  3677. diffY = pos.y - scrollPos.y;
  3678. self.pos(_removeUnit(self.x) + diffX, _removeUnit(self.y) + diffY, false);
  3679. });
  3680. } else {
  3681. self.div.css('position', 'fixed');
  3682. }
  3683. }
  3684. },
  3685. pos: function(x, y, updateProp) {
  3686. var self = this;
  3687. updateProp = _undef(updateProp, true);
  3688. if(x !== null) {
  3689. x = x < 0 ? 0 : _addUnit(Math.floor(x));
  3690. self.div.css('left', x);
  3691. if(updateProp) {
  3692. self.x = x;
  3693. }
  3694. }
  3695. if(y !== null) {
  3696. y = y < 0 ? 0 : _addUnit(Math.floor(y));
  3697. self.div.css('top', y);
  3698. if(updateProp) {
  3699. self.y = y;
  3700. }
  3701. }
  3702. return self;
  3703. },
  3704. autoPos: function(width, height) {
  3705. var self = this,
  3706. w = _removeUnit(width) || 0,
  3707. h = _removeUnit(height) || 0,
  3708. scrollPos = _getScrollPos();
  3709. if (self._alignEl) {
  3710. var knode = K(self._alignEl),
  3711. pos = knode.pos(),
  3712. diffX = _round(knode[0].clientWidth / 2 - w / 2),
  3713. diffY = _round(knode[0].clientHeight / 2 - h / 2);
  3714. x = diffX < 0 ? pos.x : pos.x + diffX;
  3715. y = diffY < 0 ? pos.y : pos.y + diffY;
  3716. } else {
  3717. var docEl = _docElement(self.doc);
  3718. x = _round(scrollPos.x + (docEl.clientWidth - w) / 2);
  3719. y = _round(scrollPos.y + (docEl.clientHeight - h) / 2);
  3720. }
  3721. if (!(_IE && _V < 7 || _QUIRKS)) {
  3722. x -= scrollPos.x;
  3723. y -= scrollPos.y;
  3724. }
  3725. return self.pos(x, y);
  3726. },
  3727. remove: function() {
  3728. var self = this;
  3729. if(_IE && _V < 7 || _QUIRKS) {
  3730. K(self.win).unbind('scroll');
  3731. }
  3732. self.div.remove();
  3733. _each(self, function(i) {
  3734. self[i] = null;
  3735. });
  3736. return this;
  3737. },
  3738. show: function() {
  3739. this.div.show();
  3740. return this;
  3741. },
  3742. hide: function() {
  3743. this.div.hide();
  3744. return this;
  3745. },
  3746. draggable: function(options) {
  3747. var self = this;
  3748. options = options || {};
  3749. options.moveEl = self.div;
  3750. options.moveFn = function(x, y, width, height, diffX, diffY) {
  3751. if((x = x + diffX) < 0) {
  3752. x = 0;
  3753. }
  3754. if((y = y + diffY) < 0) {
  3755. y = 0;
  3756. }
  3757. self.pos(x, y);
  3758. };
  3759. _drag(options);
  3760. return self;
  3761. }
  3762. });
  3763. function _widget(options) {
  3764. return new KWidget(options);
  3765. }
  3766. K.WidgetClass = KWidget;
  3767. K.widget = _widget;
  3768. function _iframeDoc(iframe) {
  3769. iframe = _get(iframe);
  3770. return iframe.contentDocument || iframe.contentWindow.document;
  3771. }
  3772. var html, _direction = '';
  3773. if((html = document.getElementsByTagName('html'))) {
  3774. _direction = html[0].dir;
  3775. }
  3776. function _getInitHtml(themesPath, bodyClass, cssPath, cssData) {
  3777. var arr = [
  3778. (_direction === '' ? '<html>' : '<html dir="' + _direction + '">'),
  3779. '<head><meta charset="utf-8" /><title></title>',
  3780. '<style>',
  3781. 'html {margin:0;padding:0;}',
  3782. 'body {margin:0;padding:5px;}',
  3783. 'body, td {font:12px/1.5 "sans serif",tahoma,verdana,helvetica;}',
  3784. 'body, p, div {word-wrap: break-word;}',
  3785. 'p {margin:5px 0;}',
  3786. 'table {border-collapse:collapse;}',
  3787. 'img {border:0;}',
  3788. 'noscript {display:none;}',
  3789. 'table.ke-zeroborder td {border:1px dotted #AAA;}',
  3790. 'img.ke-media, img.ke-audio, img.ke-video {',
  3791. ' border:1px solid #AAA;',
  3792. ' background-image:url(' + themesPath + 'common/media.png);',
  3793. ' background-position:center center;',
  3794. ' background-repeat:no-repeat;',
  3795. ' background-color:#f1f1f1;',
  3796. ' width:100px;',
  3797. ' height:100px;',
  3798. '}',
  3799. 'img.ke-audio {background-image:url(' + themesPath + 'common/audio.png); height: 54px!important}',
  3800. 'img.ke-video {background-image:url(' + themesPath + 'common/video.png)}',
  3801. 'img.ke-anchor {',
  3802. ' border:1px dashed #666;',
  3803. ' width:16px;',
  3804. ' height:16px;',
  3805. '}',
  3806. '.ke-script, .ke-noscript, .ke-display-none {',
  3807. ' display:none;',
  3808. ' font-size:0;',
  3809. ' width:0;',
  3810. ' height:0;',
  3811. '}',
  3812. '.ke-pagebreak {',
  3813. ' border:1px dotted #AAA;',
  3814. ' font-size:0;',
  3815. ' height:2px;',
  3816. '}',
  3817. '</style>'
  3818. ];
  3819. if(!_isArray(cssPath)) {
  3820. cssPath = [cssPath];
  3821. }
  3822. _each(cssPath, function(i, path) {
  3823. if(path) {
  3824. arr.push('<link href="' + path + '" rel="stylesheet" />');
  3825. }
  3826. });
  3827. if(cssData) {
  3828. arr.push('<style>' + cssData + '</style>');
  3829. }
  3830. arr.push('</head><body ' + (bodyClass ? 'class="' + bodyClass + '"' : '') + '></body></html>');
  3831. return arr.join('\n');
  3832. }
  3833. function _elementVal(knode, val) {
  3834. if(knode.hasVal()) {
  3835. if(val === undefined) {
  3836. var html = knode.val();
  3837. html = html.replace(/(<(?:p|p\s[^>]*)>) *(<\/p>)/ig, '');
  3838. return html;
  3839. }
  3840. return knode.val(val);
  3841. }
  3842. return knode.html(val);
  3843. }
  3844. function KEdit(options) {
  3845. this.init(options);
  3846. }
  3847. _extend(KEdit, KWidget, {
  3848. init: function(options) {
  3849. var self = this;
  3850. KEdit.parent.init.call(self, options);
  3851. self.srcElement = K(options.srcElement);
  3852. self.div.addClass('ke-edit');
  3853. self.designMode = _undef(options.designMode, true);
  3854. self.beforeGetHtml = options.beforeGetHtml;
  3855. self.beforeSetHtml = options.beforeSetHtml;
  3856. self.afterSetHtml = options.afterSetHtml;
  3857. var themesPath = _undef(options.themesPath, ''),
  3858. bodyClass = options.bodyClass,
  3859. cssPath = options.cssPath,
  3860. cssData = options.cssData,
  3861. isDocumentDomain = location.protocol != 'res:' && location.host.replace(/:\d+/, '') !== document.domain,
  3862. srcScript = ('document.open();' +
  3863. (isDocumentDomain ? 'document.domain="' + document.domain + '";' : '') +
  3864. 'document.close();'),
  3865. iframeSrc = _IE ? ' src="javascript:void(function(){' + encodeURIComponent(srcScript) + '}())"' : '';
  3866. self.iframe = K('<iframe class="ke-edit-iframe" hidefocus="true" frameborder="0"' + iframeSrc + '></iframe>').css('width', '100%');
  3867. self.textarea = K('<textarea class="ke-edit-textarea" hidefocus="true"></textarea>').css('width', '100%');
  3868. self.tabIndex = isNaN(parseInt(options.tabIndex, 10)) ? self.srcElement.attr('tabindex') : parseInt(options.tabIndex, 10);
  3869. self.iframe.attr('tabindex', self.tabIndex);
  3870. self.textarea.attr('tabindex', self.tabIndex);
  3871. if(self.width) {
  3872. self.setWidth(self.width);
  3873. }
  3874. if(self.height) {
  3875. self.setHeight(self.height);
  3876. }
  3877. if(self.designMode) {
  3878. self.textarea.hide();
  3879. } else {
  3880. self.iframe.hide();
  3881. }
  3882. function ready() {
  3883. var doc = _iframeDoc(self.iframe);
  3884. doc.open();
  3885. if(isDocumentDomain) {
  3886. doc.domain = document.domain;
  3887. }
  3888. doc.write(_getInitHtml(themesPath, bodyClass, cssPath, cssData));
  3889. doc.close();
  3890. self.win = self.iframe[0].contentWindow;
  3891. self.doc = doc;
  3892. var cmd = _cmd(doc);
  3893. self.afterChange(function(e) {
  3894. cmd.selection();
  3895. });
  3896. if(_WEBKIT) {
  3897. K(doc).click(function(e) {
  3898. if(K(e.target).name === 'img') {
  3899. cmd.selection(true);
  3900. cmd.range.selectNode(e.target);
  3901. cmd.select();
  3902. }
  3903. });
  3904. }
  3905. if(_IE) {
  3906. self._mousedownHandler = function() {
  3907. var newRange = cmd.range.cloneRange();
  3908. newRange.shrink();
  3909. if(newRange.isControl()) {
  3910. self.blur();
  3911. }
  3912. };
  3913. K(document).mousedown(self._mousedownHandler);
  3914. K(doc).keydown(function(e) {
  3915. if(e.which == 8) {
  3916. cmd.selection();
  3917. var rng = cmd.range;
  3918. if(rng.isControl()) {
  3919. rng.collapse(true);
  3920. K(rng.startContainer.childNodes[rng.startOffset]).remove();
  3921. e.preventDefault();
  3922. }
  3923. }
  3924. });
  3925. }
  3926. self.cmd = cmd;
  3927. self.html(_elementVal(self.srcElement));
  3928. if(_IE) {
  3929. doc.body.disabled = true;
  3930. doc.body.contentEditable = true;
  3931. doc.body.removeAttribute('disabled');
  3932. } else {
  3933. doc.designMode = 'on';
  3934. }
  3935. if(options.afterCreate) {
  3936. options.afterCreate.call(self);
  3937. }
  3938. }
  3939. if(isDocumentDomain) {
  3940. self.iframe.bind('load', function(e) {
  3941. self.iframe.unbind('load');
  3942. if(_IE) {
  3943. ready();
  3944. } else {
  3945. setTimeout(ready, 0);
  3946. }
  3947. });
  3948. }
  3949. self.div.append(self.iframe);
  3950. self.div.append(self.textarea);
  3951. self.srcElement.hide();
  3952. !isDocumentDomain && ready();
  3953. },
  3954. setWidth: function(val) {
  3955. this.div.css('width', _addUnit(val));
  3956. return this;
  3957. },
  3958. setHeight: function(val) {
  3959. var self = this;
  3960. val = _addUnit(val);
  3961. self.div.css('height', val);
  3962. self.iframe.css('height', val);
  3963. if((_IE && _V < 8) || _QUIRKS) {
  3964. val = _addUnit(_removeUnit(val) - 2);
  3965. }
  3966. self.textarea.css('height', val);
  3967. return self;
  3968. },
  3969. remove: function() {
  3970. var self = this,
  3971. doc = self.doc;
  3972. K(doc.body).unbind();
  3973. K(doc).unbind();
  3974. K(self.win).unbind();
  3975. if(self._mousedownHandler) {
  3976. K(document).unbind('mousedown', self._mousedownHandler);
  3977. }
  3978. _elementVal(self.srcElement, self.html());
  3979. self.srcElement.show();
  3980. doc.write('');
  3981. self.iframe.unbind();
  3982. self.textarea.unbind();
  3983. KEdit.parent.remove.call(self);
  3984. },
  3985. html: function(val, isFull) {
  3986. var self = this,
  3987. doc = self.doc;
  3988. if(self.designMode) {
  3989. var body = doc.body;
  3990. if(val === undefined) {
  3991. if(isFull) {
  3992. val = '<!doctype html><html>' + body.parentNode.innerHTML + '</html>';
  3993. } else {
  3994. val = body.innerHTML;
  3995. }
  3996. if(self.beforeGetHtml) {
  3997. val = self.beforeGetHtml(val);
  3998. }
  3999. if(_GECKO && val == '<br />') {
  4000. val = '';
  4001. }
  4002. return val;
  4003. }
  4004. if(self.beforeSetHtml) {
  4005. val = self.beforeSetHtml(val);
  4006. }
  4007. if(_IE && _V >= 9) {
  4008. val = val.replace(/(<.*?checked=")checked(".*>)/ig, '$1$2');
  4009. }
  4010. K(body).html(val);
  4011. if(self.afterSetHtml) {
  4012. self.afterSetHtml();
  4013. }
  4014. return self;
  4015. }
  4016. if(val === undefined) {
  4017. return self.textarea.val();
  4018. }
  4019. self.textarea.val(val);
  4020. return self;
  4021. },
  4022. design: function(bool) {
  4023. var self = this,
  4024. val;
  4025. if(bool === undefined ? !self.designMode : bool) {
  4026. if(!self.designMode) {
  4027. val = self.html();
  4028. self.designMode = true;
  4029. self.html(val);
  4030. self.textarea.hide();
  4031. self.iframe.show();
  4032. }
  4033. } else {
  4034. if(self.designMode) {
  4035. val = self.html();
  4036. self.designMode = false;
  4037. self.html(val);
  4038. self.iframe.hide();
  4039. self.textarea.show();
  4040. }
  4041. }
  4042. return self.focus();
  4043. },
  4044. focus: function() {
  4045. var self = this;
  4046. self.designMode ? self.win.focus() : self.textarea[0].focus();
  4047. return self;
  4048. },
  4049. blur: function() {
  4050. var self = this;
  4051. if(_IE) {
  4052. var input = K('<input type="text" style="float:left;width:0;height:0;padding:0;margin:0;border:0;" value="" />', self.div);
  4053. self.div.append(input);
  4054. input[0].focus();
  4055. input.remove();
  4056. } else {
  4057. self.designMode ? self.win.blur() : self.textarea[0].blur();
  4058. }
  4059. return self;
  4060. },
  4061. afterChange: function(fn) {
  4062. var self = this,
  4063. doc = self.doc,
  4064. body = doc.body;
  4065. K(doc).keyup(function(e) {
  4066. if(!e.ctrlKey && !e.altKey && _CHANGE_KEY_MAP[e.which]) {
  4067. fn(e);
  4068. }
  4069. });
  4070. K(doc).mouseup(fn).contextmenu(fn);
  4071. K(self.win).blur(fn);
  4072. function timeoutHandler(e) {
  4073. setTimeout(function() {
  4074. fn(e);
  4075. }, 1);
  4076. }
  4077. K(body).bind('paste', timeoutHandler);
  4078. K(body).bind('cut', timeoutHandler);
  4079. return self;
  4080. }
  4081. });
  4082. function _edit(options) {
  4083. return new KEdit(options);
  4084. }
  4085. K.EditClass = KEdit;
  4086. K.edit = _edit;
  4087. K.iframeDoc = _iframeDoc;
  4088. function _selectToolbar(name, fn) {
  4089. var self = this,
  4090. knode = self.get(name);
  4091. if(knode) {
  4092. if(knode.hasClass('ke-disabled')) {
  4093. return;
  4094. }
  4095. fn(knode);
  4096. }
  4097. }
  4098. function KToolbar(options) {
  4099. this.init(options);
  4100. }
  4101. _extend(KToolbar, KWidget, {
  4102. init: function(options) {
  4103. var self = this;
  4104. KToolbar.parent.init.call(self, options);
  4105. self.disableMode = _undef(options.disableMode, false);
  4106. self.noDisableItemMap = _toMap(_undef(options.noDisableItems, []));
  4107. self._itemMap = {};
  4108. self.div.addClass('ke-toolbar').bind('contextmenu,mousedown,mousemove', function(e) {
  4109. e.preventDefault();
  4110. }).attr('unselectable', 'on');
  4111. function find(target) {
  4112. var knode = K(target);
  4113. if(knode.hasClass('ke-outline')) {
  4114. return knode;
  4115. }
  4116. if(knode.hasClass('ke-toolbar-icon')) {
  4117. return knode.parent();
  4118. }
  4119. }
  4120. function hover(e, method) {
  4121. var knode = find(e.target);
  4122. if(knode) {
  4123. if(knode.hasClass('ke-disabled')) {
  4124. return;
  4125. }
  4126. if(knode.hasClass('ke-selected')) {
  4127. return;
  4128. }
  4129. knode[method]('ke-on');
  4130. }
  4131. }
  4132. self.div.mouseover(function(e) {
  4133. hover(e, 'addClass');
  4134. })
  4135. .mouseout(function(e) {
  4136. hover(e, 'removeClass');
  4137. })
  4138. .click(function(e) {
  4139. var knode = find(e.target);
  4140. if(knode) {
  4141. if(knode.hasClass('ke-disabled')) {
  4142. return;
  4143. }
  4144. self.options.click.call(this, e, knode.attr('data-name'));
  4145. }
  4146. });
  4147. },
  4148. get: function(name) {
  4149. if(this._itemMap[name]) {
  4150. return this._itemMap[name];
  4151. }
  4152. return(this._itemMap[name] = K('span.ke-icon-' + name, this.div).parent());
  4153. },
  4154. select: function(name) {
  4155. _selectToolbar.call(this, name, function(knode) {
  4156. knode.addClass('ke-selected');
  4157. });
  4158. return self;
  4159. },
  4160. unselect: function(name) {
  4161. _selectToolbar.call(this, name, function(knode) {
  4162. knode.removeClass('ke-selected').removeClass('ke-on');
  4163. });
  4164. return self;
  4165. },
  4166. enable: function(name) {
  4167. var self = this,
  4168. knode = name.get ? name : self.get(name);
  4169. if(knode) {
  4170. knode.removeClass('ke-disabled');
  4171. knode.opacity(1);
  4172. }
  4173. return self;
  4174. },
  4175. disable: function(name) {
  4176. var self = this,
  4177. knode = name.get ? name : self.get(name);
  4178. if(knode) {
  4179. knode.removeClass('ke-selected').addClass('ke-disabled');
  4180. knode.opacity(0.5);
  4181. }
  4182. return self;
  4183. },
  4184. disableAll: function(bool, noDisableItems) {
  4185. var self = this,
  4186. map = self.noDisableItemMap,
  4187. item;
  4188. if(noDisableItems) {
  4189. map = _toMap(noDisableItems);
  4190. }
  4191. if(bool === undefined ? !self.disableMode : bool) {
  4192. K('span.ke-outline', self.div).each(function() {
  4193. var knode = K(this),
  4194. name = knode[0].getAttribute('data-name', 2);
  4195. if(!map[name]) {
  4196. self.disable(knode);
  4197. }
  4198. });
  4199. self.disableMode = true;
  4200. } else {
  4201. K('span.ke-outline', self.div).each(function() {
  4202. var knode = K(this),
  4203. name = knode[0].getAttribute('data-name', 2);
  4204. if(!map[name]) {
  4205. self.enable(knode);
  4206. }
  4207. });
  4208. self.disableMode = false;
  4209. }
  4210. return self;
  4211. }
  4212. });
  4213. function _toolbar(options) {
  4214. return new KToolbar(options);
  4215. }
  4216. K.ToolbarClass = KToolbar;
  4217. K.toolbar = _toolbar;
  4218. function KMenu(options) {
  4219. this.init(options);
  4220. }
  4221. _extend(KMenu, KWidget, {
  4222. init: function(options) {
  4223. var self = this;
  4224. options.z = options.z || 811213;
  4225. KMenu.parent.init.call(self, options);
  4226. self.centerLineMode = _undef(options.centerLineMode, true);
  4227. self.div.addClass('ke-menu').bind('click,mousedown', function(e) {
  4228. e.stopPropagation();
  4229. }).attr('unselectable', 'on');
  4230. },
  4231. addItem: function(item) {
  4232. var self = this;
  4233. if(item.title === '-') {
  4234. self.div.append(K('<div class="ke-menu-separator"></div>'));
  4235. return;
  4236. }
  4237. var itemDiv = K('<div class="ke-menu-item" unselectable="on"></div>'),
  4238. leftDiv = K('<div class="ke-inline-block ke-menu-item-left"></div>'),
  4239. rightDiv = K('<div class="ke-inline-block ke-menu-item-right"></div>'),
  4240. height = _addUnit(item.height),
  4241. iconClass = _undef(item.iconClass, '');
  4242. self.div.append(itemDiv);
  4243. if(height) {
  4244. itemDiv.css('height', height);
  4245. rightDiv.css('line-height', height);
  4246. }
  4247. var centerDiv;
  4248. if(self.centerLineMode) {
  4249. centerDiv = K('<div class="ke-inline-block ke-menu-item-center"></div>');
  4250. if(height) {
  4251. centerDiv.css('height', height);
  4252. }
  4253. }
  4254. itemDiv.mouseover(function(e) {
  4255. K(this).addClass('ke-menu-item-on');
  4256. if(centerDiv) {
  4257. centerDiv.addClass('ke-menu-item-center-on');
  4258. }
  4259. })
  4260. .mouseout(function(e) {
  4261. K(this).removeClass('ke-menu-item-on');
  4262. if(centerDiv) {
  4263. centerDiv.removeClass('ke-menu-item-center-on');
  4264. }
  4265. })
  4266. .click(function(e) {
  4267. item.click.call(K(this));
  4268. e.stopPropagation();
  4269. })
  4270. .append(leftDiv);
  4271. if(centerDiv) {
  4272. itemDiv.append(centerDiv);
  4273. }
  4274. itemDiv.append(rightDiv);
  4275. if(item.checked) {
  4276. iconClass = 'ke-icon-checked';
  4277. }
  4278. if(iconClass !== '') {
  4279. leftDiv.html('<span class="ke-inline-block ke-toolbar-icon ke-toolbar-icon-url ' + iconClass + '"></span>');
  4280. }
  4281. rightDiv.html(item.title);
  4282. return self;
  4283. },
  4284. remove: function() {
  4285. var self = this;
  4286. if(self.options.beforeRemove) {
  4287. self.options.beforeRemove.call(self);
  4288. }
  4289. K('.ke-menu-item', self.div[0]).unbind();
  4290. KMenu.parent.remove.call(self);
  4291. return self;
  4292. }
  4293. });
  4294. function _menu(options) {
  4295. return new KMenu(options);
  4296. }
  4297. K.MenuClass = KMenu;
  4298. K.menu = _menu;
  4299. function KColorPicker(options) {
  4300. this.init(options);
  4301. }
  4302. _extend(KColorPicker, KWidget, {
  4303. init: function(options) {
  4304. var self = this;
  4305. options.z = options.z || 811213;
  4306. KColorPicker.parent.init.call(self, options);
  4307. var colors = options.colors || [
  4308. ['#E53333', '#E56600', '#FF9900', '#64451D', '#DFC5A4', '#FFE500'],
  4309. ['#009900', '#006600', '#99BB00', '#B8D100', '#60D978', '#00D5FF'],
  4310. ['#337FE5', '#003399', '#4C33E5', '#9933E5', '#CC33E5', '#EE33EE'],
  4311. ['#FFFFFF', '#CCCCCC', '#999999', '#666666', '#333333', '#000000']
  4312. ];
  4313. self.selectedColor = (options.selectedColor || '').toLowerCase();
  4314. self._cells = [];
  4315. self.div.addClass('ke-colorpicker').bind('click,mousedown', function(e) {
  4316. e.stopPropagation();
  4317. }).attr('unselectable', 'on');
  4318. var table = self.doc.createElement('table');
  4319. self.div.append(table);
  4320. table.className = 'ke-colorpicker-table';
  4321. table.cellPadding = 0;
  4322. table.cellSpacing = 0;
  4323. table.border = 0;
  4324. var row = table.insertRow(0),
  4325. cell = row.insertCell(0);
  4326. cell.colSpan = colors[0].length;
  4327. self._addAttr(cell, '', 'ke-colorpicker-cell-top');
  4328. for(var i = 0; i < colors.length; i++) {
  4329. row = table.insertRow(i + 1);
  4330. for(var j = 0; j < colors[i].length; j++) {
  4331. cell = row.insertCell(j);
  4332. self._addAttr(cell, colors[i][j], 'ke-colorpicker-cell');
  4333. }
  4334. }
  4335. },
  4336. _addAttr: function(cell, color, cls) {
  4337. var self = this;
  4338. cell = K(cell).addClass(cls);
  4339. if(self.selectedColor === color.toLowerCase()) {
  4340. cell.addClass('ke-colorpicker-cell-selected');
  4341. }
  4342. cell.attr('title', color || self.options.noColor);
  4343. cell.mouseover(function(e) {
  4344. K(this).addClass('ke-colorpicker-cell-on');
  4345. });
  4346. cell.mouseout(function(e) {
  4347. K(this).removeClass('ke-colorpicker-cell-on');
  4348. });
  4349. cell.click(function(e) {
  4350. e.stop();
  4351. self.options.click.call(K(this), color);
  4352. });
  4353. if(color) {
  4354. cell.append(K('<div class="ke-colorpicker-cell-color" unselectable="on"></div>').css('background-color', color));
  4355. } else {
  4356. cell.html(self.options.noColor);
  4357. }
  4358. K(cell).attr('unselectable', 'on');
  4359. self._cells.push(cell);
  4360. },
  4361. remove: function() {
  4362. var self = this;
  4363. _each(self._cells, function() {
  4364. this.unbind();
  4365. });
  4366. KColorPicker.parent.remove.call(self);
  4367. return self;
  4368. }
  4369. });
  4370. function _colorpicker(options) {
  4371. return new KColorPicker(options);
  4372. }
  4373. K.ColorPickerClass = KColorPicker;
  4374. K.colorpicker = _colorpicker;
  4375. function KUploadButton(options) {
  4376. this.init(options);
  4377. }
  4378. _extend(KUploadButton, {
  4379. init: function(options) {
  4380. var self = this,
  4381. button = K(options.button),
  4382. fieldName = options.fieldName || 'file',
  4383. url = options.url || '',
  4384. title = button.val(),
  4385. extraParams = options.extraParams || {},
  4386. cls = button[0].className || '',
  4387. target = options.target || 'kindeditor_upload_iframe_' + new Date().getTime();
  4388. options.afterError = options.afterError || function(str) {
  4389. alert(str);
  4390. };
  4391. var hiddenElements = [];
  4392. for(var k in extraParams) {
  4393. hiddenElements.push('<input type="hidden" name="' + k + '" value="' + extraParams[k] + '" />');
  4394. }
  4395. var html = [
  4396. '<div class="ke-inline-block ' + cls + '">', (options.target ? '' : '<iframe name="' + target + '" style="display:none;"></iframe>'), (options.form ? '<div class="ke-upload-area">' : '<form class="ke-upload-area ke-form" method="post" enctype="multipart/form-data" target="' + target + '" action="' + url + '">'),
  4397. '<span class="ke-button-common">',
  4398. hiddenElements.join(''),
  4399. '<input type="button" class="ke-button-common ke-button" value="' + title + '" />',
  4400. '</span>',
  4401. '<input type="file" class="ke-upload-file" name="' + fieldName + '" tabindex="-1" />', (options.form ? '</div>' : '</form>'),
  4402. '</div>'
  4403. ].join('');
  4404. var div = K(html, button.doc);
  4405. button.hide();
  4406. button.before(div);
  4407. self.div = div;
  4408. self.button = button;
  4409. self.iframe = options.target ? K('iframe[name="' + target + '"]') : K('iframe', div);
  4410. self.form = options.form ? K(options.form) : K('form', div);
  4411. self.fileBox = K('.ke-upload-file', div);
  4412. self.options = options;
  4413. },
  4414. submit: function() {
  4415. var self = this,
  4416. iframe = self.iframe;
  4417. iframe.bind('load', function() {
  4418. iframe.unbind();
  4419. var tempForm = document.createElement('form');
  4420. self.fileBox.before(tempForm);
  4421. K(tempForm).append(self.fileBox);
  4422. tempForm.reset();
  4423. K(tempForm).remove(true);
  4424. var doc = K.iframeDoc(iframe),
  4425. pre = doc.getElementsByTagName('pre')[0],
  4426. str = '',
  4427. data;
  4428. if(pre) {
  4429. str = pre.innerHTML;
  4430. } else {
  4431. str = doc.body.innerHTML;
  4432. }
  4433. str = _unescape(str);
  4434. iframe[0].src = 'javascript:false';
  4435. try {
  4436. data = K.json(str);
  4437. } catch(e) {
  4438. self.options.afterError.call(self, '<!doctype html><html>' + doc.body.parentNode.innerHTML + '</html>');
  4439. }
  4440. if(data) {
  4441. self.options.afterUpload.call(self, data);
  4442. }
  4443. });
  4444. self.form[0].submit();
  4445. return self;
  4446. },
  4447. remove: function() {
  4448. var self = this;
  4449. if(self.fileBox) {
  4450. self.fileBox.unbind();
  4451. }
  4452. self.iframe.remove();
  4453. self.div.remove();
  4454. self.button.show();
  4455. return self;
  4456. }
  4457. });
  4458. function _uploadbutton(options) {
  4459. return new KUploadButton(options);
  4460. }
  4461. K.UploadButtonClass = KUploadButton;
  4462. K.uploadbutton = _uploadbutton;
  4463. function _createButton(arg) {
  4464. arg = arg || {};
  4465. var name = arg.name || '',
  4466. span = K('<span class="ke-button-common ke-button-outer" title="' + name + '"></span>'),
  4467. btn = K('<input class="ke-button-common ke-button" type="button" value="' + name + '" />');
  4468. if(arg.click) {
  4469. btn.click(arg.click);
  4470. }
  4471. span.append(btn);
  4472. return span;
  4473. }
  4474. function KDialog(options) {
  4475. this.init(options);
  4476. }
  4477. _extend(KDialog, KWidget, {
  4478. init: function(options) {
  4479. var self = this;
  4480. var shadowMode = _undef(options.shadowMode, true);
  4481. options.z = options.z || 811213;
  4482. options.shadowMode = false;
  4483. options.autoScroll = _undef(options.autoScroll, true);
  4484. KDialog.parent.init.call(self, options);
  4485. var title = options.title,
  4486. body = K(options.body, self.doc),
  4487. previewBtn = options.previewBtn,
  4488. yesBtn = options.yesBtn,
  4489. noBtn = options.noBtn,
  4490. closeBtn = options.closeBtn,
  4491. showMask = _undef(options.showMask, true);
  4492. self.div.addClass('ke-dialog').bind('click,mousedown', function(e) {
  4493. e.stopPropagation();
  4494. });
  4495. var contentDiv = K('<div class="ke-dialog-content"></div>').appendTo(self.div);
  4496. if(_IE && _V < 7) {
  4497. self.iframeMask = K('<iframe src="about:blank" class="ke-dialog-shadow"></iframe>').appendTo(self.div);
  4498. } else if(shadowMode) {
  4499. K('<div class="ke-dialog-shadow"></div>').appendTo(self.div);
  4500. }
  4501. var headerDiv = K('<div class="ke-dialog-header"></div>');
  4502. contentDiv.append(headerDiv);
  4503. headerDiv.html(title);
  4504. self.closeIcon = K('<span class="ke-dialog-icon-close" title="' + closeBtn.name + '"></span>').click(closeBtn.click);
  4505. headerDiv.append(self.closeIcon);
  4506. self.draggable({
  4507. clickEl: headerDiv,
  4508. beforeDrag: options.beforeDrag
  4509. });
  4510. var bodyDiv = K('<div class="ke-dialog-body"></div>');
  4511. contentDiv.append(bodyDiv);
  4512. bodyDiv.append(body);
  4513. var footerDiv = K('<div class="ke-dialog-footer"></div>');
  4514. if(previewBtn || yesBtn || noBtn) {
  4515. contentDiv.append(footerDiv);
  4516. }
  4517. _each([{
  4518. btn: previewBtn,
  4519. name: 'preview'
  4520. }, {
  4521. btn: yesBtn,
  4522. name: 'yes'
  4523. }, {
  4524. btn: noBtn,
  4525. name: 'no'
  4526. }], function() {
  4527. if(this.btn) {
  4528. var button = _createButton(this.btn);
  4529. button.addClass('ke-dialog-' + this.name);
  4530. footerDiv.append(button);
  4531. }
  4532. });
  4533. if(self.height) {
  4534. bodyDiv.height(_removeUnit(self.height) - headerDiv.height() - footerDiv.height());
  4535. }
  4536. self.div.width(self.div.width());
  4537. self.div.height(self.div.height());
  4538. self.mask = null;
  4539. if(showMask) {
  4540. var docEl = _docElement(self.doc),
  4541. docWidth = Math.max(docEl.scrollWidth, docEl.clientWidth),
  4542. docHeight = Math.max(docEl.scrollHeight, docEl.clientHeight);
  4543. self.mask = _widget({
  4544. x: 0,
  4545. y: 0,
  4546. z: self.z - 1,
  4547. cls: 'ke-dialog-mask',
  4548. width: docWidth,
  4549. height: docHeight
  4550. });
  4551. }
  4552. self.autoPos(self.div.width(), self.div.height());
  4553. self.footerDiv = footerDiv;
  4554. self.bodyDiv = bodyDiv;
  4555. self.headerDiv = headerDiv;
  4556. self.isLoading = false;
  4557. },
  4558. setMaskIndex: function(z) {
  4559. var self = this;
  4560. self.mask.div.css('z-index', z);
  4561. },
  4562. showLoading: function(msg) {
  4563. msg = _undef(msg, '');
  4564. var self = this,
  4565. body = self.bodyDiv;
  4566. 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>')
  4567. .width(body.width()).height(body.height())
  4568. .css('top', self.headerDiv.height() + 'px');
  4569. body.css('visibility', 'hidden').after(self.loading);
  4570. self.isLoading = true;
  4571. return self;
  4572. },
  4573. hideLoading: function() {
  4574. this.loading && this.loading.remove();
  4575. this.bodyDiv.css('visibility', 'visible');
  4576. this.isLoading = false;
  4577. return this;
  4578. },
  4579. remove: function() {
  4580. var self = this;
  4581. if(self.options.beforeRemove) {
  4582. self.options.beforeRemove.call(self);
  4583. }
  4584. self.mask && self.mask.remove();
  4585. self.iframeMask && self.iframeMask.remove();
  4586. self.closeIcon.unbind();
  4587. K('input', self.div).unbind();
  4588. K('button', self.div).unbind();
  4589. self.footerDiv.unbind();
  4590. self.bodyDiv.unbind();
  4591. self.headerDiv.unbind();
  4592. K('iframe', self.div).each(function() {
  4593. K(this).remove();
  4594. });
  4595. KDialog.parent.remove.call(self);
  4596. return self;
  4597. }
  4598. });
  4599. function _dialog(options) {
  4600. return new KDialog(options);
  4601. }
  4602. K.DialogClass = KDialog;
  4603. K.dialog = _dialog;
  4604. function _tabs(options) {
  4605. var self = _widget(options),
  4606. remove = self.remove,
  4607. afterSelect = options.afterSelect,
  4608. div = self.div,
  4609. liList = [];
  4610. div.addClass('ke-tabs')
  4611. .bind('contextmenu,mousedown,mousemove', function(e) {
  4612. e.preventDefault();
  4613. });
  4614. var ul = K('<ul class="ke-tabs-ul ke-clearfix"></ul>');
  4615. div.append(ul);
  4616. self.add = function(tab) {
  4617. var li = K('<li class="ke-tabs-li">' + tab.title + '</li>');
  4618. li.data('tab', tab);
  4619. liList.push(li);
  4620. ul.append(li);
  4621. };
  4622. self.selectedIndex = 0;
  4623. self.select = function(index) {
  4624. self.selectedIndex = index;
  4625. _each(liList, function(i, li) {
  4626. li.unbind();
  4627. if(i === index) {
  4628. li.addClass('ke-tabs-li-selected');
  4629. K(li.data('tab').panel).show('');
  4630. } else {
  4631. li.removeClass('ke-tabs-li-selected').removeClass('ke-tabs-li-on')
  4632. .mouseover(function() {
  4633. K(this).addClass('ke-tabs-li-on');
  4634. })
  4635. .mouseout(function() {
  4636. K(this).removeClass('ke-tabs-li-on');
  4637. })
  4638. .click(function() {
  4639. self.select(i);
  4640. });
  4641. K(li.data('tab').panel).hide();
  4642. }
  4643. });
  4644. if(afterSelect) {
  4645. afterSelect.call(self, index);
  4646. }
  4647. };
  4648. self.remove = function() {
  4649. _each(liList, function() {
  4650. this.remove();
  4651. });
  4652. ul.remove();
  4653. remove.call(self);
  4654. };
  4655. return self;
  4656. }
  4657. K.tabs = _tabs;
  4658. function _loadScript(url, fn) {
  4659. var head = document.getElementsByTagName('head')[0] || (_QUIRKS ? document.body : document.documentElement),
  4660. script = document.createElement('script');
  4661. head.appendChild(script);
  4662. script.src = url;
  4663. script.charset = 'utf-8';
  4664. script.onload = script.onreadystatechange = function() {
  4665. if(!this.readyState || this.readyState === 'loaded') {
  4666. if(fn) {
  4667. fn();
  4668. }
  4669. script.onload = script.onreadystatechange = null;
  4670. head.removeChild(script);
  4671. }
  4672. };
  4673. }
  4674. function _chopQuery(url) {
  4675. var index = url.indexOf('?');
  4676. return index > 0 ? url.substr(0, index) : url;
  4677. }
  4678. function _loadStyle(url) {
  4679. var head = document.getElementsByTagName('head')[0] || (_QUIRKS ? document.body : document.documentElement),
  4680. link = document.createElement('link'),
  4681. absoluteUrl = _chopQuery(_formatUrl(url, 'absolute'));
  4682. var links = K('link[rel="stylesheet"]', head);
  4683. for(var i = 0, len = links.length; i < len; i++) {
  4684. if(_chopQuery(_formatUrl(links[i].href, 'absolute')) === absoluteUrl) {
  4685. return;
  4686. }
  4687. }
  4688. head.appendChild(link);
  4689. link.href = url;
  4690. link.rel = 'stylesheet';
  4691. }
  4692. function _ajax(url, fn, method, param, dataType) {
  4693. method = method || 'GET';
  4694. dataType = dataType || 'json';
  4695. var xhr = window.XMLHttpRequest ? new window.XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
  4696. xhr.open(method, url, true);
  4697. xhr.onreadystatechange = function() {
  4698. if(xhr.readyState == 4 && xhr.status == 200) {
  4699. if(fn) {
  4700. var data = _trim(xhr.responseText);
  4701. if(dataType == 'json') {
  4702. data = _json(data);
  4703. }
  4704. fn(data);
  4705. }
  4706. }
  4707. };
  4708. if(method == 'POST') {
  4709. var params = [];
  4710. _each(param, function(key, val) {
  4711. params.push(encodeURIComponent(key) + '=' + encodeURIComponent(val));
  4712. });
  4713. try {
  4714. xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  4715. } catch(e) {}
  4716. xhr.send(params.join('&'));
  4717. } else {
  4718. xhr.send(null);
  4719. }
  4720. }
  4721. K.loadScript = _loadScript;
  4722. K.loadStyle = _loadStyle;
  4723. K.ajax = _ajax;
  4724. var _plugins = {};
  4725. function _plugin(name, fn) {
  4726. if(name === undefined) {
  4727. return _plugins;
  4728. }
  4729. if(!fn) {
  4730. return _plugins[name];
  4731. }
  4732. _plugins[name] = fn;
  4733. }
  4734. var _language = {};
  4735. function _parseLangKey(key) {
  4736. var match, ns = 'core';
  4737. if((match = /^(\w+)\.(\w+)$/.exec(key))) {
  4738. ns = match[1];
  4739. key = match[2];
  4740. }
  4741. return {
  4742. ns: ns,
  4743. key: key
  4744. };
  4745. }
  4746. function _lang(mixed, langType) {
  4747. langType = langType === undefined ? K.options.langType : langType;
  4748. if(typeof mixed === 'string') {
  4749. if(!_language[langType]) {
  4750. return 'no language';
  4751. }
  4752. var pos = mixed.length - 1;
  4753. if(mixed.substr(pos) === '.') {
  4754. return _language[langType][mixed.substr(0, pos)];
  4755. }
  4756. var obj = _parseLangKey(mixed);
  4757. return _language[langType][obj.ns][obj.key];
  4758. }
  4759. _each(mixed, function(key, val) {
  4760. var obj = _parseLangKey(key);
  4761. if(!_language[langType]) {
  4762. _language[langType] = {};
  4763. }
  4764. if(!_language[langType][obj.ns]) {
  4765. _language[langType][obj.ns] = {};
  4766. }
  4767. _language[langType][obj.ns][obj.key] = val;
  4768. });
  4769. }
  4770. function _getImageFromRange(range, fn) {
  4771. if(range.collapsed) {
  4772. return;
  4773. }
  4774. range = range.cloneRange().up();
  4775. var sc = range.startContainer,
  4776. so = range.startOffset;
  4777. if(!_WEBKIT && !range.isControl()) {
  4778. return;
  4779. }
  4780. var img = K(sc.childNodes[so]);
  4781. if(!img || img.name != 'img') {
  4782. return;
  4783. }
  4784. if(fn(img)) {
  4785. return img;
  4786. }
  4787. }
  4788. function _bindContextmenuEvent() {
  4789. var self = this,
  4790. doc = self.edit.doc;
  4791. K(doc).contextmenu(function(e) {
  4792. if(self.menu) {
  4793. self.hideMenu();
  4794. }
  4795. if(!self.useContextmenu) {
  4796. e.preventDefault();
  4797. return;
  4798. }
  4799. if(self._contextmenus.length === 0) {
  4800. return;
  4801. }
  4802. var maxWidth = 0,
  4803. items = [];
  4804. _each(self._contextmenus, function() {
  4805. if(this.title == '-') {
  4806. items.push(this);
  4807. return;
  4808. }
  4809. if(this.cond && this.cond()) {
  4810. items.push(this);
  4811. if(this.width && this.width > maxWidth) {
  4812. maxWidth = this.width;
  4813. }
  4814. }
  4815. });
  4816. while(items.length > 0 && items[0].title == '-') {
  4817. items.shift();
  4818. }
  4819. while(items.length > 0 && items[items.length - 1].title == '-') {
  4820. items.pop();
  4821. }
  4822. var prevItem = null;
  4823. var filterItems = [];
  4824. _each(items, function(i) {
  4825. if (!prevItem || !(prevItem.title === '-' && this.title === '-')) {
  4826. filterItems.push(this);
  4827. prevItem = this;
  4828. }
  4829. });
  4830. items = filterItems;
  4831. if(items.length > 0) {
  4832. e.preventDefault();
  4833. var pos = K(self.edit.iframe).pos(),
  4834. menu = _menu({
  4835. x: pos.x + e.clientX,
  4836. y: pos.y + e.clientY,
  4837. width: maxWidth,
  4838. css: {
  4839. visibility: 'hidden'
  4840. },
  4841. shadowMode: self.shadowMode
  4842. });
  4843. _each(items, function() {
  4844. if(this.title) {
  4845. menu.addItem(this);
  4846. }
  4847. });
  4848. var docEl = _docElement(menu.doc),
  4849. menuHeight = menu.div.height();
  4850. if(e.clientY + menuHeight >= docEl.clientHeight - 100) {
  4851. menu.pos(menu.x, _removeUnit(menu.y) - menuHeight);
  4852. }
  4853. menu.div.css('visibility', 'visible');
  4854. self.menu = menu;
  4855. }
  4856. });
  4857. }
  4858. function _bindNewlineEvent() {
  4859. var self = this,
  4860. doc = self.edit.doc,
  4861. newlineTag = self.newlineTag;
  4862. if(_IE && newlineTag !== 'br') {
  4863. return;
  4864. }
  4865. if(_GECKO && _V < 3 && newlineTag !== 'p') {
  4866. return;
  4867. }
  4868. if(_OPERA && _V < 9) {
  4869. return;
  4870. }
  4871. var brSkipTagMap = _toMap('h1,h2,h3,h4,h5,h6,pre,li'),
  4872. pSkipTagMap = _toMap('p,h1,h2,h3,h4,h5,h6,pre,li,blockquote');
  4873. function getAncestorTagName(range) {
  4874. var ancestor = K(range.commonAncestor());
  4875. while(ancestor) {
  4876. if(ancestor.type == 1 && !ancestor.isStyle()) {
  4877. break;
  4878. }
  4879. ancestor = ancestor.parent();
  4880. }
  4881. return ancestor.name;
  4882. }
  4883. K(doc).keydown(function(e) {
  4884. if(e.which != 13 || e.shiftKey || e.ctrlKey || e.altKey) {
  4885. return;
  4886. }
  4887. self.cmd.selection();
  4888. var tagName = getAncestorTagName(self.cmd.range);
  4889. if(tagName == 'marquee' || tagName == 'select') {
  4890. return;
  4891. }
  4892. if(newlineTag === 'br' && !brSkipTagMap[tagName]) {
  4893. e.preventDefault();
  4894. self.insertHtml('<br />' + (_IE && _V < 9 ? '' : '\u200B'));
  4895. return;
  4896. }
  4897. if(!pSkipTagMap[tagName]) {
  4898. _nativeCommand(doc, 'formatblock', '<p>');
  4899. }
  4900. });
  4901. K(doc).keyup(function(e) {
  4902. if(e.which != 13 || e.shiftKey || e.ctrlKey || e.altKey) {
  4903. return;
  4904. }
  4905. if(newlineTag == 'br') {
  4906. return;
  4907. }
  4908. if(_GECKO) {
  4909. var root = self.cmd.commonAncestor('p');
  4910. var a = self.cmd.commonAncestor('a');
  4911. if(a && a.text() == '') {
  4912. a.remove(true);
  4913. self.cmd.range.selectNodeContents(root[0]).collapse(true);
  4914. self.cmd.select();
  4915. }
  4916. return;
  4917. }
  4918. self.cmd.selection();
  4919. var tagName = getAncestorTagName(self.cmd.range);
  4920. if(tagName == 'marquee' || tagName == 'select') {
  4921. return;
  4922. }
  4923. if(!pSkipTagMap[tagName]) {
  4924. _nativeCommand(doc, 'formatblock', '<p>');
  4925. }
  4926. // see fix: [Chrome] 在 Chrome 上添加标题之后换行 JS 报错 https://github.com/kindsoft/kindeditor/commit/6e2d34e740e76c597cc56f99706d5dc706ed6e6a
  4927. // var div = self.cmd.commonAncestor('div');
  4928. // if(div) {
  4929. // var p = K('<p></p>'),
  4930. // child = div[0].firstChild;
  4931. // while(child) {
  4932. // var next = child.nextSibling;
  4933. // p.append(child);
  4934. // child = next;
  4935. // }
  4936. // div.before(p);
  4937. // div.remove();
  4938. // self.cmd.range.selectNodeContents(p[0]);
  4939. // self.cmd.select();
  4940. // }
  4941. });
  4942. }
  4943. function _bindTabEvent() {
  4944. var self = this,
  4945. doc = self.edit.doc;
  4946. K(doc).keydown(function(e) {
  4947. if(e.which == 9) {
  4948. e.preventDefault();
  4949. if(self.afterTab) {
  4950. var tabResult = self.afterTab.call(self, e);
  4951. // 如果 afterTab 回调函数返回值为 true,则视为已经处理 tab 键操作,否则继续执行原始 tab 操作
  4952. if (tabResult === true) return;
  4953. }
  4954. var cmd = self.cmd,
  4955. range = cmd.range;
  4956. range.shrink();
  4957. if(range.collapsed && range.startContainer.nodeType == 1) {
  4958. range.insertNode(K('@&nbsp;', doc)[0]);
  4959. cmd.select();
  4960. }
  4961. self.insertHtml('&nbsp;&nbsp;&nbsp;&nbsp;');
  4962. }
  4963. });
  4964. }
  4965. function _bindFocusEvent() {
  4966. var self = this;
  4967. K(self.edit.textarea[0], self.edit.win).focus(function(e) {
  4968. if(self.afterFocus) {
  4969. self.afterFocus.call(self, e);
  4970. }
  4971. }).blur(function(e) {
  4972. if(self.afterBlur) {
  4973. self.afterBlur.call(self, e);
  4974. }
  4975. });
  4976. }
  4977. function _removeBookmarkTag(html) {
  4978. return _trim(html.replace(/<span [^>]*id="?__kindeditor_bookmark_\w+_\d+__"?[^>]*><\/span>/ig, ''));
  4979. }
  4980. function _removeTempTag(html) {
  4981. return html.replace(/<div[^>]+class="?__kindeditor_paste__"?[^>]*>[\s\S]*?<\/div>/ig, '');
  4982. }
  4983. function _addBookmarkToStack(stack, bookmark) {
  4984. if(stack.length === 0) {
  4985. stack.push(bookmark);
  4986. return;
  4987. }
  4988. var prev = stack[stack.length - 1];
  4989. if(_removeBookmarkTag(bookmark.html) !== _removeBookmarkTag(prev.html)) {
  4990. stack.push(bookmark);
  4991. }
  4992. }
  4993. function _undoToRedo(fromStack, toStack) {
  4994. var self = this,
  4995. edit = self.edit,
  4996. body = edit.doc.body,
  4997. range, bookmark;
  4998. if(fromStack.length === 0) {
  4999. return self;
  5000. }
  5001. if(edit.designMode) {
  5002. range = self.cmd.range;
  5003. bookmark = range.createBookmark(true);
  5004. bookmark.html = body.innerHTML;
  5005. } else {
  5006. bookmark = {
  5007. html: body.innerHTML
  5008. };
  5009. }
  5010. _addBookmarkToStack(toStack, bookmark);
  5011. var prev = fromStack.pop();
  5012. if(_removeBookmarkTag(bookmark.html) === _removeBookmarkTag(prev.html) && fromStack.length > 0) {
  5013. prev = fromStack.pop();
  5014. }
  5015. if(edit.designMode) {
  5016. edit.html(prev.html);
  5017. if(prev.start) {
  5018. range.moveToBookmark(prev);
  5019. self.select();
  5020. }
  5021. } else {
  5022. K(body).html(_removeBookmarkTag(prev.html));
  5023. }
  5024. return self;
  5025. }
  5026. function KEditor(options) {
  5027. var self = this;
  5028. self.options = {};
  5029. function setOption(key, val) {
  5030. if(KEditor.prototype[key] === undefined) {
  5031. self[key] = val;
  5032. }
  5033. self.options[key] = val;
  5034. }
  5035. _each(options, function(key, val) {
  5036. setOption(key, options[key]);
  5037. });
  5038. _each(K.options, function(key, val) {
  5039. if(self[key] === undefined) {
  5040. setOption(key, val);
  5041. }
  5042. });
  5043. var se = K(self.srcElement || '<textarea/>');
  5044. if(!self.width) {
  5045. self.width = se[0].style.width || se.width();
  5046. }
  5047. if(!self.height) {
  5048. self.height = se[0].style.height || se.height();
  5049. }
  5050. setOption('width', _undef(self.width, self.minWidth));
  5051. setOption('height', _undef(self.height, self.minHeight));
  5052. setOption('width', _addUnit(self.width));
  5053. setOption('height', _addUnit(self.height));
  5054. if(_MOBILE && (!_IOS || _V < 534)) {
  5055. self.designMode = false;
  5056. }
  5057. self.srcElement = se;
  5058. self.initContent = '';
  5059. self.plugin = {};
  5060. self.isCreated = false;
  5061. self._handlers = {};
  5062. self._contextmenus = [];
  5063. self._undoStack = [];
  5064. self._redoStack = [];
  5065. self._firstAddBookmark = true;
  5066. self.menu = self.contextmenu = null;
  5067. self.dialogs = [];
  5068. }
  5069. KEditor.prototype = {
  5070. lang: function(mixed) {
  5071. return _lang(mixed, this.langType);
  5072. },
  5073. loadPlugin: function(name, fn) {
  5074. var self = this;
  5075. if(_plugins[name]) {
  5076. if(!_isFunction(_plugins[name])) {
  5077. setTimeout(function() {
  5078. self.loadPlugin(name, fn);
  5079. }, 100);
  5080. return self;
  5081. }
  5082. _plugins[name].call(self, KindEditor);
  5083. if(fn) {
  5084. fn.call(self);
  5085. }
  5086. return self;
  5087. }
  5088. _plugins[name] = 'loading';
  5089. _loadScript(self.pluginsPath + name + '/' + name + '.js?ver=' + encodeURIComponent(K.DEBUG ? _TIME : _VERSION), function() {
  5090. setTimeout(function() {
  5091. if(_plugins[name]) {
  5092. self.loadPlugin(name, fn);
  5093. }
  5094. }, 0);
  5095. });
  5096. return self;
  5097. },
  5098. handler: function(key, fn) {
  5099. var self = this;
  5100. if(!self._handlers[key]) {
  5101. self._handlers[key] = [];
  5102. }
  5103. if(_isFunction(fn)) {
  5104. self._handlers[key].push(fn);
  5105. return self;
  5106. }
  5107. _each(self._handlers[key], function() {
  5108. fn = this.call(self, fn);
  5109. });
  5110. return fn;
  5111. },
  5112. clickToolbar: function(name, fn) {
  5113. var self = this,
  5114. key = 'clickToolbar' + name;
  5115. if(fn === undefined) {
  5116. if(self._handlers[key]) {
  5117. return self.handler(key);
  5118. }
  5119. self.loadPlugin(name, function() {
  5120. self.handler(key);
  5121. });
  5122. return self;
  5123. }
  5124. return self.handler(key, fn);
  5125. },
  5126. updateState: function() {
  5127. var self = this;
  5128. _each(('justifyleft,justifycenter,justifyright,justifyfull,insertorderedlist,insertunorderedlist,' +
  5129. 'subscript,superscript,bold,italic,underline,strikethrough').split(','), function(i, name) {
  5130. self.cmd.state(name) ? self.toolbar.select(name) : self.toolbar.unselect(name);
  5131. });
  5132. return self;
  5133. },
  5134. addContextmenu: function(item) {
  5135. this._contextmenus.push(item);
  5136. return this;
  5137. },
  5138. afterCreate: function(fn) {
  5139. return this.handler('afterCreate', fn);
  5140. },
  5141. beforeRemove: function(fn) {
  5142. return this.handler('beforeRemove', fn);
  5143. },
  5144. beforeGetHtml: function(fn) {
  5145. return this.handler('beforeGetHtml', fn);
  5146. },
  5147. beforeSetHtml: function(fn) {
  5148. return this.handler('beforeSetHtml', fn);
  5149. },
  5150. afterSetHtml: function(fn) {
  5151. return this.handler('afterSetHtml', fn);
  5152. },
  5153. create: function() {
  5154. var self = this,
  5155. fullscreenMode = self.fullscreenMode;
  5156. if(self.isCreated) {
  5157. return self;
  5158. }
  5159. if(self.srcElement.data('kindeditor')) {
  5160. return self;
  5161. }
  5162. self.srcElement.data('kindeditor', 'true');
  5163. if(fullscreenMode) {
  5164. _docElement().style.overflow = 'hidden';
  5165. } else {
  5166. _docElement().style.overflow = '';
  5167. }
  5168. var width = fullscreenMode ? _docElement().clientWidth + 'px' : self.width,
  5169. height = fullscreenMode ? _docElement().clientHeight + 'px' : self.height;
  5170. if((_IE && _V < 8) || _QUIRKS) {
  5171. height = _addUnit(_removeUnit(height) + 2);
  5172. }
  5173. var container = self.container = K(self.layout);
  5174. if(fullscreenMode) {
  5175. K(document.body).append(container);
  5176. } else {
  5177. self.srcElement.before(container);
  5178. }
  5179. var toolbarDiv = K('.toolbar', container),
  5180. editDiv = K('.edit', container),
  5181. statusbar = self.statusbar = K('.statusbar', container);
  5182. container.removeClass('container')
  5183. .addClass('ke-container ke-container-' + self.themeType).css('width', width);
  5184. if(fullscreenMode) {
  5185. container.css({
  5186. position: 'absolute',
  5187. left: 0,
  5188. top: 0,
  5189. 'z-index': 811211
  5190. });
  5191. if(!_GECKO) {
  5192. self._scrollPos = _getScrollPos();
  5193. }
  5194. window.scrollTo(0, 0);
  5195. K(document.body).css({
  5196. 'height': '1px',
  5197. 'overflow': 'hidden'
  5198. });
  5199. K(document.body.parentNode).css('overflow', 'hidden');
  5200. self._fullscreenExecuted = true;
  5201. } else {
  5202. if(self._fullscreenExecuted) {
  5203. K(document.body).css({
  5204. 'height': '',
  5205. 'overflow': ''
  5206. });
  5207. K(document.body.parentNode).css('overflow', '');
  5208. }
  5209. if(self._scrollPos) {
  5210. window.scrollTo(self._scrollPos.x, self._scrollPos.y);
  5211. }
  5212. }
  5213. var htmlList = [];
  5214. K.each(self.items, function(i, name) {
  5215. if(name == '|') {
  5216. htmlList.push('<span class="ke-inline-block ke-separator"></span>');
  5217. } else if(name == '/') {
  5218. htmlList.push('<div class="ke-hr"></div>');
  5219. } else {
  5220. htmlList.push('<span class="ke-outline" data-name="' + name + '" title="' + self.lang(name) + '" unselectable="on">');
  5221. htmlList.push('<span class="ke-toolbar-icon ke-toolbar-icon-url ke-icon-' + name + '" unselectable="on"></span></span>');
  5222. }
  5223. });
  5224. var toolbar = self.toolbar = _toolbar({
  5225. src: toolbarDiv,
  5226. html: htmlList.join(''),
  5227. noDisableItems: self.noDisableItems,
  5228. click: function(e, name) {
  5229. e.stop();
  5230. if(self.menu) {
  5231. var menuName = self.menu.name;
  5232. self.hideMenu();
  5233. if(menuName === name) {
  5234. return;
  5235. }
  5236. }
  5237. self.clickToolbar(name);
  5238. }
  5239. });
  5240. var editHeight = _removeUnit(height) - toolbar.div.height();
  5241. var edit = self.edit = _edit({
  5242. height: editHeight > 0 && _removeUnit(height) > self.minHeight ? editHeight : self.minHeight,
  5243. src: editDiv,
  5244. srcElement: self.srcElement,
  5245. designMode: self.designMode,
  5246. themesPath: self.themesPath,
  5247. bodyClass: self.bodyClass,
  5248. cssPath: self.cssPath,
  5249. cssData: self.cssData,
  5250. beforeGetHtml: function(html) {
  5251. html = self.beforeGetHtml(html);
  5252. html = _removeBookmarkTag(_removeTempTag(html));
  5253. return _formatHtml(html, self.filterMode ? self.htmlTags : null, self.urlType, self.wellFormatMode, self.indentChar, self.simpleWrap);
  5254. },
  5255. beforeSetHtml: function(html) {
  5256. html = _formatHtml(html, self.filterMode ? self.htmlTags : null, '', false);
  5257. return self.beforeSetHtml(html);
  5258. },
  5259. afterSetHtml: function() {
  5260. self.edit = edit = this;
  5261. self.afterSetHtml();
  5262. },
  5263. afterCreate: function() {
  5264. self.edit = edit = this;
  5265. self.cmd = edit.cmd;
  5266. self._docMousedownFn = function(e) {
  5267. if(self.menu) {
  5268. self.hideMenu();
  5269. }
  5270. };
  5271. K(edit.doc, document).mousedown(self._docMousedownFn);
  5272. _bindContextmenuEvent.call(self);
  5273. _bindNewlineEvent.call(self);
  5274. _bindTabEvent.call(self);
  5275. _bindFocusEvent.call(self);
  5276. edit.afterChange(function(e) {
  5277. if(!edit.designMode) {
  5278. return;
  5279. }
  5280. self.updateState();
  5281. self.addBookmark();
  5282. if(self.options.afterChange) {
  5283. self.options.afterChange.call(self);
  5284. }
  5285. });
  5286. edit.textarea.keyup(function(e) {
  5287. if(!e.ctrlKey && !e.altKey && _INPUT_KEY_MAP[e.which]) {
  5288. if(self.options.afterChange) {
  5289. self.options.afterChange.call(self);
  5290. }
  5291. }
  5292. });
  5293. if(self.readonlyMode) {
  5294. self.readonly();
  5295. }
  5296. self.isCreated = true;
  5297. if(self.initContent === '') {
  5298. self.initContent = self.html();
  5299. }
  5300. if(self._undoStack.length > 0) {
  5301. var prev = self._undoStack.pop();
  5302. if(prev.start) {
  5303. self.html(prev.html);
  5304. edit.cmd.range.moveToBookmark(prev);
  5305. self.select();
  5306. }
  5307. }
  5308. self.afterCreate();
  5309. if(self.options.afterCreate) {
  5310. self.options.afterCreate.call(self);
  5311. }
  5312. self.container.removeClass('ke-loading');
  5313. }
  5314. });
  5315. // statusbar.removeClass('statusbar').addClass('ke-statusbar')
  5316. // .append('<span class="ke-inline-block ke-statusbar-center-icon"></span>')
  5317. // .append('<span class="ke-inline-block ke-statusbar-right-icon"></span>');
  5318. statusbar.removeClass('statusbar').addClass('ke-statusbar')
  5319. .append('<i class="ke-statusbar-resize-icon"></i>');
  5320. if(self._fullscreenResizeHandler) {
  5321. K(window).unbind('resize', self._fullscreenResizeHandler);
  5322. self._fullscreenResizeHandler = null;
  5323. }
  5324. function initResize() {
  5325. if(statusbar.height() === 0) {
  5326. setTimeout(initResize, 100);
  5327. return;
  5328. }
  5329. self.resize(width, height, false);
  5330. }
  5331. initResize();
  5332. if(fullscreenMode) {
  5333. self._fullscreenResizeHandler = function(e) {
  5334. if(self.isCreated) {
  5335. self.resize(_docElement().clientWidth, _docElement().clientHeight, false);
  5336. }
  5337. };
  5338. K(window).bind('resize', self._fullscreenResizeHandler);
  5339. toolbar.select('fullscreen');
  5340. // statusbar.first().css('visibility', 'hidden');
  5341. // statusbar.last().css('visibility', 'hidden');
  5342. } else {
  5343. if(_GECKO) {
  5344. K(window).bind('scroll', function(e) {
  5345. self._scrollPos = _getScrollPos();
  5346. });
  5347. }
  5348. if(self.resizeType > 0) {
  5349. _drag({
  5350. moveEl: container,
  5351. clickEl: statusbar,
  5352. moveFn: function(x, y, width, height, diffX, diffY) {
  5353. height += diffY;
  5354. self.resize(null, height);
  5355. }
  5356. });
  5357. } else {
  5358. // statusbar.first().css('visibility', 'hidden');
  5359. }
  5360. if(self.resizeType === 2) {
  5361. _drag({
  5362. moveEl: container,
  5363. clickEl: statusbar.last(),
  5364. moveFn: function(x, y, width, height, diffX, diffY) {
  5365. width += diffX;
  5366. height += diffY;
  5367. self.resize(width, height);
  5368. }
  5369. });
  5370. } else {
  5371. // statusbar.last().css('visibility', 'hidden');
  5372. }
  5373. }
  5374. return self;
  5375. },
  5376. remove: function() {
  5377. var self = this;
  5378. if(!self.isCreated) {
  5379. return self;
  5380. }
  5381. self.beforeRemove();
  5382. self.srcElement.data('kindeditor', '');
  5383. if(self.menu) {
  5384. self.hideMenu();
  5385. }
  5386. _each(self.dialogs, function() {
  5387. self.hideDialog();
  5388. });
  5389. K(document).unbind('mousedown', self._docMousedownFn);
  5390. self.toolbar.remove();
  5391. self.edit.remove();
  5392. self.statusbar.last().unbind();
  5393. self.statusbar.unbind();
  5394. self.container.remove();
  5395. self.container = self.toolbar = self.edit = self.menu = null;
  5396. self.dialogs = [];
  5397. self.isCreated = false;
  5398. return self;
  5399. },
  5400. resize: function(width, height, updateProp) {
  5401. var self = this;
  5402. updateProp = _undef(updateProp, true);
  5403. if(width) {
  5404. if(!/%/.test(width)) {
  5405. width = _removeUnit(width);
  5406. width = width < self.minWidth ? self.minWidth : width;
  5407. }
  5408. self.container.css('width', _addUnit(width));
  5409. if(updateProp) {
  5410. self.width = _addUnit(width);
  5411. }
  5412. }
  5413. if(height) {
  5414. height = _removeUnit(height);
  5415. editHeight = _removeUnit(height) - self.toolbar.div.height() - self.statusbar.height();
  5416. editHeight = editHeight < self.minHeight ? self.minHeight : editHeight;
  5417. self.edit.setHeight(editHeight);
  5418. if(updateProp) {
  5419. self.height = _addUnit(height);
  5420. }
  5421. }
  5422. return self;
  5423. },
  5424. select: function() {
  5425. this.isCreated && this.cmd.select();
  5426. return this;
  5427. },
  5428. html: function(val) {
  5429. var self = this;
  5430. if(val === undefined) {
  5431. return self.isCreated ? self.edit.html() : _elementVal(self.srcElement);
  5432. }
  5433. self.isCreated ? self.edit.html(val) : _elementVal(self.srcElement, val);
  5434. if(self.isCreated) {
  5435. self.cmd.selection();
  5436. }
  5437. return self;
  5438. },
  5439. fullHtml: function() {
  5440. return this.isCreated ? this.edit.html(undefined, true) : '';
  5441. },
  5442. text: function(val) {
  5443. var self = this;
  5444. if(val === undefined) {
  5445. return _trim(self.html().replace(/<(?!img|embed).*?>/ig, '').replace(/&nbsp;/ig, ' '));
  5446. } else {
  5447. return self.html(_escape(val));
  5448. }
  5449. },
  5450. isEmpty: function() {
  5451. return _trim(this.text().replace(/\r\n|\n|\r/, '')) === '';
  5452. },
  5453. isDirty: function() {
  5454. return _trim(this.initContent.replace(/\r\n|\n|\r|t/g, '')) !== _trim(this.html().replace(/\r\n|\n|\r|t/g, ''));
  5455. },
  5456. selectedHtml: function() {
  5457. var val = this.isCreated ? this.cmd.range.html() : '';
  5458. val = _removeBookmarkTag(_removeTempTag(val));
  5459. return val;
  5460. },
  5461. count: function(mode) {
  5462. var self = this;
  5463. mode = (mode || 'html').toLowerCase();
  5464. if(mode === 'html') {
  5465. return self.html().length;
  5466. }
  5467. if(mode === 'text') {
  5468. return self.text().replace(/<(?:img|embed).*?>/ig, 'K').replace(/\r\n|\n|\r/g, '').length;
  5469. }
  5470. return 0;
  5471. },
  5472. exec: function(key) {
  5473. key = key.toLowerCase();
  5474. var self = this,
  5475. cmd = self.cmd,
  5476. changeFlag = _inArray(key, 'selectall,copy,paste,print'.split(',')) < 0;
  5477. if(changeFlag) {
  5478. self.addBookmark(false);
  5479. }
  5480. cmd[key].apply(cmd, _toArray(arguments, 1));
  5481. if(changeFlag) {
  5482. self.updateState();
  5483. self.addBookmark(false);
  5484. if(self.options.afterChange) {
  5485. self.options.afterChange.call(self);
  5486. }
  5487. }
  5488. return self;
  5489. },
  5490. insertHtml: function(val, quickMode) {
  5491. if(!this.isCreated) {
  5492. return this;
  5493. }
  5494. val = this.beforeSetHtml(val);
  5495. this.exec('inserthtml', val, quickMode);
  5496. return this;
  5497. },
  5498. appendHtml: function(val) {
  5499. this.html(this.html() + val);
  5500. if(this.isCreated) {
  5501. var cmd = this.cmd;
  5502. cmd.range.selectNodeContents(cmd.doc.body).collapse(false);
  5503. cmd.select();
  5504. }
  5505. return this;
  5506. },
  5507. sync: function() {
  5508. _elementVal(this.srcElement, this.html());
  5509. return this;
  5510. },
  5511. focus: function() {
  5512. this.isCreated ? this.edit.focus() : this.srcElement[0].focus();
  5513. return this;
  5514. },
  5515. blur: function() {
  5516. this.isCreated ? this.edit.blur() : this.srcElement[0].blur();
  5517. return this;
  5518. },
  5519. addBookmark: function(checkSize) {
  5520. checkSize = _undef(checkSize, true);
  5521. var self = this,
  5522. edit = self.edit,
  5523. body = edit.doc.body,
  5524. html = _removeTempTag(body.innerHTML),
  5525. bookmark;
  5526. if(checkSize && self._undoStack.length > 0) {
  5527. var prev = self._undoStack[self._undoStack.length - 1];
  5528. if(Math.abs(html.length - _removeBookmarkTag(prev.html).length) < self.minChangeSize) {
  5529. return self;
  5530. }
  5531. }
  5532. if(edit.designMode && !self._firstAddBookmark) {
  5533. var range = self.cmd.range;
  5534. bookmark = range.createBookmark(true);
  5535. bookmark.html = _removeTempTag(body.innerHTML);
  5536. range.moveToBookmark(bookmark);
  5537. } else {
  5538. bookmark = {
  5539. html: html
  5540. };
  5541. }
  5542. self._firstAddBookmark = false;
  5543. _addBookmarkToStack(self._undoStack, bookmark);
  5544. return self;
  5545. },
  5546. undo: function() {
  5547. return _undoToRedo.call(this, this._undoStack, this._redoStack);
  5548. },
  5549. redo: function() {
  5550. return _undoToRedo.call(this, this._redoStack, this._undoStack);
  5551. },
  5552. fullscreen: function(bool) {
  5553. this.fullscreenMode = (bool === undefined ? !this.fullscreenMode : bool);
  5554. this.addBookmark(false);
  5555. return this.remove().create();
  5556. },
  5557. readonly: function(isReadonly) {
  5558. isReadonly = _undef(isReadonly, true);
  5559. var self = this,
  5560. edit = self.edit,
  5561. doc = edit.doc;
  5562. if(self.designMode) {
  5563. self.toolbar.disableAll(isReadonly, []);
  5564. } else {
  5565. _each(self.noDisableItems, function() {
  5566. self.toolbar[isReadonly ? 'disable' : 'enable'](this);
  5567. });
  5568. }
  5569. if(_IE) {
  5570. doc.body.contentEditable = !isReadonly;
  5571. } else {
  5572. doc.designMode = isReadonly ? 'off' : 'on';
  5573. }
  5574. edit.textarea[0].disabled = isReadonly;
  5575. },
  5576. createMenu: function(options) {
  5577. var self = this,
  5578. name = options.name,
  5579. knode = self.toolbar.get(name),
  5580. pos = knode.pos();
  5581. options.x = pos.x;
  5582. options.y = pos.y + knode.height();
  5583. options.z = self.options.zIndex;
  5584. options.shadowMode = _undef(options.shadowMode, self.shadowMode);
  5585. if(options.selectedColor !== undefined) {
  5586. options.cls = 'ke-colorpicker-' + self.themeType;
  5587. options.noColor = self.lang('noColor');
  5588. self.menu = _colorpicker(options);
  5589. } else {
  5590. options.cls = 'ke-menu-' + self.themeType;
  5591. options.centerLineMode = false;
  5592. self.menu = _menu(options);
  5593. }
  5594. return self.menu;
  5595. },
  5596. hideMenu: function() {
  5597. this.menu.remove();
  5598. this.menu = null;
  5599. return this;
  5600. },
  5601. hideContextmenu: function() {
  5602. this.contextmenu.remove();
  5603. this.contextmenu = null;
  5604. return this;
  5605. },
  5606. createDialog: function(options) {
  5607. var self = this,
  5608. name = options.name;
  5609. options.z = self.options.zIndex;
  5610. options.shadowMode = _undef(options.shadowMode, self.shadowMode);
  5611. options.closeBtn = _undef(options.closeBtn, {
  5612. name: self.lang('close'),
  5613. click: function(e) {
  5614. self.hideDialog();
  5615. if(_IE && self.cmd) {
  5616. self.cmd.select();
  5617. }
  5618. }
  5619. });
  5620. options.noBtn = _undef(options.noBtn, {
  5621. name: self.lang(options.yesBtn ? 'no' : 'close'),
  5622. click: function(e) {
  5623. self.hideDialog();
  5624. if(_IE && self.cmd) {
  5625. self.cmd.select();
  5626. }
  5627. }
  5628. });
  5629. if(self.dialogAlignType != 'page') {
  5630. options.alignEl = self.container;
  5631. }
  5632. options.cls = 'ke-dialog-' + self.themeType;
  5633. if(self.dialogs.length > 0) {
  5634. var firstDialog = self.dialogs[0],
  5635. parentDialog = self.dialogs[self.dialogs.length - 1];
  5636. firstDialog.setMaskIndex(parentDialog.z + 2);
  5637. options.z = parentDialog.z + 3;
  5638. options.showMask = false;
  5639. }
  5640. var dialog = _dialog(options);
  5641. self.dialogs.push(dialog);
  5642. return dialog;
  5643. },
  5644. hideDialog: function() {
  5645. var self = this;
  5646. if(self.dialogs.length > 0) {
  5647. self.dialogs.pop().remove();
  5648. }
  5649. if(self.dialogs.length > 0) {
  5650. var firstDialog = self.dialogs[0],
  5651. parentDialog = self.dialogs[self.dialogs.length - 1];
  5652. firstDialog.setMaskIndex(parentDialog.z - 1);
  5653. }
  5654. return self;
  5655. },
  5656. errorDialog: function(html) {
  5657. var self = this;
  5658. var dialog = self.createDialog({
  5659. width: 750,
  5660. title: self.lang('uploadError'),
  5661. body: '<div style="padding:10px 20px;"><iframe frameborder="0" style="width:708px;height:400px;"></iframe></div>'
  5662. });
  5663. var iframe = K('iframe', dialog.div),
  5664. doc = K.iframeDoc(iframe);
  5665. doc.open();
  5666. doc.write(html);
  5667. doc.close();
  5668. K(doc.body).css('background-color', '#FFF');
  5669. iframe[0].contentWindow.focus();
  5670. return self;
  5671. }
  5672. };
  5673. function _editor(options) {
  5674. return new KEditor(options);
  5675. }
  5676. _instances = [];
  5677. function _create(expr, options) {
  5678. options = options || {};
  5679. options.basePath = _undef(options.basePath, K.basePath);
  5680. options.themesPath = _undef(options.themesPath, options.basePath + 'themes/');
  5681. options.langPath = _undef(options.langPath, options.basePath + 'lang/');
  5682. options.pluginsPath = _undef(options.pluginsPath, options.basePath + 'plugins/');
  5683. if(_undef(options.loadStyleMode, K.options.loadStyleMode)) {
  5684. _loadStyle(_undef(options.styleCssPath, options.basePath + '/kindeditor.min.css'));
  5685. var themeType = _undef(options.themeType, K.options.themeType);
  5686. if (themeType && themeType !== 'default') {
  5687. _loadStyle(options.themesPath + themeType + '/' + themeType + '.css');
  5688. }
  5689. }
  5690. function create(editor) {
  5691. _each(_plugins, function(name, fn) {
  5692. if(_isFunction(fn)) {
  5693. fn.call(editor, KindEditor);
  5694. }
  5695. });
  5696. return editor.create();
  5697. }
  5698. var knode = K(expr);
  5699. if(!knode || knode.length === 0) {
  5700. return;
  5701. }
  5702. if(knode.length > 1) {
  5703. knode.each(function() {
  5704. _create(this, options);
  5705. });
  5706. return _instances[0];
  5707. }
  5708. options.srcElement = knode[0];
  5709. var editor = new KEditor(options);
  5710. _instances.push(editor);
  5711. if(_language[editor.langType]) {
  5712. return create(editor);
  5713. }
  5714. _loadScript(editor.langPath + editor.langType + '.js?ver=' + encodeURIComponent(K.DEBUG ? _TIME : _VERSION), function() {
  5715. create(editor);
  5716. });
  5717. // todo: Check plugins directory
  5718. return editor;
  5719. }
  5720. function _eachEditor(expr, fn) {
  5721. K(expr).each(function(i, el) {
  5722. K.each(_instances, function(j, editor) {
  5723. if(editor && editor.srcElement[0] == el) {
  5724. fn.call(editor, j);
  5725. return false;
  5726. }
  5727. });
  5728. });
  5729. }
  5730. K.remove = function(expr) {
  5731. _eachEditor(expr, function(i) {
  5732. this.remove();
  5733. _instances.splice(i, 1);
  5734. });
  5735. };
  5736. K.sync = function(expr) {
  5737. _eachEditor(expr, function() {
  5738. this.sync();
  5739. });
  5740. };
  5741. K.html = function(expr, val) {
  5742. _eachEditor(expr, function() {
  5743. this.html(val);
  5744. });
  5745. };
  5746. K.insertHtml = function(expr, val) {
  5747. _eachEditor(expr, function() {
  5748. this.insertHtml(val);
  5749. });
  5750. };
  5751. K.appendHtml = function(expr, val) {
  5752. _eachEditor(expr, function() {
  5753. this.appendHtml(val);
  5754. });
  5755. };
  5756. if(_IE && _V < 7) {
  5757. _nativeCommand(document, 'BackgroundImageCache', true);
  5758. }
  5759. K.EditorClass = KEditor;
  5760. K.editor = _editor;
  5761. K.create = _create;
  5762. K.instances = _instances;
  5763. K.plugin = _plugin;
  5764. K.lang = _lang;
  5765. _plugin('core', function(K) {
  5766. var self = this,
  5767. shortcutKeys = {
  5768. undo: 'Z',
  5769. redo: 'Y',
  5770. bold: 'B',
  5771. italic: 'I',
  5772. underline: 'U',
  5773. print: 'P',
  5774. selectall: 'A'
  5775. };
  5776. self.afterSetHtml(function() {
  5777. if(self.options.afterChange) {
  5778. self.options.afterChange.call(self);
  5779. }
  5780. });
  5781. self.afterCreate(function() {
  5782. if(self.syncType != 'form') {
  5783. return;
  5784. }
  5785. var el = K(self.srcElement),
  5786. hasForm = false;
  5787. while((el = el.parent())) {
  5788. if(el.name == 'form') {
  5789. hasForm = true;
  5790. break;
  5791. }
  5792. }
  5793. if(hasForm) {
  5794. el.bind('submit', function(e) {
  5795. self.sync();
  5796. K(window).bind('unload', function() {
  5797. self.edit.textarea.remove();
  5798. });
  5799. });
  5800. var resetBtn = K('[type="reset"]', el);
  5801. resetBtn.click(function() {
  5802. self.html(self.initContent);
  5803. self.cmd.selection();
  5804. });
  5805. self.beforeRemove(function() {
  5806. el.unbind();
  5807. resetBtn.unbind();
  5808. });
  5809. }
  5810. });
  5811. self.clickToolbar('source', function() {
  5812. if(self.edit.designMode) {
  5813. self.toolbar.disableAll(true);
  5814. self.edit.design(false);
  5815. self.toolbar.select('source');
  5816. } else {
  5817. self.toolbar.disableAll(false);
  5818. self.edit.design(true);
  5819. self.toolbar.unselect('source');
  5820. if(_GECKO) {
  5821. setTimeout(function() {
  5822. self.cmd.selection();
  5823. }, 0);
  5824. } else {
  5825. self.cmd.selection();
  5826. }
  5827. }
  5828. self.designMode = self.edit.designMode;
  5829. });
  5830. self.afterCreate(function() {
  5831. if(!self.designMode) {
  5832. self.toolbar.disableAll(true).select('source');
  5833. }
  5834. });
  5835. self.clickToolbar('fullscreen', function() {
  5836. self.fullscreen();
  5837. });
  5838. if(self.fullscreenShortcut) {
  5839. var loaded = false;
  5840. self.afterCreate(function() {
  5841. K(self.edit.doc, self.edit.textarea).keyup(function(e) {
  5842. if(e.which == 27) {
  5843. setTimeout(function() {
  5844. self.fullscreen();
  5845. }, 0);
  5846. }
  5847. });
  5848. if(loaded) {
  5849. if(_IE && !self.designMode) {
  5850. return;
  5851. }
  5852. self.focus();
  5853. }
  5854. if(!loaded) {
  5855. loaded = true;
  5856. }
  5857. });
  5858. }
  5859. _each('undo,redo'.split(','), function(i, name) {
  5860. if(shortcutKeys[name]) {
  5861. self.afterCreate(function() {
  5862. _ctrl(this.edit.doc, shortcutKeys[name], function() {
  5863. self.clickToolbar(name);
  5864. });
  5865. });
  5866. }
  5867. self.clickToolbar(name, function() {
  5868. self[name]();
  5869. });
  5870. });
  5871. self.clickToolbar('formatblock', function() {
  5872. var blocks = self.lang('formatblock.formatBlock'),
  5873. heights = {
  5874. h1: 28,
  5875. h2: 24,
  5876. h3: 18,
  5877. H4: 14,
  5878. p: 12
  5879. },
  5880. curVal = self.cmd.val('formatblock'),
  5881. menu = self.createMenu({
  5882. name: 'formatblock',
  5883. width: self.langType == 'en' ? 200 : 150
  5884. });
  5885. _each(blocks, function(key, val) {
  5886. var style = 'font-size:' + heights[key] + 'px;';
  5887. if(key.charAt(0) === 'h') {
  5888. style += 'font-weight:bold;';
  5889. }
  5890. menu.addItem({
  5891. title: '<span style="' + style + '" unselectable="on">' + val + '</span>',
  5892. height: heights[key] + 12,
  5893. checked: (curVal === key || curVal === val),
  5894. click: function() {
  5895. self.select().exec('formatblock', '<' + key + '>').hideMenu();
  5896. }
  5897. });
  5898. });
  5899. });
  5900. self.clickToolbar('fontname', function() {
  5901. var curVal = self.cmd.val('fontname'),
  5902. menu = self.createMenu({
  5903. name: 'fontname',
  5904. width: 150
  5905. });
  5906. _each(self.lang('fontname.fontName'), function(key, val) {
  5907. menu.addItem({
  5908. title: '<span style="font-family: ' + key + ';" unselectable="on">' + val + '</span>',
  5909. checked: (curVal === key.toLowerCase() || curVal === val.toLowerCase()),
  5910. click: function() {
  5911. self.exec('fontname', key).hideMenu();
  5912. }
  5913. });
  5914. });
  5915. });
  5916. self.clickToolbar('fontsize', function() {
  5917. var curVal = self.cmd.val('fontsize'),
  5918. menu = self.createMenu({
  5919. name: 'fontsize',
  5920. width: 150
  5921. });
  5922. _each(self.fontSizeTable, function(i, val) {
  5923. menu.addItem({
  5924. title: '<span style="font-size:' + val + ';" unselectable="on">' + val + '</span>',
  5925. height: _removeUnit(val) + 12,
  5926. checked: curVal === val,
  5927. click: function() {
  5928. self.exec('fontsize', val).hideMenu();
  5929. }
  5930. });
  5931. });
  5932. });
  5933. _each('forecolor,hilitecolor'.split(','), function(i, name) {
  5934. self.clickToolbar(name, function() {
  5935. self.createMenu({
  5936. name: name,
  5937. selectedColor: self.cmd.val(name) || 'default',
  5938. colors: self.colorTable,
  5939. click: function(color) {
  5940. self.exec(name, color).hideMenu();
  5941. }
  5942. });
  5943. });
  5944. });
  5945. _each(('cut,copy,paste').split(','), function(i, name) {
  5946. self.clickToolbar(name, function() {
  5947. self.focus();
  5948. try {
  5949. self.exec(name, null);
  5950. } catch(e) {
  5951. alert(self.lang(name + 'Error'));
  5952. }
  5953. });
  5954. });
  5955. self.clickToolbar('about', function() {
  5956. var html = '<div style="margin:20px;">' +
  5957. '<div>KindEditor ' + _VERSION + '</div>' +
  5958. '<div>Copyright &copy; <a href="http://www.kindsoft.net/" target="_blank">kindsoft.net</a> All rights reserved.</div>' +
  5959. '</div>';
  5960. self.createDialog({
  5961. name: 'about',
  5962. width: 350,
  5963. title: self.lang('about'),
  5964. body: html
  5965. });
  5966. });
  5967. self.plugin.getSelectedLink = function() {
  5968. return self.cmd.commonAncestor('a');
  5969. };
  5970. self.plugin.getSelectedImage = function() {
  5971. return _getImageFromRange(self.edit.cmd.range, function(img) {
  5972. return !/^ke-\w+$/i.test(img[0].className);
  5973. });
  5974. };
  5975. self.plugin.getSelectedFlash = function() {
  5976. return _getImageFromRange(self.edit.cmd.range, function(img) {
  5977. return img[0].className == 'ke-flash';
  5978. });
  5979. };
  5980. self.plugin.getSelectedMedia = function() {
  5981. return _getImageFromRange(self.edit.cmd.range, function(img) {
  5982. return img[0].className == 'ke-media' || img[0].className == 'ke-video' || img[0].className == 'ke-audio';
  5983. });
  5984. };
  5985. self.plugin.getSelectedAnchor = function() {
  5986. return _getImageFromRange(self.edit.cmd.range, function(img) {
  5987. return img[0].className == 'ke-anchor';
  5988. });
  5989. };
  5990. _each('link,image,flash,media,anchor'.split(','), function(i, name) {
  5991. var uName = name.charAt(0).toUpperCase() + name.substr(1);
  5992. _each('edit,delete'.split(','), function(j, val) {
  5993. self.addContextmenu({
  5994. title: self.lang(val + uName),
  5995. click: function() {
  5996. self.loadPlugin(name, function() {
  5997. self.plugin[name][val]();
  5998. self.hideMenu();
  5999. });
  6000. },
  6001. cond: self.plugin['getSelected' + uName],
  6002. width: 150,
  6003. iconClass: val == 'edit' ? 'ke-icon-' + name : undefined
  6004. });
  6005. });
  6006. self.addContextmenu({
  6007. title: '-'
  6008. });
  6009. });
  6010. self.addContextmenu({
  6011. title: '-'
  6012. });
  6013. _each(('selectall,justifyleft,justifycenter,justifyright,justifyfull,insertorderedlist,' +
  6014. 'insertunorderedlist,indent,outdent,subscript,superscript,hr,print,' +
  6015. 'bold,italic,underline,strikethrough,removeformat,unlink').split(','), function(i, name) {
  6016. if(shortcutKeys[name]) {
  6017. self.afterCreate(function() {
  6018. _ctrl(this.edit.doc, shortcutKeys[name], function() {
  6019. self.cmd.selection();
  6020. self.clickToolbar(name);
  6021. });
  6022. });
  6023. }
  6024. self.clickToolbar(name, function() {
  6025. self.focus().exec(name, null);
  6026. });
  6027. });
  6028. self.afterCreate(function() {
  6029. var doc = self.edit.doc,
  6030. cmd, bookmark, div,
  6031. cls = '__kindeditor_paste__',
  6032. pasting = false;
  6033. function movePastedData() {
  6034. cmd.range.moveToBookmark(bookmark);
  6035. cmd.select();
  6036. if(_WEBKIT) {
  6037. K('div.' + cls, div).each(function() {
  6038. K(this).after('<br />').remove(true);
  6039. });
  6040. K('span.Apple-style-span', div).remove(true);
  6041. K('span.Apple-tab-span', div).remove(true);
  6042. K('span[style]', div).each(function() {
  6043. if(K(this).css('white-space') == 'nowrap') {
  6044. K(this).remove(true);
  6045. }
  6046. });
  6047. K('meta', div).remove();
  6048. }
  6049. var html = div[0].innerHTML;
  6050. div.remove();
  6051. if(html === '') {
  6052. return;
  6053. }
  6054. if(_WEBKIT) {
  6055. html = html.replace(/(<br>)\1/ig, '$1');
  6056. }
  6057. if(self.pasteType === 2) {
  6058. html = html.replace(/(<(?:p|p\s[^>]*)>) *(<\/p>)/ig, '');
  6059. if(/schemas-microsoft-com|worddocument|mso-\w+/i.test(html)) {
  6060. html = _clearMsWord(html, self.filterMode ? self.htmlTags : K.options.htmlTags);
  6061. } else {
  6062. html = _formatHtml(html, self.filterMode ? self.htmlTags : null);
  6063. html = self.beforeSetHtml(html);
  6064. }
  6065. }
  6066. if(self.pasteType === 1) {
  6067. html = html.replace(/&nbsp;/ig, ' ');
  6068. html = html.replace(/\n\s*\n/g, '\n');
  6069. html = html.replace(/<br[^>]*>/ig, '\n');
  6070. html = html.replace(/<\/p><p[^>]*>/ig, '\n');
  6071. html = html.replace(/<[^>]+>/g, '');
  6072. html = html.replace(/ {2}/g, ' &nbsp;');
  6073. if(self.newlineTag == 'p') {
  6074. if(/\n/.test(html)) {
  6075. html = html.replace(/^/, '<p>').replace(/$/, '<br /></p>').replace(/\n/g, '<br /></p><p>');
  6076. }
  6077. } else {
  6078. html = html.replace(/\n/g, '<br />$&');
  6079. }
  6080. }
  6081. self.insertHtml(html, true);
  6082. }
  6083. K(doc.body).bind('paste', function(e) {
  6084. if(self.pasteType === 0) {
  6085. e.stop();
  6086. return;
  6087. }
  6088. if(pasting) {
  6089. return;
  6090. }
  6091. pasting = true;
  6092. K('div.' + cls, doc).remove();
  6093. cmd = self.cmd.selection();
  6094. bookmark = cmd.range.createBookmark();
  6095. div = K('<div class="' + cls + '"></div>', doc).css({
  6096. position: 'absolute',
  6097. width: '1px',
  6098. height: '1px',
  6099. overflow: 'hidden',
  6100. left: '-1981px',
  6101. top: K(bookmark.start).pos().y + 'px',
  6102. 'white-space': 'nowrap'
  6103. });
  6104. K(doc.body).append(div);
  6105. if(_IE) {
  6106. var rng = cmd.range.get(true);
  6107. rng.moveToElementText(div[0]);
  6108. rng.select();
  6109. rng.execCommand('paste');
  6110. e.preventDefault();
  6111. } else {
  6112. cmd.range.selectNodeContents(div[0]);
  6113. cmd.select();
  6114. div[0].tabIndex = -1;
  6115. div[0].focus();
  6116. }
  6117. setTimeout(function() {
  6118. movePastedData();
  6119. pasting = false;
  6120. }, 0);
  6121. });
  6122. });
  6123. self.beforeGetHtml(function(html) {
  6124. if(_IE && _V <= 8) {
  6125. html = html.replace(/<div\s+[^>]*data-ke-input-tag="([^"]*)"[^>]*>([\s\S]*?)<\/div>/ig, function(full, tag) {
  6126. return unescape(tag);
  6127. });
  6128. html = html.replace(/(<input)((?:\s+[^>]*)?>)/ig, function($0, $1, $2) {
  6129. if(!/\s+type="[^"]+"/i.test($0)) {
  6130. return $1 + ' type="text"' + $2;
  6131. }
  6132. return $0;
  6133. });
  6134. }
  6135. return html.replace(/(<(?:noscript|noscript\s[^>]*)>)([\s\S]*?)(<\/noscript>)/ig, function($0, $1, $2, $3) {
  6136. return $1 + _unescape($2).replace(/\s+/g, ' ') + $3;
  6137. })
  6138. .replace(/<img[^>]*class="?ke-(media|video|audio)"?[^>]*>/ig, function(full, $1) {
  6139. var imgAttrs = _getAttrList(full);
  6140. var styles = _getCssList(imgAttrs.style || '');
  6141. var attrs = _mediaAttrs(imgAttrs['data-ke-tag']);
  6142. var width = _undef(styles.width, '');
  6143. var height = _undef(styles.height, '');
  6144. if(/px/i.test(width)) {
  6145. width = _removeUnit(width);
  6146. }
  6147. if(/px/i.test(height)) {
  6148. height = _removeUnit(height);
  6149. }
  6150. attrs.width = _undef(imgAttrs.width, width);
  6151. attrs.height = _undef(imgAttrs.height, height);
  6152. return _mediaEmbed(attrs, $1);
  6153. })
  6154. .replace(/<img[^>]*class="?ke-anchor"?[^>]*>/ig, function(full) {
  6155. var imgAttrs = _getAttrList(full);
  6156. return '<a name="' + unescape(imgAttrs['data-ke-name']) + '"></a>';
  6157. })
  6158. .replace(/<div\s+[^>]*data-ke-script-attr="([^"]*)"[^>]*>([\s\S]*?)<\/div>/ig, function(full, attr, code) {
  6159. return '<script' + unescape(attr) + '>' + unescape(code) + '</script>';
  6160. })
  6161. .replace(/<div\s+[^>]*data-ke-noscript-attr="([^"]*)"[^>]*>([\s\S]*?)<\/div>/ig, function(full, attr, code) {
  6162. return '<noscript' + unescape(attr) + '>' + unescape(code) + '</noscript>';
  6163. })
  6164. .replace(/(<[^>]*)data-ke-src="([^"]*)"([^>]*>)/ig, function(full, start, src, end) {
  6165. full = full.replace(/(\s+(?:href|src)=")[^"]*(")/i, function($0, $1, $2) {
  6166. return $1 + _unescape(src) + $2;
  6167. });
  6168. full = full.replace(/\s+data-ke-src="[^"]*"/i, '');
  6169. return full;
  6170. })
  6171. .replace(/(<[^>]+\s)data-ke-(on\w+="[^"]*"[^>]*>)/ig, function(full, start, end) {
  6172. return start + end;
  6173. });
  6174. });
  6175. self.beforeSetHtml(function(html) {
  6176. if(_IE && _V <= 8) {
  6177. html = html.replace(/<input[^>]*>|<(select|button)[^>]*>[\s\S]*?<\/\1>/ig, function(full) {
  6178. var attrs = _getAttrList(full);
  6179. var styles = _getCssList(attrs.style || '');
  6180. if(styles.display == 'none') {
  6181. return '<div class="ke-display-none" data-ke-input-tag="' + escape(full) + '"></div>';
  6182. }
  6183. return full;
  6184. });
  6185. }
  6186. return html.replace(/<embed[^>]*type="([^"]+)"[^>]*>(?:<\/embed>)?/ig, function(full) {
  6187. var attrs = _getAttrList(full);
  6188. attrs.src = _undef(attrs.src, '');
  6189. attrs.width = _undef(attrs.width, 0);
  6190. attrs.height = _undef(attrs.height, 0);
  6191. return _mediaImg(self.themesPath + 'common/blank.gif', attrs);
  6192. })
  6193. .replace(/<(video|audio)[^>]*>((\s*<source [^>]*>\s*)*)(?:<\/(video|audio)>)?/ig, function(full, $1, $2) {
  6194. var attrs = _getAttrList($2 ? full.replace($2, '') : full);
  6195. if($2) {
  6196. var srcs = [];
  6197. $($2).filter('source').each(function() {
  6198. var $source = $(this);
  6199. var src = $source.attr('src');
  6200. var type = $source.attr('type');
  6201. if(type) src += '#' + type;
  6202. srcs.push(src);
  6203. });
  6204. attrs.src = srcs.join(',');
  6205. } else {
  6206. attrs.src = _undef(attrs.src, '');
  6207. }
  6208. attrs.width = _undef(attrs.width, 0);
  6209. attrs.height = _undef(attrs.height, 0);
  6210. attrs.type = $1;
  6211. return _mediaImg(self.themesPath + 'common/blank.gif', attrs);
  6212. })
  6213. .replace(/<a[^>]*name="([^"]+)"[^>]*>(?:<\/a>)?/ig, function(full) {
  6214. var attrs = _getAttrList(full);
  6215. if(attrs.href !== undefined) {
  6216. return full;
  6217. }
  6218. return '<img class="ke-anchor" src="' + self.themesPath + 'common/anchor.gif" data-ke-name="' + escape(attrs.name) + '" />';
  6219. })
  6220. .replace(/<script([^>]*)>([\s\S]*?)<\/script>/ig, function(full, attr, code) {
  6221. return '<div class="ke-script" data-ke-script-attr="' + escape(attr) + '">' + escape(code) + '</div>';
  6222. })
  6223. .replace(/<noscript([^>]*)>([\s\S]*?)<\/noscript>/ig, function(full, attr, code) {
  6224. return '<div class="ke-noscript" data-ke-noscript-attr="' + escape(attr) + '">' + escape(code) + '</div>';
  6225. })
  6226. .replace(/(<[^>]*)(href|src)="([^"]*)"([^>]*>)/ig, function(full, start, key, src, end) {
  6227. if(full.match(/\sdata-ke-src="[^"]*"/i)) {
  6228. return full;
  6229. }
  6230. full = start + key + '="' + src + '"' + ' data-ke-src="' + _escape(src) + '"' + end;
  6231. return full;
  6232. })
  6233. .replace(/(<[^>]+\s)(on\w+="[^"]*"[^>]*>)/ig, function(full, start, end) {
  6234. return start + 'data-ke-' + end;
  6235. })
  6236. .replace(/<table[^>]*\s+border="0"[^>]*>/ig, function(full) {
  6237. if(full.indexOf('ke-zeroborder') >= 0) {
  6238. return full;
  6239. }
  6240. return _addClassToTag(full, 'ke-zeroborder');
  6241. });
  6242. });
  6243. });
  6244. })(window);
  6245. /*******************************************************************************
  6246. * KindEditor - WYSIWYG HTML Editor for Internet
  6247. * Copyright (C) 2006-2011 kindsoft.net
  6248. *
  6249. * @author Roddy <luolonghao@gmail.com>
  6250. * @site http://www.kindsoft.net/
  6251. * @licence http://www.kindsoft.net/license.php
  6252. *******************************************************************************/
  6253. KindEditor.lang({
  6254. source: 'HTML代码',
  6255. preview: '预览',
  6256. undo: '后退(Ctrl+Z)',
  6257. redo: '前进(Ctrl+Y)',
  6258. cut: '剪切(Ctrl+X)',
  6259. copy: '复制(Ctrl+C)',
  6260. paste: '粘贴(Ctrl+V)',
  6261. plainpaste: '粘贴为无格式文本',
  6262. wordpaste: '从Word粘贴',
  6263. selectall: '全选(Ctrl+A)',
  6264. justifyleft: '左对齐',
  6265. justifycenter: '居中',
  6266. justifyright: '右对齐',
  6267. justifyfull: '两端对齐',
  6268. insertorderedlist: '编号',
  6269. insertunorderedlist: '项目符号',
  6270. indent: '增加缩进',
  6271. outdent: '减少缩进',
  6272. subscript: '下标',
  6273. superscript: '上标',
  6274. formatblock: '段落',
  6275. fontname: '字体',
  6276. fontsize: '文字大小',
  6277. forecolor: '文字颜色',
  6278. hilitecolor: '文字背景',
  6279. bold: '粗体(Ctrl+B)',
  6280. italic: '斜体(Ctrl+I)',
  6281. underline: '下划线(Ctrl+U)',
  6282. strikethrough: '删除线',
  6283. removeformat: '删除格式',
  6284. image: '图片',
  6285. multiimage: '批量图片上传',
  6286. flash: 'Flash',
  6287. media: '视音频',
  6288. table: '表格',
  6289. tablecell: '单元格',
  6290. hr: '插入横线',
  6291. emoticons: '插入表情',
  6292. link: '超级链接',
  6293. unlink: '取消超级链接',
  6294. fullscreen: '全屏显示',
  6295. about: '关于',
  6296. print: '打印(Ctrl+P)',
  6297. filemanager: '文件空间',
  6298. code: '插入程序代码',
  6299. map: 'Google地图',
  6300. baidumap: '百度地图',
  6301. lineheight: '行距',
  6302. clearhtml: '清理HTML代码',
  6303. pagebreak: '插入分页符',
  6304. quickformat: '一键排版',
  6305. insertfile: '插入文件',
  6306. template: '插入模板',
  6307. anchor: '锚点',
  6308. yes: '确定',
  6309. no: '取消',
  6310. close: '关闭',
  6311. editImage: '图片属性',
  6312. deleteImage: '删除图片',
  6313. editFlash: 'Flash属性',
  6314. deleteFlash: '删除Flash',
  6315. editMedia: '视音频属性',
  6316. deleteMedia: '删除视音频',
  6317. editLink: '超级链接属性',
  6318. deleteLink: '取消超级链接',
  6319. editAnchor: '锚点属性',
  6320. deleteAnchor: '删除锚点',
  6321. tableprop: '表格属性',
  6322. tablecellprop: '单元格属性',
  6323. tableinsert: '插入表格',
  6324. tabledelete: '删除表格',
  6325. tablecolinsertleft: '左侧插入列',
  6326. tablecolinsertright: '右侧插入列',
  6327. tablerowinsertabove: '上方插入行',
  6328. tablerowinsertbelow: '下方插入行',
  6329. tablerowmerge: '向下合并单元格',
  6330. tablecolmerge: '向右合并单元格',
  6331. tablerowsplit: '拆分行',
  6332. tablecolsplit: '拆分列',
  6333. tablecoldelete: '删除列',
  6334. tablerowdelete: '删除行',
  6335. noColor: '无颜色',
  6336. pleaseSelectFile: '请选择文件。',
  6337. invalidImg: "请输入有效的URL地址。\n只允许jpg,gif,bmp,png格式。",
  6338. invalidMedia: "请输入有效的URL地址。\n只允许swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb格式。",
  6339. invalidWidth: "宽度必须为数字。",
  6340. invalidHeight: "高度必须为数字。",
  6341. invalidBorder: "边框必须为数字。",
  6342. invalidUrl: "请输入有效的URL地址。",
  6343. invalidRows: '行数为必选项,只允许输入大于0的数字。',
  6344. invalidCols: '列数为必选项,只允许输入大于0的数字。',
  6345. invalidPadding: '边距必须为数字。',
  6346. invalidSpacing: '间距必须为数字。',
  6347. invalidJson: '服务器发生故障。',
  6348. uploadSuccess: '上传成功。',
  6349. cutError: '您的浏览器安全设置不允许使用剪切操作,请使用快捷键(Ctrl+X)来完成。',
  6350. copyError: '您的浏览器安全设置不允许使用复制操作,请使用快捷键(Ctrl+C)来完成。',
  6351. pasteError: '您的浏览器安全设置不允许使用粘贴操作,请使用快捷键(Ctrl+V)来完成。',
  6352. ajaxLoading: '加载中,请稍候 ...',
  6353. uploadLoading: '上传中,请稍候 ...',
  6354. uploadError: '上传错误',
  6355. 'plainpaste.comment': '请使用快捷键(Ctrl+V)把内容粘贴到下面的方框里。',
  6356. 'wordpaste.comment': '请使用快捷键(Ctrl+V)把内容粘贴到下面的方框里。',
  6357. 'code.pleaseInput': '请输入程序代码。',
  6358. 'link.url': 'URL',
  6359. 'link.linkType': '打开类型',
  6360. 'link.newWindow': '新窗口',
  6361. 'link.selfWindow': '当前窗口',
  6362. 'flash.url': 'URL',
  6363. 'flash.width': '宽度',
  6364. 'flash.height': '高度',
  6365. 'flash.upload': '上传',
  6366. 'flash.viewServer': '文件空间',
  6367. 'media.url': 'URL',
  6368. 'media.urlTip': '多个 URL 使用英文逗号分隔',
  6369. 'media.width': '宽度',
  6370. 'media.height': '高度',
  6371. 'media.autostart': '自动播放',
  6372. 'media.upload': '上传',
  6373. 'media.viewServer': '文件空间',
  6374. 'media.controls': '播放控件',
  6375. 'image.remoteImage': '网络图片',
  6376. 'image.localImage': '本地上传',
  6377. 'image.remoteUrl': '图片地址',
  6378. 'image.localUrl': '上传文件',
  6379. 'image.size': '图片大小',
  6380. 'image.width': '宽',
  6381. 'image.height': '高',
  6382. 'image.resetSize': '重置大小',
  6383. 'image.align': '对齐方式',
  6384. 'image.defaultAlign': '默认方式',
  6385. 'image.leftAlign': '左对齐',
  6386. 'image.rightAlign': '右对齐',
  6387. 'image.imgTitle': '图片说明',
  6388. 'image.upload': '浏览...',
  6389. 'image.viewServer': '图片空间',
  6390. 'multiimage.uploadDesc': '允许用户同时上传<%=uploadLimit%>张图片,单张图片容量不超过<%=sizeLimit%>',
  6391. 'multiimage.startUpload': '开始上传',
  6392. 'multiimage.clearAll': '全部清空',
  6393. 'multiimage.insertAll': '全部插入',
  6394. 'multiimage.queueLimitExceeded': '文件数量超过限制。',
  6395. 'multiimage.fileExceedsSizeLimit': '文件大小超过限制。',
  6396. 'multiimage.zeroByteFile': '无法上传空文件。',
  6397. 'multiimage.invalidFiletype': '文件类型不正确。',
  6398. 'multiimage.unknownError': '发生异常,无法上传。',
  6399. 'multiimage.pending': '等待上传',
  6400. 'multiimage.uploadError': '上传失败',
  6401. 'filemanager.emptyFolder': '空文件夹',
  6402. 'filemanager.moveup': '移到上一级文件夹',
  6403. 'filemanager.viewType': '显示方式:',
  6404. 'filemanager.viewImage': '缩略图',
  6405. 'filemanager.listImage': '详细信息',
  6406. 'filemanager.orderType': '排序方式:',
  6407. 'filemanager.fileName': '名称',
  6408. 'filemanager.fileSize': '大小',
  6409. 'filemanager.fileType': '类型',
  6410. 'insertfile.url': 'URL',
  6411. 'insertfile.title': '文件说明',
  6412. 'insertfile.upload': '上传',
  6413. 'insertfile.viewServer': '文件空间',
  6414. 'table.cells': '单元格数',
  6415. 'table.rows': '行数',
  6416. 'table.cols': '列数',
  6417. 'table.size': '大小',
  6418. 'table.width': '宽度',
  6419. 'table.height': '高度',
  6420. 'table.percent': '%',
  6421. 'table.px': 'px',
  6422. 'table.space': '边距间距',
  6423. 'table.padding': '边距',
  6424. 'table.spacing': '间距',
  6425. 'table.align': '对齐方式',
  6426. 'table.textAlign': '水平对齐',
  6427. 'table.verticalAlign': '垂直对齐',
  6428. 'table.alignDefault': '默认',
  6429. 'table.alignLeft': '左对齐',
  6430. 'table.alignCenter': '居中',
  6431. 'table.alignRight': '右对齐',
  6432. 'table.alignTop': '顶部',
  6433. 'table.alignMiddle': '中部',
  6434. 'table.alignBottom': '底部',
  6435. 'table.alignBaseline': '基线',
  6436. 'table.border': '边框',
  6437. 'table.borderWidth': '边框',
  6438. 'table.borderColor': '颜色',
  6439. 'table.backgroundColor': '背景颜色',
  6440. 'map.address': '地址: ',
  6441. 'map.search': '搜索',
  6442. 'baidumap.address': '地址: ',
  6443. 'baidumap.search': '搜索',
  6444. 'baidumap.insertDynamicMap': '插入动态地图',
  6445. 'anchor.name': '锚点名称',
  6446. 'formatblock.formatBlock': {
  6447. h1: '标题 1',
  6448. h2: '标题 2',
  6449. h3: '标题 3',
  6450. h4: '标题 4',
  6451. p: '正 文'
  6452. },
  6453. 'fontname.fontName': {
  6454. 'SimSun': '宋体',
  6455. 'NSimSun': '新宋体',
  6456. 'FangSong_GB2312': '仿宋_GB2312',
  6457. 'KaiTi_GB2312': '楷体_GB2312',
  6458. 'SimHei': '黑体',
  6459. 'Source Han Sans': '思源黑体',
  6460. 'Source Han Serif': '思源宋体',
  6461. 'Microsoft YaHei': '微软雅黑',
  6462. 'Arial': 'Arial',
  6463. 'Arial Black': 'Arial Black',
  6464. 'Times New Roman': 'Times New Roman',
  6465. 'Courier New': 'Courier New',
  6466. 'Tahoma': 'Tahoma',
  6467. 'Verdana': 'Verdana'
  6468. },
  6469. 'lineheight.lineHeight': [{
  6470. '1': '单倍行距'
  6471. }, {
  6472. '1.5': '1.5倍行距'
  6473. }, {
  6474. '2': '2倍行距'
  6475. }, {
  6476. '2.5': '2.5倍行距'
  6477. }, {
  6478. '3': '3倍行距'
  6479. }],
  6480. 'template.selectTemplate': '可选模板',
  6481. 'template.replaceContent': '替换当前内容',
  6482. 'template.fileList': {
  6483. '1.html': '图片和文字',
  6484. '2.html': '表格',
  6485. '3.html': '项目编号'
  6486. }
  6487. }, 'zh_CN');
  6488. if (window.$ && $.zui && $.zui.getLangData) {
  6489. var langData = $.zui.getLangData('kindeditor');
  6490. if (langData) {
  6491. $.each(langData, function(langName) {
  6492. var data = langData[langName];
  6493. if (langName === 'zh_cn') langName = 'zh_CN';
  6494. else if (langName === 'zh_tw') langName = 'zh_TW';
  6495. KindEditor.lang(data, langName);
  6496. });
  6497. }
  6498. }
  6499. /*******************************************************************************
  6500. * KindEditor - WYSIWYG HTML Editor for Internet
  6501. * Copyright (C) 2006-2011 kindsoft.net
  6502. *
  6503. * @author Roddy <luolonghao@gmail.com>
  6504. * @site http://www.kindsoft.net/
  6505. * @licence http://www.kindsoft.net/license.php
  6506. *******************************************************************************/
  6507. KindEditor.plugin('anchor', function(K) {
  6508. var self = this,
  6509. name = 'anchor',
  6510. lang = self.lang(name + '.');
  6511. self.plugin.anchor = {
  6512. edit: function() {
  6513. var html = ['<div style="padding:20px;">',
  6514. '<div class="ke-dialog-row">',
  6515. '<label for="keName">' + lang.name + '</label>',
  6516. '<input class="ke-input-text" type="text" id="keName" name="name" value="" style="width:100px;" />',
  6517. '</div>',
  6518. '</div>'
  6519. ].join('');
  6520. var dialog = self.createDialog({
  6521. name: name,
  6522. width: 300,
  6523. title: self.lang(name),
  6524. body: html,
  6525. yesBtn: {
  6526. name: self.lang('yes'),
  6527. click: function(e) {
  6528. self.insertHtml('<a name="' + nameBox.val() + '">').hideDialog().focus();
  6529. }
  6530. }
  6531. });
  6532. var div = dialog.div,
  6533. nameBox = K('input[name="name"]', div);
  6534. var img = self.plugin.getSelectedAnchor();
  6535. if(img) {
  6536. nameBox.val(unescape(img.attr('data-ke-name')));
  6537. }
  6538. nameBox[0].focus();
  6539. nameBox[0].select();
  6540. },
  6541. 'delete': function() {
  6542. self.plugin.getSelectedAnchor().remove();
  6543. }
  6544. };
  6545. self.clickToolbar(name, self.plugin.anchor.edit);
  6546. });
  6547. /*******************************************************************************
  6548. * KindEditor - WYSIWYG HTML Editor for Internet
  6549. * Copyright (C) 2006-2011 kindsoft.net
  6550. *
  6551. * @author Roddy <luolonghao@gmail.com>
  6552. * @site http://www.kindsoft.net/
  6553. * @licence http://www.kindsoft.net/license.php
  6554. *******************************************************************************/
  6555. KindEditor.plugin('autoheight', function(K) {
  6556. var self = this;
  6557. if(!self.autoHeightMode) {
  6558. return;
  6559. }
  6560. var edit = self.edit;
  6561. var body = edit.doc.body;
  6562. var minHeight = K.removeUnit(self.height);
  6563. edit.iframe[0].scroll = 'no';
  6564. body.style.overflowY = 'hidden';
  6565. function resetHeight() {
  6566. edit.iframe.height(minHeight);
  6567. self.resize(null, Math.max((K.IE ? body.scrollHeight : body.offsetHeight) + 76, minHeight));
  6568. }
  6569. /*
  6570. * 如何实现真正的自动高度?
  6571. * 修改编辑器高度之后,再次获取body内容高度时,最小值只会是当前iframe的设置高度,这样就导致高度只增不减。
  6572. * 所以每次获取body内容高度之前,先将iframe的高度重置为最小高度,这样就能获取body的实际高度。
  6573. * 由此就实现了真正的自动高度
  6574. * 测试:chrome、firefox、IE9、IE8
  6575. * */
  6576. edit.afterChange(resetHeight);
  6577. if(self.isCreated) {
  6578. resetHeight();
  6579. } else {
  6580. self.afterCreate(resetHeight);
  6581. }
  6582. });
  6583. /*******************************************************************************
  6584. * KindEditor - WYSIWYG HTML Editor for Internet
  6585. * Copyright (C) 2006-2011 kindsoft.net
  6586. *
  6587. * @author Roddy <luolonghao@gmail.com>
  6588. * @site http://www.kindsoft.net/
  6589. * @licence http://www.kindsoft.net/license.php
  6590. *******************************************************************************/
  6591. // Baidu Maps: http://dev.baidu.com/wiki/map/index.php?title=%E9%A6%96%E9%A1%B5
  6592. KindEditor.plugin('baidumap', function(K) {
  6593. var self = this,
  6594. name = 'baidumap',
  6595. lang = self.lang(name + '.');
  6596. var ak = self.options.baidumapAk || 'plddmxBud2dRsVAXHS7WLqqzQQTocDkO';
  6597. var mapWidth = K.undef(self.mapWidth, 558);
  6598. var mapHeight = K.undef(self.mapHeight, 360);
  6599. self.clickToolbar(name, function() {
  6600. var html = ['<div style="padding:10px 20px;">',
  6601. '<div class="ke-header">',
  6602. // left start
  6603. '<div class="ke-left">',
  6604. lang.address + ' <input id="kindeditor_plugin_map_address" name="address" class="ke-input-text" value="" style="width:200px;" /> ',
  6605. '<span class="ke-button-common ke-button-outer">',
  6606. '<input type="button" name="searchBtn" class="ke-button-common ke-button" value="' + lang.search + '" />',
  6607. '</span>',
  6608. '</div>',
  6609. // right start
  6610. '<div class="ke-right" style="margin-top: 2px">',
  6611. '<input type="checkbox" id="keInsertDynamicMap" name="insertDynamicMap" value="1" style="margin-top: 2px" /> <label for="keInsertDynamicMap">' + lang.insertDynamicMap + '</label>',
  6612. '</div>',
  6613. '<div class="ke-clearfix"></div>',
  6614. '</div>',
  6615. '<div class="ke-map" style="width:' + mapWidth + 'px;height:' + mapHeight + 'px;"></div>',
  6616. '</div>'
  6617. ].join('');
  6618. var dialog = self.createDialog({
  6619. name: name,
  6620. width: mapWidth + 42,
  6621. title: self.lang(name),
  6622. body: html,
  6623. yesBtn: {
  6624. name: self.lang('yes'),
  6625. click: function(e) {
  6626. var map = win.map;
  6627. var centerObj = map.getCenter();
  6628. var center = centerObj.lng + ',' + centerObj.lat;
  6629. var zoom = map.getZoom();
  6630. var url = [checkbox[0].checked ? self.pluginsPath + 'baidumap/index.html?ak=' + ak : 'http://api.map.baidu.com/staticimage/v2?ak=' + ak,
  6631. '&center=' + encodeURIComponent(center),
  6632. '&zoom=' + encodeURIComponent(zoom),
  6633. '&width=' + mapWidth,
  6634. '&height=' + mapHeight,
  6635. '&markers=' + encodeURIComponent(center),
  6636. '&markerStyles=' + encodeURIComponent('l,A')
  6637. ].join('');
  6638. if(checkbox[0].checked) {
  6639. self.insertHtml('<iframe src="' + url + '" frameborder="0" style="width:' + (mapWidth + 2) + 'px;height:' + (mapHeight + 2) + 'px;"></iframe>');
  6640. } else {
  6641. self.exec('insertimage', url);
  6642. }
  6643. self.hideDialog().focus();
  6644. }
  6645. },
  6646. beforeRemove: function() {
  6647. searchBtn.remove();
  6648. if(doc) {
  6649. doc.write('');
  6650. }
  6651. iframe.remove();
  6652. }
  6653. });
  6654. var div = dialog.div,
  6655. addressBox = K('[name="address"]', div),
  6656. searchBtn = K('[name="searchBtn"]', div),
  6657. checkbox = K('[name="insertDynamicMap"]', dialog.div),
  6658. win, doc;
  6659. var iframe = K('<iframe class="ke-textarea" frameborder="0" src="' + self.pluginsPath + 'baidumap/map.html?ak=' + ak + '" style="width:' + mapWidth + 'px;height:' + mapHeight + 'px;"></iframe>');
  6660. function ready() {
  6661. win = iframe[0].contentWindow;
  6662. doc = K.iframeDoc(iframe);
  6663. }
  6664. iframe.bind('load', function() {
  6665. iframe.unbind('load');
  6666. if(K.IE) {
  6667. ready();
  6668. } else {
  6669. setTimeout(ready, 0);
  6670. }
  6671. });
  6672. K('.ke-map', div).replaceWith(iframe);
  6673. // search map
  6674. searchBtn.click(function() {
  6675. win.search(addressBox.val());
  6676. });
  6677. });
  6678. });
  6679. /*******************************************************************************
  6680. * KindEditor - WYSIWYG HTML Editor for Internet
  6681. * Copyright (C) 2006-2011 kindsoft.net
  6682. *
  6683. * @author Roddy <luolonghao@gmail.com>
  6684. * @site http://www.kindsoft.net/
  6685. * @licence http://www.kindsoft.net/license.php
  6686. *******************************************************************************/
  6687. KindEditor.plugin('clearhtml', function(K) {
  6688. var self = this,
  6689. name = 'clearhtml';
  6690. self.clickToolbar(name, function() {
  6691. self.focus();
  6692. var html = self.html();
  6693. html = html.replace(/(<script[^>]*>)([\s\S]*?)(<\/script>)/ig, '');
  6694. html = html.replace(/(<style[^>]*>)([\s\S]*?)(<\/style>)/ig, '');
  6695. html = K.formatHtml(html, {
  6696. a: ['href', 'target'],
  6697. embed: ['src', 'width', 'height', 'type', 'loop', 'autostart', 'quality', '.width', '.height', 'align', 'allowscriptaccess'],
  6698. img: ['src', 'width', 'height', 'border', 'alt', 'title', '.width', '.height'],
  6699. table: ['border'],
  6700. 'td,th': ['rowspan', 'colspan'],
  6701. 'div,hr,br,tbody,tr,p,ol,ul,li,blockquote,h1,h2,h3,h4,h5,h6': []
  6702. });
  6703. self.html(html);
  6704. self.cmd.selection(true);
  6705. self.addBookmark();
  6706. });
  6707. });
  6708. /*******************************************************************************
  6709. * KindEditor - WYSIWYG HTML Editor for Internet
  6710. * Copyright (C) 2006-2011 kindsoft.net
  6711. *
  6712. * @author Roddy <luolonghao@gmail.com>
  6713. * @site http://www.kindsoft.net/
  6714. * @licence http://www.kindsoft.net/license.php
  6715. *******************************************************************************/
  6716. // google code prettify: http://google-code-prettify.googlecode.com/
  6717. // http://google-code-prettify.googlecode.com/
  6718. KindEditor.plugin('code', function(K) {
  6719. var self = this,
  6720. name = 'code';
  6721. self.clickToolbar(name, function() {
  6722. var lang = self.lang(name + '.'),
  6723. html = ['<div style="padding:10px 20px;">',
  6724. '<div class="ke-dialog-row">',
  6725. '<select class="ke-code-type">',
  6726. '<option value="js">JavaScript</option>',
  6727. '<option value="html">HTML</option>',
  6728. '<option value="css">CSS</option>',
  6729. '<option value="php">PHP</option>',
  6730. '<option value="pl">Perl</option>',
  6731. '<option value="py">Python</option>',
  6732. '<option value="rb">Ruby</option>',
  6733. '<option value="java">Java</option>',
  6734. '<option value="vb">ASP/VB</option>',
  6735. '<option value="cpp">C/C++</option>',
  6736. '<option value="cs">C#</option>',
  6737. '<option value="xml">XML</option>',
  6738. '<option value="bsh">Shell</option>',
  6739. '<option value="">Other</option>',
  6740. '</select>',
  6741. '</div>',
  6742. '<textarea class="ke-textarea" style="width:408px;height:260px;"></textarea>',
  6743. '</div>'
  6744. ].join(''),
  6745. dialog = self.createDialog({
  6746. name: name,
  6747. width: 450,
  6748. title: self.lang(name),
  6749. body: html,
  6750. yesBtn: {
  6751. name: self.lang('yes'),
  6752. click: function(e) {
  6753. var type = K('.ke-code-type', dialog.div).val(),
  6754. code = textarea.val(),
  6755. cls = type === '' ? '' : ' lang-' + type,
  6756. html = '<pre class="prettyprint' + cls + '">\n' + K.escape(code) + '</pre> ';
  6757. if(K.trim(code) === '') {
  6758. alert(lang.pleaseInput);
  6759. textarea[0].focus();
  6760. return;
  6761. }
  6762. self.insertHtml(html).hideDialog().focus();
  6763. }
  6764. }
  6765. }),
  6766. textarea = K('textarea', dialog.div);
  6767. textarea[0].focus();
  6768. });
  6769. });
  6770. /*******************************************************************************
  6771. * KindEditor - WYSIWYG HTML Editor for Internet
  6772. * Copyright (C) 2006-2011 kindsoft.net
  6773. *
  6774. * @author Roddy <luolonghao@gmail.com>
  6775. * @site http://www.kindsoft.net/
  6776. * @licence http://www.kindsoft.net/license.php
  6777. *******************************************************************************/
  6778. KindEditor.plugin('emoticons', function(K) {
  6779. var self = this,
  6780. name = 'emoticons',
  6781. path = (self.emoticonsPath || self.pluginsPath + 'emoticons/images/'),
  6782. allowPreview = self.allowPreviewEmoticons === undefined ? true : self.allowPreviewEmoticons,
  6783. currentPageNum = 1;
  6784. self.clickToolbar(name, function() {
  6785. var rows = 5,
  6786. cols = 9,
  6787. total = 135,
  6788. startNum = 0,
  6789. cells = rows * cols,
  6790. pages = Math.ceil(total / cells),
  6791. colsHalf = Math.floor(cols / 2),
  6792. wrapperDiv = K('<div class="ke-plugin-emoticons"></div>'),
  6793. elements = [],
  6794. menu = self.createMenu({
  6795. name: name,
  6796. beforeRemove: function() {
  6797. removeEvent();
  6798. }
  6799. });
  6800. menu.div.append(wrapperDiv);
  6801. var previewDiv, previewImg;
  6802. if(allowPreview) {
  6803. previewDiv = K('<div class="ke-preview"></div>').css('right', 0);
  6804. previewImg = K('<img class="ke-preview-img" src="' + path + startNum + '.gif" />');
  6805. wrapperDiv.append(previewDiv);
  6806. previewDiv.append(previewImg);
  6807. }
  6808. function bindCellEvent(cell, j, num) {
  6809. if(previewDiv) {
  6810. cell.mouseover(function() {
  6811. if(j > colsHalf) {
  6812. previewDiv.css('left', 0);
  6813. previewDiv.css('right', '');
  6814. } else {
  6815. previewDiv.css('left', '');
  6816. previewDiv.css('right', 0);
  6817. }
  6818. previewImg.attr('src', path + num + '.gif');
  6819. K(this).addClass('ke-on');
  6820. });
  6821. } else {
  6822. cell.mouseover(function() {
  6823. K(this).addClass('ke-on');
  6824. });
  6825. }
  6826. cell.mouseout(function() {
  6827. K(this).removeClass('ke-on');
  6828. });
  6829. cell.click(function(e) {
  6830. self.insertHtml('<img src="' + path + num + '.gif" border="0" alt="" />').hideMenu().focus();
  6831. e.stop();
  6832. });
  6833. }
  6834. function createEmoticonsTable(pageNum, parentDiv) {
  6835. var table = document.createElement('table');
  6836. parentDiv.append(table);
  6837. if(previewDiv) {
  6838. K(table).mouseover(function() {
  6839. previewDiv.show('block');
  6840. });
  6841. K(table).mouseout(function() {
  6842. previewDiv.hide();
  6843. });
  6844. elements.push(K(table));
  6845. }
  6846. table.className = 'ke-table';
  6847. table.cellPadding = 0;
  6848. table.cellSpacing = 0;
  6849. table.border = 0;
  6850. var num = (pageNum - 1) * cells + startNum;
  6851. for(var i = 0; i < rows; i++) {
  6852. var row = table.insertRow(i);
  6853. for(var j = 0; j < cols; j++) {
  6854. var cell = K(row.insertCell(j));
  6855. cell.addClass('ke-cell');
  6856. bindCellEvent(cell, j, num);
  6857. var span = K('<span class="ke-img"></span>')
  6858. .css('background-position', '-' + (24 * num) + 'px 0px')
  6859. .css('background-image', 'url(' + path + 'static.gif)');
  6860. cell.append(span);
  6861. elements.push(cell);
  6862. num++;
  6863. }
  6864. }
  6865. return table;
  6866. }
  6867. var table = createEmoticonsTable(currentPageNum, wrapperDiv);
  6868. function removeEvent() {
  6869. K.each(elements, function() {
  6870. this.unbind();
  6871. });
  6872. }
  6873. var pageDiv;
  6874. function bindPageEvent(el, pageNum) {
  6875. el.click(function(e) {
  6876. removeEvent();
  6877. table.parentNode.removeChild(table);
  6878. pageDiv.remove();
  6879. table = createEmoticonsTable(pageNum, wrapperDiv);
  6880. createPageTable(pageNum);
  6881. currentPageNum = pageNum;
  6882. e.stop();
  6883. });
  6884. }
  6885. function createPageTable(currentPageNum) {
  6886. pageDiv = K('<div class="ke-page"></div>');
  6887. wrapperDiv.append(pageDiv);
  6888. for(var pageNum = 1; pageNum <= pages; pageNum++) {
  6889. if(currentPageNum !== pageNum) {
  6890. var a = K('<a href="javascript:;">[' + pageNum + ']</a>');
  6891. bindPageEvent(a, pageNum);
  6892. pageDiv.append(a);
  6893. elements.push(a);
  6894. } else {
  6895. pageDiv.append(K('@[' + pageNum + ']'));
  6896. }
  6897. pageDiv.append(K('@&nbsp;'));
  6898. }
  6899. }
  6900. createPageTable(currentPageNum);
  6901. });
  6902. });
  6903. /*******************************************************************************
  6904. * KindEditor - WYSIWYG HTML Editor for Internet
  6905. * Copyright (C) 2006-2011 kindsoft.net
  6906. *
  6907. * @author Roddy <luolonghao@gmail.com>
  6908. * @site http://www.kindsoft.net/
  6909. * @licence http://www.kindsoft.net/license.php
  6910. *******************************************************************************/
  6911. KindEditor.plugin('filemanager', function(K) {
  6912. var self = this,
  6913. name = 'filemanager',
  6914. fileManagerJson = K.undef(self.fileManagerJson, self.basePath + 'php/file_manager_json.php'),
  6915. imgPath = self.pluginsPath + name + '/images/',
  6916. lang = self.lang(name + '.');
  6917. function makeFileTitle(filename, filesize, datetime) {
  6918. return filename + ' (' + Math.ceil(filesize / 1024) + 'KB, ' + datetime + ')';
  6919. }
  6920. function bindTitle(el, data) {
  6921. if(data.is_dir) {
  6922. el.attr('title', data.filename);
  6923. } else {
  6924. el.attr('title', makeFileTitle(data.filename, data.filesize, data.datetime));
  6925. }
  6926. }
  6927. self.plugin.filemanagerDialog = function(options) {
  6928. var width = K.undef(options.width, 650),
  6929. height = K.undef(options.height, 510),
  6930. dirName = K.undef(options.dirName, ''),
  6931. viewType = K.undef(options.viewType, 'VIEW').toUpperCase(), // "LIST" or "VIEW"
  6932. clickFn = options.clickFn;
  6933. var html = [
  6934. '<div style="padding:10px 20px;">',
  6935. // header start
  6936. '<div class="ke-plugin-filemanager-header">',
  6937. // left start
  6938. '<div class="ke-left">',
  6939. '<img class="ke-inline-block" name="moveupImg" src="' + imgPath + 'go-up.gif" width="16" height="16" border="0" alt="" /> ',
  6940. '<a class="ke-inline-block" name="moveupLink" href="javascript:;">' + lang.moveup + '</a>',
  6941. '</div>',
  6942. // right start
  6943. '<div class="ke-right">',
  6944. lang.viewType + ' <select class="ke-inline-block" name="viewType">',
  6945. '<option value="VIEW">' + lang.viewImage + '</option>',
  6946. '<option value="LIST">' + lang.listImage + '</option>',
  6947. '</select> ',
  6948. lang.orderType + ' <select class="ke-inline-block" name="orderType">',
  6949. '<option value="NAME">' + lang.fileName + '</option>',
  6950. '<option value="SIZE">' + lang.fileSize + '</option>',
  6951. '<option value="TYPE">' + lang.fileType + '</option>',
  6952. '</select>',
  6953. '</div>',
  6954. '<div class="ke-clearfix"></div>',
  6955. '</div>',
  6956. // body start
  6957. '<div class="ke-plugin-filemanager-body"></div>',
  6958. '</div>'
  6959. ].join('');
  6960. var dialog = self.createDialog({
  6961. name: name,
  6962. width: width,
  6963. height: height,
  6964. title: self.lang(name),
  6965. body: html
  6966. }),
  6967. div = dialog.div,
  6968. bodyDiv = K('.ke-plugin-filemanager-body', div),
  6969. moveupImg = K('[name="moveupImg"]', div),
  6970. moveupLink = K('[name="moveupLink"]', div),
  6971. viewServerBtn = K('[name="viewServer"]', div),
  6972. viewTypeBox = K('[name="viewType"]', div),
  6973. orderTypeBox = K('[name="orderType"]', div);
  6974. function reloadPage(path, order, func) {
  6975. var param = 'path=' + path + '&order=' + order + '&dir=' + dirName;
  6976. dialog.showLoading(self.lang('ajaxLoading'));
  6977. K.ajax(K.addParam(fileManagerJson, param + '&' + new Date().getTime()), function(data) {
  6978. dialog.hideLoading();
  6979. func(data);
  6980. });
  6981. }
  6982. var elList = [];
  6983. function bindEvent(el, result, data, createFunc) {
  6984. var fileUrl = K.formatUrl(result.current_url + data.filename, 'absolute'),
  6985. dirPath = encodeURIComponent(result.current_dir_path + data.filename + '/');
  6986. if(data.is_dir) {
  6987. el.click(function(e) {
  6988. reloadPage(dirPath, orderTypeBox.val(), createFunc);
  6989. });
  6990. } else if(data.is_photo) {
  6991. el.click(function(e) {
  6992. clickFn.call(this, fileUrl, data.filename);
  6993. });
  6994. } else {
  6995. el.click(function(e) {
  6996. clickFn.call(this, fileUrl, data.filename);
  6997. });
  6998. }
  6999. elList.push(el);
  7000. }
  7001. function createCommon(result, createFunc) {
  7002. // remove events
  7003. K.each(elList, function() {
  7004. this.unbind();
  7005. });
  7006. moveupLink.unbind();
  7007. viewTypeBox.unbind();
  7008. orderTypeBox.unbind();
  7009. // add events
  7010. if(result.current_dir_path) {
  7011. moveupLink.click(function(e) {
  7012. reloadPage(result.moveup_dir_path, orderTypeBox.val(), createFunc);
  7013. });
  7014. }
  7015. function changeFunc() {
  7016. if(viewTypeBox.val() == 'VIEW') {
  7017. reloadPage(result.current_dir_path, orderTypeBox.val(), createView);
  7018. } else {
  7019. reloadPage(result.current_dir_path, orderTypeBox.val(), createList);
  7020. }
  7021. }
  7022. viewTypeBox.change(changeFunc);
  7023. orderTypeBox.change(changeFunc);
  7024. bodyDiv.html('');
  7025. }
  7026. function createList(result) {
  7027. createCommon(result, createList);
  7028. var table = document.createElement('table');
  7029. table.className = 'ke-table';
  7030. table.cellPadding = 0;
  7031. table.cellSpacing = 0;
  7032. table.border = 0;
  7033. bodyDiv.append(table);
  7034. var fileList = result.file_list;
  7035. for(var i = 0, len = fileList.length; i < len; i++) {
  7036. var data = fileList[i],
  7037. row = K(table.insertRow(i));
  7038. row.mouseover(function(e) {
  7039. K(this).addClass('ke-on');
  7040. })
  7041. .mouseout(function(e) {
  7042. K(this).removeClass('ke-on');
  7043. });
  7044. var iconUrl = imgPath + (data.is_dir ? 'folder-16.gif' : 'file-16.gif'),
  7045. img = K('<img src="' + iconUrl + '" width="16" height="16" alt="' + data.filename + '" align="absmiddle" />'),
  7046. cell0 = K(row[0].insertCell(0)).addClass('ke-cell ke-name').append(img).append(document.createTextNode(' ' + data.filename));
  7047. if(!data.is_dir || data.has_file) {
  7048. row.css('cursor', 'pointer');
  7049. cell0.attr('title', data.filename);
  7050. bindEvent(cell0, result, data, createList);
  7051. } else {
  7052. cell0.attr('title', lang.emptyFolder);
  7053. }
  7054. K(row[0].insertCell(1)).addClass('ke-cell ke-size').html(data.is_dir ? '-' : Math.ceil(data.filesize / 1024) + 'KB');
  7055. K(row[0].insertCell(2)).addClass('ke-cell ke-datetime').html(data.datetime);
  7056. }
  7057. }
  7058. function createView(result) {
  7059. createCommon(result, createView);
  7060. var fileList = result.file_list;
  7061. for(var i = 0, len = fileList.length; i < len; i++) {
  7062. var data = fileList[i],
  7063. div = K('<div class="ke-inline-block ke-item"></div>');
  7064. bodyDiv.append(div);
  7065. var photoDiv = K('<div class="ke-inline-block ke-photo"></div>')
  7066. .mouseover(function(e) {
  7067. K(this).addClass('ke-on');
  7068. })
  7069. .mouseout(function(e) {
  7070. K(this).removeClass('ke-on');
  7071. });
  7072. div.append(photoDiv);
  7073. var fileUrl = result.current_url + data.filename,
  7074. iconUrl = data.is_dir ? imgPath + 'folder-64.gif' : (data.is_photo ? fileUrl : imgPath + 'file-64.gif');
  7075. var img = K('<img src="' + iconUrl + '" width="80" height="80" alt="' + data.filename + '" />');
  7076. if(!data.is_dir || data.has_file) {
  7077. photoDiv.css('cursor', 'pointer');
  7078. bindTitle(photoDiv, data);
  7079. bindEvent(photoDiv, result, data, createView);
  7080. } else {
  7081. photoDiv.attr('title', lang.emptyFolder);
  7082. }
  7083. photoDiv.append(img);
  7084. div.append('<div class="ke-name" title="' + data.filename + '">' + data.filename + '</div>');
  7085. }
  7086. }
  7087. viewTypeBox.val(viewType);
  7088. reloadPage('', orderTypeBox.val(), viewType == 'VIEW' ? createView : createList);
  7089. return dialog;
  7090. }
  7091. });
  7092. /*******************************************************************************
  7093. * KindEditor - WYSIWYG HTML Editor for Internet
  7094. * Copyright (C) 2006-2011 kindsoft.net
  7095. *
  7096. * @author Roddy <luolonghao@gmail.com>
  7097. * @site http://www.kindsoft.net/
  7098. * @licence http://www.kindsoft.net/license.php
  7099. *******************************************************************************/
  7100. KindEditor.plugin('flash', function(K) {
  7101. var self = this,
  7102. name = 'flash',
  7103. lang = self.lang(name + '.'),
  7104. allowFlashUpload = K.undef(self.allowFlashUpload, true),
  7105. allowFileManager = K.undef(self.allowFileManager, false),
  7106. formatUploadUrl = K.undef(self.formatUploadUrl, true),
  7107. extraParams = K.undef(self.extraFileUploadParams, {}),
  7108. filePostName = K.undef(self.filePostName, 'imgFile'),
  7109. uploadJson = K.undef(self.uploadJson, self.basePath + 'php/upload_json.php');
  7110. self.plugin.flash = {
  7111. edit: function() {
  7112. var html = [
  7113. '<div style="padding:20px;">',
  7114. //url
  7115. '<div class="ke-dialog-row">',
  7116. '<label for="keUrl" style="width:60px;">' + lang.url + '</label>',
  7117. '<input class="ke-input-text" type="text" id="keUrl" name="url" value="" style="width:160px;" /> &nbsp;',
  7118. '<input type="button" class="ke-upload-button" value="' + lang.upload + '" /> &nbsp;',
  7119. '<span class="ke-button-common ke-button-outer">',
  7120. '<input type="button" class="ke-button-common ke-button" name="viewServer" value="' + lang.viewServer + '" />',
  7121. '</span>',
  7122. '</div>',
  7123. //width
  7124. '<div class="ke-dialog-row">',
  7125. '<label for="keWidth" style="width:60px;">' + lang.width + '</label>',
  7126. '<input type="text" id="keWidth" class="ke-input-text ke-input-number" name="width" value="550" maxlength="4" /> ',
  7127. '</div>',
  7128. //height
  7129. '<div class="ke-dialog-row">',
  7130. '<label for="keHeight" style="width:60px;">' + lang.height + '</label>',
  7131. '<input type="text" id="keHeight" class="ke-input-text ke-input-number" name="height" value="400" maxlength="4" /> ',
  7132. '</div>',
  7133. '</div>'
  7134. ].join('');
  7135. var dialog = self.createDialog({
  7136. name: name,
  7137. width: 450,
  7138. title: self.lang(name),
  7139. body: html,
  7140. yesBtn: {
  7141. name: self.lang('yes'),
  7142. click: function(e) {
  7143. var url = K.trim(urlBox.val()),
  7144. width = widthBox.val(),
  7145. height = heightBox.val();
  7146. if(url == 'http://' || K.invalidUrl(url)) {
  7147. alert(self.lang('invalidUrl'));
  7148. urlBox[0].focus();
  7149. return;
  7150. }
  7151. if(!/^\d*$/.test(width)) {
  7152. alert(self.lang('invalidWidth'));
  7153. widthBox[0].focus();
  7154. return;
  7155. }
  7156. if(!/^\d*$/.test(height)) {
  7157. alert(self.lang('invalidHeight'));
  7158. heightBox[0].focus();
  7159. return;
  7160. }
  7161. var html = K.mediaImg(self.themesPath + 'common/blank.gif', {
  7162. src: url,
  7163. type: K.mediaType('.swf'),
  7164. width: width,
  7165. height: height,
  7166. quality: 'high'
  7167. });
  7168. self.insertHtml(html).hideDialog().focus();
  7169. }
  7170. }
  7171. }),
  7172. div = dialog.div,
  7173. urlBox = K('[name="url"]', div),
  7174. viewServerBtn = K('[name="viewServer"]', div),
  7175. widthBox = K('[name="width"]', div),
  7176. heightBox = K('[name="height"]', div);
  7177. urlBox.val('http://');
  7178. if(allowFlashUpload) {
  7179. var uploadbutton = K.uploadbutton({
  7180. button: K('.ke-upload-button', div)[0],
  7181. fieldName: filePostName,
  7182. extraParams: extraParams,
  7183. url: K.addParam(uploadJson, 'dir=flash'),
  7184. afterUpload: function(data) {
  7185. dialog.hideLoading();
  7186. if(data.error === 0) {
  7187. var url = data.url;
  7188. if(formatUploadUrl) {
  7189. url = K.formatUrl(url, 'absolute');
  7190. }
  7191. urlBox.val(url);
  7192. if(self.afterUpload) {
  7193. self.afterUpload.call(self, url, data, name);
  7194. }
  7195. alert(self.lang('uploadSuccess'));
  7196. } else {
  7197. alert(data.message);
  7198. }
  7199. },
  7200. afterError: function(html) {
  7201. dialog.hideLoading();
  7202. self.errorDialog(html);
  7203. }
  7204. });
  7205. uploadbutton.fileBox.change(function(e) {
  7206. dialog.showLoading(self.lang('uploadLoading'));
  7207. uploadbutton.submit();
  7208. });
  7209. } else {
  7210. K('.ke-upload-button', div).hide();
  7211. }
  7212. if(allowFileManager) {
  7213. viewServerBtn.click(function(e) {
  7214. self.loadPlugin('filemanager', function() {
  7215. self.plugin.filemanagerDialog({
  7216. viewType: 'LIST',
  7217. dirName: 'flash',
  7218. clickFn: function(url, title) {
  7219. if(self.dialogs.length > 1) {
  7220. K('[name="url"]', div).val(url);
  7221. if(self.afterSelectFile) {
  7222. self.afterSelectFile.call(self, url);
  7223. }
  7224. self.hideDialog();
  7225. }
  7226. }
  7227. });
  7228. });
  7229. });
  7230. } else {
  7231. viewServerBtn.hide();
  7232. }
  7233. var img = self.plugin.getSelectedFlash();
  7234. if(img) {
  7235. var attrs = K.mediaAttrs(img.attr('data-ke-tag'));
  7236. urlBox.val(attrs.src);
  7237. widthBox.val(K.removeUnit(img.css('width')) || attrs.width || 0);
  7238. heightBox.val(K.removeUnit(img.css('height')) || attrs.height || 0);
  7239. }
  7240. urlBox[0].focus();
  7241. urlBox[0].select();
  7242. },
  7243. 'delete': function() {
  7244. self.plugin.getSelectedFlash().remove();
  7245. // [IE] 删除图片后立即点击图片按钮出错
  7246. self.addBookmark();
  7247. }
  7248. };
  7249. self.clickToolbar(name, self.plugin.flash.edit);
  7250. });
  7251. /*******************************************************************************
  7252. * KindEditor - WYSIWYG HTML Editor for Internet
  7253. * Copyright (C) 2006-2011 kindsoft.net
  7254. *
  7255. * @author Roddy <luolonghao@gmail.com>
  7256. * @site http://www.kindsoft.net/
  7257. * @licence http://www.kindsoft.net/license.php
  7258. *******************************************************************************/
  7259. KindEditor.plugin('image', function(K) {
  7260. var self = this,
  7261. name = 'image',
  7262. allowImageUpload = K.undef(self.allowImageUpload, true),
  7263. allowImageRemote = K.undef(self.allowImageRemote, true),
  7264. formatUploadUrl = K.undef(self.formatUploadUrl, true),
  7265. allowFileManager = K.undef(self.allowFileManager, false),
  7266. uploadJson = K.undef(self.uploadJson, self.basePath + 'php/upload_json.php'),
  7267. imageTabIndex = K.undef(self.imageTabIndex, 0),
  7268. imgPath = self.pluginsPath + 'image/images/',
  7269. extraParams = K.undef(self.extraFileUploadParams, {}),
  7270. filePostName = K.undef(self.filePostName, 'imgFile'),
  7271. fillDescAfterUploadImage = K.undef(self.fillDescAfterUploadImage, false),
  7272. lang = self.lang(name + '.');
  7273. self.plugin.imageDialog = function(options) {
  7274. var imageUrl = options.imageUrl,
  7275. imageWidth = K.undef(options.imageWidth, ''),
  7276. imageHeight = K.undef(options.imageHeight, ''),
  7277. imageTitle = K.undef(options.imageTitle, ''),
  7278. imageAlign = K.undef(options.imageAlign, ''),
  7279. showRemote = K.undef(options.showRemote, true),
  7280. showLocal = K.undef(options.showLocal, true),
  7281. tabIndex = K.undef(options.tabIndex, 0),
  7282. clickFn = options.clickFn;
  7283. var target = 'kindeditor_upload_iframe_' + new Date().getTime();
  7284. var hiddenElements = [];
  7285. for(var k in extraParams) {
  7286. hiddenElements.push('<input type="hidden" name="' + k + '" value="' + extraParams[k] + '" />');
  7287. }
  7288. var html = [
  7289. '<div style="padding:20px;">',
  7290. //tabs
  7291. '<div class="tabs"></div>',
  7292. //remote image - start
  7293. '<div class="tab1" style="display:none;">',
  7294. //url
  7295. '<div class="ke-dialog-row">',
  7296. '<label for="remoteUrl" style="width:60px;">' + lang.remoteUrl + '</label>',
  7297. '<input type="text" id="remoteUrl" class="ke-input-text" name="url" value="" style="width:200px;" /> &nbsp;',
  7298. '<span class="ke-button-common ke-button-outer">',
  7299. '<input type="button" class="ke-button-common ke-button" name="viewServer" value="' + lang.viewServer + '" />',
  7300. '</span>',
  7301. '</div>',
  7302. //size
  7303. '<div class="ke-dialog-row">',
  7304. '<label for="remoteWidth" style="width:60px;">' + lang.size + '</label>',
  7305. lang.width + ' <input type="text" id="remoteWidth" class="ke-input-text ke-input-number" name="width" value="" maxlength="4" /> ',
  7306. lang.height + ' <input type="text" class="ke-input-text ke-input-number" name="height" value="" maxlength="4" /> ',
  7307. '<img class="ke-refresh-btn" src="' + imgPath + 'refresh.png" width="16" height="16" alt="" style="cursor:pointer;" title="' + lang.resetSize + '" />',
  7308. '</div>',
  7309. //align
  7310. '<div class="ke-dialog-row">',
  7311. '<label style="width:60px;">' + lang.align + '</label>',
  7312. '<input type="radio" name="align" class="ke-inline-block" value="" checked="checked" /> <img name="defaultImg" src="' + imgPath + 'align_top.gif" width="23" height="25" alt="" />',
  7313. ' <input type="radio" name="align" class="ke-inline-block" value="left" /> <img name="leftImg" src="' + imgPath + 'align_left.gif" width="23" height="25" alt="" />',
  7314. ' <input type="radio" name="align" class="ke-inline-block" value="right" /> <img name="rightImg" src="' + imgPath + 'align_right.gif" width="23" height="25" alt="" />',
  7315. '</div>',
  7316. //title
  7317. '<div class="ke-dialog-row">',
  7318. '<label for="remoteTitle" style="width:60px;">' + lang.imgTitle + '</label>',
  7319. '<input type="text" id="remoteTitle" class="ke-input-text" name="title" value="" style="width:200px;" />',
  7320. '</div>',
  7321. '</div>',
  7322. //remote image - end
  7323. //local upload - start
  7324. '<div class="tab2" style="display:none;">',
  7325. '<iframe name="' + target + '" style="display:none;"></iframe>',
  7326. '<form class="ke-upload-area ke-form" method="post" enctype="multipart/form-data" target="' + target + '" action="' + K.addParam(uploadJson, 'dir=image') + '">',
  7327. //file
  7328. '<div class="ke-dialog-row">',
  7329. hiddenElements.join(''),
  7330. '<label style="width:60px;">' + lang.localUrl + '</label>',
  7331. '<input type="text" name="localUrl" class="ke-input-text" tabindex="-1" style="width:200px;" readonly="true" /> &nbsp;',
  7332. '<input type="button" class="ke-upload-button" value="' + lang.upload + '" />',
  7333. '</div>',
  7334. '</form>',
  7335. '</div>',
  7336. //local upload - end
  7337. '</div>'
  7338. ].join('');
  7339. var dialogWidth = showLocal || allowFileManager ? 450 : 400,
  7340. dialogHeight = showLocal && showRemote ? 300 : 250;
  7341. var dialog = self.createDialog({
  7342. name: name,
  7343. width: dialogWidth,
  7344. height: dialogHeight,
  7345. title: self.lang(name),
  7346. body: html,
  7347. yesBtn: {
  7348. name: self.lang('yes'),
  7349. click: function(e) {
  7350. // Bugfix: http://code.google.com/p/kindeditor/issues/detail?id=319
  7351. if(dialog.isLoading) {
  7352. return;
  7353. }
  7354. // insert local image
  7355. if(showLocal && showRemote && tabs && tabs.selectedIndex === 1 || !showRemote) {
  7356. if(uploadbutton.fileBox.val() == '') {
  7357. alert(self.lang('pleaseSelectFile'));
  7358. return;
  7359. }
  7360. dialog.showLoading(self.lang('uploadLoading'));
  7361. uploadbutton.submit();
  7362. localUrlBox.val('');
  7363. return;
  7364. }
  7365. // insert remote image
  7366. var url = K.trim(urlBox.val()),
  7367. width = widthBox.val(),
  7368. height = heightBox.val(),
  7369. title = titleBox.val(),
  7370. align = '';
  7371. alignBox.each(function() {
  7372. if(this.checked) {
  7373. align = this.value;
  7374. return false;
  7375. }
  7376. });
  7377. if(url == 'http://' || K.invalidUrl(url)) {
  7378. alert(self.lang('invalidUrl'));
  7379. urlBox[0].focus();
  7380. return;
  7381. }
  7382. if(!/^\d*$/.test(width)) {
  7383. alert(self.lang('invalidWidth'));
  7384. widthBox[0].focus();
  7385. return;
  7386. }
  7387. if(!/^\d*$/.test(height)) {
  7388. alert(self.lang('invalidHeight'));
  7389. heightBox[0].focus();
  7390. return;
  7391. }
  7392. clickFn.call(self, url, title, width, height, 0, align);
  7393. }
  7394. },
  7395. beforeRemove: function() {
  7396. viewServerBtn.unbind();
  7397. widthBox.unbind();
  7398. heightBox.unbind();
  7399. refreshBtn.unbind();
  7400. }
  7401. }),
  7402. div = dialog.div;
  7403. var urlBox = K('[name="url"]', div),
  7404. localUrlBox = K('[name="localUrl"]', div),
  7405. viewServerBtn = K('[name="viewServer"]', div),
  7406. widthBox = K('.tab1 [name="width"]', div),
  7407. heightBox = K('.tab1 [name="height"]', div),
  7408. refreshBtn = K('.ke-refresh-btn', div),
  7409. titleBox = K('.tab1 [name="title"]', div),
  7410. alignBox = K('.tab1 [name="align"]', div);
  7411. var tabs;
  7412. if(showRemote && showLocal) {
  7413. tabs = K.tabs({
  7414. src: K('.tabs', div),
  7415. afterSelect: function(i) {}
  7416. });
  7417. tabs.add({
  7418. title: lang.remoteImage,
  7419. panel: K('.tab1', div)
  7420. });
  7421. tabs.add({
  7422. title: lang.localImage,
  7423. panel: K('.tab2', div)
  7424. });
  7425. tabs.select(tabIndex);
  7426. } else if(showRemote) {
  7427. K('.tab1', div).show();
  7428. } else if(showLocal) {
  7429. K('.tab2', div).show();
  7430. }
  7431. var uploadbutton = K.uploadbutton({
  7432. button: K('.ke-upload-button', div)[0],
  7433. fieldName: filePostName,
  7434. form: K('.ke-form', div),
  7435. target: target,
  7436. width: 70,
  7437. afterUpload: function(data) {
  7438. dialog.hideLoading();
  7439. if(data.error === 0) {
  7440. var url = data.url;
  7441. if(formatUploadUrl) {
  7442. url = K.formatUrl(url, 'absolute');
  7443. }
  7444. if(self.afterUpload) {
  7445. self.afterUpload.call(self, url, data, name);
  7446. }
  7447. if(!fillDescAfterUploadImage) {
  7448. clickFn.call(self, url, data.title, data.width, data.height, data.border, data.align);
  7449. } else {
  7450. K(".ke-dialog-row #remoteUrl", div).val(url);
  7451. K(".ke-tabs-li", div)[0].click();
  7452. K(".ke-refresh-btn", div).click();
  7453. }
  7454. } else {
  7455. alert(data.message);
  7456. }
  7457. },
  7458. afterError: function(html) {
  7459. dialog.hideLoading();
  7460. self.errorDialog(html);
  7461. }
  7462. });
  7463. uploadbutton.fileBox.change(function(e) {
  7464. localUrlBox.val(uploadbutton.fileBox.val());
  7465. });
  7466. if(allowFileManager) {
  7467. viewServerBtn.click(function(e) {
  7468. self.loadPlugin('filemanager', function() {
  7469. self.plugin.filemanagerDialog({
  7470. viewType: 'VIEW',
  7471. dirName: 'image',
  7472. clickFn: function(url, title) {
  7473. if(self.dialogs.length > 1) {
  7474. K('[name="url"]', div).val(url);
  7475. if(self.afterSelectFile) {
  7476. self.afterSelectFile.call(self, url);
  7477. }
  7478. self.hideDialog();
  7479. }
  7480. }
  7481. });
  7482. });
  7483. });
  7484. } else {
  7485. viewServerBtn.hide();
  7486. }
  7487. var originalWidth = 0,
  7488. originalHeight = 0;
  7489. function setSize(width, height) {
  7490. widthBox.val(width);
  7491. heightBox.val(height);
  7492. originalWidth = width;
  7493. originalHeight = height;
  7494. }
  7495. refreshBtn.click(function(e) {
  7496. var tempImg = K('<img src="' + urlBox.val() + '" />', document).css({
  7497. position: 'absolute',
  7498. visibility: 'hidden',
  7499. top: 0,
  7500. left: '-1000px'
  7501. });
  7502. tempImg.bind('load', function() {
  7503. setSize(tempImg.width(), tempImg.height());
  7504. tempImg.remove();
  7505. });
  7506. K(document.body).append(tempImg);
  7507. });
  7508. widthBox.change(function(e) {
  7509. if(originalWidth > 0) {
  7510. heightBox.val(Math.round(originalHeight / originalWidth * parseInt(this.value, 10)));
  7511. }
  7512. });
  7513. heightBox.change(function(e) {
  7514. if(originalHeight > 0) {
  7515. widthBox.val(Math.round(originalWidth / originalHeight * parseInt(this.value, 10)));
  7516. }
  7517. });
  7518. urlBox.val(options.imageUrl);
  7519. setSize(options.imageWidth, options.imageHeight);
  7520. titleBox.val(options.imageTitle);
  7521. alignBox.each(function() {
  7522. if(this.value === options.imageAlign) {
  7523. this.checked = true;
  7524. return false;
  7525. }
  7526. });
  7527. if(showRemote && tabIndex === 0) {
  7528. urlBox[0].focus();
  7529. urlBox[0].select();
  7530. }
  7531. return dialog;
  7532. };
  7533. self.plugin.image = {
  7534. edit: function() {
  7535. var img = self.plugin.getSelectedImage();
  7536. self.plugin.imageDialog({
  7537. imageUrl: img ? img.attr('data-ke-src') : 'http://',
  7538. imageWidth: img ? img.width() : '',
  7539. imageHeight: img ? img.height() : '',
  7540. imageTitle: img ? img.attr('title') : '',
  7541. imageAlign: img ? img.attr('align') : '',
  7542. showRemote: allowImageRemote,
  7543. showLocal: allowImageUpload,
  7544. tabIndex: img ? 0 : imageTabIndex,
  7545. clickFn: function(url, title, width, height, border, align) {
  7546. if(img) {
  7547. img.attr('src', url);
  7548. img.attr('data-ke-src', url);
  7549. img.attr('width', width);
  7550. img.attr('height', height);
  7551. img.attr('title', title);
  7552. img.attr('align', align);
  7553. img.attr('alt', title);
  7554. } else {
  7555. self.exec('insertimage', url, title, width, height, border, align);
  7556. }
  7557. // Bugfix: [Firefox] 上传图片后,总是出现正在加载的样式,需要延迟执行hideDialog
  7558. setTimeout(function() {
  7559. self.hideDialog().focus();
  7560. }, 0);
  7561. }
  7562. });
  7563. },
  7564. 'delete': function() {
  7565. var target = self.plugin.getSelectedImage();
  7566. if(target.parent().name == 'a') {
  7567. target = target.parent();
  7568. }
  7569. target.remove();
  7570. // [IE] 删除图片后立即点击图片按钮出错
  7571. self.addBookmark();
  7572. }
  7573. };
  7574. self.clickToolbar(name, self.plugin.image.edit);
  7575. });
  7576. /*******************************************************************************
  7577. * KindEditor - WYSIWYG HTML Editor for Internet
  7578. * Copyright (C) 2006-2011 kindsoft.net
  7579. *
  7580. * @author Roddy <luolonghao@gmail.com>
  7581. * @site http://www.kindsoft.net/
  7582. * @licence http://www.kindsoft.net/license.php
  7583. *******************************************************************************/
  7584. KindEditor.plugin('insertfile', function(K) {
  7585. var self = this,
  7586. name = 'insertfile',
  7587. allowFileUpload = K.undef(self.allowFileUpload, true),
  7588. allowFileManager = K.undef(self.allowFileManager, false),
  7589. formatUploadUrl = K.undef(self.formatUploadUrl, true),
  7590. uploadJson = K.undef(self.uploadJson, self.basePath + 'php/upload_json.php'),
  7591. extraParams = K.undef(self.extraFileUploadParams, {}),
  7592. filePostName = K.undef(self.filePostName, 'imgFile'),
  7593. lang = self.lang(name + '.');
  7594. self.plugin.fileDialog = function(options) {
  7595. var fileUrl = K.undef(options.fileUrl, 'http://'),
  7596. fileTitle = K.undef(options.fileTitle, ''),
  7597. clickFn = options.clickFn;
  7598. var html = [
  7599. '<div style="padding:20px;">',
  7600. '<div class="ke-dialog-row">',
  7601. '<label for="keUrl" style="width:60px;">' + lang.url + '</label>',
  7602. '<input type="text" id="keUrl" name="url" class="ke-input-text" style="width:160px;" /> &nbsp;',
  7603. '<input type="button" class="ke-upload-button" value="' + lang.upload + '" /> &nbsp;',
  7604. '<span class="ke-button-common ke-button-outer">',
  7605. '<input type="button" class="ke-button-common ke-button" name="viewServer" value="' + lang.viewServer + '" />',
  7606. '</span>',
  7607. '</div>',
  7608. //title
  7609. '<div class="ke-dialog-row">',
  7610. '<label for="keTitle" style="width:60px;">' + lang.title + '</label>',
  7611. '<input type="text" id="keTitle" class="ke-input-text" name="title" value="" style="width:160px;" /></div>',
  7612. '</div>',
  7613. //form end
  7614. '</form>',
  7615. '</div>'
  7616. ].join('');
  7617. var dialog = self.createDialog({
  7618. name: name,
  7619. width: 450,
  7620. title: self.lang(name),
  7621. body: html,
  7622. yesBtn: {
  7623. name: self.lang('yes'),
  7624. click: function(e) {
  7625. var url = K.trim(urlBox.val()),
  7626. title = titleBox.val();
  7627. if(url == 'http://' || K.invalidUrl(url)) {
  7628. alert(self.lang('invalidUrl'));
  7629. urlBox[0].focus();
  7630. return;
  7631. }
  7632. if(K.trim(title) === '') {
  7633. title = url;
  7634. }
  7635. clickFn.call(self, url, title);
  7636. }
  7637. }
  7638. }),
  7639. div = dialog.div;
  7640. var urlBox = K('[name="url"]', div),
  7641. viewServerBtn = K('[name="viewServer"]', div),
  7642. titleBox = K('[name="title"]', div);
  7643. if(allowFileUpload) {
  7644. var uploadbutton = K.uploadbutton({
  7645. button: K('.ke-upload-button', div)[0],
  7646. fieldName: filePostName,
  7647. url: K.addParam(uploadJson, 'dir=file'),
  7648. extraParams: extraParams,
  7649. afterUpload: function(data) {
  7650. dialog.hideLoading();
  7651. if(data.error === 0) {
  7652. var url = data.url;
  7653. if(formatUploadUrl) {
  7654. url = K.formatUrl(url, 'absolute');
  7655. }
  7656. urlBox.val(url);
  7657. if(self.afterUpload) {
  7658. self.afterUpload.call(self, url, data, name);
  7659. }
  7660. alert(self.lang('uploadSuccess'));
  7661. } else {
  7662. alert(data.message);
  7663. }
  7664. },
  7665. afterError: function(html) {
  7666. dialog.hideLoading();
  7667. self.errorDialog(html);
  7668. }
  7669. });
  7670. uploadbutton.fileBox.change(function(e) {
  7671. dialog.showLoading(self.lang('uploadLoading'));
  7672. uploadbutton.submit();
  7673. });
  7674. } else {
  7675. K('.ke-upload-button', div).hide();
  7676. }
  7677. if(allowFileManager) {
  7678. viewServerBtn.click(function(e) {
  7679. self.loadPlugin('filemanager', function() {
  7680. self.plugin.filemanagerDialog({
  7681. viewType: 'LIST',
  7682. dirName: 'file',
  7683. clickFn: function(url, title) {
  7684. if(self.dialogs.length > 1) {
  7685. K('[name="url"]', div).val(url);
  7686. if(self.afterSelectFile) {
  7687. self.afterSelectFile.call(self, url);
  7688. }
  7689. self.hideDialog();
  7690. }
  7691. }
  7692. });
  7693. });
  7694. });
  7695. } else {
  7696. viewServerBtn.hide();
  7697. }
  7698. urlBox.val(fileUrl);
  7699. titleBox.val(fileTitle);
  7700. urlBox[0].focus();
  7701. urlBox[0].select();
  7702. };
  7703. self.clickToolbar(name, function() {
  7704. self.plugin.fileDialog({
  7705. clickFn: function(url, title) {
  7706. var html = '<a class="ke-insertfile" href="' + url + '" data-ke-src="' + url + '" target="_blank">' + title + '</a>';
  7707. self.insertHtml(html).hideDialog().focus();
  7708. }
  7709. });
  7710. });
  7711. });
  7712. /*******************************************************************************
  7713. * KindEditor - WYSIWYG HTML Editor for Internet
  7714. * Copyright (C) 2006-2011 kindsoft.net
  7715. *
  7716. * @author Roddy <luolonghao@gmail.com>
  7717. * @site http://www.kindsoft.net/
  7718. * @licence http://www.kindsoft.net/license.php
  7719. *******************************************************************************/
  7720. KindEditor.plugin('lineheight', function(K) {
  7721. var self = this,
  7722. name = 'lineheight',
  7723. lang = self.lang(name + '.');
  7724. self.clickToolbar(name, function() {
  7725. var curVal = '',
  7726. commonNode = self.cmd.commonNode({
  7727. '*': '.line-height'
  7728. });
  7729. if(commonNode) {
  7730. curVal = commonNode.css('line-height');
  7731. }
  7732. var menu = self.createMenu({
  7733. name: name,
  7734. width: 150
  7735. });
  7736. K.each(lang.lineHeight, function(i, row) {
  7737. K.each(row, function(key, val) {
  7738. menu.addItem({
  7739. title: val,
  7740. checked: curVal === key,
  7741. click: function() {
  7742. self.cmd.toggle('<span style="line-height:' + key + ';"></span>', {
  7743. span: '.line-height=' + key
  7744. });
  7745. self.updateState();
  7746. self.addBookmark();
  7747. self.hideMenu();
  7748. }
  7749. });
  7750. });
  7751. });
  7752. });
  7753. });
  7754. /*******************************************************************************
  7755. * KindEditor - WYSIWYG HTML Editor for Internet
  7756. * Copyright (C) 2006-2011 kindsoft.net
  7757. *
  7758. * @author Roddy <luolonghao@gmail.com>
  7759. * @site http://www.kindsoft.net/
  7760. * @licence http://www.kindsoft.net/license.php
  7761. *******************************************************************************/
  7762. KindEditor.plugin('link', function(K) {
  7763. var self = this,
  7764. name = 'link';
  7765. if (self.plugin.link) return;
  7766. self.plugin.link = {
  7767. edit: function() {
  7768. var lang = self.lang(name + '.'),
  7769. html = '<div style="padding:20px;">' +
  7770. //url
  7771. '<div class="ke-dialog-row">' +
  7772. '<label for="keUrl" style="width:60px;">' + lang.url + '</label>' +
  7773. '<input class="ke-input-text" type="text" id="keUrl" name="url" value="" style="width:260px;" /></div>' +
  7774. //type
  7775. '<div class="ke-dialog-row"">' +
  7776. '<label for="keType" style="width:60px;">' + lang.linkType + '</label>' +
  7777. '<select id="keType" name="type"></select>' +
  7778. '</div>' +
  7779. '</div>',
  7780. dialog = self.createDialog({
  7781. name: name,
  7782. width: 450,
  7783. title: self.lang(name),
  7784. body: html,
  7785. yesBtn: {
  7786. name: self.lang('yes'),
  7787. click: function(e) {
  7788. var url = K.trim(urlBox.val());
  7789. if(url == 'http://' || K.invalidUrl(url)) {
  7790. alert(self.lang('invalidUrl'));
  7791. urlBox[0].focus();
  7792. return;
  7793. }
  7794. self.exec('createlink', url, typeBox.val()).hideDialog().focus();
  7795. }
  7796. }
  7797. }),
  7798. div = dialog.div,
  7799. urlBox = K('input[name="url"]', div),
  7800. typeBox = K('select[name="type"]', div);
  7801. urlBox.val('http://');
  7802. typeBox[0].options[0] = new Option(lang.newWindow, '_blank');
  7803. typeBox[0].options[1] = new Option(lang.selfWindow, '');
  7804. self.cmd.selection();
  7805. var a = self.plugin.getSelectedLink();
  7806. if(a) {
  7807. self.cmd.range.selectNode(a[0]);
  7808. self.cmd.select();
  7809. urlBox.val(a.attr('data-ke-src'));
  7810. typeBox.val(a.attr('target'));
  7811. }
  7812. urlBox[0].focus();
  7813. urlBox[0].select();
  7814. },
  7815. 'delete': function() {
  7816. self.exec('unlink', null);
  7817. }
  7818. };
  7819. self.clickToolbar(name, self.plugin.link.edit);
  7820. });
  7821. /*******************************************************************************
  7822. * KindEditor - WYSIWYG HTML Editor for Internet
  7823. * Copyright (C) 2006-2011 kindsoft.net
  7824. *
  7825. * @author Roddy <luolonghao@gmail.com>
  7826. * @site http://www.kindsoft.net/
  7827. * @licence http://www.kindsoft.net/license.php
  7828. *******************************************************************************/
  7829. // Google Maps: http://code.google.com/apis/maps/index.html
  7830. KindEditor.plugin('map', function(K) {
  7831. var self = this,
  7832. name = 'map',
  7833. lang = self.lang(name + '.');
  7834. self.clickToolbar(name, function() {
  7835. var html = ['<div style="padding:10px 20px;">',
  7836. '<div class="ke-dialog-row">',
  7837. lang.address + ' <input id="kindeditor_plugin_map_address" name="address" class="ke-input-text" value="" style="width:200px;" /> ',
  7838. '<span class="ke-button-common ke-button-outer">',
  7839. '<input type="button" name="searchBtn" class="ke-button-common ke-button" value="' + lang.search + '" />',
  7840. '</span>',
  7841. '</div>',
  7842. '<div class="ke-map" style="width:558px;height:360px;"></div>',
  7843. '</div>'
  7844. ].join('');
  7845. var dialog = self.createDialog({
  7846. name: name,
  7847. width: 600,
  7848. title: self.lang(name),
  7849. body: html,
  7850. yesBtn: {
  7851. name: self.lang('yes'),
  7852. click: function(e) {
  7853. var geocoder = win.geocoder,
  7854. map = win.map,
  7855. center = map.getCenter().lat() + ',' + map.getCenter().lng(),
  7856. zoom = map.getZoom(),
  7857. maptype = map.getMapTypeId(),
  7858. url = 'http://maps.googleapis.com/maps/api/staticmap';
  7859. url += '?center=' + encodeURIComponent(center);
  7860. url += '&zoom=' + encodeURIComponent(zoom);
  7861. url += '&size=558x360';
  7862. url += '&maptype=' + encodeURIComponent(maptype);
  7863. url += '&markers=' + encodeURIComponent(center);
  7864. url += '&language=' + self.langType;
  7865. url += '&sensor=false';
  7866. self.exec('insertimage', url).hideDialog().focus();
  7867. }
  7868. },
  7869. beforeRemove: function() {
  7870. searchBtn.remove();
  7871. if(doc) {
  7872. doc.write('');
  7873. }
  7874. iframe.remove();
  7875. }
  7876. });
  7877. var div = dialog.div,
  7878. addressBox = K('[name="address"]', div),
  7879. searchBtn = K('[name="searchBtn"]', div),
  7880. win, doc;
  7881. var iframeHtml = ['<!doctype html><html><head>',
  7882. '<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />',
  7883. '<style>',
  7884. ' html { height: 100% }',
  7885. ' body { height: 100%; margin: 0; padding: 0; background-color: #FFF }',
  7886. ' #map_canvas { height: 100% }',
  7887. '</style>',
  7888. '<script src="http://maps.googleapis.com/maps/api/js?sensor=false&language=' + self.langType + '"></script>',
  7889. '<script>',
  7890. 'var map, geocoder;',
  7891. 'function initialize() {',
  7892. ' var latlng = new google.maps.LatLng(31.230393, 121.473704);',
  7893. ' var options = {',
  7894. ' zoom: 11,',
  7895. ' center: latlng,',
  7896. ' disableDefaultUI: true,',
  7897. ' panControl: true,',
  7898. ' zoomControl: true,',
  7899. ' mapTypeControl: true,',
  7900. ' scaleControl: true,',
  7901. ' streetViewControl: false,',
  7902. ' overviewMapControl: true,',
  7903. ' mapTypeId: google.maps.MapTypeId.ROADMAP',
  7904. ' };',
  7905. ' map = new google.maps.Map(document.getElementById("map_canvas"), options);',
  7906. ' geocoder = new google.maps.Geocoder();',
  7907. ' geocoder.geocode({latLng: latlng}, function(results, status) {',
  7908. ' if (status == google.maps.GeocoderStatus.OK) {',
  7909. ' if (results[3]) {',
  7910. ' parent.document.getElementById("kindeditor_plugin_map_address").value = results[3].formatted_address;',
  7911. ' }',
  7912. ' }',
  7913. ' });',
  7914. '}',
  7915. 'function search(address) {',
  7916. ' if (!map) return;',
  7917. ' geocoder.geocode({address : address}, function(results, status) {',
  7918. ' if (status == google.maps.GeocoderStatus.OK) {',
  7919. ' map.setZoom(11);',
  7920. ' map.setCenter(results[0].geometry.location);',
  7921. ' var marker = new google.maps.Marker({',
  7922. ' map: map,',
  7923. ' position: results[0].geometry.location',
  7924. ' });',
  7925. ' } else {',
  7926. ' alert("Invalid address: " + address);',
  7927. ' }',
  7928. ' });',
  7929. '}',
  7930. '</script>',
  7931. '</head>',
  7932. '<body onload="initialize();">',
  7933. '<div id="map_canvas" style="width:100%; height:100%"></div>',
  7934. '</body></html>'
  7935. ].join('\n');
  7936. // TODO:用doc.write(iframeHtml)方式加载时,在IE6上第一次加载报错,暂时使用src方式
  7937. var iframe = K('<iframe class="ke-textarea" frameborder="0" src="' + self.pluginsPath + 'map/map.html" style="width:558px;height:360px;"></iframe>');
  7938. function ready() {
  7939. win = iframe[0].contentWindow;
  7940. doc = K.iframeDoc(iframe);
  7941. //doc.open();
  7942. //doc.write(iframeHtml);
  7943. //doc.close();
  7944. }
  7945. iframe.bind('load', function() {
  7946. iframe.unbind('load');
  7947. if(K.IE) {
  7948. ready();
  7949. } else {
  7950. setTimeout(ready, 0);
  7951. }
  7952. });
  7953. K('.ke-map', div).replaceWith(iframe);
  7954. // search map
  7955. searchBtn.click(function() {
  7956. win.search(addressBox.val());
  7957. });
  7958. });
  7959. });
  7960. /*******************************************************************************
  7961. * KindEditor - WYSIWYG HTML Editor for Internet
  7962. * Copyright (C) 2006-2011 kindsoft.net
  7963. *
  7964. * @author Roddy <luolonghao@gmail.com>
  7965. * @site http://www.kindsoft.net/
  7966. * @licence http://www.kindsoft.net/license.php
  7967. *******************************************************************************/
  7968. KindEditor.plugin('media', function(K) {
  7969. var self = this,
  7970. name = 'media',
  7971. lang = self.lang(name + '.'),
  7972. allowMediaUpload = K.undef(self.allowMediaUpload, true),
  7973. allowFileManager = K.undef(self.allowFileManager, false),
  7974. formatUploadUrl = K.undef(self.formatUploadUrl, true),
  7975. extraParams = K.undef(self.extraFileUploadParams, {}),
  7976. filePostName = K.undef(self.filePostName, 'imgFile'),
  7977. uploadJson = K.undef(self.uploadJson, self.basePath + 'php/upload_json.php');
  7978. self.plugin.media = {
  7979. edit: function() {
  7980. var html = [
  7981. '<div style="padding:20px;">',
  7982. //url
  7983. '<div class="ke-dialog-row">',
  7984. '<label for="keUrl" style="width:60px;">' + lang.url + '</label>',
  7985. '<input class="ke-input-text" type="text" id="keUrl" name="url" value="" placeholder="' + lang.urlTip + '" style="width:160px;" /> &nbsp;',
  7986. '<input type="button" class="ke-upload-button" value="' + lang.upload + '" /> &nbsp;',
  7987. '<span class="ke-button-common ke-button-outer">',
  7988. '<input type="button" class="ke-button-common ke-button" name="viewServer" value="' + lang.viewServer + '" />',
  7989. '</span>',
  7990. '</div>',
  7991. //width
  7992. '<div class="ke-dialog-row">',
  7993. '<label for="keWidth" style="width:60px;">' + lang.width + '</label>',
  7994. '<input type="text" id="keWidth" class="ke-input-text ke-input-number" name="width" value="550" maxlength="4" />',
  7995. '</div>',
  7996. //height
  7997. '<div class="ke-dialog-row">',
  7998. '<label for="keHeight" style="width:60px;">' + lang.height + '</label>',
  7999. '<input type="text" id="keHeight" class="ke-input-text ke-input-number" name="height" value="400" maxlength="4" />',
  8000. '</div>',
  8001. //controls
  8002. '<div class="ke-dialog-row hidden">',
  8003. '<label for="keControls">' + lang.controls + '</label>',
  8004. '<input type="checkbox" id="keControls" checked name="controls" value="true" /> ',
  8005. '</div>',
  8006. //autostart
  8007. '<div class="ke-dialog-row">',
  8008. '<label for="keAutostart">' + lang.autostart + '</label>',
  8009. '<input type="checkbox" id="keAutostart" name="autostart" value="" /> ',
  8010. '</div>',
  8011. '</div>'
  8012. ].join('');
  8013. var dialog = self.createDialog({
  8014. name: name,
  8015. width: 450,
  8016. height: 240,
  8017. title: self.lang(name),
  8018. body: html,
  8019. yesBtn: {
  8020. name: self.lang('yes'),
  8021. click: function(e) {
  8022. var url = K.trim(urlBox.val()),
  8023. width = widthBox.val(),
  8024. height = heightBox.val();
  8025. if(url == 'http://' || K.invalidUrl(url)) {
  8026. alert(self.lang('invalidUrl'));
  8027. urlBox[0].focus();
  8028. return;
  8029. }
  8030. if(!/^\d*$/.test(width)) {
  8031. alert(self.lang('invalidWidth'));
  8032. widthBox[0].focus();
  8033. return;
  8034. }
  8035. if(!/^\d*$/.test(height)) {
  8036. alert(self.lang('invalidHeight'));
  8037. heightBox[0].focus();
  8038. return;
  8039. }
  8040. var html = K.mediaImg(self.themesPath + 'common/blank.gif', {
  8041. src: url,
  8042. type: K.mediaType(url),
  8043. width: width,
  8044. height: height,
  8045. autoplay: !!autostartBox[0].checked,
  8046. controls: !!controlsBox[0].checked,
  8047. });
  8048. self.insertHtml(html).hideDialog().focus();
  8049. }
  8050. }
  8051. }),
  8052. div = dialog.div,
  8053. urlBox = K('[name="url"]', div),
  8054. viewServerBtn = K('[name="viewServer"]', div),
  8055. widthBox = K('[name="width"]', div),
  8056. heightBox = K('[name="height"]', div),
  8057. controlsBox = K('[name="controls"]', div),
  8058. autostartBox = K('[name="autostart"]', div);
  8059. urlBox.val('http://');
  8060. if(allowMediaUpload) {
  8061. var uploadbutton = K.uploadbutton({
  8062. button: K('.ke-upload-button', div)[0],
  8063. fieldName: filePostName,
  8064. extraParams: extraParams,
  8065. url: K.addParam(uploadJson, 'dir=media'),
  8066. afterUpload: function(data) {
  8067. dialog.hideLoading();
  8068. if(data.error === 0) {
  8069. var url = data.url;
  8070. if(formatUploadUrl) {
  8071. url = K.formatUrl(url, 'absolute');
  8072. }
  8073. urlBox.val(url);
  8074. if(self.afterUpload) {
  8075. self.afterUpload.call(self, url, data, name);
  8076. }
  8077. alert(self.lang('uploadSuccess'));
  8078. } else {
  8079. alert(data.message);
  8080. }
  8081. },
  8082. afterError: function(html) {
  8083. dialog.hideLoading();
  8084. self.errorDialog(html);
  8085. }
  8086. });
  8087. uploadbutton.fileBox.change(function(e) {
  8088. dialog.showLoading(self.lang('uploadLoading'));
  8089. uploadbutton.submit();
  8090. });
  8091. } else {
  8092. K('.ke-upload-button', div).hide();
  8093. }
  8094. if(allowFileManager) {
  8095. viewServerBtn.click(function(e) {
  8096. self.loadPlugin('filemanager', function() {
  8097. self.plugin.filemanagerDialog({
  8098. viewType: 'LIST',
  8099. dirName: 'media',
  8100. clickFn: function(url, title) {
  8101. if(self.dialogs.length > 1) {
  8102. K('[name="url"]', div).val(url);
  8103. if(self.afterSelectFile) {
  8104. self.afterSelectFile.call(self, url);
  8105. }
  8106. self.hideDialog();
  8107. }
  8108. }
  8109. });
  8110. });
  8111. });
  8112. } else {
  8113. viewServerBtn.hide();
  8114. }
  8115. var img = self.plugin.getSelectedMedia();
  8116. if(img) {
  8117. var attrs = K.mediaAttrs(img.attr('data-ke-tag'));
  8118. urlBox.val(attrs.src);
  8119. widthBox.val(K.removeUnit(img.css('width')) || attrs.width || 0);
  8120. heightBox.val(K.removeUnit(img.css('height')) || attrs.height || 0);
  8121. autostartBox[0].checked = (attrs.autoplay !== undefined && attrs.autoplay !== 'false');
  8122. controlsBox[0].checked = (attrs.controls !== undefined && attrs.controls !== 'false');
  8123. }
  8124. urlBox[0].focus();
  8125. urlBox[0].select();
  8126. },
  8127. 'delete': function() {
  8128. self.plugin.getSelectedMedia().remove();
  8129. // [IE] 删除图片后立即点击图片按钮出错
  8130. self.addBookmark();
  8131. }
  8132. };
  8133. self.clickToolbar(name, self.plugin.media.edit);
  8134. });
  8135. /*******************************************************************************
  8136. * KindEditor - WYSIWYG HTML Editor for Internet
  8137. * Copyright (C) 2006-2011 kindsoft.net
  8138. *
  8139. * @author Roddy <luolonghao@gmail.com>
  8140. * @site http://www.kindsoft.net/
  8141. * @licence http://www.kindsoft.net/license.php
  8142. *******************************************************************************/
  8143. (function(K) {
  8144. function KSWFUpload(options) {
  8145. this.init(options);
  8146. }
  8147. K.extend(KSWFUpload, {
  8148. init : function(options) {
  8149. var self = this;
  8150. options.afterError = options.afterError || function(str) {
  8151. alert(str);
  8152. };
  8153. self.options = options;
  8154. self.progressbars = {};
  8155. // template
  8156. self.div = K(options.container).html([
  8157. '<div class="ke-swfupload">',
  8158. '<div class="ke-swfupload-top">',
  8159. '<div class="ke-inline-block ke-swfupload-button">',
  8160. '<input type="button" value="Browse" />',
  8161. '</div>',
  8162. '<div class="ke-inline-block ke-swfupload-desc">' + options.uploadDesc + '</div>',
  8163. '<span class="ke-button-common ke-button-outer ke-swfupload-startupload">',
  8164. '<input type="button" class="ke-button-common ke-button" value="' + options.startButtonValue + '" />',
  8165. '</span>',
  8166. '</div>',
  8167. '<div class="ke-swfupload-body"></div>',
  8168. '</div>'
  8169. ].join(''));
  8170. self.bodyDiv = K('.ke-swfupload-body', self.div);
  8171. function showError(itemDiv, msg) {
  8172. K('.ke-status > div', itemDiv).hide();
  8173. K('.ke-message', itemDiv).addClass('ke-error').show().html(K.escape(msg));
  8174. }
  8175. var settings = {
  8176. debug : false,
  8177. upload_url : options.uploadUrl,
  8178. flash_url : options.flashUrl,
  8179. file_post_name : options.filePostName,
  8180. button_placeholder : K('.ke-swfupload-button > input', self.div)[0],
  8181. button_image_url: options.buttonImageUrl,
  8182. button_width: options.buttonWidth,
  8183. button_height: options.buttonHeight,
  8184. button_cursor : SWFUpload.CURSOR.HAND,
  8185. file_types : options.fileTypes,
  8186. file_types_description : options.fileTypesDesc,
  8187. file_upload_limit : options.fileUploadLimit,
  8188. file_size_limit : options.fileSizeLimit,
  8189. post_params : options.postParams,
  8190. file_queued_handler : function(file) {
  8191. file.url = self.options.fileIconUrl;
  8192. self.appendFile(file);
  8193. },
  8194. file_queue_error_handler : function(file, errorCode, message) {
  8195. var errorName = '';
  8196. switch (errorCode) {
  8197. case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
  8198. errorName = options.queueLimitExceeded;
  8199. break;
  8200. case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
  8201. errorName = options.fileExceedsSizeLimit;
  8202. break;
  8203. case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
  8204. errorName = options.zeroByteFile;
  8205. break;
  8206. case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
  8207. errorName = options.invalidFiletype;
  8208. break;
  8209. default:
  8210. errorName = options.unknownError;
  8211. break;
  8212. }
  8213. K.DEBUG && alert(errorName);
  8214. },
  8215. upload_start_handler : function(file) {
  8216. var self = this;
  8217. var itemDiv = K('div[data-id="' + file.id + '"]', self.bodyDiv);
  8218. K('.ke-status > div', itemDiv).hide();
  8219. K('.ke-progressbar', itemDiv).show();
  8220. },
  8221. upload_progress_handler : function(file, bytesLoaded, bytesTotal) {
  8222. var percent = Math.round(bytesLoaded * 100 / bytesTotal);
  8223. var progressbar = self.progressbars[file.id];
  8224. progressbar.bar.css('width', Math.round(percent * 80 / 100) + 'px');
  8225. progressbar.percent.html(percent + '%');
  8226. },
  8227. upload_error_handler : function(file, errorCode, message) {
  8228. if (file && file.filestatus == SWFUpload.FILE_STATUS.ERROR) {
  8229. var itemDiv = K('div[data-id="' + file.id + '"]', self.bodyDiv).eq(0);
  8230. showError(itemDiv, self.options.errorMessage);
  8231. }
  8232. },
  8233. upload_success_handler : function(file, serverData) {
  8234. var itemDiv = K('div[data-id="' + file.id + '"]', self.bodyDiv).eq(0);
  8235. var data = {};
  8236. try {
  8237. data = K.json(serverData);
  8238. } catch (e) {
  8239. self.options.afterError.call(this, '<!doctype html><html>' + serverData + '</html>');
  8240. }
  8241. if (data.error !== 0) {
  8242. showError(itemDiv, K.DEBUG ? data.message : self.options.errorMessage);
  8243. return;
  8244. }
  8245. file.url = data.url;
  8246. K('.ke-img', itemDiv).attr('src', file.url).attr('data-status', file.filestatus).data('data', data);
  8247. K('.ke-status > div', itemDiv).hide();
  8248. }
  8249. };
  8250. self.swfu = new SWFUpload(settings);
  8251. K('.ke-swfupload-startupload input', self.div).click(function() {
  8252. self.swfu.startUpload();
  8253. });
  8254. },
  8255. getUrlList : function() {
  8256. var list = [];
  8257. K('.ke-img', self.bodyDiv).each(function() {
  8258. var img = K(this);
  8259. var status = img.attr('data-status');
  8260. if (status == SWFUpload.FILE_STATUS.COMPLETE) {
  8261. list.push(img.data('data'));
  8262. }
  8263. });
  8264. return list;
  8265. },
  8266. removeFile : function(fileId) {
  8267. var self = this;
  8268. self.swfu.cancelUpload(fileId);
  8269. var itemDiv = K('div[data-id="' + fileId + '"]', self.bodyDiv);
  8270. K('.ke-photo', itemDiv).unbind();
  8271. K('.ke-delete', itemDiv).unbind();
  8272. itemDiv.remove();
  8273. },
  8274. removeFiles : function() {
  8275. var self = this;
  8276. K('.ke-item', self.bodyDiv).each(function() {
  8277. self.removeFile(K(this).attr('data-id'));
  8278. });
  8279. },
  8280. appendFile : function(file) {
  8281. var self = this;
  8282. var itemDiv = K('<div class="ke-inline-block ke-item" data-id="' + file.id + '"></div>');
  8283. self.bodyDiv.append(itemDiv);
  8284. var photoDiv = K('<div class="ke-inline-block ke-photo"></div>')
  8285. .mouseover(function(e) {
  8286. K(this).addClass('ke-on');
  8287. })
  8288. .mouseout(function(e) {
  8289. K(this).removeClass('ke-on');
  8290. });
  8291. itemDiv.append(photoDiv);
  8292. var img = K('<img src="' + file.url + '" class="ke-img" data-status="' + file.filestatus + '" width="80" height="80" alt="' + file.name + '" />');
  8293. photoDiv.append(img);
  8294. K('<span class="ke-delete"></span>').appendTo(photoDiv).click(function() {
  8295. self.removeFile(file.id);
  8296. });
  8297. var statusDiv = K('<div class="ke-status"></div>').appendTo(photoDiv);
  8298. // progressbar
  8299. K(['<div class="ke-progressbar">',
  8300. '<div class="ke-progressbar-bar"><div class="ke-progressbar-bar-inner"></div></div>',
  8301. '<div class="ke-progressbar-percent">0%</div></div>'].join('')).hide().appendTo(statusDiv);
  8302. // message
  8303. K('<div class="ke-message">' + self.options.pendingMessage + '</div>').appendTo(statusDiv);
  8304. itemDiv.append('<div class="ke-name">' + file.name + '</div>');
  8305. self.progressbars[file.id] = {
  8306. bar : K('.ke-progressbar-bar-inner', photoDiv),
  8307. percent : K('.ke-progressbar-percent', photoDiv)
  8308. };
  8309. },
  8310. remove : function() {
  8311. this.removeFiles();
  8312. this.swfu.destroy();
  8313. this.div.html('');
  8314. }
  8315. });
  8316. K.swfupload = function(element, options) {
  8317. return new KSWFUpload(element, options);
  8318. };
  8319. })(KindEditor);
  8320. KindEditor.plugin('multiimage', function(K) {
  8321. var self = this, name = 'multiimage',
  8322. formatUploadUrl = K.undef(self.formatUploadUrl, true),
  8323. uploadJson = K.undef(self.uploadJson, self.basePath + 'php/upload_json.php'),
  8324. imgPath = self.pluginsPath + 'multiimage/images/',
  8325. imageSizeLimit = K.undef(self.imageSizeLimit, '1MB'),
  8326. imageFileTypes = K.undef(self.imageFileTypes, '*.jpg;*.gif;*.png'),
  8327. imageUploadLimit = K.undef(self.imageUploadLimit, 20),
  8328. filePostName = K.undef(self.filePostName, 'imgFile'),
  8329. lang = self.lang(name + '.');
  8330. self.plugin.multiImageDialog = function(options) {
  8331. var clickFn = options.clickFn,
  8332. uploadDesc = K.tmpl(lang.uploadDesc, {uploadLimit : imageUploadLimit, sizeLimit : imageSizeLimit});
  8333. var html = [
  8334. '<div style="padding:20px;">',
  8335. '<div class="swfupload">',
  8336. '</div>',
  8337. '</div>'
  8338. ].join('');
  8339. var dialog = self.createDialog({
  8340. name : name,
  8341. width : 650,
  8342. height : 510,
  8343. title : self.lang(name),
  8344. body : html,
  8345. previewBtn : {
  8346. name : lang.insertAll,
  8347. click : function(e) {
  8348. clickFn.call(self, swfupload.getUrlList());
  8349. }
  8350. },
  8351. yesBtn : {
  8352. name : lang.clearAll,
  8353. click : function(e) {
  8354. swfupload.removeFiles();
  8355. }
  8356. },
  8357. beforeRemove : function() {
  8358. // IE9 bugfix: https://github.com/kindsoft/kindeditor/issues/72
  8359. if (!K.IE || K.V <= 8) {
  8360. swfupload.remove();
  8361. }
  8362. }
  8363. }),
  8364. div = dialog.div;
  8365. var swfupload = K.swfupload({
  8366. container : K('.swfupload', div),
  8367. buttonImageUrl : imgPath + (self.langType == 'zh-CN' ? 'select-files-zh-CN.png' : 'select-files-en.png'),
  8368. buttonWidth : self.langType == 'zh-CN' ? 72 : 88,
  8369. buttonHeight : 23,
  8370. fileIconUrl : imgPath + 'image.png',
  8371. uploadDesc : uploadDesc,
  8372. startButtonValue : lang.startUpload,
  8373. uploadUrl : K.addParam(uploadJson, 'dir=image'),
  8374. flashUrl : imgPath + 'swfupload.swf',
  8375. filePostName : filePostName,
  8376. fileTypes : '*.jpg;*.jpeg;*.gif;*.png;*.bmp',
  8377. fileTypesDesc : 'Image Files',
  8378. fileUploadLimit : imageUploadLimit,
  8379. fileSizeLimit : imageSizeLimit,
  8380. postParams : K.undef(self.extraFileUploadParams, {}),
  8381. queueLimitExceeded : lang.queueLimitExceeded,
  8382. fileExceedsSizeLimit : lang.fileExceedsSizeLimit,
  8383. zeroByteFile : lang.zeroByteFile,
  8384. invalidFiletype : lang.invalidFiletype,
  8385. unknownError : lang.unknownError,
  8386. pendingMessage : lang.pending,
  8387. errorMessage : lang.uploadError,
  8388. afterError : function(html) {
  8389. self.errorDialog(html);
  8390. }
  8391. });
  8392. return dialog;
  8393. };
  8394. self.clickToolbar(name, function() {
  8395. self.plugin.multiImageDialog({
  8396. clickFn : function (urlList) {
  8397. if (urlList.length === 0) {
  8398. return;
  8399. }
  8400. K.each(urlList, function(i, data) {
  8401. if (self.afterUpload) {
  8402. self.afterUpload.call(self, data.url, data, 'multiimage');
  8403. }
  8404. self.exec('insertimage', data.url, data.title, data.width, data.height, data.border, data.align);
  8405. });
  8406. // Bugfix: [Firefox] 上传图片后,总是出现正在加载的样式,需要延迟执行hideDialog
  8407. setTimeout(function() {
  8408. self.hideDialog().focus();
  8409. }, 0);
  8410. }
  8411. });
  8412. });
  8413. });
  8414. /**
  8415. * SWFUpload: http://www.swfupload.org, http://swfupload.googlecode.com
  8416. *
  8417. * mmSWFUpload 1.0: Flash upload dialog - http://profandesign.se/swfupload/, http://www.vinterwebb.se/
  8418. *
  8419. * SWFUpload is (c) 2006-2007 Lars Huring, Olov Nilz閚 and Mammon Media and is released under the MIT License:
  8420. * http://www.opensource.org/licenses/mit-license.php
  8421. *
  8422. * SWFUpload 2 is (c) 2007-2008 Jake Roberts and is released under the MIT License:
  8423. * http://www.opensource.org/licenses/mit-license.php
  8424. *
  8425. */
  8426. /* ******************* */
  8427. /* Constructor & Init */
  8428. /* ******************* */
  8429. (function() {
  8430. window.SWFUpload = function (settings) {
  8431. this.initSWFUpload(settings);
  8432. };
  8433. SWFUpload.prototype.initSWFUpload = function (settings) {
  8434. try {
  8435. this.customSettings = {}; // A container where developers can place their own settings associated with this instance.
  8436. this.settings = settings;
  8437. this.eventQueue = [];
  8438. this.movieName = "KindEditor_SWFUpload_" + SWFUpload.movieCount++;
  8439. this.movieElement = null;
  8440. // Setup global control tracking
  8441. SWFUpload.instances[this.movieName] = this;
  8442. // Load the settings. Load the Flash movie.
  8443. this.initSettings();
  8444. this.loadFlash();
  8445. this.displayDebugInfo();
  8446. } catch (ex) {
  8447. delete SWFUpload.instances[this.movieName];
  8448. throw ex;
  8449. }
  8450. };
  8451. /* *************** */
  8452. /* Static Members */
  8453. /* *************** */
  8454. SWFUpload.instances = {};
  8455. SWFUpload.movieCount = 0;
  8456. SWFUpload.version = "2.2.0 2009-03-25";
  8457. SWFUpload.QUEUE_ERROR = {
  8458. QUEUE_LIMIT_EXCEEDED : -100,
  8459. FILE_EXCEEDS_SIZE_LIMIT : -110,
  8460. ZERO_BYTE_FILE : -120,
  8461. INVALID_FILETYPE : -130
  8462. };
  8463. SWFUpload.UPLOAD_ERROR = {
  8464. HTTP_ERROR : -200,
  8465. MISSING_UPLOAD_URL : -210,
  8466. IO_ERROR : -220,
  8467. SECURITY_ERROR : -230,
  8468. UPLOAD_LIMIT_EXCEEDED : -240,
  8469. UPLOAD_FAILED : -250,
  8470. SPECIFIED_FILE_ID_NOT_FOUND : -260,
  8471. FILE_VALIDATION_FAILED : -270,
  8472. FILE_CANCELLED : -280,
  8473. UPLOAD_STOPPED : -290
  8474. };
  8475. SWFUpload.FILE_STATUS = {
  8476. QUEUED : -1,
  8477. IN_PROGRESS : -2,
  8478. ERROR : -3,
  8479. COMPLETE : -4,
  8480. CANCELLED : -5
  8481. };
  8482. SWFUpload.BUTTON_ACTION = {
  8483. SELECT_FILE : -100,
  8484. SELECT_FILES : -110,
  8485. START_UPLOAD : -120
  8486. };
  8487. SWFUpload.CURSOR = {
  8488. ARROW : -1,
  8489. HAND : -2
  8490. };
  8491. SWFUpload.WINDOW_MODE = {
  8492. WINDOW : "window",
  8493. TRANSPARENT : "transparent",
  8494. OPAQUE : "opaque"
  8495. };
  8496. // Private: takes a URL, determines if it is relative and converts to an absolute URL
  8497. // using the current site. Only processes the URL if it can, otherwise returns the URL untouched
  8498. SWFUpload.completeURL = function(url) {
  8499. if (typeof(url) !== "string" || url.match(/^https?:\/\//i) || url.match(/^\//)) {
  8500. return url;
  8501. }
  8502. var currentURL = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ":" + window.location.port : "");
  8503. var indexSlash = window.location.pathname.lastIndexOf("/");
  8504. if (indexSlash <= 0) {
  8505. path = "/";
  8506. } else {
  8507. path = window.location.pathname.substr(0, indexSlash) + "/";
  8508. }
  8509. return /*currentURL +*/ path + url;
  8510. };
  8511. /* ******************** */
  8512. /* Instance Members */
  8513. /* ******************** */
  8514. // Private: initSettings ensures that all the
  8515. // settings are set, getting a default value if one was not assigned.
  8516. SWFUpload.prototype.initSettings = function () {
  8517. this.ensureDefault = function (settingName, defaultValue) {
  8518. this.settings[settingName] = (this.settings[settingName] == undefined) ? defaultValue : this.settings[settingName];
  8519. };
  8520. // Upload backend settings
  8521. this.ensureDefault("upload_url", "");
  8522. this.ensureDefault("preserve_relative_urls", false);
  8523. this.ensureDefault("file_post_name", "Filedata");
  8524. this.ensureDefault("post_params", {});
  8525. this.ensureDefault("use_query_string", false);
  8526. this.ensureDefault("requeue_on_error", false);
  8527. this.ensureDefault("http_success", []);
  8528. this.ensureDefault("assume_success_timeout", 0);
  8529. // File Settings
  8530. this.ensureDefault("file_types", "*.*");
  8531. this.ensureDefault("file_types_description", "All Files");
  8532. this.ensureDefault("file_size_limit", 0); // Default zero means "unlimited"
  8533. this.ensureDefault("file_upload_limit", 0);
  8534. this.ensureDefault("file_queue_limit", 0);
  8535. // Flash Settings
  8536. this.ensureDefault("flash_url", "swfupload.swf");
  8537. this.ensureDefault("prevent_swf_caching", true);
  8538. // Button Settings
  8539. this.ensureDefault("button_image_url", "");
  8540. this.ensureDefault("button_width", 1);
  8541. this.ensureDefault("button_height", 1);
  8542. this.ensureDefault("button_text", "");
  8543. this.ensureDefault("button_text_style", "color: #000000; font-size: 16pt;");
  8544. this.ensureDefault("button_text_top_padding", 0);
  8545. this.ensureDefault("button_text_left_padding", 0);
  8546. this.ensureDefault("button_action", SWFUpload.BUTTON_ACTION.SELECT_FILES);
  8547. this.ensureDefault("button_disabled", false);
  8548. this.ensureDefault("button_placeholder_id", "");
  8549. this.ensureDefault("button_placeholder", null);
  8550. this.ensureDefault("button_cursor", SWFUpload.CURSOR.ARROW);
  8551. this.ensureDefault("button_window_mode", SWFUpload.WINDOW_MODE.WINDOW);
  8552. // Debug Settings
  8553. this.ensureDefault("debug", false);
  8554. this.settings.debug_enabled = this.settings.debug; // Here to maintain v2 API
  8555. // Event Handlers
  8556. this.settings.return_upload_start_handler = this.returnUploadStart;
  8557. this.ensureDefault("swfupload_loaded_handler", null);
  8558. this.ensureDefault("file_dialog_start_handler", null);
  8559. this.ensureDefault("file_queued_handler", null);
  8560. this.ensureDefault("file_queue_error_handler", null);
  8561. this.ensureDefault("file_dialog_complete_handler", null);
  8562. this.ensureDefault("upload_start_handler", null);
  8563. this.ensureDefault("upload_progress_handler", null);
  8564. this.ensureDefault("upload_error_handler", null);
  8565. this.ensureDefault("upload_success_handler", null);
  8566. this.ensureDefault("upload_complete_handler", null);
  8567. this.ensureDefault("debug_handler", this.debugMessage);
  8568. this.ensureDefault("custom_settings", {});
  8569. // Other settings
  8570. this.customSettings = this.settings.custom_settings;
  8571. // Update the flash url if needed
  8572. if (!!this.settings.prevent_swf_caching) {
  8573. this.settings.flash_url = this.settings.flash_url + (this.settings.flash_url.indexOf("?") < 0 ? "?" : "&") + "preventswfcaching=" + new Date().getTime();
  8574. }
  8575. if (!this.settings.preserve_relative_urls) {
  8576. //this.settings.flash_url = SWFUpload.completeURL(this.settings.flash_url); // Don't need to do this one since flash doesn't look at it
  8577. this.settings.upload_url = SWFUpload.completeURL(this.settings.upload_url);
  8578. this.settings.button_image_url = SWFUpload.completeURL(this.settings.button_image_url);
  8579. }
  8580. delete this.ensureDefault;
  8581. };
  8582. // Private: loadFlash replaces the button_placeholder element with the flash movie.
  8583. SWFUpload.prototype.loadFlash = function () {
  8584. var targetElement, tempParent;
  8585. // Make sure an element with the ID we are going to use doesn't already exist
  8586. if (document.getElementById(this.movieName) !== null) {
  8587. throw "ID " + this.movieName + " is already in use. The Flash Object could not be added";
  8588. }
  8589. // Get the element where we will be placing the flash movie
  8590. targetElement = document.getElementById(this.settings.button_placeholder_id) || this.settings.button_placeholder;
  8591. if (targetElement == undefined) {
  8592. throw "Could not find the placeholder element: " + this.settings.button_placeholder_id;
  8593. }
  8594. // Append the container and load the flash
  8595. tempParent = document.createElement("div");
  8596. tempParent.innerHTML = this.getFlashHTML(); // Using innerHTML is non-standard but the only sensible way to dynamically add Flash in IE (and maybe other browsers)
  8597. targetElement.parentNode.replaceChild(tempParent.firstChild, targetElement);
  8598. // Fix IE Flash/Form bug
  8599. if (window[this.movieName] == undefined) {
  8600. window[this.movieName] = this.getMovieElement();
  8601. }
  8602. };
  8603. // Private: getFlashHTML generates the object tag needed to embed the flash in to the document
  8604. SWFUpload.prototype.getFlashHTML = function () {
  8605. // Flash Satay object syntax: http://www.alistapart.com/articles/flashsatay
  8606. // Fix bug for IE9
  8607. // http://www.kindsoft.net/view.php?bbsid=7&postid=5825&pagenum=1
  8608. var classid = '';
  8609. if (KindEditor.IE && KindEditor.V > 8) {
  8610. classid = ' classid = "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"';
  8611. }
  8612. return ['<object id="', this.movieName, '"' + classid + ' type="application/x-shockwave-flash" data="', this.settings.flash_url, '" width="', this.settings.button_width, '" height="', this.settings.button_height, '" class="swfupload">',
  8613. '<param name="wmode" value="', this.settings.button_window_mode, '" />',
  8614. '<param name="movie" value="', this.settings.flash_url, '" />',
  8615. '<param name="quality" value="high" />',
  8616. '<param name="menu" value="false" />',
  8617. '<param name="allowScriptAccess" value="always" />',
  8618. '<param name="flashvars" value="' + this.getFlashVars() + '" />',
  8619. '</object>'].join("");
  8620. };
  8621. // Private: getFlashVars builds the parameter string that will be passed
  8622. // to flash in the flashvars param.
  8623. SWFUpload.prototype.getFlashVars = function () {
  8624. // Build a string from the post param object
  8625. var paramString = this.buildParamString();
  8626. var httpSuccessString = this.settings.http_success.join(",");
  8627. // Build the parameter string
  8628. return ["movieName=", encodeURIComponent(this.movieName),
  8629. "&amp;uploadURL=", encodeURIComponent(this.settings.upload_url),
  8630. "&amp;useQueryString=", encodeURIComponent(this.settings.use_query_string),
  8631. "&amp;requeueOnError=", encodeURIComponent(this.settings.requeue_on_error),
  8632. "&amp;httpSuccess=", encodeURIComponent(httpSuccessString),
  8633. "&amp;assumeSuccessTimeout=", encodeURIComponent(this.settings.assume_success_timeout),
  8634. "&amp;params=", encodeURIComponent(paramString),
  8635. "&amp;filePostName=", encodeURIComponent(this.settings.file_post_name),
  8636. "&amp;fileTypes=", encodeURIComponent(this.settings.file_types),
  8637. "&amp;fileTypesDescription=", encodeURIComponent(this.settings.file_types_description),
  8638. "&amp;fileSizeLimit=", encodeURIComponent(this.settings.file_size_limit),
  8639. "&amp;fileUploadLimit=", encodeURIComponent(this.settings.file_upload_limit),
  8640. "&amp;fileQueueLimit=", encodeURIComponent(this.settings.file_queue_limit),
  8641. "&amp;debugEnabled=", encodeURIComponent(this.settings.debug_enabled),
  8642. "&amp;buttonImageURL=", encodeURIComponent(this.settings.button_image_url),
  8643. "&amp;buttonWidth=", encodeURIComponent(this.settings.button_width),
  8644. "&amp;buttonHeight=", encodeURIComponent(this.settings.button_height),
  8645. "&amp;buttonText=", encodeURIComponent(this.settings.button_text),
  8646. "&amp;buttonTextTopPadding=", encodeURIComponent(this.settings.button_text_top_padding),
  8647. "&amp;buttonTextLeftPadding=", encodeURIComponent(this.settings.button_text_left_padding),
  8648. "&amp;buttonTextStyle=", encodeURIComponent(this.settings.button_text_style),
  8649. "&amp;buttonAction=", encodeURIComponent(this.settings.button_action),
  8650. "&amp;buttonDisabled=", encodeURIComponent(this.settings.button_disabled),
  8651. "&amp;buttonCursor=", encodeURIComponent(this.settings.button_cursor)
  8652. ].join("");
  8653. };
  8654. // Public: getMovieElement retrieves the DOM reference to the Flash element added by SWFUpload
  8655. // The element is cached after the first lookup
  8656. SWFUpload.prototype.getMovieElement = function () {
  8657. if (this.movieElement == undefined) {
  8658. this.movieElement = document.getElementById(this.movieName);
  8659. }
  8660. if (this.movieElement === null) {
  8661. throw "Could not find Flash element";
  8662. }
  8663. return this.movieElement;
  8664. };
  8665. // Private: buildParamString takes the name/value pairs in the post_params setting object
  8666. // and joins them up in to a string formatted "name=value&amp;name=value"
  8667. SWFUpload.prototype.buildParamString = function () {
  8668. var postParams = this.settings.post_params;
  8669. var paramStringPairs = [];
  8670. if (typeof(postParams) === "object") {
  8671. for (var name in postParams) {
  8672. if (postParams.hasOwnProperty(name)) {
  8673. paramStringPairs.push(encodeURIComponent(name.toString()) + "=" + encodeURIComponent(postParams[name].toString()));
  8674. }
  8675. }
  8676. }
  8677. return paramStringPairs.join("&amp;");
  8678. };
  8679. // Public: Used to remove a SWFUpload instance from the page. This method strives to remove
  8680. // all references to the SWF, and other objects so memory is properly freed.
  8681. // Returns true if everything was destroyed. Returns a false if a failure occurs leaving SWFUpload in an inconsistant state.
  8682. // Credits: Major improvements provided by steffen
  8683. SWFUpload.prototype.destroy = function () {
  8684. try {
  8685. // Make sure Flash is done before we try to remove it
  8686. this.cancelUpload(null, false);
  8687. // Remove the SWFUpload DOM nodes
  8688. var movieElement = null;
  8689. movieElement = this.getMovieElement();
  8690. if (movieElement && typeof(movieElement.CallFunction) === "unknown") { // We only want to do this in IE
  8691. // Loop through all the movie's properties and remove all function references (DOM/JS IE 6/7 memory leak workaround)
  8692. for (var i in movieElement) {
  8693. try {
  8694. if (typeof(movieElement[i]) === "function") {
  8695. movieElement[i] = null;
  8696. }
  8697. } catch (ex1) {}
  8698. }
  8699. // Remove the Movie Element from the page
  8700. try {
  8701. movieElement.parentNode.removeChild(movieElement);
  8702. } catch (ex) {}
  8703. }
  8704. // Remove IE form fix reference
  8705. window[this.movieName] = null;
  8706. // Destroy other references
  8707. SWFUpload.instances[this.movieName] = null;
  8708. delete SWFUpload.instances[this.movieName];
  8709. this.movieElement = null;
  8710. this.settings = null;
  8711. this.customSettings = null;
  8712. this.eventQueue = null;
  8713. this.movieName = null;
  8714. return true;
  8715. } catch (ex2) {
  8716. return false;
  8717. }
  8718. };
  8719. // Public: displayDebugInfo prints out settings and configuration
  8720. // information about this SWFUpload instance.
  8721. // This function (and any references to it) can be deleted when placing
  8722. // SWFUpload in production.
  8723. SWFUpload.prototype.displayDebugInfo = function () {
  8724. this.debug(
  8725. [
  8726. "---SWFUpload Instance Info---\n",
  8727. "Version: ", SWFUpload.version, "\n",
  8728. "Movie Name: ", this.movieName, "\n",
  8729. "Settings:\n",
  8730. "\t", "upload_url: ", this.settings.upload_url, "\n",
  8731. "\t", "flash_url: ", this.settings.flash_url, "\n",
  8732. "\t", "use_query_string: ", this.settings.use_query_string.toString(), "\n",
  8733. "\t", "requeue_on_error: ", this.settings.requeue_on_error.toString(), "\n",
  8734. "\t", "http_success: ", this.settings.http_success.join(", "), "\n",
  8735. "\t", "assume_success_timeout: ", this.settings.assume_success_timeout, "\n",
  8736. "\t", "file_post_name: ", this.settings.file_post_name, "\n",
  8737. "\t", "post_params: ", this.settings.post_params.toString(), "\n",
  8738. "\t", "file_types: ", this.settings.file_types, "\n",
  8739. "\t", "file_types_description: ", this.settings.file_types_description, "\n",
  8740. "\t", "file_size_limit: ", this.settings.file_size_limit, "\n",
  8741. "\t", "file_upload_limit: ", this.settings.file_upload_limit, "\n",
  8742. "\t", "file_queue_limit: ", this.settings.file_queue_limit, "\n",
  8743. "\t", "debug: ", this.settings.debug.toString(), "\n",
  8744. "\t", "prevent_swf_caching: ", this.settings.prevent_swf_caching.toString(), "\n",
  8745. "\t", "button_placeholder_id: ", this.settings.button_placeholder_id.toString(), "\n",
  8746. "\t", "button_placeholder: ", (this.settings.button_placeholder ? "Set" : "Not Set"), "\n",
  8747. "\t", "button_image_url: ", this.settings.button_image_url.toString(), "\n",
  8748. "\t", "button_width: ", this.settings.button_width.toString(), "\n",
  8749. "\t", "button_height: ", this.settings.button_height.toString(), "\n",
  8750. "\t", "button_text: ", this.settings.button_text.toString(), "\n",
  8751. "\t", "button_text_style: ", this.settings.button_text_style.toString(), "\n",
  8752. "\t", "button_text_top_padding: ", this.settings.button_text_top_padding.toString(), "\n",
  8753. "\t", "button_text_left_padding: ", this.settings.button_text_left_padding.toString(), "\n",
  8754. "\t", "button_action: ", this.settings.button_action.toString(), "\n",
  8755. "\t", "button_disabled: ", this.settings.button_disabled.toString(), "\n",
  8756. "\t", "custom_settings: ", this.settings.custom_settings.toString(), "\n",
  8757. "Event Handlers:\n",
  8758. "\t", "swfupload_loaded_handler assigned: ", (typeof this.settings.swfupload_loaded_handler === "function").toString(), "\n",
  8759. "\t", "file_dialog_start_handler assigned: ", (typeof this.settings.file_dialog_start_handler === "function").toString(), "\n",
  8760. "\t", "file_queued_handler assigned: ", (typeof this.settings.file_queued_handler === "function").toString(), "\n",
  8761. "\t", "file_queue_error_handler assigned: ", (typeof this.settings.file_queue_error_handler === "function").toString(), "\n",
  8762. "\t", "upload_start_handler assigned: ", (typeof this.settings.upload_start_handler === "function").toString(), "\n",
  8763. "\t", "upload_progress_handler assigned: ", (typeof this.settings.upload_progress_handler === "function").toString(), "\n",
  8764. "\t", "upload_error_handler assigned: ", (typeof this.settings.upload_error_handler === "function").toString(), "\n",
  8765. "\t", "upload_success_handler assigned: ", (typeof this.settings.upload_success_handler === "function").toString(), "\n",
  8766. "\t", "upload_complete_handler assigned: ", (typeof this.settings.upload_complete_handler === "function").toString(), "\n",
  8767. "\t", "debug_handler assigned: ", (typeof this.settings.debug_handler === "function").toString(), "\n"
  8768. ].join("")
  8769. );
  8770. };
  8771. /* Note: addSetting and getSetting are no longer used by SWFUpload but are included
  8772. the maintain v2 API compatibility
  8773. */
  8774. // Public: (Deprecated) addSetting adds a setting value. If the value given is undefined or null then the default_value is used.
  8775. SWFUpload.prototype.addSetting = function (name, value, default_value) {
  8776. if (value == undefined) {
  8777. return (this.settings[name] = default_value);
  8778. } else {
  8779. return (this.settings[name] = value);
  8780. }
  8781. };
  8782. // Public: (Deprecated) getSetting gets a setting. Returns an empty string if the setting was not found.
  8783. SWFUpload.prototype.getSetting = function (name) {
  8784. if (this.settings[name] != undefined) {
  8785. return this.settings[name];
  8786. }
  8787. return "";
  8788. };
  8789. // Private: callFlash handles function calls made to the Flash element.
  8790. // Calls are made with a setTimeout for some functions to work around
  8791. // bugs in the ExternalInterface library.
  8792. SWFUpload.prototype.callFlash = function (functionName, argumentArray) {
  8793. argumentArray = argumentArray || [];
  8794. var movieElement = this.getMovieElement();
  8795. var returnValue, returnString;
  8796. // Flash's method if calling ExternalInterface methods (code adapted from MooTools).
  8797. try {
  8798. returnString = movieElement.CallFunction('<invoke name="' + functionName + '" returntype="javascript">' + __flash__argumentsToXML(argumentArray, 0) + '</invoke>');
  8799. returnValue = eval(returnString);
  8800. } catch (ex) {
  8801. throw "Call to " + functionName + " failed";
  8802. }
  8803. // Unescape file post param values
  8804. if (returnValue != undefined && typeof returnValue.post === "object") {
  8805. returnValue = this.unescapeFilePostParams(returnValue);
  8806. }
  8807. return returnValue;
  8808. };
  8809. /* *****************************
  8810. -- Flash control methods --
  8811. Your UI should use these
  8812. to operate SWFUpload
  8813. ***************************** */
  8814. // WARNING: this function does not work in Flash Player 10
  8815. // Public: selectFile causes a File Selection Dialog window to appear. This
  8816. // dialog only allows 1 file to be selected.
  8817. SWFUpload.prototype.selectFile = function () {
  8818. this.callFlash("SelectFile");
  8819. };
  8820. // WARNING: this function does not work in Flash Player 10
  8821. // Public: selectFiles causes a File Selection Dialog window to appear/ This
  8822. // dialog allows the user to select any number of files
  8823. // Flash Bug Warning: Flash limits the number of selectable files based on the combined length of the file names.
  8824. // If the selection name length is too long the dialog will fail in an unpredictable manner. There is no work-around
  8825. // for this bug.
  8826. SWFUpload.prototype.selectFiles = function () {
  8827. this.callFlash("SelectFiles");
  8828. };
  8829. // Public: startUpload starts uploading the first file in the queue unless
  8830. // the optional parameter 'fileID' specifies the ID
  8831. SWFUpload.prototype.startUpload = function (fileID) {
  8832. this.callFlash("StartUpload", [fileID]);
  8833. };
  8834. // Public: cancelUpload cancels any queued file. The fileID parameter may be the file ID or index.
  8835. // If you do not specify a fileID the current uploading file or first file in the queue is cancelled.
  8836. // If you do not want the uploadError event to trigger you can specify false for the triggerErrorEvent parameter.
  8837. SWFUpload.prototype.cancelUpload = function (fileID, triggerErrorEvent) {
  8838. if (triggerErrorEvent !== false) {
  8839. triggerErrorEvent = true;
  8840. }
  8841. this.callFlash("CancelUpload", [fileID, triggerErrorEvent]);
  8842. };
  8843. // Public: stopUpload stops the current upload and requeues the file at the beginning of the queue.
  8844. // If nothing is currently uploading then nothing happens.
  8845. SWFUpload.prototype.stopUpload = function () {
  8846. this.callFlash("StopUpload");
  8847. };
  8848. /* ************************
  8849. * Settings methods
  8850. * These methods change the SWFUpload settings.
  8851. * SWFUpload settings should not be changed directly on the settings object
  8852. * since many of the settings need to be passed to Flash in order to take
  8853. * effect.
  8854. * *********************** */
  8855. // Public: getStats gets the file statistics object.
  8856. SWFUpload.prototype.getStats = function () {
  8857. return this.callFlash("GetStats");
  8858. };
  8859. // Public: setStats changes the SWFUpload statistics. You shouldn't need to
  8860. // change the statistics but you can. Changing the statistics does not
  8861. // affect SWFUpload accept for the successful_uploads count which is used
  8862. // by the upload_limit setting to determine how many files the user may upload.
  8863. SWFUpload.prototype.setStats = function (statsObject) {
  8864. this.callFlash("SetStats", [statsObject]);
  8865. };
  8866. // Public: getFile retrieves a File object by ID or Index. If the file is
  8867. // not found then 'null' is returned.
  8868. SWFUpload.prototype.getFile = function (fileID) {
  8869. if (typeof(fileID) === "number") {
  8870. return this.callFlash("GetFileByIndex", [fileID]);
  8871. } else {
  8872. return this.callFlash("GetFile", [fileID]);
  8873. }
  8874. };
  8875. // Public: addFileParam sets a name/value pair that will be posted with the
  8876. // file specified by the Files ID. If the name already exists then the
  8877. // exiting value will be overwritten.
  8878. SWFUpload.prototype.addFileParam = function (fileID, name, value) {
  8879. return this.callFlash("AddFileParam", [fileID, name, value]);
  8880. };
  8881. // Public: removeFileParam removes a previously set (by addFileParam) name/value
  8882. // pair from the specified file.
  8883. SWFUpload.prototype.removeFileParam = function (fileID, name) {
  8884. this.callFlash("RemoveFileParam", [fileID, name]);
  8885. };
  8886. // Public: setUploadUrl changes the upload_url setting.
  8887. SWFUpload.prototype.setUploadURL = function (url) {
  8888. this.settings.upload_url = url.toString();
  8889. this.callFlash("SetUploadURL", [url]);
  8890. };
  8891. // Public: setPostParams changes the post_params setting
  8892. SWFUpload.prototype.setPostParams = function (paramsObject) {
  8893. this.settings.post_params = paramsObject;
  8894. this.callFlash("SetPostParams", [paramsObject]);
  8895. };
  8896. // Public: addPostParam adds post name/value pair. Each name can have only one value.
  8897. SWFUpload.prototype.addPostParam = function (name, value) {
  8898. this.settings.post_params[name] = value;
  8899. this.callFlash("SetPostParams", [this.settings.post_params]);
  8900. };
  8901. // Public: removePostParam deletes post name/value pair.
  8902. SWFUpload.prototype.removePostParam = function (name) {
  8903. delete this.settings.post_params[name];
  8904. this.callFlash("SetPostParams", [this.settings.post_params]);
  8905. };
  8906. // Public: setFileTypes changes the file_types setting and the file_types_description setting
  8907. SWFUpload.prototype.setFileTypes = function (types, description) {
  8908. this.settings.file_types = types;
  8909. this.settings.file_types_description = description;
  8910. this.callFlash("SetFileTypes", [types, description]);
  8911. };
  8912. // Public: setFileSizeLimit changes the file_size_limit setting
  8913. SWFUpload.prototype.setFileSizeLimit = function (fileSizeLimit) {
  8914. this.settings.file_size_limit = fileSizeLimit;
  8915. this.callFlash("SetFileSizeLimit", [fileSizeLimit]);
  8916. };
  8917. // Public: setFileUploadLimit changes the file_upload_limit setting
  8918. SWFUpload.prototype.setFileUploadLimit = function (fileUploadLimit) {
  8919. this.settings.file_upload_limit = fileUploadLimit;
  8920. this.callFlash("SetFileUploadLimit", [fileUploadLimit]);
  8921. };
  8922. // Public: setFileQueueLimit changes the file_queue_limit setting
  8923. SWFUpload.prototype.setFileQueueLimit = function (fileQueueLimit) {
  8924. this.settings.file_queue_limit = fileQueueLimit;
  8925. this.callFlash("SetFileQueueLimit", [fileQueueLimit]);
  8926. };
  8927. // Public: setFilePostName changes the file_post_name setting
  8928. SWFUpload.prototype.setFilePostName = function (filePostName) {
  8929. this.settings.file_post_name = filePostName;
  8930. this.callFlash("SetFilePostName", [filePostName]);
  8931. };
  8932. // Public: setUseQueryString changes the use_query_string setting
  8933. SWFUpload.prototype.setUseQueryString = function (useQueryString) {
  8934. this.settings.use_query_string = useQueryString;
  8935. this.callFlash("SetUseQueryString", [useQueryString]);
  8936. };
  8937. // Public: setRequeueOnError changes the requeue_on_error setting
  8938. SWFUpload.prototype.setRequeueOnError = function (requeueOnError) {
  8939. this.settings.requeue_on_error = requeueOnError;
  8940. this.callFlash("SetRequeueOnError", [requeueOnError]);
  8941. };
  8942. // Public: setHTTPSuccess changes the http_success setting
  8943. SWFUpload.prototype.setHTTPSuccess = function (http_status_codes) {
  8944. if (typeof http_status_codes === "string") {
  8945. http_status_codes = http_status_codes.replace(" ", "").split(",");
  8946. }
  8947. this.settings.http_success = http_status_codes;
  8948. this.callFlash("SetHTTPSuccess", [http_status_codes]);
  8949. };
  8950. // Public: setHTTPSuccess changes the http_success setting
  8951. SWFUpload.prototype.setAssumeSuccessTimeout = function (timeout_seconds) {
  8952. this.settings.assume_success_timeout = timeout_seconds;
  8953. this.callFlash("SetAssumeSuccessTimeout", [timeout_seconds]);
  8954. };
  8955. // Public: setDebugEnabled changes the debug_enabled setting
  8956. SWFUpload.prototype.setDebugEnabled = function (debugEnabled) {
  8957. this.settings.debug_enabled = debugEnabled;
  8958. this.callFlash("SetDebugEnabled", [debugEnabled]);
  8959. };
  8960. // Public: setButtonImageURL loads a button image sprite
  8961. SWFUpload.prototype.setButtonImageURL = function (buttonImageURL) {
  8962. if (buttonImageURL == undefined) {
  8963. buttonImageURL = "";
  8964. }
  8965. this.settings.button_image_url = buttonImageURL;
  8966. this.callFlash("SetButtonImageURL", [buttonImageURL]);
  8967. };
  8968. // Public: setButtonDimensions resizes the Flash Movie and button
  8969. SWFUpload.prototype.setButtonDimensions = function (width, height) {
  8970. this.settings.button_width = width;
  8971. this.settings.button_height = height;
  8972. var movie = this.getMovieElement();
  8973. if (movie != undefined) {
  8974. movie.style.width = width + "px";
  8975. movie.style.height = height + "px";
  8976. }
  8977. this.callFlash("SetButtonDimensions", [width, height]);
  8978. };
  8979. // Public: setButtonText Changes the text overlaid on the button
  8980. SWFUpload.prototype.setButtonText = function (html) {
  8981. this.settings.button_text = html;
  8982. this.callFlash("SetButtonText", [html]);
  8983. };
  8984. // Public: setButtonTextPadding changes the top and left padding of the text overlay
  8985. SWFUpload.prototype.setButtonTextPadding = function (left, top) {
  8986. this.settings.button_text_top_padding = top;
  8987. this.settings.button_text_left_padding = left;
  8988. this.callFlash("SetButtonTextPadding", [left, top]);
  8989. };
  8990. // Public: setButtonTextStyle changes the CSS used to style the HTML/Text overlaid on the button
  8991. SWFUpload.prototype.setButtonTextStyle = function (css) {
  8992. this.settings.button_text_style = css;
  8993. this.callFlash("SetButtonTextStyle", [css]);
  8994. };
  8995. // Public: setButtonDisabled disables/enables the button
  8996. SWFUpload.prototype.setButtonDisabled = function (isDisabled) {
  8997. this.settings.button_disabled = isDisabled;
  8998. this.callFlash("SetButtonDisabled", [isDisabled]);
  8999. };
  9000. // Public: setButtonAction sets the action that occurs when the button is clicked
  9001. SWFUpload.prototype.setButtonAction = function (buttonAction) {
  9002. this.settings.button_action = buttonAction;
  9003. this.callFlash("SetButtonAction", [buttonAction]);
  9004. };
  9005. // Public: setButtonCursor changes the mouse cursor displayed when hovering over the button
  9006. SWFUpload.prototype.setButtonCursor = function (cursor) {
  9007. this.settings.button_cursor = cursor;
  9008. this.callFlash("SetButtonCursor", [cursor]);
  9009. };
  9010. /* *******************************
  9011. Flash Event Interfaces
  9012. These functions are used by Flash to trigger the various
  9013. events.
  9014. All these functions a Private.
  9015. Because the ExternalInterface library is buggy the event calls
  9016. are added to a queue and the queue then executed by a setTimeout.
  9017. This ensures that events are executed in a determinate order and that
  9018. the ExternalInterface bugs are avoided.
  9019. ******************************* */
  9020. SWFUpload.prototype.queueEvent = function (handlerName, argumentArray) {
  9021. // Warning: Don't call this.debug inside here or you'll create an infinite loop
  9022. if (argumentArray == undefined) {
  9023. argumentArray = [];
  9024. } else if (!(argumentArray instanceof Array)) {
  9025. argumentArray = [argumentArray];
  9026. }
  9027. var self = this;
  9028. if (typeof this.settings[handlerName] === "function") {
  9029. // Queue the event
  9030. this.eventQueue.push(function () {
  9031. this.settings[handlerName].apply(this, argumentArray);
  9032. });
  9033. // Execute the next queued event
  9034. setTimeout(function () {
  9035. self.executeNextEvent();
  9036. }, 0);
  9037. } else if (this.settings[handlerName] !== null) {
  9038. throw "Event handler " + handlerName + " is unknown or is not a function";
  9039. }
  9040. };
  9041. // Private: Causes the next event in the queue to be executed. Since events are queued using a setTimeout
  9042. // we must queue them in order to garentee that they are executed in order.
  9043. SWFUpload.prototype.executeNextEvent = function () {
  9044. // Warning: Don't call this.debug inside here or you'll create an infinite loop
  9045. var f = this.eventQueue ? this.eventQueue.shift() : null;
  9046. if (typeof(f) === "function") {
  9047. f.apply(this);
  9048. }
  9049. };
  9050. // Private: unescapeFileParams is part of a workaround for a flash bug where objects passed through ExternalInterface cannot have
  9051. // properties that contain characters that are not valid for JavaScript identifiers. To work around this
  9052. // the Flash Component escapes the parameter names and we must unescape again before passing them along.
  9053. SWFUpload.prototype.unescapeFilePostParams = function (file) {
  9054. var reg = /[$]([0-9a-f]{4})/i;
  9055. var unescapedPost = {};
  9056. var uk;
  9057. if (file != undefined) {
  9058. for (var k in file.post) {
  9059. if (file.post.hasOwnProperty(k)) {
  9060. uk = k;
  9061. var match;
  9062. while ((match = reg.exec(uk)) !== null) {
  9063. uk = uk.replace(match[0], String.fromCharCode(parseInt("0x" + match[1], 16)));
  9064. }
  9065. unescapedPost[uk] = file.post[k];
  9066. }
  9067. }
  9068. file.post = unescapedPost;
  9069. }
  9070. return file;
  9071. };
  9072. // Private: Called by Flash to see if JS can call in to Flash (test if External Interface is working)
  9073. SWFUpload.prototype.testExternalInterface = function () {
  9074. try {
  9075. return this.callFlash("TestExternalInterface");
  9076. } catch (ex) {
  9077. return false;
  9078. }
  9079. };
  9080. // Private: This event is called by Flash when it has finished loading. Don't modify this.
  9081. // Use the swfupload_loaded_handler event setting to execute custom code when SWFUpload has loaded.
  9082. SWFUpload.prototype.flashReady = function () {
  9083. // Check that the movie element is loaded correctly with its ExternalInterface methods defined
  9084. var movieElement = this.getMovieElement();
  9085. if (!movieElement) {
  9086. this.debug("Flash called back ready but the flash movie can't be found.");
  9087. return;
  9088. }
  9089. this.cleanUp(movieElement);
  9090. this.queueEvent("swfupload_loaded_handler");
  9091. };
  9092. // Private: removes Flash added fuctions to the DOM node to prevent memory leaks in IE.
  9093. // This function is called by Flash each time the ExternalInterface functions are created.
  9094. SWFUpload.prototype.cleanUp = function (movieElement) {
  9095. // Pro-actively unhook all the Flash functions
  9096. try {
  9097. if (this.movieElement && typeof(movieElement.CallFunction) === "unknown") { // We only want to do this in IE
  9098. this.debug("Removing Flash functions hooks (this should only run in IE and should prevent memory leaks)");
  9099. for (var key in movieElement) {
  9100. try {
  9101. if (typeof(movieElement[key]) === "function") {
  9102. movieElement[key] = null;
  9103. }
  9104. } catch (ex) {
  9105. }
  9106. }
  9107. }
  9108. } catch (ex1) {
  9109. }
  9110. // Fix Flashes own cleanup code so if the SWFMovie was removed from the page
  9111. // it doesn't display errors.
  9112. window["__flash__removeCallback"] = function (instance, name) {
  9113. try {
  9114. if (instance) {
  9115. instance[name] = null;
  9116. }
  9117. } catch (flashEx) {
  9118. }
  9119. };
  9120. };
  9121. /* This is a chance to do something before the browse window opens */
  9122. SWFUpload.prototype.fileDialogStart = function () {
  9123. this.queueEvent("file_dialog_start_handler");
  9124. };
  9125. /* Called when a file is successfully added to the queue. */
  9126. SWFUpload.prototype.fileQueued = function (file) {
  9127. file = this.unescapeFilePostParams(file);
  9128. this.queueEvent("file_queued_handler", file);
  9129. };
  9130. /* Handle errors that occur when an attempt to queue a file fails. */
  9131. SWFUpload.prototype.fileQueueError = function (file, errorCode, message) {
  9132. file = this.unescapeFilePostParams(file);
  9133. this.queueEvent("file_queue_error_handler", [file, errorCode, message]);
  9134. };
  9135. /* Called after the file dialog has closed and the selected files have been queued.
  9136. You could call startUpload here if you want the queued files to begin uploading immediately. */
  9137. SWFUpload.prototype.fileDialogComplete = function (numFilesSelected, numFilesQueued, numFilesInQueue) {
  9138. this.queueEvent("file_dialog_complete_handler", [numFilesSelected, numFilesQueued, numFilesInQueue]);
  9139. };
  9140. SWFUpload.prototype.uploadStart = function (file) {
  9141. file = this.unescapeFilePostParams(file);
  9142. this.queueEvent("return_upload_start_handler", file);
  9143. };
  9144. SWFUpload.prototype.returnUploadStart = function (file) {
  9145. var returnValue;
  9146. if (typeof this.settings.upload_start_handler === "function") {
  9147. file = this.unescapeFilePostParams(file);
  9148. returnValue = this.settings.upload_start_handler.call(this, file);
  9149. } else if (this.settings.upload_start_handler != undefined) {
  9150. throw "upload_start_handler must be a function";
  9151. }
  9152. // Convert undefined to true so if nothing is returned from the upload_start_handler it is
  9153. // interpretted as 'true'.
  9154. if (returnValue === undefined) {
  9155. returnValue = true;
  9156. }
  9157. returnValue = !!returnValue;
  9158. this.callFlash("ReturnUploadStart", [returnValue]);
  9159. };
  9160. SWFUpload.prototype.uploadProgress = function (file, bytesComplete, bytesTotal) {
  9161. file = this.unescapeFilePostParams(file);
  9162. this.queueEvent("upload_progress_handler", [file, bytesComplete, bytesTotal]);
  9163. };
  9164. SWFUpload.prototype.uploadError = function (file, errorCode, message) {
  9165. file = this.unescapeFilePostParams(file);
  9166. this.queueEvent("upload_error_handler", [file, errorCode, message]);
  9167. };
  9168. SWFUpload.prototype.uploadSuccess = function (file, serverData, responseReceived) {
  9169. file = this.unescapeFilePostParams(file);
  9170. this.queueEvent("upload_success_handler", [file, serverData, responseReceived]);
  9171. };
  9172. SWFUpload.prototype.uploadComplete = function (file) {
  9173. file = this.unescapeFilePostParams(file);
  9174. this.queueEvent("upload_complete_handler", file);
  9175. };
  9176. /* Called by SWFUpload JavaScript and Flash functions when debug is enabled. By default it writes messages to the
  9177. internal debug console. You can override this event and have messages written where you want. */
  9178. SWFUpload.prototype.debug = function (message) {
  9179. this.queueEvent("debug_handler", message);
  9180. };
  9181. /* **********************************
  9182. Debug Console
  9183. The debug console is a self contained, in page location
  9184. for debug message to be sent. The Debug Console adds
  9185. itself to the body if necessary.
  9186. The console is automatically scrolled as messages appear.
  9187. If you are using your own debug handler or when you deploy to production and
  9188. have debug disabled you can remove these functions to reduce the file size
  9189. and complexity.
  9190. ********************************** */
  9191. // Private: debugMessage is the default debug_handler. If you want to print debug messages
  9192. // call the debug() function. When overriding the function your own function should
  9193. // check to see if the debug setting is true before outputting debug information.
  9194. SWFUpload.prototype.debugMessage = function (message) {
  9195. if (this.settings.debug) {
  9196. var exceptionMessage, exceptionValues = [];
  9197. // Check for an exception object and print it nicely
  9198. if (typeof message === "object" && typeof message.name === "string" && typeof message.message === "string") {
  9199. for (var key in message) {
  9200. if (message.hasOwnProperty(key)) {
  9201. exceptionValues.push(key + ": " + message[key]);
  9202. }
  9203. }
  9204. exceptionMessage = exceptionValues.join("\n") || "";
  9205. exceptionValues = exceptionMessage.split("\n");
  9206. exceptionMessage = "EXCEPTION: " + exceptionValues.join("\nEXCEPTION: ");
  9207. SWFUpload.Console.writeLine(exceptionMessage);
  9208. } else {
  9209. SWFUpload.Console.writeLine(message);
  9210. }
  9211. }
  9212. };
  9213. SWFUpload.Console = {};
  9214. SWFUpload.Console.writeLine = function (message) {
  9215. var console, documentForm;
  9216. try {
  9217. console = document.getElementById("SWFUpload_Console");
  9218. if (!console) {
  9219. documentForm = document.createElement("form");
  9220. document.getElementsByTagName("body")[0].appendChild(documentForm);
  9221. console = document.createElement("textarea");
  9222. console.id = "SWFUpload_Console";
  9223. console.style.fontFamily = "monospace";
  9224. console.setAttribute("wrap", "off");
  9225. console.wrap = "off";
  9226. console.style.overflow = "auto";
  9227. console.style.width = "700px";
  9228. console.style.height = "350px";
  9229. console.style.margin = "5px";
  9230. documentForm.appendChild(console);
  9231. }
  9232. console.value += message + "\n";
  9233. console.scrollTop = console.scrollHeight - console.clientHeight;
  9234. } catch (ex) {
  9235. alert("Exception: " + ex.name + " Message: " + ex.message);
  9236. }
  9237. };
  9238. })();
  9239. (function() {
  9240. /*
  9241. Queue Plug-in
  9242. Features:
  9243. *Adds a cancelQueue() method for cancelling the entire queue.
  9244. *All queued files are uploaded when startUpload() is called.
  9245. *If false is returned from uploadComplete then the queue upload is stopped.
  9246. If false is not returned (strict comparison) then the queue upload is continued.
  9247. *Adds a QueueComplete event that is fired when all the queued files have finished uploading.
  9248. Set the event handler with the queue_complete_handler setting.
  9249. */
  9250. if (typeof(SWFUpload) === "function") {
  9251. SWFUpload.queue = {};
  9252. SWFUpload.prototype.initSettings = (function (oldInitSettings) {
  9253. return function () {
  9254. if (typeof(oldInitSettings) === "function") {
  9255. oldInitSettings.call(this);
  9256. }
  9257. this.queueSettings = {};
  9258. this.queueSettings.queue_cancelled_flag = false;
  9259. this.queueSettings.queue_upload_count = 0;
  9260. this.queueSettings.user_upload_complete_handler = this.settings.upload_complete_handler;
  9261. this.queueSettings.user_upload_start_handler = this.settings.upload_start_handler;
  9262. this.settings.upload_complete_handler = SWFUpload.queue.uploadCompleteHandler;
  9263. this.settings.upload_start_handler = SWFUpload.queue.uploadStartHandler;
  9264. this.settings.queue_complete_handler = this.settings.queue_complete_handler || null;
  9265. };
  9266. })(SWFUpload.prototype.initSettings);
  9267. SWFUpload.prototype.startUpload = function (fileID) {
  9268. this.queueSettings.queue_cancelled_flag = false;
  9269. this.callFlash("StartUpload", [fileID]);
  9270. };
  9271. SWFUpload.prototype.cancelQueue = function () {
  9272. this.queueSettings.queue_cancelled_flag = true;
  9273. this.stopUpload();
  9274. var stats = this.getStats();
  9275. while (stats.files_queued > 0) {
  9276. this.cancelUpload();
  9277. stats = this.getStats();
  9278. }
  9279. };
  9280. SWFUpload.queue.uploadStartHandler = function (file) {
  9281. var returnValue;
  9282. if (typeof(this.queueSettings.user_upload_start_handler) === "function") {
  9283. returnValue = this.queueSettings.user_upload_start_handler.call(this, file);
  9284. }
  9285. // To prevent upload a real "FALSE" value must be returned, otherwise default to a real "TRUE" value.
  9286. returnValue = (returnValue === false) ? false : true;
  9287. this.queueSettings.queue_cancelled_flag = !returnValue;
  9288. return returnValue;
  9289. };
  9290. SWFUpload.queue.uploadCompleteHandler = function (file) {
  9291. var user_upload_complete_handler = this.queueSettings.user_upload_complete_handler;
  9292. var continueUpload;
  9293. if (file.filestatus === SWFUpload.FILE_STATUS.COMPLETE) {
  9294. this.queueSettings.queue_upload_count++;
  9295. }
  9296. if (typeof(user_upload_complete_handler) === "function") {
  9297. continueUpload = (user_upload_complete_handler.call(this, file) === false) ? false : true;
  9298. } else if (file.filestatus === SWFUpload.FILE_STATUS.QUEUED) {
  9299. // If the file was stopped and re-queued don't restart the upload
  9300. continueUpload = false;
  9301. } else {
  9302. continueUpload = true;
  9303. }
  9304. if (continueUpload) {
  9305. var stats = this.getStats();
  9306. if (stats.files_queued > 0 && this.queueSettings.queue_cancelled_flag === false) {
  9307. this.startUpload();
  9308. } else if (this.queueSettings.queue_cancelled_flag === false) {
  9309. this.queueEvent("queue_complete_handler", [this.queueSettings.queue_upload_count]);
  9310. this.queueSettings.queue_upload_count = 0;
  9311. } else {
  9312. this.queueSettings.queue_cancelled_flag = false;
  9313. this.queueSettings.queue_upload_count = 0;
  9314. }
  9315. }
  9316. };
  9317. }
  9318. })();
  9319. /*******************************************************************************
  9320. * KindEditor - WYSIWYG HTML Editor for Internet
  9321. * Copyright (C) 2006-2011 kindsoft.net
  9322. *
  9323. * @author Roddy <luolonghao@gmail.com>
  9324. * @site http://www.kindsoft.net/
  9325. * @licence http://www.kindsoft.net/license.php
  9326. *******************************************************************************/
  9327. KindEditor.plugin('pagebreak', function(K) {
  9328. var self = this;
  9329. var name = 'pagebreak';
  9330. var pagebreakHtml = K.undef(self.pagebreakHtml, '<hr style="page-break-after: always;" class="ke-pagebreak" />');
  9331. self.clickToolbar(name, function() {
  9332. var cmd = self.cmd,
  9333. range = cmd.range;
  9334. self.focus();
  9335. var tail = self.newlineTag == 'br' || K.WEBKIT ? '' : '<span id="__kindeditor_tail_tag__"></span>';
  9336. self.insertHtml(pagebreakHtml + tail);
  9337. if(tail !== '') {
  9338. var p = K('#__kindeditor_tail_tag__', self.edit.doc);
  9339. range.selectNodeContents(p[0]);
  9340. p.removeAttr('id');
  9341. cmd.select();
  9342. }
  9343. });
  9344. });
  9345. /*******************************************************************************
  9346. * KindEditor - WYSIWYG HTML Editor for Internet
  9347. * Copyright (C) 2006-2011 kindsoft.net
  9348. *
  9349. * @author Roddy <luolonghao@gmail.com>
  9350. * @site http://www.kindsoft.net/
  9351. * @licence http://www.kindsoft.net/license.php
  9352. *******************************************************************************/
  9353. KindEditor.plugin('plainpaste', function(K) {
  9354. var self = this,
  9355. name = 'plainpaste';
  9356. self.clickToolbar(name, function() {
  9357. var lang = self.lang(name + '.'),
  9358. html = '<div style="padding:10px 20px;">' +
  9359. '<div style="margin-bottom:10px;">' + lang.comment + '</div>' +
  9360. '<textarea class="ke-textarea" style="width:408px;height:260px;"></textarea>' +
  9361. '</div>',
  9362. dialog = self.createDialog({
  9363. name: name,
  9364. width: 450,
  9365. title: self.lang(name),
  9366. body: html,
  9367. yesBtn: {
  9368. name: self.lang('yes'),
  9369. click: function(e) {
  9370. var html = textarea.val();
  9371. html = K.escape(html);
  9372. html = html.replace(/ {2}/g, ' &nbsp;');
  9373. if(self.newlineTag == 'p') {
  9374. html = html.replace(/^/, '<p>').replace(/$/, '</p>').replace(/\n/g, '</p><p>');
  9375. } else {
  9376. html = html.replace(/\n/g, '<br />$&');
  9377. }
  9378. self.insertHtml(html).hideDialog().focus();
  9379. }
  9380. }
  9381. }),
  9382. textarea = K('textarea', dialog.div);
  9383. textarea[0].focus();
  9384. });
  9385. });
  9386. /*******************************************************************************
  9387. * KindEditor - WYSIWYG HTML Editor for Internet
  9388. * Copyright (C) 2006-2011 kindsoft.net
  9389. *
  9390. * @author Roddy <luolonghao@gmail.com>
  9391. * @site http://www.kindsoft.net/
  9392. * @licence http://www.kindsoft.net/license.php
  9393. *******************************************************************************/
  9394. KindEditor.plugin('preview', function(K) {
  9395. var self = this,
  9396. name = 'preview';
  9397. self.clickToolbar(name, function() {
  9398. var lang = self.lang(name + '.'),
  9399. html = '<div style="padding:10px 20px;">' +
  9400. '<iframe class="ke-textarea" frameborder="0" style="width:708px;height:400px;"></iframe>' +
  9401. '</div>',
  9402. dialog = self.createDialog({
  9403. name: name,
  9404. width: 750,
  9405. title: self.lang(name),
  9406. body: html
  9407. }),
  9408. iframe = K('iframe', dialog.div),
  9409. doc = K.iframeDoc(iframe);
  9410. doc.open();
  9411. doc.write(self.fullHtml());
  9412. doc.write('<style>.kindeditor-ph{display:none!important;}</style>');
  9413. var cssData = self.options.cssData;
  9414. var cssPath = self.options.cssPath;
  9415. var bodyClass = self.options.bodyClass;
  9416. if(!K.isArray(cssPath)) {
  9417. cssPath = [cssPath];
  9418. }
  9419. K.each(cssPath, function(i, path) {
  9420. if(path) {
  9421. doc.write('<link href="' + path + '" rel="stylesheet" />');
  9422. }
  9423. });
  9424. if(cssData) {
  9425. doc.write('<style>' + cssData + '</style>');
  9426. }
  9427. doc.close();
  9428. var body = K(doc.body).css('background-color', '#FFF');
  9429. if (bodyClass) {
  9430. body.addClass(bodyClass);
  9431. }
  9432. iframe[0].contentWindow.focus();
  9433. });
  9434. });
  9435. /*******************************************************************************
  9436. * KindEditor - WYSIWYG HTML Editor for Internet
  9437. * Copyright (C) 2006-2011 kindsoft.net
  9438. *
  9439. * @author Roddy <luolonghao@gmail.com>
  9440. * @site http://www.kindsoft.net/
  9441. * @licence http://www.kindsoft.net/license.php
  9442. *******************************************************************************/
  9443. KindEditor.plugin('quickformat', function(K) {
  9444. var self = this,
  9445. name = 'quickformat',
  9446. blockMap = K.toMap('blockquote,center,div,h1,h2,h3,h4,h5,h6,p');
  9447. function getFirstChild(knode) {
  9448. var child = knode.first();
  9449. while(child && child.first()) {
  9450. child = child.first();
  9451. }
  9452. return child;
  9453. }
  9454. self.clickToolbar(name, function() {
  9455. self.focus();
  9456. var doc = self.edit.doc,
  9457. range = self.cmd.range,
  9458. child = K(doc.body).first(),
  9459. next,
  9460. nodeList = [],
  9461. subList = [],
  9462. bookmark = range.createBookmark(true);
  9463. while(child) {
  9464. next = child.next();
  9465. var firstChild = getFirstChild(child);
  9466. if(!firstChild || firstChild.name != 'img') {
  9467. if(blockMap[child.name]) {
  9468. child.html(child.html().replace(/^(\s|&nbsp;| )+/ig, ''));
  9469. child.css('text-indent', '2em');
  9470. } else {
  9471. subList.push(child);
  9472. }
  9473. if(!next || (blockMap[next.name] || blockMap[child.name] && !blockMap[next.name])) {
  9474. if(subList.length > 0) {
  9475. nodeList.push(subList);
  9476. }
  9477. subList = [];
  9478. }
  9479. }
  9480. child = next;
  9481. }
  9482. K.each(nodeList, function(i, subList) {
  9483. var wrapper = K('<p style="text-indent:2em;"></p>', doc);
  9484. subList[0].before(wrapper);
  9485. K.each(subList, function(i, knode) {
  9486. wrapper.append(knode);
  9487. });
  9488. });
  9489. range.moveToBookmark(bookmark);
  9490. self.addBookmark();
  9491. });
  9492. });
  9493. /**
  9494. --------------------------
  9495. abcd<br />
  9496. 1234<br />
  9497. to
  9498. <p style="text-indent:2em;">
  9499. abcd<br />
  9500. 1234<br />
  9501. </p>
  9502. --------------------------
  9503. &nbsp; abcd<img>1233
  9504. <p>1234</p>
  9505. to
  9506. <p style="text-indent:2em;">abcd<img>1233</p>
  9507. <p style="text-indent:2em;">1234</p>
  9508. --------------------------
  9509. */
  9510. /*******************************************************************************
  9511. * KindEditor - WYSIWYG HTML Editor for Internet
  9512. * Copyright (C) 2006-2011 kindsoft.net
  9513. *
  9514. * @author Roddy <luolonghao@gmail.com>
  9515. * @site http://www.kindsoft.net/
  9516. * @licence http://www.kindsoft.net/license.php
  9517. *******************************************************************************/
  9518. KindEditor.plugin('template', function(K) {
  9519. var self = this,
  9520. name = 'template',
  9521. lang = self.lang(name + '.'),
  9522. htmlPath = self.pluginsPath + name + '/html/';
  9523. function getFilePath(fileName) {
  9524. return htmlPath + fileName + '?ver=' + encodeURIComponent(K.DEBUG ? K.TIME : K.VERSION);
  9525. }
  9526. self.clickToolbar(name, function() {
  9527. var lang = self.lang(name + '.'),
  9528. arr = ['<div style="padding:10px 20px;">',
  9529. '<div class="ke-header">',
  9530. // left start
  9531. '<div class="ke-left">',
  9532. lang.selectTemplate + ' <select>'
  9533. ];
  9534. K.each(lang.fileList, function(key, val) {
  9535. arr.push('<option value="' + key + '">' + val + '</option>');
  9536. });
  9537. html = [arr.join(''),
  9538. '</select></div>',
  9539. // right start
  9540. '<div class="ke-right">',
  9541. '<input type="checkbox" id="keReplaceFlag" name="replaceFlag" value="1" /> <label for="keReplaceFlag">' + lang.replaceContent + '</label>',
  9542. '</div>',
  9543. '<div class="ke-clearfix"></div>',
  9544. '</div>',
  9545. '<iframe class="ke-textarea" frameborder="0" style="width:458px;height:260px;background-color:#FFF;"></iframe>',
  9546. '</div>'
  9547. ].join('');
  9548. var dialog = self.createDialog({
  9549. name: name,
  9550. width: 500,
  9551. title: self.lang(name),
  9552. body: html,
  9553. yesBtn: {
  9554. name: self.lang('yes'),
  9555. click: function(e) {
  9556. var doc = K.iframeDoc(iframe);
  9557. self[checkbox[0].checked ? 'html' : 'insertHtml'](doc.body.innerHTML).hideDialog().focus();
  9558. }
  9559. }
  9560. });
  9561. var selectBox = K('select', dialog.div),
  9562. checkbox = K('[name="replaceFlag"]', dialog.div),
  9563. iframe = K('iframe', dialog.div);
  9564. checkbox[0].checked = true;
  9565. iframe.attr('src', getFilePath(selectBox.val()));
  9566. selectBox.change(function() {
  9567. iframe.attr('src', getFilePath(this.value));
  9568. });
  9569. });
  9570. });
  9571. /*******************************************************************************
  9572. * KindEditor - WYSIWYG HTML Editor for Internet
  9573. * Copyright (C) 2006-2011 kindsoft.net
  9574. *
  9575. * @author Roddy <luolonghao@gmail.com>
  9576. * @site http://www.kindsoft.net/
  9577. * @licence http://www.kindsoft.net/license.php
  9578. *******************************************************************************/
  9579. KindEditor.plugin('wordpaste', function(K) {
  9580. var self = this,
  9581. name = 'wordpaste';
  9582. self.clickToolbar(name, function() {
  9583. var lang = self.lang(name + '.'),
  9584. html = '<div style="padding:10px 20px;">' +
  9585. '<div style="margin-bottom:10px;">' + lang.comment + '</div>' +
  9586. '<iframe class="ke-textarea" frameborder="0" style="width:408px;height:260px;"></iframe>' +
  9587. '</div>',
  9588. dialog = self.createDialog({
  9589. name: name,
  9590. width: 450,
  9591. title: self.lang(name),
  9592. body: html,
  9593. yesBtn: {
  9594. name: self.lang('yes'),
  9595. click: function(e) {
  9596. var str = doc.body.innerHTML;
  9597. str = K.clearMsWord(str, self.filterMode ? self.htmlTags : K.options.htmlTags);
  9598. self.insertHtml(str).hideDialog().focus();
  9599. }
  9600. }
  9601. }),
  9602. div = dialog.div,
  9603. iframe = K('iframe', div),
  9604. doc = K.iframeDoc(iframe);
  9605. if(!K.IE) {
  9606. doc.designMode = 'on';
  9607. }
  9608. doc.open();
  9609. doc.write('<!doctype html><html><head><title>WordPaste</title></head>');
  9610. doc.write('<body style="background-color:#FFF;font-size:12px;margin:2px;">');
  9611. if(!K.IE) {
  9612. doc.write('<br />');
  9613. }
  9614. doc.write('</body></html>');
  9615. doc.close();
  9616. if(K.IE) {
  9617. doc.body.contentEditable = 'true';
  9618. }
  9619. iframe[0].contentWindow.focus();
  9620. });
  9621. });
  9622. /* ========================================================================
  9623. * ZUI: Kindeditor plugin - zui
  9624. * http://openzui.com
  9625. * ========================================================================
  9626. * Copyright (c) 2019-2020 cnezsoft.com; Licensed MIT
  9627. * ======================================================================== */
  9628. $.each(['afterBlur', 'afterFocus', 'afterChange', 'afterTab'], function(_index, name) {
  9629. KindEditor.EditorClass.prototype[name] = function(fn) {
  9630. return this.handler(name, fn);
  9631. };
  9632. });
  9633. KindEditor.plugin('zui', function(K) {
  9634. var self = this;
  9635. var options = self.options;
  9636. self.uuid = $.zui.uuid();
  9637. self.afterBlur(function() {
  9638. if (options.syncAfterBlur) {
  9639. self.sync();
  9640. }
  9641. self.container.removeClass('focus');
  9642. });
  9643. self.afterFocus(function() {
  9644. self.container.addClass('focus');
  9645. });
  9646. self.afterChange(function() {
  9647. self.edit.srcElement.change().hide();
  9648. });
  9649. self.afterCreate(function() {
  9650. $(self.edit.srcElement[0]).data('keditor', self);
  9651. var spellcheck = options.spellcheck;
  9652. if (spellcheck !== undefined) {
  9653. self.edit.doc.documentElement.setAttribute('spellcheck', spellcheck);
  9654. }
  9655. var transferEvents = options.transferEvents;
  9656. if (transferEvents !== false) {
  9657. $(self.edit.doc).on(typeof transferEvents === 'string' ? transferEvents : 'click mousedown', function(event) {
  9658. $(self.edit.srcElement[0]).trigger(event.type);
  9659. });
  9660. }
  9661. });
  9662. if (options.transferTab !== false) {
  9663. var nextFormControl = 'input:not([type="hidden"]), textarea:not(.ke-edit-textarea), button[type="submit"], select';
  9664. self.afterTab(function() {
  9665. var $editor = $(self.edit.srcElement[0]);
  9666. var $next = $editor.next(nextFormControl);
  9667. if(!$next.length) $next = $editor.next().next(nextFormControl);
  9668. if(!$next.length) $next = $editor.parent().next().find(nextFormControl);
  9669. if(!$next.length) $next = $editor.parent().parent().next().find(nextFormControl);
  9670. $next = $next.first();
  9671. if ($next.length) {
  9672. var keditor = $next.data('keditor');
  9673. if(keditor) {
  9674. keditor.focus();
  9675. } else {
  9676. $next.focus();
  9677. }
  9678. return true;
  9679. }
  9680. return true;
  9681. });
  9682. }
  9683. });
  9684. /* ========================================================================
  9685. * ZUI: Kindeditor plugin - placeholder
  9686. * http://openzui.com
  9687. * ========================================================================
  9688. * Copyright (c) 2019-2020 cnezsoft.com; Licensed MIT
  9689. * ======================================================================== */
  9690. KindEditor.EditorClass.prototype.setPlaceholder = function(placeholder, asHtml) {
  9691. var self = this;
  9692. var options = self.options;
  9693. var $editDiv = $(self.edit.div[0]);
  9694. var $placeholder = $editDiv.find('.kindeditor-ph');
  9695. if (!$placeholder.length) {
  9696. $editDiv.css('position', 'relative');
  9697. $placeholder = $('<div class="kindeditor-ph" style="width:100%; color:#888; padding: 8px; background:none; position:absolute;z-index:10;top:0;border:0;overflow:auto;resize:none; pointer-events:none; white-space: pre-wrap; font-size: 13px"></div>');
  9698. if (options.placeholderStyle) {
  9699. $placeholder.css(options.placeholderStyle);
  9700. }
  9701. $editDiv.append($placeholder);
  9702. }
  9703. if (self.plugin.hasContent()) {
  9704. $placeholder.hide();
  9705. }
  9706. $placeholder[asHtml ? 'html' : 'text'](placeholder);
  9707. self.$placeholder = $placeholder;
  9708. };
  9709. KindEditor.EditorClass.prototype.getPlaceholder = function(asHtml) {
  9710. return this.$placeholder ? this.$placeholder[asHtml ? 'html' : 'text']() : '';
  9711. };
  9712. KindEditor.plugin('placeholder', function(K) {
  9713. var self = this;
  9714. self.plugin.hasContent = function() {
  9715. return self.html().replace(/\s|\n|\r|\t/g, '').replace(/<br\/>/g, '').replace(/<p><\/p>/g, '') !== '';
  9716. };
  9717. self.afterBlur(function() {
  9718. if (!self.plugin.hasContent()) {
  9719. self.$placeholder && self.$placeholder.show();
  9720. }
  9721. });
  9722. self.afterFocus(function() {
  9723. self.$placeholder && self.$placeholder.hide();
  9724. });
  9725. self.afterCreate(function() {
  9726. var options = self.options;
  9727. if (options.placeholderHtml) {
  9728. self.setPlaceholder(options.placeholderHtml, true);
  9729. } else if (options.placeholder) {
  9730. self.setPlaceholder(options.placeholder);
  9731. }
  9732. });
  9733. });
  9734. /* ========================================================================
  9735. * ZUI: Kindeditor plugin - paste-image
  9736. * http://openzui.com
  9737. * ========================================================================
  9738. * Copyright (c) 2019-2019 cnezsoft.com; Licensed MIT
  9739. * ======================================================================== */
  9740. KindEditor.plugin('pasteimage', function(K) {
  9741. var self = this;
  9742. var allLangs = {
  9743. zh_cn: {
  9744. notSupportMsg: '您的浏览器不支持粘贴图片!',
  9745. placeholder: '可以在编辑器直接贴图。',
  9746. failMsg: '贴图失败,请稍后重试。',
  9747. uploadingHint: '正在上传图片,请稍后...',
  9748. },
  9749. zh_tw: {
  9750. notSupportMsg: '您的瀏覽器不支持粘貼圖片!',
  9751. placeholder: '可以在編輯器直接貼圖。',
  9752. failMsg: '貼圖失敗,請稍後重試。',
  9753. uploadingHint: '正在上傳圖片,請稍後...',
  9754. },
  9755. en: {
  9756. notSupportMsg: 'Image is not allowed to paste in your browser!',
  9757. placeholder: 'You can paste images in the editor.',
  9758. failMsg: 'Pasting image failed. Try again later.',
  9759. uploadingHint: 'Uploading...',
  9760. }
  9761. };
  9762. self.afterCreate(function() {
  9763. var edit = self.edit;
  9764. var doc = edit.doc;
  9765. var uuid = self.uuid;
  9766. var options = self.options.pasteImage;
  9767. if (!options) {
  9768. return;
  9769. }
  9770. if (typeof options === 'string') {
  9771. options = {postUrl: options};
  9772. }
  9773. var langName = $.clientLang ? $.clientLang() : ($.zui && $.zui.clientLang) ? $.zui.clientLang() : 'en';
  9774. var lang = $.extend({}, ($.zui && $.zui.getLangData) ? $.zui.getLangData('kindeditor.advanceTable', langName, allLangs) : $.extend({}, allLangs.en, self.lang('table.'), allLangs[langName]), options.lang);
  9775. if(!K.WEBKIT && !K.GECKO)
  9776. {
  9777. $(doc.body).on('keyup.ke' + uuid, function(ev)
  9778. {
  9779. if(ev.keyCode == 86 && ev.ctrlKey) alert(lang.notSupportMsg);
  9780. });
  9781. }
  9782. if(self.setPlaceholder)
  9783. {
  9784. var placeholder = options.placeholder;
  9785. if (placeholder === true) placeholder = lang.placeholder;
  9786. if (placeholder) {
  9787. var oldPlaceholder = self.getPlaceholder();
  9788. if (!oldPlaceholder) oldPlaceholder = placeholder;
  9789. else if (oldPlaceholder.indexOf(placeholder) < 0) placeholder = oldPlaceholder + '\n' + placeholder;
  9790. self.setPlaceholder(placeholder);
  9791. }
  9792. }
  9793. var pasteBegin = function() {
  9794. // if ($.enableForm) {
  9795. // $.enableForm(false, 0, 1);
  9796. // $('body').one('click.ke' + uuid, function(){$.enableForm(true);});
  9797. // }
  9798. if (options.beforePaste) {
  9799. options.beforePaste();
  9800. }
  9801. var imageLoadingEle = '<div class="image-loading-ele small" style="padding: 5px; background: #FFF3E0; width: 300px; border-radius: 2px; border: 1px solid #FF9800; color: #ff5d5d; margin: 10px 0;"><i class="icon icon-spin icon-spinner-indicator muted"></i> ' + lang.uploadingHint + '</div>';
  9802. self.readonly(true);
  9803. if ($.fn.enableForm) {
  9804. $(self.edit.div[0]).closest('form').enableForm(false);
  9805. }
  9806. self.cmd.inserthtml(imageLoadingEle);
  9807. };
  9808. var pasteEnd = function(error) {
  9809. if(error) {
  9810. if (options.onError) {
  9811. options.onError(error);
  9812. } else {
  9813. if(error === true) error = lang.failMsg;
  9814. if ($.zui && $.zui.messager) {
  9815. $.zui.messager.danger(error, {placement: 'center'});
  9816. }
  9817. }
  9818. }
  9819. // if ($.enableForm) {
  9820. // $.enableForm(true, 0, 1);
  9821. // }
  9822. // $('body').off('.ke' + uuid);
  9823. if (options.afterPaste) {
  9824. options.afterPaste();
  9825. }
  9826. // Use self.undo to remove .image-loading-ele now
  9827. // $(doc.body).find('.image-loading-ele').remove();
  9828. self.readonly(false);
  9829. if ($.fn.enableForm) {
  9830. $(self.edit.div[0]).closest('form').enableForm(true);
  9831. }
  9832. };
  9833. var pasteUrl = options.postUrl;
  9834. var findBase64OnPaste = function() {
  9835. setTimeout(function() {
  9836. var html = K(doc.body).html();
  9837. if(html.search(/<img src="data:.+;base64,/) > -1) {
  9838. pasteBegin();
  9839. $.post(pasteUrl, {editor: html}, function(data) {
  9840. if(data.indexOf('<img') === 0) data = '<p>' + data + '</p>';
  9841. self.undo();
  9842. self._redoStack.pop();
  9843. edit.html(data);
  9844. pasteEnd();
  9845. }).error(function()
  9846. {
  9847. pasteEnd(true);
  9848. });
  9849. }
  9850. }, 80);
  9851. };
  9852. $(doc.body).on('paste.ke' + uuid, function(ev) {
  9853. if (K.WEBKIT) {
  9854. /* Paste in chrome.*/
  9855. /* Code reference from http://www.foliotek.com/devblog/copy-images-from-clipboard-in-javascript/. */
  9856. var original = ev.originalEvent;
  9857. var clipboardItems = original.clipboardData && original.clipboardData.items;
  9858. var clipboardItem = null;
  9859. if(clipboardItems)
  9860. {
  9861. var IMAGE_MIME_REGEX = /^image\/(p?jpeg|gif|png)$/i;
  9862. for (var i = 0; i < clipboardItems.length; i++)
  9863. {
  9864. var dataType = clipboardItems[i].type;
  9865. if(options.pasteTextFirst && dataType.indexOf('text/') === 0) return;
  9866. if (IMAGE_MIME_REGEX.test(dataType))
  9867. {
  9868. clipboardItem = clipboardItems[i];
  9869. if(!options.pasteTextFirst) break;
  9870. }
  9871. }
  9872. }
  9873. var file = clipboardItem && clipboardItem.getAsFile();
  9874. if (!file) return findBase64OnPaste();
  9875. original.preventDefault();
  9876. pasteBegin();
  9877. var reader = new FileReader();
  9878. reader.onload = function(evt) {
  9879. var result = evt.target.result;
  9880. // var arr = result.split(",");
  9881. // var data = arr[1]; // raw base64
  9882. // var contentType = arr[0].split(";")[0].split(":")[1];
  9883. var html = '<img src="' + result + '" alt="" />';
  9884. $.post(pasteUrl, {editor: html}, function(data)
  9885. {
  9886. self.undo();
  9887. self._redoStack.pop();
  9888. if (data) {
  9889. var $img = $(data);
  9890. edit.cmd.insertimage($img.attr('src'), $img.attr('title'), $img.attr('width'), $img.attr('height'));
  9891. } else {
  9892. edit.cmd.insertimage(result);
  9893. }
  9894. pasteEnd();
  9895. }).error(function()
  9896. {
  9897. pasteEnd(true);
  9898. });
  9899. };
  9900. reader.readAsDataURL(file);
  9901. } else {
  9902. /* Paste in firefox and other browsers. */
  9903. findBase64OnPaste();
  9904. }
  9905. });
  9906. self.beforeRemove(function() {
  9907. $(doc.body).off('.ke' + uuid);
  9908. });
  9909. });
  9910. });
  9911. /* cellPos jQuery plugin
  9912. ---------------------
  9913. Get visual position of cell in HTML table (or its block like thead).
  9914. Return value is object with "top" and "left" properties set to row and column index of top-left cell corner.
  9915. Example of use:
  9916. $("#myTable tbody td").each(function(){
  9917. $(this).text( $(this).cellPos().top +", "+ $(this).cellPos().left );
  9918. });
  9919. */
  9920. (function ($) {
  9921. /* scan individual table and set "cellPos" data in the form { left: x-coord, top: y-coord } */
  9922. function scanTable($table) {
  9923. var m = [];
  9924. var tableWidth = 0;
  9925. var tableHeight = 0;
  9926. $table.children('thead,tbody,tfoot').children('tr').each(function (y, row) {
  9927. $(row).children('td,th').each(function (x, cell) {
  9928. var $cell = $(cell),
  9929. cspan = $cell.attr('colspan') | 0,
  9930. rspan = $cell.attr('rowspan') | 0,
  9931. tx, ty;
  9932. cspan = cspan ? cspan : 1;
  9933. rspan = rspan ? rspan : 1;
  9934. for (; m[y] && m[y][x]; ++x); //skip already occupied cells in current row
  9935. for (tx = x; tx < x + cspan; ++tx) { //mark matrix elements occupied by current cell with true
  9936. for (ty = y; ty < y + rspan; ++ty) {
  9937. if (!m[ty]) { //fill missing rows
  9938. m[ty] = [];
  9939. }
  9940. m[ty][tx] = true;
  9941. }
  9942. }
  9943. var pos = {top: y, left: x, bottom: y + rspan - 1, right: x + cspan - 1};
  9944. $cell.data('cellPos', pos);
  9945. tableWidth = Math.max(tableWidth, pos.right);
  9946. tableHeight = Math.max(tableHeight, pos.bottom);
  9947. // $cell.text(x + ', ' + y + ' | ' + pos.right + ',' + pos.bottom);
  9948. });
  9949. });
  9950. $table.data('tableSize', {width: tableWidth + 1, height: tableHeight + 1});
  9951. };
  9952. /* plugin */
  9953. $.fn.cellPos = function (rescan) {
  9954. var $cell = this.first(),
  9955. pos = $cell.data('cellPos');
  9956. if (!pos || rescan) {
  9957. var $table = $cell.closest('table');
  9958. scanTable($table);
  9959. }
  9960. pos = $cell.data('cellPos');
  9961. return pos;
  9962. }
  9963. })(jQuery);
  9964. /*******************************************************************************
  9965. * KindEditor - WYSIWYG HTML Editor for Internet
  9966. * Copyright (C) 2006-2011 kindsoft.net
  9967. *
  9968. * @author Roddy <luolonghao@gmail.com>
  9969. * @site http://www.kindsoft.net/
  9970. * @licence http://www.kindsoft.net/license.php
  9971. *******************************************************************************/
  9972. KindEditor.plugin('table', function (K) {
  9973. var self = this;
  9974. var name = 'table';
  9975. var allLangs = {
  9976. zh_cn: {
  9977. name: '表格',
  9978. xRxC: '{0}行 × {1}列',
  9979. headerRow: '标题行',
  9980. headerCol: '标题列',
  9981. tableStyle: '表格样式',
  9982. addHeaderRow: '添加表格标题行',
  9983. stripedRows: '隔行变色效果',
  9984. hoverRows: '鼠标悬停效果',
  9985. autoChangeTableWidth: '自动调整表格尺寸',
  9986. tableWidthFixed: '按表格文字自适应',
  9987. tableWidthFull: '按页面宽度自适应',
  9988. tableBorder: '表格边框',
  9989. tableHead: '标题',
  9990. tableContent: '内容',
  9991. mergeCells: '合并单元格',
  9992. defaultColor: '默认颜色',
  9993. color: '颜色',
  9994. forecolor: '文字颜色',
  9995. backcolor: '背景颜色',
  9996. invalidBoderWidth: '边框大小必须为数字。'
  9997. },
  9998. zh_tw: {
  9999. name: '表格',
  10000. xRxC: '{0}行×{1}列',
  10001. headerRow: '標題行',
  10002. headerCol: '標題列',
  10003. tableStyle: '表格樣式',
  10004. addHeaderRow: '添加表格標題行',
  10005. stripedRows: '隔行變色效果',
  10006. hoverRows: '鼠標懸停效果',
  10007. autoChangeTableWidth: '自動調整表格尺寸',
  10008. tableWidthFixed: '按表格文字自適應',
  10009. tableWidthFull: '按頁面寬度自適應',
  10010. tableBorder: '表格邊框',
  10011. tableHead: '標題',
  10012. tableContent: '內容',
  10013. mergeCells: '合併單元格',
  10014. defaultColor: '默認顏色',
  10015. color: '顏色',
  10016. forecolor: '文字顏色',
  10017. backcolor: '背景顏色',
  10018. invalidBoderWidth: '邊框大小必須為數字。'
  10019. },
  10020. en: {
  10021. name: 'Table',
  10022. xRxC: '{0} Rows × {1} Columns',
  10023. headerRow: 'Header Row',
  10024. headerCol: 'Header Column',
  10025. tableStyle: 'Table style',
  10026. addHeaderRow: 'Add header row',
  10027. stripedRows: 'Striped effection',
  10028. hoverRows: 'Mouse hover effection',
  10029. autoChangeTableWidth: 'Automatically adjust table size',
  10030. tableWidthFixed: 'Adaptive by form text',
  10031. tableWidthFull: 'Page width adaptive',
  10032. tableBorder: 'Table border',
  10033. tableHead: 'Title',
  10034. tableContent: 'Text',
  10035. mergeCells: 'Merge Cells',
  10036. defaultColor: 'Default color',
  10037. color: 'Color',
  10038. forecolor: 'Text Color',
  10039. backcolor: 'Back Color',
  10040. invalidBoderWidth: 'Border width value must be number'
  10041. }
  10042. };
  10043. var $elements = [];
  10044. var langName = $.clientLang ? $.clientLang() : ($.zui && $.zui.clientLang) ? $.zui.clientLang() : 'en';
  10045. var lang = ($.zui && $.zui.getLangData) ? $.extend({}, self.lang('table.'), $.zui.getLangData('kindeditor.advanceTable', langName, allLangs)) : $.extend({}, allLangs.en, self.lang('table.'), allLangs[langName]);
  10046. var defaultTableBorderColor = self.options.tableBorderColor || '#ddd';
  10047. self.tableIdIndex = 0;
  10048. // 设置颜色
  10049. function _setColor(box, color) {
  10050. color = color.toUpperCase();
  10051. box.css('background-color', color);
  10052. if (color) {
  10053. if ($ && $.zui && $.zui.Color) {
  10054. box.css('color', new $.zui.Color(color).contrast().toCssStr());
  10055. } else {
  10056. box.css('color', (color === '#FFF' || color === '#FFFFFF') ? '#000' : '#FFF');
  10057. }
  10058. }
  10059. box.name === 'input' ? box.val(color) : box.html(color);
  10060. }
  10061. // 初始化取色器
  10062. var pickerList = [];
  10063. function _initColorPicker(dialogDiv, colorBox, onSetColor) {
  10064. colorBox.bind('click,mousedown', function (e) {
  10065. e.stopPropagation();
  10066. });
  10067. function removePicker() {
  10068. K.each(pickerList, function () {
  10069. this.remove();
  10070. });
  10071. pickerList = [];
  10072. K(document).unbind('click,mousedown', removePicker);
  10073. dialogDiv.unbind('click,mousedown', removePicker);
  10074. }
  10075. colorBox.click(function (e) {
  10076. removePicker();
  10077. var box = K(this),
  10078. pos = box.pos();
  10079. var picker = K.colorpicker({
  10080. x: pos.x,
  10081. y: pos.y + box.height(),
  10082. z: 811214,
  10083. selectedColor: K(this).val(),
  10084. colors: self.colorTable,
  10085. noColor: lang['defaultColor'],
  10086. shadowMode: self.shadowMode,
  10087. click: function (color) {
  10088. _setColor(box, color);
  10089. removePicker();
  10090. onSetColor && onSetColor(color);
  10091. }
  10092. });
  10093. pickerList.push(picker);
  10094. K(document).bind('click,mousedown', removePicker);
  10095. dialogDiv.bind('click,mousedown', removePicker);
  10096. });
  10097. }
  10098. // 取得下一行cell的index
  10099. function _getCellIndex(table, row, cell) {
  10100. var rowSpanCount = 0;
  10101. for (var i = 0, len = row.cells.length; i < len; i++) {
  10102. if (row.cells[i] == cell) {
  10103. break;
  10104. }
  10105. rowSpanCount += row.cells[i].rowSpan - 1;
  10106. }
  10107. return cell.cellIndex - rowSpanCount;
  10108. }
  10109. function removeEvent() {
  10110. K.each($elements, function () {
  10111. this.off('.kTable');
  10112. });
  10113. }
  10114. function getTableSetting($table, setting)
  10115. {
  10116. if (!$table) {
  10117. var table = self.plugin.getSelectedTable();
  10118. $table = $(table[0]);
  10119. }
  10120. var setting = $.extend({
  10121. borderColor: defaultTableBorderColor
  10122. }, $table.data('tableSetting'), setting);
  10123. if (setting.autoWidth === undefined) {
  10124. setting.autoWidth = $table[0].style.width === 'auto';
  10125. }
  10126. if (setting.stripedRows === undefined) {
  10127. var $rows = $table.find('tbody>tr');
  10128. var coloredRowsLength = $rows.filter(function () {
  10129. return !!this.style.backgroundColor;
  10130. }).length;
  10131. setting.stripedRows = coloredRowsLength >= Math.floor($rows.length / 2);
  10132. }
  10133. return setting;
  10134. }
  10135. function updateTable(setting, $table, onUpdateSetting) {
  10136. if (!$table) {
  10137. var table = self.plugin.getSelectedTable();
  10138. $table = $(table[0]);
  10139. }
  10140. if (!$table || !$table.length) return;
  10141. setting = getTableSetting($table, setting);
  10142. $table.data('tableSetting', setting);
  10143. if (setting.header !== undefined) {
  10144. if ($table.is('.ke-plugin-table-example')) {
  10145. $table.find('thead').toggleClass('hidden', !setting.header);
  10146. } else {
  10147. var $thead = $table.find('thead');
  10148. if (setting.header) {
  10149. if (!$thead.length) {
  10150. var theadHtml = ['<thead><tr>'];
  10151. var $firstRow = $table.find('tbody>tr:first').children();
  10152. var colsCount = 0;
  10153. $firstRow.each(function () {
  10154. var $cell = $(this);
  10155. var cellSpan = $cell.attr('colspan');
  10156. colsCount += cellSpan ? parseInt(cellSpan) : 1;
  10157. });
  10158. for (var i = 0; i < colsCount; ++i) {
  10159. theadHtml.push('<th style="background-color: #f1f1f1; border: 1px solid ' + (setting.borderColor || defaultTableBorderColor) + '">' + (K.IE ? '&nbsp;' : '<br />') + '</th>');
  10160. }
  10161. theadHtml.push('</tr></thead>');
  10162. $thead = $(theadHtml.join(''));
  10163. $table.prepend($thead);
  10164. }
  10165. } else {
  10166. $thead.remove();
  10167. }
  10168. }
  10169. onUpdateSetting && onUpdateSetting('header', setting.header);
  10170. }
  10171. if (setting.stripedRows !== undefined) {
  10172. var $rows = $table.find('tbody>tr');
  10173. $rows.each(function (index) {
  10174. $(this).css('background-color', (setting.stripedRows && (index % 2 === 0)) ? '#f9f9f9' : '');
  10175. });
  10176. onUpdateSetting && onUpdateSetting('stripedRows', setting.stripedRows);
  10177. }
  10178. // if (setting.hoverRows !== undefined) {
  10179. // $table.toggleClass('table-hover', !!setting.hoverRows);
  10180. // onUpdateSetting && onUpdateSetting('hoverRows', setting.hoverRows);
  10181. // }
  10182. if (setting.autoWidth !== undefined) {
  10183. $table.css(setting.autoWidth ? {
  10184. width: 'auto',
  10185. maxWidth: '100%'
  10186. } : {
  10187. width: '100%',
  10188. });
  10189. onUpdateSetting && onUpdateSetting('autoWidth', setting.autoWidth);
  10190. }
  10191. if (setting.borderColor !== undefined) {
  10192. $table.find('td,th').css('border-color', setting.borderColor);
  10193. onUpdateSetting && onUpdateSetting('borderColor', setting.borderColor);
  10194. }
  10195. }
  10196. function insertTable(row, col, headerRow, headerCol) {
  10197. if (!(row * col)) {
  10198. return;
  10199. }
  10200. var tableID = 'ke-table-' + (self.tableIdIndex++);
  10201. var $table = $('<table id="' + tableID + '" class="table table-kindeditor" style="width: 100%"></table>');
  10202. var $body = $('<tbody></tbody>');
  10203. for (var r = 0; r < row; r++) {
  10204. var $row = $('<tr></tr>');
  10205. for (var c = 0; c < col; c++) {
  10206. var $cell = $('<td style="border: 1px solid ' + defaultTableBorderColor + '">' + (K.IE ? '&nbsp;' : '<br />') + '</td>');
  10207. $row.append($cell);
  10208. }
  10209. $body.append($row);
  10210. }
  10211. $table.append($body);
  10212. var html = $('<div>').append($table).html();
  10213. if (!K.IE) {
  10214. html += '<br />';
  10215. }
  10216. self.insertHtml(html);
  10217. var $table = $(self.edit.doc).find('#' + tableID);
  10218. $table.attr('id', null);
  10219. self.cmd.range.selectNodeContents($table.find('th,td').first()[0]).collapse(true);
  10220. self.cmd.select();
  10221. self.addBookmark();
  10222. return $table;
  10223. }
  10224. function modifyTable(table) {
  10225. var $table = $(table[0]);
  10226. var theadHtml = ['<thead><tr>'];
  10227. var tbodyHtml = ['<tbody>'];
  10228. for (var i = 0; i < 6; ++i) {
  10229. theadHtml.push('<th style="padding:4px">{tableHead}</th>');
  10230. tbodyHtml.push('<tr>');
  10231. for (var j = 0; j < 6; ++j) {
  10232. tbodyHtml.push('<td style="padding:4px">{tableContent}</td>');
  10233. }
  10234. tbodyHtml.push('</tr>');
  10235. }
  10236. theadHtml.push('</tr></thead>');
  10237. tbodyHtml.push('</tbody>');
  10238. var dialogHtml = [
  10239. '<div class="container" style="padding: 15px">',
  10240. '<div class="row">',
  10241. '<div class="col-xs-5 col-left">',
  10242. '<div class="form-group">',
  10243. '<label>{tableStyle}</label>',
  10244. '<div class="checkbox" style="margin: 0 0 5px"><label><input type="checkbox" name="header"> {addHeaderRow}</label></div>',
  10245. '<div class="checkbox" style="margin: 0 0 5px"><label><input type="checkbox" name="stripedRows"> {stripedRows}</label></div>',
  10246. // '<div class="checkbox" style="margin: 0 0 5px"><label><input type="checkbox" name="hoverRows"> {hoverRows}</label></div>',
  10247. '</div>',
  10248. '<div class="form-group">',
  10249. '<label>{autoChangeTableWidth}</label>',
  10250. '<div class="radio" style="margin: 0 0 5px"><label><input type="radio" name="autoWidth" value="auto"> {tableWidthFixed}</label></div>',
  10251. '<div class="radio" style="margin: 0 0 5px"><label><input type="radio" name="autoWidth" value=""> {tableWidthFull}</label></div>',
  10252. '</div>',
  10253. '<div class="form-group" style="margin: 0">',
  10254. '<label>{tableBorder}</label>',
  10255. '<div class="input-group" style="width: 180px">',
  10256. '<span class="input-group-addon">{borderColor}</span>',
  10257. '<input class="form-control ke-plugin-table-input-color" readonly style="background: ' + defaultTableBorderColor + '; color: #333; font-size: 12px" value="' + defaultTableBorderColor + '" name="borderColor" />',
  10258. '</div>',
  10259. '</div>',
  10260. '</div>',
  10261. '<div class="col-xs-7 col-right">',
  10262. '<table class="table table-bordered table-kindeditor ke-plugin-table-example">',
  10263. theadHtml.join(''),
  10264. tbodyHtml.join(''),
  10265. '<table>',
  10266. '</div>',
  10267. '</div>',
  10268. '</div>'
  10269. ].join('').format(lang);
  10270. var $dialog = $(dialogHtml);
  10271. var $exampleTable = $dialog.find('.ke-plugin-table-example');
  10272. var bookmark = self.cmd.range.createBookmark();
  10273. var $colorBox = $dialog.find('.ke-plugin-table-input-color');
  10274. var colorBox = K($colorBox[0]);
  10275. $dialog.on('change.kTable', 'input[name]', function () {
  10276. var $input = $(this);
  10277. var updateSetting = {};
  10278. updateSetting[$input.attr('name')] = $input.is('[type="checkbox"]') ? $input.is(':checked') : $input.val();
  10279. updateTable(updateSetting, $exampleTable);
  10280. });
  10281. var dialog = self.createDialog({
  10282. name: name + 'Dialog',
  10283. width: 550,
  10284. title: self.lang(name),
  10285. body: $dialog[0],
  10286. beforeRemove: function () {
  10287. $dialog.off('.kTable');
  10288. },
  10289. yesBtn: {
  10290. name: self.lang('yes'),
  10291. click: function (e) {
  10292. updateTable({
  10293. borderColor: $dialog.find('[name="borderColor"]').val(),
  10294. header: $dialog.find('[name="header"]').is(':checked'),
  10295. stripedRows: $dialog.find('[name="stripedRows"]').is(':checked'),
  10296. hoverRows: $dialog.find('[name="hoverRows"]').is(':checked'),
  10297. autoWidth: $dialog.find('[name="autoWidth"]:checked').val(),
  10298. }, $table);
  10299. self.hideDialog().focus();
  10300. self.cmd.range.moveToBookmark(bookmark);
  10301. self.cmd.select();
  10302. self.addBookmark();
  10303. }
  10304. }
  10305. });
  10306. _initColorPicker(dialog.div, colorBox, function (color) {
  10307. updateTable({ borderColor: color }, $exampleTable);
  10308. });
  10309. updateTable(getTableSetting($table), $exampleTable, function (name, value) {
  10310. switch (name) {
  10311. case 'borderColor':
  10312. _setColor(colorBox, value || defaultTableBorderColor);
  10313. break;
  10314. case 'header':
  10315. $dialog.find('[name="header"]').prop('checked', !!value);
  10316. break;
  10317. case 'stripedRows':
  10318. $dialog.find('[name="stripedRows"]').prop('checked', !!value);
  10319. break;
  10320. case 'hoverRows':
  10321. $dialog.find('[name="hoverRows"]').prop('checked', !!value);
  10322. break;
  10323. case 'autoWidth':
  10324. $dialog.find('[name="autoWidth"][value="' + (value ? 'auto' : '') + '"]').prop('checked', true);
  10325. break;
  10326. }
  10327. });
  10328. }
  10329. if (!self.plugin.table) {
  10330. self.plugin.table = {
  10331. // modify table
  10332. prop: function () {
  10333. var table = self.plugin.getSelectedTable();
  10334. if (table && table.length) {
  10335. modifyTable(table);
  10336. }
  10337. },
  10338. //modify cell
  10339. cellprop: function () {
  10340. var html = [
  10341. '<div class="form-horizontal" style="padding: 20px;">',
  10342. //width, height
  10343. '<div class="form-group">',
  10344. '<label class="col-xs-2" style="margin: 0;">' + lang.size + '</label>',
  10345. '<div class="col-xs-5">',
  10346. '<div class="input-group">',
  10347. '<span class="input-group-addon">' + lang.width + '</span>',
  10348. '<input type="number" class="form-control" id="keWidth" name="width" value="" maxlength="4" />',
  10349. '<span class="input-group-addon fix-border fix-padding"></span>',
  10350. '<select name="widthType" class="form-control" style="width: 45px">',
  10351. '<option value="%">' + lang.percent + '</option>',
  10352. '<option value="px">' + lang.px + '</option>',
  10353. '</select>',
  10354. '</div>',
  10355. '</div>',
  10356. '<div class="col-xs-5">',
  10357. '<div class="input-group">',
  10358. '<span class="input-group-addon">' + lang.height + '</span>',
  10359. '<input type="number" class="form-control" id="keWidth" name="height" value="" maxlength="4" />',
  10360. '<span class="input-group-addon fix-border fix-padding"></span>',
  10361. '<select name="heightType" class="form-control" style="width: 45px">',
  10362. '<option value="%">' + lang.percent + '</option>',
  10363. '<option value="px">' + lang.px + '</option>',
  10364. '</select>',
  10365. '</div>',
  10366. '</div>',
  10367. '</div>',
  10368. //align
  10369. '<div class="form-group">',
  10370. '<label class="col-xs-2" style="margin: 0;">' + lang.align + '</label>',
  10371. '<div class="col-xs-5">',
  10372. '<div class="input-group">',
  10373. '<span class="input-group-addon">' + lang.textAlign + '</span>',
  10374. '<select id="keAlign" name="textAlign" class="form-control">',
  10375. '<option value="">' + lang.alignDefault + '</option>',
  10376. '<option value="left">' + lang.alignLeft + '</option>',
  10377. '<option value="center">' + lang.alignCenter + '</option>',
  10378. '<option value="right">' + lang.alignRight + '</option>',
  10379. '</select>',
  10380. '</div>',
  10381. '</div>',
  10382. '<div class="col-xs-5">',
  10383. '<div class="input-group">',
  10384. '<span class="input-group-addon">' + lang.verticalAlign + '</span>',
  10385. '<select name="verticalAlign" class="form-control">',
  10386. '<option value="">' + lang.alignDefault + '</option>',
  10387. '<option value="top">' + lang.alignTop + '</option>',
  10388. '<option value="middle">' + lang.alignMiddle + '</option>',
  10389. '<option value="bottom">' + lang.alignBottom + '</option>',
  10390. '<option value="baseline">' + lang.alignBaseline + '</option>',
  10391. '</select>',
  10392. '</div>',
  10393. '</div>',
  10394. '</div>',
  10395. //border
  10396. '<div class="form-group">',
  10397. '<label class="col-xs-2" style="margin: 0;">' + lang.border + '</label>',
  10398. '<div class="col-xs-5">',
  10399. '<div class="input-group">',
  10400. '<span class="input-group-addon">' + lang.borderColor + '</span>',
  10401. '<input class="form-control ke-plugin-table-input-color" readonly style="background: ' + defaultTableBorderColor + '; color: #333; font-size: 12px" value="' + defaultTableBorderColor + '" name="borderColor" />',
  10402. '</div>',
  10403. '</div>',
  10404. '<div class="col-xs-5">',
  10405. '<div class="input-group">',
  10406. '<span class="input-group-addon">' + lang.size + '</span>',
  10407. '<input type="number" class="form-control" name="borderWidth" value="1" min="0" step="1" />',
  10408. '<span class="input-group-addon">px</span>',
  10409. '</div>',
  10410. '</div>',
  10411. '</div>',
  10412. //background color
  10413. '<div class="form-group">',
  10414. '<label class="col-xs-2" style="margin: 0;">' + lang.color + '</label>',
  10415. '<div class="col-xs-5">',
  10416. '<div class="input-group">',
  10417. '<span class="input-group-addon">' + lang.forecolor + '</span>',
  10418. '<input class="form-control ke-plugin-table-input-color" readonly style="background: #333; color: #fff; font-size: 12px" value="#333" name="forecolor" />',
  10419. '</div>',
  10420. '</div>',
  10421. '<div class="col-xs-5">',
  10422. '<div class="input-group">',
  10423. '<span class="input-group-addon">' + lang.backcolor + '</span>',
  10424. '<input class="form-control ke-plugin-table-input-color" readonly style="background: #fff; color: #333; font-size: 12px" value="#333" name="backgroundColor" />',
  10425. '</div>',
  10426. '</div>',
  10427. '</div>',
  10428. '</div>',
  10429. ].join('');
  10430. var bookmark = self.cmd.range.createBookmark();
  10431. var div, widthBox, heightBox, widthTypeBox, widthTypeBox, textAlignBox, verticalAlignBox, colorBox, borderWidthBox;
  10432. var dialog = self.createDialog({
  10433. name: name,
  10434. width: 500,
  10435. title: self.lang('tablecell'),
  10436. body: html,
  10437. beforeRemove: function () {
  10438. colorBox.unbind();
  10439. },
  10440. yesBtn: {
  10441. name: self.lang('yes'),
  10442. click: function (e) {
  10443. var width = widthBox.val(),
  10444. height = heightBox.val(),
  10445. widthType = widthTypeBox.val(),
  10446. heightType = heightTypeBox.val(),
  10447. textAlign = textAlignBox.val(),
  10448. verticalAlign = verticalAlignBox.val(),
  10449. borderWidth = borderWidthBox.val(),
  10450. borderColor = K(colorBox[0]).val() || '',
  10451. textColor = K(colorBox[1]).val() || '',
  10452. bgColor = K(colorBox[2]).val() || '';
  10453. if (!/^\d*$/.test(width)) {
  10454. alert(self.lang('invalidWidth'));
  10455. widthBox[0].focus();
  10456. return;
  10457. }
  10458. if (!/^\d*$/.test(height)) {
  10459. alert(self.lang('invalidHeight'));
  10460. heightBox[0].focus();
  10461. return;
  10462. }
  10463. if (!/^\d*$/.test(borderWidth)) {
  10464. alert(lang.invalidBoderWidth);
  10465. borderWidthBox[0].focus();
  10466. return;
  10467. }
  10468. var cells = self.plugin.getAllSelectedCells();
  10469. var style = {
  10470. width: width !== '' ? (width + widthType) : '',
  10471. height: height !== '' ? (height + heightType) : '',
  10472. 'background-color': bgColor,
  10473. 'text-align': textAlign,
  10474. 'border-width': borderWidth + 'px',
  10475. 'vertical-align': verticalAlign,
  10476. 'border-color': borderColor,
  10477. color: textColor
  10478. };
  10479. for(var i = 0; i < cells.length; ++i) {
  10480. cells.eq(i).css(style);
  10481. }
  10482. self.hideDialog().focus();
  10483. self.cmd.range.moveToBookmark(bookmark);
  10484. self.cmd.select();
  10485. self.addBookmark();
  10486. }
  10487. }
  10488. });
  10489. div = dialog.div,
  10490. widthBox = K('[name="width"]', div).val(100),
  10491. heightBox = K('[name="height"]', div),
  10492. widthTypeBox = K('[name="widthType"]', div),
  10493. heightTypeBox = K('[name="heightType"]', div),
  10494. textAlignBox = K('[name="textAlign"]', div),
  10495. verticalAlignBox = K('[name="verticalAlign"]', div),
  10496. borderWidthBox = K('[name="borderWidth"]', div),
  10497. colorBox = K('.ke-plugin-table-input-color', div);
  10498. _initColorPicker(div, colorBox.eq(0));
  10499. _initColorPicker(div, colorBox.eq(1));
  10500. _initColorPicker(div, colorBox.eq(2));
  10501. _setColor(colorBox.eq(0), '#000000');
  10502. _setColor(colorBox.eq(1), '');
  10503. _setColor(colorBox.eq(2), '');
  10504. // foucs and select
  10505. widthBox[0].focus();
  10506. widthBox[0].select();
  10507. // get selected cell
  10508. var cell = self.plugin.getSelectedCell();
  10509. var match,
  10510. cellWidth = cell[0].style.width || cell[0].width || '',
  10511. cellHeight = cell[0].style.height || cell[0].height || '';
  10512. if ((match = /^(\d+)((?:px|%)*)$/.exec(cellWidth))) {
  10513. widthBox.val(match[1]);
  10514. widthTypeBox.val(match[2]);
  10515. } else {
  10516. widthBox.val('');
  10517. }
  10518. if ((match = /^(\d+)((?:px|%)*)$/.exec(cellHeight))) {
  10519. heightBox.val(match[1]);
  10520. heightTypeBox.val(match[2]);
  10521. }
  10522. var borderWidth = cell[0].style.borderWidth || '';
  10523. if ((match = /^(\d+)((?:px)*)$/.exec(borderWidth))) {
  10524. borderWidthBox.val(match[1]);
  10525. }
  10526. textAlignBox.val(cell[0].style.textAlign || '');
  10527. verticalAlignBox.val(cell[0].style.verticalAlign || '');
  10528. _setColor(colorBox.eq(0), K.toHex(cell[0].style.borderColor || ''));
  10529. _setColor(colorBox.eq(1), K.toHex(cell[0].style.color || ''));
  10530. _setColor(colorBox.eq(2), K.toHex(cell[0].style.backgroundColor || ''));
  10531. widthBox[0].focus();
  10532. widthBox[0].select();
  10533. },
  10534. insert: function () {
  10535. console.warn('Table insert not available.');
  10536. },
  10537. 'delete': function () {
  10538. var table = self.plugin.getSelectedTable();
  10539. self.cmd.range.setStartBefore(table[0]).collapse(true);
  10540. self.cmd.select();
  10541. table.remove();
  10542. self.addBookmark();
  10543. },
  10544. colinsert: function (offset) {
  10545. var table = self.plugin.getSelectedTable()[0],
  10546. row = self.plugin.getSelectedRow()[0],
  10547. cell = self.plugin.getSelectedCell()[0],
  10548. index = cell.cellIndex + offset;
  10549. var tableSetting = getTableSetting($(table));
  10550. // 取得第一行的index
  10551. index += table.rows[0].cells.length - row.cells.length;
  10552. for (var i = 0, len = table.rows.length; i < len; i++) {
  10553. var newRow = table.rows[i],
  10554. newCell = newRow.insertCell(index),
  10555. isThead = newRow.parentNode.tagName === 'THEAD';
  10556. newCell.outerHTML = '<' + (isThead ? 'th' : 'td') + (newCell.rowSpan > 1 ? ' rowspan="' + newCell.rowSpan + '"' : '') + (newCell.colSpan > 1 ? ' colspan="' + newCell.colSpan + '"' : '') + ' style="' + (isThead ? 'background-color: #f1f1f1;' : '') + 'border: 1px solid ' + ((tableSetting && tableSetting.borderColor) || defaultTableBorderColor) + '">' + (K.IE ? '&nbsp;' : '<br />') + '</' + (isThead ? 'th' : 'td') + '>';
  10557. newCell = newRow.cells[index];
  10558. // 调整下一行的单元格index
  10559. index = _getCellIndex(table, newRow, newCell);
  10560. }
  10561. self.cmd.range.selectNodeContents(cell).collapse(true);
  10562. // self.cmd.select();
  10563. self.addBookmark();
  10564. self.focus();
  10565. },
  10566. colinsertleft: function () {
  10567. this.colinsert(0);
  10568. },
  10569. colinsertright: function () {
  10570. this.colinsert(1);
  10571. },
  10572. rowinsert: function (offset) {
  10573. var table = self.plugin.getSelectedTable()[0],
  10574. row = self.plugin.getSelectedRow()[0],
  10575. cell = self.plugin.getSelectedCell()[0],
  10576. firstRow = table.rows[0];
  10577. var tableSetting = getTableSetting($(table));
  10578. var rowIndex = row.rowIndex;
  10579. if (offset === 1) {
  10580. rowIndex = row.rowIndex + (cell.rowSpan - 1) + offset;
  10581. }
  10582. var newRow = table.insertRow(rowIndex);
  10583. var isThead = newRow.parentNode.tagName === 'THEAD';
  10584. // debugger;
  10585. for (var i = 0, len = firstRow.cells.length; i < len; i++) {
  10586. // 调整cell个数
  10587. var currentCell = firstRow.cells[i];
  10588. if (currentCell && currentCell.rowSpan > 1) {
  10589. len += currentCell.rowSpan - 1;
  10590. }
  10591. var newCell = newRow.insertCell(i);
  10592. // copy colspan
  10593. // if (offset === 1 && currentCell.colSpan > 1) {
  10594. // newCell.colSpan = currentCell.colSpan;
  10595. // }
  10596. newCell.outerHTML = '<' + (isThead ? 'th' : 'td') + (newCell.rowSpan > 1 ? ' rowspan="' + newCell.rowSpan + '"' : '') + (newCell.colSpan > 1 ? ' colspan="' + newCell.colSpan + '"' : '') + ' style="' + (isThead ? 'background-color: #f1f1f1;' : '') + 'border: 1px solid ' + ((tableSetting && tableSetting.borderColor) || defaultTableBorderColor) + '">' + (K.IE ? '&nbsp;' : '<br />') + '</' + (isThead ? 'th' : 'td') + '>';
  10597. }
  10598. // 调整rowspan
  10599. for (var j = rowIndex; j >= 0; j--) {
  10600. var cells = table.rows[j].cells;
  10601. if (cells.length > i) {
  10602. for (var k = cell.cellIndex; k >= 0; k--) {
  10603. if (cells[k].rowSpan > 1) {
  10604. cells[k].rowSpan += 1;
  10605. }
  10606. }
  10607. break;
  10608. }
  10609. }
  10610. updateTable(null, $(table));
  10611. self.cmd.range.selectNodeContents(cell).collapse(true);
  10612. // self.cmd.select();
  10613. self.addBookmark();
  10614. self.focus();
  10615. },
  10616. rowinsertabove: function () {
  10617. this.rowinsert(0);
  10618. },
  10619. rowinsertbelow: function () {
  10620. this.rowinsert(1);
  10621. },
  10622. rowmerge: function () {
  10623. var table = self.plugin.getSelectedTable()[0],
  10624. row = self.plugin.getSelectedRow()[0],
  10625. cell = self.plugin.getSelectedCell()[0],
  10626. rowIndex = row.rowIndex, // 当前行的index
  10627. nextRowIndex = rowIndex + cell.rowSpan, // 下一行的index
  10628. nextRow = table.rows[nextRowIndex]; // 下一行
  10629. // 最后一行不能合并
  10630. if (table.rows.length <= nextRowIndex) {
  10631. return;
  10632. }
  10633. var cellIndex = cell.cellIndex; // 下一行单元格的index
  10634. if (nextRow.cells.length <= cellIndex) {
  10635. return;
  10636. }
  10637. var nextCell = nextRow.cells[cellIndex]; // 下一行单元格
  10638. // 上下行的colspan不一致时不能合并
  10639. if (cell.colSpan !== nextCell.colSpan) {
  10640. return;
  10641. }
  10642. cell.rowSpan += nextCell.rowSpan;
  10643. nextRow.deleteCell(cellIndex);
  10644. self.cmd.range.selectNodeContents(cell).collapse(true);
  10645. // self.cmd.select();
  10646. self.addBookmark();
  10647. self.focus();
  10648. },
  10649. colmerge: function () {
  10650. var table = self.plugin.getSelectedTable()[0],
  10651. row = self.plugin.getSelectedRow()[0],
  10652. cell = self.plugin.getSelectedCell()[0],
  10653. rowIndex = row.rowIndex, // 当前行的index
  10654. cellIndex = cell.cellIndex,
  10655. nextCellIndex = cellIndex + 1;
  10656. // 最后一列不能合并
  10657. if (row.cells.length <= nextCellIndex) {
  10658. return;
  10659. }
  10660. var nextCell = row.cells[nextCellIndex];
  10661. // 左右列的rowspan不一致时不能合并
  10662. if (cell.rowSpan !== nextCell.rowSpan) {
  10663. return;
  10664. }
  10665. cell.colSpan += nextCell.colSpan;
  10666. row.deleteCell(nextCellIndex);
  10667. updateTable(null, $(table));
  10668. self.cmd.range.selectNodeContents(cell).collapse(true);
  10669. // self.cmd.select();
  10670. self.addBookmark();
  10671. self.focus();
  10672. },
  10673. mergeCells: function () {
  10674. var tableSelectionRange = self.tableSelectionRange;
  10675. if (!tableSelectionRange) return;
  10676. var table = self.plugin.getSelectedTable()[0];
  10677. var $table = $(table);
  10678. var top = tableSelectionRange.top;
  10679. var left = tableSelectionRange.left;
  10680. var right = tableSelectionRange.right;
  10681. var bottom = tableSelectionRange.bottom;
  10682. var $firstCell;
  10683. $table.children('thead,tbody,tfoot').children('tr').each(function () {
  10684. $(this).children('td,th').each(function () {
  10685. var $cell = $(this);
  10686. var pos = $cell.cellPos();
  10687. if (pos.left === left && pos.top === top) {
  10688. $firstCell = $cell;
  10689. } else if (pos.right >= left && pos.left <= right && pos.bottom >= top && pos.top <= bottom) {
  10690. $cell.addClass('ke-cell-removed');
  10691. }
  10692. });
  10693. });
  10694. if ($firstCell) {
  10695. $firstCell.attr({
  10696. rowspan: bottom - top + 1,
  10697. colspan: right - left + 1,
  10698. });
  10699. $table.find('.ke-cell-removed').remove();
  10700. updateTable(null, $table);
  10701. self.cmd.range.selectNodeContents($firstCell[0]).collapse(true);
  10702. // self.cmd.select();
  10703. self.addBookmark();
  10704. self.focus();
  10705. }
  10706. },
  10707. rowsplit: function () {
  10708. var table = self.plugin.getSelectedTable()[0],
  10709. row = self.plugin.getSelectedRow()[0],
  10710. cell = self.plugin.getSelectedCell()[0],
  10711. rowIndex = row.rowIndex;
  10712. var tableSetting = getTableSetting($(table));
  10713. // 不是可分割单元格
  10714. if (cell.rowSpan === 1) {
  10715. return;
  10716. }
  10717. var cellIndex = _getCellIndex(table, row, cell);
  10718. for (var i = 1, len = cell.rowSpan; i < len; i++) {
  10719. var newRow = table.rows[rowIndex + i],
  10720. newCell = newRow.insertCell(cellIndex);
  10721. var isThead = newRow.parentNode.tagName === 'THEAD';
  10722. var colSpan = cell.colSpan > 1 ? cell.colSpan : newCell.colSpan;
  10723. newCell.outerHTML = '<' + (isThead ? 'th' : 'td') + (newCell.rowSpan > 1 ? ' rowspan="' + newCell.rowSpan + '"' : '') + (colSpan > 1 ? ' colspan="' + colSpan + '"' : '') + ' style="' + (isThead ? 'background-color: #f1f1f1;' : '') + 'border: 1px solid ' + ((tableSetting && tableSetting.borderColor) || defaultTableBorderColor) + '">' + (K.IE ? '&nbsp;' : '<br />') + '</' + (isThead ? 'th' : 'td') + '>';
  10724. if (cell.colSpan > 1) {
  10725. newCell.colSpan = cell.colSpan;
  10726. }
  10727. // 调整下一行的单元格index
  10728. cellIndex = _getCellIndex(table, newRow, newCell);
  10729. }
  10730. K(cell).removeAttr('rowSpan');
  10731. updateTable(null, $(table));
  10732. self.cmd.range.selectNodeContents(cell).collapse(true);
  10733. // self.cmd.select();
  10734. self.addBookmark();
  10735. self.focus();
  10736. },
  10737. colsplit: function () {
  10738. var table = self.plugin.getSelectedTable()[0],
  10739. row = self.plugin.getSelectedRow()[0],
  10740. cell = self.plugin.getSelectedCell()[0],
  10741. cellIndex = cell.cellIndex;
  10742. var tableSetting = getTableSetting($(table));
  10743. // 不是可分割单元格
  10744. if (cell.colSpan === 1) {
  10745. return;
  10746. }
  10747. var isThead = row.parentNode.tagName === 'THEAD';
  10748. for (var i = 1, len = cell.colSpan; i < len; i++) {
  10749. var newCell = row.insertCell(cellIndex + i);
  10750. var rowSpan = cell.rowSpan > 1 ? cell.rowSpan : newCell.rowSpan;
  10751. var colSpan = newCell.colSpan;
  10752. newCell.outerHTML = '<' + (isThead ? 'th' : 'td') + (rowSpan > 1 ? ' rowspan="' + rowSpan + '"' : '') + (colSpan > 1 ? ' colspan="' + colSpan + '"' : '') + ' style="' + (isThead ? 'background-color: #f1f1f1;' : '') + 'border: 1px solid ' + ((tableSetting && tableSetting.borderColor) || defaultTableBorderColor) + '">' + (K.IE ? '&nbsp;' : '<br />') + '</' + (isThead ? 'th' : 'td') + '>';
  10753. }
  10754. K(cell).removeAttr('colSpan');
  10755. updateTable(null, $(table));
  10756. self.cmd.range.selectNodeContents(cell).collapse(true);
  10757. // self.cmd.select();
  10758. self.addBookmark();
  10759. self.focus();
  10760. },
  10761. coldelete: function () {
  10762. var table = self.plugin.getSelectedTable()[0];
  10763. var cells = self.plugin.getAllSelectedCells();
  10764. if (!cells.length) return;
  10765. for (var j = 0; j < cells.length; ++j) {
  10766. var cell = cells.get(j);
  10767. var row = cell.parentNode;
  10768. if (!row || !row.parentNode) continue;
  10769. var index = cell.cellIndex;
  10770. for (var i = 0, len = table.rows.length; i < len; i++) {
  10771. var newRow = table.rows[i],
  10772. newCell = newRow.cells[index];
  10773. if (!newCell) continue;
  10774. if (newCell.colSpan > 1) {
  10775. newCell.colSpan -= 1;
  10776. if (newCell.colSpan === 1) {
  10777. K(newCell).removeAttr('colSpan');
  10778. }
  10779. } else {
  10780. newRow.deleteCell(index);
  10781. }
  10782. // 跳过不需要删除的行
  10783. if (newCell.rowSpan > 1) {
  10784. i += newCell.rowSpan - 1;
  10785. }
  10786. }
  10787. if (row.cells.length === 0) {
  10788. self.cmd.range.setStartBefore(table).collapse(true);
  10789. // self.cmd.select();
  10790. K(table).remove();
  10791. break;
  10792. }
  10793. }
  10794. if (table.parentNode) {
  10795. self.cmd.selection(true);
  10796. }
  10797. self.addBookmark();
  10798. self.focus();
  10799. },
  10800. rowdelete: function () {
  10801. var table = self.plugin.getSelectedTable()[0];
  10802. var cells = self.plugin.getAllSelectedCells();
  10803. if (!cells.length) return;
  10804. for (var j = 0; j < cells.length; ++j) {
  10805. var cell = cells.get(j);
  10806. var row = cell.parentNode;
  10807. if (!row || !row.parentNode) continue;
  10808. // 从下到上删除
  10809. for (var i = cell.rowSpan - 1; i >= 0; i--) {
  10810. table.deleteRow(row.rowIndex + i);
  10811. }
  10812. }
  10813. if (table.rows.length === 0) {
  10814. self.cmd.range.setStartBefore(table).collapse(true);
  10815. // self.cmd.select();
  10816. K(table).remove();
  10817. } else {
  10818. updateTable(null, $(table));
  10819. self.cmd.selection(true);
  10820. }
  10821. self.addBookmark();
  10822. self.focus();
  10823. }
  10824. };
  10825. self.plugin.getSelectedTable = function () {
  10826. return K($(self.cmd.range.startContainer).closest('table')[0]);
  10827. };
  10828. // 获取选中的行
  10829. self.plugin.getSelectedRow = function () {
  10830. return K($(self.cmd.range.startContainer).closest('tr')[0]);
  10831. };
  10832. // 获取光标所在的单元格
  10833. self.plugin.getSelectedCell = function () {
  10834. return K($(self.cmd.range.startContainer).closest('td,th')[0]);
  10835. };
  10836. // 获取用户拖选的单元格
  10837. self.plugin.getSelectedCells = function () {
  10838. var table = self.plugin.getSelectedTable();
  10839. if (table && table.length) {
  10840. var cells = K('.ke-select-cell', table.get(0));
  10841. if (cells && cells.length > 1) {
  10842. return cells;
  10843. }
  10844. }
  10845. };
  10846. // 当用户没有拖选多个单元格时,获取光标所在的单元格
  10847. self.plugin.getSingleSelectedCell = function () {
  10848. var selectedCells = self.plugin.getSelectedCells();
  10849. if (selectedCells && selectedCells.length > 1) {
  10850. return;
  10851. }
  10852. return self.plugin.getSelectedCell();
  10853. };
  10854. // 获取用户拖选或光标所在位置的单元格
  10855. self.plugin.getAllSelectedCells = function () {
  10856. var selectedCells = self.plugin.getSelectedCells();
  10857. if (selectedCells && selectedCells.length) {
  10858. return selectedCells;
  10859. }
  10860. return self.plugin.getSelectedCell();
  10861. };
  10862. var contextMenuIconClass = {
  10863. mergeCells: 'ke-icon-tablecolmerge'
  10864. };
  10865. K.each(('prop,cellprop,colinsertleft,colinsertright,rowinsertabove,rowinsertbelow,mergeCells,rowmerge,colmerge,rowsplit,colsplit,coldelete,rowdelete,delete').split(','), function (i, val) {
  10866. var cond;
  10867. if (val === 'prop' || val === 'delete') {
  10868. cond = self.plugin.getSelectedTable;
  10869. } else if (val === 'mergeCells') {
  10870. cond = self.plugin.getSelectedCells;
  10871. }else if (val === 'rowmerge') {
  10872. cond = function() {
  10873. var cell = self.plugin.getSingleSelectedCell();
  10874. if (cell && cell.length) {
  10875. if($(cell.get(0)).parent().next('tr').length) {
  10876. return cell;
  10877. }
  10878. }
  10879. };
  10880. } else if (val === 'colmerge') {
  10881. cond = function() {
  10882. var cell = self.plugin.getSingleSelectedCell();
  10883. if (cell && cell.length) {
  10884. if($(cell.get(0)).next('th,td').length) {
  10885. return cell;
  10886. }
  10887. }
  10888. };
  10889. } else if (val === 'rowsplit') {
  10890. cond = function() {
  10891. var cell = self.plugin.getSingleSelectedCell();
  10892. if (cell && cell.get(0).rowSpan > 1) {
  10893. return cell;
  10894. }
  10895. };
  10896. } else if (val === 'colsplit') {
  10897. cond = function() {
  10898. var cell = self.plugin.getSingleSelectedCell();
  10899. if (cell && cell.get(0).colSpan > 1) {
  10900. return cell;
  10901. }
  10902. };
  10903. } else if (K.inArray(val, ['colinsertleft', 'colinsertright', 'rowinsertabove', 'rowinsertbelow']) > -1) {
  10904. cond = self.plugin.getSingleSelectedCell;
  10905. } else {
  10906. cond = self.plugin.getSelectedCell;
  10907. }
  10908. self.addContextmenu({
  10909. title: lang[val] || self.lang('table' + val),
  10910. click: function () {
  10911. self.plugin.table[val]();
  10912. self.hideMenu();
  10913. },
  10914. cond: cond,
  10915. width: 170,
  10916. iconClass: contextMenuIconClass[val] || ('ke-icon-table' + val)
  10917. });
  10918. });
  10919. }
  10920. self.clickToolbar(name, function () {
  10921. if (self.menu) return;
  10922. var menu = self.createMenu({
  10923. name: name,
  10924. beforeRemove: function () {
  10925. removeEvent();
  10926. }
  10927. });
  10928. var $wrapperDiv = $('<div class="ke-plugin-table"></div>');
  10929. var $header = $('<div class="ke-plugin-table-header" style="padding: 0 5px;">' + lang.xRxC.format(0, 0) + '</div>');
  10930. $wrapperDiv.append($header);
  10931. var $grid = $('<div class="ke-plugin-table-grid clearfix" style="width: 230px; padding: 5px 5px 0 5px"></div>');
  10932. $grid.on('mouseenter.kTable', '.ke-plugin-table-grid-cell', function () {
  10933. var $cell = $(this);
  10934. var row = $cell.data('row');
  10935. var col = $cell.data('col');
  10936. $header.text(lang.xRxC.format(row, col));
  10937. var $cells = $grid.find('.ke-plugin-table-grid-cell');
  10938. $cells.each(function () {
  10939. var $c = $(this);
  10940. var r = $c.data('row');
  10941. var c = $c.data('col');
  10942. if (r <= row && c <= col) {
  10943. $c.css({
  10944. border: '1px solid #2286d2',
  10945. background: '#eff7ff'
  10946. });
  10947. } else {
  10948. $c.css({
  10949. border: '1px solid #ddd',
  10950. background: '#f1f1f1'
  10951. });
  10952. }
  10953. });
  10954. }).on('click.kTable', '.ke-plugin-table-grid-cell', function (e) {
  10955. var $cell = $(this);
  10956. var row = $cell.data('row');
  10957. var col = $cell.data('col');
  10958. insertTable(row, col);
  10959. self.hideMenu().focus();
  10960. self.addBookmark();
  10961. e.stopPropagation();
  10962. });
  10963. for (var r = 1; r < 11; r++) {
  10964. for (var c = 1; c < 11; c++) {
  10965. $grid.append('<div class="ke-plugin-table-grid-cell" style="float: left; width: 20px; height: 20px; margin: 1px; border: 1px solid #ddd; background: #f1f1f1;" data-row="' + r + '" data-col="' + c + '"></div>');
  10966. }
  10967. }
  10968. $elements.push($grid);
  10969. $wrapperDiv.append($grid);
  10970. menu.div.append($wrapperDiv[0]);
  10971. });
  10972. // https://zui.5upm.com/task-view-2.html
  10973. self.afterTab(function (result) {
  10974. var selectedCell = self.plugin.getSelectedCell();
  10975. if (selectedCell && selectedCell.length) {
  10976. var selectNextCell = function ($currentCell) {
  10977. if ($currentCell.length) {
  10978. var $nextCell = $currentCell.next();
  10979. if (!$nextCell.is('td,th')) {
  10980. $nextCell = $currentCell.parent().next('tr').children('th,td').first();
  10981. }
  10982. if (!$nextCell.is('td,th')) {
  10983. $nextCell = $currentCell.closest('tbody,tfoot,thead').next().children('tr').first().children('th,td').first();
  10984. }
  10985. if ($nextCell.length) {
  10986. self.cmd.range.selectNodeContents($nextCell[0]).collapse(true);
  10987. self.cmd.select();
  10988. return true;
  10989. }
  10990. }
  10991. return false;
  10992. };
  10993. var $selectedCell = $(selectedCell.get(0));
  10994. if ($selectedCell.length) {
  10995. self.focus();
  10996. if (!selectNextCell($selectedCell)) {
  10997. self.plugin.table.rowinsertbelow();
  10998. selectNextCell($selectedCell);
  10999. }
  11000. return true;
  11001. }
  11002. }
  11003. return result;
  11004. });
  11005. var selectCellsRange = function ($table, startPos, endPos) {
  11006. var top = endPos ? Math.min(startPos.top, endPos.top) : startPos.top;
  11007. var left = endPos ? Math.min(startPos.left, endPos.left) : startPos.left;
  11008. var bottom = endPos ? Math.max(startPos.bottom, endPos.bottom) : startPos.bottom;
  11009. var right = endPos ? Math.max(startPos.right, endPos.right) : startPos.right;
  11010. if (top === bottom && left === right) {
  11011. return false;
  11012. }
  11013. var hasCellSelected = false;
  11014. var hasNewCellSelect = false;
  11015. var $rows = $table.children('thead,tbody,tfoot').children('tr').each(function () {
  11016. $(this).children('td,th').each(function () {
  11017. var $cell = $(this);
  11018. var pos = $cell.cellPos();
  11019. if (pos.right >= left && pos.left <= right && pos.bottom >= top && pos.top <= bottom) {
  11020. top = Math.min(top, pos.top);
  11021. left = Math.min(left, pos.left);
  11022. bottom = Math.max(bottom, pos.bottom);
  11023. right = Math.max(right, pos.right);
  11024. $cell.addClass('ke-select-cell');
  11025. hasCellSelected = true;
  11026. hasNewCellSelect = true;
  11027. }
  11028. });
  11029. });
  11030. while(hasNewCellSelect) {
  11031. hasNewCellSelect = false;
  11032. $rows.each(function () {
  11033. $(this).children('td,th').each(function () {
  11034. var $cell = $(this);
  11035. if ($cell.hasClass('ke-select-cell')) return;
  11036. var pos = $cell.cellPos();
  11037. if (pos.right >= left && pos.left <= right && pos.bottom >= top && pos.top <= bottom) {
  11038. top = Math.min(top, pos.top);
  11039. left = Math.min(left, pos.left);
  11040. bottom = Math.max(bottom, pos.bottom);
  11041. right = Math.max(right, pos.right);
  11042. $cell.addClass('ke-select-cell');
  11043. hasNewCellSelect = true;
  11044. }
  11045. });
  11046. });
  11047. }
  11048. var $selectedCells = $table.find('.ke-select-cell');
  11049. if ($selectedCells.length === 1) {
  11050. $selectedCells.removeClass('ke-select-cell');
  11051. hasCellSelected = false;
  11052. }
  11053. if (hasCellSelected) {
  11054. self.tableSelectionRange = {
  11055. top: top,
  11056. left: left,
  11057. bottom: bottom,
  11058. right: right,
  11059. };
  11060. } else {
  11061. self.tableSelectionRange = null;
  11062. }
  11063. return hasCellSelected;
  11064. };
  11065. var selectRow = function ($table, rowIndex) {
  11066. return selectCellsRange($table, {
  11067. left: 0,
  11068. right: $table.data('tableSize').width - 1,
  11069. top: rowIndex,
  11070. bottom: rowIndex,
  11071. });
  11072. };
  11073. var selectCol = function ($table, cellIndex) {
  11074. return selectCellsRange($table, {
  11075. left: cellIndex,
  11076. right: cellIndex,
  11077. top: 0,
  11078. bottom: $table.data('tableSize').height - 1,
  11079. });
  11080. };
  11081. self.afterCreate(function () {
  11082. var isMouseDown = false;
  11083. var $mouseDownTable = null;
  11084. var $mouseMoveTable = null;
  11085. var mouseDownCellPos = null;
  11086. var mouseMoveCellPos = null;
  11087. var handleMouseUp = function () {
  11088. isMouseDown = false;
  11089. $mouseDownTable = null;
  11090. mouseMoveCellPos = null;
  11091. };
  11092. $(self.edit.doc.body).on('mousedown.ke' + self.uuid, function (e) {
  11093. var $cell = $(e.target).closest('td,th');
  11094. var $table = $cell.closest('table');
  11095. var rightClickOnTable = false;
  11096. if ($cell.length && $table.length) {
  11097. $mouseDownTable = $table;
  11098. isMouseDown = true;
  11099. mouseDownCellPos = $cell.cellPos(true);
  11100. rightClickOnTable = e.which === 3;
  11101. $table.removeClass('ke-select-cells');
  11102. }
  11103. if (!rightClickOnTable) {
  11104. $(self.edit.doc).find('.ke-select-cell').removeClass('ke-select-cell');
  11105. self.tableSelectionRange = null;
  11106. }
  11107. }).on('mousemove.ke' + self.uuid, function (e) {
  11108. var $cell = $(e.target).closest('td,th');
  11109. if (!$cell.length) return isMouseDown ? e.preventDefault() : null;
  11110. var $table = $cell.closest('table');
  11111. if (!$table.length) return isMouseDown ? e.preventDefault() : null;
  11112. $table.removeClass('ke-select-row ke-select-col ke-select-cells');
  11113. mouseMoveCellPos = $cell.cellPos();
  11114. if (isMouseDown) {
  11115. if ($table[0] !== $mouseDownTable[0]) return e.preventDefault();
  11116. $(self.edit.doc).find('table').find('.ke-select-cell').removeClass('ke-select-cell');
  11117. if (selectCellsRange($table, mouseDownCellPos, mouseMoveCellPos)) {
  11118. $table.addClass('ke-select-cells');
  11119. e.preventDefault();
  11120. }
  11121. } else {
  11122. $mouseMoveTable = $table;
  11123. var tableOffset = $table.offset();
  11124. var pageX = e.pageX;
  11125. var pageY = e.pageY;
  11126. var moveX = pageX - tableOffset.left;
  11127. var moveY = pageY - tableOffset.top;
  11128. if (moveX < 8) {
  11129. $table.addClass('ke-select-row');
  11130. mouseMoveCellPos.selectRow = mouseMoveCellPos.top;
  11131. delete mouseMoveCellPos.selectCol;
  11132. e.preventDefault();
  11133. e.stopPropagation();
  11134. } else if (moveY < 8) {
  11135. $table.addClass('ke-select-col');
  11136. mouseMoveCellPos.selectCol = mouseMoveCellPos.left;
  11137. delete mouseMoveCellPos.selectRow;
  11138. e.preventDefault();
  11139. e.stopPropagation();
  11140. }
  11141. }
  11142. }).on('mouseup.ke' + self.uuid, function (e) {
  11143. var $target = $(e.target);
  11144. var $cell = $target.closest('td,th');
  11145. if ($cell.length) {
  11146. if (mouseMoveCellPos && mouseMoveCellPos.selectRow !== undefined) {
  11147. selectRow($mouseMoveTable, mouseMoveCellPos.selectRow);
  11148. e.stopPropagation();
  11149. } else if (mouseMoveCellPos && mouseMoveCellPos.selectCol !== undefined) {
  11150. selectCol($mouseMoveTable, mouseMoveCellPos.selectCol);
  11151. e.stopPropagation();
  11152. }
  11153. }
  11154. handleMouseUp();
  11155. }).on('paste.ke' + self.uuid + ' keydown.ke' + self.uuid, function () {
  11156. $(self.edit.doc).find('table').removeClass('ke-select-row ke-select-col').find('.ke-select-cell').removeClass('ke-select-cell');
  11157. });
  11158. $(document).on('mouseup.ke' + self.uuid, function () {
  11159. handleMouseUp();
  11160. });
  11161. $(self.edit.doc.head).append([
  11162. '<style>',
  11163. '.ke-select-cells {cursor: cell}',
  11164. '.ke-select-row {cursor: e-resize; cursor: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUBAMAAAB/pwA+AAAAMFBMVEUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABaPxwLAAAAD3RSTlMAqiTk590pHjjw0cZyAjPTb5hoAAAARUlEQVQI12MgCnAowJmdbjAW7/rPcOHS/3Bh9vgvCSCaR1BQcP9/IxCT8T8IAIVhTKBGuAK4NrhppUBBTCteGqE6hzAAAHccHSlSjBVHAAAAAElFTkSuQmCC) 10 10, auto}',
  11165. '.ke-select-col {cursor: s-resize; cursor: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUBAMAAAB/pwA+AAAAJ1BMVEUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADdEvm1AAAADHRSTlMAqiPfH+Q58dPHcgLUxK6wAAAAUklEQVQI12MgCiyUgjNlDuJlcoOYG8DMDAWZgyxtIBZbjYnMQefjCUAmU8zhOSdtjiqAhJ3PAEEQWC2LzZkzIEGwMFgQKgwShApDBUGGKBDlagAGvBgJQ+z5fwAAAABJRU5ErkJggg==) 10 10, auto}',
  11166. '.ke-select-cell {outline: #b3d4fc 2px solid; outline-color: rgba(100, 150, 255, 0.7); outline-offset: -1px; position: relative}',
  11167. '.ke-select-cell:before {content: " "; position: absolute; top: 0; right: 0; bottom: 0; left: 0; background: rgba(0, 50, 255, 0.08)}',
  11168. '</style>',
  11169. ].join(''));
  11170. var cmdToggleBack = self.cmd.toggle;
  11171. var cmdToggle = function (wrapper, map, flag) {
  11172. var self = this;
  11173. if (flag === undefined || flag === null) {
  11174. flag = self.commonNode(map);
  11175. }
  11176. if (flag) {
  11177. self.remove(map);
  11178. } else {
  11179. self.wrap(wrapper);
  11180. }
  11181. return self.select();
  11182. };
  11183. var eachSelectCells = function (eachCallback, beforeCallback, afterCallback) {
  11184. var range = self.cmd.range;
  11185. if (range && range.endContainer) {
  11186. var $cell = $(range.endContainer).closest('th,td');
  11187. if (!$cell.length) return;
  11188. var $table = $cell.closest('table');
  11189. if (!$table.length) return;
  11190. var $selectCells = $table.children('thead,tbody,tfoot').children('tr').children('.ke-select-cell');
  11191. if ($selectCells.length) {
  11192. if (beforeCallback) beforeCallback($cell, $table);
  11193. $selectCells.each(eachCallback);
  11194. if (afterCallback) afterCallback($cell, $table);
  11195. range.selectNodeContents($cell[0]);
  11196. // range.collapse();
  11197. self.cmd.select();
  11198. self.focus();
  11199. return true;
  11200. }
  11201. }
  11202. };
  11203. self.cmd.toggle = function (wrapper, map) {
  11204. var flag;
  11205. if (eachSelectCells(function () {
  11206. self.cmd.range.selectNodeContents(this);
  11207. self.cmd.select();
  11208. cmdToggle.call(self.cmd, wrapper, map, flag);
  11209. }, function ($cell) {
  11210. self.cmd.range.selectNodeContents($cell[0]);
  11211. self.cmd.select();
  11212. flag = !!self.cmd.commonNode(map);
  11213. })) {
  11214. return;
  11215. }
  11216. return cmdToggleBack.call(self.cmd, wrapper, map);
  11217. };
  11218. var commands = ',justifyleft,justifycenter,justifyright,justifyfull,insertorderedlist,insertunorderedlist,';
  11219. var clickToolbarBack = self.clickToolbar;
  11220. self.clickToolbar = function (name, fn) {
  11221. if (fn === undefined && commands.indexOf(',' + name + ',') > -1) {
  11222. if (eachSelectCells(function () {
  11223. self.cmd.range.selectNode(this);
  11224. self.cmd.select();
  11225. clickToolbarBack.call(self, name, fn);
  11226. })) {
  11227. return;
  11228. }
  11229. }
  11230. return clickToolbarBack.call(self, name, fn);
  11231. }
  11232. });
  11233. self.beforeRemove(function () {
  11234. $(self.edit.doc.body).off('.ke' + self.uuid);
  11235. $(document).off('.ke' + self.uuid);
  11236. });
  11237. });
  11238. KindEditor.lang({
  11239. table: KindEditor.lang('table')
  11240. });