ueditor.all.js 1.1 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573
  1. /*!
  2. * UEditor
  3. * version: ueditor
  4. * build: Wed Aug 10 2016 11:06:16 GMT+0800 (CST)
  5. */
  6. (function(){
  7. // editor.js
  8. UEDITOR_CONFIG = window.UEDITOR_CONFIG || {};
  9. var baidu = window.baidu || {};
  10. window.baidu = baidu;
  11. window.UE = baidu.editor = window.UE || {};
  12. UE.plugins = {};
  13. UE.commands = {};
  14. UE.instants = {};
  15. UE.I18N = {};
  16. UE._customizeUI = {};
  17. UE.version = "1.4.3";
  18. var dom = UE.dom = {};
  19. // core/browser.js
  20. /**
  21. * 浏览器判断模块
  22. * @file
  23. * @module UE.browser
  24. * @since 1.2.6.1
  25. */
  26. /**
  27. * 提供浏览器检测的模块
  28. * @unfile
  29. * @module UE.browser
  30. */
  31. var browser = UE.browser = function(){
  32. var agent = navigator.userAgent.toLowerCase(),
  33. opera = window.opera,
  34. browser = {
  35. /**
  36. * @property {boolean} ie 检测当前浏览器是否为IE
  37. * @example
  38. * ```javascript
  39. * if ( UE.browser.ie ) {
  40. * console.log( '当前浏览器是IE' );
  41. * }
  42. * ```
  43. */
  44. ie : /(msie\s|trident.*rv:)([\w.]+)/.test(agent),
  45. /**
  46. * @property {boolean} opera 检测当前浏览器是否为Opera
  47. * @example
  48. * ```javascript
  49. * if ( UE.browser.opera ) {
  50. * console.log( '当前浏览器是Opera' );
  51. * }
  52. * ```
  53. */
  54. opera : ( !!opera && opera.version ),
  55. /**
  56. * @property {boolean} webkit 检测当前浏览器是否是webkit内核的浏览器
  57. * @example
  58. * ```javascript
  59. * if ( UE.browser.webkit ) {
  60. * console.log( '当前浏览器是webkit内核浏览器' );
  61. * }
  62. * ```
  63. */
  64. webkit : ( agent.indexOf( ' applewebkit/' ) > -1 ),
  65. /**
  66. * @property {boolean} mac 检测当前浏览器是否是运行在mac平台下
  67. * @example
  68. * ```javascript
  69. * if ( UE.browser.mac ) {
  70. * console.log( '当前浏览器运行在mac平台下' );
  71. * }
  72. * ```
  73. */
  74. mac : ( agent.indexOf( 'macintosh' ) > -1 ),
  75. /**
  76. * @property {boolean} quirks 检测当前浏览器是否处于“怪异模式”下
  77. * @example
  78. * ```javascript
  79. * if ( UE.browser.quirks ) {
  80. * console.log( '当前浏览器运行处于“怪异模式”' );
  81. * }
  82. * ```
  83. */
  84. quirks : ( document.compatMode == 'BackCompat' )
  85. };
  86. /**
  87. * @property {boolean} gecko 检测当前浏览器内核是否是gecko内核
  88. * @example
  89. * ```javascript
  90. * if ( UE.browser.gecko ) {
  91. * console.log( '当前浏览器内核是gecko内核' );
  92. * }
  93. * ```
  94. */
  95. browser.gecko =( navigator.product == 'Gecko' && !browser.webkit && !browser.opera && !browser.ie);
  96. var version = 0;
  97. // Internet Explorer 6.0+
  98. if ( browser.ie ){
  99. var v1 = agent.match(/(?:msie\s([\w.]+))/);
  100. var v2 = agent.match(/(?:trident.*rv:([\w.]+))/);
  101. if(v1 && v2 && v1[1] && v2[1]){
  102. version = Math.max(v1[1]*1,v2[1]*1);
  103. }else if(v1 && v1[1]){
  104. version = v1[1]*1;
  105. }else if(v2 && v2[1]){
  106. version = v2[1]*1;
  107. }else{
  108. version = 0;
  109. }
  110. browser.ie11Compat = document.documentMode == 11;
  111. /**
  112. * @property { boolean } ie9Compat 检测浏览器模式是否为 IE9 兼容模式
  113. * @warning 如果浏览器不是IE, 则该值为undefined
  114. * @example
  115. * ```javascript
  116. * if ( UE.browser.ie9Compat ) {
  117. * console.log( '当前浏览器运行在IE9兼容模式下' );
  118. * }
  119. * ```
  120. */
  121. browser.ie9Compat = document.documentMode == 9;
  122. /**
  123. * @property { boolean } ie8 检测浏览器是否是IE8浏览器
  124. * @warning 如果浏览器不是IE, 则该值为undefined
  125. * @example
  126. * ```javascript
  127. * if ( UE.browser.ie8 ) {
  128. * console.log( '当前浏览器是IE8浏览器' );
  129. * }
  130. * ```
  131. */
  132. browser.ie8 = !!document.documentMode;
  133. /**
  134. * @property { boolean } ie8Compat 检测浏览器模式是否为 IE8 兼容模式
  135. * @warning 如果浏览器不是IE, 则该值为undefined
  136. * @example
  137. * ```javascript
  138. * if ( UE.browser.ie8Compat ) {
  139. * console.log( '当前浏览器运行在IE8兼容模式下' );
  140. * }
  141. * ```
  142. */
  143. browser.ie8Compat = document.documentMode == 8;
  144. /**
  145. * @property { boolean } ie7Compat 检测浏览器模式是否为 IE7 兼容模式
  146. * @warning 如果浏览器不是IE, 则该值为undefined
  147. * @example
  148. * ```javascript
  149. * if ( UE.browser.ie7Compat ) {
  150. * console.log( '当前浏览器运行在IE7兼容模式下' );
  151. * }
  152. * ```
  153. */
  154. browser.ie7Compat = ( ( version == 7 && !document.documentMode )
  155. || document.documentMode == 7 );
  156. /**
  157. * @property { boolean } ie6Compat 检测浏览器模式是否为 IE6 模式 或者怪异模式
  158. * @warning 如果浏览器不是IE, 则该值为undefined
  159. * @example
  160. * ```javascript
  161. * if ( UE.browser.ie6Compat ) {
  162. * console.log( '当前浏览器运行在IE6模式或者怪异模式下' );
  163. * }
  164. * ```
  165. */
  166. browser.ie6Compat = ( version < 7 || browser.quirks );
  167. browser.ie9above = version > 8;
  168. browser.ie9below = version < 9;
  169. browser.ie11above = version > 10;
  170. browser.ie11below = version < 11;
  171. }
  172. // Gecko.
  173. if ( browser.gecko ){
  174. var geckoRelease = agent.match( /rv:([\d\.]+)/ );
  175. if ( geckoRelease )
  176. {
  177. geckoRelease = geckoRelease[1].split( '.' );
  178. version = geckoRelease[0] * 10000 + ( geckoRelease[1] || 0 ) * 100 + ( geckoRelease[2] || 0 ) * 1;
  179. }
  180. }
  181. /**
  182. * @property { Number } chrome 检测当前浏览器是否为Chrome, 如果是,则返回Chrome的大版本号
  183. * @warning 如果浏览器不是chrome, 则该值为undefined
  184. * @example
  185. * ```javascript
  186. * if ( UE.browser.chrome ) {
  187. * console.log( '当前浏览器是Chrome' );
  188. * }
  189. * ```
  190. */
  191. if (/chrome\/(\d+\.\d)/i.test(agent)) {
  192. browser.chrome = + RegExp['\x241'];
  193. }
  194. /**
  195. * @property { Number } safari 检测当前浏览器是否为Safari, 如果是,则返回Safari的大版本号
  196. * @warning 如果浏览器不是safari, 则该值为undefined
  197. * @example
  198. * ```javascript
  199. * if ( UE.browser.safari ) {
  200. * console.log( '当前浏览器是Safari' );
  201. * }
  202. * ```
  203. */
  204. if(/(\d+\.\d)?(?:\.\d)?\s+safari\/?(\d+\.\d+)?/i.test(agent) && !/chrome/i.test(agent)){
  205. browser.safari = + (RegExp['\x241'] || RegExp['\x242']);
  206. }
  207. // Opera 9.50+
  208. if ( browser.opera )
  209. version = parseFloat( opera.version() );
  210. // WebKit 522+ (Safari 3+)
  211. if ( browser.webkit )
  212. version = parseFloat( agent.match( / applewebkit\/(\d+)/ )[1] );
  213. /**
  214. * @property { Number } version 检测当前浏览器版本号
  215. * @remind
  216. * <ul>
  217. * <li>IE系列返回值为5,6,7,8,9,10等</li>
  218. * <li>gecko系列会返回10900,158900等</li>
  219. * <li>webkit系列会返回其build号 (如 522等)</li>
  220. * </ul>
  221. * @example
  222. * ```javascript
  223. * console.log( '当前浏览器版本号是: ' + UE.browser.version );
  224. * ```
  225. */
  226. browser.version = version;
  227. /**
  228. * @property { boolean } isCompatible 检测当前浏览器是否能够与UEditor良好兼容
  229. * @example
  230. * ```javascript
  231. * if ( UE.browser.isCompatible ) {
  232. * console.log( '浏览器与UEditor能够良好兼容' );
  233. * }
  234. * ```
  235. */
  236. browser.isCompatible =
  237. !browser.mobile && (
  238. ( browser.ie && version >= 6 ) ||
  239. ( browser.gecko && version >= 10801 ) ||
  240. ( browser.opera && version >= 9.5 ) ||
  241. ( browser.air && version >= 1 ) ||
  242. ( browser.webkit && version >= 522 ) ||
  243. false );
  244. return browser;
  245. }();
  246. //快捷方式
  247. var ie = browser.ie,
  248. webkit = browser.webkit,
  249. gecko = browser.gecko,
  250. opera = browser.opera;
  251. // core/utils.js
  252. /**
  253. * 工具函数包
  254. * @file
  255. * @module UE.utils
  256. * @since 1.2.6.1
  257. */
  258. /**
  259. * UEditor封装使用的静态工具函数
  260. * @module UE.utils
  261. * @unfile
  262. */
  263. var utils = UE.utils = {
  264. /**
  265. * 用给定的迭代器遍历对象
  266. * @method each
  267. * @param { Object } obj 需要遍历的对象
  268. * @param { Function } iterator 迭代器, 该方法接受两个参数, 第一个参数是当前所处理的value, 第二个参数是当前遍历对象的key
  269. * @example
  270. * ```javascript
  271. * var demoObj = {
  272. * key1: 1,
  273. * key2: 2
  274. * };
  275. *
  276. * //output: key1: 1, key2: 2
  277. * UE.utils.each( demoObj, funciton ( value, key ) {
  278. *
  279. * console.log( key + ":" + value );
  280. *
  281. * } );
  282. * ```
  283. */
  284. /**
  285. * 用给定的迭代器遍历数组或类数组对象
  286. * @method each
  287. * @param { Array } array 需要遍历的数组或者类数组
  288. * @param { Function } iterator 迭代器, 该方法接受两个参数, 第一个参数是当前所处理的value, 第二个参数是当前遍历对象的key
  289. * @example
  290. * ```javascript
  291. * var divs = document.getElmentByTagNames( "div" );
  292. *
  293. * //output: 0: DIV, 1: DIV ...
  294. * UE.utils.each( divs, funciton ( value, key ) {
  295. *
  296. * console.log( key + ":" + value.tagName );
  297. *
  298. * } );
  299. * ```
  300. */
  301. each : function(obj, iterator, context) {
  302. if (obj == null) return;
  303. if (obj.length === +obj.length) {
  304. for (var i = 0, l = obj.length; i < l; i++) {
  305. if(iterator.call(context, obj[i], i, obj) === false)
  306. return false;
  307. }
  308. } else {
  309. for (var key in obj) {
  310. if (obj.hasOwnProperty(key)) {
  311. if(iterator.call(context, obj[key], key, obj) === false)
  312. return false;
  313. }
  314. }
  315. }
  316. },
  317. /**
  318. * 以给定对象作为原型创建一个新对象
  319. * @method makeInstance
  320. * @param { Object } protoObject 该对象将作为新创建对象的原型
  321. * @return { Object } 新的对象, 该对象的原型是给定的protoObject对象
  322. * @example
  323. * ```javascript
  324. *
  325. * var protoObject = { sayHello: function () { console.log('Hello UEditor!'); } };
  326. *
  327. * var newObject = UE.utils.makeInstance( protoObject );
  328. * //output: Hello UEditor!
  329. * newObject.sayHello();
  330. * ```
  331. */
  332. makeInstance:function (obj) {
  333. var noop = new Function();
  334. noop.prototype = obj;
  335. obj = new noop;
  336. noop.prototype = null;
  337. return obj;
  338. },
  339. /**
  340. * 将source对象中的属性扩展到target对象上
  341. * @method extend
  342. * @remind 该方法将强制把source对象上的属性复制到target对象上
  343. * @see UE.utils.extend(Object,Object,Boolean)
  344. * @param { Object } target 目标对象, 新的属性将附加到该对象上
  345. * @param { Object } source 源对象, 该对象的属性会被附加到target对象上
  346. * @return { Object } 返回target对象
  347. * @example
  348. * ```javascript
  349. *
  350. * var target = { name: 'target', sex: 1 },
  351. * source = { name: 'source', age: 17 };
  352. *
  353. * UE.utils.extend( target, source );
  354. *
  355. * //output: { name: 'source', sex: 1, age: 17 }
  356. * console.log( target );
  357. *
  358. * ```
  359. */
  360. /**
  361. * 将source对象中的属性扩展到target对象上, 根据指定的isKeepTarget值决定是否保留目标对象中与
  362. * 源对象属性名相同的属性值。
  363. * @method extend
  364. * @param { Object } target 目标对象, 新的属性将附加到该对象上
  365. * @param { Object } source 源对象, 该对象的属性会被附加到target对象上
  366. * @param { Boolean } isKeepTarget 是否保留目标对象中与源对象中属性名相同的属性
  367. * @return { Object } 返回target对象
  368. * @example
  369. * ```javascript
  370. *
  371. * var target = { name: 'target', sex: 1 },
  372. * source = { name: 'source', age: 17 };
  373. *
  374. * UE.utils.extend( target, source, true );
  375. *
  376. * //output: { name: 'target', sex: 1, age: 17 }
  377. * console.log( target );
  378. *
  379. * ```
  380. */
  381. extend:function (t, s, b) {
  382. if (s) {
  383. for (var k in s) {
  384. if (!b || !t.hasOwnProperty(k)) {
  385. t[k] = s[k];
  386. }
  387. }
  388. }
  389. return t;
  390. },
  391. /**
  392. * 将给定的多个对象的属性复制到目标对象target上
  393. * @method extend2
  394. * @remind 该方法将强制把源对象上的属性复制到target对象上
  395. * @remind 该方法支持两个及以上的参数, 从第二个参数开始, 其属性都会被复制到第一个参数上。 如果遇到同名的属性,
  396. * 将会覆盖掉之前的值。
  397. * @param { Object } target 目标对象, 新的属性将附加到该对象上
  398. * @param { Object... } source 源对象, 支持多个对象, 该对象的属性会被附加到target对象上
  399. * @return { Object } 返回target对象
  400. * @example
  401. * ```javascript
  402. *
  403. * var target = {},
  404. * source1 = { name: 'source', age: 17 },
  405. * source2 = { title: 'dev' };
  406. *
  407. * UE.utils.extend2( target, source1, source2 );
  408. *
  409. * //output: { name: 'source', age: 17, title: 'dev' }
  410. * console.log( target );
  411. *
  412. * ```
  413. */
  414. extend2:function (t) {
  415. var a = arguments;
  416. for (var i = 1; i < a.length; i++) {
  417. var x = a[i];
  418. for (var k in x) {
  419. if (!t.hasOwnProperty(k)) {
  420. t[k] = x[k];
  421. }
  422. }
  423. }
  424. return t;
  425. },
  426. /**
  427. * 模拟继承机制, 使得subClass继承自superClass
  428. * @method inherits
  429. * @param { Object } subClass 子类对象
  430. * @param { Object } superClass 超类对象
  431. * @warning 该方法只能让subClass继承超类的原型, subClass对象自身的属性和方法不会被继承
  432. * @return { Object } 继承superClass后的子类对象
  433. * @example
  434. * ```javascript
  435. * function SuperClass(){
  436. * this.name = "小李";
  437. * }
  438. *
  439. * SuperClass.prototype = {
  440. * hello:function(str){
  441. * console.log(this.name + str);
  442. * }
  443. * }
  444. *
  445. * function SubClass(){
  446. * this.name = "小张";
  447. * }
  448. *
  449. * UE.utils.inherits(SubClass,SuperClass);
  450. *
  451. * var sub = new SubClass();
  452. * //output: '小张早上好!
  453. * sub.hello("早上好!");
  454. * ```
  455. */
  456. inherits:function (subClass, superClass) {
  457. var oldP = subClass.prototype,
  458. newP = utils.makeInstance(superClass.prototype);
  459. utils.extend(newP, oldP, true);
  460. subClass.prototype = newP;
  461. return (newP.constructor = subClass);
  462. },
  463. /**
  464. * 用指定的context对象作为函数fn的上下文
  465. * @method bind
  466. * @param { Function } fn 需要绑定上下文的函数对象
  467. * @param { Object } content 函数fn新的上下文对象
  468. * @return { Function } 一个新的函数, 该函数作为原始函数fn的代理, 将完成fn的上下文调换工作。
  469. * @example
  470. * ```javascript
  471. *
  472. * var name = 'window',
  473. * newTest = null;
  474. *
  475. * function test () {
  476. * console.log( this.name );
  477. * }
  478. *
  479. * newTest = UE.utils.bind( test, { name: 'object' } );
  480. *
  481. * //output: object
  482. * newTest();
  483. *
  484. * //output: window
  485. * test();
  486. *
  487. * ```
  488. */
  489. bind:function (fn, context) {
  490. return function () {
  491. return fn.apply(context, arguments);
  492. };
  493. },
  494. /**
  495. * 创建延迟指定时间后执行的函数fn
  496. * @method defer
  497. * @param { Function } fn 需要延迟执行的函数对象
  498. * @param { int } delay 延迟的时间, 单位是毫秒
  499. * @warning 该方法的时间控制是不精确的,仅仅只能保证函数的执行是在给定的时间之后,
  500. * 而不能保证刚好到达延迟时间时执行。
  501. * @return { Function } 目标函数fn的代理函数, 只有执行该函数才能起到延时效果
  502. * @example
  503. * ```javascript
  504. * var start = 0;
  505. *
  506. * function test(){
  507. * console.log( new Date() - start );
  508. * }
  509. *
  510. * var testDefer = UE.utils.defer( test, 1000 );
  511. * //
  512. * start = new Date();
  513. * //output: (大约在1000毫秒之后输出) 1000
  514. * testDefer();
  515. * ```
  516. */
  517. /**
  518. * 创建延迟指定时间后执行的函数fn, 如果在延迟时间内再次执行该方法, 将会根据指定的exclusion的值,
  519. * 决定是否取消前一次函数的执行, 如果exclusion的值为true, 则取消执行,反之,将继续执行前一个方法。
  520. * @method defer
  521. * @param { Function } fn 需要延迟执行的函数对象
  522. * @param { int } delay 延迟的时间, 单位是毫秒
  523. * @param { Boolean } exclusion 如果在延迟时间内再次执行该函数,该值将决定是否取消执行前一次函数的执行,
  524. * 值为true表示取消执行, 反之则将在执行前一次函数之后才执行本次函数调用。
  525. * @warning 该方法的时间控制是不精确的,仅仅只能保证函数的执行是在给定的时间之后,
  526. * 而不能保证刚好到达延迟时间时执行。
  527. * @return { Function } 目标函数fn的代理函数, 只有执行该函数才能起到延时效果
  528. * @example
  529. * ```javascript
  530. *
  531. * function test(){
  532. * console.log(1);
  533. * }
  534. *
  535. * var testDefer = UE.utils.defer( test, 1000, true );
  536. *
  537. * //output: (两次调用仅有一次输出) 1
  538. * testDefer();
  539. * testDefer();
  540. * ```
  541. */
  542. defer:function (fn, delay, exclusion) {
  543. var timerID;
  544. return function () {
  545. if (exclusion) {
  546. clearTimeout(timerID);
  547. }
  548. timerID = setTimeout(fn, delay);
  549. };
  550. },
  551. /**
  552. * 获取元素item在数组array中首次出现的位置, 如果未找到item, 则返回-1
  553. * @method indexOf
  554. * @remind 该方法的匹配过程使用的是恒等“===”
  555. * @param { Array } array 需要查找的数组对象
  556. * @param { * } item 需要在目标数组中查找的值
  557. * @return { int } 返回item在目标数组array中首次出现的位置, 如果在数组中未找到item, 则返回-1
  558. * @example
  559. * ```javascript
  560. * var item = 1,
  561. * arr = [ 3, 4, 6, 8, 1, 1, 2 ];
  562. *
  563. * //output: 4
  564. * console.log( UE.utils.indexOf( arr, item ) );
  565. * ```
  566. */
  567. /**
  568. * 获取元素item数组array中首次出现的位置, 如果未找到item, 则返回-1。通过start的值可以指定搜索的起始位置。
  569. * @method indexOf
  570. * @remind 该方法的匹配过程使用的是恒等“===”
  571. * @param { Array } array 需要查找的数组对象
  572. * @param { * } item 需要在目标数组中查找的值
  573. * @param { int } start 搜索的起始位置
  574. * @return { int } 返回item在目标数组array中的start位置之后首次出现的位置, 如果在数组中未找到item, 则返回-1
  575. * @example
  576. * ```javascript
  577. * var item = 1,
  578. * arr = [ 3, 4, 6, 8, 1, 2, 8, 3, 2, 1, 1, 4 ];
  579. *
  580. * //output: 9
  581. * console.log( UE.utils.indexOf( arr, item, 5 ) );
  582. * ```
  583. */
  584. indexOf:function (array, item, start) {
  585. var index = -1;
  586. start = this.isNumber(start) ? start : 0;
  587. this.each(array, function (v, i) {
  588. if (i >= start && v === item) {
  589. index = i;
  590. return false;
  591. }
  592. });
  593. return index;
  594. },
  595. /**
  596. * 移除数组array中所有的元素item
  597. * @method removeItem
  598. * @param { Array } array 要移除元素的目标数组
  599. * @param { * } item 将要被移除的元素
  600. * @remind 该方法的匹配过程使用的是恒等“===”
  601. * @example
  602. * ```javascript
  603. * var arr = [ 4, 5, 7, 1, 3, 4, 6 ];
  604. *
  605. * UE.utils.removeItem( arr, 4 );
  606. * //output: [ 5, 7, 1, 3, 6 ]
  607. * console.log( arr );
  608. *
  609. * ```
  610. */
  611. removeItem:function (array, item) {
  612. for (var i = 0, l = array.length; i < l; i++) {
  613. if (array[i] === item) {
  614. array.splice(i, 1);
  615. i--;
  616. }
  617. }
  618. },
  619. /**
  620. * 删除字符串str的首尾空格
  621. * @method trim
  622. * @param { String } str 需要删除首尾空格的字符串
  623. * @return { String } 删除了首尾的空格后的字符串
  624. * @example
  625. * ```javascript
  626. *
  627. * var str = " UEdtior ";
  628. *
  629. * //output: 9
  630. * console.log( str.length );
  631. *
  632. * //output: 7
  633. * console.log( UE.utils.trim( " UEdtior " ).length );
  634. *
  635. * //output: 9
  636. * console.log( str.length );
  637. *
  638. * ```
  639. */
  640. trim:function (str) {
  641. return str.replace(/(^[ \t\n\r]+)|([ \t\n\r]+$)/g, '');
  642. },
  643. /**
  644. * 将字符串str以','分隔成数组后,将该数组转换成哈希对象, 其生成的hash对象的key为数组中的元素, value为1
  645. * @method listToMap
  646. * @warning 该方法在生成的hash对象中,会为每一个key同时生成一个另一个全大写的key。
  647. * @param { String } str 该字符串将被以','分割为数组, 然后进行转化
  648. * @return { Object } 转化之后的hash对象
  649. * @example
  650. * ```javascript
  651. *
  652. * //output: Object {UEdtior: 1, UEDTIOR: 1, Hello: 1, HELLO: 1}
  653. * console.log( UE.utils.listToMap( 'UEdtior,Hello' ) );
  654. *
  655. * ```
  656. */
  657. /**
  658. * 将字符串数组转换成哈希对象, 其生成的hash对象的key为数组中的元素, value为1
  659. * @method listToMap
  660. * @warning 该方法在生成的hash对象中,会为每一个key同时生成一个另一个全大写的key。
  661. * @param { Array } arr 字符串数组
  662. * @return { Object } 转化之后的hash对象
  663. * @example
  664. * ```javascript
  665. *
  666. * //output: Object {UEdtior: 1, UEDTIOR: 1, Hello: 1, HELLO: 1}
  667. * console.log( UE.utils.listToMap( [ 'UEdtior', 'Hello' ] ) );
  668. *
  669. * ```
  670. */
  671. listToMap:function (list) {
  672. if (!list)return {};
  673. list = utils.isArray(list) ? list : list.split(',');
  674. for (var i = 0, ci, obj = {}; ci = list[i++];) {
  675. obj[ci.toUpperCase()] = obj[ci] = 1;
  676. }
  677. return obj;
  678. },
  679. /**
  680. * 将str中的html符号转义,将转义“',&,<,",>”五个字符
  681. * @method unhtml
  682. * @param { String } str 需要转义的字符串
  683. * @return { String } 转义后的字符串
  684. * @example
  685. * ```javascript
  686. * var html = '<body>&</body>';
  687. *
  688. * //output: &lt;body&gt;&amp;&lt;/body&gt;
  689. * console.log( UE.utils.unhtml( html ) );
  690. *
  691. * ```
  692. */
  693. unhtml:function (str, reg) {
  694. return str ? str.replace(reg || /[&<">'](?:(amp|lt|quot|gt|#39|nbsp|#\d+);)?/g, function (a, b) {
  695. if (b) {
  696. return a;
  697. } else {
  698. return {
  699. '<':'&lt;',
  700. '&':'&amp;',
  701. '"':'&quot;',
  702. '>':'&gt;',
  703. "'":'&#39;'
  704. }[a]
  705. }
  706. }) : '';
  707. },
  708. /**
  709. * 将url中的html字符转义, 仅转义 ', ", <, > 四个字符
  710. * @param { String } str 需要转义的字符串
  711. * @param { RegExp } reg 自定义的正则
  712. * @return { String } 转义后的字符串
  713. */
  714. unhtmlForUrl:function (str, reg) {
  715. return str ? str.replace(reg || /[<">']/g, function (a) {
  716. return {
  717. '<':'&lt;',
  718. '&':'&amp;',
  719. '"':'&quot;',
  720. '>':'&gt;',
  721. "'":'&#39;'
  722. }[a]
  723. }) : '';
  724. },
  725. /**
  726. * 将str中的转义字符还原成html字符
  727. * @see UE.utils.unhtml(String);
  728. * @method html
  729. * @param { String } str 需要逆转义的字符串
  730. * @return { String } 逆转义后的字符串
  731. * @example
  732. * ```javascript
  733. *
  734. * var str = '&lt;body&gt;&amp;&lt;/body&gt;';
  735. *
  736. * //output: <body>&</body>
  737. * console.log( UE.utils.html( str ) );
  738. *
  739. * ```
  740. */
  741. html:function (str) {
  742. return str ? str.replace(/&((g|l|quo)t|amp|#39|nbsp);/g, function (m) {
  743. return {
  744. '&lt;':'<',
  745. '&amp;':'&',
  746. '&quot;':'"',
  747. '&gt;':'>',
  748. '&#39;':"'",
  749. '&nbsp;':' '
  750. }[m]
  751. }) : '';
  752. },
  753. /**
  754. * 将css样式转换为驼峰的形式
  755. * @method cssStyleToDomStyle
  756. * @param { String } cssName 需要转换的css样式名
  757. * @return { String } 转换成驼峰形式后的css样式名
  758. * @example
  759. * ```javascript
  760. *
  761. * var str = 'border-top';
  762. *
  763. * //output: borderTop
  764. * console.log( UE.utils.cssStyleToDomStyle( str ) );
  765. *
  766. * ```
  767. */
  768. cssStyleToDomStyle:function () {
  769. var test = document.createElement('div').style,
  770. cache = {
  771. 'float':test.cssFloat != undefined ? 'cssFloat' : test.styleFloat != undefined ? 'styleFloat' : 'float'
  772. };
  773. return function (cssName) {
  774. return cache[cssName] || (cache[cssName] = cssName.toLowerCase().replace(/-./g, function (match) {
  775. return match.charAt(1).toUpperCase();
  776. }));
  777. };
  778. }(),
  779. /**
  780. * 动态加载文件到doc中
  781. * @method loadFile
  782. * @param { DomDocument } document 需要加载资源文件的文档对象
  783. * @param { Object } options 加载资源文件的属性集合, 取值请参考代码示例
  784. * @example
  785. * ```javascript
  786. *
  787. * UE.utils.loadFile( document, {
  788. * src:"test.js",
  789. * tag:"script",
  790. * type:"text/javascript",
  791. * defer:"defer"
  792. * } );
  793. *
  794. * ```
  795. */
  796. /**
  797. * 动态加载文件到doc中,加载成功后执行的回调函数fn
  798. * @method loadFile
  799. * @param { DomDocument } document 需要加载资源文件的文档对象
  800. * @param { Object } options 加载资源文件的属性集合, 该集合支持的值是script标签和style标签支持的所有属性。
  801. * @param { Function } fn 资源文件加载成功之后执行的回调
  802. * @warning 对于在同一个文档中多次加载同一URL的文件, 该方法会在第一次加载之后缓存该请求,
  803. * 在此之后的所有同一URL的请求, 将会直接触发回调。
  804. * @example
  805. * ```javascript
  806. *
  807. * UE.utils.loadFile( document, {
  808. * src:"test.js",
  809. * tag:"script",
  810. * type:"text/javascript",
  811. * defer:"defer"
  812. * }, function () {
  813. * console.log('加载成功');
  814. * } );
  815. *
  816. * ```
  817. */
  818. loadFile:function () {
  819. var tmpList = [];
  820. function getItem(doc, obj) {
  821. try {
  822. for (var i = 0, ci; ci = tmpList[i++];) {
  823. if (ci.doc === doc && ci.url == (obj.src || obj.href)) {
  824. return ci;
  825. }
  826. }
  827. } catch (e) {
  828. return null;
  829. }
  830. }
  831. return function (doc, obj, fn) {
  832. var item = getItem(doc, obj);
  833. if (item) {
  834. if (item.ready) {
  835. fn && fn();
  836. } else {
  837. item.funs.push(fn)
  838. }
  839. return;
  840. }
  841. tmpList.push({
  842. doc:doc,
  843. url:obj.src || obj.href,
  844. funs:[fn]
  845. });
  846. if (!doc.body) {
  847. var html = [];
  848. for (var p in obj) {
  849. if (p == 'tag')continue;
  850. html.push(p + '="' + obj[p] + '"')
  851. }
  852. doc.write('<' + obj.tag + ' ' + html.join(' ') + ' ></' + obj.tag + '>');
  853. return;
  854. }
  855. if (obj.id && doc.getElementById(obj.id)) {
  856. return;
  857. }
  858. var element = doc.createElement(obj.tag);
  859. delete obj.tag;
  860. for (var p in obj) {
  861. element.setAttribute(p, obj[p]);
  862. }
  863. element.onload = element.onreadystatechange = function () {
  864. if (!this.readyState || /loaded|complete/.test(this.readyState)) {
  865. item = getItem(doc, obj);
  866. if (item.funs.length > 0) {
  867. item.ready = 1;
  868. for (var fi; fi = item.funs.pop();) {
  869. fi();
  870. }
  871. }
  872. element.onload = element.onreadystatechange = null;
  873. }
  874. };
  875. element.onerror = function () {
  876. throw Error('The load ' + (obj.href || obj.src) + ' fails,check the url settings of file ueditor.config.js ')
  877. };
  878. doc.getElementsByTagName("head")[0].appendChild(element);
  879. }
  880. }(),
  881. /**
  882. * 判断obj对象是否为空
  883. * @method isEmptyObject
  884. * @param { * } obj 需要判断的对象
  885. * @remind 如果判断的对象是NULL, 将直接返回true, 如果是数组且为空, 返回true, 如果是字符串, 且字符串为空,
  886. * 返回true, 如果是普通对象, 且该对象没有任何实例属性, 返回true
  887. * @return { Boolean } 对象是否为空
  888. * @example
  889. * ```javascript
  890. *
  891. * //output: true
  892. * console.log( UE.utils.isEmptyObject( {} ) );
  893. *
  894. * //output: true
  895. * console.log( UE.utils.isEmptyObject( [] ) );
  896. *
  897. * //output: true
  898. * console.log( UE.utils.isEmptyObject( "" ) );
  899. *
  900. * //output: false
  901. * console.log( UE.utils.isEmptyObject( { key: 1 } ) );
  902. *
  903. * //output: false
  904. * console.log( UE.utils.isEmptyObject( [1] ) );
  905. *
  906. * //output: false
  907. * console.log( UE.utils.isEmptyObject( "1" ) );
  908. *
  909. * ```
  910. */
  911. isEmptyObject:function (obj) {
  912. if (obj == null) return true;
  913. if (this.isArray(obj) || this.isString(obj)) return obj.length === 0;
  914. for (var key in obj) if (obj.hasOwnProperty(key)) return false;
  915. return true;
  916. },
  917. /**
  918. * 把rgb格式的颜色值转换成16进制格式
  919. * @method fixColor
  920. * @param { String } rgb格式的颜色值
  921. * @param { String }
  922. * @example
  923. * rgb(255,255,255) => "#ffffff"
  924. */
  925. fixColor:function (name, value) {
  926. if (/color/i.test(name) && /rgba?/.test(value)) {
  927. var array = value.split(",");
  928. if (array.length > 3)
  929. return "";
  930. value = "#";
  931. for (var i = 0, color; color = array[i++];) {
  932. color = parseInt(color.replace(/[^\d]/gi, ''), 10).toString(16);
  933. value += color.length == 1 ? "0" + color : color;
  934. }
  935. value = value.toUpperCase();
  936. }
  937. return value;
  938. },
  939. /**
  940. * 只针对border,padding,margin做了处理,因为性能问题
  941. * @public
  942. * @function
  943. * @param {String} val style字符串
  944. */
  945. optCss:function (val) {
  946. var padding, margin, border;
  947. val = val.replace(/(padding|margin|border)\-([^:]+):([^;]+);?/gi, function (str, key, name, val) {
  948. if (val.split(' ').length == 1) {
  949. switch (key) {
  950. case 'padding':
  951. !padding && (padding = {});
  952. padding[name] = val;
  953. return '';
  954. case 'margin':
  955. !margin && (margin = {});
  956. margin[name] = val;
  957. return '';
  958. case 'border':
  959. return val == 'initial' ? '' : str;
  960. }
  961. }
  962. return str;
  963. });
  964. function opt(obj, name) {
  965. if (!obj) {
  966. return '';
  967. }
  968. var t = obj.top , b = obj.bottom, l = obj.left, r = obj.right, val = '';
  969. if (!t || !l || !b || !r) {
  970. for (var p in obj) {
  971. val += ';' + name + '-' + p + ':' + obj[p] + ';';
  972. }
  973. } else {
  974. val += ';' + name + ':' +
  975. (t == b && b == l && l == r ? t :
  976. t == b && l == r ? (t + ' ' + l) :
  977. l == r ? (t + ' ' + l + ' ' + b) : (t + ' ' + r + ' ' + b + ' ' + l)) + ';'
  978. }
  979. return val;
  980. }
  981. val += opt(padding, 'padding') + opt(margin, 'margin');
  982. return val.replace(/^[ \n\r\t;]*|[ \n\r\t]*$/, '').replace(/;([ \n\r\t]+)|\1;/g, ';')
  983. .replace(/(&((l|g)t|quot|#39))?;{2,}/g, function (a, b) {
  984. return b ? b + ";;" : ';'
  985. });
  986. },
  987. /**
  988. * 克隆对象
  989. * @method clone
  990. * @param { Object } source 源对象
  991. * @return { Object } source的一个副本
  992. */
  993. /**
  994. * 深度克隆对象,将source的属性克隆到target对象, 会覆盖target重名的属性。
  995. * @method clone
  996. * @param { Object } source 源对象
  997. * @param { Object } target 目标对象
  998. * @return { Object } 附加了source对象所有属性的target对象
  999. */
  1000. clone:function (source, target) {
  1001. var tmp;
  1002. target = target || {};
  1003. for (var i in source) {
  1004. if (source.hasOwnProperty(i)) {
  1005. tmp = source[i];
  1006. if (typeof tmp == 'object') {
  1007. target[i] = utils.isArray(tmp) ? [] : {};
  1008. utils.clone(source[i], target[i])
  1009. } else {
  1010. target[i] = tmp;
  1011. }
  1012. }
  1013. }
  1014. return target;
  1015. },
  1016. /**
  1017. * 把cm/pt为单位的值转换为px为单位的值
  1018. * @method transUnitToPx
  1019. * @param { String } 待转换的带单位的字符串
  1020. * @return { String } 转换为px为计量单位的值的字符串
  1021. * @example
  1022. * ```javascript
  1023. *
  1024. * //output: 500px
  1025. * console.log( UE.utils.transUnitToPx( '20cm' ) );
  1026. *
  1027. * //output: 27px
  1028. * console.log( UE.utils.transUnitToPx( '20pt' ) );
  1029. *
  1030. * ```
  1031. */
  1032. transUnitToPx:function (val) {
  1033. if (!/(pt|cm)/.test(val)) {
  1034. return val
  1035. }
  1036. var unit;
  1037. val.replace(/([\d.]+)(\w+)/, function (str, v, u) {
  1038. val = v;
  1039. unit = u;
  1040. });
  1041. switch (unit) {
  1042. case 'cm':
  1043. val = parseFloat(val) * 25;
  1044. break;
  1045. case 'pt':
  1046. val = Math.round(parseFloat(val) * 96 / 72);
  1047. }
  1048. return val + (val ? 'px' : '');
  1049. },
  1050. /**
  1051. * 在dom树ready之后执行给定的回调函数
  1052. * @method domReady
  1053. * @remind 如果在执行该方法的时候, dom树已经ready, 那么回调函数将立刻执行
  1054. * @param { Function } fn dom树ready之后的回调函数
  1055. * @example
  1056. * ```javascript
  1057. *
  1058. * UE.utils.domReady( function () {
  1059. *
  1060. * console.log('123');
  1061. *
  1062. * } );
  1063. *
  1064. * ```
  1065. */
  1066. domReady:function () {
  1067. var fnArr = [];
  1068. function doReady(doc) {
  1069. //确保onready只执行一次
  1070. doc.isReady = true;
  1071. for (var ci; ci = fnArr.pop(); ci()) {
  1072. }
  1073. }
  1074. return function (onready, win) {
  1075. win = win || window;
  1076. var doc = win.document;
  1077. onready && fnArr.push(onready);
  1078. if (doc.readyState === "complete") {
  1079. doReady(doc);
  1080. } else {
  1081. doc.isReady && doReady(doc);
  1082. if (browser.ie && browser.version != 11) {
  1083. (function () {
  1084. if (doc.isReady) return;
  1085. try {
  1086. doc.documentElement.doScroll("left");
  1087. } catch (error) {
  1088. setTimeout(arguments.callee, 0);
  1089. return;
  1090. }
  1091. doReady(doc);
  1092. })();
  1093. win.attachEvent('onload', function () {
  1094. doReady(doc)
  1095. });
  1096. } else {
  1097. doc.addEventListener("DOMContentLoaded", function () {
  1098. doc.removeEventListener("DOMContentLoaded", arguments.callee, false);
  1099. doReady(doc);
  1100. }, false);
  1101. win.addEventListener('load', function () {
  1102. doReady(doc)
  1103. }, false);
  1104. }
  1105. }
  1106. }
  1107. }(),
  1108. /**
  1109. * 动态添加css样式
  1110. * @method cssRule
  1111. * @param { String } 节点名称
  1112. * @grammar UE.utils.cssRule('添加的样式的节点名称',['样式','放到哪个document上'])
  1113. * @grammar UE.utils.cssRule('body','body{background:#ccc}') => null //给body添加背景颜色
  1114. * @grammar UE.utils.cssRule('body') =>样式的字符串 //取得key值为body的样式的内容,如果没有找到key值先关的样式将返回空,例如刚才那个背景颜色,将返回 body{background:#ccc}
  1115. * @grammar UE.utils.cssRule('body',document) => 返回指定key的样式,并且指定是哪个document
  1116. * @grammar UE.utils.cssRule('body','') =>null //清空给定的key值的背景颜色
  1117. */
  1118. cssRule:browser.ie && browser.version != 11 ? function (key, style, doc) {
  1119. var indexList, index;
  1120. if(style === undefined || style && style.nodeType && style.nodeType == 9){
  1121. //获取样式
  1122. doc = style && style.nodeType && style.nodeType == 9 ? style : (doc || document);
  1123. indexList = doc.indexList || (doc.indexList = {});
  1124. index = indexList[key];
  1125. if(index !== undefined){
  1126. return doc.styleSheets[index].cssText
  1127. }
  1128. return undefined;
  1129. }
  1130. doc = doc || document;
  1131. indexList = doc.indexList || (doc.indexList = {});
  1132. index = indexList[key];
  1133. //清除样式
  1134. if(style === ''){
  1135. if(index!== undefined){
  1136. doc.styleSheets[index].cssText = '';
  1137. delete indexList[key];
  1138. return true
  1139. }
  1140. return false;
  1141. }
  1142. //添加样式
  1143. if(index!== undefined){
  1144. sheetStyle = doc.styleSheets[index];
  1145. }else{
  1146. sheetStyle = doc.createStyleSheet('', index = doc.styleSheets.length);
  1147. indexList[key] = index;
  1148. }
  1149. sheetStyle.cssText = style;
  1150. }: function (key, style, doc) {
  1151. var head, node;
  1152. if(style === undefined || style && style.nodeType && style.nodeType == 9){
  1153. //获取样式
  1154. doc = style && style.nodeType && style.nodeType == 9 ? style : (doc || document);
  1155. node = doc.getElementById(key);
  1156. return node ? node.innerHTML : undefined;
  1157. }
  1158. doc = doc || document;
  1159. node = doc.getElementById(key);
  1160. //清除样式
  1161. if(style === ''){
  1162. if(node){
  1163. node.parentNode.removeChild(node);
  1164. return true
  1165. }
  1166. return false;
  1167. }
  1168. //添加样式
  1169. if(node){
  1170. node.innerHTML = style;
  1171. }else{
  1172. node = doc.createElement('style');
  1173. node.id = key;
  1174. node.innerHTML = style;
  1175. doc.getElementsByTagName('head')[0].appendChild(node);
  1176. }
  1177. },
  1178. sort:function(array,compareFn){
  1179. compareFn = compareFn || function(item1, item2){ return item1.localeCompare(item2);};
  1180. for(var i= 0,len = array.length; i<len; i++){
  1181. for(var j = i,length = array.length; j<length; j++){
  1182. if(compareFn(array[i], array[j]) > 0){
  1183. var t = array[i];
  1184. array[i] = array[j];
  1185. array[j] = t;
  1186. }
  1187. }
  1188. }
  1189. return array;
  1190. },
  1191. serializeParam:function (json) {
  1192. var strArr = [];
  1193. for (var i in json) {
  1194. //忽略默认的几个参数
  1195. if(i=="method" || i=="timeout" || i=="async") continue;
  1196. //传递过来的对象和函数不在提交之列
  1197. if (!((typeof json[i]).toLowerCase() == "function" || (typeof json[i]).toLowerCase() == "object")) {
  1198. strArr.push( encodeURIComponent(i) + "="+encodeURIComponent(json[i]) );
  1199. } else if (utils.isArray(json[i])) {
  1200. //支持传数组内容
  1201. for(var j = 0; j < json[i].length; j++) {
  1202. strArr.push( encodeURIComponent(i) + "[]="+encodeURIComponent(json[i][j]) );
  1203. }
  1204. }
  1205. }
  1206. return strArr.join("&");
  1207. },
  1208. formatUrl:function (url) {
  1209. var u = url.replace(/&&/g, '&');
  1210. u = u.replace(/\?&/g, '?');
  1211. u = u.replace(/&$/g, '');
  1212. u = u.replace(/&#/g, '#');
  1213. u = u.replace(/&+/g, '&');
  1214. return u;
  1215. },
  1216. isCrossDomainUrl:function (url) {
  1217. var a = document.createElement('a');
  1218. a.href = url;
  1219. if (browser.ie) {
  1220. a.href = a.href;
  1221. }
  1222. return !(a.protocol == location.protocol && a.hostname == location.hostname &&
  1223. (a.port == location.port || (a.port == '80' && location.port == '') || (a.port == '' && location.port == '80')));
  1224. },
  1225. clearEmptyAttrs : function(obj){
  1226. for(var p in obj){
  1227. if(obj[p] === ''){
  1228. delete obj[p]
  1229. }
  1230. }
  1231. return obj;
  1232. },
  1233. str2json : function(s){
  1234. if (!utils.isString(s)) return null;
  1235. if (window.JSON) {
  1236. return JSON.parse(s);
  1237. } else {
  1238. return (new Function("return " + utils.trim(s || '')))();
  1239. }
  1240. },
  1241. json2str : (function(){
  1242. if (window.JSON) {
  1243. return JSON.stringify;
  1244. } else {
  1245. var escapeMap = {
  1246. "\b": '\\b',
  1247. "\t": '\\t',
  1248. "\n": '\\n',
  1249. "\f": '\\f',
  1250. "\r": '\\r',
  1251. '"' : '\\"',
  1252. "\\": '\\\\'
  1253. };
  1254. function encodeString(source) {
  1255. if (/["\\\x00-\x1f]/.test(source)) {
  1256. source = source.replace(
  1257. /["\\\x00-\x1f]/g,
  1258. function (match) {
  1259. var c = escapeMap[match];
  1260. if (c) {
  1261. return c;
  1262. }
  1263. c = match.charCodeAt();
  1264. return "\\u00"
  1265. + Math.floor(c / 16).toString(16)
  1266. + (c % 16).toString(16);
  1267. });
  1268. }
  1269. return '"' + source + '"';
  1270. }
  1271. function encodeArray(source) {
  1272. var result = ["["],
  1273. l = source.length,
  1274. preComma, i, item;
  1275. for (i = 0; i < l; i++) {
  1276. item = source[i];
  1277. switch (typeof item) {
  1278. case "undefined":
  1279. case "function":
  1280. case "unknown":
  1281. break;
  1282. default:
  1283. if(preComma) {
  1284. result.push(',');
  1285. }
  1286. result.push(utils.json2str(item));
  1287. preComma = 1;
  1288. }
  1289. }
  1290. result.push("]");
  1291. return result.join("");
  1292. }
  1293. function pad(source) {
  1294. return source < 10 ? '0' + source : source;
  1295. }
  1296. function encodeDate(source){
  1297. return '"' + source.getFullYear() + "-"
  1298. + pad(source.getMonth() + 1) + "-"
  1299. + pad(source.getDate()) + "T"
  1300. + pad(source.getHours()) + ":"
  1301. + pad(source.getMinutes()) + ":"
  1302. + pad(source.getSeconds()) + '"';
  1303. }
  1304. return function (value) {
  1305. switch (typeof value) {
  1306. case 'undefined':
  1307. return 'undefined';
  1308. case 'number':
  1309. return isFinite(value) ? String(value) : "null";
  1310. case 'string':
  1311. return encodeString(value);
  1312. case 'boolean':
  1313. return String(value);
  1314. default:
  1315. if (value === null) {
  1316. return 'null';
  1317. } else if (utils.isArray(value)) {
  1318. return encodeArray(value);
  1319. } else if (utils.isDate(value)) {
  1320. return encodeDate(value);
  1321. } else {
  1322. var result = ['{'],
  1323. encode = utils.json2str,
  1324. preComma,
  1325. item;
  1326. for (var key in value) {
  1327. if (Object.prototype.hasOwnProperty.call(value, key)) {
  1328. item = value[key];
  1329. switch (typeof item) {
  1330. case 'undefined':
  1331. case 'unknown':
  1332. case 'function':
  1333. break;
  1334. default:
  1335. if (preComma) {
  1336. result.push(',');
  1337. }
  1338. preComma = 1;
  1339. result.push(encode(key) + ':' + encode(item));
  1340. }
  1341. }
  1342. }
  1343. result.push('}');
  1344. return result.join('');
  1345. }
  1346. }
  1347. };
  1348. }
  1349. })()
  1350. };
  1351. /**
  1352. * 判断给定的对象是否是字符串
  1353. * @method isString
  1354. * @param { * } object 需要判断的对象
  1355. * @return { Boolean } 给定的对象是否是字符串
  1356. */
  1357. /**
  1358. * 判断给定的对象是否是数组
  1359. * @method isArray
  1360. * @param { * } object 需要判断的对象
  1361. * @return { Boolean } 给定的对象是否是数组
  1362. */
  1363. /**
  1364. * 判断给定的对象是否是一个Function
  1365. * @method isFunction
  1366. * @param { * } object 需要判断的对象
  1367. * @return { Boolean } 给定的对象是否是Function
  1368. */
  1369. /**
  1370. * 判断给定的对象是否是Number
  1371. * @method isNumber
  1372. * @param { * } object 需要判断的对象
  1373. * @return { Boolean } 给定的对象是否是Number
  1374. */
  1375. /**
  1376. * 判断给定的对象是否是一个正则表达式
  1377. * @method isRegExp
  1378. * @param { * } object 需要判断的对象
  1379. * @return { Boolean } 给定的对象是否是正则表达式
  1380. */
  1381. /**
  1382. * 判断给定的对象是否是一个普通对象
  1383. * @method isObject
  1384. * @param { * } object 需要判断的对象
  1385. * @return { Boolean } 给定的对象是否是普通对象
  1386. */
  1387. utils.each(['String', 'Function', 'Array', 'Number', 'RegExp', 'Object', 'Date'], function (v) {
  1388. UE.utils['is' + v] = function (obj) {
  1389. return Object.prototype.toString.apply(obj) == '[object ' + v + ']';
  1390. }
  1391. });
  1392. // core/EventBase.js
  1393. /**
  1394. * UE采用的事件基类
  1395. * @file
  1396. * @module UE
  1397. * @class EventBase
  1398. * @since 1.2.6.1
  1399. */
  1400. /**
  1401. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  1402. * @unfile
  1403. * @module UE
  1404. */
  1405. /**
  1406. * UE采用的事件基类,继承此类的对应类将获取addListener,removeListener,fireEvent方法。
  1407. * 在UE中,Editor以及所有ui实例都继承了该类,故可以在对应的ui对象以及editor对象上使用上述方法。
  1408. * @unfile
  1409. * @module UE
  1410. * @class EventBase
  1411. */
  1412. /**
  1413. * 通过此构造器,子类可以继承EventBase获取事件监听的方法
  1414. * @constructor
  1415. * @example
  1416. * ```javascript
  1417. * UE.EventBase.call(editor);
  1418. * ```
  1419. */
  1420. var EventBase = UE.EventBase = function () {};
  1421. EventBase.prototype = {
  1422. /**
  1423. * 注册事件监听器
  1424. * @method addListener
  1425. * @param { String } types 监听的事件名称,同时监听多个事件使用空格分隔
  1426. * @param { Function } fn 监听的事件被触发时,会执行该回调函数
  1427. * @waining 事件被触发时,监听的函数假如返回的值恒等于true,回调函数的队列中后面的函数将不执行
  1428. * @example
  1429. * ```javascript
  1430. * editor.addListener('selectionchange',function(){
  1431. * console.log("选区已经变化!");
  1432. * })
  1433. * editor.addListener('beforegetcontent aftergetcontent',function(type){
  1434. * if(type == 'beforegetcontent'){
  1435. * //do something
  1436. * }else{
  1437. * //do something
  1438. * }
  1439. * console.log(this.getContent) // this是注册的事件的编辑器实例
  1440. * })
  1441. * ```
  1442. * @see UE.EventBase:fireEvent(String)
  1443. */
  1444. addListener:function (types, listener) {
  1445. types = utils.trim(types).split(/\s+/);
  1446. for (var i = 0, ti; ti = types[i++];) {
  1447. getListener(this, ti, true).push(listener);
  1448. }
  1449. },
  1450. on : function(types, listener){
  1451. return this.addListener(types,listener);
  1452. },
  1453. off : function(types, listener){
  1454. return this.removeListener(types, listener)
  1455. },
  1456. trigger:function(){
  1457. return this.fireEvent.apply(this,arguments);
  1458. },
  1459. /**
  1460. * 移除事件监听器
  1461. * @method removeListener
  1462. * @param { String } types 移除的事件名称,同时移除多个事件使用空格分隔
  1463. * @param { Function } fn 移除监听事件的函数引用
  1464. * @example
  1465. * ```javascript
  1466. * //changeCallback为方法体
  1467. * editor.removeListener("selectionchange",changeCallback);
  1468. * ```
  1469. */
  1470. removeListener:function (types, listener) {
  1471. types = utils.trim(types).split(/\s+/);
  1472. for (var i = 0, ti; ti = types[i++];) {
  1473. utils.removeItem(getListener(this, ti) || [], listener);
  1474. }
  1475. },
  1476. /**
  1477. * 触发事件
  1478. * @method fireEvent
  1479. * @param { String } types 触发的事件名称,同时触发多个事件使用空格分隔
  1480. * @remind 该方法会触发addListener
  1481. * @return { * } 返回触发事件的队列中,最后执行的回调函数的返回值
  1482. * @example
  1483. * ```javascript
  1484. * editor.fireEvent("selectionchange");
  1485. * ```
  1486. */
  1487. /**
  1488. * 触发事件
  1489. * @method fireEvent
  1490. * @param { String } types 触发的事件名称,同时触发多个事件使用空格分隔
  1491. * @param { *... } options 可选参数,可以传入一个或多个参数,会传给事件触发的回调函数
  1492. * @return { * } 返回触发事件的队列中,最后执行的回调函数的返回值
  1493. * @example
  1494. * ```javascript
  1495. *
  1496. * editor.addListener( "selectionchange", function ( type, arg1, arg2 ) {
  1497. *
  1498. * console.log( arg1 + " " + arg2 );
  1499. *
  1500. * } );
  1501. *
  1502. * //触发selectionchange事件, 会执行上面的事件监听器
  1503. * //output: Hello World
  1504. * editor.fireEvent("selectionchange", "Hello", "World");
  1505. * ```
  1506. */
  1507. fireEvent:function () {
  1508. var types = arguments[0];
  1509. types = utils.trim(types).split(' ');
  1510. for (var i = 0, ti; ti = types[i++];) {
  1511. var listeners = getListener(this, ti),
  1512. r, t, k;
  1513. if (listeners) {
  1514. k = listeners.length;
  1515. while (k--) {
  1516. if(!listeners[k])continue;
  1517. t = listeners[k].apply(this, arguments);
  1518. if(t === true){
  1519. return t;
  1520. }
  1521. if (t !== undefined) {
  1522. r = t;
  1523. }
  1524. }
  1525. }
  1526. if (t = this['on' + ti.toLowerCase()]) {
  1527. r = t.apply(this, arguments);
  1528. }
  1529. }
  1530. return r;
  1531. }
  1532. };
  1533. /**
  1534. * 获得对象所拥有监听类型的所有监听器
  1535. * @unfile
  1536. * @module UE
  1537. * @since 1.2.6.1
  1538. * @method getListener
  1539. * @public
  1540. * @param { Object } obj 查询监听器的对象
  1541. * @param { String } type 事件类型
  1542. * @param { Boolean } force 为true且当前所有type类型的侦听器不存在时,创建一个空监听器数组
  1543. * @return { Array } 监听器数组
  1544. */
  1545. function getListener(obj, type, force) {
  1546. var allListeners;
  1547. type = type.toLowerCase();
  1548. return ( ( allListeners = ( obj.__allListeners || force && ( obj.__allListeners = {} ) ) )
  1549. && ( allListeners[type] || force && ( allListeners[type] = [] ) ) );
  1550. }
  1551. // core/dtd.js
  1552. ///import editor.js
  1553. ///import core/dom/dom.js
  1554. ///import core/utils.js
  1555. /**
  1556. * dtd html语义化的体现类
  1557. * @constructor
  1558. * @namespace dtd
  1559. */
  1560. var dtd = dom.dtd = (function() {
  1561. function _( s ) {
  1562. for (var k in s) {
  1563. s[k.toUpperCase()] = s[k];
  1564. }
  1565. return s;
  1566. }
  1567. var X = utils.extend2;
  1568. var A = _({isindex:1,fieldset:1}),
  1569. B = _({input:1,button:1,select:1,textarea:1,label:1}),
  1570. C = X( _({a:1}), B ),
  1571. D = X( {iframe:1}, C ),
  1572. E = _({hr:1,ul:1,menu:1,div:1,blockquote:1,noscript:1,table:1,center:1,address:1,dir:1,pre:1,h5:1,dl:1,h4:1,noframes:1,h6:1,ol:1,h1:1,h3:1,h2:1}),
  1573. F = _({ins:1,del:1,script:1,style:1}),
  1574. G = X( _({b:1,acronym:1,bdo:1,'var':1,'#':1,abbr:1,code:1,br:1,i:1,cite:1,kbd:1,u:1,strike:1,s:1,tt:1,strong:1,q:1,samp:1,em:1,dfn:1,span:1}), F ),
  1575. H = X( _({sub:1,img:1,embed:1,object:1,sup:1,basefont:1,map:1,applet:1,font:1,big:1,small:1}), G ),
  1576. I = X( _({p:1}), H ),
  1577. J = X( _({iframe:1}), H, B ),
  1578. K = _({img:1,embed:1,noscript:1,br:1,kbd:1,center:1,button:1,basefont:1,h5:1,h4:1,samp:1,h6:1,ol:1,h1:1,h3:1,h2:1,form:1,font:1,'#':1,select:1,menu:1,ins:1,abbr:1,label:1,code:1,table:1,script:1,cite:1,input:1,iframe:1,strong:1,textarea:1,noframes:1,big:1,small:1,span:1,hr:1,sub:1,bdo:1,'var':1,div:1,object:1,sup:1,strike:1,dir:1,map:1,dl:1,applet:1,del:1,isindex:1,fieldset:1,ul:1,b:1,acronym:1,a:1,blockquote:1,i:1,u:1,s:1,tt:1,address:1,q:1,pre:1,p:1,em:1,dfn:1}),
  1579. L = X( _({a:0}), J ),//a不能被切开,所以把他
  1580. M = _({tr:1}),
  1581. N = _({'#':1}),
  1582. O = X( _({param:1}), K ),
  1583. P = X( _({form:1}), A, D, E, I ),
  1584. Q = _({li:1,ol:1,ul:1}),
  1585. R = _({style:1,script:1}),
  1586. S = _({base:1,link:1,meta:1,title:1}),
  1587. T = X( S, R ),
  1588. U = _({head:1,body:1}),
  1589. V = _({html:1});
  1590. var block = _({address:1,blockquote:1,center:1,dir:1,div:1,dl:1,fieldset:1,form:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,hr:1,isindex:1,menu:1,noframes:1,ol:1,p:1,pre:1,table:1,ul:1}),
  1591. empty = _({area:1,base:1,basefont:1,br:1,col:1,command:1,dialog:1,embed:1,hr:1,img:1,input:1,isindex:1,keygen:1,link:1,meta:1,param:1,source:1,track:1,wbr:1});
  1592. return _({
  1593. // $ 表示自定的属性
  1594. // body外的元素列表.
  1595. $nonBodyContent: X( V, U, S ),
  1596. //块结构元素列表
  1597. $block : block,
  1598. //内联元素列表
  1599. $inline : L,
  1600. $inlineWithA : X(_({a:1}),L),
  1601. $body : X( _({script:1,style:1}), block ),
  1602. $cdata : _({script:1,style:1}),
  1603. //自闭和元素
  1604. $empty : empty,
  1605. //不是自闭合,但不能让range选中里边
  1606. $nonChild : _({iframe:1,textarea:1}),
  1607. //列表元素列表
  1608. $listItem : _({dd:1,dt:1,li:1}),
  1609. //列表根元素列表
  1610. $list: _({ul:1,ol:1,dl:1}),
  1611. //不能认为是空的元素
  1612. $isNotEmpty : _({table:1,ul:1,ol:1,dl:1,iframe:1,area:1,base:1,col:1,hr:1,img:1,embed:1,input:1,link:1,meta:1,param:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1}),
  1613. //如果没有子节点就可以删除的元素列表,像span,a
  1614. $removeEmpty : _({a:1,abbr:1,acronym:1,address:1,b:1,bdo:1,big:1,cite:1,code:1,del:1,dfn:1,em:1,font:1,i:1,ins:1,label:1,kbd:1,q:1,s:1,samp:1,small:1,span:1,strike:1,strong:1,sub:1,sup:1,tt:1,u:1,'var':1}),
  1615. $removeEmptyBlock : _({'p':1,'div':1}),
  1616. //在table元素里的元素列表
  1617. $tableContent : _({caption:1,col:1,colgroup:1,tbody:1,td:1,tfoot:1,th:1,thead:1,tr:1,table:1}),
  1618. //不转换的标签
  1619. $notTransContent : _({pre:1,script:1,style:1,textarea:1}),
  1620. html: U,
  1621. head: T,
  1622. style: N,
  1623. script: N,
  1624. body: P,
  1625. base: {},
  1626. link: {},
  1627. meta: {},
  1628. title: N,
  1629. col : {},
  1630. tr : _({td:1,th:1}),
  1631. img : {},
  1632. embed: {},
  1633. colgroup : _({thead:1,col:1,tbody:1,tr:1,tfoot:1}),
  1634. noscript : P,
  1635. td : P,
  1636. br : {},
  1637. th : P,
  1638. center : P,
  1639. kbd : L,
  1640. button : X( I, E ),
  1641. basefont : {},
  1642. h5 : L,
  1643. h4 : L,
  1644. samp : L,
  1645. h6 : L,
  1646. ol : Q,
  1647. h1 : L,
  1648. h3 : L,
  1649. option : N,
  1650. h2 : L,
  1651. form : X( A, D, E, I ),
  1652. select : _({optgroup:1,option:1}),
  1653. font : L,
  1654. ins : L,
  1655. menu : Q,
  1656. abbr : L,
  1657. label : L,
  1658. table : _({thead:1,col:1,tbody:1,tr:1,colgroup:1,caption:1,tfoot:1}),
  1659. code : L,
  1660. tfoot : M,
  1661. cite : L,
  1662. li : P,
  1663. input : {},
  1664. iframe : P,
  1665. strong : L,
  1666. textarea : N,
  1667. noframes : P,
  1668. big : L,
  1669. small : L,
  1670. //trace:
  1671. span :_({'#':1,br:1,b:1,strong:1,u:1,i:1,em:1,sub:1,sup:1,strike:1,span:1}),
  1672. hr : L,
  1673. dt : L,
  1674. sub : L,
  1675. optgroup : _({option:1}),
  1676. param : {},
  1677. bdo : L,
  1678. 'var' : L,
  1679. div : P,
  1680. object : O,
  1681. sup : L,
  1682. dd : P,
  1683. strike : L,
  1684. area : {},
  1685. dir : Q,
  1686. map : X( _({area:1,form:1,p:1}), A, F, E ),
  1687. applet : O,
  1688. dl : _({dt:1,dd:1}),
  1689. del : L,
  1690. isindex : {},
  1691. fieldset : X( _({legend:1}), K ),
  1692. thead : M,
  1693. ul : Q,
  1694. acronym : L,
  1695. b : L,
  1696. a : X( _({a:1}), J ),
  1697. blockquote :X(_({td:1,tr:1,tbody:1,li:1}),P),
  1698. caption : L,
  1699. i : L,
  1700. u : L,
  1701. tbody : M,
  1702. s : L,
  1703. address : X( D, I ),
  1704. tt : L,
  1705. legend : L,
  1706. q : L,
  1707. pre : X( G, C ),
  1708. p : X(_({'a':1}),L),
  1709. em :L,
  1710. dfn : L
  1711. });
  1712. })();
  1713. // core/domUtils.js
  1714. /**
  1715. * Dom操作工具包
  1716. * @file
  1717. * @module UE.dom.domUtils
  1718. * @since 1.2.6.1
  1719. */
  1720. /**
  1721. * Dom操作工具包
  1722. * @unfile
  1723. * @module UE.dom.domUtils
  1724. */
  1725. function getDomNode(node, start, ltr, startFromChild, fn, guard) {
  1726. var tmpNode = startFromChild && node[start],
  1727. parent;
  1728. !tmpNode && (tmpNode = node[ltr]);
  1729. while (!tmpNode && (parent = (parent || node).parentNode)) {
  1730. if (parent.tagName == 'BODY' || guard && !guard(parent)) {
  1731. return null;
  1732. }
  1733. tmpNode = parent[ltr];
  1734. }
  1735. if (tmpNode && fn && !fn(tmpNode)) {
  1736. return getDomNode(tmpNode, start, ltr, false, fn);
  1737. }
  1738. return tmpNode;
  1739. }
  1740. var attrFix = ie && browser.version < 9 ? {
  1741. tabindex:"tabIndex",
  1742. readonly:"readOnly",
  1743. "for":"htmlFor",
  1744. "class":"className",
  1745. maxlength:"maxLength",
  1746. cellspacing:"cellSpacing",
  1747. cellpadding:"cellPadding",
  1748. rowspan:"rowSpan",
  1749. colspan:"colSpan",
  1750. usemap:"useMap",
  1751. frameborder:"frameBorder"
  1752. } : {
  1753. tabindex:"tabIndex",
  1754. readonly:"readOnly"
  1755. },
  1756. styleBlock = utils.listToMap([
  1757. '-webkit-box', '-moz-box', 'block' ,
  1758. 'list-item' , 'table' , 'table-row-group' ,
  1759. 'table-header-group', 'table-footer-group' ,
  1760. 'table-row' , 'table-column-group' , 'table-column' ,
  1761. 'table-cell' , 'table-caption'
  1762. ]);
  1763. var domUtils = dom.domUtils = {
  1764. //节点常量
  1765. NODE_ELEMENT:1,
  1766. NODE_DOCUMENT:9,
  1767. NODE_TEXT:3,
  1768. NODE_COMMENT:8,
  1769. NODE_DOCUMENT_FRAGMENT:11,
  1770. //位置关系
  1771. POSITION_IDENTICAL:0,
  1772. POSITION_DISCONNECTED:1,
  1773. POSITION_FOLLOWING:2,
  1774. POSITION_PRECEDING:4,
  1775. POSITION_IS_CONTAINED:8,
  1776. POSITION_CONTAINS:16,
  1777. //ie6使用其他的会有一段空白出现
  1778. fillChar:ie && browser.version == '6' ? '\ufeff' : '\u200B',
  1779. //-------------------------Node部分--------------------------------
  1780. keys:{
  1781. /*Backspace*/ 8:1, /*Delete*/ 46:1,
  1782. /*Shift*/ 16:1, /*Ctrl*/ 17:1, /*Alt*/ 18:1,
  1783. 37:1, 38:1, 39:1, 40:1,
  1784. 13:1 /*enter*/
  1785. },
  1786. /**
  1787. * 获取节点A相对于节点B的位置关系
  1788. * @method getPosition
  1789. * @param { Node } nodeA 需要查询位置关系的节点A
  1790. * @param { Node } nodeB 需要查询位置关系的节点B
  1791. * @return { Number } 节点A与节点B的关系
  1792. * @example
  1793. * ```javascript
  1794. * //output: 20
  1795. * var position = UE.dom.domUtils.getPosition( document.documentElement, document.body );
  1796. *
  1797. * switch ( position ) {
  1798. *
  1799. * //0
  1800. * case UE.dom.domUtils.POSITION_IDENTICAL:
  1801. * console.log('元素相同');
  1802. * break;
  1803. * //1
  1804. * case UE.dom.domUtils.POSITION_DISCONNECTED:
  1805. * console.log('两个节点在不同的文档中');
  1806. * break;
  1807. * //2
  1808. * case UE.dom.domUtils.POSITION_FOLLOWING:
  1809. * console.log('节点A在节点B之后');
  1810. * break;
  1811. * //4
  1812. * case UE.dom.domUtils.POSITION_PRECEDING;
  1813. * console.log('节点A在节点B之前');
  1814. * break;
  1815. * //8
  1816. * case UE.dom.domUtils.POSITION_IS_CONTAINED:
  1817. * console.log('节点A被节点B包含');
  1818. * break;
  1819. * case 10:
  1820. * console.log('节点A被节点B包含且节点A在节点B之后');
  1821. * break;
  1822. * //16
  1823. * case UE.dom.domUtils.POSITION_CONTAINS:
  1824. * console.log('节点A包含节点B');
  1825. * break;
  1826. * case 20:
  1827. * console.log('节点A包含节点B且节点A在节点B之前');
  1828. * break;
  1829. *
  1830. * }
  1831. * ```
  1832. */
  1833. getPosition:function (nodeA, nodeB) {
  1834. // 如果两个节点是同一个节点
  1835. if (nodeA === nodeB) {
  1836. // domUtils.POSITION_IDENTICAL
  1837. return 0;
  1838. }
  1839. var node,
  1840. parentsA = [nodeA],
  1841. parentsB = [nodeB];
  1842. node = nodeA;
  1843. while (node = node.parentNode) {
  1844. // 如果nodeB是nodeA的祖先节点
  1845. if (node === nodeB) {
  1846. // domUtils.POSITION_IS_CONTAINED + domUtils.POSITION_FOLLOWING
  1847. return 10;
  1848. }
  1849. parentsA.push(node);
  1850. }
  1851. node = nodeB;
  1852. while (node = node.parentNode) {
  1853. // 如果nodeA是nodeB的祖先节点
  1854. if (node === nodeA) {
  1855. // domUtils.POSITION_CONTAINS + domUtils.POSITION_PRECEDING
  1856. return 20;
  1857. }
  1858. parentsB.push(node);
  1859. }
  1860. parentsA.reverse();
  1861. parentsB.reverse();
  1862. if (parentsA[0] !== parentsB[0]) {
  1863. // domUtils.POSITION_DISCONNECTED
  1864. return 1;
  1865. }
  1866. var i = -1;
  1867. while (i++, parentsA[i] === parentsB[i]) {
  1868. }
  1869. nodeA = parentsA[i];
  1870. nodeB = parentsB[i];
  1871. while (nodeA = nodeA.nextSibling) {
  1872. if (nodeA === nodeB) {
  1873. // domUtils.POSITION_PRECEDING
  1874. return 4
  1875. }
  1876. }
  1877. // domUtils.POSITION_FOLLOWING
  1878. return 2;
  1879. },
  1880. /**
  1881. * 检测节点node在父节点中的索引位置
  1882. * @method getNodeIndex
  1883. * @param { Node } node 需要检测的节点对象
  1884. * @return { Number } 该节点在父节点中的位置
  1885. * @see UE.dom.domUtils.getNodeIndex(Node,Boolean)
  1886. */
  1887. /**
  1888. * 检测节点node在父节点中的索引位置, 根据给定的mergeTextNode参数决定是否要合并多个连续的文本节点为一个节点
  1889. * @method getNodeIndex
  1890. * @param { Node } node 需要检测的节点对象
  1891. * @param { Boolean } mergeTextNode 是否合并多个连续的文本节点为一个节点
  1892. * @return { Number } 该节点在父节点中的位置
  1893. * @example
  1894. * ```javascript
  1895. *
  1896. * var node = document.createElement("div");
  1897. *
  1898. * node.appendChild( document.createTextNode( "hello" ) );
  1899. * node.appendChild( document.createTextNode( "world" ) );
  1900. * node.appendChild( node = document.createElement( "div" ) );
  1901. *
  1902. * //output: 2
  1903. * console.log( UE.dom.domUtils.getNodeIndex( node ) );
  1904. *
  1905. * //output: 1
  1906. * console.log( UE.dom.domUtils.getNodeIndex( node, true ) );
  1907. *
  1908. * ```
  1909. */
  1910. getNodeIndex:function (node, ignoreTextNode) {
  1911. var preNode = node,
  1912. i = 0;
  1913. while (preNode = preNode.previousSibling) {
  1914. if (ignoreTextNode && preNode.nodeType == 3) {
  1915. if(preNode.nodeType != preNode.nextSibling.nodeType ){
  1916. i++;
  1917. }
  1918. continue;
  1919. }
  1920. i++;
  1921. }
  1922. return i;
  1923. },
  1924. /**
  1925. * 检测节点node是否在给定的document对象上
  1926. * @method inDoc
  1927. * @param { Node } node 需要检测的节点对象
  1928. * @param { DomDocument } doc 需要检测的document对象
  1929. * @return { Boolean } 该节点node是否在给定的document的dom树上
  1930. * @example
  1931. * ```javascript
  1932. *
  1933. * var node = document.createElement("div");
  1934. *
  1935. * //output: false
  1936. * console.log( UE.do.domUtils.inDoc( node, document ) );
  1937. *
  1938. * document.body.appendChild( node );
  1939. *
  1940. * //output: true
  1941. * console.log( UE.do.domUtils.inDoc( node, document ) );
  1942. *
  1943. * ```
  1944. */
  1945. inDoc:function (node, doc) {
  1946. return domUtils.getPosition(node, doc) == 10;
  1947. },
  1948. /**
  1949. * 根据给定的过滤规则filterFn, 查找符合该过滤规则的node节点的第一个祖先节点,
  1950. * 查找的起点是给定node节点的父节点。
  1951. * @method findParent
  1952. * @param { Node } node 需要查找的节点
  1953. * @param { Function } filterFn 自定义的过滤方法。
  1954. * @warning 查找的终点是到body节点为止
  1955. * @remind 自定义的过滤方法filterFn接受一个Node对象作为参数, 该对象代表当前执行检测的祖先节点。 如果该
  1956. * 节点满足过滤条件, 则要求返回true, 这时将直接返回该节点作为findParent()的结果, 否则, 请返回false。
  1957. * @return { Node | Null } 如果找到符合过滤条件的节点, 就返回该节点, 否则返回NULL
  1958. * @example
  1959. * ```javascript
  1960. * var filterNode = UE.dom.domUtils.findParent( document.body.firstChild, function ( node ) {
  1961. *
  1962. * //由于查找的终点是body节点, 所以永远也不会匹配当前过滤器的条件, 即这里永远会返回false
  1963. * return node.tagName === "HTML";
  1964. *
  1965. * } );
  1966. *
  1967. * //output: true
  1968. * console.log( filterNode === null );
  1969. * ```
  1970. */
  1971. /**
  1972. * 根据给定的过滤规则filterFn, 查找符合该过滤规则的node节点的第一个祖先节点,
  1973. * 如果includeSelf的值为true,则查找的起点是给定的节点node, 否则, 起点是node的父节点
  1974. * @method findParent
  1975. * @param { Node } node 需要查找的节点
  1976. * @param { Function } filterFn 自定义的过滤方法。
  1977. * @param { Boolean } includeSelf 查找过程是否包含自身
  1978. * @warning 查找的终点是到body节点为止
  1979. * @remind 自定义的过滤方法filterFn接受一个Node对象作为参数, 该对象代表当前执行检测的祖先节点。 如果该
  1980. * 节点满足过滤条件, 则要求返回true, 这时将直接返回该节点作为findParent()的结果, 否则, 请返回false。
  1981. * @remind 如果includeSelf为true, 则过滤器第一次执行时的参数会是节点本身。
  1982. * 反之, 过滤器第一次执行时的参数将是该节点的父节点。
  1983. * @return { Node | Null } 如果找到符合过滤条件的节点, 就返回该节点, 否则返回NULL
  1984. * @example
  1985. * ```html
  1986. * <body>
  1987. *
  1988. * <div id="test">
  1989. * </div>
  1990. *
  1991. * <script type="text/javascript">
  1992. *
  1993. * //output: DIV, BODY
  1994. * var filterNode = UE.dom.domUtils.findParent( document.getElementById( "test" ), function ( node ) {
  1995. *
  1996. * console.log( node.tagName );
  1997. * return false;
  1998. *
  1999. * }, true );
  2000. *
  2001. * </script>
  2002. * </body>
  2003. * ```
  2004. */
  2005. findParent:function (node, filterFn, includeSelf) {
  2006. if (node && !domUtils.isBody(node)) {
  2007. node = includeSelf ? node : node.parentNode;
  2008. while (node) {
  2009. if (!filterFn || filterFn(node) || domUtils.isBody(node)) {
  2010. return filterFn && !filterFn(node) && domUtils.isBody(node) ? null : node;
  2011. }
  2012. node = node.parentNode;
  2013. }
  2014. }
  2015. return null;
  2016. },
  2017. /**
  2018. * 查找node的节点名为tagName的第一个祖先节点, 查找的起点是node节点的父节点。
  2019. * @method findParentByTagName
  2020. * @param { Node } node 需要查找的节点对象
  2021. * @param { Array } tagNames 需要查找的父节点的名称数组
  2022. * @warning 查找的终点是到body节点为止
  2023. * @return { Node | NULL } 如果找到符合条件的节点, 则返回该节点, 否则返回NULL
  2024. * @example
  2025. * ```javascript
  2026. * var node = UE.dom.domUtils.findParentByTagName( document.getElementsByTagName("div")[0], [ "BODY" ] );
  2027. * //output: BODY
  2028. * console.log( node.tagName );
  2029. * ```
  2030. */
  2031. /**
  2032. * 查找node的节点名为tagName的祖先节点, 如果includeSelf的值为true,则查找的起点是给定的节点node,
  2033. * 否则, 起点是node的父节点。
  2034. * @method findParentByTagName
  2035. * @param { Node } node 需要查找的节点对象
  2036. * @param { Array } tagNames 需要查找的父节点的名称数组
  2037. * @param { Boolean } includeSelf 查找过程是否包含node节点自身
  2038. * @warning 查找的终点是到body节点为止
  2039. * @return { Node | NULL } 如果找到符合条件的节点, 则返回该节点, 否则返回NULL
  2040. * @example
  2041. * ```javascript
  2042. * var queryTarget = document.getElementsByTagName("div")[0];
  2043. * var node = UE.dom.domUtils.findParentByTagName( queryTarget, [ "DIV" ], true );
  2044. * //output: true
  2045. * console.log( queryTarget === node );
  2046. * ```
  2047. */
  2048. findParentByTagName:function (node, tagNames, includeSelf, excludeFn) {
  2049. tagNames = utils.listToMap(utils.isArray(tagNames) ? tagNames : [tagNames]);
  2050. return domUtils.findParent(node, function (node) {
  2051. return tagNames[node.tagName] && !(excludeFn && excludeFn(node));
  2052. }, includeSelf);
  2053. },
  2054. /**
  2055. * 查找节点node的祖先节点集合, 查找的起点是给定节点的父节点,结果集中不包含给定的节点。
  2056. * @method findParents
  2057. * @param { Node } node 需要查找的节点对象
  2058. * @return { Array } 给定节点的祖先节点数组
  2059. * @grammar UE.dom.domUtils.findParents(node) => Array //返回一个祖先节点数组集合,不包含自身
  2060. * @grammar UE.dom.domUtils.findParents(node,includeSelf) => Array //返回一个祖先节点数组集合,includeSelf指定是否包含自身
  2061. * @grammar UE.dom.domUtils.findParents(node,includeSelf,filterFn) => Array //返回一个祖先节点数组集合,filterFn指定过滤条件,返回true的node将被选取
  2062. * @grammar UE.dom.domUtils.findParents(node,includeSelf,filterFn,closerFirst) => Array //返回一个祖先节点数组集合,closerFirst为true的话,node的直接父亲节点是数组的第0个
  2063. */
  2064. /**
  2065. * 查找节点node的祖先节点集合, 如果includeSelf的值为true,
  2066. * 则返回的结果集中允许出现当前给定的节点, 否则, 该节点不会出现在其结果集中。
  2067. * @method findParents
  2068. * @param { Node } node 需要查找的节点对象
  2069. * @param { Boolean } includeSelf 查找的结果中是否允许包含当前查找的节点对象
  2070. * @return { Array } 给定节点的祖先节点数组
  2071. */
  2072. findParents:function (node, includeSelf, filterFn, closerFirst) {
  2073. var parents = includeSelf && ( filterFn && filterFn(node) || !filterFn ) ? [node] : [];
  2074. while (node = domUtils.findParent(node, filterFn)) {
  2075. parents.push(node);
  2076. }
  2077. return closerFirst ? parents : parents.reverse();
  2078. },
  2079. /**
  2080. * 在节点node后面插入新节点newNode
  2081. * @method insertAfter
  2082. * @param { Node } node 目标节点
  2083. * @param { Node } newNode 新插入的节点, 该节点将置于目标节点之后
  2084. * @return { Node } 新插入的节点
  2085. */
  2086. insertAfter:function (node, newNode) {
  2087. return node.nextSibling ? node.parentNode.insertBefore(newNode, node.nextSibling):
  2088. node.parentNode.appendChild(newNode);
  2089. },
  2090. /**
  2091. * 删除节点node及其下属的所有节点
  2092. * @method remove
  2093. * @param { Node } node 需要删除的节点对象
  2094. * @return { Node } 返回刚删除的节点对象
  2095. * @example
  2096. * ```html
  2097. * <div id="test">
  2098. * <div id="child">你好</div>
  2099. * </div>
  2100. * <script>
  2101. * UE.dom.domUtils.remove( document.body, false );
  2102. * //output: false
  2103. * console.log( document.getElementById( "child" ) !== null );
  2104. * </script>
  2105. * ```
  2106. */
  2107. /**
  2108. * 删除节点node,并根据keepChildren的值决定是否保留子节点
  2109. * @method remove
  2110. * @param { Node } node 需要删除的节点对象
  2111. * @param { Boolean } keepChildren 是否需要保留子节点
  2112. * @return { Node } 返回刚删除的节点对象
  2113. * @example
  2114. * ```html
  2115. * <div id="test">
  2116. * <div id="child">你好</div>
  2117. * </div>
  2118. * <script>
  2119. * UE.dom.domUtils.remove( document.body, true );
  2120. * //output: true
  2121. * console.log( document.getElementById( "child" ) !== null );
  2122. * </script>
  2123. * ```
  2124. */
  2125. remove:function (node, keepChildren) {
  2126. var parent = node.parentNode,
  2127. child;
  2128. if (parent) {
  2129. if (keepChildren && node.hasChildNodes()) {
  2130. while (child = node.firstChild) {
  2131. parent.insertBefore(child, node);
  2132. }
  2133. }
  2134. parent.removeChild(node);
  2135. }
  2136. return node;
  2137. },
  2138. /**
  2139. * 取得node节点的下一个兄弟节点, 如果该节点其后没有兄弟节点, 则递归查找其父节点之后的第一个兄弟节点,
  2140. * 直到找到满足条件的节点或者递归到BODY节点之后才会结束。
  2141. * @method getNextDomNode
  2142. * @param { Node } node 需要获取其后的兄弟节点的节点对象
  2143. * @return { Node | NULL } 如果找满足条件的节点, 则返回该节点, 否则返回NULL
  2144. * @example
  2145. * ```html
  2146. * <body>
  2147. * <div id="test">
  2148. * <span></span>
  2149. * </div>
  2150. * <i>xxx</i>
  2151. * </body>
  2152. * <script>
  2153. *
  2154. * //output: i节点
  2155. * console.log( UE.dom.domUtils.getNextDomNode( document.getElementById( "test" ) ) );
  2156. *
  2157. * </script>
  2158. * ```
  2159. * @example
  2160. * ```html
  2161. * <body>
  2162. * <div>
  2163. * <span></span>
  2164. * <i id="test">xxx</i>
  2165. * </div>
  2166. * <b>xxx</b>
  2167. * </body>
  2168. * <script>
  2169. *
  2170. * //由于id为test的i节点之后没有兄弟节点, 则查找其父节点(div)后面的兄弟节点
  2171. * //output: b节点
  2172. * console.log( UE.dom.domUtils.getNextDomNode( document.getElementById( "test" ) ) );
  2173. *
  2174. * </script>
  2175. * ```
  2176. */
  2177. /**
  2178. * 取得node节点的下一个兄弟节点, 如果startFromChild的值为ture,则先获取其子节点,
  2179. * 如果有子节点则直接返回第一个子节点;如果没有子节点或者startFromChild的值为false,
  2180. * 则执行<a href="#UE.dom.domUtils.getNextDomNode(Node)">getNextDomNode(Node node)</a>的查找过程。
  2181. * @method getNextDomNode
  2182. * @param { Node } node 需要获取其后的兄弟节点的节点对象
  2183. * @param { Boolean } startFromChild 查找过程是否从其子节点开始
  2184. * @return { Node | NULL } 如果找满足条件的节点, 则返回该节点, 否则返回NULL
  2185. * @see UE.dom.domUtils.getNextDomNode(Node)
  2186. */
  2187. getNextDomNode:function (node, startFromChild, filterFn, guard) {
  2188. return getDomNode(node, 'firstChild', 'nextSibling', startFromChild, filterFn, guard);
  2189. },
  2190. getPreDomNode:function (node, startFromChild, filterFn, guard) {
  2191. return getDomNode(node, 'lastChild', 'previousSibling', startFromChild, filterFn, guard);
  2192. },
  2193. /**
  2194. * 检测节点node是否属是UEditor定义的bookmark节点
  2195. * @method isBookmarkNode
  2196. * @private
  2197. * @param { Node } node 需要检测的节点对象
  2198. * @return { Boolean } 是否是bookmark节点
  2199. * @example
  2200. * ```html
  2201. * <span id="_baidu_bookmark_1"></span>
  2202. * <script>
  2203. * var bookmarkNode = document.getElementById("_baidu_bookmark_1");
  2204. * //output: true
  2205. * console.log( UE.dom.domUtils.isBookmarkNode( bookmarkNode ) );
  2206. * </script>
  2207. * ```
  2208. */
  2209. isBookmarkNode:function (node) {
  2210. return node.nodeType == 1 && node.id && /^_baidu_bookmark_/i.test(node.id);
  2211. },
  2212. /**
  2213. * 获取节点node所属的window对象
  2214. * @method getWindow
  2215. * @param { Node } node 节点对象
  2216. * @return { Window } 当前节点所属的window对象
  2217. * @example
  2218. * ```javascript
  2219. * //output: true
  2220. * console.log( UE.dom.domUtils.getWindow( document.body ) === window );
  2221. * ```
  2222. */
  2223. getWindow:function (node) {
  2224. var doc = node.ownerDocument || node;
  2225. return doc.defaultView || doc.parentWindow;
  2226. },
  2227. /**
  2228. * 获取离nodeA与nodeB最近的公共的祖先节点
  2229. * @method getCommonAncestor
  2230. * @param { Node } nodeA 第一个节点
  2231. * @param { Node } nodeB 第二个节点
  2232. * @remind 如果给定的两个节点是同一个节点, 将直接返回该节点。
  2233. * @return { Node | NULL } 如果未找到公共节点, 返回NULL, 否则返回最近的公共祖先节点。
  2234. * @example
  2235. * ```javascript
  2236. * var commonAncestor = UE.dom.domUtils.getCommonAncestor( document.body, document.body.firstChild );
  2237. * //output: true
  2238. * console.log( commonAncestor.tagName.toLowerCase() === 'body' );
  2239. * ```
  2240. */
  2241. getCommonAncestor:function (nodeA, nodeB) {
  2242. if (nodeA === nodeB)
  2243. return nodeA;
  2244. var parentsA = [nodeA] , parentsB = [nodeB], parent = nodeA, i = -1;
  2245. while (parent = parent.parentNode) {
  2246. if (parent === nodeB) {
  2247. return parent;
  2248. }
  2249. parentsA.push(parent);
  2250. }
  2251. parent = nodeB;
  2252. while (parent = parent.parentNode) {
  2253. if (parent === nodeA)
  2254. return parent;
  2255. parentsB.push(parent);
  2256. }
  2257. parentsA.reverse();
  2258. parentsB.reverse();
  2259. while (i++, parentsA[i] === parentsB[i]) {
  2260. }
  2261. return i == 0 ? null : parentsA[i - 1];
  2262. },
  2263. /**
  2264. * 清除node节点左右连续为空的兄弟inline节点
  2265. * @method clearEmptySibling
  2266. * @param { Node } node 执行的节点对象, 如果该节点的左右连续的兄弟节点是空的inline节点,
  2267. * 则这些兄弟节点将被删除
  2268. * @grammar UE.dom.domUtils.clearEmptySibling(node,ignoreNext) //ignoreNext指定是否忽略右边空节点
  2269. * @grammar UE.dom.domUtils.clearEmptySibling(node,ignoreNext,ignorePre) //ignorePre指定是否忽略左边空节点
  2270. * @example
  2271. * ```html
  2272. * <body>
  2273. * <div></div>
  2274. * <span id="test"></span>
  2275. * <i></i>
  2276. * <b></b>
  2277. * <em>xxx</em>
  2278. * <span></span>
  2279. * </body>
  2280. * <script>
  2281. *
  2282. * UE.dom.domUtils.clearEmptySibling( document.getElementById( "test" ) );
  2283. *
  2284. * //output: <div></div><span id="test"></span><em>xxx</em><span></span>
  2285. * console.log( document.body.innerHTML );
  2286. *
  2287. * </script>
  2288. * ```
  2289. */
  2290. /**
  2291. * 清除node节点左右连续为空的兄弟inline节点, 如果ignoreNext的值为true,
  2292. * 则忽略对右边兄弟节点的操作。
  2293. * @method clearEmptySibling
  2294. * @param { Node } node 执行的节点对象, 如果该节点的左右连续的兄弟节点是空的inline节点,
  2295. * @param { Boolean } ignoreNext 是否忽略忽略对右边的兄弟节点的操作
  2296. * 则这些兄弟节点将被删除
  2297. * @see UE.dom.domUtils.clearEmptySibling(Node)
  2298. */
  2299. /**
  2300. * 清除node节点左右连续为空的兄弟inline节点, 如果ignoreNext的值为true,
  2301. * 则忽略对右边兄弟节点的操作, 如果ignorePre的值为true,则忽略对左边兄弟节点的操作。
  2302. * @method clearEmptySibling
  2303. * @param { Node } node 执行的节点对象, 如果该节点的左右连续的兄弟节点是空的inline节点,
  2304. * @param { Boolean } ignoreNext 是否忽略忽略对右边的兄弟节点的操作
  2305. * @param { Boolean } ignorePre 是否忽略忽略对左边的兄弟节点的操作
  2306. * 则这些兄弟节点将被删除
  2307. * @see UE.dom.domUtils.clearEmptySibling(Node)
  2308. */
  2309. clearEmptySibling:function (node, ignoreNext, ignorePre) {
  2310. function clear(next, dir) {
  2311. var tmpNode;
  2312. while (next && !domUtils.isBookmarkNode(next) && (domUtils.isEmptyInlineElement(next)
  2313. //这里不能把空格算进来会吧空格干掉,出现文字间的空格丢掉了
  2314. || !new RegExp('[^\t\n\r' + domUtils.fillChar + ']').test(next.nodeValue) )) {
  2315. tmpNode = next[dir];
  2316. domUtils.remove(next);
  2317. next = tmpNode;
  2318. }
  2319. }
  2320. !ignoreNext && clear(node.nextSibling, 'nextSibling');
  2321. !ignorePre && clear(node.previousSibling, 'previousSibling');
  2322. },
  2323. /**
  2324. * 将一个文本节点textNode拆分成两个文本节点,offset指定拆分位置
  2325. * @method split
  2326. * @param { Node } textNode 需要拆分的文本节点对象
  2327. * @param { int } offset 需要拆分的位置, 位置计算从0开始
  2328. * @return { Node } 拆分后形成的新节点
  2329. * @example
  2330. * ```html
  2331. * <div id="test">abcdef</div>
  2332. * <script>
  2333. * var newNode = UE.dom.domUtils.split( document.getElementById( "test" ).firstChild, 3 );
  2334. * //output: def
  2335. * console.log( newNode.nodeValue );
  2336. * </script>
  2337. * ```
  2338. */
  2339. split:function (node, offset) {
  2340. var doc = node.ownerDocument;
  2341. if (browser.ie && offset == node.nodeValue.length) {
  2342. var next = doc.createTextNode('');
  2343. return domUtils.insertAfter(node, next);
  2344. }
  2345. var retval = node.splitText(offset);
  2346. //ie8下splitText不会跟新childNodes,我们手动触发他的更新
  2347. if (browser.ie8) {
  2348. var tmpNode = doc.createTextNode('');
  2349. domUtils.insertAfter(retval, tmpNode);
  2350. domUtils.remove(tmpNode);
  2351. }
  2352. return retval;
  2353. },
  2354. /**
  2355. * 检测文本节点textNode是否为空节点(包括空格、换行、占位符等字符)
  2356. * @method isWhitespace
  2357. * @param { Node } node 需要检测的节点对象
  2358. * @return { Boolean } 检测的节点是否为空
  2359. * @example
  2360. * ```html
  2361. * <div id="test">
  2362. *
  2363. * </div>
  2364. * <script>
  2365. * //output: true
  2366. * console.log( UE.dom.domUtils.isWhitespace( document.getElementById("test").firstChild ) );
  2367. * </script>
  2368. * ```
  2369. */
  2370. isWhitespace:function (node) {
  2371. return !new RegExp('[^ \t\n\r' + domUtils.fillChar + ']').test(node.nodeValue);
  2372. },
  2373. /**
  2374. * 获取元素element相对于viewport的位置坐标
  2375. * @method getXY
  2376. * @param { Node } element 需要计算位置的节点对象
  2377. * @return { Object } 返回形如{x:left,y:top}的一个key-value映射对象, 其中键x代表水平偏移距离,
  2378. * y代表垂直偏移距离。
  2379. *
  2380. * @example
  2381. * ```javascript
  2382. * var location = UE.dom.domUtils.getXY( document.getElementById("test") );
  2383. * //output: test的坐标为: 12, 24
  2384. * console.log( 'test的坐标为: ', location.x, ',', location.y );
  2385. * ```
  2386. */
  2387. getXY:function (element) {
  2388. var x = 0, y = 0;
  2389. while (element.offsetParent) {
  2390. y += element.offsetTop;
  2391. x += element.offsetLeft;
  2392. element = element.offsetParent;
  2393. }
  2394. return { 'x':x, 'y':y};
  2395. },
  2396. /**
  2397. * 为元素element绑定原生DOM事件,type为事件类型,handler为处理函数
  2398. * @method on
  2399. * @param { Node } element 需要绑定事件的节点对象
  2400. * @param { String } type 绑定的事件类型
  2401. * @param { Function } handler 事件处理器
  2402. * @example
  2403. * ```javascript
  2404. * UE.dom.domUtils.on(document.body,"click",function(e){
  2405. * //e为事件对象,this为被点击元素对戏那个
  2406. * });
  2407. * ```
  2408. */
  2409. /**
  2410. * 为元素element绑定原生DOM事件,type为事件类型,handler为处理函数
  2411. * @method on
  2412. * @param { Node } element 需要绑定事件的节点对象
  2413. * @param { Array } type 绑定的事件类型数组
  2414. * @param { Function } handler 事件处理器
  2415. * @example
  2416. * ```javascript
  2417. * UE.dom.domUtils.on(document.body,["click","mousedown"],function(evt){
  2418. * //evt为事件对象,this为被点击元素对象
  2419. * });
  2420. * ```
  2421. */
  2422. on:function (element, type, handler) {
  2423. var types = utils.isArray(type) ? type : utils.trim(type).split(/\s+/),
  2424. k = types.length;
  2425. if (k) while (k--) {
  2426. type = types[k];
  2427. if (element.addEventListener) {
  2428. element.addEventListener(type, handler, false);
  2429. } else {
  2430. if (!handler._d) {
  2431. handler._d = {
  2432. els : []
  2433. };
  2434. }
  2435. var key = type + handler.toString(),index = utils.indexOf(handler._d.els,element);
  2436. if (!handler._d[key] || index == -1) {
  2437. if(index == -1){
  2438. handler._d.els.push(element);
  2439. }
  2440. if(!handler._d[key]){
  2441. handler._d[key] = function (evt) {
  2442. return handler.call(evt.srcElement, evt || window.event);
  2443. };
  2444. }
  2445. element.attachEvent('on' + type, handler._d[key]);
  2446. }
  2447. }
  2448. }
  2449. element = null;
  2450. },
  2451. /**
  2452. * 解除DOM事件绑定
  2453. * @method un
  2454. * @param { Node } element 需要解除事件绑定的节点对象
  2455. * @param { String } type 需要接触绑定的事件类型
  2456. * @param { Function } handler 对应的事件处理器
  2457. * @example
  2458. * ```javascript
  2459. * UE.dom.domUtils.un(document.body,"click",function(evt){
  2460. * //evt为事件对象,this为被点击元素对象
  2461. * });
  2462. * ```
  2463. */
  2464. /**
  2465. * 解除DOM事件绑定
  2466. * @method un
  2467. * @param { Node } element 需要解除事件绑定的节点对象
  2468. * @param { Array } type 需要接触绑定的事件类型数组
  2469. * @param { Function } handler 对应的事件处理器
  2470. * @example
  2471. * ```javascript
  2472. * UE.dom.domUtils.un(document.body, ["click","mousedown"],function(evt){
  2473. * //evt为事件对象,this为被点击元素对象
  2474. * });
  2475. * ```
  2476. */
  2477. un:function (element, type, handler) {
  2478. var types = utils.isArray(type) ? type : utils.trim(type).split(/\s+/),
  2479. k = types.length;
  2480. if (k) while (k--) {
  2481. type = types[k];
  2482. if (element.removeEventListener) {
  2483. element.removeEventListener(type, handler, false);
  2484. } else {
  2485. var key = type + handler.toString();
  2486. try{
  2487. element.detachEvent('on' + type, handler._d ? handler._d[key] : handler);
  2488. }catch(e){}
  2489. if (handler._d && handler._d[key]) {
  2490. var index = utils.indexOf(handler._d.els,element);
  2491. if(index!=-1){
  2492. handler._d.els.splice(index,1);
  2493. }
  2494. handler._d.els.length == 0 && delete handler._d[key];
  2495. }
  2496. }
  2497. }
  2498. },
  2499. /**
  2500. * 比较节点nodeA与节点nodeB是否具有相同的标签名、属性名以及属性值
  2501. * @method isSameElement
  2502. * @param { Node } nodeA 需要比较的节点
  2503. * @param { Node } nodeB 需要比较的节点
  2504. * @return { Boolean } 两个节点是否具有相同的标签名、属性名以及属性值
  2505. * @example
  2506. * ```html
  2507. * <span style="font-size:12px">ssss</span>
  2508. * <span style="font-size:12px">bbbbb</span>
  2509. * <span style="font-size:13px">ssss</span>
  2510. * <span style="font-size:14px">bbbbb</span>
  2511. *
  2512. * <script>
  2513. *
  2514. * var nodes = document.getElementsByTagName( "span" );
  2515. *
  2516. * //output: true
  2517. * console.log( UE.dom.domUtils.isSameElement( nodes[0], nodes[1] ) );
  2518. *
  2519. * //output: false
  2520. * console.log( UE.dom.domUtils.isSameElement( nodes[2], nodes[3] ) );
  2521. *
  2522. * </script>
  2523. * ```
  2524. */
  2525. isSameElement:function (nodeA, nodeB) {
  2526. if (nodeA.tagName != nodeB.tagName) {
  2527. return false;
  2528. }
  2529. var thisAttrs = nodeA.attributes,
  2530. otherAttrs = nodeB.attributes;
  2531. if (!ie && thisAttrs.length != otherAttrs.length) {
  2532. return false;
  2533. }
  2534. var attrA, attrB, al = 0, bl = 0;
  2535. for (var i = 0; attrA = thisAttrs[i++];) {
  2536. if (attrA.nodeName == 'style') {
  2537. if (attrA.specified) {
  2538. al++;
  2539. }
  2540. if (domUtils.isSameStyle(nodeA, nodeB)) {
  2541. continue;
  2542. } else {
  2543. return false;
  2544. }
  2545. }
  2546. if (ie) {
  2547. if (attrA.specified) {
  2548. al++;
  2549. attrB = otherAttrs.getNamedItem(attrA.nodeName);
  2550. } else {
  2551. continue;
  2552. }
  2553. } else {
  2554. attrB = nodeB.attributes[attrA.nodeName];
  2555. }
  2556. if (!attrB.specified || attrA.nodeValue != attrB.nodeValue) {
  2557. return false;
  2558. }
  2559. }
  2560. // 有可能attrB的属性包含了attrA的属性之外还有自己的属性
  2561. if (ie) {
  2562. for (i = 0; attrB = otherAttrs[i++];) {
  2563. if (attrB.specified) {
  2564. bl++;
  2565. }
  2566. }
  2567. if (al != bl) {
  2568. return false;
  2569. }
  2570. }
  2571. return true;
  2572. },
  2573. /**
  2574. * 判断节点nodeA与节点nodeB的元素的style属性是否一致
  2575. * @method isSameStyle
  2576. * @param { Node } nodeA 需要比较的节点
  2577. * @param { Node } nodeB 需要比较的节点
  2578. * @return { Boolean } 两个节点是否具有相同的style属性值
  2579. * @example
  2580. * ```html
  2581. * <span style="font-size:12px">ssss</span>
  2582. * <span style="font-size:12px">bbbbb</span>
  2583. * <span style="font-size:13px">ssss</span>
  2584. * <span style="font-size:14px">bbbbb</span>
  2585. *
  2586. * <script>
  2587. *
  2588. * var nodes = document.getElementsByTagName( "span" );
  2589. *
  2590. * //output: true
  2591. * console.log( UE.dom.domUtils.isSameStyle( nodes[0], nodes[1] ) );
  2592. *
  2593. * //output: false
  2594. * console.log( UE.dom.domUtils.isSameStyle( nodes[2], nodes[3] ) );
  2595. *
  2596. * </script>
  2597. * ```
  2598. */
  2599. isSameStyle:function (nodeA, nodeB) {
  2600. var styleA = nodeA.style.cssText.replace(/( ?; ?)/g, ';').replace(/( ?: ?)/g, ':'),
  2601. styleB = nodeB.style.cssText.replace(/( ?; ?)/g, ';').replace(/( ?: ?)/g, ':');
  2602. if (browser.opera) {
  2603. styleA = nodeA.style;
  2604. styleB = nodeB.style;
  2605. if (styleA.length != styleB.length)
  2606. return false;
  2607. for (var p in styleA) {
  2608. if (/^(\d+|csstext)$/i.test(p)) {
  2609. continue;
  2610. }
  2611. if (styleA[p] != styleB[p]) {
  2612. return false;
  2613. }
  2614. }
  2615. return true;
  2616. }
  2617. if (!styleA || !styleB) {
  2618. return styleA == styleB;
  2619. }
  2620. styleA = styleA.split(';');
  2621. styleB = styleB.split(';');
  2622. if (styleA.length != styleB.length) {
  2623. return false;
  2624. }
  2625. for (var i = 0, ci; ci = styleA[i++];) {
  2626. if (utils.indexOf(styleB, ci) == -1) {
  2627. return false;
  2628. }
  2629. }
  2630. return true;
  2631. },
  2632. /**
  2633. * 检查节点node是否为block元素
  2634. * @method isBlockElm
  2635. * @param { Node } node 需要检测的节点对象
  2636. * @return { Boolean } 是否是block元素节点
  2637. * @warning 该方法的判断规则如下: 如果该元素原本是block元素, 则不论该元素当前的css样式是什么都会返回true;
  2638. * 否则,检测该元素的css样式, 如果该元素当前是block元素, 则返回true。 其余情况下都返回false。
  2639. * @example
  2640. * ```html
  2641. * <span id="test1" style="display: block"></span>
  2642. * <span id="test2"></span>
  2643. * <div id="test3" style="display: inline"></div>
  2644. *
  2645. * <script>
  2646. *
  2647. * //output: true
  2648. * console.log( UE.dom.domUtils.isBlockElm( document.getElementById("test1") ) );
  2649. *
  2650. * //output: false
  2651. * console.log( UE.dom.domUtils.isBlockElm( document.getElementById("test2") ) );
  2652. *
  2653. * //output: true
  2654. * console.log( UE.dom.domUtils.isBlockElm( document.getElementById("test3") ) );
  2655. *
  2656. * </script>
  2657. * ```
  2658. */
  2659. isBlockElm:function (node) {
  2660. return node.nodeType == 1 && (dtd.$block[node.tagName] || styleBlock[domUtils.getComputedStyle(node, 'display')]) && !dtd.$nonChild[node.tagName];
  2661. },
  2662. /**
  2663. * 检测node节点是否为body节点
  2664. * @method isBody
  2665. * @param { Element } node 需要检测的dom元素
  2666. * @return { Boolean } 给定的元素是否是body元素
  2667. * @example
  2668. * ```javascript
  2669. * //output: true
  2670. * console.log( UE.dom.domUtils.isBody( document.body ) );
  2671. * ```
  2672. */
  2673. isBody:function (node) {
  2674. return node && node.nodeType == 1 && node.tagName.toLowerCase() == 'body';
  2675. },
  2676. /**
  2677. * 以node节点为分界,将该节点的指定祖先节点parent拆分成两个独立的节点,
  2678. * 拆分形成的两个节点之间是node节点
  2679. * @method breakParent
  2680. * @param { Node } node 作为分界的节点对象
  2681. * @param { Node } parent 该节点必须是node节点的祖先节点, 且是block节点。
  2682. * @return { Node } 给定的node分界节点
  2683. * @example
  2684. * ```javascript
  2685. *
  2686. * var node = document.createElement("span"),
  2687. * wrapNode = document.createElement( "div" ),
  2688. * parent = document.createElement("p");
  2689. *
  2690. * parent.appendChild( node );
  2691. * wrapNode.appendChild( parent );
  2692. *
  2693. * //拆分前
  2694. * //output: <p><span></span></p>
  2695. * console.log( wrapNode.innerHTML );
  2696. *
  2697. *
  2698. * UE.dom.domUtils.breakParent( node, parent );
  2699. * //拆分后
  2700. * //output: <p></p><span></span><p></p>
  2701. * console.log( wrapNode.innerHTML );
  2702. *
  2703. * ```
  2704. */
  2705. breakParent:function (node, parent) {
  2706. var tmpNode,
  2707. parentClone = node,
  2708. clone = node,
  2709. leftNodes,
  2710. rightNodes;
  2711. do {
  2712. parentClone = parentClone.parentNode;
  2713. if (leftNodes) {
  2714. tmpNode = parentClone.cloneNode(false);
  2715. tmpNode.appendChild(leftNodes);
  2716. leftNodes = tmpNode;
  2717. tmpNode = parentClone.cloneNode(false);
  2718. tmpNode.appendChild(rightNodes);
  2719. rightNodes = tmpNode;
  2720. } else {
  2721. leftNodes = parentClone.cloneNode(false);
  2722. rightNodes = leftNodes.cloneNode(false);
  2723. }
  2724. while (tmpNode = clone.previousSibling) {
  2725. leftNodes.insertBefore(tmpNode, leftNodes.firstChild);
  2726. }
  2727. while (tmpNode = clone.nextSibling) {
  2728. rightNodes.appendChild(tmpNode);
  2729. }
  2730. clone = parentClone;
  2731. } while (parent !== parentClone);
  2732. tmpNode = parent.parentNode;
  2733. tmpNode.insertBefore(leftNodes, parent);
  2734. tmpNode.insertBefore(rightNodes, parent);
  2735. tmpNode.insertBefore(node, rightNodes);
  2736. domUtils.remove(parent);
  2737. return node;
  2738. },
  2739. /**
  2740. * 检查节点node是否是空inline节点
  2741. * @method isEmptyInlineElement
  2742. * @param { Node } node 需要检测的节点对象
  2743. * @return { Number } 如果给定的节点是空的inline节点, 则返回1, 否则返回0。
  2744. * @example
  2745. * ```html
  2746. * <b><i></i></b> => 1
  2747. * <b><i></i><u></u></b> => 1
  2748. * <b></b> => 1
  2749. * <b>xx<i></i></b> => 0
  2750. * ```
  2751. */
  2752. isEmptyInlineElement:function (node) {
  2753. if (node.nodeType != 1 || !dtd.$removeEmpty[ node.tagName ]) {
  2754. return 0;
  2755. }
  2756. node = node.firstChild;
  2757. while (node) {
  2758. //如果是创建的bookmark就跳过
  2759. if (domUtils.isBookmarkNode(node)) {
  2760. return 0;
  2761. }
  2762. if (node.nodeType == 1 && !domUtils.isEmptyInlineElement(node) ||
  2763. node.nodeType == 3 && !domUtils.isWhitespace(node)
  2764. ) {
  2765. return 0;
  2766. }
  2767. node = node.nextSibling;
  2768. }
  2769. return 1;
  2770. },
  2771. /**
  2772. * 删除node节点下首尾两端的空白文本子节点
  2773. * @method trimWhiteTextNode
  2774. * @param { Element } node 需要执行删除操作的元素对象
  2775. * @example
  2776. * ```javascript
  2777. * var node = document.createElement("div");
  2778. *
  2779. * node.appendChild( document.createTextNode( "" ) );
  2780. *
  2781. * node.appendChild( document.createElement("div") );
  2782. *
  2783. * node.appendChild( document.createTextNode( "" ) );
  2784. *
  2785. * //3
  2786. * console.log( node.childNodes.length );
  2787. *
  2788. * UE.dom.domUtils.trimWhiteTextNode( node );
  2789. *
  2790. * //1
  2791. * console.log( node.childNodes.length );
  2792. * ```
  2793. */
  2794. trimWhiteTextNode:function (node) {
  2795. function remove(dir) {
  2796. var child;
  2797. while ((child = node[dir]) && child.nodeType == 3 && domUtils.isWhitespace(child)) {
  2798. node.removeChild(child);
  2799. }
  2800. }
  2801. remove('firstChild');
  2802. remove('lastChild');
  2803. },
  2804. /**
  2805. * 合并node节点下相同的子节点
  2806. * @name mergeChild
  2807. * @desc
  2808. * UE.dom.domUtils.mergeChild(node,tagName) //tagName要合并的子节点的标签
  2809. * @example
  2810. * <p><span style="font-size:12px;">xx<span style="font-size:12px;">aa</span>xx</span></p>
  2811. * ==> UE.dom.domUtils.mergeChild(node,'span')
  2812. * <p><span style="font-size:12px;">xxaaxx</span></p>
  2813. */
  2814. mergeChild:function (node, tagName, attrs) {
  2815. var list = domUtils.getElementsByTagName(node, node.tagName.toLowerCase());
  2816. for (var i = 0, ci; ci = list[i++];) {
  2817. if (!ci.parentNode || domUtils.isBookmarkNode(ci)) {
  2818. continue;
  2819. }
  2820. //span单独处理
  2821. if (ci.tagName.toLowerCase() == 'span') {
  2822. if (node === ci.parentNode) {
  2823. domUtils.trimWhiteTextNode(node);
  2824. if (node.childNodes.length == 1) {
  2825. node.style.cssText = ci.style.cssText + ";" + node.style.cssText;
  2826. domUtils.remove(ci, true);
  2827. continue;
  2828. }
  2829. }
  2830. ci.style.cssText = node.style.cssText + ';' + ci.style.cssText;
  2831. if (attrs) {
  2832. var style = attrs.style;
  2833. if (style) {
  2834. style = style.split(';');
  2835. for (var j = 0, s; s = style[j++];) {
  2836. ci.style[utils.cssStyleToDomStyle(s.split(':')[0])] = s.split(':')[1];
  2837. }
  2838. }
  2839. }
  2840. if (domUtils.isSameStyle(ci, node)) {
  2841. domUtils.remove(ci, true);
  2842. }
  2843. continue;
  2844. }
  2845. if (domUtils.isSameElement(node, ci)) {
  2846. domUtils.remove(ci, true);
  2847. }
  2848. }
  2849. },
  2850. /**
  2851. * 原生方法getElementsByTagName的封装
  2852. * @method getElementsByTagName
  2853. * @param { Node } node 目标节点对象
  2854. * @param { String } tagName 需要查找的节点的tagName, 多个tagName以空格分割
  2855. * @return { Array } 符合条件的节点集合
  2856. */
  2857. getElementsByTagName:function (node, name,filter) {
  2858. if(filter && utils.isString(filter)){
  2859. var className = filter;
  2860. filter = function(node){return domUtils.hasClass(node,className)}
  2861. }
  2862. name = utils.trim(name).replace(/[ ]{2,}/g,' ').split(' ');
  2863. var arr = [];
  2864. for(var n = 0,ni;ni=name[n++];){
  2865. var list = node.getElementsByTagName(ni);
  2866. for (var i = 0, ci; ci = list[i++];) {
  2867. if(!filter || filter(ci))
  2868. arr.push(ci);
  2869. }
  2870. }
  2871. return arr;
  2872. },
  2873. /**
  2874. * 将节点node提取到父节点上
  2875. * @method mergeToParent
  2876. * @param { Element } node 需要提取的元素对象
  2877. * @example
  2878. * ```html
  2879. * <div id="parent">
  2880. * <div id="sub">
  2881. * <span id="child"></span>
  2882. * </div>
  2883. * </div>
  2884. *
  2885. * <script>
  2886. *
  2887. * var child = document.getElementById( "child" );
  2888. *
  2889. * //output: sub
  2890. * console.log( child.parentNode.id );
  2891. *
  2892. * UE.dom.domUtils.mergeToParent( child );
  2893. *
  2894. * //output: parent
  2895. * console.log( child.parentNode.id );
  2896. *
  2897. * </script>
  2898. * ```
  2899. */
  2900. mergeToParent:function (node) {
  2901. var parent = node.parentNode;
  2902. while (parent && dtd.$removeEmpty[parent.tagName]) {
  2903. if (parent.tagName == node.tagName || parent.tagName == 'A') {//针对a标签单独处理
  2904. domUtils.trimWhiteTextNode(parent);
  2905. //span需要特殊处理 不处理这样的情况 <span stlye="color:#fff">xxx<span style="color:#ccc">xxx</span>xxx</span>
  2906. if (parent.tagName == 'SPAN' && !domUtils.isSameStyle(parent, node)
  2907. || (parent.tagName == 'A' && node.tagName == 'SPAN')) {
  2908. if (parent.childNodes.length > 1 || parent !== node.parentNode) {
  2909. node.style.cssText = parent.style.cssText + ";" + node.style.cssText;
  2910. parent = parent.parentNode;
  2911. continue;
  2912. } else {
  2913. parent.style.cssText += ";" + node.style.cssText;
  2914. //trace:952 a标签要保持下划线
  2915. if (parent.tagName == 'A') {
  2916. parent.style.textDecoration = 'underline';
  2917. }
  2918. }
  2919. }
  2920. if (parent.tagName != 'A') {
  2921. parent === node.parentNode && domUtils.remove(node, true);
  2922. break;
  2923. }
  2924. }
  2925. parent = parent.parentNode;
  2926. }
  2927. },
  2928. /**
  2929. * 合并节点node的左右兄弟节点
  2930. * @method mergeSibling
  2931. * @param { Element } node 需要合并的目标节点
  2932. * @example
  2933. * ```html
  2934. * <b>xxxx</b><b id="test">ooo</b><b>xxxx</b>
  2935. *
  2936. * <script>
  2937. * var demoNode = document.getElementById("test");
  2938. * UE.dom.domUtils.mergeSibling( demoNode );
  2939. * //output: xxxxoooxxxx
  2940. * console.log( demoNode.innerHTML );
  2941. * </script>
  2942. * ```
  2943. */
  2944. /**
  2945. * 合并节点node的左右兄弟节点, 可以根据给定的条件选择是否忽略合并左节点。
  2946. * @method mergeSibling
  2947. * @param { Element } node 需要合并的目标节点
  2948. * @param { Boolean } ignorePre 是否忽略合并左节点
  2949. * @example
  2950. * ```html
  2951. * <b>xxxx</b><b id="test">ooo</b><b>xxxx</b>
  2952. *
  2953. * <script>
  2954. * var demoNode = document.getElementById("test");
  2955. * UE.dom.domUtils.mergeSibling( demoNode, true );
  2956. * //output: oooxxxx
  2957. * console.log( demoNode.innerHTML );
  2958. * </script>
  2959. * ```
  2960. */
  2961. /**
  2962. * 合并节点node的左右兄弟节点,可以根据给定的条件选择是否忽略合并左右节点。
  2963. * @method mergeSibling
  2964. * @param { Element } node 需要合并的目标节点
  2965. * @param { Boolean } ignorePre 是否忽略合并左节点
  2966. * @param { Boolean } ignoreNext 是否忽略合并右节点
  2967. * @remind 如果同时忽略左右节点, 则该操作什么也不会做
  2968. * @example
  2969. * ```html
  2970. * <b>xxxx</b><b id="test">ooo</b><b>xxxx</b>
  2971. *
  2972. * <script>
  2973. * var demoNode = document.getElementById("test");
  2974. * UE.dom.domUtils.mergeSibling( demoNode, false, true );
  2975. * //output: xxxxooo
  2976. * console.log( demoNode.innerHTML );
  2977. * </script>
  2978. * ```
  2979. */
  2980. mergeSibling:function (node, ignorePre, ignoreNext) {
  2981. function merge(rtl, start, node) {
  2982. var next;
  2983. if ((next = node[rtl]) && !domUtils.isBookmarkNode(next) && next.nodeType == 1 && domUtils.isSameElement(node, next)) {
  2984. while (next.firstChild) {
  2985. if (start == 'firstChild') {
  2986. node.insertBefore(next.lastChild, node.firstChild);
  2987. } else {
  2988. node.appendChild(next.firstChild);
  2989. }
  2990. }
  2991. domUtils.remove(next);
  2992. }
  2993. }
  2994. !ignorePre && merge('previousSibling', 'firstChild', node);
  2995. !ignoreNext && merge('nextSibling', 'lastChild', node);
  2996. },
  2997. /**
  2998. * 设置节点node及其子节点不会被选中
  2999. * @method unSelectable
  3000. * @param { Element } node 需要执行操作的dom元素
  3001. * @remind 执行该操作后的节点, 将不能被鼠标选中
  3002. * @example
  3003. * ```javascript
  3004. * UE.dom.domUtils.unSelectable( document.body );
  3005. * ```
  3006. */
  3007. unSelectable:ie && browser.ie9below || browser.opera ? function (node) {
  3008. //for ie9
  3009. node.onselectstart = function () {
  3010. return false;
  3011. };
  3012. node.onclick = node.onkeyup = node.onkeydown = function () {
  3013. return false;
  3014. };
  3015. node.unselectable = 'on';
  3016. node.setAttribute("unselectable", "on");
  3017. for (var i = 0, ci; ci = node.all[i++];) {
  3018. switch (ci.tagName.toLowerCase()) {
  3019. case 'iframe' :
  3020. case 'textarea' :
  3021. case 'input' :
  3022. case 'select' :
  3023. break;
  3024. default :
  3025. ci.unselectable = 'on';
  3026. node.setAttribute("unselectable", "on");
  3027. }
  3028. }
  3029. } : function (node) {
  3030. node.style.MozUserSelect =
  3031. node.style.webkitUserSelect =
  3032. node.style.msUserSelect =
  3033. node.style.KhtmlUserSelect = 'none';
  3034. },
  3035. /**
  3036. * 删除节点node上的指定属性名称的属性
  3037. * @method removeAttributes
  3038. * @param { Node } node 需要删除属性的节点对象
  3039. * @param { String } attrNames 可以是空格隔开的多个属性名称,该操作将会依次删除相应的属性
  3040. * @example
  3041. * ```html
  3042. * <div id="wrap">
  3043. * <span style="font-size:14px;" id="test" name="followMe">xxxxx</span>
  3044. * </div>
  3045. *
  3046. * <script>
  3047. *
  3048. * UE.dom.domUtils.removeAttributes( document.getElementById( "test" ), "id name" );
  3049. *
  3050. * //output: <span style="font-size:14px;">xxxxx</span>
  3051. * console.log( document.getElementById("wrap").innerHTML );
  3052. *
  3053. * </script>
  3054. * ```
  3055. */
  3056. /**
  3057. * 删除节点node上的指定属性名称的属性
  3058. * @method removeAttributes
  3059. * @param { Node } node 需要删除属性的节点对象
  3060. * @param { Array } attrNames 需要删除的属性名数组
  3061. * @example
  3062. * ```html
  3063. * <div id="wrap">
  3064. * <span style="font-size:14px;" id="test" name="followMe">xxxxx</span>
  3065. * </div>
  3066. *
  3067. * <script>
  3068. *
  3069. * UE.dom.domUtils.removeAttributes( document.getElementById( "test" ), ["id", "name"] );
  3070. *
  3071. * //output: <span style="font-size:14px;">xxxxx</span>
  3072. * console.log( document.getElementById("wrap").innerHTML );
  3073. *
  3074. * </script>
  3075. * ```
  3076. */
  3077. removeAttributes:function (node, attrNames) {
  3078. attrNames = utils.isArray(attrNames) ? attrNames : utils.trim(attrNames).replace(/[ ]{2,}/g,' ').split(' ');
  3079. for (var i = 0, ci; ci = attrNames[i++];) {
  3080. ci = attrFix[ci] || ci;
  3081. switch (ci) {
  3082. case 'className':
  3083. node[ci] = '';
  3084. break;
  3085. case 'style':
  3086. node.style.cssText = '';
  3087. var val = node.getAttributeNode('style');
  3088. !browser.ie && val && node.removeAttributeNode(val);
  3089. }
  3090. node.removeAttribute(ci);
  3091. }
  3092. },
  3093. /**
  3094. * 在doc下创建一个标签名为tag,属性为attrs的元素
  3095. * @method createElement
  3096. * @param { DomDocument } doc 新创建的元素属于该document节点创建
  3097. * @param { String } tagName 需要创建的元素的标签名
  3098. * @param { Object } attrs 新创建的元素的属性key-value集合
  3099. * @return { Element } 新创建的元素对象
  3100. * @example
  3101. * ```javascript
  3102. * var ele = UE.dom.domUtils.createElement( document, 'div', {
  3103. * id: 'test'
  3104. * } );
  3105. *
  3106. * //output: DIV
  3107. * console.log( ele.tagName );
  3108. *
  3109. * //output: test
  3110. * console.log( ele.id );
  3111. *
  3112. * ```
  3113. */
  3114. createElement:function (doc, tag, attrs) {
  3115. return domUtils.setAttributes(doc.createElement(tag), attrs)
  3116. },
  3117. /**
  3118. * 为节点node添加属性attrs,attrs为属性键值对
  3119. * @method setAttributes
  3120. * @param { Element } node 需要设置属性的元素对象
  3121. * @param { Object } attrs 需要设置的属性名-值对
  3122. * @return { Element } 设置属性的元素对象
  3123. * @example
  3124. * ```html
  3125. * <span id="test"></span>
  3126. *
  3127. * <script>
  3128. *
  3129. * var testNode = UE.dom.domUtils.setAttributes( document.getElementById( "test" ), {
  3130. * id: 'demo'
  3131. * } );
  3132. *
  3133. * //output: demo
  3134. * console.log( testNode.id );
  3135. *
  3136. * </script>
  3137. *
  3138. */
  3139. setAttributes:function (node, attrs) {
  3140. for (var attr in attrs) {
  3141. if(attrs.hasOwnProperty(attr)){
  3142. var value = attrs[attr];
  3143. switch (attr) {
  3144. case 'class':
  3145. //ie下要这样赋值,setAttribute不起作用
  3146. node.className = value;
  3147. break;
  3148. case 'style' :
  3149. node.style.cssText = node.style.cssText + ";" + value;
  3150. break;
  3151. case 'innerHTML':
  3152. node[attr] = value;
  3153. break;
  3154. case 'value':
  3155. node.value = value;
  3156. break;
  3157. default:
  3158. node.setAttribute(attrFix[attr] || attr, value);
  3159. }
  3160. }
  3161. }
  3162. return node;
  3163. },
  3164. /**
  3165. * 获取元素element经过计算后的样式值
  3166. * @method getComputedStyle
  3167. * @param { Element } element 需要获取样式的元素对象
  3168. * @param { String } styleName 需要获取的样式名
  3169. * @return { String } 获取到的样式值
  3170. * @example
  3171. * ```html
  3172. * <style type="text/css">
  3173. * #test {
  3174. * font-size: 15px;
  3175. * }
  3176. * </style>
  3177. *
  3178. * <span id="test"></span>
  3179. *
  3180. * <script>
  3181. * //output: 15px
  3182. * console.log( UE.dom.domUtils.getComputedStyle( document.getElementById( "test" ), 'font-size' ) );
  3183. * </script>
  3184. * ```
  3185. */
  3186. getComputedStyle:function (element, styleName) {
  3187. //一下的属性单独处理
  3188. var pros = 'width height top left';
  3189. if(pros.indexOf(styleName) > -1){
  3190. return element['offset' + styleName.replace(/^\w/,function(s){return s.toUpperCase()})] + 'px';
  3191. }
  3192. //忽略文本节点
  3193. if (element.nodeType == 3) {
  3194. element = element.parentNode;
  3195. }
  3196. //ie下font-size若body下定义了font-size,则从currentStyle里会取到这个font-size. 取不到实际值,故此修改.
  3197. if (browser.ie && browser.version < 9 && styleName == 'font-size' && !element.style.fontSize &&
  3198. !dtd.$empty[element.tagName] && !dtd.$nonChild[element.tagName]) {
  3199. var span = element.ownerDocument.createElement('span');
  3200. span.style.cssText = 'padding:0;border:0;font-family:simsun;';
  3201. span.innerHTML = '.';
  3202. element.appendChild(span);
  3203. var result = span.offsetHeight;
  3204. element.removeChild(span);
  3205. span = null;
  3206. return result + 'px';
  3207. }
  3208. try {
  3209. var value = domUtils.getStyle(element, styleName) ||
  3210. (window.getComputedStyle ? domUtils.getWindow(element).getComputedStyle(element, '').getPropertyValue(styleName) :
  3211. ( element.currentStyle || element.style )[utils.cssStyleToDomStyle(styleName)]);
  3212. } catch (e) {
  3213. return "";
  3214. }
  3215. return utils.transUnitToPx(utils.fixColor(styleName, value));
  3216. },
  3217. /**
  3218. * 删除元素element指定的className
  3219. * @method removeClasses
  3220. * @param { Element } ele 需要删除class的元素节点
  3221. * @param { String } classNames 需要删除的className, 多个className之间以空格分开
  3222. * @example
  3223. * ```html
  3224. * <span id="test" class="test1 test2 test3">xxx</span>
  3225. *
  3226. * <script>
  3227. *
  3228. * var testNode = document.getElementById( "test" );
  3229. * UE.dom.domUtils.removeClasses( testNode, "test1 test2" );
  3230. *
  3231. * //output: test3
  3232. * console.log( testNode.className );
  3233. *
  3234. * </script>
  3235. * ```
  3236. */
  3237. /**
  3238. * 删除元素element指定的className
  3239. * @method removeClasses
  3240. * @param { Element } ele 需要删除class的元素节点
  3241. * @param { Array } classNames 需要删除的className数组
  3242. * @example
  3243. * ```html
  3244. * <span id="test" class="test1 test2 test3">xxx</span>
  3245. *
  3246. * <script>
  3247. *
  3248. * var testNode = document.getElementById( "test" );
  3249. * UE.dom.domUtils.removeClasses( testNode, ["test1", "test2"] );
  3250. *
  3251. * //output: test3
  3252. * console.log( testNode.className );
  3253. *
  3254. * </script>
  3255. * ```
  3256. */
  3257. removeClasses:function (elm, classNames) {
  3258. classNames = utils.isArray(classNames) ? classNames :
  3259. utils.trim(classNames).replace(/[ ]{2,}/g,' ').split(' ');
  3260. for(var i = 0,ci,cls = elm.className;ci=classNames[i++];){
  3261. cls = cls.replace(new RegExp('\\b' + ci + '\\b'),'')
  3262. }
  3263. cls = utils.trim(cls).replace(/[ ]{2,}/g,' ');
  3264. if(cls){
  3265. elm.className = cls;
  3266. }else{
  3267. domUtils.removeAttributes(elm,['class']);
  3268. }
  3269. },
  3270. /**
  3271. * 给元素element添加className
  3272. * @method addClass
  3273. * @param { Node } ele 需要增加className的元素
  3274. * @param { String } classNames 需要添加的className, 多个className之间以空格分割
  3275. * @remind 相同的类名不会被重复添加
  3276. * @example
  3277. * ```html
  3278. * <span id="test" class="cls1 cls2"></span>
  3279. *
  3280. * <script>
  3281. * var testNode = document.getElementById("test");
  3282. *
  3283. * UE.dom.domUtils.addClass( testNode, "cls2 cls3 cls4" );
  3284. *
  3285. * //output: cl1 cls2 cls3 cls4
  3286. * console.log( testNode.className );
  3287. *
  3288. * <script>
  3289. * ```
  3290. */
  3291. /**
  3292. * 给元素element添加className
  3293. * @method addClass
  3294. * @param { Node } ele 需要增加className的元素
  3295. * @param { Array } classNames 需要添加的className的数组
  3296. * @remind 相同的类名不会被重复添加
  3297. * @example
  3298. * ```html
  3299. * <span id="test" class="cls1 cls2"></span>
  3300. *
  3301. * <script>
  3302. * var testNode = document.getElementById("test");
  3303. *
  3304. * UE.dom.domUtils.addClass( testNode, ["cls2", "cls3", "cls4"] );
  3305. *
  3306. * //output: cl1 cls2 cls3 cls4
  3307. * console.log( testNode.className );
  3308. *
  3309. * <script>
  3310. * ```
  3311. */
  3312. addClass:function (elm, classNames) {
  3313. if(!elm)return;
  3314. classNames = utils.trim(classNames).replace(/[ ]{2,}/g,' ').split(' ');
  3315. for(var i = 0,ci,cls = elm.className;ci=classNames[i++];){
  3316. if(!new RegExp('\\b' + ci + '\\b').test(cls)){
  3317. cls += ' ' + ci;
  3318. }
  3319. }
  3320. elm.className = utils.trim(cls);
  3321. },
  3322. /**
  3323. * 判断元素element是否包含给定的样式类名className
  3324. * @method hasClass
  3325. * @param { Node } ele 需要检测的元素
  3326. * @param { String } classNames 需要检测的className, 多个className之间用空格分割
  3327. * @return { Boolean } 元素是否包含所有给定的className
  3328. * @example
  3329. * ```html
  3330. * <span id="test1" class="cls1 cls2"></span>
  3331. *
  3332. * <script>
  3333. * var test1 = document.getElementById("test1");
  3334. *
  3335. * //output: false
  3336. * console.log( UE.dom.domUtils.hasClass( test1, "cls2 cls1 cls3" ) );
  3337. *
  3338. * //output: true
  3339. * console.log( UE.dom.domUtils.hasClass( test1, "cls2 cls1" ) );
  3340. * </script>
  3341. * ```
  3342. */
  3343. /**
  3344. * 判断元素element是否包含给定的样式类名className
  3345. * @method hasClass
  3346. * @param { Node } ele 需要检测的元素
  3347. * @param { Array } classNames 需要检测的className数组
  3348. * @return { Boolean } 元素是否包含所有给定的className
  3349. * @example
  3350. * ```html
  3351. * <span id="test1" class="cls1 cls2"></span>
  3352. *
  3353. * <script>
  3354. * var test1 = document.getElementById("test1");
  3355. *
  3356. * //output: false
  3357. * console.log( UE.dom.domUtils.hasClass( test1, [ "cls2", "cls1", "cls3" ] ) );
  3358. *
  3359. * //output: true
  3360. * console.log( UE.dom.domUtils.hasClass( test1, [ "cls2", "cls1" ]) );
  3361. * </script>
  3362. * ```
  3363. */
  3364. hasClass:function (element, className) {
  3365. if(utils.isRegExp(className)){
  3366. return className.test(element.className)
  3367. }
  3368. className = utils.trim(className).replace(/[ ]{2,}/g,' ').split(' ');
  3369. for(var i = 0,ci,cls = element.className;ci=className[i++];){
  3370. if(!new RegExp('\\b' + ci + '\\b','i').test(cls)){
  3371. return false;
  3372. }
  3373. }
  3374. return i - 1 == className.length;
  3375. },
  3376. /**
  3377. * 阻止事件默认行为
  3378. * @method preventDefault
  3379. * @param { Event } evt 需要阻止默认行为的事件对象
  3380. * @example
  3381. * ```javascript
  3382. * UE.dom.domUtils.preventDefault( evt );
  3383. * ```
  3384. */
  3385. preventDefault:function (evt) {
  3386. evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false);
  3387. },
  3388. /**
  3389. * 删除元素element指定的样式
  3390. * @method removeStyle
  3391. * @param { Element } element 需要删除样式的元素
  3392. * @param { String } styleName 需要删除的样式名
  3393. * @example
  3394. * ```html
  3395. * <span id="test" style="color: red; background: blue;"></span>
  3396. *
  3397. * <script>
  3398. *
  3399. * var testNode = document.getElementById("test");
  3400. *
  3401. * UE.dom.domUtils.removeStyle( testNode, 'color' );
  3402. *
  3403. * //output: background: blue;
  3404. * console.log( testNode.style.cssText );
  3405. *
  3406. * </script>
  3407. * ```
  3408. */
  3409. removeStyle:function (element, name) {
  3410. if(browser.ie ){
  3411. //针对color先单独处理一下
  3412. if(name == 'color'){
  3413. name = '(^|;)' + name;
  3414. }
  3415. element.style.cssText = element.style.cssText.replace(new RegExp(name + '[^:]*:[^;]+;?','ig'),'')
  3416. }else{
  3417. if (element.style.removeProperty) {
  3418. element.style.removeProperty (name);
  3419. }else {
  3420. element.style.removeAttribute (utils.cssStyleToDomStyle(name));
  3421. }
  3422. }
  3423. if (!element.style.cssText) {
  3424. domUtils.removeAttributes(element, ['style']);
  3425. }
  3426. },
  3427. /**
  3428. * 获取元素element的style属性的指定值
  3429. * @method getStyle
  3430. * @param { Element } element 需要获取属性值的元素
  3431. * @param { String } styleName 需要获取的style的名称
  3432. * @warning 该方法仅获取元素style属性中所标明的值
  3433. * @return { String } 该元素包含指定的style属性值
  3434. * @example
  3435. * ```html
  3436. * <div id="test" style="color: red;"></div>
  3437. *
  3438. * <script>
  3439. *
  3440. * var testNode = document.getElementById( "test" );
  3441. *
  3442. * //output: red
  3443. * console.log( UE.dom.domUtils.getStyle( testNode, "color" ) );
  3444. *
  3445. * //output: ""
  3446. * console.log( UE.dom.domUtils.getStyle( testNode, "background" ) );
  3447. *
  3448. * </script>
  3449. * ```
  3450. */
  3451. getStyle:function (element, name) {
  3452. var value = element.style[ utils.cssStyleToDomStyle(name) ];
  3453. return utils.fixColor(name, value);
  3454. },
  3455. /**
  3456. * 为元素element设置样式属性值
  3457. * @method setStyle
  3458. * @param { Element } element 需要设置样式的元素
  3459. * @param { String } styleName 样式名
  3460. * @param { String } styleValue 样式值
  3461. * @example
  3462. * ```html
  3463. * <div id="test"></div>
  3464. *
  3465. * <script>
  3466. *
  3467. * var testNode = document.getElementById( "test" );
  3468. *
  3469. * //output: ""
  3470. * console.log( testNode.style.color );
  3471. *
  3472. * UE.dom.domUtils.setStyle( testNode, 'color', 'red' );
  3473. * //output: "red"
  3474. * console.log( testNode.style.color );
  3475. *
  3476. * </script>
  3477. * ```
  3478. */
  3479. setStyle:function (element, name, value) {
  3480. element.style[utils.cssStyleToDomStyle(name)] = value;
  3481. if(!utils.trim(element.style.cssText)){
  3482. this.removeAttributes(element,'style')
  3483. }
  3484. },
  3485. /**
  3486. * 为元素element设置多个样式属性值
  3487. * @method setStyles
  3488. * @param { Element } element 需要设置样式的元素
  3489. * @param { Object } styles 样式名值对
  3490. * @example
  3491. * ```html
  3492. * <div id="test"></div>
  3493. *
  3494. * <script>
  3495. *
  3496. * var testNode = document.getElementById( "test" );
  3497. *
  3498. * //output: ""
  3499. * console.log( testNode.style.color );
  3500. *
  3501. * UE.dom.domUtils.setStyles( testNode, {
  3502. * 'color': 'red'
  3503. * } );
  3504. * //output: "red"
  3505. * console.log( testNode.style.color );
  3506. *
  3507. * </script>
  3508. * ```
  3509. */
  3510. setStyles:function (element, styles) {
  3511. for (var name in styles) {
  3512. if (styles.hasOwnProperty(name)) {
  3513. domUtils.setStyle(element, name, styles[name]);
  3514. }
  3515. }
  3516. },
  3517. /**
  3518. * 删除_moz_dirty属性
  3519. * @private
  3520. * @method removeDirtyAttr
  3521. */
  3522. removeDirtyAttr:function (node) {
  3523. for (var i = 0, ci, nodes = node.getElementsByTagName('*'); ci = nodes[i++];) {
  3524. ci.removeAttribute('_moz_dirty');
  3525. }
  3526. node.removeAttribute('_moz_dirty');
  3527. },
  3528. /**
  3529. * 获取子节点的数量
  3530. * @method getChildCount
  3531. * @param { Element } node 需要检测的元素
  3532. * @return { Number } 给定的node元素的子节点数量
  3533. * @example
  3534. * ```html
  3535. * <div id="test">
  3536. * <span></span>
  3537. * </div>
  3538. *
  3539. * <script>
  3540. *
  3541. * //output: 3
  3542. * console.log( UE.dom.domUtils.getChildCount( document.getElementById("test") ) );
  3543. *
  3544. * </script>
  3545. * ```
  3546. */
  3547. /**
  3548. * 根据给定的过滤规则, 获取符合条件的子节点的数量
  3549. * @method getChildCount
  3550. * @param { Element } node 需要检测的元素
  3551. * @param { Function } fn 过滤器, 要求对符合条件的子节点返回true, 反之则要求返回false
  3552. * @return { Number } 符合过滤条件的node元素的子节点数量
  3553. * @example
  3554. * ```html
  3555. * <div id="test">
  3556. * <span></span>
  3557. * </div>
  3558. *
  3559. * <script>
  3560. *
  3561. * //output: 1
  3562. * console.log( UE.dom.domUtils.getChildCount( document.getElementById("test"), function ( node ) {
  3563. *
  3564. * return node.nodeType === 1;
  3565. *
  3566. * } ) );
  3567. *
  3568. * </script>
  3569. * ```
  3570. */
  3571. getChildCount:function (node, fn) {
  3572. var count = 0, first = node.firstChild;
  3573. fn = fn || function () {
  3574. return 1;
  3575. };
  3576. while (first) {
  3577. if (fn(first)) {
  3578. count++;
  3579. }
  3580. first = first.nextSibling;
  3581. }
  3582. return count;
  3583. },
  3584. /**
  3585. * 判断给定节点是否为空节点
  3586. * @method isEmptyNode
  3587. * @param { Node } node 需要检测的节点对象
  3588. * @return { Boolean } 节点是否为空
  3589. * @example
  3590. * ```javascript
  3591. * UE.dom.domUtils.isEmptyNode( document.body );
  3592. * ```
  3593. */
  3594. isEmptyNode:function (node) {
  3595. return !node.firstChild || domUtils.getChildCount(node, function (node) {
  3596. return !domUtils.isBr(node) && !domUtils.isBookmarkNode(node) && !domUtils.isWhitespace(node)
  3597. }) == 0
  3598. },
  3599. clearSelectedArr:function (nodes) {
  3600. var node;
  3601. while (node = nodes.pop()) {
  3602. domUtils.removeAttributes(node, ['class']);
  3603. }
  3604. },
  3605. /**
  3606. * 将显示区域滚动到指定节点的位置
  3607. * @method scrollToView
  3608. * @param {Node} node 节点
  3609. * @param {window} win window对象
  3610. * @param {Number} offsetTop 距离上方的偏移量
  3611. */
  3612. scrollToView:function (node, win, offsetTop) {
  3613. var getViewPaneSize = function () {
  3614. var doc = win.document,
  3615. mode = doc.compatMode == 'CSS1Compat';
  3616. return {
  3617. width:( mode ? doc.documentElement.clientWidth : doc.body.clientWidth ) || 0,
  3618. height:( mode ? doc.documentElement.clientHeight : doc.body.clientHeight ) || 0
  3619. };
  3620. },
  3621. getScrollPosition = function (win) {
  3622. if ('pageXOffset' in win) {
  3623. return {
  3624. x:win.pageXOffset || 0,
  3625. y:win.pageYOffset || 0
  3626. };
  3627. }
  3628. else {
  3629. var doc = win.document;
  3630. return {
  3631. x:doc.documentElement.scrollLeft || doc.body.scrollLeft || 0,
  3632. y:doc.documentElement.scrollTop || doc.body.scrollTop || 0
  3633. };
  3634. }
  3635. };
  3636. var winHeight = getViewPaneSize().height, offset = winHeight * -1 + offsetTop;
  3637. offset += (node.offsetHeight || 0);
  3638. var elementPosition = domUtils.getXY(node);
  3639. offset += elementPosition.y;
  3640. var currentScroll = getScrollPosition(win).y;
  3641. // offset += 50;
  3642. if (offset > currentScroll || offset < currentScroll - winHeight) {
  3643. win.scrollTo(0, offset + (offset < 0 ? -20 : 20));
  3644. }
  3645. },
  3646. /**
  3647. * 判断给定节点是否为br
  3648. * @method isBr
  3649. * @param { Node } node 需要判断的节点对象
  3650. * @return { Boolean } 给定的节点是否是br节点
  3651. */
  3652. isBr:function (node) {
  3653. return node.nodeType == 1 && node.tagName == 'BR';
  3654. },
  3655. /**
  3656. * 判断给定的节点是否是一个“填充”节点
  3657. * @private
  3658. * @method isFillChar
  3659. * @param { Node } node 需要判断的节点
  3660. * @param { Boolean } isInStart 是否从节点内容的开始位置匹配
  3661. * @returns { Boolean } 节点是否是填充节点
  3662. */
  3663. isFillChar:function (node,isInStart) {
  3664. if(node.nodeType != 3)
  3665. return false;
  3666. var text = node.nodeValue;
  3667. if(isInStart){
  3668. return new RegExp('^' + domUtils.fillChar).test(text)
  3669. }
  3670. return !text.replace(new RegExp(domUtils.fillChar,'g'), '').length
  3671. },
  3672. isStartInblock:function (range) {
  3673. var tmpRange = range.cloneRange(),
  3674. flag = 0,
  3675. start = tmpRange.startContainer,
  3676. tmp;
  3677. if(start.nodeType == 1 && start.childNodes[tmpRange.startOffset]){
  3678. start = start.childNodes[tmpRange.startOffset];
  3679. var pre = start.previousSibling;
  3680. while(pre && domUtils.isFillChar(pre)){
  3681. start = pre;
  3682. pre = pre.previousSibling;
  3683. }
  3684. }
  3685. if(this.isFillChar(start,true) && tmpRange.startOffset == 1){
  3686. tmpRange.setStartBefore(start);
  3687. start = tmpRange.startContainer;
  3688. }
  3689. while (start && domUtils.isFillChar(start)) {
  3690. tmp = start;
  3691. start = start.previousSibling
  3692. }
  3693. if (tmp) {
  3694. tmpRange.setStartBefore(tmp);
  3695. start = tmpRange.startContainer;
  3696. }
  3697. if (start.nodeType == 1 && domUtils.isEmptyNode(start) && tmpRange.startOffset == 1) {
  3698. tmpRange.setStart(start, 0).collapse(true);
  3699. }
  3700. while (!tmpRange.startOffset) {
  3701. start = tmpRange.startContainer;
  3702. if (domUtils.isBlockElm(start) || domUtils.isBody(start)) {
  3703. flag = 1;
  3704. break;
  3705. }
  3706. var pre = tmpRange.startContainer.previousSibling,
  3707. tmpNode;
  3708. if (!pre) {
  3709. tmpRange.setStartBefore(tmpRange.startContainer);
  3710. } else {
  3711. while (pre && domUtils.isFillChar(pre)) {
  3712. tmpNode = pre;
  3713. pre = pre.previousSibling;
  3714. }
  3715. if (tmpNode) {
  3716. tmpRange.setStartBefore(tmpNode);
  3717. } else {
  3718. tmpRange.setStartBefore(tmpRange.startContainer);
  3719. }
  3720. }
  3721. }
  3722. return flag && !domUtils.isBody(tmpRange.startContainer) ? 1 : 0;
  3723. },
  3724. /**
  3725. * 判断给定的元素是否是一个空元素
  3726. * @method isEmptyBlock
  3727. * @param { Element } node 需要判断的元素
  3728. * @return { Boolean } 是否是空元素
  3729. * @example
  3730. * ```html
  3731. * <div id="test"></div>
  3732. *
  3733. * <script>
  3734. * //output: true
  3735. * console.log( UE.dom.domUtils.isEmptyBlock( document.getElementById("test") ) );
  3736. * </script>
  3737. * ```
  3738. */
  3739. /**
  3740. * 根据指定的判断规则判断给定的元素是否是一个空元素
  3741. * @method isEmptyBlock
  3742. * @param { Element } node 需要判断的元素
  3743. * @param { RegExp } reg 对内容执行判断的正则表达式对象
  3744. * @return { Boolean } 是否是空元素
  3745. */
  3746. isEmptyBlock:function (node,reg) {
  3747. if(node.nodeType != 1)
  3748. return 0;
  3749. reg = reg || new RegExp('[ \xa0\t\r\n' + domUtils.fillChar + ']', 'g');
  3750. if (node[browser.ie ? 'innerText' : 'textContent'].replace(reg, '').length > 0) {
  3751. return 0;
  3752. }
  3753. for (var n in dtd.$isNotEmpty) {
  3754. if (node.getElementsByTagName(n).length) {
  3755. return 0;
  3756. }
  3757. }
  3758. return 1;
  3759. },
  3760. /**
  3761. * 移动元素使得该元素的位置移动指定的偏移量的距离
  3762. * @method setViewportOffset
  3763. * @param { Element } element 需要设置偏移量的元素
  3764. * @param { Object } offset 偏移量, 形如{ left: 100, top: 50 }的一个键值对, 表示该元素将在
  3765. * 现有的位置上向水平方向偏移offset.left的距离, 在竖直方向上偏移
  3766. * offset.top的距离
  3767. * @example
  3768. * ```html
  3769. * <div id="test" style="top: 100px; left: 50px; position: absolute;"></div>
  3770. *
  3771. * <script>
  3772. *
  3773. * var testNode = document.getElementById("test");
  3774. *
  3775. * UE.dom.domUtils.setViewportOffset( testNode, {
  3776. * left: 200,
  3777. * top: 50
  3778. * } );
  3779. *
  3780. * //output: top: 300px; left: 100px; position: absolute;
  3781. * console.log( testNode.style.cssText );
  3782. *
  3783. * </script>
  3784. * ```
  3785. */
  3786. setViewportOffset:function (element, offset) {
  3787. var left = parseInt(element.style.left) | 0;
  3788. var top = parseInt(element.style.top) | 0;
  3789. var rect = element.getBoundingClientRect();
  3790. var offsetLeft = offset.left - rect.left;
  3791. var offsetTop = offset.top - rect.top;
  3792. if (offsetLeft) {
  3793. element.style.left = left + offsetLeft + 'px';
  3794. }
  3795. if (offsetTop) {
  3796. element.style.top = top + offsetTop + 'px';
  3797. }
  3798. },
  3799. /**
  3800. * 用“填充字符”填充节点
  3801. * @method fillNode
  3802. * @private
  3803. * @param { DomDocument } doc 填充的节点所在的docment对象
  3804. * @param { Node } node 需要填充的节点对象
  3805. * @example
  3806. * ```html
  3807. * <div id="test"></div>
  3808. *
  3809. * <script>
  3810. * var testNode = document.getElementById("test");
  3811. *
  3812. * //output: 0
  3813. * console.log( testNode.childNodes.length );
  3814. *
  3815. * UE.dom.domUtils.fillNode( document, testNode );
  3816. *
  3817. * //output: 1
  3818. * console.log( testNode.childNodes.length );
  3819. *
  3820. * </script>
  3821. * ```
  3822. */
  3823. fillNode:function (doc, node) {
  3824. var tmpNode = browser.ie ? doc.createTextNode(domUtils.fillChar) : doc.createElement('br');
  3825. node.innerHTML = '';
  3826. node.appendChild(tmpNode);
  3827. },
  3828. /**
  3829. * 把节点src的所有子节点追加到另一个节点tag上去
  3830. * @method moveChild
  3831. * @param { Node } src 源节点, 该节点下的所有子节点将被移除
  3832. * @param { Node } tag 目标节点, 从源节点移除的子节点将被追加到该节点下
  3833. * @example
  3834. * ```html
  3835. * <div id="test1">
  3836. * <span></span>
  3837. * </div>
  3838. * <div id="test2">
  3839. * <div></div>
  3840. * </div>
  3841. *
  3842. * <script>
  3843. *
  3844. * var test1 = document.getElementById("test1"),
  3845. * test2 = document.getElementById("test2");
  3846. *
  3847. * UE.dom.domUtils.moveChild( test1, test2 );
  3848. *
  3849. * //output: ""(空字符串)
  3850. * console.log( test1.innerHTML );
  3851. *
  3852. * //output: "<div></div><span></span>"
  3853. * console.log( test2.innerHTML );
  3854. *
  3855. * </script>
  3856. * ```
  3857. */
  3858. /**
  3859. * 把节点src的所有子节点移动到另一个节点tag上去, 可以通过dir参数控制附加的行为是“追加”还是“插入顶部”
  3860. * @method moveChild
  3861. * @param { Node } src 源节点, 该节点下的所有子节点将被移除
  3862. * @param { Node } tag 目标节点, 从源节点移除的子节点将被附加到该节点下
  3863. * @param { Boolean } dir 附加方式, 如果为true, 则附加进去的节点将被放到目标节点的顶部, 反之,则放到末尾
  3864. * @example
  3865. * ```html
  3866. * <div id="test1">
  3867. * <span></span>
  3868. * </div>
  3869. * <div id="test2">
  3870. * <div></div>
  3871. * </div>
  3872. *
  3873. * <script>
  3874. *
  3875. * var test1 = document.getElementById("test1"),
  3876. * test2 = document.getElementById("test2");
  3877. *
  3878. * UE.dom.domUtils.moveChild( test1, test2, true );
  3879. *
  3880. * //output: ""(空字符串)
  3881. * console.log( test1.innerHTML );
  3882. *
  3883. * //output: "<span></span><div></div>"
  3884. * console.log( test2.innerHTML );
  3885. *
  3886. * </script>
  3887. * ```
  3888. */
  3889. moveChild:function (src, tag, dir) {
  3890. while (src.firstChild) {
  3891. if (dir && tag.firstChild) {
  3892. tag.insertBefore(src.lastChild, tag.firstChild);
  3893. } else {
  3894. tag.appendChild(src.firstChild);
  3895. }
  3896. }
  3897. },
  3898. /**
  3899. * 判断节点的标签上是否不存在任何属性
  3900. * @method hasNoAttributes
  3901. * @private
  3902. * @param { Node } node 需要检测的节点对象
  3903. * @return { Boolean } 节点是否不包含任何属性
  3904. * @example
  3905. * ```html
  3906. * <div id="test"><span>xxxx</span></div>
  3907. *
  3908. * <script>
  3909. *
  3910. * //output: false
  3911. * console.log( UE.dom.domUtils.hasNoAttributes( document.getElementById("test") ) );
  3912. *
  3913. * //output: true
  3914. * console.log( UE.dom.domUtils.hasNoAttributes( document.getElementById("test").firstChild ) );
  3915. *
  3916. * </script>
  3917. * ```
  3918. */
  3919. hasNoAttributes:function (node) {
  3920. return browser.ie ? /^<\w+\s*?>/.test(node.outerHTML) : node.attributes.length == 0;
  3921. },
  3922. /**
  3923. * 检测节点是否是UEditor所使用的辅助节点
  3924. * @method isCustomeNode
  3925. * @private
  3926. * @param { Node } node 需要检测的节点
  3927. * @remind 辅助节点是指编辑器要完成工作临时添加的节点, 在输出的时候将会从编辑器内移除, 不会影响最终的结果。
  3928. * @return { Boolean } 给定的节点是否是一个辅助节点
  3929. */
  3930. isCustomeNode:function (node) {
  3931. return node.nodeType == 1 && node.getAttribute('_ue_custom_node_');
  3932. },
  3933. /**
  3934. * 检测节点的标签是否是给定的标签
  3935. * @method isTagNode
  3936. * @param { Node } node 需要检测的节点对象
  3937. * @param { String } tagName 标签
  3938. * @return { Boolean } 节点的标签是否是给定的标签
  3939. * @example
  3940. * ```html
  3941. * <div id="test"></div>
  3942. *
  3943. * <script>
  3944. *
  3945. * //output: true
  3946. * console.log( UE.dom.domUtils.isTagNode( document.getElementById("test"), "div" ) );
  3947. *
  3948. * </script>
  3949. * ```
  3950. */
  3951. isTagNode:function (node, tagNames) {
  3952. return node.nodeType == 1 && new RegExp('\\b' + node.tagName + '\\b','i').test(tagNames)
  3953. },
  3954. /**
  3955. * 给定一个节点数组,在通过指定的过滤器过滤后, 获取其中满足过滤条件的第一个节点
  3956. * @method filterNodeList
  3957. * @param { Array } nodeList 需要过滤的节点数组
  3958. * @param { Function } fn 过滤器, 对符合条件的节点, 执行结果返回true, 反之则返回false
  3959. * @return { Node | NULL } 如果找到符合过滤条件的节点, 则返回该节点, 否则返回NULL
  3960. * @example
  3961. * ```javascript
  3962. * var divNodes = document.getElementsByTagName("div");
  3963. * divNodes = [].slice.call( divNodes, 0 );
  3964. *
  3965. * //output: null
  3966. * console.log( UE.dom.domUtils.filterNodeList( divNodes, function ( node ) {
  3967. * return node.tagName.toLowerCase() !== 'div';
  3968. * } ) );
  3969. * ```
  3970. */
  3971. /**
  3972. * 给定一个节点数组nodeList和一组标签名tagNames, 获取其中能够匹配标签名的节点集合中的第一个节点
  3973. * @method filterNodeList
  3974. * @param { Array } nodeList 需要过滤的节点数组
  3975. * @param { String } tagNames 需要匹配的标签名, 多个标签名之间用空格分割
  3976. * @return { Node | NULL } 如果找到标签名匹配的节点, 则返回该节点, 否则返回NULL
  3977. * @example
  3978. * ```javascript
  3979. * var divNodes = document.getElementsByTagName("div");
  3980. * divNodes = [].slice.call( divNodes, 0 );
  3981. *
  3982. * //output: null
  3983. * console.log( UE.dom.domUtils.filterNodeList( divNodes, 'a span' ) );
  3984. * ```
  3985. */
  3986. /**
  3987. * 给定一个节点数组,在通过指定的过滤器过滤后, 如果参数forAll为true, 则会返回所有满足过滤
  3988. * 条件的节点集合, 否则, 返回满足条件的节点集合中的第一个节点
  3989. * @method filterNodeList
  3990. * @param { Array } nodeList 需要过滤的节点数组
  3991. * @param { Function } fn 过滤器, 对符合条件的节点, 执行结果返回true, 反之则返回false
  3992. * @param { Boolean } forAll 是否返回整个节点数组, 如果该参数为false, 则返回节点集合中的第一个节点
  3993. * @return { Array | Node | NULL } 如果找到符合过滤条件的节点, 则根据参数forAll的值决定返回满足
  3994. * 过滤条件的节点数组或第一个节点, 否则返回NULL
  3995. * @example
  3996. * ```javascript
  3997. * var divNodes = document.getElementsByTagName("div");
  3998. * divNodes = [].slice.call( divNodes, 0 );
  3999. *
  4000. * //output: 3(假定有3个div)
  4001. * console.log( divNodes.length );
  4002. *
  4003. * var nodes = UE.dom.domUtils.filterNodeList( divNodes, function ( node ) {
  4004. * return node.tagName.toLowerCase() === 'div';
  4005. * }, true );
  4006. *
  4007. * //output: 3
  4008. * console.log( nodes.length );
  4009. *
  4010. * var node = UE.dom.domUtils.filterNodeList( divNodes, function ( node ) {
  4011. * return node.tagName.toLowerCase() === 'div';
  4012. * }, false );
  4013. *
  4014. * //output: div
  4015. * console.log( node.nodeName );
  4016. * ```
  4017. */
  4018. filterNodeList : function(nodelist,filter,forAll){
  4019. var results = [];
  4020. if(!utils .isFunction(filter)){
  4021. var str = filter;
  4022. filter = function(n){
  4023. return utils.indexOf(utils.isArray(str) ? str:str.split(' '), n.tagName.toLowerCase()) != -1
  4024. };
  4025. }
  4026. utils.each(nodelist,function(n){
  4027. filter(n) && results.push(n)
  4028. });
  4029. return results.length == 0 ? null : results.length == 1 || !forAll ? results[0] : results
  4030. },
  4031. /**
  4032. * 查询给定的range选区是否在给定的node节点内,且在该节点的最末尾
  4033. * @method isInNodeEndBoundary
  4034. * @param { UE.dom.Range } rng 需要判断的range对象, 该对象的startContainer不能为NULL
  4035. * @param node 需要检测的节点对象
  4036. * @return { Number } 如果给定的选取range对象是在node内部的最末端, 则返回1, 否则返回0
  4037. */
  4038. isInNodeEndBoundary : function (rng,node){
  4039. var start = rng.startContainer;
  4040. if(start.nodeType == 3 && rng.startOffset != start.nodeValue.length){
  4041. return 0;
  4042. }
  4043. if(start.nodeType == 1 && rng.startOffset != start.childNodes.length){
  4044. return 0;
  4045. }
  4046. while(start !== node){
  4047. if(start.nextSibling){
  4048. return 0
  4049. };
  4050. start = start.parentNode;
  4051. }
  4052. return 1;
  4053. },
  4054. isBoundaryNode : function (node,dir){
  4055. var tmp;
  4056. while(!domUtils.isBody(node)){
  4057. tmp = node;
  4058. node = node.parentNode;
  4059. if(tmp !== node[dir]){
  4060. return false;
  4061. }
  4062. }
  4063. return true;
  4064. },
  4065. fillHtml : browser.ie11below ? '&nbsp;' : '<br/>'
  4066. };
  4067. var fillCharReg = new RegExp(domUtils.fillChar, 'g');
  4068. // core/Range.js
  4069. /**
  4070. * Range封装
  4071. * @file
  4072. * @module UE.dom
  4073. * @class Range
  4074. * @since 1.2.6.1
  4075. */
  4076. /**
  4077. * dom操作封装
  4078. * @unfile
  4079. * @module UE.dom
  4080. */
  4081. /**
  4082. * Range实现类,本类是UEditor底层核心类,封装不同浏览器之间的Range操作。
  4083. * @unfile
  4084. * @module UE.dom
  4085. * @class Range
  4086. */
  4087. (function () {
  4088. var guid = 0,
  4089. fillChar = domUtils.fillChar,
  4090. fillData;
  4091. /**
  4092. * 更新range的collapse状态
  4093. * @param {Range} range range对象
  4094. */
  4095. function updateCollapse(range) {
  4096. range.collapsed =
  4097. range.startContainer && range.endContainer &&
  4098. range.startContainer === range.endContainer &&
  4099. range.startOffset == range.endOffset;
  4100. }
  4101. function selectOneNode(rng){
  4102. return !rng.collapsed && rng.startContainer.nodeType == 1 && rng.startContainer === rng.endContainer && rng.endOffset - rng.startOffset == 1
  4103. }
  4104. function setEndPoint(toStart, node, offset, range) {
  4105. //如果node是自闭合标签要处理
  4106. if (node.nodeType == 1 && (dtd.$empty[node.tagName] || dtd.$nonChild[node.tagName])) {
  4107. offset = domUtils.getNodeIndex(node) + (toStart ? 0 : 1);
  4108. node = node.parentNode;
  4109. }
  4110. if (toStart) {
  4111. range.startContainer = node;
  4112. range.startOffset = offset;
  4113. if (!range.endContainer) {
  4114. range.collapse(true);
  4115. }
  4116. } else {
  4117. range.endContainer = node;
  4118. range.endOffset = offset;
  4119. if (!range.startContainer) {
  4120. range.collapse(false);
  4121. }
  4122. }
  4123. updateCollapse(range);
  4124. return range;
  4125. }
  4126. function execContentsAction(range, action) {
  4127. //调整边界
  4128. //range.includeBookmark();
  4129. var start = range.startContainer,
  4130. end = range.endContainer,
  4131. startOffset = range.startOffset,
  4132. endOffset = range.endOffset,
  4133. doc = range.document,
  4134. frag = doc.createDocumentFragment(),
  4135. tmpStart, tmpEnd;
  4136. if (start.nodeType == 1) {
  4137. start = start.childNodes[startOffset] || (tmpStart = start.appendChild(doc.createTextNode('')));
  4138. }
  4139. if (end.nodeType == 1) {
  4140. end = end.childNodes[endOffset] || (tmpEnd = end.appendChild(doc.createTextNode('')));
  4141. }
  4142. if (start === end && start.nodeType == 3) {
  4143. frag.appendChild(doc.createTextNode(start.substringData(startOffset, endOffset - startOffset)));
  4144. //is not clone
  4145. if (action) {
  4146. start.deleteData(startOffset, endOffset - startOffset);
  4147. range.collapse(true);
  4148. }
  4149. return frag;
  4150. }
  4151. var current, currentLevel, clone = frag,
  4152. startParents = domUtils.findParents(start, true), endParents = domUtils.findParents(end, true);
  4153. for (var i = 0; startParents[i] == endParents[i];) {
  4154. i++;
  4155. }
  4156. for (var j = i, si; si = startParents[j]; j++) {
  4157. current = si.nextSibling;
  4158. if (si == start) {
  4159. if (!tmpStart) {
  4160. if (range.startContainer.nodeType == 3) {
  4161. clone.appendChild(doc.createTextNode(start.nodeValue.slice(startOffset)));
  4162. //is not clone
  4163. if (action) {
  4164. start.deleteData(startOffset, start.nodeValue.length - startOffset);
  4165. }
  4166. } else {
  4167. clone.appendChild(!action ? start.cloneNode(true) : start);
  4168. }
  4169. }
  4170. } else {
  4171. currentLevel = si.cloneNode(false);
  4172. clone.appendChild(currentLevel);
  4173. }
  4174. while (current) {
  4175. if (current === end || current === endParents[j]) {
  4176. break;
  4177. }
  4178. si = current.nextSibling;
  4179. clone.appendChild(!action ? current.cloneNode(true) : current);
  4180. current = si;
  4181. }
  4182. clone = currentLevel;
  4183. }
  4184. clone = frag;
  4185. if (!startParents[i]) {
  4186. clone.appendChild(startParents[i - 1].cloneNode(false));
  4187. clone = clone.firstChild;
  4188. }
  4189. for (var j = i, ei; ei = endParents[j]; j++) {
  4190. current = ei.previousSibling;
  4191. if (ei == end) {
  4192. if (!tmpEnd && range.endContainer.nodeType == 3) {
  4193. clone.appendChild(doc.createTextNode(end.substringData(0, endOffset)));
  4194. //is not clone
  4195. if (action) {
  4196. end.deleteData(0, endOffset);
  4197. }
  4198. }
  4199. } else {
  4200. currentLevel = ei.cloneNode(false);
  4201. clone.appendChild(currentLevel);
  4202. }
  4203. //如果两端同级,右边第一次已经被开始做了
  4204. if (j != i || !startParents[i]) {
  4205. while (current) {
  4206. if (current === start) {
  4207. break;
  4208. }
  4209. ei = current.previousSibling;
  4210. clone.insertBefore(!action ? current.cloneNode(true) : current, clone.firstChild);
  4211. current = ei;
  4212. }
  4213. }
  4214. clone = currentLevel;
  4215. }
  4216. if (action) {
  4217. range.setStartBefore(!endParents[i] ? endParents[i - 1] : !startParents[i] ? startParents[i - 1] : endParents[i]).collapse(true);
  4218. }
  4219. tmpStart && domUtils.remove(tmpStart);
  4220. tmpEnd && domUtils.remove(tmpEnd);
  4221. return frag;
  4222. }
  4223. /**
  4224. * 创建一个跟document绑定的空的Range实例
  4225. * @constructor
  4226. * @param { Document } document 新建的选区所属的文档对象
  4227. */
  4228. /**
  4229. * @property { Node } startContainer 当前Range的开始边界的容器节点, 可以是一个元素节点或者是文本节点
  4230. */
  4231. /**
  4232. * @property { Node } startOffset 当前Range的开始边界容器节点的偏移量, 如果是元素节点,
  4233. * 该值就是childNodes中的第几个节点, 如果是文本节点就是文本内容的第几个字符
  4234. */
  4235. /**
  4236. * @property { Node } endContainer 当前Range的结束边界的容器节点, 可以是一个元素节点或者是文本节点
  4237. */
  4238. /**
  4239. * @property { Node } endOffset 当前Range的结束边界容器节点的偏移量, 如果是元素节点,
  4240. * 该值就是childNodes中的第几个节点, 如果是文本节点就是文本内容的第几个字符
  4241. */
  4242. /**
  4243. * @property { Boolean } collapsed 当前Range是否闭合
  4244. * @default true
  4245. * @remind Range是闭合的时候, startContainer === endContainer && startOffset === endOffset
  4246. */
  4247. /**
  4248. * @property { Document } document 当前Range所属的Document对象
  4249. * @remind 不同range的的document属性可以是不同的
  4250. */
  4251. var Range = dom.Range = function (document) {
  4252. var me = this;
  4253. me.startContainer =
  4254. me.startOffset =
  4255. me.endContainer =
  4256. me.endOffset = null;
  4257. me.document = document;
  4258. me.collapsed = true;
  4259. };
  4260. /**
  4261. * 删除fillData
  4262. * @param doc
  4263. * @param excludeNode
  4264. */
  4265. function removeFillData(doc, excludeNode) {
  4266. try {
  4267. if (fillData && domUtils.inDoc(fillData, doc)) {
  4268. if (!fillData.nodeValue.replace(fillCharReg, '').length) {
  4269. var tmpNode = fillData.parentNode;
  4270. domUtils.remove(fillData);
  4271. while (tmpNode && domUtils.isEmptyInlineElement(tmpNode) &&
  4272. //safari的contains有bug
  4273. (browser.safari ? !(domUtils.getPosition(tmpNode,excludeNode) & domUtils.POSITION_CONTAINS) : !tmpNode.contains(excludeNode))
  4274. ) {
  4275. fillData = tmpNode.parentNode;
  4276. domUtils.remove(tmpNode);
  4277. tmpNode = fillData;
  4278. }
  4279. } else {
  4280. fillData.nodeValue = fillData.nodeValue.replace(fillCharReg, '');
  4281. }
  4282. }
  4283. } catch (e) {
  4284. }
  4285. }
  4286. /**
  4287. * @param node
  4288. * @param dir
  4289. */
  4290. function mergeSibling(node, dir) {
  4291. var tmpNode;
  4292. node = node[dir];
  4293. while (node && domUtils.isFillChar(node)) {
  4294. tmpNode = node[dir];
  4295. domUtils.remove(node);
  4296. node = tmpNode;
  4297. }
  4298. }
  4299. Range.prototype = {
  4300. /**
  4301. * 克隆选区的内容到一个DocumentFragment里
  4302. * @method cloneContents
  4303. * @return { DocumentFragment | NULL } 如果选区是闭合的将返回null, 否则, 返回包含所clone内容的DocumentFragment元素
  4304. * @example
  4305. * ```html
  4306. * <body>
  4307. * <!-- 中括号表示选区 -->
  4308. * <b>x<i>x[x</i>xx]x</b>
  4309. *
  4310. * <script>
  4311. * //range是已选中的选区
  4312. * var fragment = range.cloneContents(),
  4313. * node = document.createElement("div");
  4314. *
  4315. * node.appendChild( fragment );
  4316. *
  4317. * //output: <i>x</i>xx
  4318. * console.log( node.innerHTML );
  4319. *
  4320. * </script>
  4321. * </body>
  4322. * ```
  4323. */
  4324. cloneContents:function () {
  4325. return this.collapsed ? null : execContentsAction(this, 0);
  4326. },
  4327. /**
  4328. * 删除当前选区范围中的所有内容
  4329. * @method deleteContents
  4330. * @remind 执行完该操作后, 当前Range对象变成了闭合状态
  4331. * @return { UE.dom.Range } 当前操作的Range对象
  4332. * @example
  4333. * ```html
  4334. * <body>
  4335. * <!-- 中括号表示选区 -->
  4336. * <b>x<i>x[x</i>xx]x</b>
  4337. *
  4338. * <script>
  4339. * //range是已选中的选区
  4340. * range.deleteContents();
  4341. *
  4342. * //竖线表示闭合后的选区位置
  4343. * //output: <b>x<i>x</i>|x</b>
  4344. * console.log( document.body.innerHTML );
  4345. *
  4346. * //此时, range的各项属性为
  4347. * //output: B
  4348. * console.log( range.startContainer.tagName );
  4349. * //output: 2
  4350. * console.log( range.startOffset );
  4351. * //output: B
  4352. * console.log( range.endContainer.tagName );
  4353. * //output: 2
  4354. * console.log( range.endOffset );
  4355. * //output: true
  4356. * console.log( range.collapsed );
  4357. *
  4358. * </script>
  4359. * </body>
  4360. * ```
  4361. */
  4362. deleteContents:function () {
  4363. var txt;
  4364. if (!this.collapsed) {
  4365. execContentsAction(this, 1);
  4366. }
  4367. if (browser.webkit) {
  4368. txt = this.startContainer;
  4369. if (txt.nodeType == 3 && !txt.nodeValue.length) {
  4370. this.setStartBefore(txt).collapse(true);
  4371. domUtils.remove(txt);
  4372. }
  4373. }
  4374. return this;
  4375. },
  4376. /**
  4377. * 将当前选区的内容提取到一个DocumentFragment里
  4378. * @method extractContents
  4379. * @remind 执行该操作后, 选区将变成闭合状态
  4380. * @warning 执行该操作后, 原来选区所选中的内容将从dom树上剥离出来
  4381. * @return { DocumentFragment } 返回包含所提取内容的DocumentFragment对象
  4382. * @example
  4383. * ```html
  4384. * <body>
  4385. * <!-- 中括号表示选区 -->
  4386. * <b>x<i>x[x</i>xx]x</b>
  4387. *
  4388. * <script>
  4389. * //range是已选中的选区
  4390. * var fragment = range.extractContents(),
  4391. * node = document.createElement( "div" );
  4392. *
  4393. * node.appendChild( fragment );
  4394. *
  4395. * //竖线表示闭合后的选区位置
  4396. *
  4397. * //output: <b>x<i>x</i>|x</b>
  4398. * console.log( document.body.innerHTML );
  4399. * //output: <i>x</i>xx
  4400. * console.log( node.innerHTML );
  4401. *
  4402. * //此时, range的各项属性为
  4403. * //output: B
  4404. * console.log( range.startContainer.tagName );
  4405. * //output: 2
  4406. * console.log( range.startOffset );
  4407. * //output: B
  4408. * console.log( range.endContainer.tagName );
  4409. * //output: 2
  4410. * console.log( range.endOffset );
  4411. * //output: true
  4412. * console.log( range.collapsed );
  4413. *
  4414. * </script>
  4415. * </body>
  4416. */
  4417. extractContents:function () {
  4418. return this.collapsed ? null : execContentsAction(this, 2);
  4419. },
  4420. /**
  4421. * 设置Range的开始容器节点和偏移量
  4422. * @method setStart
  4423. * @remind 如果给定的节点是元素节点,那么offset指的是其子元素中索引为offset的元素,
  4424. * 如果是文本节点,那么offset指的是其文本内容的第offset个字符
  4425. * @remind 如果提供的容器节点是一个不能包含子元素的节点, 则该选区的开始容器将被设置
  4426. * 为该节点的父节点, 此时, 其距离开始容器的偏移量也变成了该节点在其父节点
  4427. * 中的索引
  4428. * @param { Node } node 将被设为当前选区开始边界容器的节点对象
  4429. * @param { int } offset 选区的开始位置偏移量
  4430. * @return { UE.dom.Range } 当前range对象
  4431. * @example
  4432. * ```html
  4433. * <!-- 选区 -->
  4434. * <b>xxx<i>x<span>xx</span>xx<em>xx</em>xxx</i>[xxx]</b>
  4435. *
  4436. * <script>
  4437. *
  4438. * //执行操作
  4439. * range.setStart( document.getElementsByTagName("i")[0], 1 );
  4440. *
  4441. * //此时, 选区变成了
  4442. * //<b>xxx<i>x[<span>xx</span>xx<em>xx</em>xxx</i>xxx]</b>
  4443. *
  4444. * </script>
  4445. * ```
  4446. * @example
  4447. * ```html
  4448. * <!-- 选区 -->
  4449. * <b>xxx<img>[xx]x</b>
  4450. *
  4451. * <script>
  4452. *
  4453. * //执行操作
  4454. * range.setStart( document.getElementsByTagName("img")[0], 3 );
  4455. *
  4456. * //此时, 选区变成了
  4457. * //<b>xxx[<img>xx]x</b>
  4458. *
  4459. * </script>
  4460. * ```
  4461. */
  4462. setStart:function (node, offset) {
  4463. return setEndPoint(true, node, offset, this);
  4464. },
  4465. /**
  4466. * 设置Range的结束容器和偏移量
  4467. * @method setEnd
  4468. * @param { Node } node 作为当前选区结束边界容器的节点对象
  4469. * @param { int } offset 结束边界的偏移量
  4470. * @see UE.dom.Range:setStart(Node,int)
  4471. * @return { UE.dom.Range } 当前range对象
  4472. */
  4473. setEnd:function (node, offset) {
  4474. return setEndPoint(false, node, offset, this);
  4475. },
  4476. /**
  4477. * 将Range开始位置设置到node节点之后
  4478. * @method setStartAfter
  4479. * @remind 该操作将会把给定节点的父节点作为range的开始容器, 且偏移量是该节点在其父节点中的位置索引+1
  4480. * @param { Node } node 选区的开始边界将紧接着该节点之后
  4481. * @return { UE.dom.Range } 当前range对象
  4482. * @example
  4483. * ```html
  4484. * <!-- 选区示例 -->
  4485. * <b>xx<i>xxx</i><span>xx[x</span>xxx]</b>
  4486. *
  4487. * <script>
  4488. *
  4489. * //执行操作
  4490. * range.setStartAfter( document.getElementsByTagName("i")[0] );
  4491. *
  4492. * //结果选区
  4493. * //<b>xx<i>xxx</i>[<span>xxx</span>xxx]</b>
  4494. *
  4495. * </script>
  4496. * ```
  4497. */
  4498. setStartAfter:function (node) {
  4499. return this.setStart(node.parentNode, domUtils.getNodeIndex(node) + 1);
  4500. },
  4501. /**
  4502. * 将Range开始位置设置到node节点之前
  4503. * @method setStartBefore
  4504. * @remind 该操作将会把给定节点的父节点作为range的开始容器, 且偏移量是该节点在其父节点中的位置索引
  4505. * @param { Node } node 新的选区开始位置在该节点之前
  4506. * @see UE.dom.Range:setStartAfter(Node)
  4507. * @return { UE.dom.Range } 当前range对象
  4508. */
  4509. setStartBefore:function (node) {
  4510. return this.setStart(node.parentNode, domUtils.getNodeIndex(node));
  4511. },
  4512. /**
  4513. * 将Range结束位置设置到node节点之后
  4514. * @method setEndAfter
  4515. * @remind 该操作将会把给定节点的父节点作为range的结束容器, 且偏移量是该节点在其父节点中的位置索引+1
  4516. * @param { Node } node 目标节点
  4517. * @see UE.dom.Range:setStartAfter(Node)
  4518. * @return { UE.dom.Range } 当前range对象
  4519. * @example
  4520. * ```html
  4521. * <!-- 选区示例 -->
  4522. * <b>[xx<i>xxx</i><span>xx]x</span>xxx</b>
  4523. *
  4524. * <script>
  4525. *
  4526. * //执行操作
  4527. * range.setStartAfter( document.getElementsByTagName("span")[0] );
  4528. *
  4529. * //结果选区
  4530. * //<b>[xx<i>xxx</i><span>xxx</span>]xxx</b>
  4531. *
  4532. * </script>
  4533. * ```
  4534. */
  4535. setEndAfter:function (node) {
  4536. return this.setEnd(node.parentNode, domUtils.getNodeIndex(node) + 1);
  4537. },
  4538. /**
  4539. * 将Range结束位置设置到node节点之前
  4540. * @method setEndBefore
  4541. * @remind 该操作将会把给定节点的父节点作为range的结束容器, 且偏移量是该节点在其父节点中的位置索引
  4542. * @param { Node } node 目标节点
  4543. * @see UE.dom.Range:setEndAfter(Node)
  4544. * @return { UE.dom.Range } 当前range对象
  4545. */
  4546. setEndBefore:function (node) {
  4547. return this.setEnd(node.parentNode, domUtils.getNodeIndex(node));
  4548. },
  4549. /**
  4550. * 设置Range的开始位置到node节点内的第一个子节点之前
  4551. * @method setStartAtFirst
  4552. * @remind 选区的开始容器将变成给定的节点, 且偏移量为0
  4553. * @remind 如果给定的节点是元素节点, 则该节点必须是允许包含子节点的元素。
  4554. * @param { Node } node 目标节点
  4555. * @see UE.dom.Range:setStartBefore(Node)
  4556. * @return { UE.dom.Range } 当前range对象
  4557. * @example
  4558. * ```html
  4559. * <!-- 选区示例 -->
  4560. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4561. *
  4562. * <script>
  4563. *
  4564. * //执行操作
  4565. * range.setStartAtFirst( document.getElementsByTagName("i")[0] );
  4566. *
  4567. * //结果选区
  4568. * //<b>xx<i>[xxx</i><span>xx]x</span>xxx</b>
  4569. *
  4570. * </script>
  4571. * ```
  4572. */
  4573. setStartAtFirst:function (node) {
  4574. return this.setStart(node, 0);
  4575. },
  4576. /**
  4577. * 设置Range的开始位置到node节点内的最后一个节点之后
  4578. * @method setStartAtLast
  4579. * @remind 选区的开始容器将变成给定的节点, 且偏移量为该节点的子节点数
  4580. * @remind 如果给定的节点是元素节点, 则该节点必须是允许包含子节点的元素。
  4581. * @param { Node } node 目标节点
  4582. * @see UE.dom.Range:setStartAtFirst(Node)
  4583. * @return { UE.dom.Range } 当前range对象
  4584. */
  4585. setStartAtLast:function (node) {
  4586. return this.setStart(node, node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length);
  4587. },
  4588. /**
  4589. * 设置Range的结束位置到node节点内的第一个节点之前
  4590. * @method setEndAtFirst
  4591. * @param { Node } node 目标节点
  4592. * @remind 选区的结束容器将变成给定的节点, 且偏移量为0
  4593. * @remind node必须是一个元素节点, 且必须是允许包含子节点的元素。
  4594. * @see UE.dom.Range:setStartAtFirst(Node)
  4595. * @return { UE.dom.Range } 当前range对象
  4596. */
  4597. setEndAtFirst:function (node) {
  4598. return this.setEnd(node, 0);
  4599. },
  4600. /**
  4601. * 设置Range的结束位置到node节点内的最后一个节点之后
  4602. * @method setEndAtLast
  4603. * @param { Node } node 目标节点
  4604. * @remind 选区的结束容器将变成给定的节点, 且偏移量为该节点的子节点数量
  4605. * @remind node必须是一个元素节点, 且必须是允许包含子节点的元素。
  4606. * @see UE.dom.Range:setStartAtFirst(Node)
  4607. * @return { UE.dom.Range } 当前range对象
  4608. */
  4609. setEndAtLast:function (node) {
  4610. return this.setEnd(node, node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length);
  4611. },
  4612. /**
  4613. * 选中给定节点
  4614. * @method selectNode
  4615. * @remind 此时, 选区的开始容器和结束容器都是该节点的父节点, 其startOffset是该节点在父节点中的位置索引,
  4616. * 而endOffset为startOffset+1
  4617. * @param { Node } node 需要选中的节点
  4618. * @return { UE.dom.Range } 当前range对象,此时的range仅包含当前给定的节点对象
  4619. * @example
  4620. * ```html
  4621. * <!-- 选区示例 -->
  4622. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4623. *
  4624. * <script>
  4625. *
  4626. * //执行操作
  4627. * range.selectNode( document.getElementsByTagName("i")[0] );
  4628. *
  4629. * //结果选区
  4630. * //<b>xx[<i>xxx</i>]<span>xxx</span>xxx</b>
  4631. *
  4632. * </script>
  4633. * ```
  4634. */
  4635. selectNode:function (node) {
  4636. return this.setStartBefore(node).setEndAfter(node);
  4637. },
  4638. /**
  4639. * 选中给定节点内部的所有节点
  4640. * @method selectNodeContents
  4641. * @remind 此时, 选区的开始容器和结束容器都是该节点, 其startOffset为0,
  4642. * 而endOffset是该节点的子节点数。
  4643. * @param { Node } node 目标节点, 当前range将包含该节点内的所有节点
  4644. * @return { UE.dom.Range } 当前range对象, 此时range仅包含给定节点的所有子节点
  4645. * @example
  4646. * ```html
  4647. * <!-- 选区示例 -->
  4648. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4649. *
  4650. * <script>
  4651. *
  4652. * //执行操作
  4653. * range.selectNode( document.getElementsByTagName("b")[0] );
  4654. *
  4655. * //结果选区
  4656. * //<b>[xx<i>xxx</i><span>xxx</span>xxx]</b>
  4657. *
  4658. * </script>
  4659. * ```
  4660. */
  4661. selectNodeContents:function (node) {
  4662. return this.setStart(node, 0).setEndAtLast(node);
  4663. },
  4664. /**
  4665. * clone当前Range对象
  4666. * @method cloneRange
  4667. * @remind 返回的range是一个全新的range对象, 其内部所有属性与当前被clone的range相同。
  4668. * @return { UE.dom.Range } 当前range对象的一个副本
  4669. */
  4670. cloneRange:function () {
  4671. var me = this;
  4672. return new Range(me.document).setStart(me.startContainer, me.startOffset).setEnd(me.endContainer, me.endOffset);
  4673. },
  4674. /**
  4675. * 向当前选区的结束处闭合选区
  4676. * @method collapse
  4677. * @return { UE.dom.Range } 当前range对象
  4678. * @example
  4679. * ```html
  4680. * <!-- 选区示例 -->
  4681. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4682. *
  4683. * <script>
  4684. *
  4685. * //执行操作
  4686. * range.collapse();
  4687. *
  4688. * //结果选区
  4689. * //“|”表示选区已闭合
  4690. * //<b>xx<i>xxx</i><span>xx|x</span>xxx</b>
  4691. *
  4692. * </script>
  4693. * ```
  4694. */
  4695. /**
  4696. * 闭合当前选区,根据给定的toStart参数项决定是向当前选区开始处闭合还是向结束处闭合,
  4697. * 如果toStart的值为true,则向开始位置闭合, 反之,向结束位置闭合。
  4698. * @method collapse
  4699. * @param { Boolean } toStart 是否向选区开始处闭合
  4700. * @return { UE.dom.Range } 当前range对象,此时range对象处于闭合状态
  4701. * @see UE.dom.Range:collapse()
  4702. * @example
  4703. * ```html
  4704. * <!-- 选区示例 -->
  4705. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4706. *
  4707. * <script>
  4708. *
  4709. * //执行操作
  4710. * range.collapse( true );
  4711. *
  4712. * //结果选区
  4713. * //“|”表示选区已闭合
  4714. * //<b>xx<i>xxx</i><span>|xxx</span>xxx</b>
  4715. *
  4716. * </script>
  4717. * ```
  4718. */
  4719. collapse:function (toStart) {
  4720. var me = this;
  4721. if (toStart) {
  4722. me.endContainer = me.startContainer;
  4723. me.endOffset = me.startOffset;
  4724. } else {
  4725. me.startContainer = me.endContainer;
  4726. me.startOffset = me.endOffset;
  4727. }
  4728. me.collapsed = true;
  4729. return me;
  4730. },
  4731. /**
  4732. * 调整range的开始位置和结束位置,使其"收缩"到最小的位置
  4733. * @method shrinkBoundary
  4734. * @return { UE.dom.Range } 当前range对象
  4735. * @example
  4736. * ```html
  4737. * <span>xx<b>xx[</b>xxxxx]</span> => <span>xx<b>xx</b>[xxxxx]</span>
  4738. * ```
  4739. *
  4740. * @example
  4741. * ```html
  4742. * <!-- 选区示例 -->
  4743. * <b>x[xx</b><i>]xxx</i>
  4744. *
  4745. * <script>
  4746. *
  4747. * //执行收缩
  4748. * range.shrinkBoundary();
  4749. *
  4750. * //结果选区
  4751. * //<b>x[xx]</b><i>xxx</i>
  4752. * </script>
  4753. * ```
  4754. *
  4755. * @example
  4756. * ```html
  4757. * [<b><i>xxxx</i>xxxxxxx</b>] => <b><i>[xxxx</i>xxxxxxx]</b>
  4758. * ```
  4759. */
  4760. /**
  4761. * 调整range的开始位置和结束位置,使其"收缩"到最小的位置,
  4762. * 如果ignoreEnd的值为true,则忽略对结束位置的调整
  4763. * @method shrinkBoundary
  4764. * @param { Boolean } ignoreEnd 是否忽略对结束位置的调整
  4765. * @return { UE.dom.Range } 当前range对象
  4766. * @see UE.dom.domUtils.Range:shrinkBoundary()
  4767. */
  4768. shrinkBoundary:function (ignoreEnd) {
  4769. var me = this, child,
  4770. collapsed = me.collapsed;
  4771. function check(node){
  4772. return node.nodeType == 1 && !domUtils.isBookmarkNode(node) && !dtd.$empty[node.tagName] && !dtd.$nonChild[node.tagName]
  4773. }
  4774. while (me.startContainer.nodeType == 1 //是element
  4775. && (child = me.startContainer.childNodes[me.startOffset]) //子节点也是element
  4776. && check(child)) {
  4777. me.setStart(child, 0);
  4778. }
  4779. if (collapsed) {
  4780. return me.collapse(true);
  4781. }
  4782. if (!ignoreEnd) {
  4783. while (me.endContainer.nodeType == 1//是element
  4784. && me.endOffset > 0 //如果是空元素就退出 endOffset=0那么endOffst-1为负值,childNodes[endOffset]报错
  4785. && (child = me.endContainer.childNodes[me.endOffset - 1]) //子节点也是element
  4786. && check(child)) {
  4787. me.setEnd(child, child.childNodes.length);
  4788. }
  4789. }
  4790. return me;
  4791. },
  4792. /**
  4793. * 获取离当前选区内包含的所有节点最近的公共祖先节点,
  4794. * @method getCommonAncestor
  4795. * @remind 返回的公共祖先节点一定不是range自身的容器节点, 但有可能是一个文本节点
  4796. * @return { Node } 当前range对象内所有节点的公共祖先节点
  4797. * @example
  4798. * ```html
  4799. * //选区示例
  4800. * <span>xxx<b>x[x<em>xx]x</em>xxx</b>xx</span>
  4801. * <script>
  4802. *
  4803. * var node = range.getCommonAncestor();
  4804. *
  4805. * //公共祖先节点是: b节点
  4806. * //输出: B
  4807. * console.log(node.tagName);
  4808. *
  4809. * </script>
  4810. * ```
  4811. */
  4812. /**
  4813. * 获取当前选区所包含的所有节点的公共祖先节点, 可以根据给定的参数 includeSelf 决定获取到
  4814. * 的公共祖先节点是否可以是当前选区的startContainer或endContainer节点, 如果 includeSelf
  4815. * 的取值为true, 则返回的节点可以是自身的容器节点, 否则, 则不能是容器节点
  4816. * @method getCommonAncestor
  4817. * @param { Boolean } includeSelf 是否允许获取到的公共祖先节点是当前range对象的容器节点
  4818. * @return { Node } 当前range对象内所有节点的公共祖先节点
  4819. * @see UE.dom.Range:getCommonAncestor()
  4820. * @example
  4821. * ```html
  4822. * <body>
  4823. *
  4824. * <!-- 选区示例 -->
  4825. * <b>xxx<i>xxxx<span>xx[x</span>xx]x</i>xxxxxxx</b>
  4826. *
  4827. * <script>
  4828. *
  4829. * var node = range.getCommonAncestor( false );
  4830. *
  4831. * //这里的公共祖先节点是B而不是I, 是因为参数限制了获取到的节点不能是容器节点
  4832. * //output: B
  4833. * console.log( node.tagName );
  4834. *
  4835. * </script>
  4836. *
  4837. * </body>
  4838. * ```
  4839. */
  4840. /**
  4841. * 获取当前选区所包含的所有节点的公共祖先节点, 可以根据给定的参数 includeSelf 决定获取到
  4842. * 的公共祖先节点是否可以是当前选区的startContainer或endContainer节点, 如果 includeSelf
  4843. * 的取值为true, 则返回的节点可以是自身的容器节点, 否则, 则不能是容器节点; 同时可以根据
  4844. * ignoreTextNode 参数的取值决定是否忽略类型为文本节点的祖先节点。
  4845. * @method getCommonAncestor
  4846. * @param { Boolean } includeSelf 是否允许获取到的公共祖先节点是当前range对象的容器节点
  4847. * @param { Boolean } ignoreTextNode 获取祖先节点的过程中是否忽略类型为文本节点的祖先节点
  4848. * @return { Node } 当前range对象内所有节点的公共祖先节点
  4849. * @see UE.dom.Range:getCommonAncestor()
  4850. * @see UE.dom.Range:getCommonAncestor(Boolean)
  4851. * @example
  4852. * ```html
  4853. * <body>
  4854. *
  4855. * <!-- 选区示例 -->
  4856. * <b>xxx<i>xxxx<span>x[x]x</span>xxx</i>xxxxxxx</b>
  4857. *
  4858. * <script>
  4859. *
  4860. * var node = range.getCommonAncestor( true, false );
  4861. *
  4862. * //output: SPAN
  4863. * console.log( node.tagName );
  4864. *
  4865. * </script>
  4866. *
  4867. * </body>
  4868. * ```
  4869. */
  4870. getCommonAncestor:function (includeSelf, ignoreTextNode) {
  4871. var me = this,
  4872. start = me.startContainer,
  4873. end = me.endContainer;
  4874. if (start === end) {
  4875. if (includeSelf && selectOneNode(this)) {
  4876. start = start.childNodes[me.startOffset];
  4877. if(start.nodeType == 1)
  4878. return start;
  4879. }
  4880. //只有在上来就相等的情况下才会出现是文本的情况
  4881. return ignoreTextNode && start.nodeType == 3 ? start.parentNode : start;
  4882. }
  4883. return domUtils.getCommonAncestor(start, end);
  4884. },
  4885. /**
  4886. * 调整当前Range的开始和结束边界容器,如果是容器节点是文本节点,就调整到包含该文本节点的父节点上
  4887. * @method trimBoundary
  4888. * @remind 该操作有可能会引起文本节点被切开
  4889. * @return { UE.dom.Range } 当前range对象
  4890. * @example
  4891. * ```html
  4892. *
  4893. * //选区示例
  4894. * <b>xxx<i>[xxxxx]</i>xxx</b>
  4895. *
  4896. * <script>
  4897. * //未调整前, 选区的开始容器和结束都是文本节点
  4898. * //执行调整
  4899. * range.trimBoundary();
  4900. *
  4901. * //调整之后, 容器节点变成了i节点
  4902. * //<b>xxx[<i>xxxxx</i>]xxx</b>
  4903. * </script>
  4904. * ```
  4905. */
  4906. /**
  4907. * 调整当前Range的开始和结束边界容器,如果是容器节点是文本节点,就调整到包含该文本节点的父节点上,
  4908. * 可以根据 ignoreEnd 参数的值决定是否调整对结束边界的调整
  4909. * @method trimBoundary
  4910. * @param { Boolean } ignoreEnd 是否忽略对结束边界的调整
  4911. * @return { UE.dom.Range } 当前range对象
  4912. * @example
  4913. * ```html
  4914. *
  4915. * //选区示例
  4916. * <b>xxx<i>[xxxxx]</i>xxx</b>
  4917. *
  4918. * <script>
  4919. * //未调整前, 选区的开始容器和结束都是文本节点
  4920. * //执行调整
  4921. * range.trimBoundary( true );
  4922. *
  4923. * //调整之后, 开始容器节点变成了i节点
  4924. * //但是, 结束容器没有发生变化
  4925. * //<b>xxx[<i>xxxxx]</i>xxx</b>
  4926. * </script>
  4927. * ```
  4928. */
  4929. trimBoundary:function (ignoreEnd) {
  4930. this.txtToElmBoundary();
  4931. var start = this.startContainer,
  4932. offset = this.startOffset,
  4933. collapsed = this.collapsed,
  4934. end = this.endContainer;
  4935. if (start.nodeType == 3) {
  4936. if (offset == 0) {
  4937. this.setStartBefore(start);
  4938. } else {
  4939. if (offset >= start.nodeValue.length) {
  4940. this.setStartAfter(start);
  4941. } else {
  4942. var textNode = domUtils.split(start, offset);
  4943. //跟新结束边界
  4944. if (start === end) {
  4945. this.setEnd(textNode, this.endOffset - offset);
  4946. } else if (start.parentNode === end) {
  4947. this.endOffset += 1;
  4948. }
  4949. this.setStartBefore(textNode);
  4950. }
  4951. }
  4952. if (collapsed) {
  4953. return this.collapse(true);
  4954. }
  4955. }
  4956. if (!ignoreEnd) {
  4957. offset = this.endOffset;
  4958. end = this.endContainer;
  4959. if (end.nodeType == 3) {
  4960. if (offset == 0) {
  4961. this.setEndBefore(end);
  4962. } else {
  4963. offset < end.nodeValue.length && domUtils.split(end, offset);
  4964. this.setEndAfter(end);
  4965. }
  4966. }
  4967. }
  4968. return this;
  4969. },
  4970. /**
  4971. * 如果选区在文本的边界上,就扩展选区到文本的父节点上, 如果当前选区是闭合的, 则什么也不做
  4972. * @method txtToElmBoundary
  4973. * @remind 该操作不会修改dom节点
  4974. * @return { UE.dom.Range } 当前range对象
  4975. */
  4976. /**
  4977. * 如果选区在文本的边界上,就扩展选区到文本的父节点上, 如果当前选区是闭合的, 则根据参数项
  4978. * ignoreCollapsed 的值决定是否执行该调整
  4979. * @method txtToElmBoundary
  4980. * @param { Boolean } ignoreCollapsed 是否忽略选区的闭合状态, 如果该参数取值为true, 则
  4981. * 不论选区是否闭合, 都会执行该操作, 反之, 则不会对闭合的选区执行该操作
  4982. * @return { UE.dom.Range } 当前range对象
  4983. */
  4984. txtToElmBoundary:function (ignoreCollapsed) {
  4985. function adjust(r, c) {
  4986. var container = r[c + 'Container'],
  4987. offset = r[c + 'Offset'];
  4988. if (container.nodeType == 3) {
  4989. if (!offset) {
  4990. r['set' + c.replace(/(\w)/, function (a) {
  4991. return a.toUpperCase();
  4992. }) + 'Before'](container);
  4993. } else if (offset >= container.nodeValue.length) {
  4994. r['set' + c.replace(/(\w)/, function (a) {
  4995. return a.toUpperCase();
  4996. }) + 'After' ](container);
  4997. }
  4998. }
  4999. }
  5000. if (ignoreCollapsed || !this.collapsed) {
  5001. adjust(this, 'start');
  5002. adjust(this, 'end');
  5003. }
  5004. return this;
  5005. },
  5006. /**
  5007. * 在当前选区的开始位置前插入节点,新插入的节点会被该range包含
  5008. * @method insertNode
  5009. * @param { Node } node 需要插入的节点
  5010. * @remind 插入的节点可以是一个DocumentFragment依次插入多个节点
  5011. * @return { UE.dom.Range } 当前range对象
  5012. */
  5013. insertNode:function (node) {
  5014. var first = node, length = 1;
  5015. if (node.nodeType == 11) {
  5016. first = node.firstChild;
  5017. length = node.childNodes.length;
  5018. }
  5019. this.trimBoundary(true);
  5020. var start = this.startContainer,
  5021. offset = this.startOffset;
  5022. var nextNode = start.childNodes[ offset ];
  5023. if (nextNode) {
  5024. start.insertBefore(node, nextNode);
  5025. } else {
  5026. start.appendChild(node);
  5027. }
  5028. if (first.parentNode === this.endContainer) {
  5029. this.endOffset = this.endOffset + length;
  5030. }
  5031. return this.setStartBefore(first);
  5032. },
  5033. /**
  5034. * 闭合选区到当前选区的开始位置, 并且定位光标到闭合后的位置
  5035. * @method setCursor
  5036. * @return { UE.dom.Range } 当前range对象
  5037. * @see UE.dom.Range:collapse()
  5038. */
  5039. /**
  5040. * 闭合选区,可以根据参数toEnd的值控制选区是向前闭合还是向后闭合, 并且定位光标到闭合后的位置。
  5041. * @method setCursor
  5042. * @param { Boolean } toEnd 是否向后闭合, 如果为true, 则闭合选区时, 将向结束容器方向闭合,
  5043. * 反之,则向开始容器方向闭合
  5044. * @return { UE.dom.Range } 当前range对象
  5045. * @see UE.dom.Range:collapse(Boolean)
  5046. */
  5047. setCursor:function (toEnd, noFillData) {
  5048. return this.collapse(!toEnd).select(noFillData);
  5049. },
  5050. /**
  5051. * 创建当前range的一个书签,记录下当前range的位置,方便当dom树改变时,还能找回原来的选区位置
  5052. * @method createBookmark
  5053. * @param { Boolean } serialize 控制返回的标记位置是对当前位置的引用还是ID,如果该值为true,则
  5054. * 返回标记位置的ID, 反之则返回标记位置节点的引用
  5055. * @return { Object } 返回一个书签记录键值对, 其包含的key有: start => 开始标记的ID或者引用,
  5056. * end => 结束标记的ID或引用, id => 当前标记的类型, 如果为true,则表示
  5057. * 返回的记录的类型为ID, 反之则为引用
  5058. */
  5059. createBookmark:function (serialize, same) {
  5060. var endNode,
  5061. startNode = this.document.createElement('span');
  5062. startNode.style.cssText = 'display:none;line-height:0px;';
  5063. startNode.appendChild(this.document.createTextNode('\u200D'));
  5064. startNode.id = '_baidu_bookmark_start_' + (same ? '' : guid++);
  5065. if (!this.collapsed) {
  5066. endNode = startNode.cloneNode(true);
  5067. endNode.id = '_baidu_bookmark_end_' + (same ? '' : guid++);
  5068. }
  5069. this.insertNode(startNode);
  5070. if (endNode) {
  5071. this.collapse().insertNode(endNode).setEndBefore(endNode);
  5072. }
  5073. this.setStartAfter(startNode);
  5074. return {
  5075. start:serialize ? startNode.id : startNode,
  5076. end:endNode ? serialize ? endNode.id : endNode : null,
  5077. id:serialize
  5078. }
  5079. },
  5080. /**
  5081. * 调整当前range的边界到书签位置,并删除该书签对象所标记的位置内的节点
  5082. * @method moveToBookmark
  5083. * @param { BookMark } bookmark createBookmark所创建的标签对象
  5084. * @return { UE.dom.Range } 当前range对象
  5085. * @see UE.dom.Range:createBookmark(Boolean)
  5086. */
  5087. moveToBookmark:function (bookmark) {
  5088. var start = bookmark.id ? this.document.getElementById(bookmark.start) : bookmark.start,
  5089. end = bookmark.end && bookmark.id ? this.document.getElementById(bookmark.end) : bookmark.end;
  5090. this.setStartBefore(start);
  5091. domUtils.remove(start);
  5092. if (end) {
  5093. this.setEndBefore(end);
  5094. domUtils.remove(end);
  5095. } else {
  5096. this.collapse(true);
  5097. }
  5098. return this;
  5099. },
  5100. /**
  5101. * 调整range的边界,使其"放大"到最近的父节点
  5102. * @method enlarge
  5103. * @remind 会引起选区的变化
  5104. * @return { UE.dom.Range } 当前range对象
  5105. */
  5106. /**
  5107. * 调整range的边界,使其"放大"到最近的父节点,根据参数 toBlock 的取值, 可以
  5108. * 要求扩大之后的父节点是block节点
  5109. * @method enlarge
  5110. * @param { Boolean } toBlock 是否要求扩大之后的父节点必须是block节点
  5111. * @return { UE.dom.Range } 当前range对象
  5112. */
  5113. enlarge:function (toBlock, stopFn) {
  5114. var isBody = domUtils.isBody,
  5115. pre, node, tmp = this.document.createTextNode('');
  5116. if (toBlock) {
  5117. node = this.startContainer;
  5118. if (node.nodeType == 1) {
  5119. if (node.childNodes[this.startOffset]) {
  5120. pre = node = node.childNodes[this.startOffset]
  5121. } else {
  5122. node.appendChild(tmp);
  5123. pre = node = tmp;
  5124. }
  5125. } else {
  5126. pre = node;
  5127. }
  5128. while (1) {
  5129. if (domUtils.isBlockElm(node)) {
  5130. node = pre;
  5131. while ((pre = node.previousSibling) && !domUtils.isBlockElm(pre)) {
  5132. node = pre;
  5133. }
  5134. this.setStartBefore(node);
  5135. break;
  5136. }
  5137. pre = node;
  5138. node = node.parentNode;
  5139. }
  5140. node = this.endContainer;
  5141. if (node.nodeType == 1) {
  5142. if (pre = node.childNodes[this.endOffset]) {
  5143. node.insertBefore(tmp, pre);
  5144. } else {
  5145. node.appendChild(tmp);
  5146. }
  5147. pre = node = tmp;
  5148. } else {
  5149. pre = node;
  5150. }
  5151. while (1) {
  5152. if (domUtils.isBlockElm(node)) {
  5153. node = pre;
  5154. while ((pre = node.nextSibling) && !domUtils.isBlockElm(pre)) {
  5155. node = pre;
  5156. }
  5157. this.setEndAfter(node);
  5158. break;
  5159. }
  5160. pre = node;
  5161. node = node.parentNode;
  5162. }
  5163. if (tmp.parentNode === this.endContainer) {
  5164. this.endOffset--;
  5165. }
  5166. domUtils.remove(tmp);
  5167. }
  5168. // 扩展边界到最大
  5169. if (!this.collapsed) {
  5170. while (this.startOffset == 0) {
  5171. if (stopFn && stopFn(this.startContainer)) {
  5172. break;
  5173. }
  5174. if (isBody(this.startContainer)) {
  5175. break;
  5176. }
  5177. this.setStartBefore(this.startContainer);
  5178. }
  5179. while (this.endOffset == (this.endContainer.nodeType == 1 ? this.endContainer.childNodes.length : this.endContainer.nodeValue.length)) {
  5180. if (stopFn && stopFn(this.endContainer)) {
  5181. break;
  5182. }
  5183. if (isBody(this.endContainer)) {
  5184. break;
  5185. }
  5186. this.setEndAfter(this.endContainer);
  5187. }
  5188. }
  5189. return this;
  5190. },
  5191. enlargeToBlockElm:function(ignoreEnd){
  5192. while(!domUtils.isBlockElm(this.startContainer)){
  5193. this.setStartBefore(this.startContainer);
  5194. }
  5195. if(!ignoreEnd){
  5196. while(!domUtils.isBlockElm(this.endContainer)){
  5197. this.setEndAfter(this.endContainer);
  5198. }
  5199. }
  5200. return this;
  5201. },
  5202. /**
  5203. * 调整Range的边界,使其"缩小"到最合适的位置
  5204. * @method adjustmentBoundary
  5205. * @return { UE.dom.Range } 当前range对象
  5206. * @see UE.dom.Range:shrinkBoundary()
  5207. */
  5208. adjustmentBoundary:function () {
  5209. if (!this.collapsed) {
  5210. while (!domUtils.isBody(this.startContainer) &&
  5211. this.startOffset == this.startContainer[this.startContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length &&
  5212. this.startContainer[this.startContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length
  5213. ) {
  5214. this.setStartAfter(this.startContainer);
  5215. }
  5216. while (!domUtils.isBody(this.endContainer) && !this.endOffset &&
  5217. this.endContainer[this.endContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length
  5218. ) {
  5219. this.setEndBefore(this.endContainer);
  5220. }
  5221. }
  5222. return this;
  5223. },
  5224. /**
  5225. * 给range选区中的内容添加给定的inline标签
  5226. * @method applyInlineStyle
  5227. * @param { String } tagName 需要添加的标签名
  5228. * @example
  5229. * ```html
  5230. * <p>xxxx[xxxx]x</p> ==> range.applyInlineStyle("strong") ==> <p>xxxx[<strong>xxxx</strong>]x</p>
  5231. * ```
  5232. */
  5233. /**
  5234. * 给range选区中的内容添加给定的inline标签, 并且为标签附加上一些初始化属性。
  5235. * @method applyInlineStyle
  5236. * @param { String } tagName 需要添加的标签名
  5237. * @param { Object } attrs 跟随新添加的标签的属性
  5238. * @return { UE.dom.Range } 当前选区
  5239. * @example
  5240. * ```html
  5241. * <p>xxxx[xxxx]x</p>
  5242. *
  5243. * ==>
  5244. *
  5245. * <!-- 执行操作 -->
  5246. * range.applyInlineStyle("strong",{"style":"font-size:12px"})
  5247. *
  5248. * ==>
  5249. *
  5250. * <p>xxxx[<strong style="font-size:12px">xxxx</strong>]x</p>
  5251. * ```
  5252. */
  5253. applyInlineStyle:function (tagName, attrs, list) {
  5254. if (this.collapsed)return this;
  5255. this.trimBoundary().enlarge(false,
  5256. function (node) {
  5257. return node.nodeType == 1 && domUtils.isBlockElm(node)
  5258. }).adjustmentBoundary();
  5259. var bookmark = this.createBookmark(),
  5260. end = bookmark.end,
  5261. filterFn = function (node) {
  5262. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' : !domUtils.isWhitespace(node);
  5263. },
  5264. current = domUtils.getNextDomNode(bookmark.start, false, filterFn),
  5265. node,
  5266. pre,
  5267. range = this.cloneRange();
  5268. while (current && (domUtils.getPosition(current, end) & domUtils.POSITION_PRECEDING)) {
  5269. if (current.nodeType == 3 || dtd[tagName][current.tagName]) {
  5270. range.setStartBefore(current);
  5271. node = current;
  5272. while (node && (node.nodeType == 3 || dtd[tagName][node.tagName]) && node !== end) {
  5273. pre = node;
  5274. node = domUtils.getNextDomNode(node, node.nodeType == 1, null, function (parent) {
  5275. return dtd[tagName][parent.tagName];
  5276. });
  5277. }
  5278. var frag = range.setEndAfter(pre).extractContents(), elm;
  5279. if (list && list.length > 0) {
  5280. var level, top;
  5281. top = level = list[0].cloneNode(false);
  5282. for (var i = 1, ci; ci = list[i++];) {
  5283. level.appendChild(ci.cloneNode(false));
  5284. level = level.firstChild;
  5285. }
  5286. elm = level;
  5287. } else {
  5288. elm = range.document.createElement(tagName);
  5289. }
  5290. if (attrs) {
  5291. domUtils.setAttributes(elm, attrs);
  5292. }
  5293. elm.appendChild(frag);
  5294. range.insertNode(list ? top : elm);
  5295. //处理下滑线在a上的情况
  5296. var aNode;
  5297. if (tagName == 'span' && attrs.style && /text\-decoration/.test(attrs.style) && (aNode = domUtils.findParentByTagName(elm, 'a', true))) {
  5298. domUtils.setAttributes(aNode, attrs);
  5299. domUtils.remove(elm, true);
  5300. elm = aNode;
  5301. } else {
  5302. domUtils.mergeSibling(elm);
  5303. domUtils.clearEmptySibling(elm);
  5304. }
  5305. //去除子节点相同的
  5306. domUtils.mergeChild(elm, attrs);
  5307. current = domUtils.getNextDomNode(elm, false, filterFn);
  5308. domUtils.mergeToParent(elm);
  5309. if (node === end) {
  5310. break;
  5311. }
  5312. } else {
  5313. current = domUtils.getNextDomNode(current, true, filterFn);
  5314. }
  5315. }
  5316. return this.moveToBookmark(bookmark);
  5317. },
  5318. /**
  5319. * 移除当前选区内指定的inline标签,但保留其中的内容
  5320. * @method removeInlineStyle
  5321. * @param { String } tagName 需要移除的标签名
  5322. * @return { UE.dom.Range } 当前的range对象
  5323. * @example
  5324. * ```html
  5325. * xx[x<span>xxx<em>yyy</em>zz]z</span> => range.removeInlineStyle(["em"]) => xx[x<span>xxxyyyzz]z</span>
  5326. * ```
  5327. */
  5328. /**
  5329. * 移除当前选区内指定的一组inline标签,但保留其中的内容
  5330. * @method removeInlineStyle
  5331. * @param { Array } tagNameArr 需要移除的标签名的数组
  5332. * @return { UE.dom.Range } 当前的range对象
  5333. * @see UE.dom.Range:removeInlineStyle(String)
  5334. */
  5335. removeInlineStyle:function (tagNames) {
  5336. if (this.collapsed)return this;
  5337. tagNames = utils.isArray(tagNames) ? tagNames : [tagNames];
  5338. this.shrinkBoundary().adjustmentBoundary();
  5339. var start = this.startContainer, end = this.endContainer;
  5340. while (1) {
  5341. if (start.nodeType == 1) {
  5342. if (utils.indexOf(tagNames, start.tagName.toLowerCase()) > -1) {
  5343. break;
  5344. }
  5345. if (start.tagName.toLowerCase() == 'body') {
  5346. start = null;
  5347. break;
  5348. }
  5349. }
  5350. start = start.parentNode;
  5351. }
  5352. while (1) {
  5353. if (end.nodeType == 1) {
  5354. if (utils.indexOf(tagNames, end.tagName.toLowerCase()) > -1) {
  5355. break;
  5356. }
  5357. if (end.tagName.toLowerCase() == 'body') {
  5358. end = null;
  5359. break;
  5360. }
  5361. }
  5362. end = end.parentNode;
  5363. }
  5364. var bookmark = this.createBookmark(),
  5365. frag,
  5366. tmpRange;
  5367. if (start) {
  5368. tmpRange = this.cloneRange().setEndBefore(bookmark.start).setStartBefore(start);
  5369. frag = tmpRange.extractContents();
  5370. tmpRange.insertNode(frag);
  5371. domUtils.clearEmptySibling(start, true);
  5372. start.parentNode.insertBefore(bookmark.start, start);
  5373. }
  5374. if (end) {
  5375. tmpRange = this.cloneRange().setStartAfter(bookmark.end).setEndAfter(end);
  5376. frag = tmpRange.extractContents();
  5377. tmpRange.insertNode(frag);
  5378. domUtils.clearEmptySibling(end, false, true);
  5379. end.parentNode.insertBefore(bookmark.end, end.nextSibling);
  5380. }
  5381. var current = domUtils.getNextDomNode(bookmark.start, false, function (node) {
  5382. return node.nodeType == 1;
  5383. }), next;
  5384. while (current && current !== bookmark.end) {
  5385. next = domUtils.getNextDomNode(current, true, function (node) {
  5386. return node.nodeType == 1;
  5387. });
  5388. if (utils.indexOf(tagNames, current.tagName.toLowerCase()) > -1) {
  5389. domUtils.remove(current, true);
  5390. }
  5391. current = next;
  5392. }
  5393. return this.moveToBookmark(bookmark);
  5394. },
  5395. /**
  5396. * 获取当前选中的自闭合的节点
  5397. * @method getClosedNode
  5398. * @return { Node | NULL } 如果当前选中的是自闭合节点, 则返回该节点, 否则返回NULL
  5399. */
  5400. getClosedNode:function () {
  5401. var node;
  5402. if (!this.collapsed) {
  5403. var range = this.cloneRange().adjustmentBoundary().shrinkBoundary();
  5404. if (selectOneNode(range)) {
  5405. var child = range.startContainer.childNodes[range.startOffset];
  5406. if (child && child.nodeType == 1 && (dtd.$empty[child.tagName] || dtd.$nonChild[child.tagName])) {
  5407. node = child;
  5408. }
  5409. }
  5410. }
  5411. return node;
  5412. },
  5413. /**
  5414. * 在页面上高亮range所表示的选区
  5415. * @method select
  5416. * @return { UE.dom.Range } 返回当前Range对象
  5417. */
  5418. //这里不区分ie9以上,trace:3824
  5419. select:browser.ie ? function (noFillData, textRange) {
  5420. var nativeRange;
  5421. if (!this.collapsed)
  5422. this.shrinkBoundary();
  5423. var node = this.getClosedNode();
  5424. if (node && !textRange) {
  5425. try {
  5426. nativeRange = this.document.body.createControlRange();
  5427. nativeRange.addElement(node);
  5428. nativeRange.select();
  5429. } catch (e) {}
  5430. return this;
  5431. }
  5432. var bookmark = this.createBookmark(),
  5433. start = bookmark.start,
  5434. end;
  5435. nativeRange = this.document.body.createTextRange();
  5436. nativeRange.moveToElementText(start);
  5437. nativeRange.moveStart('character', 1);
  5438. if (!this.collapsed) {
  5439. var nativeRangeEnd = this.document.body.createTextRange();
  5440. end = bookmark.end;
  5441. nativeRangeEnd.moveToElementText(end);
  5442. nativeRange.setEndPoint('EndToEnd', nativeRangeEnd);
  5443. } else {
  5444. if (!noFillData && this.startContainer.nodeType != 3) {
  5445. //使用<span>|x<span>固定住光标
  5446. var tmpText = this.document.createTextNode(fillChar),
  5447. tmp = this.document.createElement('span');
  5448. tmp.appendChild(this.document.createTextNode(fillChar));
  5449. start.parentNode.insertBefore(tmp, start);
  5450. start.parentNode.insertBefore(tmpText, start);
  5451. //当点b,i,u时,不能清除i上边的b
  5452. removeFillData(this.document, tmpText);
  5453. fillData = tmpText;
  5454. mergeSibling(tmp, 'previousSibling');
  5455. mergeSibling(start, 'nextSibling');
  5456. nativeRange.moveStart('character', -1);
  5457. nativeRange.collapse(true);
  5458. }
  5459. }
  5460. this.moveToBookmark(bookmark);
  5461. tmp && domUtils.remove(tmp);
  5462. //IE在隐藏状态下不支持range操作,catch一下
  5463. try {
  5464. nativeRange.select();
  5465. } catch (e) {
  5466. }
  5467. return this;
  5468. } : function (notInsertFillData) {
  5469. function checkOffset(rng){
  5470. function check(node,offset,dir){
  5471. if(node.nodeType == 3 && node.nodeValue.length < offset){
  5472. rng[dir + 'Offset'] = node.nodeValue.length
  5473. }
  5474. }
  5475. check(rng.startContainer,rng.startOffset,'start');
  5476. check(rng.endContainer,rng.endOffset,'end');
  5477. }
  5478. var win = domUtils.getWindow(this.document),
  5479. sel = win.getSelection(),
  5480. txtNode;
  5481. //FF下关闭自动长高时滚动条在关闭dialog时会跳
  5482. //ff下如果不body.focus将不能定位闭合光标到编辑器内
  5483. browser.gecko ? this.document.body.focus() : win.focus();
  5484. if (sel) {
  5485. sel.removeAllRanges();
  5486. // trace:870 chrome/safari后边是br对于闭合得range不能定位 所以去掉了判断
  5487. // this.startContainer.nodeType != 3 &&! ((child = this.startContainer.childNodes[this.startOffset]) && child.nodeType == 1 && child.tagName == 'BR'
  5488. if (this.collapsed && !notInsertFillData) {
  5489. // //opear如果没有节点接着,原生的不能够定位,不能在body的第一级插入空白节点
  5490. // if (notInsertFillData && browser.opera && !domUtils.isBody(this.startContainer) && this.startContainer.nodeType == 1) {
  5491. // var tmp = this.document.createTextNode('');
  5492. // this.insertNode(tmp).setStart(tmp, 0).collapse(true);
  5493. // }
  5494. //
  5495. //处理光标落在文本节点的情况
  5496. //处理以下的情况
  5497. //<b>|xxxx</b>
  5498. //<b>xxxx</b>|xxxx
  5499. //xxxx<b>|</b>
  5500. var start = this.startContainer,child = start;
  5501. if(start.nodeType == 1){
  5502. child = start.childNodes[this.startOffset];
  5503. }
  5504. if( !(start.nodeType == 3 && this.startOffset) &&
  5505. (child ?
  5506. (!child.previousSibling || child.previousSibling.nodeType != 3)
  5507. :
  5508. (!start.lastChild || start.lastChild.nodeType != 3)
  5509. )
  5510. ){
  5511. txtNode = this.document.createTextNode(fillChar);
  5512. //跟着前边走
  5513. this.insertNode(txtNode);
  5514. removeFillData(this.document, txtNode);
  5515. mergeSibling(txtNode, 'previousSibling');
  5516. mergeSibling(txtNode, 'nextSibling');
  5517. fillData = txtNode;
  5518. this.setStart(txtNode, browser.webkit ? 1 : 0).collapse(true);
  5519. }
  5520. }
  5521. var nativeRange = this.document.createRange();
  5522. if(this.collapsed && browser.opera && this.startContainer.nodeType == 1){
  5523. var child = this.startContainer.childNodes[this.startOffset];
  5524. if(!child){
  5525. //往前靠拢
  5526. child = this.startContainer.lastChild;
  5527. if( child && domUtils.isBr(child)){
  5528. this.setStartBefore(child).collapse(true);
  5529. }
  5530. }else{
  5531. //向后靠拢
  5532. while(child && domUtils.isBlockElm(child)){
  5533. if(child.nodeType == 1 && child.childNodes[0]){
  5534. child = child.childNodes[0]
  5535. }else{
  5536. break;
  5537. }
  5538. }
  5539. child && this.setStartBefore(child).collapse(true)
  5540. }
  5541. }
  5542. //是createAddress最后一位算的不准,现在这里进行微调
  5543. checkOffset(this);
  5544. nativeRange.setStart(this.startContainer, this.startOffset);
  5545. nativeRange.setEnd(this.endContainer, this.endOffset);
  5546. sel.addRange(nativeRange);
  5547. }
  5548. return this;
  5549. },
  5550. /**
  5551. * 滚动到当前range开始的位置
  5552. * @method scrollToView
  5553. * @param { Window } win 当前range对象所属的window对象
  5554. * @return { UE.dom.Range } 当前Range对象
  5555. */
  5556. /**
  5557. * 滚动到距离当前range开始位置 offset 的位置处
  5558. * @method scrollToView
  5559. * @param { Window } win 当前range对象所属的window对象
  5560. * @param { Number } offset 距离range开始位置处的偏移量, 如果为正数, 则向下偏移, 反之, 则向上偏移
  5561. * @return { UE.dom.Range } 当前Range对象
  5562. */
  5563. scrollToView:function (win, offset) {
  5564. win = win ? window : domUtils.getWindow(this.document);
  5565. var me = this,
  5566. span = me.document.createElement('span');
  5567. //trace:717
  5568. span.innerHTML = '&nbsp;';
  5569. me.cloneRange().insertNode(span);
  5570. domUtils.scrollToView(span, win, offset);
  5571. domUtils.remove(span);
  5572. return me;
  5573. },
  5574. /**
  5575. * 判断当前选区内容是否占位符
  5576. * @private
  5577. * @method inFillChar
  5578. * @return { Boolean } 如果是占位符返回true,否则返回false
  5579. */
  5580. inFillChar : function(){
  5581. var start = this.startContainer;
  5582. if(this.collapsed && start.nodeType == 3
  5583. && start.nodeValue.replace(new RegExp('^' + domUtils.fillChar),'').length + 1 == start.nodeValue.length
  5584. ){
  5585. return true;
  5586. }
  5587. return false;
  5588. },
  5589. /**
  5590. * 保存
  5591. * @method createAddress
  5592. * @private
  5593. * @return { Boolean } 返回开始和结束的位置
  5594. * @example
  5595. * ```html
  5596. * <body>
  5597. * <p>
  5598. * aaaa
  5599. * <em>
  5600. * <!-- 选区开始 -->
  5601. * bbbb
  5602. * <!-- 选区结束 -->
  5603. * </em>
  5604. * </p>
  5605. *
  5606. * <script>
  5607. * //output: {startAddress:[0,1,0,0],endAddress:[0,1,0,4]}
  5608. * console.log( range.createAddress() );
  5609. * </script>
  5610. * </body>
  5611. * ```
  5612. */
  5613. createAddress : function(ignoreEnd,ignoreTxt){
  5614. var addr = {},me = this;
  5615. function getAddress(isStart){
  5616. var node = isStart ? me.startContainer : me.endContainer;
  5617. var parents = domUtils.findParents(node,true,function(node){return !domUtils.isBody(node)}),
  5618. addrs = [];
  5619. for(var i = 0,ci;ci = parents[i++];){
  5620. addrs.push(domUtils.getNodeIndex(ci,ignoreTxt));
  5621. }
  5622. var firstIndex = 0;
  5623. if(ignoreTxt){
  5624. if(node.nodeType == 3){
  5625. var tmpNode = node.previousSibling;
  5626. while(tmpNode && tmpNode.nodeType == 3){
  5627. firstIndex += tmpNode.nodeValue.replace(fillCharReg,'').length;
  5628. tmpNode = tmpNode.previousSibling;
  5629. }
  5630. firstIndex += (isStart ? me.startOffset : me.endOffset)// - (fillCharReg.test(node.nodeValue) ? 1 : 0 )
  5631. }else{
  5632. node = node.childNodes[ isStart ? me.startOffset : me.endOffset];
  5633. if(node){
  5634. firstIndex = domUtils.getNodeIndex(node,ignoreTxt);
  5635. }else{
  5636. node = isStart ? me.startContainer : me.endContainer;
  5637. var first = node.firstChild;
  5638. while(first){
  5639. if(domUtils.isFillChar(first)){
  5640. first = first.nextSibling;
  5641. continue;
  5642. }
  5643. firstIndex++;
  5644. if(first.nodeType == 3){
  5645. while( first && first.nodeType == 3){
  5646. first = first.nextSibling;
  5647. }
  5648. }else{
  5649. first = first.nextSibling;
  5650. }
  5651. }
  5652. }
  5653. }
  5654. }else{
  5655. firstIndex = isStart ? domUtils.isFillChar(node) ? 0 : me.startOffset : me.endOffset
  5656. }
  5657. if(firstIndex < 0){
  5658. firstIndex = 0;
  5659. }
  5660. addrs.push(firstIndex);
  5661. return addrs;
  5662. }
  5663. addr.startAddress = getAddress(true);
  5664. if(!ignoreEnd){
  5665. addr.endAddress = me.collapsed ? [].concat(addr.startAddress) : getAddress();
  5666. }
  5667. return addr;
  5668. },
  5669. /**
  5670. * 保存
  5671. * @method createAddress
  5672. * @private
  5673. * @return { Boolean } 返回开始和结束的位置
  5674. * @example
  5675. * ```html
  5676. * <body>
  5677. * <p>
  5678. * aaaa
  5679. * <em>
  5680. * <!-- 选区开始 -->
  5681. * bbbb
  5682. * <!-- 选区结束 -->
  5683. * </em>
  5684. * </p>
  5685. *
  5686. * <script>
  5687. * var range = editor.selection.getRange();
  5688. * range.moveToAddress({startAddress:[0,1,0,0],endAddress:[0,1,0,4]});
  5689. * range.select();
  5690. * //output: 'bbbb'
  5691. * console.log(editor.selection.getText());
  5692. * </script>
  5693. * </body>
  5694. * ```
  5695. */
  5696. moveToAddress : function(addr,ignoreEnd){
  5697. var me = this;
  5698. function getNode(address,isStart){
  5699. var tmpNode = me.document.body,
  5700. parentNode,offset;
  5701. for(var i= 0,ci,l=address.length;i<l;i++){
  5702. ci = address[i];
  5703. parentNode = tmpNode;
  5704. tmpNode = tmpNode.childNodes[ci];
  5705. if(!tmpNode){
  5706. offset = ci;
  5707. break;
  5708. }
  5709. }
  5710. if(isStart){
  5711. if(tmpNode){
  5712. me.setStartBefore(tmpNode)
  5713. }else{
  5714. me.setStart(parentNode,offset)
  5715. }
  5716. }else{
  5717. if(tmpNode){
  5718. me.setEndBefore(tmpNode)
  5719. }else{
  5720. me.setEnd(parentNode,offset)
  5721. }
  5722. }
  5723. }
  5724. getNode(addr.startAddress,true);
  5725. !ignoreEnd && addr.endAddress && getNode(addr.endAddress);
  5726. return me;
  5727. },
  5728. /**
  5729. * 判断给定的Range对象是否和当前Range对象表示的是同一个选区
  5730. * @method equals
  5731. * @param { UE.dom.Range } 需要判断的Range对象
  5732. * @return { Boolean } 如果给定的Range对象与当前Range对象表示的是同一个选区, 则返回true, 否则返回false
  5733. */
  5734. equals : function(rng){
  5735. for(var p in this){
  5736. if(this.hasOwnProperty(p)){
  5737. if(this[p] !== rng[p])
  5738. return false
  5739. }
  5740. }
  5741. return true;
  5742. },
  5743. /**
  5744. * 遍历range内的节点。每当遍历一个节点时, 都会执行参数项 doFn 指定的函数, 该函数的接受当前遍历的节点
  5745. * 作为其参数。
  5746. * @method traversal
  5747. * @param { Function } doFn 对每个遍历的节点要执行的方法, 该方法接受当前遍历的节点作为其参数
  5748. * @return { UE.dom.Range } 当前range对象
  5749. * @example
  5750. * ```html
  5751. *
  5752. * <body>
  5753. *
  5754. * <!-- 选区开始 -->
  5755. * <span></span>
  5756. * <a></a>
  5757. * <!-- 选区结束 -->
  5758. * </body>
  5759. *
  5760. * <script>
  5761. *
  5762. * //output: <span></span><a></a>
  5763. * console.log( range.cloneContents() );
  5764. *
  5765. * range.traversal( function ( node ) {
  5766. *
  5767. * if ( node.nodeType === 1 ) {
  5768. * node.className = "test";
  5769. * }
  5770. *
  5771. * } );
  5772. *
  5773. * //output: <span class="test"></span><a class="test"></a>
  5774. * console.log( range.cloneContents() );
  5775. *
  5776. * </script>
  5777. * ```
  5778. */
  5779. /**
  5780. * 遍历range内的节点。
  5781. * 每当遍历一个节点时, 都会执行参数项 doFn 指定的函数, 该函数的接受当前遍历的节点
  5782. * 作为其参数。
  5783. * 可以通过参数项 filterFn 来指定一个过滤器, 只有符合该过滤器过滤规则的节点才会触
  5784. * 发doFn函数的执行
  5785. * @method traversal
  5786. * @param { Function } doFn 对每个遍历的节点要执行的方法, 该方法接受当前遍历的节点作为其参数
  5787. * @param { Function } filterFn 过滤器, 该函数接受当前遍历的节点作为参数, 如果该节点满足过滤
  5788. * 规则, 请返回true, 该节点会触发doFn, 否则, 请返回false, 则该节点不
  5789. * 会触发doFn。
  5790. * @return { UE.dom.Range } 当前range对象
  5791. * @see UE.dom.Range:traversal(Function)
  5792. * @example
  5793. * ```html
  5794. *
  5795. * <body>
  5796. *
  5797. * <!-- 选区开始 -->
  5798. * <span></span>
  5799. * <a></a>
  5800. * <!-- 选区结束 -->
  5801. * </body>
  5802. *
  5803. * <script>
  5804. *
  5805. * //output: <span></span><a></a>
  5806. * console.log( range.cloneContents() );
  5807. *
  5808. * range.traversal( function ( node ) {
  5809. *
  5810. * node.className = "test";
  5811. *
  5812. * }, function ( node ) {
  5813. * return node.nodeType === 1;
  5814. * } );
  5815. *
  5816. * //output: <span class="test"></span><a class="test"></a>
  5817. * console.log( range.cloneContents() );
  5818. *
  5819. * </script>
  5820. * ```
  5821. */
  5822. traversal:function(doFn,filterFn){
  5823. if (this.collapsed)
  5824. return this;
  5825. var bookmark = this.createBookmark(),
  5826. end = bookmark.end,
  5827. current = domUtils.getNextDomNode(bookmark.start, false, filterFn);
  5828. while (current && current !== end && (domUtils.getPosition(current, end) & domUtils.POSITION_PRECEDING)) {
  5829. var tmpNode = domUtils.getNextDomNode(current,false,filterFn);
  5830. doFn(current);
  5831. current = tmpNode;
  5832. }
  5833. return this.moveToBookmark(bookmark);
  5834. }
  5835. };
  5836. })();
  5837. // core/Selection.js
  5838. /**
  5839. * 选集
  5840. * @file
  5841. * @module UE.dom
  5842. * @class Selection
  5843. * @since 1.2.6.1
  5844. */
  5845. /**
  5846. * 选区集合
  5847. * @unfile
  5848. * @module UE.dom
  5849. * @class Selection
  5850. */
  5851. (function () {
  5852. function getBoundaryInformation( range, start ) {
  5853. var getIndex = domUtils.getNodeIndex;
  5854. range = range.duplicate();
  5855. range.collapse( start );
  5856. var parent = range.parentElement();
  5857. //如果节点里没有子节点,直接退出
  5858. if ( !parent.hasChildNodes() ) {
  5859. return {container:parent, offset:0};
  5860. }
  5861. var siblings = parent.children,
  5862. child,
  5863. testRange = range.duplicate(),
  5864. startIndex = 0, endIndex = siblings.length - 1, index = -1,
  5865. distance;
  5866. while ( startIndex <= endIndex ) {
  5867. index = Math.floor( (startIndex + endIndex) / 2 );
  5868. child = siblings[index];
  5869. testRange.moveToElementText( child );
  5870. var position = testRange.compareEndPoints( 'StartToStart', range );
  5871. if ( position > 0 ) {
  5872. endIndex = index - 1;
  5873. } else if ( position < 0 ) {
  5874. startIndex = index + 1;
  5875. } else {
  5876. //trace:1043
  5877. return {container:parent, offset:getIndex( child )};
  5878. }
  5879. }
  5880. if ( index == -1 ) {
  5881. testRange.moveToElementText( parent );
  5882. testRange.setEndPoint( 'StartToStart', range );
  5883. distance = testRange.text.replace( /(\r\n|\r)/g, '\n' ).length;
  5884. siblings = parent.childNodes;
  5885. if ( !distance ) {
  5886. child = siblings[siblings.length - 1];
  5887. return {container:child, offset:child.nodeValue.length};
  5888. }
  5889. var i = siblings.length;
  5890. while ( distance > 0 ){
  5891. distance -= siblings[ --i ].nodeValue.length;
  5892. }
  5893. return {container:siblings[i], offset:-distance};
  5894. }
  5895. testRange.collapse( position > 0 );
  5896. testRange.setEndPoint( position > 0 ? 'StartToStart' : 'EndToStart', range );
  5897. distance = testRange.text.replace( /(\r\n|\r)/g, '\n' ).length;
  5898. if ( !distance ) {
  5899. return dtd.$empty[child.tagName] || dtd.$nonChild[child.tagName] ?
  5900. {container:parent, offset:getIndex( child ) + (position > 0 ? 0 : 1)} :
  5901. {container:child, offset:position > 0 ? 0 : child.childNodes.length}
  5902. }
  5903. while ( distance > 0 ) {
  5904. try {
  5905. var pre = child;
  5906. child = child[position > 0 ? 'previousSibling' : 'nextSibling'];
  5907. distance -= child.nodeValue.length;
  5908. } catch ( e ) {
  5909. return {container:parent, offset:getIndex( pre )};
  5910. }
  5911. }
  5912. return {container:child, offset:position > 0 ? -distance : child.nodeValue.length + distance}
  5913. }
  5914. /**
  5915. * 将ieRange转换为Range对象
  5916. * @param {Range} ieRange ieRange对象
  5917. * @param {Range} range Range对象
  5918. * @return {Range} range 返回转换后的Range对象
  5919. */
  5920. function transformIERangeToRange( ieRange, range ) {
  5921. if ( ieRange.item ) {
  5922. range.selectNode( ieRange.item( 0 ) );
  5923. } else {
  5924. var bi = getBoundaryInformation( ieRange, true );
  5925. range.setStart( bi.container, bi.offset );
  5926. if ( ieRange.compareEndPoints( 'StartToEnd', ieRange ) != 0 ) {
  5927. bi = getBoundaryInformation( ieRange, false );
  5928. range.setEnd( bi.container, bi.offset );
  5929. }
  5930. }
  5931. return range;
  5932. }
  5933. /**
  5934. * 获得ieRange
  5935. * @param {Selection} sel Selection对象
  5936. * @return {ieRange} 得到ieRange
  5937. */
  5938. function _getIERange( sel ) {
  5939. var ieRange;
  5940. //ie下有可能报错
  5941. try {
  5942. ieRange = sel.getNative().createRange();
  5943. } catch ( e ) {
  5944. return null;
  5945. }
  5946. var el = ieRange.item ? ieRange.item( 0 ) : ieRange.parentElement();
  5947. if ( ( el.ownerDocument || el ) === sel.document ) {
  5948. return ieRange;
  5949. }
  5950. return null;
  5951. }
  5952. var Selection = dom.Selection = function ( doc ) {
  5953. var me = this, iframe;
  5954. me.document = doc;
  5955. if ( browser.ie9below ) {
  5956. iframe = domUtils.getWindow( doc ).frameElement;
  5957. domUtils.on( iframe, 'beforedeactivate', function () {
  5958. me._bakIERange = me.getIERange();
  5959. } );
  5960. domUtils.on( iframe, 'activate', function () {
  5961. try {
  5962. if ( !_getIERange( me ) && me._bakIERange ) {
  5963. me._bakIERange.select();
  5964. }
  5965. } catch ( ex ) {
  5966. }
  5967. me._bakIERange = null;
  5968. } );
  5969. }
  5970. iframe = doc = null;
  5971. };
  5972. Selection.prototype = {
  5973. rangeInBody : function(rng,txtRange){
  5974. var node = browser.ie9below || txtRange ? rng.item ? rng.item() : rng.parentElement() : rng.startContainer;
  5975. return node === this.document.body || domUtils.inDoc(node,this.document);
  5976. },
  5977. /**
  5978. * 获取原生seleciton对象
  5979. * @method getNative
  5980. * @return { Object } 获得selection对象
  5981. * @example
  5982. * ```javascript
  5983. * editor.selection.getNative();
  5984. * ```
  5985. */
  5986. getNative:function () {
  5987. var doc = this.document;
  5988. try {
  5989. return !doc ? null : browser.ie9below ? doc.selection : domUtils.getWindow( doc ).getSelection();
  5990. } catch ( e ) {
  5991. return null;
  5992. }
  5993. },
  5994. /**
  5995. * 获得ieRange
  5996. * @method getIERange
  5997. * @return { Object } 返回ie原生的Range
  5998. * @example
  5999. * ```javascript
  6000. * editor.selection.getIERange();
  6001. * ```
  6002. */
  6003. getIERange:function () {
  6004. var ieRange = _getIERange( this );
  6005. if ( !ieRange ) {
  6006. if ( this._bakIERange ) {
  6007. return this._bakIERange;
  6008. }
  6009. }
  6010. return ieRange;
  6011. },
  6012. /**
  6013. * 缓存当前选区的range和选区的开始节点
  6014. * @method cache
  6015. */
  6016. cache:function () {
  6017. this.clear();
  6018. this._cachedRange = this.getRange();
  6019. this._cachedStartElement = this.getStart();
  6020. this._cachedStartElementPath = this.getStartElementPath();
  6021. },
  6022. /**
  6023. * 获取选区开始位置的父节点到body
  6024. * @method getStartElementPath
  6025. * @return { Array } 返回父节点集合
  6026. * @example
  6027. * ```javascript
  6028. * editor.selection.getStartElementPath();
  6029. * ```
  6030. */
  6031. getStartElementPath:function () {
  6032. if ( this._cachedStartElementPath ) {
  6033. return this._cachedStartElementPath;
  6034. }
  6035. var start = this.getStart();
  6036. if ( start ) {
  6037. return domUtils.findParents( start, true, null, true )
  6038. }
  6039. return [];
  6040. },
  6041. /**
  6042. * 清空缓存
  6043. * @method clear
  6044. */
  6045. clear:function () {
  6046. this._cachedStartElementPath = this._cachedRange = this._cachedStartElement = null;
  6047. },
  6048. /**
  6049. * 编辑器是否得到了选区
  6050. * @method isFocus
  6051. */
  6052. isFocus:function () {
  6053. try {
  6054. if(browser.ie9below){
  6055. var nativeRange = _getIERange(this);
  6056. return !!(nativeRange && this.rangeInBody(nativeRange));
  6057. }else{
  6058. return !!this.getNative().rangeCount;
  6059. }
  6060. } catch ( e ) {
  6061. return false;
  6062. }
  6063. },
  6064. /**
  6065. * 获取选区对应的Range
  6066. * @method getRange
  6067. * @return { Object } 得到Range对象
  6068. * @example
  6069. * ```javascript
  6070. * editor.selection.getRange();
  6071. * ```
  6072. */
  6073. getRange:function () {
  6074. var me = this;
  6075. function optimze( range ) {
  6076. var child = me.document.body.firstChild,
  6077. collapsed = range.collapsed;
  6078. while ( child && child.firstChild ) {
  6079. range.setStart( child, 0 );
  6080. child = child.firstChild;
  6081. }
  6082. if ( !range.startContainer ) {
  6083. range.setStart( me.document.body, 0 )
  6084. }
  6085. if ( collapsed ) {
  6086. range.collapse( true );
  6087. }
  6088. }
  6089. if ( me._cachedRange != null ) {
  6090. return this._cachedRange;
  6091. }
  6092. var range = new baidu.editor.dom.Range( me.document );
  6093. if ( browser.ie9below ) {
  6094. var nativeRange = me.getIERange();
  6095. if ( nativeRange ) {
  6096. //备份的_bakIERange可能已经实效了,dom树发生了变化比如从源码模式切回来,所以try一下,实效就放到body开始位置
  6097. try{
  6098. transformIERangeToRange( nativeRange, range );
  6099. }catch(e){
  6100. optimze( range );
  6101. }
  6102. } else {
  6103. optimze( range );
  6104. }
  6105. } else {
  6106. var sel = me.getNative();
  6107. if ( sel && sel.rangeCount ) {
  6108. var firstRange = sel.getRangeAt( 0 );
  6109. var lastRange = sel.getRangeAt( sel.rangeCount - 1 );
  6110. range.setStart( firstRange.startContainer, firstRange.startOffset ).setEnd( lastRange.endContainer, lastRange.endOffset );
  6111. if ( range.collapsed && domUtils.isBody( range.startContainer ) && !range.startOffset ) {
  6112. optimze( range );
  6113. }
  6114. } else {
  6115. //trace:1734 有可能已经不在dom树上了,标识的节点
  6116. if ( this._bakRange && domUtils.inDoc( this._bakRange.startContainer, this.document ) ){
  6117. return this._bakRange;
  6118. }
  6119. optimze( range );
  6120. }
  6121. }
  6122. return this._bakRange = range;
  6123. },
  6124. /**
  6125. * 获取开始元素,用于状态反射
  6126. * @method getStart
  6127. * @return { Element } 获得开始元素
  6128. * @example
  6129. * ```javascript
  6130. * editor.selection.getStart();
  6131. * ```
  6132. */
  6133. getStart:function () {
  6134. if ( this._cachedStartElement ) {
  6135. return this._cachedStartElement;
  6136. }
  6137. var range = browser.ie9below ? this.getIERange() : this.getRange(),
  6138. tmpRange,
  6139. start, tmp, parent;
  6140. if ( browser.ie9below ) {
  6141. if ( !range ) {
  6142. //todo 给第一个值可能会有问题
  6143. return this.document.body.firstChild;
  6144. }
  6145. //control元素
  6146. if ( range.item ){
  6147. return range.item( 0 );
  6148. }
  6149. tmpRange = range.duplicate();
  6150. //修正ie下<b>x</b>[xx] 闭合后 <b>x|</b>xx
  6151. tmpRange.text.length > 0 && tmpRange.moveStart( 'character', 1 );
  6152. tmpRange.collapse( 1 );
  6153. start = tmpRange.parentElement();
  6154. parent = tmp = range.parentElement();
  6155. while ( tmp = tmp.parentNode ) {
  6156. if ( tmp == start ) {
  6157. start = parent;
  6158. break;
  6159. }
  6160. }
  6161. } else {
  6162. range.shrinkBoundary();
  6163. start = range.startContainer;
  6164. if ( start.nodeType == 1 && start.hasChildNodes() ){
  6165. start = start.childNodes[Math.min( start.childNodes.length - 1, range.startOffset )];
  6166. }
  6167. if ( start.nodeType == 3 ){
  6168. return start.parentNode;
  6169. }
  6170. }
  6171. return start;
  6172. },
  6173. /**
  6174. * 得到选区中的文本
  6175. * @method getText
  6176. * @return { String } 选区中包含的文本
  6177. * @example
  6178. * ```javascript
  6179. * editor.selection.getText();
  6180. * ```
  6181. */
  6182. getText:function () {
  6183. var nativeSel, nativeRange;
  6184. if ( this.isFocus() && (nativeSel = this.getNative()) ) {
  6185. nativeRange = browser.ie9below ? nativeSel.createRange() : nativeSel.getRangeAt( 0 );
  6186. return browser.ie9below ? nativeRange.text : nativeRange.toString();
  6187. }
  6188. return '';
  6189. },
  6190. /**
  6191. * 清除选区
  6192. * @method clearRange
  6193. * @example
  6194. * ```javascript
  6195. * editor.selection.clearRange();
  6196. * ```
  6197. */
  6198. clearRange : function(){
  6199. this.getNative()[browser.ie9below ? 'empty' : 'removeAllRanges']();
  6200. }
  6201. };
  6202. })();
  6203. // core/Editor.js
  6204. /**
  6205. * 编辑器主类,包含编辑器提供的大部分公用接口
  6206. * @file
  6207. * @module UE
  6208. * @class Editor
  6209. * @since 1.2.6.1
  6210. */
  6211. /**
  6212. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  6213. * @unfile
  6214. * @module UE
  6215. */
  6216. /**
  6217. * UEditor的核心类,为用户提供与编辑器交互的接口。
  6218. * @unfile
  6219. * @module UE
  6220. * @class Editor
  6221. */
  6222. (function () {
  6223. var uid = 0, _selectionChangeTimer;
  6224. /**
  6225. * 获取编辑器的html内容,赋值到编辑器所在表单的textarea文本域里面
  6226. * @private
  6227. * @method setValue
  6228. * @param { UE.Editor } editor 编辑器事例
  6229. */
  6230. function setValue(form, editor) {
  6231. var textarea;
  6232. if (editor.textarea) {
  6233. if (utils.isString(editor.textarea)) {
  6234. for (var i = 0, ti, tis = domUtils.getElementsByTagName(form, 'textarea'); ti = tis[i++];) {
  6235. if (ti.id == 'ueditor_textarea_' + editor.options.textarea) {
  6236. textarea = ti;
  6237. break;
  6238. }
  6239. }
  6240. } else {
  6241. textarea = editor.textarea;
  6242. }
  6243. }
  6244. if (!textarea) {
  6245. form.appendChild(textarea = domUtils.createElement(document, 'textarea', {
  6246. 'name': editor.options.textarea,
  6247. 'id': 'ueditor_textarea_' + editor.options.textarea,
  6248. 'style': "display:none"
  6249. }));
  6250. //不要产生多个textarea
  6251. editor.textarea = textarea;
  6252. }
  6253. !textarea.getAttribute('name') && textarea.setAttribute('name', editor.options.textarea );
  6254. textarea.value = editor.hasContents() ?
  6255. (editor.options.allHtmlEnabled ? editor.getAllHtml() : editor.getContent(null, null, true)) :
  6256. ''
  6257. }
  6258. function loadPlugins(me){
  6259. //初始化插件
  6260. for (var pi in UE.plugins) {
  6261. UE.plugins[pi].call(me);
  6262. }
  6263. }
  6264. function checkCurLang(I18N){
  6265. for(var lang in I18N){
  6266. return lang
  6267. }
  6268. }
  6269. function langReadied(me){
  6270. me.langIsReady = true;
  6271. me.fireEvent("langReady");
  6272. }
  6273. /**
  6274. * 编辑器准备就绪后会触发该事件
  6275. * @module UE
  6276. * @class Editor
  6277. * @event ready
  6278. * @remind render方法执行完成之后,会触发该事件
  6279. * @remind
  6280. * @example
  6281. * ```javascript
  6282. * editor.addListener( 'ready', function( editor ) {
  6283. * editor.execCommand( 'focus' ); //编辑器家在完成后,让编辑器拿到焦点
  6284. * } );
  6285. * ```
  6286. */
  6287. /**
  6288. * 执行destroy方法,会触发该事件
  6289. * @module UE
  6290. * @class Editor
  6291. * @event destroy
  6292. * @see UE.Editor:destroy()
  6293. */
  6294. /**
  6295. * 执行reset方法,会触发该事件
  6296. * @module UE
  6297. * @class Editor
  6298. * @event reset
  6299. * @see UE.Editor:reset()
  6300. */
  6301. /**
  6302. * 执行focus方法,会触发该事件
  6303. * @module UE
  6304. * @class Editor
  6305. * @event focus
  6306. * @see UE.Editor:focus(Boolean)
  6307. */
  6308. /**
  6309. * 语言加载完成会触发该事件
  6310. * @module UE
  6311. * @class Editor
  6312. * @event langReady
  6313. */
  6314. /**
  6315. * 运行命令之后会触发该命令
  6316. * @module UE
  6317. * @class Editor
  6318. * @event beforeExecCommand
  6319. */
  6320. /**
  6321. * 运行命令之后会触发该命令
  6322. * @module UE
  6323. * @class Editor
  6324. * @event afterExecCommand
  6325. */
  6326. /**
  6327. * 运行命令之前会触发该命令
  6328. * @module UE
  6329. * @class Editor
  6330. * @event firstBeforeExecCommand
  6331. */
  6332. /**
  6333. * 在getContent方法执行之前会触发该事件
  6334. * @module UE
  6335. * @class Editor
  6336. * @event beforeGetContent
  6337. * @see UE.Editor:getContent()
  6338. */
  6339. /**
  6340. * 在getContent方法执行之后会触发该事件
  6341. * @module UE
  6342. * @class Editor
  6343. * @event afterGetContent
  6344. * @see UE.Editor:getContent()
  6345. */
  6346. /**
  6347. * 在getAllHtml方法执行时会触发该事件
  6348. * @module UE
  6349. * @class Editor
  6350. * @event getAllHtml
  6351. * @see UE.Editor:getAllHtml()
  6352. */
  6353. /**
  6354. * 在setContent方法执行之前会触发该事件
  6355. * @module UE
  6356. * @class Editor
  6357. * @event beforeSetContent
  6358. * @see UE.Editor:setContent(String)
  6359. */
  6360. /**
  6361. * 在setContent方法执行之后会触发该事件
  6362. * @module UE
  6363. * @class Editor
  6364. * @event afterSetContent
  6365. * @see UE.Editor:setContent(String)
  6366. */
  6367. /**
  6368. * 每当编辑器内部选区发生改变时,将触发该事件
  6369. * @event selectionchange
  6370. * @warning 该事件的触发非常频繁,不建议在该事件的处理过程中做重量级的处理
  6371. * @example
  6372. * ```javascript
  6373. * editor.addListener( 'selectionchange', function( editor ) {
  6374. * console.log('选区发生改变');
  6375. * }
  6376. */
  6377. /**
  6378. * 在所有selectionchange的监听函数执行之前,会触发该事件
  6379. * @module UE
  6380. * @class Editor
  6381. * @event beforeSelectionChange
  6382. * @see UE.Editor:selectionchange
  6383. */
  6384. /**
  6385. * 在所有selectionchange的监听函数执行完之后,会触发该事件
  6386. * @module UE
  6387. * @class Editor
  6388. * @event afterSelectionChange
  6389. * @see UE.Editor:selectionchange
  6390. */
  6391. /**
  6392. * 编辑器内容发生改变时会触发该事件
  6393. * @module UE
  6394. * @class Editor
  6395. * @event contentChange
  6396. */
  6397. /**
  6398. * 以默认参数构建一个编辑器实例
  6399. * @constructor
  6400. * @remind 通过 改构造方法实例化的编辑器,不带ui层.需要render到一个容器,编辑器实例才能正常渲染到页面
  6401. * @example
  6402. * ```javascript
  6403. * var editor = new UE.Editor();
  6404. * editor.execCommand('blod');
  6405. * ```
  6406. * @see UE.Config
  6407. */
  6408. /**
  6409. * 以给定的参数集合创建一个编辑器实例,对于未指定的参数,将应用默认参数。
  6410. * @constructor
  6411. * @remind 通过 改构造方法实例化的编辑器,不带ui层.需要render到一个容器,编辑器实例才能正常渲染到页面
  6412. * @param { Object } setting 创建编辑器的参数
  6413. * @example
  6414. * ```javascript
  6415. * var editor = new UE.Editor();
  6416. * editor.execCommand('blod');
  6417. * ```
  6418. * @see UE.Config
  6419. */
  6420. var Editor = UE.Editor = function (options) {
  6421. var me = this;
  6422. me.uid = uid++;
  6423. EventBase.call(me);
  6424. me.commands = {};
  6425. me.options = utils.extend(utils.clone(options || {}), UEDITOR_CONFIG, true);
  6426. me.shortcutkeys = {};
  6427. me.inputRules = [];
  6428. me.outputRules = [];
  6429. //设置默认的常用属性
  6430. me.setOpt(Editor.defaultOptions(me));
  6431. /* 尝试异步加载后台配置 */
  6432. me.loadServerConfig();
  6433. if(!utils.isEmptyObject(UE.I18N)){
  6434. //修改默认的语言类型
  6435. me.options.lang = checkCurLang(UE.I18N);
  6436. UE.plugin.load(me);
  6437. langReadied(me);
  6438. }else{
  6439. utils.loadFile(document, {
  6440. src: me.options.langPath + me.options.lang + "/" + me.options.lang + ".js",
  6441. tag: "script",
  6442. type: "text/javascript",
  6443. defer: "defer"
  6444. }, function () {
  6445. UE.plugin.load(me);
  6446. langReadied(me);
  6447. });
  6448. }
  6449. UE.instants['ueditorInstant' + me.uid] = me;
  6450. };
  6451. Editor.prototype = {
  6452. registerCommand : function(name,obj){
  6453. this.commands[name] = obj;
  6454. },
  6455. /**
  6456. * 编辑器对外提供的监听ready事件的接口, 通过调用该方法,达到的效果与监听ready事件是一致的
  6457. * @method ready
  6458. * @param { Function } fn 编辑器ready之后所执行的回调, 如果在注册事件之前编辑器已经ready,将会
  6459. * 立即触发该回调。
  6460. * @remind 需要等待编辑器加载完成后才能执行的代码,可以使用该方法传入
  6461. * @example
  6462. * ```javascript
  6463. * editor.ready( function( editor ) {
  6464. * editor.setContent('初始化完毕');
  6465. * } );
  6466. * ```
  6467. * @see UE.Editor.event:ready
  6468. */
  6469. ready: function (fn) {
  6470. var me = this;
  6471. if (fn) {
  6472. me.isReady ? fn.apply(me) : me.addListener('ready', fn);
  6473. }
  6474. },
  6475. /**
  6476. * 该方法是提供给插件里面使用,设置配置项默认值
  6477. * @method setOpt
  6478. * @warning 三处设置配置项的优先级: 实例化时传入参数 > setOpt()设置 > config文件里设置
  6479. * @warning 该方法仅供编辑器插件内部和编辑器初始化时调用,其他地方不能调用。
  6480. * @param { String } key 编辑器的可接受的选项名称
  6481. * @param { * } val 该选项可接受的值
  6482. * @example
  6483. * ```javascript
  6484. * editor.setOpt( 'initContent', '欢迎使用编辑器' );
  6485. * ```
  6486. */
  6487. /**
  6488. * 该方法是提供给插件里面使用,以{key:value}集合的方式设置插件内用到的配置项默认值
  6489. * @method setOpt
  6490. * @warning 三处设置配置项的优先级: 实例化时传入参数 > setOpt()设置 > config文件里设置
  6491. * @warning 该方法仅供编辑器插件内部和编辑器初始化时调用,其他地方不能调用。
  6492. * @param { Object } options 将要设置的选项的键值对对象
  6493. * @example
  6494. * ```javascript
  6495. * editor.setOpt( {
  6496. * 'initContent': '欢迎使用编辑器'
  6497. * } );
  6498. * ```
  6499. */
  6500. setOpt: function (key, val) {
  6501. var obj = {};
  6502. if (utils.isString(key)) {
  6503. obj[key] = val
  6504. } else {
  6505. obj = key;
  6506. }
  6507. utils.extend(this.options, obj, true);
  6508. },
  6509. getOpt:function(key){
  6510. return this.options[key]
  6511. },
  6512. /**
  6513. * 销毁编辑器实例,使用textarea代替
  6514. * @method destroy
  6515. * @example
  6516. * ```javascript
  6517. * editor.destroy();
  6518. * ```
  6519. */
  6520. destroy: function () {
  6521. var me = this;
  6522. me.fireEvent('destroy');
  6523. var container = me.container.parentNode;
  6524. var textarea = me.textarea;
  6525. if (!textarea) {
  6526. textarea = document.createElement('textarea');
  6527. container.parentNode.insertBefore(textarea, container);
  6528. } else {
  6529. textarea.style.display = ''
  6530. }
  6531. textarea.style.width = me.iframe.offsetWidth + 'px';
  6532. textarea.style.height = me.iframe.offsetHeight + 'px';
  6533. textarea.value = me.getContent();
  6534. textarea.id = me.key;
  6535. container.innerHTML = '';
  6536. domUtils.remove(container);
  6537. var key = me.key;
  6538. //trace:2004
  6539. for (var p in me) {
  6540. if (me.hasOwnProperty(p)) {
  6541. delete this[p];
  6542. }
  6543. }
  6544. UE.delEditor(key);
  6545. },
  6546. /**
  6547. * 渲染编辑器的DOM到指定容器
  6548. * @method render
  6549. * @param { String } containerId 指定一个容器ID
  6550. * @remind 执行该方法,会触发ready事件
  6551. * @warning 必须且只能调用一次
  6552. */
  6553. /**
  6554. * 渲染编辑器的DOM到指定容器
  6555. * @method render
  6556. * @param { Element } containerDom 直接指定容器对象
  6557. * @remind 执行该方法,会触发ready事件
  6558. * @warning 必须且只能调用一次
  6559. */
  6560. render: function (container) {
  6561. var me = this,
  6562. options = me.options,
  6563. getStyleValue=function(attr){
  6564. return parseInt(domUtils.getComputedStyle(container,attr));
  6565. };
  6566. if (utils.isString(container)) {
  6567. container = document.getElementById(container);
  6568. }
  6569. if (container) {
  6570. if(options.initialFrameWidth){
  6571. options.minFrameWidth = options.initialFrameWidth
  6572. }else{
  6573. options.minFrameWidth = options.initialFrameWidth = container.offsetWidth;
  6574. }
  6575. if(options.initialFrameHeight){
  6576. options.minFrameHeight = options.initialFrameHeight
  6577. }else{
  6578. options.initialFrameHeight = options.minFrameHeight = container.offsetHeight;
  6579. }
  6580. container.style.width = /%$/.test(options.initialFrameWidth) ? '100%' : options.initialFrameWidth-
  6581. getStyleValue("padding-left")- getStyleValue("padding-right") +'px';
  6582. container.style.height = /%$/.test(options.initialFrameHeight) ? '100%' : options.initialFrameHeight -
  6583. getStyleValue("padding-top")- getStyleValue("padding-bottom") +'px';
  6584. container.style.zIndex = options.zIndex;
  6585. var html = ( ie && browser.version < 9 ? '' : '<!DOCTYPE html>') +
  6586. '<html xmlns=\'http://www.w3.org/1999/xhtml\' class=\'view\' ><head>' +
  6587. '<style type=\'text/css\'>' +
  6588. //设置四周的留边
  6589. '.view{padding:0;word-wrap:break-word;cursor:text;height:90%;}\n' +
  6590. //设置默认字体和字号
  6591. //font-family不能呢随便改,在safari下fillchar会有解析问题
  6592. 'body{margin:8px;font-family:sans-serif;font-size:16px;}' +
  6593. //设置段落间距
  6594. 'p{margin:5px 0;}</style>' +
  6595. ( options.iframeCssUrl ? '<link rel=\'stylesheet\' type=\'text/css\' href=\'' + utils.unhtml(options.iframeCssUrl) + '\'/>' : '' ) +
  6596. (options.initialStyle ? '<style>' + options.initialStyle + '</style>' : '') +
  6597. '</head><body class=\'view\' ></body>' +
  6598. '<script type=\'text/javascript\' ' + (ie ? 'defer=\'defer\'' : '' ) +' id=\'_initialScript\'>' +
  6599. 'setTimeout(function(){editor = window.parent.UE.instants[\'ueditorInstant' + me.uid + '\'];editor._setup(document);},0);' +
  6600. 'var _tmpScript = document.getElementById(\'_initialScript\');_tmpScript.parentNode.removeChild(_tmpScript);</script></html>';
  6601. container.appendChild(domUtils.createElement(document, 'iframe', {
  6602. id: 'ueditor_' + me.uid,
  6603. width: "100%",
  6604. height: "100%",
  6605. frameborder: "0",
  6606. //先注释掉了,加的原因忘记了,但开启会直接导致全屏模式下内容多时不会出现滚动条
  6607. // scrolling :'no',
  6608. src: 'javascript:void(function(){document.open();' + (options.customDomain && document.domain != location.hostname ? 'document.domain="' + document.domain + '";' : '') +
  6609. 'document.write("' + html + '");document.close();}())'
  6610. }));
  6611. container.style.overflow = 'hidden';
  6612. //解决如果是给定的百分比,会导致高度算不对的问题
  6613. setTimeout(function(){
  6614. if( /%$/.test(options.initialFrameWidth)){
  6615. options.minFrameWidth = options.initialFrameWidth = container.offsetWidth;
  6616. //如果这里给定宽度,会导致ie在拖动窗口大小时,编辑区域不随着变化
  6617. // container.style.width = options.initialFrameWidth + 'px';
  6618. }
  6619. if(/%$/.test(options.initialFrameHeight)){
  6620. options.minFrameHeight = options.initialFrameHeight = container.offsetHeight;
  6621. container.style.height = options.initialFrameHeight + 'px';
  6622. }
  6623. })
  6624. }
  6625. },
  6626. /**
  6627. * 编辑器初始化
  6628. * @method _setup
  6629. * @private
  6630. * @param { Element } doc 编辑器Iframe中的文档对象
  6631. */
  6632. _setup: function (doc) {
  6633. var me = this,
  6634. options = me.options;
  6635. if (ie) {
  6636. doc.body.disabled = true;
  6637. doc.body.contentEditable = true;
  6638. doc.body.disabled = false;
  6639. } else {
  6640. doc.body.contentEditable = true;
  6641. }
  6642. doc.body.spellcheck = false;
  6643. me.document = doc;
  6644. me.window = doc.defaultView || doc.parentWindow;
  6645. me.iframe = me.window.frameElement;
  6646. me.body = doc.body;
  6647. me.selection = new dom.Selection(doc);
  6648. //gecko初始化就能得到range,无法判断isFocus了
  6649. var geckoSel;
  6650. if (browser.gecko && (geckoSel = this.selection.getNative())) {
  6651. geckoSel.removeAllRanges();
  6652. }
  6653. this._initEvents();
  6654. //为form提交提供一个隐藏的textarea
  6655. for (var form = this.iframe.parentNode; !domUtils.isBody(form); form = form.parentNode) {
  6656. if (form.tagName == 'FORM') {
  6657. me.form = form;
  6658. if(me.options.autoSyncData){
  6659. domUtils.on(me.window,'blur',function(){
  6660. setValue(form,me);
  6661. });
  6662. }else{
  6663. domUtils.on(form, 'submit', function () {
  6664. setValue(this, me);
  6665. });
  6666. }
  6667. break;
  6668. }
  6669. }
  6670. if (options.initialContent) {
  6671. if (options.autoClearinitialContent) {
  6672. var oldExecCommand = me.execCommand;
  6673. me.execCommand = function () {
  6674. me.fireEvent('firstBeforeExecCommand');
  6675. return oldExecCommand.apply(me, arguments);
  6676. };
  6677. this._setDefaultContent(options.initialContent);
  6678. } else
  6679. this.setContent(options.initialContent, false, true);
  6680. }
  6681. //编辑器不能为空内容
  6682. if (domUtils.isEmptyNode(me.body)) {
  6683. me.body.innerHTML = '<p>' + (browser.ie ? '' : '<br/>') + '</p>';
  6684. }
  6685. //如果要求focus, 就把光标定位到内容开始
  6686. if (options.focus) {
  6687. setTimeout(function () {
  6688. me.focus(me.options.focusInEnd);
  6689. //如果自动清除开着,就不需要做selectionchange;
  6690. !me.options.autoClearinitialContent && me._selectionChange();
  6691. }, 0);
  6692. }
  6693. if (!me.container) {
  6694. me.container = this.iframe.parentNode;
  6695. }
  6696. if (options.fullscreen && me.ui) {
  6697. me.ui.setFullScreen(true);
  6698. }
  6699. try {
  6700. me.document.execCommand('2D-position', false, false);
  6701. } catch (e) {
  6702. }
  6703. try {
  6704. me.document.execCommand('enableInlineTableEditing', false, false);
  6705. } catch (e) {
  6706. }
  6707. try {
  6708. me.document.execCommand('enableObjectResizing', false, false);
  6709. } catch (e) {
  6710. }
  6711. //挂接快捷键
  6712. me._bindshortcutKeys();
  6713. me.isReady = 1;
  6714. me.fireEvent('ready');
  6715. options.onready && options.onready.call(me);
  6716. if (!browser.ie9below) {
  6717. domUtils.on(me.window, ['blur', 'focus'], function (e) {
  6718. //chrome下会出现alt+tab切换时,导致选区位置不对
  6719. if (e.type == 'blur') {
  6720. me._bakRange = me.selection.getRange();
  6721. try {
  6722. me._bakNativeRange = me.selection.getNative().getRangeAt(0);
  6723. me.selection.getNative().removeAllRanges();
  6724. } catch (e) {
  6725. me._bakNativeRange = null;
  6726. }
  6727. } else {
  6728. try {
  6729. me._bakRange && me._bakRange.select();
  6730. } catch (e) {
  6731. }
  6732. }
  6733. });
  6734. }
  6735. //trace:1518 ff3.6body不够寛,会导致点击空白处无法获得焦点
  6736. if (browser.gecko && browser.version <= 10902) {
  6737. //修复ff3.6初始化进来,不能点击获得焦点
  6738. me.body.contentEditable = false;
  6739. setTimeout(function () {
  6740. me.body.contentEditable = true;
  6741. }, 100);
  6742. setInterval(function () {
  6743. me.body.style.height = me.iframe.offsetHeight - 20 + 'px'
  6744. }, 100)
  6745. }
  6746. !options.isShow && me.setHide();
  6747. options.readonly && me.setDisabled();
  6748. },
  6749. /**
  6750. * 同步数据到编辑器所在的form
  6751. * 从编辑器的容器节点向上查找form元素,若找到,就同步编辑内容到找到的form里,为提交数据做准备,主要用于是手动提交的情况
  6752. * 后台取得数据的键值,使用你容器上的name属性,如果没有就使用参数里的textarea项
  6753. * @method sync
  6754. * @example
  6755. * ```javascript
  6756. * editor.sync();
  6757. * form.sumbit(); //form变量已经指向了form元素
  6758. * ```
  6759. */
  6760. /**
  6761. * 根据传入的formId,在页面上查找要同步数据的表单,若找到,就同步编辑内容到找到的form里,为提交数据做准备
  6762. * 后台取得数据的键值,该键值默认使用给定的编辑器容器的name属性,如果没有name属性则使用参数项里给定的“textarea”项
  6763. * @method sync
  6764. * @param { String } formID 指定一个要同步数据的form的id,编辑器的数据会同步到你指定form下
  6765. */
  6766. sync: function (formId) {
  6767. var me = this,
  6768. form = formId ? document.getElementById(formId) :
  6769. domUtils.findParent(me.iframe.parentNode, function (node) {
  6770. return node.tagName == 'FORM'
  6771. }, true);
  6772. form && setValue(form, me);
  6773. },
  6774. /**
  6775. * 设置编辑器高度
  6776. * @method setHeight
  6777. * @remind 当配置项autoHeightEnabled为真时,该方法无效
  6778. * @param { Number } number 设置的高度值,纯数值,不带单位
  6779. * @example
  6780. * ```javascript
  6781. * editor.setHeight(number);
  6782. * ```
  6783. */
  6784. setHeight: function (height,notSetHeight) {
  6785. if (height !== parseInt(this.iframe.parentNode.style.height)) {
  6786. this.iframe.parentNode.style.height = height + 'px';
  6787. }
  6788. !notSetHeight && (this.options.minFrameHeight = this.options.initialFrameHeight = height);
  6789. this.body.style.height = height + 'px';
  6790. !notSetHeight && this.trigger('setHeight')
  6791. },
  6792. /**
  6793. * 为编辑器的编辑命令提供快捷键
  6794. * 这个接口是为插件扩展提供的接口,主要是为新添加的插件,如果需要添加快捷键,所提供的接口
  6795. * @method addshortcutkey
  6796. * @param { Object } keyset 命令名和快捷键键值对对象,多个按钮的快捷键用“+”分隔
  6797. * @example
  6798. * ```javascript
  6799. * editor.addshortcutkey({
  6800. * "Bold" : "ctrl+66",//^B
  6801. * "Italic" : "ctrl+73", //^I
  6802. * });
  6803. * ```
  6804. */
  6805. /**
  6806. * 这个接口是为插件扩展提供的接口,主要是为新添加的插件,如果需要添加快捷键,所提供的接口
  6807. * @method addshortcutkey
  6808. * @param { String } cmd 触发快捷键时,响应的命令
  6809. * @param { String } keys 快捷键的字符串,多个按钮用“+”分隔
  6810. * @example
  6811. * ```javascript
  6812. * editor.addshortcutkey("Underline", "ctrl+85"); //^U
  6813. * ```
  6814. */
  6815. addshortcutkey: function (cmd, keys) {
  6816. var obj = {};
  6817. if (keys) {
  6818. obj[cmd] = keys
  6819. } else {
  6820. obj = cmd;
  6821. }
  6822. utils.extend(this.shortcutkeys, obj)
  6823. },
  6824. /**
  6825. * 对编辑器设置keydown事件监听,绑定快捷键和命令,当快捷键组合触发成功,会响应对应的命令
  6826. * @method _bindshortcutKeys
  6827. * @private
  6828. */
  6829. _bindshortcutKeys: function () {
  6830. var me = this, shortcutkeys = this.shortcutkeys;
  6831. me.addListener('keydown', function (type, e) {
  6832. var keyCode = e.keyCode || e.which;
  6833. for (var i in shortcutkeys) {
  6834. var tmp = shortcutkeys[i].split(',');
  6835. for (var t = 0, ti; ti = tmp[t++];) {
  6836. ti = ti.split(':');
  6837. var key = ti[0], param = ti[1];
  6838. if (/^(ctrl)(\+shift)?\+(\d+)$/.test(key.toLowerCase()) || /^(\d+)$/.test(key)) {
  6839. if (( (RegExp.$1 == 'ctrl' ? (e.ctrlKey || e.metaKey) : 0)
  6840. && (RegExp.$2 != "" ? e[RegExp.$2.slice(1) + "Key"] : 1)
  6841. && keyCode == RegExp.$3
  6842. ) ||
  6843. keyCode == RegExp.$1
  6844. ) {
  6845. if (me.queryCommandState(i,param) != -1)
  6846. me.execCommand(i, param);
  6847. domUtils.preventDefault(e);
  6848. }
  6849. }
  6850. }
  6851. }
  6852. });
  6853. },
  6854. /**
  6855. * 获取编辑器的内容
  6856. * @method getContent
  6857. * @warning 该方法获取到的是经过编辑器内置的过滤规则进行过滤后得到的内容
  6858. * @return { String } 编辑器的内容字符串, 如果编辑器的内容为空,或者是空的标签内容(如:”&lt;p&gt;&lt;br/&gt;&lt;/p&gt;“), 则返回空字符串
  6859. * @example
  6860. * ```javascript
  6861. * //编辑器html内容:<p>1<strong>2<em>34</em>5</strong>6</p>
  6862. * var content = editor.getContent(); //返回值:<p>1<strong>2<em>34</em>5</strong>6</p>
  6863. * ```
  6864. */
  6865. /**
  6866. * 获取编辑器的内容。 可以通过参数定义编辑器内置的判空规则
  6867. * @method getContent
  6868. * @param { Function } fn 自定的判空规则, 要求该方法返回一个boolean类型的值,
  6869. * 代表当前编辑器的内容是否空,
  6870. * 如果返回true, 则该方法将直接返回空字符串;如果返回false,则编辑器将返回
  6871. * 经过内置过滤规则处理后的内容。
  6872. * @remind 该方法在处理包含有初始化内容的时候能起到很好的作用。
  6873. * @warning 该方法获取到的是经过编辑器内置的过滤规则进行过滤后得到的内容
  6874. * @return { String } 编辑器的内容字符串
  6875. * @example
  6876. * ```javascript
  6877. * // editor 是一个编辑器的实例
  6878. * var content = editor.getContent( function ( editor ) {
  6879. * return editor.body.innerHTML === '欢迎使用UEditor'; //返回空字符串
  6880. * } );
  6881. * ```
  6882. */
  6883. getContent: function (cmd, fn,notSetCursor,ignoreBlank,formatter) {
  6884. var me = this;
  6885. if (cmd && utils.isFunction(cmd)) {
  6886. fn = cmd;
  6887. cmd = '';
  6888. }
  6889. if (fn ? !fn() : !this.hasContents()) {
  6890. return '';
  6891. }
  6892. me.fireEvent('beforegetcontent');
  6893. var root = UE.htmlparser(me.body.innerHTML,ignoreBlank);
  6894. me.filterOutputRule(root);
  6895. me.fireEvent('aftergetcontent', cmd,root);
  6896. return root.toHtml(formatter);
  6897. },
  6898. /**
  6899. * 取得完整的html代码,可以直接显示成完整的html文档
  6900. * @method getAllHtml
  6901. * @return { String } 编辑器的内容html文档字符串
  6902. * @eaxmple
  6903. * ```javascript
  6904. * editor.getAllHtml(); //返回格式大致是: <html><head>...</head><body>...</body></html>
  6905. * ```
  6906. */
  6907. getAllHtml: function () {
  6908. var me = this,
  6909. headHtml = [],
  6910. html = '';
  6911. me.fireEvent('getAllHtml', headHtml);
  6912. if (browser.ie && browser.version > 8) {
  6913. var headHtmlForIE9 = '';
  6914. utils.each(me.document.styleSheets, function (si) {
  6915. headHtmlForIE9 += ( si.href ? '<link rel="stylesheet" type="text/css" href="' + si.href + '" />' : '<style>' + si.cssText + '</style>');
  6916. });
  6917. utils.each(me.document.getElementsByTagName('script'), function (si) {
  6918. headHtmlForIE9 += si.outerHTML;
  6919. });
  6920. }
  6921. return '<html><head>' + (me.options.charset ? '<meta http-equiv="Content-Type" content="text/html; charset=' + me.options.charset + '"/>' : '')
  6922. + (headHtmlForIE9 || me.document.getElementsByTagName('head')[0].innerHTML) + headHtml.join('\n') + '</head>'
  6923. + '<body ' + (ie && browser.version < 9 ? 'class="view"' : '') + '>' + me.getContent(null, null, true) + '</body></html>';
  6924. },
  6925. /**
  6926. * 得到编辑器的纯文本内容,但会保留段落格式
  6927. * @method getPlainTxt
  6928. * @return { String } 编辑器带段落格式的纯文本内容字符串
  6929. * @example
  6930. * ```javascript
  6931. * //编辑器html内容:<p><strong>1</strong></p><p><strong>2</strong></p>
  6932. * console.log(editor.getPlainTxt()); //输出:"1\n2\n
  6933. * ```
  6934. */
  6935. getPlainTxt: function () {
  6936. var reg = new RegExp(domUtils.fillChar, 'g'),
  6937. html = this.body.innerHTML.replace(/[\n\r]/g, '');//ie要先去了\n在处理
  6938. html = html.replace(/<(p|div)[^>]*>(<br\/?>|&nbsp;)<\/\1>/gi, '\n')
  6939. .replace(/<br\/?>/gi, '\n')
  6940. .replace(/<[^>/]+>/g, '')
  6941. .replace(/(\n)?<\/([^>]+)>/g, function (a, b, c) {
  6942. return dtd.$block[c] ? '\n' : b ? b : '';
  6943. });
  6944. //取出来的空格会有c2a0会变成乱码,处理这种情况\u00a0
  6945. return html.replace(reg, '').replace(/\u00a0/g, ' ').replace(/&nbsp;/g, ' ');
  6946. },
  6947. /**
  6948. * 获取编辑器中的纯文本内容,没有段落格式
  6949. * @method getContentTxt
  6950. * @return { String } 编辑器不带段落格式的纯文本内容字符串
  6951. * @example
  6952. * ```javascript
  6953. * //编辑器html内容:<p><strong>1</strong></p><p><strong>2</strong></p>
  6954. * console.log(editor.getPlainTxt()); //输出:"12
  6955. * ```
  6956. */
  6957. getContentTxt: function () {
  6958. var reg = new RegExp(domUtils.fillChar, 'g');
  6959. //取出来的空格会有c2a0会变成乱码,处理这种情况\u00a0
  6960. return this.body[browser.ie ? 'innerText' : 'textContent'].replace(reg, '').replace(/\u00a0/g, ' ');
  6961. },
  6962. /**
  6963. * 设置编辑器的内容,可修改编辑器当前的html内容
  6964. * @method setContent
  6965. * @warning 通过该方法插入的内容,是经过编辑器内置的过滤规则进行过滤后得到的内容
  6966. * @warning 该方法会触发selectionchange事件
  6967. * @param { String } html 要插入的html内容
  6968. * @example
  6969. * ```javascript
  6970. * editor.getContent('<p>test</p>');
  6971. * ```
  6972. */
  6973. /**
  6974. * 设置编辑器的内容,可修改编辑器当前的html内容
  6975. * @method setContent
  6976. * @warning 通过该方法插入的内容,是经过编辑器内置的过滤规则进行过滤后得到的内容
  6977. * @warning 该方法会触发selectionchange事件
  6978. * @param { String } html 要插入的html内容
  6979. * @param { Boolean } isAppendTo 若传入true,不清空原来的内容,在最后插入内容,否则,清空内容再插入
  6980. * @example
  6981. * ```javascript
  6982. * //假设设置前的编辑器内容是 <p>old text</p>
  6983. * editor.setContent('<p>new text</p>', true); //插入的结果是<p>old text</p><p>new text</p>
  6984. * ```
  6985. */
  6986. setContent: function (html, isAppendTo, notFireSelectionchange) {
  6987. var me = this;
  6988. me.fireEvent('beforesetcontent', html);
  6989. var root = UE.htmlparser(html);
  6990. me.filterInputRule(root);
  6991. html = root.toHtml();
  6992. me.body.innerHTML = (isAppendTo ? me.body.innerHTML : '') + html;
  6993. function isCdataDiv(node){
  6994. return node.tagName == 'DIV' && node.getAttribute('cdata_tag');
  6995. }
  6996. //给文本或者inline节点套p标签
  6997. if (me.options.enterTag == 'p') {
  6998. var child = this.body.firstChild, tmpNode;
  6999. if (!child || child.nodeType == 1 &&
  7000. (dtd.$cdata[child.tagName] || isCdataDiv(child) ||
  7001. domUtils.isCustomeNode(child)
  7002. )
  7003. && child === this.body.lastChild) {
  7004. this.body.innerHTML = '<p>' + (browser.ie ? '&nbsp;' : '<br/>') + '</p>' + this.body.innerHTML;
  7005. } else {
  7006. var p = me.document.createElement('p');
  7007. while (child) {
  7008. while (child && (child.nodeType == 3 || child.nodeType == 1 && dtd.p[child.tagName] && !dtd.$cdata[child.tagName])) {
  7009. tmpNode = child.nextSibling;
  7010. p.appendChild(child);
  7011. child = tmpNode;
  7012. }
  7013. if (p.firstChild) {
  7014. if (!child) {
  7015. me.body.appendChild(p);
  7016. break;
  7017. } else {
  7018. child.parentNode.insertBefore(p, child);
  7019. p = me.document.createElement('p');
  7020. }
  7021. }
  7022. child = child.nextSibling;
  7023. }
  7024. }
  7025. }
  7026. me.fireEvent('aftersetcontent');
  7027. me.fireEvent('contentchange');
  7028. !notFireSelectionchange && me._selectionChange();
  7029. //清除保存的选区
  7030. me._bakRange = me._bakIERange = me._bakNativeRange = null;
  7031. //trace:1742 setContent后gecko能得到焦点问题
  7032. var geckoSel;
  7033. if (browser.gecko && (geckoSel = this.selection.getNative())) {
  7034. geckoSel.removeAllRanges();
  7035. }
  7036. if(me.options.autoSyncData){
  7037. me.form && setValue(me.form,me);
  7038. }
  7039. },
  7040. /**
  7041. * 让编辑器获得焦点,默认focus到编辑器头部
  7042. * @method focus
  7043. * @example
  7044. * ```javascript
  7045. * editor.focus()
  7046. * ```
  7047. */
  7048. /**
  7049. * 让编辑器获得焦点,toEnd确定focus位置
  7050. * @method focus
  7051. * @param { Boolean } toEnd 默认focus到编辑器头部,toEnd为true时focus到内容尾部
  7052. * @example
  7053. * ```javascript
  7054. * editor.focus(true)
  7055. * ```
  7056. */
  7057. focus: function (toEnd) {
  7058. try {
  7059. var me = this,
  7060. rng = me.selection.getRange();
  7061. if (toEnd) {
  7062. var node = me.body.lastChild;
  7063. if(node && node.nodeType == 1 && !dtd.$empty[node.tagName]){
  7064. if(domUtils.isEmptyBlock(node)){
  7065. rng.setStartAtFirst(node)
  7066. }else{
  7067. rng.setStartAtLast(node)
  7068. }
  7069. rng.collapse(true);
  7070. }
  7071. rng.setCursor(true);
  7072. } else {
  7073. if(!rng.collapsed && domUtils.isBody(rng.startContainer) && rng.startOffset == 0){
  7074. var node = me.body.firstChild;
  7075. if(node && node.nodeType == 1 && !dtd.$empty[node.tagName]){
  7076. rng.setStartAtFirst(node).collapse(true);
  7077. }
  7078. }
  7079. rng.select(true);
  7080. }
  7081. this.fireEvent('focus selectionchange');
  7082. } catch (e) {
  7083. }
  7084. },
  7085. isFocus:function(){
  7086. return this.selection.isFocus();
  7087. },
  7088. blur:function(){
  7089. var sel = this.selection.getNative();
  7090. if(sel.empty && browser.ie){
  7091. var nativeRng = document.body.createTextRange();
  7092. nativeRng.moveToElementText(document.body);
  7093. nativeRng.collapse(true);
  7094. nativeRng.select();
  7095. sel.empty()
  7096. }else{
  7097. sel.removeAllRanges()
  7098. }
  7099. //this.fireEvent('blur selectionchange');
  7100. },
  7101. /**
  7102. * 初始化UE事件及部分事件代理
  7103. * @method _initEvents
  7104. * @private
  7105. */
  7106. _initEvents: function () {
  7107. var me = this,
  7108. doc = me.document,
  7109. win = me.window;
  7110. me._proxyDomEvent = utils.bind(me._proxyDomEvent, me);
  7111. domUtils.on(doc, ['click', 'contextmenu', 'mousedown', 'keydown', 'keyup', 'keypress', 'mouseup', 'mouseover', 'mouseout', 'selectstart'], me._proxyDomEvent);
  7112. domUtils.on(win, ['focus', 'blur'], me._proxyDomEvent);
  7113. domUtils.on(me.body,'drop',function(e){
  7114. //阻止ff下默认的弹出新页面打开图片
  7115. if(browser.gecko && e.stopPropagation) { e.stopPropagation(); }
  7116. me.fireEvent('contentchange')
  7117. });
  7118. domUtils.on(doc, ['mouseup', 'keydown'], function (evt) {
  7119. //特殊键不触发selectionchange
  7120. if (evt.type == 'keydown' && (evt.ctrlKey || evt.metaKey || evt.shiftKey || evt.altKey)) {
  7121. return;
  7122. }
  7123. if (evt.button == 2)return;
  7124. me._selectionChange(250, evt);
  7125. });
  7126. },
  7127. /**
  7128. * 触发事件代理
  7129. * @method _proxyDomEvent
  7130. * @private
  7131. * @return { * } fireEvent的返回值
  7132. * @see UE.EventBase:fireEvent(String)
  7133. */
  7134. _proxyDomEvent: function (evt) {
  7135. if(this.fireEvent('before' + evt.type.replace(/^on/, '').toLowerCase()) === false){
  7136. return false;
  7137. }
  7138. if(this.fireEvent(evt.type.replace(/^on/, ''), evt) === false){
  7139. return false;
  7140. }
  7141. return this.fireEvent('after' + evt.type.replace(/^on/, '').toLowerCase())
  7142. },
  7143. /**
  7144. * 变化选区
  7145. * @method _selectionChange
  7146. * @private
  7147. */
  7148. _selectionChange: function (delay, evt) {
  7149. var me = this;
  7150. //有光标才做selectionchange 为了解决未focus时点击source不能触发更改工具栏状态的问题(source命令notNeedUndo=1)
  7151. // if ( !me.selection.isFocus() ){
  7152. // return;
  7153. // }
  7154. var hackForMouseUp = false;
  7155. var mouseX, mouseY;
  7156. if (browser.ie && browser.version < 9 && evt && evt.type == 'mouseup') {
  7157. var range = this.selection.getRange();
  7158. if (!range.collapsed) {
  7159. hackForMouseUp = true;
  7160. mouseX = evt.clientX;
  7161. mouseY = evt.clientY;
  7162. }
  7163. }
  7164. clearTimeout(_selectionChangeTimer);
  7165. _selectionChangeTimer = setTimeout(function () {
  7166. if (!me.selection || !me.selection.getNative()) {
  7167. return;
  7168. }
  7169. //修复一个IE下的bug: 鼠标点击一段已选择的文本中间时,可能在mouseup后的一段时间内取到的range是在selection的type为None下的错误值.
  7170. //IE下如果用户是拖拽一段已选择文本,则不会触发mouseup事件,所以这里的特殊处理不会对其有影响
  7171. var ieRange;
  7172. if (hackForMouseUp && me.selection.getNative().type == 'None') {
  7173. ieRange = me.document.body.createTextRange();
  7174. try {
  7175. ieRange.moveToPoint(mouseX, mouseY);
  7176. } catch (ex) {
  7177. ieRange = null;
  7178. }
  7179. }
  7180. var bakGetIERange;
  7181. if (ieRange) {
  7182. bakGetIERange = me.selection.getIERange;
  7183. me.selection.getIERange = function () {
  7184. return ieRange;
  7185. };
  7186. }
  7187. me.selection.cache();
  7188. if (bakGetIERange) {
  7189. me.selection.getIERange = bakGetIERange;
  7190. }
  7191. if (me.selection._cachedRange && me.selection._cachedStartElement) {
  7192. me.fireEvent('beforeselectionchange');
  7193. // 第二个参数causeByUi为true代表由用户交互造成的selectionchange.
  7194. me.fireEvent('selectionchange', !!evt);
  7195. me.fireEvent('afterselectionchange');
  7196. me.selection.clear();
  7197. }
  7198. }, delay || 50);
  7199. },
  7200. /**
  7201. * 执行编辑命令
  7202. * @method _callCmdFn
  7203. * @private
  7204. * @param { String } fnName 函数名称
  7205. * @param { * } args 传给命令函数的参数
  7206. * @return { * } 返回命令函数运行的返回值
  7207. */
  7208. _callCmdFn: function (fnName, args) {
  7209. var cmdName = args[0].toLowerCase(),
  7210. cmd, cmdFn;
  7211. cmd = this.commands[cmdName] || UE.commands[cmdName];
  7212. cmdFn = cmd && cmd[fnName];
  7213. //没有querycommandstate或者没有command的都默认返回0
  7214. if ((!cmd || !cmdFn) && fnName == 'queryCommandState') {
  7215. return 0;
  7216. } else if (cmdFn) {
  7217. return cmdFn.apply(this, args);
  7218. }
  7219. },
  7220. /**
  7221. * 执行编辑命令cmdName,完成富文本编辑效果
  7222. * @method execCommand
  7223. * @param { String } cmdName 需要执行的命令
  7224. * @remind 具体命令的使用请参考<a href="#COMMAND.LIST">命令列表</a>
  7225. * @return { * } 返回命令函数运行的返回值
  7226. * @example
  7227. * ```javascript
  7228. * editor.execCommand(cmdName);
  7229. * ```
  7230. */
  7231. execCommand: function (cmdName) {
  7232. cmdName = cmdName.toLowerCase();
  7233. var me = this,
  7234. result,
  7235. cmd = me.commands[cmdName] || UE.commands[cmdName];
  7236. if (!cmd || !cmd.execCommand) {
  7237. return null;
  7238. }
  7239. if (!cmd.notNeedUndo && !me.__hasEnterExecCommand) {
  7240. me.__hasEnterExecCommand = true;
  7241. if (me.queryCommandState.apply(me,arguments) != -1) {
  7242. me.fireEvent('saveScene');
  7243. me.fireEvent.apply(me, ['beforeexeccommand', cmdName].concat(arguments));
  7244. result = this._callCmdFn('execCommand', arguments);
  7245. //保存场景时,做了内容对比,再看是否进行contentchange触发,这里多触发了一次,去掉
  7246. // (!cmd.ignoreContentChange && !me._ignoreContentChange) && me.fireEvent('contentchange');
  7247. me.fireEvent.apply(me, ['afterexeccommand', cmdName].concat(arguments));
  7248. me.fireEvent('saveScene');
  7249. }
  7250. me.__hasEnterExecCommand = false;
  7251. } else {
  7252. result = this._callCmdFn('execCommand', arguments);
  7253. (!me.__hasEnterExecCommand && !cmd.ignoreContentChange && !me._ignoreContentChange) && me.fireEvent('contentchange')
  7254. }
  7255. (!me.__hasEnterExecCommand && !cmd.ignoreContentChange && !me._ignoreContentChange) && me._selectionChange();
  7256. return result;
  7257. },
  7258. /**
  7259. * 根据传入的command命令,查选编辑器当前的选区,返回命令的状态
  7260. * @method queryCommandState
  7261. * @param { String } cmdName 需要查询的命令名称
  7262. * @remind 具体命令的使用请参考<a href="#COMMAND.LIST">命令列表</a>
  7263. * @return { Number } number 返回放前命令的状态,返回值三种情况:(-1|0|1)
  7264. * @example
  7265. * ```javascript
  7266. * editor.queryCommandState(cmdName) => (-1|0|1)
  7267. * ```
  7268. * @see COMMAND.LIST
  7269. */
  7270. queryCommandState: function (cmdName) {
  7271. return this._callCmdFn('queryCommandState', arguments);
  7272. },
  7273. /**
  7274. * 根据传入的command命令,查选编辑器当前的选区,根据命令返回相关的值
  7275. * @method queryCommandValue
  7276. * @param { String } cmdName 需要查询的命令名称
  7277. * @remind 具体命令的使用请参考<a href="#COMMAND.LIST">命令列表</a>
  7278. * @remind 只有部分插件有此方法
  7279. * @return { * } 返回每个命令特定的当前状态值
  7280. * @grammar editor.queryCommandValue(cmdName) => {*}
  7281. * @see COMMAND.LIST
  7282. */
  7283. queryCommandValue: function (cmdName) {
  7284. return this._callCmdFn('queryCommandValue', arguments);
  7285. },
  7286. /**
  7287. * 检查编辑区域中是否有内容
  7288. * @method hasContents
  7289. * @remind 默认有文本内容,或者有以下节点都不认为是空
  7290. * table,ul,ol,dl,iframe,area,base,col,hr,img,embed,input,link,meta,param
  7291. * @return { Boolean } 检查有内容返回true,否则返回false
  7292. * @example
  7293. * ```javascript
  7294. * editor.hasContents()
  7295. * ```
  7296. */
  7297. /**
  7298. * 检查编辑区域中是否有内容,若包含参数tags中的节点类型,直接返回true
  7299. * @method hasContents
  7300. * @param { Array } tags 传入数组判断时用到的节点类型
  7301. * @return { Boolean } 若文档中包含tags数组里对应的tag,返回true,否则返回false
  7302. * @example
  7303. * ```javascript
  7304. * editor.hasContents(['span']);
  7305. * ```
  7306. */
  7307. hasContents: function (tags) {
  7308. if (tags) {
  7309. for (var i = 0, ci; ci = tags[i++];) {
  7310. if (this.document.getElementsByTagName(ci).length > 0) {
  7311. return true;
  7312. }
  7313. }
  7314. }
  7315. if (!domUtils.isEmptyBlock(this.body)) {
  7316. return true
  7317. }
  7318. //随时添加,定义的特殊标签如果存在,不能认为是空
  7319. tags = ['div'];
  7320. for (i = 0; ci = tags[i++];) {
  7321. var nodes = domUtils.getElementsByTagName(this.document, ci);
  7322. for (var n = 0, cn; cn = nodes[n++];) {
  7323. if (domUtils.isCustomeNode(cn)) {
  7324. return true;
  7325. }
  7326. }
  7327. }
  7328. return false;
  7329. },
  7330. /**
  7331. * 重置编辑器,可用来做多个tab使用同一个编辑器实例
  7332. * @method reset
  7333. * @remind 此方法会清空编辑器内容,清空回退列表,会触发reset事件
  7334. * @example
  7335. * ```javascript
  7336. * editor.reset()
  7337. * ```
  7338. */
  7339. reset: function () {
  7340. this.fireEvent('reset');
  7341. },
  7342. /**
  7343. * 设置当前编辑区域可以编辑
  7344. * @method setEnabled
  7345. * @example
  7346. * ```javascript
  7347. * editor.setEnabled()
  7348. * ```
  7349. */
  7350. setEnabled: function () {
  7351. var me = this, range;
  7352. if (me.body.contentEditable == 'false') {
  7353. me.body.contentEditable = true;
  7354. range = me.selection.getRange();
  7355. //有可能内容丢失了
  7356. try {
  7357. range.moveToBookmark(me.lastBk);
  7358. delete me.lastBk
  7359. } catch (e) {
  7360. range.setStartAtFirst(me.body).collapse(true)
  7361. }
  7362. range.select(true);
  7363. if (me.bkqueryCommandState) {
  7364. me.queryCommandState = me.bkqueryCommandState;
  7365. delete me.bkqueryCommandState;
  7366. }
  7367. if (me.bkqueryCommandValue) {
  7368. me.queryCommandValue = me.bkqueryCommandValue;
  7369. delete me.bkqueryCommandValue;
  7370. }
  7371. me.fireEvent('selectionchange');
  7372. }
  7373. },
  7374. enable: function () {
  7375. return this.setEnabled();
  7376. },
  7377. /** 设置当前编辑区域不可编辑
  7378. * @method setDisabled
  7379. */
  7380. /** 设置当前编辑区域不可编辑,except中的命令除外
  7381. * @method setDisabled
  7382. * @param { String } except 例外命令的字符串
  7383. * @remind 即使设置了disable,此处配置的例外命令仍然可以执行
  7384. * @example
  7385. * ```javascript
  7386. * editor.setDisabled('bold'); //禁用工具栏中除加粗之外的所有功能
  7387. * ```
  7388. */
  7389. /** 设置当前编辑区域不可编辑,except中的命令除外
  7390. * @method setDisabled
  7391. * @param { Array } except 例外命令的字符串数组,数组中的命令仍然可以执行
  7392. * @remind 即使设置了disable,此处配置的例外命令仍然可以执行
  7393. * @example
  7394. * ```javascript
  7395. * editor.setDisabled(['bold','insertimage']); //禁用工具栏中除加粗和插入图片之外的所有功能
  7396. * ```
  7397. */
  7398. setDisabled: function (except) {
  7399. var me = this;
  7400. except = except ? utils.isArray(except) ? except : [except] : [];
  7401. if (me.body.contentEditable == 'true') {
  7402. if (!me.lastBk) {
  7403. me.lastBk = me.selection.getRange().createBookmark(true);
  7404. }
  7405. me.body.contentEditable = false;
  7406. me.bkqueryCommandState = me.queryCommandState;
  7407. me.bkqueryCommandValue = me.queryCommandValue;
  7408. me.queryCommandState = function (type) {
  7409. if (utils.indexOf(except, type) != -1) {
  7410. return me.bkqueryCommandState.apply(me, arguments);
  7411. }
  7412. return -1;
  7413. };
  7414. me.queryCommandValue = function (type) {
  7415. if (utils.indexOf(except, type) != -1) {
  7416. return me.bkqueryCommandValue.apply(me, arguments);
  7417. }
  7418. return null;
  7419. };
  7420. me.fireEvent('selectionchange');
  7421. }
  7422. },
  7423. disable: function (except) {
  7424. return this.setDisabled(except);
  7425. },
  7426. /**
  7427. * 设置默认内容
  7428. * @method _setDefaultContent
  7429. * @private
  7430. * @param { String } cont 要存入的内容
  7431. */
  7432. _setDefaultContent: function () {
  7433. function clear() {
  7434. var me = this;
  7435. if (me.document.getElementById('initContent')) {
  7436. me.body.innerHTML = '<p>' + (ie ? '' : '<br/>') + '</p>';
  7437. me.removeListener('firstBeforeExecCommand focus', clear);
  7438. setTimeout(function () {
  7439. me.focus();
  7440. me._selectionChange();
  7441. }, 0)
  7442. }
  7443. }
  7444. return function (cont) {
  7445. var me = this;
  7446. me.body.innerHTML = '<p id="initContent">' + cont + '</p>';
  7447. me.addListener('firstBeforeExecCommand focus', clear);
  7448. }
  7449. }(),
  7450. /**
  7451. * 显示编辑器
  7452. * @method setShow
  7453. * @example
  7454. * ```javascript
  7455. * editor.setShow()
  7456. * ```
  7457. */
  7458. setShow: function () {
  7459. var me = this, range = me.selection.getRange();
  7460. if (me.container.style.display == 'none') {
  7461. //有可能内容丢失了
  7462. try {
  7463. range.moveToBookmark(me.lastBk);
  7464. delete me.lastBk
  7465. } catch (e) {
  7466. range.setStartAtFirst(me.body).collapse(true)
  7467. }
  7468. //ie下focus实效,所以做了个延迟
  7469. setTimeout(function () {
  7470. range.select(true);
  7471. }, 100);
  7472. me.container.style.display = '';
  7473. }
  7474. },
  7475. show: function () {
  7476. return this.setShow();
  7477. },
  7478. /**
  7479. * 隐藏编辑器
  7480. * @method setHide
  7481. * @example
  7482. * ```javascript
  7483. * editor.setHide()
  7484. * ```
  7485. */
  7486. setHide: function () {
  7487. var me = this;
  7488. if (!me.lastBk) {
  7489. me.lastBk = me.selection.getRange().createBookmark(true);
  7490. }
  7491. me.container.style.display = 'none'
  7492. },
  7493. hide: function () {
  7494. return this.setHide();
  7495. },
  7496. /**
  7497. * 根据指定的路径,获取对应的语言资源
  7498. * @method getLang
  7499. * @param { String } path 路径根据的是lang目录下的语言文件的路径结构
  7500. * @return { Object | String } 根据路径返回语言资源的Json格式对象或者语言字符串
  7501. * @example
  7502. * ```javascript
  7503. * editor.getLang('contextMenu.delete'); //如果当前是中文,那返回是的是'删除'
  7504. * ```
  7505. */
  7506. getLang: function (path) {
  7507. var lang = UE.I18N[this.options.lang];
  7508. if (!lang) {
  7509. throw Error("not import language file");
  7510. }
  7511. path = (path || "").split(".");
  7512. for (var i = 0, ci; ci = path[i++];) {
  7513. lang = lang[ci];
  7514. if (!lang)break;
  7515. }
  7516. return lang;
  7517. },
  7518. /**
  7519. * 计算编辑器html内容字符串的长度
  7520. * @method getContentLength
  7521. * @return { Number } 返回计算的长度
  7522. * @example
  7523. * ```javascript
  7524. * //编辑器html内容<p><strong>132</strong></p>
  7525. * editor.getContentLength() //返回27
  7526. * ```
  7527. */
  7528. /**
  7529. * 计算编辑器当前纯文本内容的长度
  7530. * @method getContentLength
  7531. * @param { Boolean } ingoneHtml 传入true时,只按照纯文本来计算
  7532. * @return { Number } 返回计算的长度,内容中有hr/img/iframe标签,长度加1
  7533. * @example
  7534. * ```javascript
  7535. * //编辑器html内容<p><strong>132</strong></p>
  7536. * editor.getContentLength() //返回3
  7537. * ```
  7538. */
  7539. getContentLength: function (ingoneHtml, tagNames) {
  7540. var count = this.getContent(false,false,true).length;
  7541. if (ingoneHtml) {
  7542. tagNames = (tagNames || []).concat([ 'hr', 'img', 'iframe']);
  7543. count = this.getContentTxt().replace(/[\t\r\n]+/g, '').length;
  7544. for (var i = 0, ci; ci = tagNames[i++];) {
  7545. count += this.document.getElementsByTagName(ci).length;
  7546. }
  7547. }
  7548. return count;
  7549. },
  7550. /**
  7551. * 注册输入过滤规则
  7552. * @method addInputRule
  7553. * @param { Function } rule 要添加的过滤规则
  7554. * @example
  7555. * ```javascript
  7556. * editor.addInputRule(function(root){
  7557. * $.each(root.getNodesByTagName('div'),function(i,node){
  7558. * node.tagName="p";
  7559. * });
  7560. * });
  7561. * ```
  7562. */
  7563. addInputRule: function (rule) {
  7564. this.inputRules.push(rule);
  7565. },
  7566. /**
  7567. * 执行注册的过滤规则
  7568. * @method filterInputRule
  7569. * @param { UE.uNode } root 要过滤的uNode节点
  7570. * @remind 执行editor.setContent方法和执行'inserthtml'命令后,会运行该过滤函数
  7571. * @example
  7572. * ```javascript
  7573. * editor.filterInputRule(editor.body);
  7574. * ```
  7575. * @see UE.Editor:addInputRule
  7576. */
  7577. filterInputRule: function (root) {
  7578. for (var i = 0, ci; ci = this.inputRules[i++];) {
  7579. ci.call(this, root)
  7580. }
  7581. },
  7582. /**
  7583. * 注册输出过滤规则
  7584. * @method addOutputRule
  7585. * @param { Function } rule 要添加的过滤规则
  7586. * @example
  7587. * ```javascript
  7588. * editor.addOutputRule(function(root){
  7589. * $.each(root.getNodesByTagName('p'),function(i,node){
  7590. * node.tagName="div";
  7591. * });
  7592. * });
  7593. * ```
  7594. */
  7595. addOutputRule: function (rule) {
  7596. this.outputRules.push(rule)
  7597. },
  7598. /**
  7599. * 根据输出过滤规则,过滤编辑器内容
  7600. * @method filterOutputRule
  7601. * @remind 执行editor.getContent方法的时候,会先运行该过滤函数
  7602. * @param { UE.uNode } root 要过滤的uNode节点
  7603. * @example
  7604. * ```javascript
  7605. * editor.filterOutputRule(editor.body);
  7606. * ```
  7607. * @see UE.Editor:addOutputRule
  7608. */
  7609. filterOutputRule: function (root) {
  7610. for (var i = 0, ci; ci = this.outputRules[i++];) {
  7611. ci.call(this, root)
  7612. }
  7613. },
  7614. /**
  7615. * 根据action名称获取请求的路径
  7616. * @method getActionUrl
  7617. * @remind 假如没有设置serverUrl,会根据imageUrl设置默认的controller路径
  7618. * @param { String } action action名称
  7619. * @example
  7620. * ```javascript
  7621. * editor.getActionUrl('config'); //返回 "/ueditor/php/controller.php?action=config"
  7622. * editor.getActionUrl('image'); //返回 "/ueditor/php/controller.php?action=uplaodimage"
  7623. * editor.getActionUrl('scrawl'); //返回 "/ueditor/php/controller.php?action=uplaodscrawl"
  7624. * editor.getActionUrl('imageManager'); //返回 "/ueditor/php/controller.php?action=listimage"
  7625. * ```
  7626. */
  7627. getActionUrl: function(action){
  7628. var actionName = this.getOpt(action) || action,
  7629. imageUrl = this.getOpt('imageUrl'),
  7630. serverUrl = this.getOpt('serverUrl');
  7631. if(!serverUrl && imageUrl) {
  7632. serverUrl = imageUrl.replace(/^(.*[\/]).+([\.].+)$/, '$1controller$2');
  7633. }
  7634. if(serverUrl) {
  7635. serverUrl = serverUrl + (serverUrl.indexOf('?') == -1 ? '?':'&') + 'action=' + (actionName || '');
  7636. return utils.formatUrl(serverUrl);
  7637. } else {
  7638. return '';
  7639. }
  7640. }
  7641. };
  7642. utils.inherits(Editor, EventBase);
  7643. })();
  7644. // core/Editor.defaultoptions.js
  7645. //维护编辑器一下默认的不在插件中的配置项
  7646. UE.Editor.defaultOptions = function(editor){
  7647. var _url = editor.options.UEDITOR_HOME_URL;
  7648. return {
  7649. isShow: true,
  7650. initialContent: '',
  7651. initialStyle:'',
  7652. autoClearinitialContent: false,
  7653. iframeCssUrl: _url + 'themes/iframe.css',
  7654. textarea: 'editorValue',
  7655. focus: false,
  7656. focusInEnd: true,
  7657. autoClearEmptyNode: true,
  7658. fullscreen: false,
  7659. readonly: false,
  7660. zIndex: 999,
  7661. imagePopup: true,
  7662. enterTag: 'p',
  7663. customDomain: false,
  7664. lang: 'zh-cn',
  7665. langPath: _url + 'lang/',
  7666. theme: 'default',
  7667. themePath: _url + 'themes/',
  7668. allHtmlEnabled: false,
  7669. scaleEnabled: false,
  7670. tableNativeEditInFF: false,
  7671. autoSyncData : true,
  7672. fileNameFormat: '{time}{rand:6}'
  7673. }
  7674. };
  7675. // core/loadconfig.js
  7676. (function(){
  7677. UE.Editor.prototype.loadServerConfig = function(){
  7678. var me = this;
  7679. setTimeout(function(){
  7680. try{
  7681. me.options.imageUrl && me.setOpt('serverUrl', me.options.imageUrl.replace(/^(.*[\/]).+([\.].+)$/, '$1controller$2'));
  7682. var configUrl = me.getActionUrl('config'),
  7683. isJsonp = utils.isCrossDomainUrl(configUrl);
  7684. /* 发出ajax请求 */
  7685. me._serverConfigLoaded = false;
  7686. configUrl && UE.ajax.request(configUrl,{
  7687. 'method': 'GET',
  7688. 'dataType': isJsonp ? 'jsonp':'',
  7689. 'onsuccess':function(r){
  7690. try {
  7691. var config = isJsonp ? r:eval("("+r.responseText+")");
  7692. utils.extend(me.options, config);
  7693. me.fireEvent('serverConfigLoaded');
  7694. me._serverConfigLoaded = true;
  7695. } catch (e) {
  7696. showErrorMsg(me.getLang('loadconfigFormatError'));
  7697. }
  7698. },
  7699. 'onerror':function(){
  7700. showErrorMsg(me.getLang('loadconfigHttpError'));
  7701. }
  7702. });
  7703. } catch(e){
  7704. showErrorMsg(me.getLang('loadconfigError'));
  7705. }
  7706. });
  7707. function showErrorMsg(msg) {
  7708. console && console.error(msg);
  7709. //me.fireEvent('showMessage', {
  7710. // 'title': msg,
  7711. // 'type': 'error'
  7712. //});
  7713. }
  7714. };
  7715. UE.Editor.prototype.isServerConfigLoaded = function(){
  7716. var me = this;
  7717. return me._serverConfigLoaded || false;
  7718. };
  7719. UE.Editor.prototype.afterConfigReady = function(handler){
  7720. if (!handler || !utils.isFunction(handler)) return;
  7721. var me = this;
  7722. var readyHandler = function(){
  7723. handler.apply(me, arguments);
  7724. me.removeListener('serverConfigLoaded', readyHandler);
  7725. };
  7726. if (me.isServerConfigLoaded()) {
  7727. handler.call(me, 'serverConfigLoaded');
  7728. } else {
  7729. me.addListener('serverConfigLoaded', readyHandler);
  7730. }
  7731. };
  7732. })();
  7733. // core/ajax.js
  7734. /**
  7735. * @file
  7736. * @module UE.ajax
  7737. * @since 1.2.6.1
  7738. */
  7739. /**
  7740. * 提供对ajax请求的支持
  7741. * @module UE.ajax
  7742. */
  7743. UE.ajax = function() {
  7744. //创建一个ajaxRequest对象
  7745. var fnStr = 'XMLHttpRequest()';
  7746. try {
  7747. new ActiveXObject("Msxml2.XMLHTTP");
  7748. fnStr = 'ActiveXObject(\'Msxml2.XMLHTTP\')';
  7749. } catch (e) {
  7750. try {
  7751. new ActiveXObject("Microsoft.XMLHTTP");
  7752. fnStr = 'ActiveXObject(\'Microsoft.XMLHTTP\')'
  7753. } catch (e) {
  7754. }
  7755. }
  7756. var creatAjaxRequest = new Function('return new ' + fnStr);
  7757. /**
  7758. * 将json参数转化成适合ajax提交的参数列表
  7759. * @param json
  7760. */
  7761. function json2str(json) {
  7762. var strArr = [];
  7763. for (var i in json) {
  7764. //忽略默认的几个参数
  7765. if(i=="method" || i=="timeout" || i=="async" || i=="dataType" || i=="callback") continue;
  7766. //忽略控制
  7767. if(json[i] == undefined || json[i] == null) continue;
  7768. //传递过来的对象和函数不在提交之列
  7769. if (!((typeof json[i]).toLowerCase() == "function" || (typeof json[i]).toLowerCase() == "object")) {
  7770. strArr.push( encodeURIComponent(i) + "="+encodeURIComponent(json[i]) );
  7771. } else if (utils.isArray(json[i])) {
  7772. //支持传数组内容
  7773. for(var j = 0; j < json[i].length; j++) {
  7774. strArr.push( encodeURIComponent(i) + "[]="+encodeURIComponent(json[i][j]) );
  7775. }
  7776. }
  7777. }
  7778. return strArr.join("&");
  7779. }
  7780. function doAjax(url, ajaxOptions) {
  7781. var xhr = creatAjaxRequest(),
  7782. //是否超时
  7783. timeIsOut = false,
  7784. //默认参数
  7785. defaultAjaxOptions = {
  7786. method:"POST",
  7787. timeout:5000,
  7788. async:true,
  7789. data:{},//需要传递对象的话只能覆盖
  7790. onsuccess:function() {
  7791. },
  7792. onerror:function() {
  7793. }
  7794. };
  7795. if (typeof url === "object") {
  7796. ajaxOptions = url;
  7797. url = ajaxOptions.url;
  7798. }
  7799. if (!xhr || !url) return;
  7800. var ajaxOpts = ajaxOptions ? utils.extend(defaultAjaxOptions,ajaxOptions) : defaultAjaxOptions;
  7801. var submitStr = json2str(ajaxOpts); // { name:"Jim",city:"Beijing" } --> "name=Jim&city=Beijing"
  7802. //如果用户直接通过data参数传递json对象过来,则也要将此json对象转化为字符串
  7803. if (!utils.isEmptyObject(ajaxOpts.data)){
  7804. submitStr += (submitStr? "&":"") + json2str(ajaxOpts.data);
  7805. }
  7806. //超时检测
  7807. var timerID = setTimeout(function() {
  7808. if (xhr.readyState != 4) {
  7809. timeIsOut = true;
  7810. xhr.abort();
  7811. clearTimeout(timerID);
  7812. }
  7813. }, ajaxOpts.timeout);
  7814. var method = ajaxOpts.method.toUpperCase();
  7815. var str = url + (url.indexOf("?")==-1?"?":"&") + (method=="POST"?"":submitStr+ "&noCache=" + +new Date);
  7816. xhr.open(method, str, ajaxOpts.async);
  7817. xhr.onreadystatechange = function() {
  7818. if (xhr.readyState == 4) {
  7819. if (!timeIsOut && xhr.status == 200) {
  7820. ajaxOpts.onsuccess(xhr);
  7821. } else {
  7822. ajaxOpts.onerror(xhr);
  7823. }
  7824. }
  7825. };
  7826. if (method == "POST") {
  7827. xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  7828. xhr.send(submitStr);
  7829. } else {
  7830. xhr.send(null);
  7831. }
  7832. }
  7833. function doJsonp(url, opts) {
  7834. var successhandler = opts.onsuccess || function(){},
  7835. scr = document.createElement('SCRIPT'),
  7836. options = opts || {},
  7837. charset = options['charset'],
  7838. callbackField = options['jsonp'] || 'callback',
  7839. callbackFnName,
  7840. timeOut = options['timeOut'] || 0,
  7841. timer,
  7842. reg = new RegExp('(\\?|&)' + callbackField + '=([^&]*)'),
  7843. matches;
  7844. if (utils.isFunction(successhandler)) {
  7845. callbackFnName = 'bd__editor__' + Math.floor(Math.random() * 2147483648).toString(36);
  7846. window[callbackFnName] = getCallBack(0);
  7847. } else if(utils.isString(successhandler)){
  7848. callbackFnName = successhandler;
  7849. } else {
  7850. if (matches = reg.exec(url)) {
  7851. callbackFnName = matches[2];
  7852. }
  7853. }
  7854. url = url.replace(reg, '\x241' + callbackField + '=' + callbackFnName);
  7855. if (url.search(reg) < 0) {
  7856. url += (url.indexOf('?') < 0 ? '?' : '&') + callbackField + '=' + callbackFnName;
  7857. }
  7858. var queryStr = json2str(opts); // { name:"Jim",city:"Beijing" } --> "name=Jim&city=Beijing"
  7859. //如果用户直接通过data参数传递json对象过来,则也要将此json对象转化为字符串
  7860. if (!utils.isEmptyObject(opts.data)){
  7861. queryStr += (queryStr? "&":"") + json2str(opts.data);
  7862. }
  7863. if (queryStr) {
  7864. url = url.replace(/\?/, '?' + queryStr + '&');
  7865. }
  7866. scr.onerror = getCallBack(1);
  7867. if( timeOut ){
  7868. timer = setTimeout(getCallBack(1), timeOut);
  7869. }
  7870. createScriptTag(scr, url, charset);
  7871. function createScriptTag(scr, url, charset) {
  7872. scr.setAttribute('type', 'text/javascript');
  7873. scr.setAttribute('defer', 'defer');
  7874. charset && scr.setAttribute('charset', charset);
  7875. scr.setAttribute('src', url);
  7876. document.getElementsByTagName('head')[0].appendChild(scr);
  7877. }
  7878. function getCallBack(onTimeOut){
  7879. return function(){
  7880. try {
  7881. if(onTimeOut){
  7882. options.onerror && options.onerror();
  7883. }else{
  7884. try{
  7885. clearTimeout(timer);
  7886. successhandler.apply(window, arguments);
  7887. } catch (e){}
  7888. }
  7889. } catch (exception) {
  7890. options.onerror && options.onerror.call(window, exception);
  7891. } finally {
  7892. options.oncomplete && options.oncomplete.apply(window, arguments);
  7893. scr.parentNode && scr.parentNode.removeChild(scr);
  7894. window[callbackFnName] = null;
  7895. try {
  7896. delete window[callbackFnName];
  7897. }catch(e){}
  7898. }
  7899. }
  7900. }
  7901. }
  7902. return {
  7903. /**
  7904. * 根据给定的参数项,向指定的url发起一个ajax请求。 ajax请求完成后,会根据请求结果调用相应回调: 如果请求
  7905. * 成功, 则调用onsuccess回调, 失败则调用 onerror 回调
  7906. * @method request
  7907. * @param { URLString } url ajax请求的url地址
  7908. * @param { Object } ajaxOptions ajax请求选项的键值对,支持的选项如下:
  7909. * @example
  7910. * ```javascript
  7911. * //向sayhello.php发起一个异步的Ajax GET请求, 请求超时时间为10s, 请求完成后执行相应的回调。
  7912. * UE.ajax.requeset( 'sayhello.php', {
  7913. *
  7914. * //请求方法。可选值: 'GET', 'POST',默认值是'POST'
  7915. * method: 'GET',
  7916. *
  7917. * //超时时间。 默认为5000, 单位是ms
  7918. * timeout: 10000,
  7919. *
  7920. * //是否是异步请求。 true为异步请求, false为同步请求
  7921. * async: true,
  7922. *
  7923. * //请求携带的数据。如果请求为GET请求, data会经过stringify后附加到请求url之后。
  7924. * data: {
  7925. * name: 'ueditor'
  7926. * },
  7927. *
  7928. * //请求成功后的回调, 该回调接受当前的XMLHttpRequest对象作为参数。
  7929. * onsuccess: function ( xhr ) {
  7930. * console.log( xhr.responseText );
  7931. * },
  7932. *
  7933. * //请求失败或者超时后的回调。
  7934. * onerror: function ( xhr ) {
  7935. * alert( 'Ajax请求失败' );
  7936. * }
  7937. *
  7938. * } );
  7939. * ```
  7940. */
  7941. /**
  7942. * 根据给定的参数项发起一个ajax请求, 参数项里必须包含一个url地址。 ajax请求完成后,会根据请求结果调用相应回调: 如果请求
  7943. * 成功, 则调用onsuccess回调, 失败则调用 onerror 回调。
  7944. * @method request
  7945. * @warning 如果在参数项里未提供一个key为“url”的地址值,则该请求将直接退出。
  7946. * @param { Object } ajaxOptions ajax请求选项的键值对,支持的选项如下:
  7947. * @example
  7948. * ```javascript
  7949. *
  7950. * //向sayhello.php发起一个异步的Ajax POST请求, 请求超时时间为5s, 请求完成后不执行任何回调。
  7951. * UE.ajax.requeset( 'sayhello.php', {
  7952. *
  7953. * //请求的地址, 该项是必须的。
  7954. * url: 'sayhello.php'
  7955. *
  7956. * } );
  7957. * ```
  7958. */
  7959. request:function(url, opts) {
  7960. if (opts && opts.dataType == 'jsonp') {
  7961. doJsonp(url, opts);
  7962. } else {
  7963. doAjax(url, opts);
  7964. }
  7965. },
  7966. getJSONP:function(url, data, fn) {
  7967. var opts = {
  7968. 'data': data,
  7969. 'oncomplete': fn
  7970. };
  7971. doJsonp(url, opts);
  7972. }
  7973. };
  7974. }();
  7975. // core/filterword.js
  7976. /**
  7977. * UE过滤word的静态方法
  7978. * @file
  7979. */
  7980. /**
  7981. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  7982. * @module UE
  7983. */
  7984. /**
  7985. * 根据传入html字符串过滤word
  7986. * @module UE
  7987. * @since 1.2.6.1
  7988. * @method filterWord
  7989. * @param { String } html html字符串
  7990. * @return { String } 已过滤后的结果字符串
  7991. * @example
  7992. * ```javascript
  7993. * UE.filterWord(html);
  7994. * ```
  7995. */
  7996. var filterWord = UE.filterWord = function () {
  7997. //是否是word过来的内容
  7998. function isWordDocument( str ) {
  7999. return /(class="?Mso|style="[^"]*\bmso\-|w:WordDocument|<(v|o):|lang=)/ig.test( str );
  8000. }
  8001. //去掉小数
  8002. function transUnit( v ) {
  8003. v = v.replace( /[\d.]+\w+/g, function ( m ) {
  8004. return utils.transUnitToPx(m);
  8005. } );
  8006. return v;
  8007. }
  8008. function filterPasteWord( str ) {
  8009. return str.replace(/[\t\r\n]+/g,' ')
  8010. .replace( /<!--[\s\S]*?-->/ig, "" )
  8011. //转换图片
  8012. .replace(/<v:shape [^>]*>[\s\S]*?.<\/v:shape>/gi,function(str){
  8013. //opera能自己解析出image所这里直接返回空
  8014. if(browser.opera){
  8015. return '';
  8016. }
  8017. try{
  8018. //有可能是bitmap占为图,无用,直接过滤掉,主要体现在粘贴excel表格中
  8019. if(/Bitmap/i.test(str)){
  8020. return '';
  8021. }
  8022. var width = str.match(/width:([ \d.]*p[tx])/i)[1],
  8023. height = str.match(/height:([ \d.]*p[tx])/i)[1],
  8024. src = str.match(/src=\s*"([^"]*)"/i)[1];
  8025. return '<img width="'+ transUnit(width) +'" height="'+transUnit(height) +'" src="' + src + '" />';
  8026. } catch(e){
  8027. return '';
  8028. }
  8029. })
  8030. //针对wps添加的多余标签处理
  8031. .replace(/<\/?div[^>]*>/g,'')
  8032. //去掉多余的属性
  8033. .replace( /v:\w+=(["']?)[^'"]+\1/g, '' )
  8034. .replace( /<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|xml|meta|link|style|\w+:\w+)(?=[\s\/>]))[^>]*>/gi, "" )
  8035. .replace( /<p [^>]*class="?MsoHeading"?[^>]*>(.*?)<\/p>/gi, "<p><strong>$1</strong></p>" )
  8036. //去掉多余的属性
  8037. .replace( /\s+(class|lang|align)\s*=\s*(['"]?)([\w-]+)\2/ig, function(str,name,marks,val){
  8038. //保留list的标示
  8039. return name == 'class' && val == 'MsoListParagraph' ? str : ''
  8040. })
  8041. //清除多余的font/span不能匹配&nbsp;有可能是空格
  8042. .replace( /<(font|span)[^>]*>(\s*)<\/\1>/gi, function(a,b,c){
  8043. return c.replace(/[\t\r\n ]+/g,' ')
  8044. })
  8045. //处理style的问题
  8046. .replace( /(<[a-z][^>]*)\sstyle=(["'])([^\2]*?)\2/gi, function( str, tag, tmp, style ) {
  8047. var n = [],
  8048. s = style.replace( /^\s+|\s+$/, '' )
  8049. .replace(/&#39;/g,'\'')
  8050. .replace( /&quot;/gi, "'" )
  8051. .replace(/[\d.]+(cm|pt)/g,function(str){
  8052. return utils.transUnitToPx(str)
  8053. })
  8054. .split( /;\s*/g );
  8055. for ( var i = 0,v; v = s[i];i++ ) {
  8056. var name, value,
  8057. parts = v.split( ":" );
  8058. if ( parts.length == 2 ) {
  8059. name = parts[0].toLowerCase();
  8060. value = parts[1].toLowerCase();
  8061. if(/^(background)\w*/.test(name) && value.replace(/(initial|\s)/g,'').length == 0
  8062. ||
  8063. /^(margin)\w*/.test(name) && /^0\w+$/.test(value)
  8064. ){
  8065. continue;
  8066. }
  8067. switch ( name ) {
  8068. case "mso-padding-alt":
  8069. case "mso-padding-top-alt":
  8070. case "mso-padding-right-alt":
  8071. case "mso-padding-bottom-alt":
  8072. case "mso-padding-left-alt":
  8073. case "mso-margin-alt":
  8074. case "mso-margin-top-alt":
  8075. case "mso-margin-right-alt":
  8076. case "mso-margin-bottom-alt":
  8077. case "mso-margin-left-alt":
  8078. //ie下会出现挤到一起的情况
  8079. //case "mso-table-layout-alt":
  8080. case "mso-height":
  8081. case "mso-width":
  8082. case "mso-vertical-align-alt":
  8083. //trace:1819 ff下会解析出padding在table上
  8084. if(!/<table/.test(tag))
  8085. n[i] = name.replace( /^mso-|-alt$/g, "" ) + ":" + transUnit( value );
  8086. continue;
  8087. case "horiz-align":
  8088. n[i] = "text-align:" + value;
  8089. continue;
  8090. case "vert-align":
  8091. n[i] = "vertical-align:" + value;
  8092. continue;
  8093. case "font-color":
  8094. case "mso-foreground":
  8095. n[i] = "color:" + value;
  8096. continue;
  8097. case "mso-background":
  8098. case "mso-highlight":
  8099. n[i] = "background:" + value;
  8100. continue;
  8101. case "mso-default-height":
  8102. n[i] = "min-height:" + transUnit( value );
  8103. continue;
  8104. case "mso-default-width":
  8105. n[i] = "min-width:" + transUnit( value );
  8106. continue;
  8107. case "mso-padding-between-alt":
  8108. n[i] = "border-collapse:separate;border-spacing:" + transUnit( value );
  8109. continue;
  8110. case "text-line-through":
  8111. if ( (value == "single") || (value == "double") ) {
  8112. n[i] = "text-decoration:line-through";
  8113. }
  8114. continue;
  8115. case "mso-zero-height":
  8116. if ( value == "yes" ) {
  8117. n[i] = "display:none";
  8118. }
  8119. continue;
  8120. // case 'background':
  8121. // break;
  8122. case 'margin':
  8123. if ( !/[1-9]/.test( value ) ) {
  8124. continue;
  8125. }
  8126. }
  8127. if ( /^(mso|column|font-emph|lang|layout|line-break|list-image|nav|panose|punct|row|ruby|sep|size|src|tab-|table-border|text-(?:decor|trans)|top-bar|version|vnd|word-break)/.test( name )
  8128. ||
  8129. /text\-indent|padding|margin/.test(name) && /\-[\d.]+/.test(value)
  8130. ) {
  8131. continue;
  8132. }
  8133. n[i] = name + ":" + parts[1];
  8134. }
  8135. }
  8136. return tag + (n.length ? ' style="' + n.join( ';').replace(/;{2,}/g,';') + '"' : '');
  8137. })
  8138. }
  8139. return function ( html ) {
  8140. return (isWordDocument( html ) ? filterPasteWord( html ) : html);
  8141. };
  8142. }();
  8143. // core/node.js
  8144. /**
  8145. * 编辑器模拟的节点类
  8146. * @file
  8147. * @module UE
  8148. * @class uNode
  8149. * @since 1.2.6.1
  8150. */
  8151. /**
  8152. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  8153. * @unfile
  8154. * @module UE
  8155. */
  8156. (function () {
  8157. /**
  8158. * 编辑器模拟的节点类
  8159. * @unfile
  8160. * @module UE
  8161. * @class uNode
  8162. */
  8163. /**
  8164. * 通过一个键值对,创建一个uNode对象
  8165. * @constructor
  8166. * @param { Object } attr 传入要创建的uNode的初始属性
  8167. * @example
  8168. * ```javascript
  8169. * var node = new uNode({
  8170. * type:'element',
  8171. * tagName:'span',
  8172. * attrs:{style:'font-size:14px;'}
  8173. * }
  8174. * ```
  8175. */
  8176. var uNode = UE.uNode = function (obj) {
  8177. this.type = obj.type;
  8178. this.data = obj.data;
  8179. this.tagName = obj.tagName;
  8180. this.parentNode = obj.parentNode;
  8181. this.attrs = obj.attrs || {};
  8182. this.children = obj.children;
  8183. };
  8184. var notTransAttrs = {
  8185. 'href':1,
  8186. 'src':1,
  8187. '_src':1,
  8188. '_href':1,
  8189. 'cdata_data':1
  8190. };
  8191. var notTransTagName = {
  8192. style:1,
  8193. script:1
  8194. };
  8195. var indentChar = ' ',
  8196. breakChar = '\n';
  8197. function insertLine(arr, current, begin) {
  8198. arr.push(breakChar);
  8199. return current + (begin ? 1 : -1);
  8200. }
  8201. function insertIndent(arr, current) {
  8202. //插入缩进
  8203. for (var i = 0; i < current; i++) {
  8204. arr.push(indentChar);
  8205. }
  8206. }
  8207. //创建uNode的静态方法
  8208. //支持标签和html
  8209. uNode.createElement = function (html) {
  8210. if (/[<>]/.test(html)) {
  8211. return UE.htmlparser(html).children[0]
  8212. } else {
  8213. return new uNode({
  8214. type:'element',
  8215. children:[],
  8216. tagName:html
  8217. })
  8218. }
  8219. };
  8220. uNode.createText = function (data,noTrans) {
  8221. return new UE.uNode({
  8222. type:'text',
  8223. 'data':noTrans ? data : utils.unhtml(data || '')
  8224. })
  8225. };
  8226. function nodeToHtml(node, arr, formatter, current) {
  8227. switch (node.type) {
  8228. case 'root':
  8229. for (var i = 0, ci; ci = node.children[i++];) {
  8230. //插入新行
  8231. if (formatter && ci.type == 'element' && !dtd.$inlineWithA[ci.tagName] && i > 1) {
  8232. insertLine(arr, current, true);
  8233. insertIndent(arr, current)
  8234. }
  8235. nodeToHtml(ci, arr, formatter, current)
  8236. }
  8237. break;
  8238. case 'text':
  8239. isText(node, arr);
  8240. break;
  8241. case 'element':
  8242. isElement(node, arr, formatter, current);
  8243. break;
  8244. case 'comment':
  8245. isComment(node, arr, formatter);
  8246. }
  8247. return arr;
  8248. }
  8249. function isText(node, arr) {
  8250. if(node.parentNode.tagName == 'pre'){
  8251. //源码模式下输入html标签,不能做转换处理,直接输出
  8252. arr.push(node.data)
  8253. }else{
  8254. arr.push(notTransTagName[node.parentNode.tagName] ? utils.html(node.data) : node.data.replace(/[ ]{2}/g,' &nbsp;'))
  8255. }
  8256. }
  8257. function isElement(node, arr, formatter, current) {
  8258. var attrhtml = '';
  8259. if (node.attrs) {
  8260. attrhtml = [];
  8261. var attrs = node.attrs;
  8262. for (var a in attrs) {
  8263. //这里就针对
  8264. //<p>'<img src='http://nsclick.baidu.com/u.gif?&asdf=\"sdf&asdfasdfs;asdf'></p>
  8265. //这里边的\"做转换,要不用innerHTML直接被截断了,属性src
  8266. //有可能做的不够
  8267. attrhtml.push(a + (attrs[a] !== undefined ? '="' + (notTransAttrs[a] ? utils.html(attrs[a]).replace(/["]/g, function (a) {
  8268. return '&quot;'
  8269. }) : utils.unhtml(attrs[a])) + '"' : ''))
  8270. }
  8271. attrhtml = attrhtml.join(' ');
  8272. }
  8273. arr.push('<' + node.tagName +
  8274. (attrhtml ? ' ' + attrhtml : '') +
  8275. (dtd.$empty[node.tagName] ? '\/' : '' ) + '>'
  8276. );
  8277. //插入新行
  8278. if (formatter && !dtd.$inlineWithA[node.tagName] && node.tagName != 'pre') {
  8279. if(node.children && node.children.length){
  8280. current = insertLine(arr, current, true);
  8281. insertIndent(arr, current)
  8282. }
  8283. }
  8284. if (node.children && node.children.length) {
  8285. for (var i = 0, ci; ci = node.children[i++];) {
  8286. if (formatter && ci.type == 'element' && !dtd.$inlineWithA[ci.tagName] && i > 1) {
  8287. insertLine(arr, current);
  8288. insertIndent(arr, current)
  8289. }
  8290. nodeToHtml(ci, arr, formatter, current)
  8291. }
  8292. }
  8293. if (!dtd.$empty[node.tagName]) {
  8294. if (formatter && !dtd.$inlineWithA[node.tagName] && node.tagName != 'pre') {
  8295. if(node.children && node.children.length){
  8296. current = insertLine(arr, current);
  8297. insertIndent(arr, current)
  8298. }
  8299. }
  8300. arr.push('<\/' + node.tagName + '>');
  8301. }
  8302. }
  8303. function isComment(node, arr) {
  8304. arr.push('<!--' + node.data + '-->');
  8305. }
  8306. function getNodeById(root, id) {
  8307. var node;
  8308. if (root.type == 'element' && root.getAttr('id') == id) {
  8309. return root;
  8310. }
  8311. if (root.children && root.children.length) {
  8312. for (var i = 0, ci; ci = root.children[i++];) {
  8313. if (node = getNodeById(ci, id)) {
  8314. return node;
  8315. }
  8316. }
  8317. }
  8318. }
  8319. function getNodesByTagName(node, tagName, arr) {
  8320. if (node.type == 'element' && node.tagName == tagName) {
  8321. arr.push(node);
  8322. }
  8323. if (node.children && node.children.length) {
  8324. for (var i = 0, ci; ci = node.children[i++];) {
  8325. getNodesByTagName(ci, tagName, arr)
  8326. }
  8327. }
  8328. }
  8329. function nodeTraversal(root,fn){
  8330. if(root.children && root.children.length){
  8331. for(var i= 0,ci;ci=root.children[i];){
  8332. nodeTraversal(ci,fn);
  8333. //ci被替换的情况,这里就不再走 fn了
  8334. if(ci.parentNode ){
  8335. if(ci.children && ci.children.length){
  8336. fn(ci)
  8337. }
  8338. if(ci.parentNode) i++
  8339. }
  8340. }
  8341. }else{
  8342. fn(root)
  8343. }
  8344. }
  8345. uNode.prototype = {
  8346. /**
  8347. * 当前节点对象,转换成html文本
  8348. * @method toHtml
  8349. * @return { String } 返回转换后的html字符串
  8350. * @example
  8351. * ```javascript
  8352. * node.toHtml();
  8353. * ```
  8354. */
  8355. /**
  8356. * 当前节点对象,转换成html文本
  8357. * @method toHtml
  8358. * @param { Boolean } formatter 是否格式化返回值
  8359. * @return { String } 返回转换后的html字符串
  8360. * @example
  8361. * ```javascript
  8362. * node.toHtml( true );
  8363. * ```
  8364. */
  8365. toHtml:function (formatter) {
  8366. var arr = [];
  8367. nodeToHtml(this, arr, formatter, 0);
  8368. return arr.join('')
  8369. },
  8370. /**
  8371. * 获取节点的html内容
  8372. * @method innerHTML
  8373. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  8374. * @return { String } 返回节点的html内容
  8375. * @example
  8376. * ```javascript
  8377. * var htmlstr = node.innerHTML();
  8378. * ```
  8379. */
  8380. /**
  8381. * 设置节点的html内容
  8382. * @method innerHTML
  8383. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  8384. * @param { String } htmlstr 传入要设置的html内容
  8385. * @return { UE.uNode } 返回节点本身
  8386. * @example
  8387. * ```javascript
  8388. * node.innerHTML('<span>text</span>');
  8389. * ```
  8390. */
  8391. innerHTML:function (htmlstr) {
  8392. if (this.type != 'element' || dtd.$empty[this.tagName]) {
  8393. return this;
  8394. }
  8395. if (utils.isString(htmlstr)) {
  8396. if(this.children){
  8397. for (var i = 0, ci; ci = this.children[i++];) {
  8398. ci.parentNode = null;
  8399. }
  8400. }
  8401. this.children = [];
  8402. var tmpRoot = UE.htmlparser(htmlstr);
  8403. for (var i = 0, ci; ci = tmpRoot.children[i++];) {
  8404. this.children.push(ci);
  8405. ci.parentNode = this;
  8406. }
  8407. return this;
  8408. } else {
  8409. var tmpRoot = new UE.uNode({
  8410. type:'root',
  8411. children:this.children
  8412. });
  8413. return tmpRoot.toHtml();
  8414. }
  8415. },
  8416. /**
  8417. * 获取节点的纯文本内容
  8418. * @method innerText
  8419. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  8420. * @return { String } 返回节点的存文本内容
  8421. * @example
  8422. * ```javascript
  8423. * var textStr = node.innerText();
  8424. * ```
  8425. */
  8426. /**
  8427. * 设置节点的纯文本内容
  8428. * @method innerText
  8429. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  8430. * @param { String } textStr 传入要设置的文本内容
  8431. * @return { UE.uNode } 返回节点本身
  8432. * @example
  8433. * ```javascript
  8434. * node.innerText('<span>text</span>');
  8435. * ```
  8436. */
  8437. innerText:function (textStr,noTrans) {
  8438. if (this.type != 'element' || dtd.$empty[this.tagName]) {
  8439. return this;
  8440. }
  8441. if (textStr) {
  8442. if(this.children){
  8443. for (var i = 0, ci; ci = this.children[i++];) {
  8444. ci.parentNode = null;
  8445. }
  8446. }
  8447. this.children = [];
  8448. this.appendChild(uNode.createText(textStr,noTrans));
  8449. return this;
  8450. } else {
  8451. return this.toHtml().replace(/<[^>]+>/g, '');
  8452. }
  8453. },
  8454. /**
  8455. * 获取当前对象的data属性
  8456. * @method getData
  8457. * @return { Object } 若节点的type值是elemenet,返回空字符串,否则返回节点的data属性
  8458. * @example
  8459. * ```javascript
  8460. * node.getData();
  8461. * ```
  8462. */
  8463. getData:function () {
  8464. if (this.type == 'element')
  8465. return '';
  8466. return this.data
  8467. },
  8468. /**
  8469. * 获取当前节点下的第一个子节点
  8470. * @method firstChild
  8471. * @return { UE.uNode } 返回第一个子节点
  8472. * @example
  8473. * ```javascript
  8474. * node.firstChild(); //返回第一个子节点
  8475. * ```
  8476. */
  8477. firstChild:function () {
  8478. // if (this.type != 'element' || dtd.$empty[this.tagName]) {
  8479. // return this;
  8480. // }
  8481. return this.children ? this.children[0] : null;
  8482. },
  8483. /**
  8484. * 获取当前节点下的最后一个子节点
  8485. * @method lastChild
  8486. * @return { UE.uNode } 返回最后一个子节点
  8487. * @example
  8488. * ```javascript
  8489. * node.lastChild(); //返回最后一个子节点
  8490. * ```
  8491. */
  8492. lastChild:function () {
  8493. // if (this.type != 'element' || dtd.$empty[this.tagName] ) {
  8494. // return this;
  8495. // }
  8496. return this.children ? this.children[this.children.length - 1] : null;
  8497. },
  8498. /**
  8499. * 获取和当前节点有相同父亲节点的前一个节点
  8500. * @method previousSibling
  8501. * @return { UE.uNode } 返回前一个节点
  8502. * @example
  8503. * ```javascript
  8504. * node.children[2].previousSibling(); //返回子节点node.children[1]
  8505. * ```
  8506. */
  8507. previousSibling : function(){
  8508. var parent = this.parentNode;
  8509. for (var i = 0, ci; ci = parent.children[i]; i++) {
  8510. if (ci === this) {
  8511. return i == 0 ? null : parent.children[i-1];
  8512. }
  8513. }
  8514. },
  8515. /**
  8516. * 获取和当前节点有相同父亲节点的后一个节点
  8517. * @method nextSibling
  8518. * @return { UE.uNode } 返回后一个节点,找不到返回null
  8519. * @example
  8520. * ```javascript
  8521. * node.children[2].nextSibling(); //如果有,返回子节点node.children[3]
  8522. * ```
  8523. */
  8524. nextSibling : function(){
  8525. var parent = this.parentNode;
  8526. for (var i = 0, ci; ci = parent.children[i++];) {
  8527. if (ci === this) {
  8528. return parent.children[i];
  8529. }
  8530. }
  8531. },
  8532. /**
  8533. * 用新的节点替换当前节点
  8534. * @method replaceChild
  8535. * @param { UE.uNode } target 要替换成该节点参数
  8536. * @param { UE.uNode } source 要被替换掉的节点
  8537. * @return { UE.uNode } 返回替换之后的节点对象
  8538. * @example
  8539. * ```javascript
  8540. * node.replaceChild(newNode, childNode); //用newNode替换childNode,childNode是node的子节点
  8541. * ```
  8542. */
  8543. replaceChild:function (target, source) {
  8544. if (this.children) {
  8545. if(target.parentNode){
  8546. target.parentNode.removeChild(target);
  8547. }
  8548. for (var i = 0, ci; ci = this.children[i]; i++) {
  8549. if (ci === source) {
  8550. this.children.splice(i, 1, target);
  8551. source.parentNode = null;
  8552. target.parentNode = this;
  8553. return target;
  8554. }
  8555. }
  8556. }
  8557. },
  8558. /**
  8559. * 在节点的子节点列表最后位置插入一个节点
  8560. * @method appendChild
  8561. * @param { UE.uNode } node 要插入的节点
  8562. * @return { UE.uNode } 返回刚插入的子节点
  8563. * @example
  8564. * ```javascript
  8565. * node.appendChild( newNode ); //在node内插入子节点newNode
  8566. * ```
  8567. */
  8568. appendChild:function (node) {
  8569. if (this.type == 'root' || (this.type == 'element' && !dtd.$empty[this.tagName])) {
  8570. if (!this.children) {
  8571. this.children = []
  8572. }
  8573. if(node.parentNode){
  8574. node.parentNode.removeChild(node);
  8575. }
  8576. for (var i = 0, ci; ci = this.children[i]; i++) {
  8577. if (ci === node) {
  8578. this.children.splice(i, 1);
  8579. break;
  8580. }
  8581. }
  8582. this.children.push(node);
  8583. node.parentNode = this;
  8584. return node;
  8585. }
  8586. },
  8587. /**
  8588. * 在传入节点的前面插入一个节点
  8589. * @method insertBefore
  8590. * @param { UE.uNode } target 要插入的节点
  8591. * @param { UE.uNode } source 在该参数节点前面插入
  8592. * @return { UE.uNode } 返回刚插入的子节点
  8593. * @example
  8594. * ```javascript
  8595. * node.parentNode.insertBefore(newNode, node); //在node节点后面插入newNode
  8596. * ```
  8597. */
  8598. insertBefore:function (target, source) {
  8599. if (this.children) {
  8600. if(target.parentNode){
  8601. target.parentNode.removeChild(target);
  8602. }
  8603. for (var i = 0, ci; ci = this.children[i]; i++) {
  8604. if (ci === source) {
  8605. this.children.splice(i, 0, target);
  8606. target.parentNode = this;
  8607. return target;
  8608. }
  8609. }
  8610. }
  8611. },
  8612. /**
  8613. * 在传入节点的后面插入一个节点
  8614. * @method insertAfter
  8615. * @param { UE.uNode } target 要插入的节点
  8616. * @param { UE.uNode } source 在该参数节点后面插入
  8617. * @return { UE.uNode } 返回刚插入的子节点
  8618. * @example
  8619. * ```javascript
  8620. * node.parentNode.insertAfter(newNode, node); //在node节点后面插入newNode
  8621. * ```
  8622. */
  8623. insertAfter:function (target, source) {
  8624. if (this.children) {
  8625. if(target.parentNode){
  8626. target.parentNode.removeChild(target);
  8627. }
  8628. for (var i = 0, ci; ci = this.children[i]; i++) {
  8629. if (ci === source) {
  8630. this.children.splice(i + 1, 0, target);
  8631. target.parentNode = this;
  8632. return target;
  8633. }
  8634. }
  8635. }
  8636. },
  8637. /**
  8638. * 从当前节点的子节点列表中,移除节点
  8639. * @method removeChild
  8640. * @param { UE.uNode } node 要移除的节点引用
  8641. * @param { Boolean } keepChildren 是否保留移除节点的子节点,若传入true,自动把移除节点的子节点插入到移除的位置
  8642. * @return { * } 返回刚移除的子节点
  8643. * @example
  8644. * ```javascript
  8645. * node.removeChild(childNode,true); //在node的子节点列表中移除child节点,并且吧child的子节点插入到移除的位置
  8646. * ```
  8647. */
  8648. removeChild:function (node,keepChildren) {
  8649. if (this.children) {
  8650. for (var i = 0, ci; ci = this.children[i]; i++) {
  8651. if (ci === node) {
  8652. this.children.splice(i, 1);
  8653. ci.parentNode = null;
  8654. if(keepChildren && ci.children && ci.children.length){
  8655. for(var j= 0,cj;cj=ci.children[j];j++){
  8656. this.children.splice(i+j,0,cj);
  8657. cj.parentNode = this;
  8658. }
  8659. }
  8660. return ci;
  8661. }
  8662. }
  8663. }
  8664. },
  8665. /**
  8666. * 获取当前节点所代表的元素属性,即获取attrs对象下的属性值
  8667. * @method getAttr
  8668. * @param { String } attrName 要获取的属性名称
  8669. * @return { * } 返回attrs对象下的属性值
  8670. * @example
  8671. * ```javascript
  8672. * node.getAttr('title');
  8673. * ```
  8674. */
  8675. getAttr:function (attrName) {
  8676. return this.attrs && this.attrs[attrName.toLowerCase()]
  8677. },
  8678. /**
  8679. * 设置当前节点所代表的元素属性,即设置attrs对象下的属性值
  8680. * @method setAttr
  8681. * @param { String } attrName 要设置的属性名称
  8682. * @param { * } attrVal 要设置的属性值,类型视设置的属性而定
  8683. * @return { * } 返回attrs对象下的属性值
  8684. * @example
  8685. * ```javascript
  8686. * node.setAttr('title','标题');
  8687. * ```
  8688. */
  8689. setAttr:function (attrName, attrVal) {
  8690. if (!attrName) {
  8691. delete this.attrs;
  8692. return;
  8693. }
  8694. if(!this.attrs){
  8695. this.attrs = {};
  8696. }
  8697. if (utils.isObject(attrName)) {
  8698. for (var a in attrName) {
  8699. if (!attrName[a]) {
  8700. delete this.attrs[a]
  8701. } else {
  8702. this.attrs[a.toLowerCase()] = attrName[a];
  8703. }
  8704. }
  8705. } else {
  8706. if (!attrVal) {
  8707. delete this.attrs[attrName]
  8708. } else {
  8709. this.attrs[attrName.toLowerCase()] = attrVal;
  8710. }
  8711. }
  8712. },
  8713. /**
  8714. * 获取当前节点在父节点下的位置索引
  8715. * @method getIndex
  8716. * @return { Number } 返回索引数值,如果没有父节点,返回-1
  8717. * @example
  8718. * ```javascript
  8719. * node.getIndex();
  8720. * ```
  8721. */
  8722. getIndex:function(){
  8723. var parent = this.parentNode;
  8724. for(var i= 0,ci;ci=parent.children[i];i++){
  8725. if(ci === this){
  8726. return i;
  8727. }
  8728. }
  8729. return -1;
  8730. },
  8731. /**
  8732. * 在当前节点下,根据id查找节点
  8733. * @method getNodeById
  8734. * @param { String } id 要查找的id
  8735. * @return { UE.uNode } 返回找到的节点
  8736. * @example
  8737. * ```javascript
  8738. * node.getNodeById('textId');
  8739. * ```
  8740. */
  8741. getNodeById:function (id) {
  8742. var node;
  8743. if (this.children && this.children.length) {
  8744. for (var i = 0, ci; ci = this.children[i++];) {
  8745. if (node = getNodeById(ci, id)) {
  8746. return node;
  8747. }
  8748. }
  8749. }
  8750. },
  8751. /**
  8752. * 在当前节点下,根据元素名称查找节点列表
  8753. * @method getNodesByTagName
  8754. * @param { String } tagNames 要查找的元素名称
  8755. * @return { Array } 返回找到的节点列表
  8756. * @example
  8757. * ```javascript
  8758. * node.getNodesByTagName('span');
  8759. * ```
  8760. */
  8761. getNodesByTagName:function (tagNames) {
  8762. tagNames = utils.trim(tagNames).replace(/[ ]{2,}/g, ' ').split(' ');
  8763. var arr = [], me = this;
  8764. utils.each(tagNames, function (tagName) {
  8765. if (me.children && me.children.length) {
  8766. for (var i = 0, ci; ci = me.children[i++];) {
  8767. getNodesByTagName(ci, tagName, arr)
  8768. }
  8769. }
  8770. });
  8771. return arr;
  8772. },
  8773. /**
  8774. * 根据样式名称,获取节点的样式值
  8775. * @method getStyle
  8776. * @param { String } name 要获取的样式名称
  8777. * @return { String } 返回样式值
  8778. * @example
  8779. * ```javascript
  8780. * node.getStyle('font-size');
  8781. * ```
  8782. */
  8783. getStyle:function (name) {
  8784. var cssStyle = this.getAttr('style');
  8785. if (!cssStyle) {
  8786. return ''
  8787. }
  8788. var reg = new RegExp('(^|;)\\s*' + name + ':([^;]+)','i');
  8789. var match = cssStyle.match(reg);
  8790. if (match && match[0]) {
  8791. return match[2]
  8792. }
  8793. return '';
  8794. },
  8795. /**
  8796. * 给节点设置样式
  8797. * @method setStyle
  8798. * @param { String } name 要设置的的样式名称
  8799. * @param { String } val 要设置的的样值
  8800. * @example
  8801. * ```javascript
  8802. * node.setStyle('font-size', '12px');
  8803. * ```
  8804. */
  8805. setStyle:function (name, val) {
  8806. function exec(name, val) {
  8807. var reg = new RegExp('(^|;)\\s*' + name + ':([^;]+;?)', 'gi');
  8808. cssStyle = cssStyle.replace(reg, '$1');
  8809. if (val) {
  8810. cssStyle = name + ':' + utils.unhtml(val) + ';' + cssStyle
  8811. }
  8812. }
  8813. var cssStyle = this.getAttr('style');
  8814. if (!cssStyle) {
  8815. cssStyle = '';
  8816. }
  8817. if (utils.isObject(name)) {
  8818. for (var a in name) {
  8819. exec(a, name[a])
  8820. }
  8821. } else {
  8822. exec(name, val)
  8823. }
  8824. this.setAttr('style', utils.trim(cssStyle))
  8825. },
  8826. /**
  8827. * 传入一个函数,递归遍历当前节点下的所有节点
  8828. * @method traversal
  8829. * @param { Function } fn 遍历到节点的时,传入节点作为参数,运行此函数
  8830. * @example
  8831. * ```javascript
  8832. * traversal(node, function(){
  8833. * console.log(node.type);
  8834. * });
  8835. * ```
  8836. */
  8837. traversal:function(fn){
  8838. if(this.children && this.children.length){
  8839. nodeTraversal(this,fn);
  8840. }
  8841. return this;
  8842. }
  8843. }
  8844. })();
  8845. // core/htmlparser.js
  8846. /**
  8847. * html字符串转换成uNode节点
  8848. * @file
  8849. * @module UE
  8850. * @since 1.2.6.1
  8851. */
  8852. /**
  8853. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  8854. * @unfile
  8855. * @module UE
  8856. */
  8857. /**
  8858. * html字符串转换成uNode节点的静态方法
  8859. * @method htmlparser
  8860. * @param { String } htmlstr 要转换的html代码
  8861. * @param { Boolean } ignoreBlank 若设置为true,转换的时候忽略\n\r\t等空白字符
  8862. * @return { uNode } 给定的html片段转换形成的uNode对象
  8863. * @example
  8864. * ```javascript
  8865. * var root = UE.htmlparser('<p><b>htmlparser</b></p>', true);
  8866. * ```
  8867. */
  8868. var htmlparser = UE.htmlparser = function (htmlstr,ignoreBlank) {
  8869. //todo 原来的方式 [^"'<>\/] 有\/就不能配对上 <TD vAlign=top background=../AAA.JPG> 这样的标签了
  8870. //先去掉了,加上的原因忘了,这里先记录
  8871. var re_tag = /<(?:(?:\/([^>]+)>)|(?:!--([\S|\s]*?)-->)|(?:([^\s\/<>]+)\s*((?:(?:"[^"]*")|(?:'[^']*')|[^"'<>])*)\/?>))/g,
  8872. re_attr = /([\w\-:.]+)(?:(?:\s*=\s*(?:(?:"([^"]*)")|(?:'([^']*)')|([^\s>]+)))|(?=\s|$))/g;
  8873. //ie下取得的html可能会有\n存在,要去掉,在处理replace(/[\t\r\n]*/g,'');代码高量的\n不能去除
  8874. var allowEmptyTags = {
  8875. b:1,code:1,i:1,u:1,strike:1,s:1,tt:1,strong:1,q:1,samp:1,em:1,span:1,
  8876. sub:1,img:1,sup:1,font:1,big:1,small:1,iframe:1,a:1,br:1,pre:1
  8877. };
  8878. htmlstr = htmlstr.replace(new RegExp(domUtils.fillChar, 'g'), '');
  8879. if(!ignoreBlank){
  8880. htmlstr = htmlstr.replace(new RegExp('[\\r\\t\\n'+(ignoreBlank?'':' ')+']*<\/?(\\w+)\\s*(?:[^>]*)>[\\r\\t\\n'+(ignoreBlank?'':' ')+']*','g'), function(a,b){
  8881. //br暂时单独处理
  8882. if(b && allowEmptyTags[b.toLowerCase()]){
  8883. return a.replace(/(^[\n\r]+)|([\n\r]+$)/g,'');
  8884. }
  8885. return a.replace(new RegExp('^[\\r\\n'+(ignoreBlank?'':' ')+']+'),'').replace(new RegExp('[\\r\\n'+(ignoreBlank?'':' ')+']+$'),'');
  8886. });
  8887. }
  8888. var notTransAttrs = {
  8889. 'href':1,
  8890. 'src':1
  8891. };
  8892. var uNode = UE.uNode,
  8893. needParentNode = {
  8894. 'td':'tr',
  8895. 'tr':['tbody','thead','tfoot'],
  8896. 'tbody':'table',
  8897. 'th':'tr',
  8898. 'thead':'table',
  8899. 'tfoot':'table',
  8900. 'caption':'table',
  8901. 'li':['ul', 'ol'],
  8902. 'dt':'dl',
  8903. 'dd':'dl',
  8904. 'option':'select'
  8905. },
  8906. needChild = {
  8907. 'ol':'li',
  8908. 'ul':'li'
  8909. };
  8910. function text(parent, data) {
  8911. if(needChild[parent.tagName]){
  8912. var tmpNode = uNode.createElement(needChild[parent.tagName]);
  8913. parent.appendChild(tmpNode);
  8914. tmpNode.appendChild(uNode.createText(data));
  8915. parent = tmpNode;
  8916. }else{
  8917. parent.appendChild(uNode.createText(data));
  8918. }
  8919. }
  8920. function element(parent, tagName, htmlattr) {
  8921. var needParentTag;
  8922. if (needParentTag = needParentNode[tagName]) {
  8923. var tmpParent = parent,hasParent;
  8924. while(tmpParent.type != 'root'){
  8925. if(utils.isArray(needParentTag) ? utils.indexOf(needParentTag, tmpParent.tagName) != -1 : needParentTag == tmpParent.tagName){
  8926. parent = tmpParent;
  8927. hasParent = true;
  8928. break;
  8929. }
  8930. tmpParent = tmpParent.parentNode;
  8931. }
  8932. if(!hasParent){
  8933. parent = element(parent, utils.isArray(needParentTag) ? needParentTag[0] : needParentTag)
  8934. }
  8935. }
  8936. //按dtd处理嵌套
  8937. // if(parent.type != 'root' && !dtd[parent.tagName][tagName])
  8938. // parent = parent.parentNode;
  8939. var elm = new uNode({
  8940. parentNode:parent,
  8941. type:'element',
  8942. tagName:tagName.toLowerCase(),
  8943. //是自闭合的处理一下
  8944. children:dtd.$empty[tagName] ? null : []
  8945. });
  8946. //如果属性存在,处理属性
  8947. if (htmlattr) {
  8948. var attrs = {}, match;
  8949. while (match = re_attr.exec(htmlattr)) {
  8950. attrs[match[1].toLowerCase()] = notTransAttrs[match[1].toLowerCase()] ? (match[2] || match[3] || match[4]) : utils.unhtml(match[2] || match[3] || match[4])
  8951. }
  8952. elm.attrs = attrs;
  8953. }
  8954. //trace:3970
  8955. // //如果parent下不能放elm
  8956. // if(dtd.$inline[parent.tagName] && dtd.$block[elm.tagName] && !dtd[parent.tagName][elm.tagName]){
  8957. // parent = parent.parentNode;
  8958. // elm.parentNode = parent;
  8959. // }
  8960. parent.children.push(elm);
  8961. //如果是自闭合节点返回父亲节点
  8962. return dtd.$empty[tagName] ? parent : elm
  8963. }
  8964. function comment(parent, data) {
  8965. parent.children.push(new uNode({
  8966. type:'comment',
  8967. data:data,
  8968. parentNode:parent
  8969. }));
  8970. }
  8971. var match, currentIndex = 0, nextIndex = 0;
  8972. //设置根节点
  8973. var root = new uNode({
  8974. type:'root',
  8975. children:[]
  8976. });
  8977. var currentParent = root;
  8978. while (match = re_tag.exec(htmlstr)) {
  8979. currentIndex = match.index;
  8980. try{
  8981. if (currentIndex > nextIndex) {
  8982. //text node
  8983. text(currentParent, htmlstr.slice(nextIndex, currentIndex));
  8984. }
  8985. if (match[3]) {
  8986. if(dtd.$cdata[currentParent.tagName]){
  8987. text(currentParent, match[0]);
  8988. }else{
  8989. //start tag
  8990. currentParent = element(currentParent, match[3].toLowerCase(), match[4]);
  8991. }
  8992. } else if (match[1]) {
  8993. if(currentParent.type != 'root'){
  8994. if(dtd.$cdata[currentParent.tagName] && !dtd.$cdata[match[1]]){
  8995. text(currentParent, match[0]);
  8996. }else{
  8997. var tmpParent = currentParent;
  8998. while(currentParent.type == 'element' && currentParent.tagName != match[1].toLowerCase()){
  8999. currentParent = currentParent.parentNode;
  9000. if(currentParent.type == 'root'){
  9001. currentParent = tmpParent;
  9002. throw 'break'
  9003. }
  9004. }
  9005. //end tag
  9006. currentParent = currentParent.parentNode;
  9007. }
  9008. }
  9009. } else if (match[2]) {
  9010. //comment
  9011. comment(currentParent, match[2])
  9012. }
  9013. }catch(e){}
  9014. nextIndex = re_tag.lastIndex;
  9015. }
  9016. //如果结束是文本,就有可能丢掉,所以这里手动判断一下
  9017. //例如 <li>sdfsdfsdf<li>sdfsdfsdfsdf
  9018. if (nextIndex < htmlstr.length) {
  9019. text(currentParent, htmlstr.slice(nextIndex));
  9020. }
  9021. return root;
  9022. };
  9023. // core/filternode.js
  9024. /**
  9025. * UE过滤节点的静态方法
  9026. * @file
  9027. */
  9028. /**
  9029. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  9030. * @module UE
  9031. */
  9032. /**
  9033. * 根据传入节点和过滤规则过滤相应节点
  9034. * @module UE
  9035. * @since 1.2.6.1
  9036. * @method filterNode
  9037. * @param { Object } root 指定root节点
  9038. * @param { Object } rules 过滤规则json对象
  9039. * @example
  9040. * ```javascript
  9041. * UE.filterNode(root,editor.options.filterRules);
  9042. * ```
  9043. */
  9044. var filterNode = UE.filterNode = function () {
  9045. function filterNode(node,rules){
  9046. switch (node.type) {
  9047. case 'text':
  9048. break;
  9049. case 'element':
  9050. var val;
  9051. if(val = rules[node.tagName]){
  9052. if(val === '-'){
  9053. node.parentNode.removeChild(node)
  9054. }else if(utils.isFunction(val)){
  9055. var parentNode = node.parentNode,
  9056. index = node.getIndex();
  9057. val(node);
  9058. if(node.parentNode){
  9059. if(node.children){
  9060. for(var i = 0,ci;ci=node.children[i];){
  9061. filterNode(ci,rules);
  9062. if(ci.parentNode){
  9063. i++;
  9064. }
  9065. }
  9066. }
  9067. }else{
  9068. for(var i = index,ci;ci=parentNode.children[i];){
  9069. filterNode(ci,rules);
  9070. if(ci.parentNode){
  9071. i++;
  9072. }
  9073. }
  9074. }
  9075. }else{
  9076. var attrs = val['$'];
  9077. if(attrs && node.attrs){
  9078. var tmpAttrs = {},tmpVal;
  9079. for(var a in attrs){
  9080. tmpVal = node.getAttr(a);
  9081. //todo 只先对style单独处理
  9082. if(a == 'style' && utils.isArray(attrs[a])){
  9083. var tmpCssStyle = [];
  9084. utils.each(attrs[a],function(v){
  9085. var tmp;
  9086. if(tmp = node.getStyle(v)){
  9087. tmpCssStyle.push(v + ':' + tmp);
  9088. }
  9089. });
  9090. tmpVal = tmpCssStyle.join(';')
  9091. }
  9092. if(tmpVal){
  9093. tmpAttrs[a] = tmpVal;
  9094. }
  9095. }
  9096. node.attrs = tmpAttrs;
  9097. }
  9098. if(node.children){
  9099. for(var i = 0,ci;ci=node.children[i];){
  9100. filterNode(ci,rules);
  9101. if(ci.parentNode){
  9102. i++;
  9103. }
  9104. }
  9105. }
  9106. }
  9107. }else{
  9108. //如果不在名单里扣出子节点并删除该节点,cdata除外
  9109. if(dtd.$cdata[node.tagName]){
  9110. node.parentNode.removeChild(node)
  9111. }else{
  9112. var parentNode = node.parentNode,
  9113. index = node.getIndex();
  9114. node.parentNode.removeChild(node,true);
  9115. for(var i = index,ci;ci=parentNode.children[i];){
  9116. filterNode(ci,rules);
  9117. if(ci.parentNode){
  9118. i++;
  9119. }
  9120. }
  9121. }
  9122. }
  9123. break;
  9124. case 'comment':
  9125. node.parentNode.removeChild(node)
  9126. }
  9127. }
  9128. return function(root,rules){
  9129. if(utils.isEmptyObject(rules)){
  9130. return root;
  9131. }
  9132. var val;
  9133. if(val = rules['-']){
  9134. utils.each(val.split(' '),function(k){
  9135. rules[k] = '-'
  9136. })
  9137. }
  9138. for(var i= 0,ci;ci=root.children[i];){
  9139. filterNode(ci,rules);
  9140. if(ci.parentNode){
  9141. i++;
  9142. }
  9143. }
  9144. return root;
  9145. }
  9146. }();
  9147. // core/plugin.js
  9148. /**
  9149. * Created with JetBrains PhpStorm.
  9150. * User: campaign
  9151. * Date: 10/8/13
  9152. * Time: 6:15 PM
  9153. * To change this template use File | Settings | File Templates.
  9154. */
  9155. UE.plugin = function(){
  9156. var _plugins = {};
  9157. return {
  9158. register : function(pluginName,fn,oldOptionName,afterDisabled){
  9159. if(oldOptionName && utils.isFunction(oldOptionName)){
  9160. afterDisabled = oldOptionName;
  9161. oldOptionName = null
  9162. }
  9163. _plugins[pluginName] = {
  9164. optionName : oldOptionName || pluginName,
  9165. execFn : fn,
  9166. //当插件被禁用时执行
  9167. afterDisabled : afterDisabled
  9168. }
  9169. },
  9170. load : function(editor){
  9171. utils.each(_plugins,function(plugin){
  9172. var _export = plugin.execFn.call(editor);
  9173. if(editor.options[plugin.optionName] !== false){
  9174. if(_export){
  9175. //后边需要再做扩展
  9176. utils.each(_export,function(v,k){
  9177. switch(k.toLowerCase()){
  9178. case 'shortcutkey':
  9179. editor.addshortcutkey(v);
  9180. break;
  9181. case 'bindevents':
  9182. utils.each(v,function(fn,eventName){
  9183. editor.addListener(eventName,fn);
  9184. });
  9185. break;
  9186. case 'bindmultievents':
  9187. utils.each(utils.isArray(v) ? v:[v],function(event){
  9188. var types = utils.trim(event.type).split(/\s+/);
  9189. utils.each(types,function(eventName){
  9190. editor.addListener(eventName, event.handler);
  9191. });
  9192. });
  9193. break;
  9194. case 'commands':
  9195. utils.each(v,function(execFn,execName){
  9196. editor.commands[execName] = execFn
  9197. });
  9198. break;
  9199. case 'outputrule':
  9200. editor.addOutputRule(v);
  9201. break;
  9202. case 'inputrule':
  9203. editor.addInputRule(v);
  9204. break;
  9205. case 'defaultoptions':
  9206. editor.setOpt(v)
  9207. }
  9208. })
  9209. }
  9210. }else if(plugin.afterDisabled){
  9211. plugin.afterDisabled.call(editor)
  9212. }
  9213. });
  9214. //向下兼容
  9215. utils.each(UE.plugins,function(plugin){
  9216. plugin.call(editor);
  9217. });
  9218. },
  9219. run : function(pluginName,editor){
  9220. var plugin = _plugins[pluginName];
  9221. if(plugin){
  9222. plugin.exeFn.call(editor)
  9223. }
  9224. }
  9225. }
  9226. }();
  9227. // core/keymap.js
  9228. var keymap = UE.keymap = {
  9229. 'Backspace' : 8,
  9230. 'Tab' : 9,
  9231. 'Enter' : 13,
  9232. 'Shift':16,
  9233. 'Control':17,
  9234. 'Alt':18,
  9235. 'CapsLock':20,
  9236. 'Esc':27,
  9237. 'Spacebar':32,
  9238. 'PageUp':33,
  9239. 'PageDown':34,
  9240. 'End':35,
  9241. 'Home':36,
  9242. 'Left':37,
  9243. 'Up':38,
  9244. 'Right':39,
  9245. 'Down':40,
  9246. 'Insert':45,
  9247. 'Del':46,
  9248. 'NumLock':144,
  9249. 'Cmd':91,
  9250. '=':187,
  9251. '-':189,
  9252. "b":66,
  9253. 'i':73,
  9254. //回退
  9255. 'z':90,
  9256. 'y':89,
  9257. //粘贴
  9258. 'v' : 86,
  9259. 'x' : 88,
  9260. 's' : 83,
  9261. 'n' : 78
  9262. };
  9263. // core/localstorage.js
  9264. //存储媒介封装
  9265. var LocalStorage = UE.LocalStorage = (function () {
  9266. var storage = window.localStorage || getUserData() || null,
  9267. LOCAL_FILE = 'localStorage';
  9268. return {
  9269. saveLocalData: function (key, data) {
  9270. if (storage && data) {
  9271. storage.setItem(key, data);
  9272. return true;
  9273. }
  9274. return false;
  9275. },
  9276. getLocalData: function (key) {
  9277. if (storage) {
  9278. return storage.getItem(key);
  9279. }
  9280. return null;
  9281. },
  9282. removeItem: function (key) {
  9283. storage && storage.removeItem(key);
  9284. }
  9285. };
  9286. function getUserData() {
  9287. var container = document.createElement("div");
  9288. container.style.display = "none";
  9289. if (!container.addBehavior) {
  9290. return null;
  9291. }
  9292. container.addBehavior("#default#userdata");
  9293. return {
  9294. getItem: function (key) {
  9295. var result = null;
  9296. try {
  9297. document.body.appendChild(container);
  9298. container.load(LOCAL_FILE);
  9299. result = container.getAttribute(key);
  9300. document.body.removeChild(container);
  9301. } catch (e) {
  9302. }
  9303. return result;
  9304. },
  9305. setItem: function (key, value) {
  9306. document.body.appendChild(container);
  9307. container.setAttribute(key, value);
  9308. container.save(LOCAL_FILE);
  9309. document.body.removeChild(container);
  9310. },
  9311. //// 暂时没有用到
  9312. //clear: function () {
  9313. //
  9314. // var expiresTime = new Date();
  9315. // expiresTime.setFullYear(expiresTime.getFullYear() - 1);
  9316. // document.body.appendChild(container);
  9317. // container.expires = expiresTime.toUTCString();
  9318. // container.save(LOCAL_FILE);
  9319. // document.body.removeChild(container);
  9320. //
  9321. //},
  9322. removeItem: function (key) {
  9323. document.body.appendChild(container);
  9324. container.removeAttribute(key);
  9325. container.save(LOCAL_FILE);
  9326. document.body.removeChild(container);
  9327. }
  9328. };
  9329. }
  9330. })();
  9331. (function () {
  9332. var ROOTKEY = 'ueditor_preference';
  9333. UE.Editor.prototype.setPreferences = function(key,value){
  9334. var obj = {};
  9335. if (utils.isString(key)) {
  9336. obj[ key ] = value;
  9337. } else {
  9338. obj = key;
  9339. }
  9340. var data = LocalStorage.getLocalData(ROOTKEY);
  9341. if (data && (data = utils.str2json(data))) {
  9342. utils.extend(data, obj);
  9343. } else {
  9344. data = obj;
  9345. }
  9346. data && LocalStorage.saveLocalData(ROOTKEY, utils.json2str(data));
  9347. };
  9348. UE.Editor.prototype.getPreferences = function(key){
  9349. var data = LocalStorage.getLocalData(ROOTKEY);
  9350. if (data && (data = utils.str2json(data))) {
  9351. return key ? data[key] : data
  9352. }
  9353. return null;
  9354. };
  9355. UE.Editor.prototype.removePreferences = function (key) {
  9356. var data = LocalStorage.getLocalData(ROOTKEY);
  9357. if (data && (data = utils.str2json(data))) {
  9358. data[key] = undefined;
  9359. delete data[key]
  9360. }
  9361. data && LocalStorage.saveLocalData(ROOTKEY, utils.json2str(data));
  9362. };
  9363. })();
  9364. // plugins/defaultfilter.js
  9365. ///import core
  9366. ///plugin 编辑器默认的过滤转换机制
  9367. UE.plugins['defaultfilter'] = function () {
  9368. var me = this;
  9369. me.setOpt({
  9370. 'allowDivTransToP':true,
  9371. 'disabledTableInTable':true
  9372. });
  9373. //默认的过滤处理
  9374. //进入编辑器的内容处理
  9375. me.addInputRule(function (root) {
  9376. var allowDivTransToP = this.options.allowDivTransToP;
  9377. var val;
  9378. function tdParent(node){
  9379. while(node && node.type == 'element'){
  9380. if(node.tagName == 'td'){
  9381. return true;
  9382. }
  9383. node = node.parentNode;
  9384. }
  9385. return false;
  9386. }
  9387. //进行默认的处理
  9388. root.traversal(function (node) {
  9389. if (node.type == 'element') {
  9390. if (!dtd.$cdata[node.tagName] && me.options.autoClearEmptyNode && dtd.$inline[node.tagName] && !dtd.$empty[node.tagName] && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  9391. if (!node.firstChild()) node.parentNode.removeChild(node);
  9392. else if (node.tagName == 'span' && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  9393. node.parentNode.removeChild(node, true)
  9394. }
  9395. return;
  9396. }
  9397. switch (node.tagName) {
  9398. case 'style':
  9399. case 'script':
  9400. node.setAttr({
  9401. cdata_tag: node.tagName,
  9402. cdata_data: (node.innerHTML() || ''),
  9403. '_ue_custom_node_':'true'
  9404. });
  9405. node.tagName = 'div';
  9406. node.innerHTML('');
  9407. break;
  9408. case 'a':
  9409. if (val = node.getAttr('href')) {
  9410. node.setAttr('_href', val)
  9411. }
  9412. break;
  9413. case 'img':
  9414. //todo base64暂时去掉,后边做远程图片上传后,干掉这个
  9415. if (val = node.getAttr('src')) {
  9416. if (/^data:/.test(val)) {
  9417. node.parentNode.removeChild(node);
  9418. break;
  9419. }
  9420. }
  9421. node.setAttr('_src', node.getAttr('src'));
  9422. break;
  9423. case 'span':
  9424. if (browser.webkit && (val = node.getStyle('white-space'))) {
  9425. if (/nowrap|normal/.test(val)) {
  9426. node.setStyle('white-space', '');
  9427. if (me.options.autoClearEmptyNode && utils.isEmptyObject(node.attrs)) {
  9428. node.parentNode.removeChild(node, true)
  9429. }
  9430. }
  9431. }
  9432. val = node.getAttr('id');
  9433. if(val && /^_baidu_bookmark_/i.test(val)){
  9434. node.parentNode.removeChild(node)
  9435. }
  9436. break;
  9437. case 'p':
  9438. if (val = node.getAttr('align')) {
  9439. node.setAttr('align');
  9440. node.setStyle('text-align', val)
  9441. }
  9442. //trace:3431
  9443. // var cssStyle = node.getAttr('style');
  9444. // if (cssStyle) {
  9445. // cssStyle = cssStyle.replace(/(margin|padding)[^;]+/g, '');
  9446. // node.setAttr('style', cssStyle)
  9447. //
  9448. // }
  9449. //p标签不允许嵌套
  9450. utils.each(node.children,function(n){
  9451. if(n.type == 'element' && n.tagName == 'p'){
  9452. var next = n.nextSibling();
  9453. node.parentNode.insertAfter(n,node);
  9454. var last = n;
  9455. while(next){
  9456. var tmp = next.nextSibling();
  9457. node.parentNode.insertAfter(next,last);
  9458. last = next;
  9459. next = tmp;
  9460. }
  9461. return false;
  9462. }
  9463. });
  9464. if (!node.firstChild()) {
  9465. node.innerHTML(browser.ie ? '&nbsp;' : '<br/>')
  9466. }
  9467. break;
  9468. case 'div':
  9469. if(node.getAttr('cdata_tag')){
  9470. break;
  9471. }
  9472. //针对代码这里不处理插入代码的div
  9473. val = node.getAttr('class');
  9474. if(val && /^line number\d+/.test(val)){
  9475. break;
  9476. }
  9477. if(!allowDivTransToP){
  9478. break;
  9479. }
  9480. var tmpNode, p = UE.uNode.createElement('p');
  9481. while (tmpNode = node.firstChild()) {
  9482. if (tmpNode.type == 'text' || !UE.dom.dtd.$block[tmpNode.tagName]) {
  9483. p.appendChild(tmpNode);
  9484. } else {
  9485. if (p.firstChild()) {
  9486. node.parentNode.insertBefore(p, node);
  9487. p = UE.uNode.createElement('p');
  9488. } else {
  9489. node.parentNode.insertBefore(tmpNode, node);
  9490. }
  9491. }
  9492. }
  9493. if (p.firstChild()) {
  9494. node.parentNode.insertBefore(p, node);
  9495. }
  9496. node.parentNode.removeChild(node);
  9497. break;
  9498. case 'dl':
  9499. node.tagName = 'ul';
  9500. break;
  9501. case 'dt':
  9502. case 'dd':
  9503. node.tagName = 'li';
  9504. break;
  9505. case 'li':
  9506. var className = node.getAttr('class');
  9507. if (!className || !/list\-/.test(className)) {
  9508. node.setAttr()
  9509. }
  9510. var tmpNodes = node.getNodesByTagName('ol ul');
  9511. UE.utils.each(tmpNodes, function (n) {
  9512. node.parentNode.insertAfter(n, node);
  9513. });
  9514. break;
  9515. case 'td':
  9516. case 'th':
  9517. case 'caption':
  9518. if(!node.children || !node.children.length){
  9519. node.appendChild(browser.ie11below ? UE.uNode.createText(' ') : UE.uNode.createElement('br'))
  9520. }
  9521. break;
  9522. case 'table':
  9523. if(me.options.disabledTableInTable && tdParent(node)){
  9524. node.parentNode.insertBefore(UE.uNode.createText(node.innerText()),node);
  9525. node.parentNode.removeChild(node)
  9526. }
  9527. }
  9528. }
  9529. // if(node.type == 'comment'){
  9530. // node.parentNode.removeChild(node);
  9531. // }
  9532. })
  9533. });
  9534. //从编辑器出去的内容处理
  9535. me.addOutputRule(function (root) {
  9536. var val;
  9537. root.traversal(function (node) {
  9538. if (node.type == 'element') {
  9539. if (me.options.autoClearEmptyNode && dtd.$inline[node.tagName] && !dtd.$empty[node.tagName] && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  9540. if (!node.firstChild()) node.parentNode.removeChild(node);
  9541. else if (node.tagName == 'span' && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  9542. node.parentNode.removeChild(node, true)
  9543. }
  9544. return;
  9545. }
  9546. switch (node.tagName) {
  9547. case 'div':
  9548. if (val = node.getAttr('cdata_tag')) {
  9549. node.tagName = val;
  9550. node.appendChild(UE.uNode.createText(node.getAttr('cdata_data')));
  9551. node.setAttr({cdata_tag: '', cdata_data: '','_ue_custom_node_':''});
  9552. }
  9553. break;
  9554. case 'a':
  9555. if (val = node.getAttr('_href')) {
  9556. node.setAttr({
  9557. 'href': utils.html(val),
  9558. '_href': ''
  9559. })
  9560. }
  9561. break;
  9562. break;
  9563. case 'span':
  9564. val = node.getAttr('id');
  9565. if(val && /^_baidu_bookmark_/i.test(val)){
  9566. node.parentNode.removeChild(node)
  9567. }
  9568. break;
  9569. case 'img':
  9570. if (val = node.getAttr('_src')) {
  9571. node.setAttr({
  9572. 'src': node.getAttr('_src'),
  9573. '_src': ''
  9574. })
  9575. }
  9576. }
  9577. }
  9578. })
  9579. });
  9580. };
  9581. // plugins/inserthtml.js
  9582. /**
  9583. * 插入html字符串插件
  9584. * @file
  9585. * @since 1.2.6.1
  9586. */
  9587. /**
  9588. * 插入html代码
  9589. * @command inserthtml
  9590. * @method execCommand
  9591. * @param { String } cmd 命令字符串
  9592. * @param { String } html 插入的html字符串
  9593. * @remaind 插入的标签内容是在当前的选区位置上插入,如果当前是闭合状态,那直接插入内容, 如果当前是选中状态,将先清除当前选中内容后,再做插入
  9594. * @warning 注意:该命令会对当前选区的位置,对插入的内容进行过滤转换处理。 过滤的规则遵循html语意化的原则。
  9595. * @example
  9596. * ```javascript
  9597. * //xxx[BB]xxx 当前选区为非闭合选区,选中BB这两个文本
  9598. * //执行命令,插入<b>CC</b>
  9599. * //插入后的效果 xxx<b>CC</b>xxx
  9600. * //<p>xx|xxx</p> 当前选区为闭合状态
  9601. * //插入<p>CC</p>
  9602. * //结果 <p>xx</p><p>CC</p><p>xxx</p>
  9603. * //<p>xxxx</p>|</p>xxx</p> 当前选区在两个p标签之间
  9604. * //插入 xxxx
  9605. * //结果 <p>xxxx</p><p>xxxx</p></p>xxx</p>
  9606. * ```
  9607. */
  9608. UE.commands['inserthtml'] = {
  9609. execCommand: function (command,html,notNeedFilter){
  9610. var me = this,
  9611. range,
  9612. div;
  9613. if(!html){
  9614. return;
  9615. }
  9616. if(me.fireEvent('beforeinserthtml',html) === true){
  9617. return;
  9618. }
  9619. range = me.selection.getRange();
  9620. div = range.document.createElement( 'div' );
  9621. div.style.display = 'inline';
  9622. if (!notNeedFilter) {
  9623. var root = UE.htmlparser(html);
  9624. //如果给了过滤规则就先进行过滤
  9625. if(me.options.filterRules){
  9626. UE.filterNode(root,me.options.filterRules);
  9627. }
  9628. //执行默认的处理
  9629. me.filterInputRule(root);
  9630. html = root.toHtml()
  9631. }
  9632. div.innerHTML = utils.trim( html );
  9633. if ( !range.collapsed ) {
  9634. var tmpNode = range.startContainer;
  9635. if(domUtils.isFillChar(tmpNode)){
  9636. range.setStartBefore(tmpNode)
  9637. }
  9638. tmpNode = range.endContainer;
  9639. if(domUtils.isFillChar(tmpNode)){
  9640. range.setEndAfter(tmpNode)
  9641. }
  9642. range.txtToElmBoundary();
  9643. //结束边界可能放到了br的前边,要把br包含进来
  9644. // x[xxx]<br/>
  9645. if(range.endContainer && range.endContainer.nodeType == 1){
  9646. tmpNode = range.endContainer.childNodes[range.endOffset];
  9647. if(tmpNode && domUtils.isBr(tmpNode)){
  9648. range.setEndAfter(tmpNode);
  9649. }
  9650. }
  9651. if(range.startOffset == 0){
  9652. tmpNode = range.startContainer;
  9653. if(domUtils.isBoundaryNode(tmpNode,'firstChild') ){
  9654. tmpNode = range.endContainer;
  9655. if(range.endOffset == (tmpNode.nodeType == 3 ? tmpNode.nodeValue.length : tmpNode.childNodes.length) && domUtils.isBoundaryNode(tmpNode,'lastChild')){
  9656. me.body.innerHTML = '<p>'+(browser.ie ? '' : '<br/>')+'</p>';
  9657. range.setStart(me.body.firstChild,0).collapse(true)
  9658. }
  9659. }
  9660. }
  9661. !range.collapsed && range.deleteContents();
  9662. if(range.startContainer.nodeType == 1){
  9663. var child = range.startContainer.childNodes[range.startOffset],pre;
  9664. if(child && domUtils.isBlockElm(child) && (pre = child.previousSibling) && domUtils.isBlockElm(pre)){
  9665. range.setEnd(pre,pre.childNodes.length).collapse();
  9666. while(child.firstChild){
  9667. pre.appendChild(child.firstChild);
  9668. }
  9669. domUtils.remove(child);
  9670. }
  9671. }
  9672. }
  9673. var child,parent,pre,tmp,hadBreak = 0, nextNode;
  9674. //如果当前位置选中了fillchar要干掉,要不会产生空行
  9675. if(range.inFillChar()){
  9676. child = range.startContainer;
  9677. if(domUtils.isFillChar(child)){
  9678. range.setStartBefore(child).collapse(true);
  9679. domUtils.remove(child);
  9680. }else if(domUtils.isFillChar(child,true)){
  9681. child.nodeValue = child.nodeValue.replace(fillCharReg,'');
  9682. range.startOffset--;
  9683. range.collapsed && range.collapse(true)
  9684. }
  9685. }
  9686. //列表单独处理
  9687. var li = domUtils.findParentByTagName(range.startContainer,'li',true);
  9688. if(li){
  9689. var next,last;
  9690. while(child = div.firstChild){
  9691. //针对hr单独处理一下先
  9692. while(child && (child.nodeType == 3 || !domUtils.isBlockElm(child) || child.tagName=='HR' )){
  9693. next = child.nextSibling;
  9694. range.insertNode( child).collapse();
  9695. last = child;
  9696. child = next;
  9697. }
  9698. if(child){
  9699. if(/^(ol|ul)$/i.test(child.tagName)){
  9700. while(child.firstChild){
  9701. last = child.firstChild;
  9702. domUtils.insertAfter(li,child.firstChild);
  9703. li = li.nextSibling;
  9704. }
  9705. domUtils.remove(child)
  9706. }else{
  9707. var tmpLi;
  9708. next = child.nextSibling;
  9709. tmpLi = me.document.createElement('li');
  9710. domUtils.insertAfter(li,tmpLi);
  9711. tmpLi.appendChild(child);
  9712. last = child;
  9713. child = next;
  9714. li = tmpLi;
  9715. }
  9716. }
  9717. }
  9718. li = domUtils.findParentByTagName(range.startContainer,'li',true);
  9719. if(domUtils.isEmptyBlock(li)){
  9720. domUtils.remove(li)
  9721. }
  9722. if(last){
  9723. range.setStartAfter(last).collapse(true).select(true)
  9724. }
  9725. }else{
  9726. while ( child = div.firstChild ) {
  9727. if(hadBreak){
  9728. var p = me.document.createElement('p');
  9729. while(child && (child.nodeType == 3 || !dtd.$block[child.tagName])){
  9730. nextNode = child.nextSibling;
  9731. p.appendChild(child);
  9732. child = nextNode;
  9733. }
  9734. if(p.firstChild){
  9735. child = p
  9736. }
  9737. }
  9738. range.insertNode( child );
  9739. nextNode = child.nextSibling;
  9740. if ( !hadBreak && child.nodeType == domUtils.NODE_ELEMENT && domUtils.isBlockElm( child ) ){
  9741. parent = domUtils.findParent( child,function ( node ){ return domUtils.isBlockElm( node ); } );
  9742. if ( parent && parent.tagName.toLowerCase() != 'body' && !(dtd[parent.tagName][child.nodeName] && child.parentNode === parent)){
  9743. if(!dtd[parent.tagName][child.nodeName]){
  9744. pre = parent;
  9745. }else{
  9746. tmp = child.parentNode;
  9747. while (tmp !== parent){
  9748. pre = tmp;
  9749. tmp = tmp.parentNode;
  9750. }
  9751. }
  9752. domUtils.breakParent( child, pre || tmp );
  9753. //去掉break后前一个多余的节点 <p>|<[p> ==> <p></p><div></div><p>|</p>
  9754. var pre = child.previousSibling;
  9755. domUtils.trimWhiteTextNode(pre);
  9756. if(!pre.childNodes.length){
  9757. domUtils.remove(pre);
  9758. }
  9759. //trace:2012,在非ie的情况,切开后剩下的节点有可能不能点入光标添加br占位
  9760. if(!browser.ie &&
  9761. (next = child.nextSibling) &&
  9762. domUtils.isBlockElm(next) &&
  9763. next.lastChild &&
  9764. !domUtils.isBr(next.lastChild)){
  9765. next.appendChild(me.document.createElement('br'));
  9766. }
  9767. hadBreak = 1;
  9768. }
  9769. }
  9770. var next = child.nextSibling;
  9771. if(!div.firstChild && next && domUtils.isBlockElm(next)){
  9772. range.setStart(next,0).collapse(true);
  9773. break;
  9774. }
  9775. range.setEndAfter( child ).collapse();
  9776. }
  9777. child = range.startContainer;
  9778. if(nextNode && domUtils.isBr(nextNode)){
  9779. domUtils.remove(nextNode)
  9780. }
  9781. //用chrome可能有空白展位符
  9782. if(domUtils.isBlockElm(child) && domUtils.isEmptyNode(child)){
  9783. if(nextNode = child.nextSibling){
  9784. domUtils.remove(child);
  9785. if(nextNode.nodeType == 1 && dtd.$block[nextNode.tagName]){
  9786. range.setStart(nextNode,0).collapse(true).shrinkBoundary()
  9787. }
  9788. }else{
  9789. try{
  9790. child.innerHTML = browser.ie ? domUtils.fillChar : '<br/>';
  9791. }catch(e){
  9792. range.setStartBefore(child);
  9793. domUtils.remove(child)
  9794. }
  9795. }
  9796. }
  9797. //加上true因为在删除表情等时会删两次,第一次是删的fillData
  9798. try{
  9799. range.select(true);
  9800. }catch(e){}
  9801. }
  9802. setTimeout(function(){
  9803. range = me.selection.getRange();
  9804. range.scrollToView(me.autoHeightEnabled,me.autoHeightEnabled ? domUtils.getXY(me.iframe).y:0);
  9805. me.fireEvent('afterinserthtml', html);
  9806. },200);
  9807. }
  9808. };
  9809. // plugins/autotypeset.js
  9810. /**
  9811. * 自动排版
  9812. * @file
  9813. * @since 1.2.6.1
  9814. */
  9815. /**
  9816. * 对当前编辑器的内容执行自动排版, 排版的行为根据config配置文件里的“autotypeset”选项进行控制。
  9817. * @command autotypeset
  9818. * @method execCommand
  9819. * @param { String } cmd 命令字符串
  9820. * @example
  9821. * ```javascript
  9822. * editor.execCommand( 'autotypeset' );
  9823. * ```
  9824. */
  9825. UE.plugins['autotypeset'] = function(){
  9826. this.setOpt({'autotypeset': {
  9827. mergeEmptyline: true, //合并空行
  9828. removeClass: true, //去掉冗余的class
  9829. removeEmptyline: false, //去掉空行
  9830. textAlign:"left", //段落的排版方式,可以是 left,right,center,justify 去掉这个属性表示不执行排版
  9831. imageBlockLine: 'center', //图片的浮动方式,独占一行剧中,左右浮动,默认: center,left,right,none 去掉这个属性表示不执行排版
  9832. pasteFilter: false, //根据规则过滤没事粘贴进来的内容
  9833. clearFontSize: false, //去掉所有的内嵌字号,使用编辑器默认的字号
  9834. clearFontFamily: false, //去掉所有的内嵌字体,使用编辑器默认的字体
  9835. removeEmptyNode: false, // 去掉空节点
  9836. //可以去掉的标签
  9837. removeTagNames: utils.extend({div:1},dtd.$removeEmpty),
  9838. indent: false, // 行首缩进
  9839. indentValue : '2em', //行首缩进的大小
  9840. bdc2sb: false,
  9841. tobdc: false
  9842. }});
  9843. var me = this,
  9844. opt = me.options.autotypeset,
  9845. remainClass = {
  9846. 'selectTdClass':1,
  9847. 'pagebreak':1,
  9848. 'anchorclass':1
  9849. },
  9850. remainTag = {
  9851. 'li':1
  9852. },
  9853. tags = {
  9854. div:1,
  9855. p:1,
  9856. //trace:2183 这些也认为是行
  9857. blockquote:1,center:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,
  9858. span:1
  9859. },
  9860. highlightCont;
  9861. //升级了版本,但配置项目里没有autotypeset
  9862. if(!opt){
  9863. return;
  9864. }
  9865. readLocalOpts();
  9866. function isLine(node,notEmpty){
  9867. if(!node || node.nodeType == 3)
  9868. return 0;
  9869. if(domUtils.isBr(node))
  9870. return 1;
  9871. if(node && node.parentNode && tags[node.tagName.toLowerCase()]){
  9872. if(highlightCont && highlightCont.contains(node)
  9873. ||
  9874. node.getAttribute('pagebreak')
  9875. ){
  9876. return 0;
  9877. }
  9878. return notEmpty ? !domUtils.isEmptyBlock(node) : domUtils.isEmptyBlock(node,new RegExp('[\\s'+domUtils.fillChar
  9879. +']','g'));
  9880. }
  9881. }
  9882. function removeNotAttributeSpan(node){
  9883. if(!node.style.cssText){
  9884. domUtils.removeAttributes(node,['style']);
  9885. if(node.tagName.toLowerCase() == 'span' && domUtils.hasNoAttributes(node)){
  9886. domUtils.remove(node,true);
  9887. }
  9888. }
  9889. }
  9890. function autotype(type,html){
  9891. var me = this,cont;
  9892. if(html){
  9893. if(!opt.pasteFilter){
  9894. return;
  9895. }
  9896. cont = me.document.createElement('div');
  9897. cont.innerHTML = html.html;
  9898. }else{
  9899. cont = me.document.body;
  9900. }
  9901. var nodes = domUtils.getElementsByTagName(cont,'*');
  9902. // 行首缩进,段落方向,段间距,段内间距
  9903. for(var i=0,ci;ci=nodes[i++];){
  9904. if(me.fireEvent('excludeNodeinautotype',ci) === true){
  9905. continue;
  9906. }
  9907. //font-size
  9908. if(opt.clearFontSize && ci.style.fontSize){
  9909. domUtils.removeStyle(ci,'font-size');
  9910. removeNotAttributeSpan(ci);
  9911. }
  9912. //font-family
  9913. if(opt.clearFontFamily && ci.style.fontFamily){
  9914. domUtils.removeStyle(ci,'font-family');
  9915. removeNotAttributeSpan(ci);
  9916. }
  9917. if(isLine(ci)){
  9918. //合并空行
  9919. if(opt.mergeEmptyline ){
  9920. var next = ci.nextSibling,tmpNode,isBr = domUtils.isBr(ci);
  9921. while(isLine(next)){
  9922. tmpNode = next;
  9923. next = tmpNode.nextSibling;
  9924. if(isBr && (!next || next && !domUtils.isBr(next))){
  9925. break;
  9926. }
  9927. domUtils.remove(tmpNode);
  9928. }
  9929. }
  9930. //去掉空行,保留占位的空行
  9931. if(opt.removeEmptyline && domUtils.inDoc(ci,cont) && !remainTag[ci.parentNode.tagName.toLowerCase()] ){
  9932. if(domUtils.isBr(ci)){
  9933. next = ci.nextSibling;
  9934. if(next && !domUtils.isBr(next)){
  9935. continue;
  9936. }
  9937. }
  9938. domUtils.remove(ci);
  9939. continue;
  9940. }
  9941. }
  9942. if(isLine(ci,true) && ci.tagName != 'SPAN'){
  9943. if(opt.indent){
  9944. ci.style.textIndent = opt.indentValue;
  9945. }
  9946. if(opt.textAlign){
  9947. ci.style.textAlign = opt.textAlign;
  9948. }
  9949. // if(opt.lineHeight)
  9950. // ci.style.lineHeight = opt.lineHeight + 'cm';
  9951. }
  9952. //去掉class,保留的class不去掉
  9953. if(opt.removeClass && ci.className && !remainClass[ci.className.toLowerCase()]){
  9954. if(highlightCont && highlightCont.contains(ci)){
  9955. continue;
  9956. }
  9957. domUtils.removeAttributes(ci,['class']);
  9958. }
  9959. //表情不处理
  9960. if(opt.imageBlockLine && ci.tagName.toLowerCase() == 'img' && !ci.getAttribute('emotion')){
  9961. if(html){
  9962. var img = ci;
  9963. switch (opt.imageBlockLine){
  9964. case 'left':
  9965. case 'right':
  9966. case 'none':
  9967. var pN = img.parentNode,tmpNode,pre,next;
  9968. while(dtd.$inline[pN.tagName] || pN.tagName == 'A'){
  9969. pN = pN.parentNode;
  9970. }
  9971. tmpNode = pN;
  9972. if(tmpNode.tagName == 'P' && domUtils.getStyle(tmpNode,'text-align') == 'center'){
  9973. if(!domUtils.isBody(tmpNode) && domUtils.getChildCount(tmpNode,function(node){return !domUtils.isBr(node) && !domUtils.isWhitespace(node)}) == 1){
  9974. pre = tmpNode.previousSibling;
  9975. next = tmpNode.nextSibling;
  9976. if(pre && next && pre.nodeType == 1 && next.nodeType == 1 && pre.tagName == next.tagName && domUtils.isBlockElm(pre)){
  9977. pre.appendChild(tmpNode.firstChild);
  9978. while(next.firstChild){
  9979. pre.appendChild(next.firstChild);
  9980. }
  9981. domUtils.remove(tmpNode);
  9982. domUtils.remove(next);
  9983. }else{
  9984. domUtils.setStyle(tmpNode,'text-align','');
  9985. }
  9986. }
  9987. }
  9988. domUtils.setStyle(img,'float', opt.imageBlockLine);
  9989. break;
  9990. case 'center':
  9991. if(me.queryCommandValue('imagefloat') != 'center'){
  9992. pN = img.parentNode;
  9993. domUtils.setStyle(img,'float','none');
  9994. tmpNode = img;
  9995. while(pN && domUtils.getChildCount(pN,function(node){return !domUtils.isBr(node) && !domUtils.isWhitespace(node)}) == 1
  9996. && (dtd.$inline[pN.tagName] || pN.tagName == 'A')){
  9997. tmpNode = pN;
  9998. pN = pN.parentNode;
  9999. }
  10000. var pNode = me.document.createElement('p');
  10001. domUtils.setAttributes(pNode,{
  10002. style:'text-align:center'
  10003. });
  10004. tmpNode.parentNode.insertBefore(pNode,tmpNode);
  10005. pNode.appendChild(tmpNode);
  10006. domUtils.setStyle(tmpNode,'float','');
  10007. }
  10008. }
  10009. } else {
  10010. var range = me.selection.getRange();
  10011. range.selectNode(ci).select();
  10012. me.execCommand('imagefloat', opt.imageBlockLine);
  10013. }
  10014. }
  10015. //去掉冗余的标签
  10016. if(opt.removeEmptyNode){
  10017. if(opt.removeTagNames[ci.tagName.toLowerCase()] && domUtils.hasNoAttributes(ci) && domUtils.isEmptyBlock(ci)){
  10018. domUtils.remove(ci);
  10019. }
  10020. }
  10021. }
  10022. if(opt.tobdc){
  10023. var root = UE.htmlparser(cont.innerHTML);
  10024. root.traversal(function(node){
  10025. if(node.type == 'text'){
  10026. node.data = ToDBC(node.data)
  10027. }
  10028. });
  10029. cont.innerHTML = root.toHtml()
  10030. }
  10031. if(opt.bdc2sb){
  10032. var root = UE.htmlparser(cont.innerHTML);
  10033. root.traversal(function(node){
  10034. if(node.type == 'text'){
  10035. node.data = DBC2SB(node.data)
  10036. }
  10037. });
  10038. cont.innerHTML = root.toHtml()
  10039. }
  10040. if(html){
  10041. html.html = cont.innerHTML;
  10042. }
  10043. }
  10044. if(opt.pasteFilter){
  10045. me.addListener('beforepaste',autotype);
  10046. }
  10047. function DBC2SB(str) {
  10048. var result = '';
  10049. for (var i = 0; i < str.length; i++) {
  10050. var code = str.charCodeAt(i); //获取当前字符的unicode编码
  10051. if (code >= 65281 && code <= 65373)//在这个unicode编码范围中的是所有的英文字母已经各种字符
  10052. {
  10053. result += String.fromCharCode(str.charCodeAt(i) - 65248); //把全角字符的unicode编码转换为对应半角字符的unicode码
  10054. } else if (code == 12288)//空格
  10055. {
  10056. result += String.fromCharCode(str.charCodeAt(i) - 12288 + 32);
  10057. } else {
  10058. result += str.charAt(i);
  10059. }
  10060. }
  10061. return result;
  10062. }
  10063. function ToDBC(txtstring) {
  10064. txtstring = utils.html(txtstring);
  10065. var tmp = "";
  10066. var mark = "";/*用于判断,如果是html尖括里的标记,则不进行全角的转换*/
  10067. for (var i = 0; i < txtstring.length; i++) {
  10068. if (txtstring.charCodeAt(i) == 32) {
  10069. tmp = tmp + String.fromCharCode(12288);
  10070. }
  10071. else if (txtstring.charCodeAt(i) < 127) {
  10072. tmp = tmp + String.fromCharCode(txtstring.charCodeAt(i) + 65248);
  10073. }
  10074. else {
  10075. tmp += txtstring.charAt(i);
  10076. }
  10077. }
  10078. return tmp;
  10079. }
  10080. function readLocalOpts() {
  10081. var cookieOpt = me.getPreferences('autotypeset');
  10082. utils.extend(me.options.autotypeset, cookieOpt);
  10083. }
  10084. me.commands['autotypeset'] = {
  10085. execCommand:function () {
  10086. me.removeListener('beforepaste',autotype);
  10087. if(opt.pasteFilter){
  10088. me.addListener('beforepaste',autotype);
  10089. }
  10090. autotype.call(me)
  10091. }
  10092. };
  10093. };
  10094. // plugins/autosubmit.js
  10095. /**
  10096. * 快捷键提交
  10097. * @file
  10098. * @since 1.2.6.1
  10099. */
  10100. /**
  10101. * 提交表单
  10102. * @command autosubmit
  10103. * @method execCommand
  10104. * @param { String } cmd 命令字符串
  10105. * @example
  10106. * ```javascript
  10107. * editor.execCommand( 'autosubmit' );
  10108. * ```
  10109. */
  10110. UE.plugin.register('autosubmit',function(){
  10111. return {
  10112. shortcutkey:{
  10113. "autosubmit":"ctrl+13" //手动提交
  10114. },
  10115. commands:{
  10116. 'autosubmit':{
  10117. execCommand:function () {
  10118. var me=this,
  10119. form = domUtils.findParentByTagName(me.iframe,"form", false);
  10120. if (form){
  10121. if(me.fireEvent("beforesubmit")===false){
  10122. return;
  10123. }
  10124. me.sync();
  10125. form.submit();
  10126. }
  10127. }
  10128. }
  10129. }
  10130. }
  10131. });
  10132. // plugins/background.js
  10133. /**
  10134. * 背景插件,为UEditor提供设置背景功能
  10135. * @file
  10136. * @since 1.2.6.1
  10137. */
  10138. UE.plugin.register('background', function () {
  10139. var me = this,
  10140. cssRuleId = 'editor_background',
  10141. isSetColored,
  10142. reg = new RegExp('body[\\s]*\\{(.+)\\}', 'i');
  10143. function stringToObj(str) {
  10144. var obj = {}, styles = str.split(';');
  10145. utils.each(styles, function (v) {
  10146. var index = v.indexOf(':'),
  10147. key = utils.trim(v.substr(0, index)).toLowerCase();
  10148. key && (obj[key] = utils.trim(v.substr(index + 1) || ''));
  10149. });
  10150. return obj;
  10151. }
  10152. function setBackground(obj) {
  10153. if (obj) {
  10154. var styles = [];
  10155. for (var name in obj) {
  10156. if (obj.hasOwnProperty(name)) {
  10157. styles.push(name + ":" + obj[name] + '; ');
  10158. }
  10159. }
  10160. utils.cssRule(cssRuleId, styles.length ? ('body{' + styles.join("") + '}') : '', me.document);
  10161. } else {
  10162. utils.cssRule(cssRuleId, '', me.document)
  10163. }
  10164. }
  10165. //重写editor.hasContent方法
  10166. var orgFn = me.hasContents;
  10167. me.hasContents = function(){
  10168. if(me.queryCommandValue('background')){
  10169. return true
  10170. }
  10171. return orgFn.apply(me,arguments);
  10172. };
  10173. return {
  10174. bindEvents: {
  10175. 'getAllHtml': function (type, headHtml) {
  10176. var body = this.body,
  10177. su = domUtils.getComputedStyle(body, "background-image"),
  10178. url = "";
  10179. if (su.indexOf(me.options.imagePath) > 0) {
  10180. url = su.substring(su.indexOf(me.options.imagePath), su.length - 1).replace(/"|\(|\)/ig, "");
  10181. } else {
  10182. url = su != "none" ? su.replace(/url\("?|"?\)/ig, "") : "";
  10183. }
  10184. var html = '<style type="text/css">body{';
  10185. var bgObj = {
  10186. "background-color": domUtils.getComputedStyle(body, "background-color") || "#ffffff",
  10187. 'background-image': url ? 'url(' + url + ')' : '',
  10188. 'background-repeat': domUtils.getComputedStyle(body, "background-repeat") || "",
  10189. 'background-position': browser.ie ? (domUtils.getComputedStyle(body, "background-position-x") + " " + domUtils.getComputedStyle(body, "background-position-y")) : domUtils.getComputedStyle(body, "background-position"),
  10190. 'height': domUtils.getComputedStyle(body, "height")
  10191. };
  10192. for (var name in bgObj) {
  10193. if (bgObj.hasOwnProperty(name)) {
  10194. html += name + ":" + bgObj[name] + "; ";
  10195. }
  10196. }
  10197. html += '}</style> ';
  10198. headHtml.push(html);
  10199. },
  10200. 'aftersetcontent': function () {
  10201. if(isSetColored == false) setBackground();
  10202. }
  10203. },
  10204. inputRule: function (root) {
  10205. isSetColored = false;
  10206. utils.each(root.getNodesByTagName('p'), function (p) {
  10207. var styles = p.getAttr('data-background');
  10208. if (styles) {
  10209. isSetColored = true;
  10210. setBackground(stringToObj(styles));
  10211. p.parentNode.removeChild(p);
  10212. }
  10213. })
  10214. },
  10215. outputRule: function (root) {
  10216. var me = this,
  10217. styles = (utils.cssRule(cssRuleId, me.document) || '').replace(/[\n\r]+/g, '').match(reg);
  10218. if (styles) {
  10219. root.appendChild(UE.uNode.createElement('<p style="display:none;" data-background="' + utils.trim(styles[1].replace(/"/g, '').replace(/[\s]+/g, ' ')) + '"><br/></p>'));
  10220. }
  10221. },
  10222. commands: {
  10223. 'background': {
  10224. execCommand: function (cmd, obj) {
  10225. setBackground(obj);
  10226. },
  10227. queryCommandValue: function () {
  10228. var me = this,
  10229. styles = (utils.cssRule(cssRuleId, me.document) || '').replace(/[\n\r]+/g, '').match(reg);
  10230. return styles ? stringToObj(styles[1]) : null;
  10231. },
  10232. notNeedUndo: true
  10233. }
  10234. }
  10235. }
  10236. });
  10237. // plugins/image.js
  10238. /**
  10239. * 图片插入、排版插件
  10240. * @file
  10241. * @since 1.2.6.1
  10242. */
  10243. /**
  10244. * 图片对齐方式
  10245. * @command imagefloat
  10246. * @method execCommand
  10247. * @remind 值center为独占一行居中
  10248. * @param { String } cmd 命令字符串
  10249. * @param { String } align 对齐方式,可传left、right、none、center
  10250. * @remaind center表示图片独占一行
  10251. * @example
  10252. * ```javascript
  10253. * editor.execCommand( 'imagefloat', 'center' );
  10254. * ```
  10255. */
  10256. /**
  10257. * 如果选区所在位置是图片区域
  10258. * @command imagefloat
  10259. * @method queryCommandValue
  10260. * @param { String } cmd 命令字符串
  10261. * @return { String } 返回图片对齐方式
  10262. * @example
  10263. * ```javascript
  10264. * editor.queryCommandValue( 'imagefloat' );
  10265. * ```
  10266. */
  10267. UE.commands['imagefloat'] = {
  10268. execCommand:function (cmd, align) {
  10269. var me = this,
  10270. range = me.selection.getRange();
  10271. if (!range.collapsed) {
  10272. var img = range.getClosedNode();
  10273. if (img && img.tagName == 'IMG') {
  10274. switch (align) {
  10275. case 'left':
  10276. case 'right':
  10277. case 'none':
  10278. var pN = img.parentNode, tmpNode, pre, next;
  10279. while (dtd.$inline[pN.tagName] || pN.tagName == 'A') {
  10280. pN = pN.parentNode;
  10281. }
  10282. tmpNode = pN;
  10283. if (tmpNode.tagName == 'P' && domUtils.getStyle(tmpNode, 'text-align') == 'center') {
  10284. if (!domUtils.isBody(tmpNode) && domUtils.getChildCount(tmpNode, function (node) {
  10285. return !domUtils.isBr(node) && !domUtils.isWhitespace(node);
  10286. }) == 1) {
  10287. pre = tmpNode.previousSibling;
  10288. next = tmpNode.nextSibling;
  10289. if (pre && next && pre.nodeType == 1 && next.nodeType == 1 && pre.tagName == next.tagName && domUtils.isBlockElm(pre)) {
  10290. pre.appendChild(tmpNode.firstChild);
  10291. while (next.firstChild) {
  10292. pre.appendChild(next.firstChild);
  10293. }
  10294. domUtils.remove(tmpNode);
  10295. domUtils.remove(next);
  10296. } else {
  10297. domUtils.setStyle(tmpNode, 'text-align', '');
  10298. }
  10299. }
  10300. range.selectNode(img).select();
  10301. }
  10302. domUtils.setStyle(img, 'float', align == 'none' ? '' : align);
  10303. if(align == 'none'){
  10304. domUtils.removeAttributes(img,'align');
  10305. }
  10306. break;
  10307. case 'center':
  10308. if (me.queryCommandValue('imagefloat') != 'center') {
  10309. pN = img.parentNode;
  10310. domUtils.setStyle(img, 'float', '');
  10311. domUtils.removeAttributes(img,'align');
  10312. tmpNode = img;
  10313. while (pN && domUtils.getChildCount(pN, function (node) {
  10314. return !domUtils.isBr(node) && !domUtils.isWhitespace(node);
  10315. }) == 1
  10316. && (dtd.$inline[pN.tagName] || pN.tagName == 'A')) {
  10317. tmpNode = pN;
  10318. pN = pN.parentNode;
  10319. }
  10320. range.setStartBefore(tmpNode).setCursor(false);
  10321. pN = me.document.createElement('div');
  10322. pN.appendChild(tmpNode);
  10323. domUtils.setStyle(tmpNode, 'float', '');
  10324. me.execCommand('insertHtml', '<p id="_img_parent_tmp" style="text-align:center">' + pN.innerHTML + '</p>');
  10325. tmpNode = me.document.getElementById('_img_parent_tmp');
  10326. tmpNode.removeAttribute('id');
  10327. tmpNode = tmpNode.firstChild;
  10328. range.selectNode(tmpNode).select();
  10329. //去掉后边多余的元素
  10330. next = tmpNode.parentNode.nextSibling;
  10331. if (next && domUtils.isEmptyNode(next)) {
  10332. domUtils.remove(next);
  10333. }
  10334. }
  10335. break;
  10336. }
  10337. }
  10338. }
  10339. },
  10340. queryCommandValue:function () {
  10341. var range = this.selection.getRange(),
  10342. startNode, floatStyle;
  10343. if (range.collapsed) {
  10344. return 'none';
  10345. }
  10346. startNode = range.getClosedNode();
  10347. if (startNode && startNode.nodeType == 1 && startNode.tagName == 'IMG') {
  10348. floatStyle = domUtils.getComputedStyle(startNode, 'float') || startNode.getAttribute('align');
  10349. if (floatStyle == 'none') {
  10350. floatStyle = domUtils.getComputedStyle(startNode.parentNode, 'text-align') == 'center' ? 'center' : floatStyle;
  10351. }
  10352. return {
  10353. left:1,
  10354. right:1,
  10355. center:1
  10356. }[floatStyle] ? floatStyle : 'none';
  10357. }
  10358. return 'none';
  10359. },
  10360. queryCommandState:function () {
  10361. var range = this.selection.getRange(),
  10362. startNode;
  10363. if (range.collapsed) return -1;
  10364. startNode = range.getClosedNode();
  10365. if (startNode && startNode.nodeType == 1 && startNode.tagName == 'IMG') {
  10366. return 0;
  10367. }
  10368. return -1;
  10369. }
  10370. };
  10371. /**
  10372. * 插入图片
  10373. * @command insertimage
  10374. * @method execCommand
  10375. * @param { String } cmd 命令字符串
  10376. * @param { Object } opt 属性键值对,这些属性都将被复制到当前插入图片
  10377. * @remind 该命令第二个参数可接受一个图片配置项对象的数组,可以插入多张图片,
  10378. * 此时数组的每一个元素都是一个Object类型的图片属性集合。
  10379. * @example
  10380. * ```javascript
  10381. * editor.execCommand( 'insertimage', {
  10382. * src:'a/b/c.jpg',
  10383. * width:'100',
  10384. * height:'100'
  10385. * } );
  10386. * ```
  10387. * @example
  10388. * ```javascript
  10389. * editor.execCommand( 'insertimage', [{
  10390. * src:'a/b/c.jpg',
  10391. * width:'100',
  10392. * height:'100'
  10393. * },{
  10394. * src:'a/b/d.jpg',
  10395. * width:'100',
  10396. * height:'100'
  10397. * }] );
  10398. * ```
  10399. */
  10400. UE.commands['insertimage'] = {
  10401. execCommand:function (cmd, opt) {
  10402. opt = utils.isArray(opt) ? opt : [opt];
  10403. if (!opt.length) {
  10404. return;
  10405. }
  10406. var me = this,
  10407. range = me.selection.getRange(),
  10408. img = range.getClosedNode();
  10409. if(me.fireEvent('beforeinsertimage', opt) === true){
  10410. return;
  10411. }
  10412. function unhtmlData(imgCi) {
  10413. utils.each('width,height,border,hspace,vspace'.split(','), function (item) {
  10414. if (imgCi[item]) {
  10415. imgCi[item] = parseInt(imgCi[item], 10) || 0;
  10416. }
  10417. });
  10418. utils.each('src,_src'.split(','), function (item) {
  10419. if (imgCi[item]) {
  10420. imgCi[item] = utils.unhtmlForUrl(imgCi[item]);
  10421. }
  10422. });
  10423. utils.each('title,alt'.split(','), function (item) {
  10424. if (imgCi[item]) {
  10425. imgCi[item] = utils.unhtml(imgCi[item]);
  10426. }
  10427. });
  10428. }
  10429. if (img && /img/i.test(img.tagName) && (img.className != "edui-faked-video" || img.className.indexOf("edui-upload-video")!=-1) && !img.getAttribute("word_img")) {
  10430. var first = opt.shift();
  10431. var floatStyle = first['floatStyle'];
  10432. delete first['floatStyle'];
  10433. //// img.style.border = (first.border||0) +"px solid #000";
  10434. //// img.style.margin = (first.margin||0) +"px";
  10435. // img.style.cssText += ';margin:' + (first.margin||0) +"px;" + 'border:' + (first.border||0) +"px solid #000";
  10436. domUtils.setAttributes(img, first);
  10437. me.execCommand('imagefloat', floatStyle);
  10438. if (opt.length > 0) {
  10439. range.setStartAfter(img).setCursor(false, true);
  10440. me.execCommand('insertimage', opt);
  10441. }
  10442. } else {
  10443. var html = [], str = '', ci;
  10444. ci = opt[0];
  10445. if (opt.length == 1) {
  10446. unhtmlData(ci);
  10447. str = '<img src="' + ci.src + '" ' + (ci._src ? ' _src="' + ci._src + '" ' : '') +
  10448. (ci.width ? 'width="' + ci.width + '" ' : '') +
  10449. (ci.height ? ' height="' + ci.height + '" ' : '') +
  10450. (ci['floatStyle'] == 'left' || ci['floatStyle'] == 'right' ? ' style="float:' + ci['floatStyle'] + ';"' : '') +
  10451. (ci.title && ci.title != "" ? ' title="' + ci.title + '"' : '') +
  10452. (ci.border && ci.border != "0" ? ' border="' + ci.border + '"' : '') +
  10453. (ci.alt && ci.alt != "" ? ' alt="' + ci.alt + '"' : '') +
  10454. (ci.hspace && ci.hspace != "0" ? ' hspace = "' + ci.hspace + '"' : '') +
  10455. (ci.vspace && ci.vspace != "0" ? ' vspace = "' + ci.vspace + '"' : '') + '/>';
  10456. if (ci['floatStyle'] == 'center') {
  10457. str = '<p style="text-align: center">' + str + '</p>';
  10458. }
  10459. html.push(str);
  10460. } else {
  10461. for (var i = 0; ci = opt[i++];) {
  10462. unhtmlData(ci);
  10463. str = '<p ' + (ci['floatStyle'] == 'center' ? 'style="text-align: center" ' : '') + '><img src="' + ci.src + '" ' +
  10464. (ci.width ? 'width="' + ci.width + '" ' : '') + (ci._src ? ' _src="' + ci._src + '" ' : '') +
  10465. (ci.height ? ' height="' + ci.height + '" ' : '') +
  10466. ' style="' + (ci['floatStyle'] && ci['floatStyle'] != 'center' ? 'float:' + ci['floatStyle'] + ';' : '') +
  10467. (ci.border || '') + '" ' +
  10468. (ci.title ? ' title="' + ci.title + '"' : '') + ' /></p>';
  10469. html.push(str);
  10470. }
  10471. }
  10472. me.execCommand('insertHtml', html.join(''));
  10473. }
  10474. me.fireEvent('afterinsertimage', opt)
  10475. }
  10476. };
  10477. // plugins/justify.js
  10478. /**
  10479. * 段落格式
  10480. * @file
  10481. * @since 1.2.6.1
  10482. */
  10483. /**
  10484. * 段落对齐方式
  10485. * @command justify
  10486. * @method execCommand
  10487. * @param { String } cmd 命令字符串
  10488. * @param { String } align 对齐方式:left => 居左,right => 居右,center => 居中,justify => 两端对齐
  10489. * @example
  10490. * ```javascript
  10491. * editor.execCommand( 'justify', 'center' );
  10492. * ```
  10493. */
  10494. /**
  10495. * 如果选区所在位置是段落区域,返回当前段落对齐方式
  10496. * @command justify
  10497. * @method queryCommandValue
  10498. * @param { String } cmd 命令字符串
  10499. * @return { String } 返回段落对齐方式
  10500. * @example
  10501. * ```javascript
  10502. * editor.queryCommandValue( 'justify' );
  10503. * ```
  10504. */
  10505. UE.plugins['justify']=function(){
  10506. var me=this,
  10507. block = domUtils.isBlockElm,
  10508. defaultValue = {
  10509. left:1,
  10510. right:1,
  10511. center:1,
  10512. justify:1
  10513. },
  10514. doJustify = function (range, style) {
  10515. var bookmark = range.createBookmark(),
  10516. filterFn = function (node) {
  10517. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' && !domUtils.isBookmarkNode(node) : !domUtils.isWhitespace(node);
  10518. };
  10519. range.enlarge(true);
  10520. var bookmark2 = range.createBookmark(),
  10521. current = domUtils.getNextDomNode(bookmark2.start, false, filterFn),
  10522. tmpRange = range.cloneRange(),
  10523. tmpNode;
  10524. while (current && !(domUtils.getPosition(current, bookmark2.end) & domUtils.POSITION_FOLLOWING)) {
  10525. if (current.nodeType == 3 || !block(current)) {
  10526. tmpRange.setStartBefore(current);
  10527. while (current && current !== bookmark2.end && !block(current)) {
  10528. tmpNode = current;
  10529. current = domUtils.getNextDomNode(current, false, null, function (node) {
  10530. return !block(node);
  10531. });
  10532. }
  10533. tmpRange.setEndAfter(tmpNode);
  10534. var common = tmpRange.getCommonAncestor();
  10535. if (!domUtils.isBody(common) && block(common)) {
  10536. domUtils.setStyles(common, utils.isString(style) ? {'text-align':style} : style);
  10537. current = common;
  10538. } else {
  10539. var p = range.document.createElement('p');
  10540. domUtils.setStyles(p, utils.isString(style) ? {'text-align':style} : style);
  10541. var frag = tmpRange.extractContents();
  10542. p.appendChild(frag);
  10543. tmpRange.insertNode(p);
  10544. current = p;
  10545. }
  10546. current = domUtils.getNextDomNode(current, false, filterFn);
  10547. } else {
  10548. current = domUtils.getNextDomNode(current, true, filterFn);
  10549. }
  10550. }
  10551. return range.moveToBookmark(bookmark2).moveToBookmark(bookmark);
  10552. };
  10553. UE.commands['justify'] = {
  10554. execCommand:function (cmdName, align) {
  10555. var range = this.selection.getRange(),
  10556. txt;
  10557. //闭合时单独处理
  10558. if (range.collapsed) {
  10559. txt = this.document.createTextNode('p');
  10560. range.insertNode(txt);
  10561. }
  10562. doJustify(range, align);
  10563. if (txt) {
  10564. range.setStartBefore(txt).collapse(true);
  10565. domUtils.remove(txt);
  10566. }
  10567. range.select();
  10568. return true;
  10569. },
  10570. queryCommandValue:function () {
  10571. var startNode = this.selection.getStart(),
  10572. value = domUtils.getComputedStyle(startNode, 'text-align');
  10573. return defaultValue[value] ? value : 'left';
  10574. },
  10575. queryCommandState:function () {
  10576. var start = this.selection.getStart(),
  10577. cell = start && domUtils.findParentByTagName(start, ["td", "th","caption"], true);
  10578. return cell? -1:0;
  10579. }
  10580. };
  10581. };
  10582. // plugins/font.js
  10583. /**
  10584. * 字体颜色,背景色,字号,字体,下划线,删除线
  10585. * @file
  10586. * @since 1.2.6.1
  10587. */
  10588. /**
  10589. * 字体颜色
  10590. * @command forecolor
  10591. * @method execCommand
  10592. * @param { String } cmd 命令字符串
  10593. * @param { String } value 色值(必须十六进制)
  10594. * @example
  10595. * ```javascript
  10596. * editor.execCommand( 'forecolor', '#000' );
  10597. * ```
  10598. */
  10599. /**
  10600. * 返回选区字体颜色
  10601. * @command forecolor
  10602. * @method queryCommandValue
  10603. * @param { String } cmd 命令字符串
  10604. * @return { String } 返回字体颜色
  10605. * @example
  10606. * ```javascript
  10607. * editor.queryCommandValue( 'forecolor' );
  10608. * ```
  10609. */
  10610. /**
  10611. * 字体背景颜色
  10612. * @command backcolor
  10613. * @method execCommand
  10614. * @param { String } cmd 命令字符串
  10615. * @param { String } value 色值(必须十六进制)
  10616. * @example
  10617. * ```javascript
  10618. * editor.execCommand( 'backcolor', '#000' );
  10619. * ```
  10620. */
  10621. /**
  10622. * 返回选区字体颜色
  10623. * @command backcolor
  10624. * @method queryCommandValue
  10625. * @param { String } cmd 命令字符串
  10626. * @return { String } 返回字体背景颜色
  10627. * @example
  10628. * ```javascript
  10629. * editor.queryCommandValue( 'backcolor' );
  10630. * ```
  10631. */
  10632. /**
  10633. * 字体大小
  10634. * @command fontsize
  10635. * @method execCommand
  10636. * @param { String } cmd 命令字符串
  10637. * @param { String } value 字体大小
  10638. * @example
  10639. * ```javascript
  10640. * editor.execCommand( 'fontsize', '14px' );
  10641. * ```
  10642. */
  10643. /**
  10644. * 返回选区字体大小
  10645. * @command fontsize
  10646. * @method queryCommandValue
  10647. * @param { String } cmd 命令字符串
  10648. * @return { String } 返回字体大小
  10649. * @example
  10650. * ```javascript
  10651. * editor.queryCommandValue( 'fontsize' );
  10652. * ```
  10653. */
  10654. /**
  10655. * 字体样式
  10656. * @command fontfamily
  10657. * @method execCommand
  10658. * @param { String } cmd 命令字符串
  10659. * @param { String } value 字体样式
  10660. * @example
  10661. * ```javascript
  10662. * editor.execCommand( 'fontfamily', '微软雅黑' );
  10663. * ```
  10664. */
  10665. /**
  10666. * 返回选区字体样式
  10667. * @command fontfamily
  10668. * @method queryCommandValue
  10669. * @param { String } cmd 命令字符串
  10670. * @return { String } 返回字体样式
  10671. * @example
  10672. * ```javascript
  10673. * editor.queryCommandValue( 'fontfamily' );
  10674. * ```
  10675. */
  10676. /**
  10677. * 字体下划线,与删除线互斥
  10678. * @command underline
  10679. * @method execCommand
  10680. * @param { String } cmd 命令字符串
  10681. * @example
  10682. * ```javascript
  10683. * editor.execCommand( 'underline' );
  10684. * ```
  10685. */
  10686. /**
  10687. * 字体删除线,与下划线互斥
  10688. * @command strikethrough
  10689. * @method execCommand
  10690. * @param { String } cmd 命令字符串
  10691. * @example
  10692. * ```javascript
  10693. * editor.execCommand( 'strikethrough' );
  10694. * ```
  10695. */
  10696. /**
  10697. * 字体边框
  10698. * @command fontborder
  10699. * @method execCommand
  10700. * @param { String } cmd 命令字符串
  10701. * @example
  10702. * ```javascript
  10703. * editor.execCommand( 'fontborder' );
  10704. * ```
  10705. */
  10706. UE.plugins['font'] = function () {
  10707. var me = this,
  10708. fonts = {
  10709. 'forecolor': 'color',
  10710. 'backcolor': 'background-color',
  10711. 'fontsize': 'font-size',
  10712. 'fontfamily': 'font-family',
  10713. 'underline': 'text-decoration',
  10714. 'strikethrough': 'text-decoration',
  10715. 'fontborder': 'border'
  10716. },
  10717. needCmd = {'underline': 1, 'strikethrough': 1, 'fontborder': 1},
  10718. needSetChild = {
  10719. 'forecolor': 'color',
  10720. 'backcolor': 'background-color',
  10721. 'fontsize': 'font-size',
  10722. 'fontfamily': 'font-family'
  10723. };
  10724. me.setOpt({
  10725. 'fontfamily': [
  10726. { name: 'songti', val: '宋体,SimSun'},
  10727. { name: 'yahei', val: '微软雅黑,Microsoft YaHei'},
  10728. { name: 'kaiti', val: '楷体,楷体_GB2312, SimKai'},
  10729. { name: 'heiti', val: '黑体, SimHei'},
  10730. { name: 'lishu', val: '隶书, SimLi'},
  10731. { name: 'andaleMono', val: 'andale mono'},
  10732. { name: 'arial', val: 'arial, helvetica,sans-serif'},
  10733. { name: 'arialBlack', val: 'arial black,avant garde'},
  10734. { name: 'comicSansMs', val: 'comic sans ms'},
  10735. { name: 'impact', val: 'impact,chicago'},
  10736. { name: 'timesNewRoman', val: 'times new roman'}
  10737. ],
  10738. 'fontsize': [10, 11, 12, 14, 16, 18, 20, 24, 36]
  10739. });
  10740. function mergeWithParent(node){
  10741. var parent;
  10742. while(parent = node.parentNode){
  10743. if(parent.tagName == 'SPAN' && domUtils.getChildCount(parent,function(child){
  10744. return !domUtils.isBookmarkNode(child) && !domUtils.isBr(child)
  10745. }) == 1) {
  10746. parent.style.cssText += node.style.cssText;
  10747. domUtils.remove(node,true);
  10748. node = parent;
  10749. }else{
  10750. break;
  10751. }
  10752. }
  10753. }
  10754. function mergeChild(rng,cmdName,value){
  10755. if(needSetChild[cmdName]){
  10756. rng.adjustmentBoundary();
  10757. if(!rng.collapsed && rng.startContainer.nodeType == 1){
  10758. var start = rng.startContainer.childNodes[rng.startOffset];
  10759. if(start && domUtils.isTagNode(start,'span')){
  10760. var bk = rng.createBookmark();
  10761. utils.each(domUtils.getElementsByTagName(start, 'span'), function (span) {
  10762. if (!span.parentNode || domUtils.isBookmarkNode(span))return;
  10763. if(cmdName == 'backcolor' && domUtils.getComputedStyle(span,'background-color').toLowerCase() === value){
  10764. return;
  10765. }
  10766. domUtils.removeStyle(span,needSetChild[cmdName]);
  10767. if(span.style.cssText.replace(/^\s+$/,'').length == 0){
  10768. domUtils.remove(span,true)
  10769. }
  10770. });
  10771. rng.moveToBookmark(bk)
  10772. }
  10773. }
  10774. }
  10775. }
  10776. function mergesibling(rng,cmdName,value) {
  10777. var collapsed = rng.collapsed,
  10778. bk = rng.createBookmark(), common;
  10779. if (collapsed) {
  10780. common = bk.start.parentNode;
  10781. while (dtd.$inline[common.tagName]) {
  10782. common = common.parentNode;
  10783. }
  10784. } else {
  10785. common = domUtils.getCommonAncestor(bk.start, bk.end);
  10786. }
  10787. utils.each(domUtils.getElementsByTagName(common, 'span'), function (span) {
  10788. if (!span.parentNode || domUtils.isBookmarkNode(span))return;
  10789. if (/\s*border\s*:\s*none;?\s*/i.test(span.style.cssText)) {
  10790. if(/^\s*border\s*:\s*none;?\s*$/.test(span.style.cssText)){
  10791. domUtils.remove(span, true);
  10792. }else{
  10793. domUtils.removeStyle(span,'border');
  10794. }
  10795. return
  10796. }
  10797. if (/border/i.test(span.style.cssText) && span.parentNode.tagName == 'SPAN' && /border/i.test(span.parentNode.style.cssText)) {
  10798. span.style.cssText = span.style.cssText.replace(/border[^:]*:[^;]+;?/gi, '');
  10799. }
  10800. if(!(cmdName=='fontborder' && value=='none')){
  10801. var next = span.nextSibling;
  10802. while (next && next.nodeType == 1 && next.tagName == 'SPAN' ) {
  10803. if(domUtils.isBookmarkNode(next) && cmdName == 'fontborder') {
  10804. span.appendChild(next);
  10805. next = span.nextSibling;
  10806. continue;
  10807. }
  10808. if (next.style.cssText == span.style.cssText) {
  10809. domUtils.moveChild(next, span);
  10810. domUtils.remove(next);
  10811. }
  10812. if (span.nextSibling === next)
  10813. break;
  10814. next = span.nextSibling;
  10815. }
  10816. }
  10817. mergeWithParent(span);
  10818. if(browser.ie && browser.version > 8 ){
  10819. //拷贝父亲们的特别的属性,这里只做背景颜色的处理
  10820. var parent = domUtils.findParent(span,function(n){return n.tagName == 'SPAN' && /background-color/.test(n.style.cssText)});
  10821. if(parent && !/background-color/.test(span.style.cssText)){
  10822. span.style.backgroundColor = parent.style.backgroundColor;
  10823. }
  10824. }
  10825. });
  10826. rng.moveToBookmark(bk);
  10827. mergeChild(rng,cmdName,value)
  10828. }
  10829. me.addInputRule(function (root) {
  10830. utils.each(root.getNodesByTagName('u s del font strike'), function (node) {
  10831. if (node.tagName == 'font') {
  10832. var cssStyle = [];
  10833. for (var p in node.attrs) {
  10834. switch (p) {
  10835. case 'size':
  10836. cssStyle.push('font-size:' +
  10837. ({
  10838. '1':'10',
  10839. '2':'12',
  10840. '3':'16',
  10841. '4':'18',
  10842. '5':'24',
  10843. '6':'32',
  10844. '7':'48'
  10845. }[node.attrs[p]] || node.attrs[p]) + 'px');
  10846. break;
  10847. case 'color':
  10848. cssStyle.push('color:' + node.attrs[p]);
  10849. break;
  10850. case 'face':
  10851. cssStyle.push('font-family:' + node.attrs[p]);
  10852. break;
  10853. case 'style':
  10854. cssStyle.push(node.attrs[p]);
  10855. }
  10856. }
  10857. node.attrs = {
  10858. 'style': cssStyle.join(';')
  10859. };
  10860. } else {
  10861. var val = node.tagName == 'u' ? 'underline' : 'line-through';
  10862. node.attrs = {
  10863. 'style': (node.getAttr('style') || '') + 'text-decoration:' + val + ';'
  10864. }
  10865. }
  10866. node.tagName = 'span';
  10867. });
  10868. // utils.each(root.getNodesByTagName('span'), function (node) {
  10869. // var val;
  10870. // if(val = node.getAttr('class')){
  10871. // if(/fontstrikethrough/.test(val)){
  10872. // node.setStyle('text-decoration','line-through');
  10873. // if(node.attrs['class']){
  10874. // node.attrs['class'] = node.attrs['class'].replace(/fontstrikethrough/,'');
  10875. // }else{
  10876. // node.setAttr('class')
  10877. // }
  10878. // }
  10879. // if(/fontborder/.test(val)){
  10880. // node.setStyle('border','1px solid #000');
  10881. // if(node.attrs['class']){
  10882. // node.attrs['class'] = node.attrs['class'].replace(/fontborder/,'');
  10883. // }else{
  10884. // node.setAttr('class')
  10885. // }
  10886. // }
  10887. // }
  10888. // });
  10889. });
  10890. // me.addOutputRule(function(root){
  10891. // utils.each(root.getNodesByTagName('span'), function (node) {
  10892. // var val;
  10893. // if(val = node.getStyle('text-decoration')){
  10894. // if(/line-through/.test(val)){
  10895. // if(node.attrs['class']){
  10896. // node.attrs['class'] += ' fontstrikethrough';
  10897. // }else{
  10898. // node.setAttr('class','fontstrikethrough')
  10899. // }
  10900. // }
  10901. //
  10902. // node.setStyle('text-decoration')
  10903. // }
  10904. // if(val = node.getStyle('border')){
  10905. // if(/1px/.test(val) && /solid/.test(val)){
  10906. // if(node.attrs['class']){
  10907. // node.attrs['class'] += ' fontborder';
  10908. //
  10909. // }else{
  10910. // node.setAttr('class','fontborder')
  10911. // }
  10912. // }
  10913. // node.setStyle('border')
  10914. //
  10915. // }
  10916. // });
  10917. // });
  10918. for (var p in fonts) {
  10919. (function (cmd, style) {
  10920. UE.commands[cmd] = {
  10921. execCommand: function (cmdName, value) {
  10922. value = value || (this.queryCommandState(cmdName) ? 'none' : cmdName == 'underline' ? 'underline' :
  10923. cmdName == 'fontborder' ? '1px solid #000' :
  10924. 'line-through');
  10925. var me = this,
  10926. range = this.selection.getRange(),
  10927. text;
  10928. if (value == 'default') {
  10929. if (range.collapsed) {
  10930. text = me.document.createTextNode('font');
  10931. range.insertNode(text).select();
  10932. }
  10933. me.execCommand('removeFormat', 'span,a', style);
  10934. if (text) {
  10935. range.setStartBefore(text).collapse(true);
  10936. domUtils.remove(text);
  10937. }
  10938. mergesibling(range,cmdName,value);
  10939. range.select()
  10940. } else {
  10941. if (!range.collapsed) {
  10942. if (needCmd[cmd] && me.queryCommandValue(cmd)) {
  10943. me.execCommand('removeFormat', 'span,a', style);
  10944. }
  10945. range = me.selection.getRange();
  10946. range.applyInlineStyle('span', {'style': style + ':' + value});
  10947. mergesibling(range, cmdName,value);
  10948. range.select();
  10949. } else {
  10950. var span = domUtils.findParentByTagName(range.startContainer, 'span', true);
  10951. text = me.document.createTextNode('font');
  10952. if (span && !span.children.length && !span[browser.ie ? 'innerText' : 'textContent'].replace(fillCharReg, '').length) {
  10953. //for ie hack when enter
  10954. range.insertNode(text);
  10955. if (needCmd[cmd]) {
  10956. range.selectNode(text).select();
  10957. me.execCommand('removeFormat', 'span,a', style, null);
  10958. span = domUtils.findParentByTagName(text, 'span', true);
  10959. range.setStartBefore(text);
  10960. }
  10961. span && (span.style.cssText += ';' + style + ':' + value);
  10962. range.collapse(true).select();
  10963. } else {
  10964. range.insertNode(text);
  10965. range.selectNode(text).select();
  10966. span = range.document.createElement('span');
  10967. if (needCmd[cmd]) {
  10968. //a标签内的不处理跳过
  10969. if (domUtils.findParentByTagName(text, 'a', true)) {
  10970. range.setStartBefore(text).setCursor();
  10971. domUtils.remove(text);
  10972. return;
  10973. }
  10974. me.execCommand('removeFormat', 'span,a', style);
  10975. }
  10976. span.style.cssText = style + ':' + value;
  10977. text.parentNode.insertBefore(span, text);
  10978. //修复,span套span 但样式不继承的问题
  10979. if (!browser.ie || browser.ie && browser.version == 9) {
  10980. var spanParent = span.parentNode;
  10981. while (!domUtils.isBlockElm(spanParent)) {
  10982. if (spanParent.tagName == 'SPAN') {
  10983. //opera合并style不会加入";"
  10984. span.style.cssText = spanParent.style.cssText + ";" + span.style.cssText;
  10985. }
  10986. spanParent = spanParent.parentNode;
  10987. }
  10988. }
  10989. if (opera) {
  10990. setTimeout(function () {
  10991. range.setStart(span, 0).collapse(true);
  10992. mergesibling(range, cmdName,value);
  10993. range.select();
  10994. });
  10995. } else {
  10996. range.setStart(span, 0).collapse(true);
  10997. mergesibling(range,cmdName,value);
  10998. range.select();
  10999. }
  11000. //trace:981
  11001. //domUtils.mergeToParent(span)
  11002. }
  11003. domUtils.remove(text);
  11004. }
  11005. }
  11006. return true;
  11007. },
  11008. queryCommandValue: function (cmdName) {
  11009. var startNode = this.selection.getStart();
  11010. //trace:946
  11011. if (cmdName == 'underline' || cmdName == 'strikethrough') {
  11012. var tmpNode = startNode, value;
  11013. while (tmpNode && !domUtils.isBlockElm(tmpNode) && !domUtils.isBody(tmpNode)) {
  11014. if (tmpNode.nodeType == 1) {
  11015. value = domUtils.getComputedStyle(tmpNode, style);
  11016. if (value != 'none') {
  11017. return value;
  11018. }
  11019. }
  11020. tmpNode = tmpNode.parentNode;
  11021. }
  11022. return 'none';
  11023. }
  11024. if (cmdName == 'fontborder') {
  11025. var tmp = startNode, val;
  11026. while (tmp && dtd.$inline[tmp.tagName]) {
  11027. if (val = domUtils.getComputedStyle(tmp, 'border')) {
  11028. if (/1px/.test(val) && /solid/.test(val)) {
  11029. return val;
  11030. }
  11031. }
  11032. tmp = tmp.parentNode;
  11033. }
  11034. return ''
  11035. }
  11036. if( cmdName == 'FontSize' ) {
  11037. var styleVal = domUtils.getComputedStyle(startNode, style),
  11038. tmp = /^([\d\.]+)(\w+)$/.exec( styleVal );
  11039. if( tmp ) {
  11040. return Math.floor( tmp[1] ) + tmp[2];
  11041. }
  11042. return styleVal;
  11043. }
  11044. return domUtils.getComputedStyle(startNode, style);
  11045. },
  11046. queryCommandState: function (cmdName) {
  11047. if (!needCmd[cmdName])
  11048. return 0;
  11049. var val = this.queryCommandValue(cmdName);
  11050. if (cmdName == 'fontborder') {
  11051. return /1px/.test(val) && /solid/.test(val)
  11052. } else {
  11053. return cmdName == 'underline' ? /underline/.test(val) : /line\-through/.test(val);
  11054. }
  11055. }
  11056. };
  11057. })(p, fonts[p]);
  11058. }
  11059. };
  11060. // plugins/link.js
  11061. /**
  11062. * 超链接
  11063. * @file
  11064. * @since 1.2.6.1
  11065. */
  11066. /**
  11067. * 插入超链接
  11068. * @command link
  11069. * @method execCommand
  11070. * @param { String } cmd 命令字符串
  11071. * @param { Object } options 设置自定义属性,例如:url、title、target
  11072. * @example
  11073. * ```javascript
  11074. * editor.execCommand( 'link', '{
  11075. * url:'ueditor.baidu.com',
  11076. * title:'ueditor',
  11077. * target:'_blank'
  11078. * }' );
  11079. * ```
  11080. */
  11081. /**
  11082. * 返回当前选中的第一个超链接节点
  11083. * @command link
  11084. * @method queryCommandValue
  11085. * @param { String } cmd 命令字符串
  11086. * @return { Element } 超链接节点
  11087. * @example
  11088. * ```javascript
  11089. * editor.queryCommandValue( 'link' );
  11090. * ```
  11091. */
  11092. /**
  11093. * 取消超链接
  11094. * @command unlink
  11095. * @method execCommand
  11096. * @param { String } cmd 命令字符串
  11097. * @example
  11098. * ```javascript
  11099. * editor.execCommand( 'unlink');
  11100. * ```
  11101. */
  11102. UE.plugins['link'] = function(){
  11103. function optimize( range ) {
  11104. var start = range.startContainer,end = range.endContainer;
  11105. if ( start = domUtils.findParentByTagName( start, 'a', true ) ) {
  11106. range.setStartBefore( start );
  11107. }
  11108. if ( end = domUtils.findParentByTagName( end, 'a', true ) ) {
  11109. range.setEndAfter( end );
  11110. }
  11111. }
  11112. UE.commands['unlink'] = {
  11113. execCommand : function() {
  11114. var range = this.selection.getRange(),
  11115. bookmark;
  11116. if(range.collapsed && !domUtils.findParentByTagName( range.startContainer, 'a', true )){
  11117. return;
  11118. }
  11119. bookmark = range.createBookmark();
  11120. optimize( range );
  11121. range.removeInlineStyle( 'a' ).moveToBookmark( bookmark ).select();
  11122. },
  11123. queryCommandState : function(){
  11124. return !this.highlight && this.queryCommandValue('link') ? 0 : -1;
  11125. }
  11126. };
  11127. function doLink(range,opt,me){
  11128. var rngClone = range.cloneRange(),
  11129. link = me.queryCommandValue('link');
  11130. optimize( range = range.adjustmentBoundary() );
  11131. var start = range.startContainer;
  11132. if(start.nodeType == 1 && link){
  11133. start = start.childNodes[range.startOffset];
  11134. if(start && start.nodeType == 1 && start.tagName == 'A' && /^(?:https?|ftp|file)\s*:\s*\/\//.test(start[browser.ie?'innerText':'textContent'])){
  11135. start[browser.ie ? 'innerText' : 'textContent'] = utils.html(opt.textValue||opt.href);
  11136. }
  11137. }
  11138. if( !rngClone.collapsed || link){
  11139. range.removeInlineStyle( 'a' );
  11140. rngClone = range.cloneRange();
  11141. }
  11142. if ( rngClone.collapsed ) {
  11143. var a = range.document.createElement( 'a'),
  11144. text = '';
  11145. if(opt.textValue){
  11146. text = utils.html(opt.textValue);
  11147. delete opt.textValue;
  11148. }else{
  11149. text = utils.html(opt.href);
  11150. }
  11151. domUtils.setAttributes( a, opt );
  11152. start = domUtils.findParentByTagName( rngClone.startContainer, 'a', true );
  11153. if(start && domUtils.isInNodeEndBoundary(rngClone,start)){
  11154. range.setStartAfter(start).collapse(true);
  11155. }
  11156. a[browser.ie ? 'innerText' : 'textContent'] = text;
  11157. range.insertNode(a).selectNode( a );
  11158. } else {
  11159. range.applyInlineStyle( 'a', opt );
  11160. }
  11161. }
  11162. UE.commands['link'] = {
  11163. execCommand : function( cmdName, opt ) {
  11164. var range;
  11165. opt._href && (opt._href = utils.unhtml(opt._href,/[<">]/g));
  11166. opt.href && (opt.href = utils.unhtml(opt.href,/[<">]/g));
  11167. opt.textValue && (opt.textValue = utils.unhtml(opt.textValue,/[<">]/g));
  11168. doLink(range=this.selection.getRange(),opt,this);
  11169. //闭合都不加占位符,如果加了会在a后边多个占位符节点,导致a是图片背景组成的列表,出现空白问题
  11170. range.collapse().select(true);
  11171. },
  11172. queryCommandValue : function() {
  11173. var range = this.selection.getRange(),
  11174. node;
  11175. if ( range.collapsed ) {
  11176. // node = this.selection.getStart();
  11177. //在ie下getstart()取值偏上了
  11178. node = range.startContainer;
  11179. node = node.nodeType == 1 ? node : node.parentNode;
  11180. if ( node && (node = domUtils.findParentByTagName( node, 'a', true )) && ! domUtils.isInNodeEndBoundary(range,node)) {
  11181. return node;
  11182. }
  11183. } else {
  11184. //trace:1111 如果是<p><a>xx</a></p> startContainer是p就会找不到a
  11185. range.shrinkBoundary();
  11186. var start = range.startContainer.nodeType == 3 || !range.startContainer.childNodes[range.startOffset] ? range.startContainer : range.startContainer.childNodes[range.startOffset],
  11187. end = range.endContainer.nodeType == 3 || range.endOffset == 0 ? range.endContainer : range.endContainer.childNodes[range.endOffset-1],
  11188. common = range.getCommonAncestor();
  11189. node = domUtils.findParentByTagName( common, 'a', true );
  11190. if ( !node && common.nodeType == 1){
  11191. var as = common.getElementsByTagName( 'a' ),
  11192. ps,pe;
  11193. for ( var i = 0,ci; ci = as[i++]; ) {
  11194. ps = domUtils.getPosition( ci, start ),pe = domUtils.getPosition( ci,end);
  11195. if ( (ps & domUtils.POSITION_FOLLOWING || ps & domUtils.POSITION_CONTAINS)
  11196. &&
  11197. (pe & domUtils.POSITION_PRECEDING || pe & domUtils.POSITION_CONTAINS)
  11198. ) {
  11199. node = ci;
  11200. break;
  11201. }
  11202. }
  11203. }
  11204. return node;
  11205. }
  11206. },
  11207. queryCommandState : function() {
  11208. //判断如果是视频的话连接不可用
  11209. //fix 853
  11210. var img = this.selection.getRange().getClosedNode(),
  11211. flag = img && (img.className == "edui-faked-video" || img.className.indexOf("edui-upload-video")!=-1);
  11212. return flag ? -1 : 0;
  11213. }
  11214. };
  11215. };
  11216. // plugins/iframe.js
  11217. ///import core
  11218. ///import plugins\inserthtml.js
  11219. ///commands 插入框架
  11220. ///commandsName InsertFrame
  11221. ///commandsTitle 插入Iframe
  11222. ///commandsDialog dialogs\insertframe
  11223. UE.plugins['insertframe'] = function() {
  11224. var me =this;
  11225. function deleteIframe(){
  11226. me._iframe && delete me._iframe;
  11227. }
  11228. me.addListener("selectionchange",function(){
  11229. deleteIframe();
  11230. });
  11231. };
  11232. // plugins/scrawl.js
  11233. ///import core
  11234. ///commands 涂鸦
  11235. ///commandsName Scrawl
  11236. ///commandsTitle 涂鸦
  11237. ///commandsDialog dialogs\scrawl
  11238. UE.commands['scrawl'] = {
  11239. queryCommandState : function(){
  11240. return ( browser.ie && browser.version <= 8 ) ? -1 :0;
  11241. }
  11242. };
  11243. // plugins/removeformat.js
  11244. /**
  11245. * 清除格式
  11246. * @file
  11247. * @since 1.2.6.1
  11248. */
  11249. /**
  11250. * 清除文字样式
  11251. * @command removeformat
  11252. * @method execCommand
  11253. * @param { String } cmd 命令字符串
  11254. * @param {String} tags 以逗号隔开的标签。如:strong
  11255. * @param {String} style 样式如:color
  11256. * @param {String} attrs 属性如:width
  11257. * @example
  11258. * ```javascript
  11259. * editor.execCommand( 'removeformat', 'strong','color','width' );
  11260. * ```
  11261. */
  11262. UE.plugins['removeformat'] = function(){
  11263. var me = this;
  11264. me.setOpt({
  11265. 'removeFormatTags': 'b,big,code,del,dfn,em,font,i,ins,kbd,q,samp,small,span,strike,strong,sub,sup,tt,u,var',
  11266. 'removeFormatAttributes':'class,style,lang,width,height,align,hspace,valign'
  11267. });
  11268. me.commands['removeformat'] = {
  11269. execCommand : function( cmdName, tags, style, attrs,notIncludeA ) {
  11270. var tagReg = new RegExp( '^(?:' + (tags || this.options.removeFormatTags).replace( /,/g, '|' ) + ')$', 'i' ) ,
  11271. removeFormatAttributes = style ? [] : (attrs || this.options.removeFormatAttributes).split( ',' ),
  11272. range = new dom.Range( this.document ),
  11273. bookmark,node,parent,
  11274. filter = function( node ) {
  11275. return node.nodeType == 1;
  11276. };
  11277. function isRedundantSpan (node) {
  11278. if (node.nodeType == 3 || node.tagName.toLowerCase() != 'span'){
  11279. return 0;
  11280. }
  11281. if (browser.ie) {
  11282. //ie 下判断实效,所以只能简单用style来判断
  11283. //return node.style.cssText == '' ? 1 : 0;
  11284. var attrs = node.attributes;
  11285. if ( attrs.length ) {
  11286. for ( var i = 0,l = attrs.length; i<l; i++ ) {
  11287. if ( attrs[i].specified ) {
  11288. return 0;
  11289. }
  11290. }
  11291. return 1;
  11292. }
  11293. }
  11294. return !node.attributes.length;
  11295. }
  11296. function doRemove( range ) {
  11297. var bookmark1 = range.createBookmark();
  11298. if ( range.collapsed ) {
  11299. range.enlarge( true );
  11300. }
  11301. //不能把a标签切了
  11302. if(!notIncludeA){
  11303. var aNode = domUtils.findParentByTagName(range.startContainer,'a',true);
  11304. if(aNode){
  11305. range.setStartBefore(aNode);
  11306. }
  11307. aNode = domUtils.findParentByTagName(range.endContainer,'a',true);
  11308. if(aNode){
  11309. range.setEndAfter(aNode);
  11310. }
  11311. }
  11312. bookmark = range.createBookmark();
  11313. node = bookmark.start;
  11314. //切开始
  11315. while ( (parent = node.parentNode) && !domUtils.isBlockElm( parent ) ) {
  11316. domUtils.breakParent( node, parent );
  11317. domUtils.clearEmptySibling( node );
  11318. }
  11319. if ( bookmark.end ) {
  11320. //切结束
  11321. node = bookmark.end;
  11322. while ( (parent = node.parentNode) && !domUtils.isBlockElm( parent ) ) {
  11323. domUtils.breakParent( node, parent );
  11324. domUtils.clearEmptySibling( node );
  11325. }
  11326. //开始去除样式
  11327. var current = domUtils.getNextDomNode( bookmark.start, false, filter ),
  11328. next;
  11329. while ( current ) {
  11330. if ( current == bookmark.end ) {
  11331. break;
  11332. }
  11333. next = domUtils.getNextDomNode( current, true, filter );
  11334. if ( !dtd.$empty[current.tagName.toLowerCase()] && !domUtils.isBookmarkNode( current ) ) {
  11335. if ( tagReg.test( current.tagName ) ) {
  11336. if ( style ) {
  11337. domUtils.removeStyle( current, style );
  11338. if ( isRedundantSpan( current ) && style != 'text-decoration'){
  11339. domUtils.remove( current, true );
  11340. }
  11341. } else {
  11342. domUtils.remove( current, true );
  11343. }
  11344. } else {
  11345. //trace:939 不能把list上的样式去掉
  11346. if(!dtd.$tableContent[current.tagName] && !dtd.$list[current.tagName]){
  11347. domUtils.removeAttributes( current, removeFormatAttributes );
  11348. if ( isRedundantSpan( current ) ){
  11349. domUtils.remove( current, true );
  11350. }
  11351. }
  11352. }
  11353. }
  11354. current = next;
  11355. }
  11356. }
  11357. //trace:1035
  11358. //trace:1096 不能把td上的样式去掉,比如边框
  11359. var pN = bookmark.start.parentNode;
  11360. if(domUtils.isBlockElm(pN) && !dtd.$tableContent[pN.tagName] && !dtd.$list[pN.tagName]){
  11361. domUtils.removeAttributes( pN,removeFormatAttributes );
  11362. }
  11363. pN = bookmark.end.parentNode;
  11364. if(bookmark.end && domUtils.isBlockElm(pN) && !dtd.$tableContent[pN.tagName]&& !dtd.$list[pN.tagName]){
  11365. domUtils.removeAttributes( pN,removeFormatAttributes );
  11366. }
  11367. range.moveToBookmark( bookmark ).moveToBookmark(bookmark1);
  11368. //清除冗余的代码 <b><bookmark></b>
  11369. var node = range.startContainer,
  11370. tmp,
  11371. collapsed = range.collapsed;
  11372. while(node.nodeType == 1 && domUtils.isEmptyNode(node) && dtd.$removeEmpty[node.tagName]){
  11373. tmp = node.parentNode;
  11374. range.setStartBefore(node);
  11375. //trace:937
  11376. //更新结束边界
  11377. if(range.startContainer === range.endContainer){
  11378. range.endOffset--;
  11379. }
  11380. domUtils.remove(node);
  11381. node = tmp;
  11382. }
  11383. if(!collapsed){
  11384. node = range.endContainer;
  11385. while(node.nodeType == 1 && domUtils.isEmptyNode(node) && dtd.$removeEmpty[node.tagName]){
  11386. tmp = node.parentNode;
  11387. range.setEndBefore(node);
  11388. domUtils.remove(node);
  11389. node = tmp;
  11390. }
  11391. }
  11392. }
  11393. range = this.selection.getRange();
  11394. doRemove( range );
  11395. range.select();
  11396. }
  11397. };
  11398. };
  11399. // plugins/blockquote.js
  11400. /**
  11401. * 添加引用
  11402. * @file
  11403. * @since 1.2.6.1
  11404. */
  11405. /**
  11406. * 添加引用
  11407. * @command blockquote
  11408. * @method execCommand
  11409. * @param { String } cmd 命令字符串
  11410. * @example
  11411. * ```javascript
  11412. * editor.execCommand( 'blockquote' );
  11413. * ```
  11414. */
  11415. /**
  11416. * 添加引用
  11417. * @command blockquote
  11418. * @method execCommand
  11419. * @param { String } cmd 命令字符串
  11420. * @param { Object } attrs 节点属性
  11421. * @example
  11422. * ```javascript
  11423. * editor.execCommand( 'blockquote',{
  11424. * style: "color: red;"
  11425. * } );
  11426. * ```
  11427. */
  11428. UE.plugins['blockquote'] = function(){
  11429. var me = this;
  11430. function getObj(editor){
  11431. return domUtils.filterNodeList(editor.selection.getStartElementPath(),'blockquote');
  11432. }
  11433. me.commands['blockquote'] = {
  11434. execCommand : function( cmdName, attrs ) {
  11435. var range = this.selection.getRange(),
  11436. obj = getObj(this),
  11437. blockquote = dtd.blockquote,
  11438. bookmark = range.createBookmark();
  11439. if ( obj ) {
  11440. var start = range.startContainer,
  11441. startBlock = domUtils.isBlockElm(start) ? start : domUtils.findParent(start,function(node){return domUtils.isBlockElm(node)}),
  11442. end = range.endContainer,
  11443. endBlock = domUtils.isBlockElm(end) ? end : domUtils.findParent(end,function(node){return domUtils.isBlockElm(node)});
  11444. //处理一下li
  11445. startBlock = domUtils.findParentByTagName(startBlock,'li',true) || startBlock;
  11446. endBlock = domUtils.findParentByTagName(endBlock,'li',true) || endBlock;
  11447. if(startBlock.tagName == 'LI' || startBlock.tagName == 'TD' || startBlock === obj || domUtils.isBody(startBlock)){
  11448. domUtils.remove(obj,true);
  11449. }else{
  11450. domUtils.breakParent(startBlock,obj);
  11451. }
  11452. if(startBlock !== endBlock){
  11453. obj = domUtils.findParentByTagName(endBlock,'blockquote');
  11454. if(obj){
  11455. if(endBlock.tagName == 'LI' || endBlock.tagName == 'TD'|| domUtils.isBody(endBlock)){
  11456. obj.parentNode && domUtils.remove(obj,true);
  11457. }else{
  11458. domUtils.breakParent(endBlock,obj);
  11459. }
  11460. }
  11461. }
  11462. var blockquotes = domUtils.getElementsByTagName(this.document,'blockquote');
  11463. for(var i=0,bi;bi=blockquotes[i++];){
  11464. if(!bi.childNodes.length){
  11465. domUtils.remove(bi);
  11466. }else if(domUtils.getPosition(bi,startBlock)&domUtils.POSITION_FOLLOWING && domUtils.getPosition(bi,endBlock)&domUtils.POSITION_PRECEDING){
  11467. domUtils.remove(bi,true);
  11468. }
  11469. }
  11470. } else {
  11471. var tmpRange = range.cloneRange(),
  11472. node = tmpRange.startContainer.nodeType == 1 ? tmpRange.startContainer : tmpRange.startContainer.parentNode,
  11473. preNode = node,
  11474. doEnd = 1;
  11475. //调整开始
  11476. while ( 1 ) {
  11477. if ( domUtils.isBody(node) ) {
  11478. if ( preNode !== node ) {
  11479. if ( range.collapsed ) {
  11480. tmpRange.selectNode( preNode );
  11481. doEnd = 0;
  11482. } else {
  11483. tmpRange.setStartBefore( preNode );
  11484. }
  11485. }else{
  11486. tmpRange.setStart(node,0);
  11487. }
  11488. break;
  11489. }
  11490. if ( !blockquote[node.tagName] ) {
  11491. if ( range.collapsed ) {
  11492. tmpRange.selectNode( preNode );
  11493. } else{
  11494. tmpRange.setStartBefore( preNode);
  11495. }
  11496. break;
  11497. }
  11498. preNode = node;
  11499. node = node.parentNode;
  11500. }
  11501. //调整结束
  11502. if ( doEnd ) {
  11503. preNode = node = node = tmpRange.endContainer.nodeType == 1 ? tmpRange.endContainer : tmpRange.endContainer.parentNode;
  11504. while ( 1 ) {
  11505. if ( domUtils.isBody( node ) ) {
  11506. if ( preNode !== node ) {
  11507. tmpRange.setEndAfter( preNode );
  11508. } else {
  11509. tmpRange.setEnd( node, node.childNodes.length );
  11510. }
  11511. break;
  11512. }
  11513. if ( !blockquote[node.tagName] ) {
  11514. tmpRange.setEndAfter( preNode );
  11515. break;
  11516. }
  11517. preNode = node;
  11518. node = node.parentNode;
  11519. }
  11520. }
  11521. node = range.document.createElement( 'blockquote' );
  11522. domUtils.setAttributes( node, attrs );
  11523. node.appendChild( tmpRange.extractContents() );
  11524. tmpRange.insertNode( node );
  11525. //去除重复的
  11526. var childs = domUtils.getElementsByTagName(node,'blockquote');
  11527. for(var i=0,ci;ci=childs[i++];){
  11528. if(ci.parentNode){
  11529. domUtils.remove(ci,true);
  11530. }
  11531. }
  11532. }
  11533. range.moveToBookmark( bookmark ).select();
  11534. },
  11535. queryCommandState : function() {
  11536. return getObj(this) ? 1 : 0;
  11537. }
  11538. };
  11539. };
  11540. // plugins/convertcase.js
  11541. /**
  11542. * 大小写转换
  11543. * @file
  11544. * @since 1.2.6.1
  11545. */
  11546. /**
  11547. * 把选区内文本变大写,与“tolowercase”命令互斥
  11548. * @command touppercase
  11549. * @method execCommand
  11550. * @param { String } cmd 命令字符串
  11551. * @example
  11552. * ```javascript
  11553. * editor.execCommand( 'touppercase' );
  11554. * ```
  11555. */
  11556. /**
  11557. * 把选区内文本变小写,与“touppercase”命令互斥
  11558. * @command tolowercase
  11559. * @method execCommand
  11560. * @param { String } cmd 命令字符串
  11561. * @example
  11562. * ```javascript
  11563. * editor.execCommand( 'tolowercase' );
  11564. * ```
  11565. */
  11566. UE.commands['touppercase'] =
  11567. UE.commands['tolowercase'] = {
  11568. execCommand:function (cmd) {
  11569. var me = this;
  11570. var rng = me.selection.getRange();
  11571. if(rng.collapsed){
  11572. return rng;
  11573. }
  11574. var bk = rng.createBookmark(),
  11575. bkEnd = bk.end,
  11576. filterFn = function( node ) {
  11577. return !domUtils.isBr(node) && !domUtils.isWhitespace( node );
  11578. },
  11579. curNode = domUtils.getNextDomNode( bk.start, false, filterFn );
  11580. while ( curNode && (domUtils.getPosition( curNode, bkEnd ) & domUtils.POSITION_PRECEDING) ) {
  11581. if ( curNode.nodeType == 3 ) {
  11582. curNode.nodeValue = curNode.nodeValue[cmd == 'touppercase' ? 'toUpperCase' : 'toLowerCase']();
  11583. }
  11584. curNode = domUtils.getNextDomNode( curNode, true, filterFn );
  11585. if(curNode === bkEnd){
  11586. break;
  11587. }
  11588. }
  11589. rng.moveToBookmark(bk).select();
  11590. }
  11591. };
  11592. // plugins/indent.js
  11593. /**
  11594. * 首行缩进
  11595. * @file
  11596. * @since 1.2.6.1
  11597. */
  11598. /**
  11599. * 缩进
  11600. * @command indent
  11601. * @method execCommand
  11602. * @param { String } cmd 命令字符串
  11603. * @example
  11604. * ```javascript
  11605. * editor.execCommand( 'indent' );
  11606. * ```
  11607. */
  11608. UE.commands['indent'] = {
  11609. execCommand : function() {
  11610. var me = this,value = me.queryCommandState("indent") ? "0em" : (me.options.indentValue || '2em');
  11611. me.execCommand('Paragraph','p',{style:'text-indent:'+ value});
  11612. },
  11613. queryCommandState : function() {
  11614. var pN = domUtils.filterNodeList(this.selection.getStartElementPath(),'p h1 h2 h3 h4 h5 h6');
  11615. return pN && pN.style.textIndent && parseInt(pN.style.textIndent) ? 1 : 0;
  11616. }
  11617. };
  11618. // plugins/print.js
  11619. /**
  11620. * 打印
  11621. * @file
  11622. * @since 1.2.6.1
  11623. */
  11624. /**
  11625. * 打印
  11626. * @command print
  11627. * @method execCommand
  11628. * @param { String } cmd 命令字符串
  11629. * @example
  11630. * ```javascript
  11631. * editor.execCommand( 'print' );
  11632. * ```
  11633. */
  11634. UE.commands['print'] = {
  11635. execCommand : function(){
  11636. this.window.print();
  11637. },
  11638. notNeedUndo : 1
  11639. };
  11640. // plugins/preview.js
  11641. /**
  11642. * 预览
  11643. * @file
  11644. * @since 1.2.6.1
  11645. */
  11646. /**
  11647. * 预览
  11648. * @command preview
  11649. * @method execCommand
  11650. * @param { String } cmd 命令字符串
  11651. * @example
  11652. * ```javascript
  11653. * editor.execCommand( 'preview' );
  11654. * ```
  11655. */
  11656. UE.commands['preview'] = {
  11657. execCommand : function(){
  11658. var w = window.open('', '_blank', ''),
  11659. d = w.document;
  11660. d.open();
  11661. d.write('<!DOCTYPE html><html><head><meta charset="utf-8"/><script src="'+this.options.UEDITOR_HOME_URL+'ueditor.parse.js"></script><script>' +
  11662. "setTimeout(function(){uParse('div',{rootPath: '"+ this.options.UEDITOR_HOME_URL +"'})},300)" +
  11663. '</script></head><body><div>'+this.getContent(null,null,true)+'</div></body></html>');
  11664. d.close();
  11665. },
  11666. notNeedUndo : 1
  11667. };
  11668. // plugins/selectall.js
  11669. /**
  11670. * 全选
  11671. * @file
  11672. * @since 1.2.6.1
  11673. */
  11674. /**
  11675. * 选中所有内容
  11676. * @command selectall
  11677. * @method execCommand
  11678. * @param { String } cmd 命令字符串
  11679. * @example
  11680. * ```javascript
  11681. * editor.execCommand( 'selectall' );
  11682. * ```
  11683. */
  11684. UE.plugins['selectall'] = function(){
  11685. var me = this;
  11686. me.commands['selectall'] = {
  11687. execCommand : function(){
  11688. //去掉了原生的selectAll,因为会出现报错和当内容为空时,不能出现闭合状态的光标
  11689. var me = this,body = me.body,
  11690. range = me.selection.getRange();
  11691. range.selectNodeContents(body);
  11692. if(domUtils.isEmptyBlock(body)){
  11693. //opera不能自动合并到元素的里边,要手动处理一下
  11694. if(browser.opera && body.firstChild && body.firstChild.nodeType == 1){
  11695. range.setStartAtFirst(body.firstChild);
  11696. }
  11697. range.collapse(true);
  11698. }
  11699. range.select(true);
  11700. },
  11701. notNeedUndo : 1
  11702. };
  11703. //快捷键
  11704. me.addshortcutkey({
  11705. "selectAll" : "ctrl+65"
  11706. });
  11707. };
  11708. // plugins/paragraph.js
  11709. /**
  11710. * 段落样式
  11711. * @file
  11712. * @since 1.2.6.1
  11713. */
  11714. /**
  11715. * 段落格式
  11716. * @command paragraph
  11717. * @method execCommand
  11718. * @param { String } cmd 命令字符串
  11719. * @param {String} style 标签值为:'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'
  11720. * @param {Object} attrs 标签的属性
  11721. * @example
  11722. * ```javascript
  11723. * editor.execCommand( 'Paragraph','h1','{
  11724. * class:'test'
  11725. * }' );
  11726. * ```
  11727. */
  11728. /**
  11729. * 返回选区内节点标签名
  11730. * @command paragraph
  11731. * @method queryCommandValue
  11732. * @param { String } cmd 命令字符串
  11733. * @return { String } 节点标签名
  11734. * @example
  11735. * ```javascript
  11736. * editor.queryCommandValue( 'Paragraph' );
  11737. * ```
  11738. */
  11739. UE.plugins['paragraph'] = function() {
  11740. var me = this,
  11741. block = domUtils.isBlockElm,
  11742. notExchange = ['TD','LI','PRE'],
  11743. doParagraph = function(range,style,attrs,sourceCmdName){
  11744. var bookmark = range.createBookmark(),
  11745. filterFn = function( node ) {
  11746. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' && !domUtils.isBookmarkNode(node) : !domUtils.isWhitespace( node );
  11747. },
  11748. para;
  11749. range.enlarge( true );
  11750. var bookmark2 = range.createBookmark(),
  11751. current = domUtils.getNextDomNode( bookmark2.start, false, filterFn ),
  11752. tmpRange = range.cloneRange(),
  11753. tmpNode;
  11754. while ( current && !(domUtils.getPosition( current, bookmark2.end ) & domUtils.POSITION_FOLLOWING) ) {
  11755. if ( current.nodeType == 3 || !block( current ) ) {
  11756. tmpRange.setStartBefore( current );
  11757. while ( current && current !== bookmark2.end && !block( current ) ) {
  11758. tmpNode = current;
  11759. current = domUtils.getNextDomNode( current, false, null, function( node ) {
  11760. return !block( node );
  11761. } );
  11762. }
  11763. tmpRange.setEndAfter( tmpNode );
  11764. para = range.document.createElement( style );
  11765. if(attrs){
  11766. domUtils.setAttributes(para,attrs);
  11767. if(sourceCmdName && sourceCmdName == 'customstyle' && attrs.style){
  11768. para.style.cssText = attrs.style;
  11769. }
  11770. }
  11771. para.appendChild( tmpRange.extractContents() );
  11772. //需要内容占位
  11773. if(domUtils.isEmptyNode(para)){
  11774. domUtils.fillChar(range.document,para);
  11775. }
  11776. tmpRange.insertNode( para );
  11777. var parent = para.parentNode;
  11778. //如果para上一级是一个block元素且不是body,td就删除它
  11779. if ( block( parent ) && !domUtils.isBody( para.parentNode ) && utils.indexOf(notExchange,parent.tagName)==-1) {
  11780. //存储dir,style
  11781. if(!(sourceCmdName && sourceCmdName == 'customstyle')){
  11782. parent.getAttribute('dir') && para.setAttribute('dir',parent.getAttribute('dir'));
  11783. //trace:1070
  11784. parent.style.cssText && (para.style.cssText = parent.style.cssText + ';' + para.style.cssText);
  11785. //trace:1030
  11786. parent.style.textAlign && !para.style.textAlign && (para.style.textAlign = parent.style.textAlign);
  11787. parent.style.textIndent && !para.style.textIndent && (para.style.textIndent = parent.style.textIndent);
  11788. parent.style.padding && !para.style.padding && (para.style.padding = parent.style.padding);
  11789. }
  11790. //trace:1706 选择的就是h1-6要删除
  11791. if(attrs && /h\d/i.test(parent.tagName) && !/h\d/i.test(para.tagName) ){
  11792. domUtils.setAttributes(parent,attrs);
  11793. if(sourceCmdName && sourceCmdName == 'customstyle' && attrs.style){
  11794. parent.style.cssText = attrs.style;
  11795. }
  11796. domUtils.remove(para,true);
  11797. para = parent;
  11798. }else{
  11799. domUtils.remove( para.parentNode, true );
  11800. }
  11801. }
  11802. if( utils.indexOf(notExchange,parent.tagName)!=-1){
  11803. current = parent;
  11804. }else{
  11805. current = para;
  11806. }
  11807. current = domUtils.getNextDomNode( current, false, filterFn );
  11808. } else {
  11809. current = domUtils.getNextDomNode( current, true, filterFn );
  11810. }
  11811. }
  11812. return range.moveToBookmark( bookmark2 ).moveToBookmark( bookmark );
  11813. };
  11814. me.setOpt('paragraph',{'p':'', 'h1':'', 'h2':'', 'h3':'', 'h4':'', 'h5':'', 'h6':''});
  11815. me.commands['paragraph'] = {
  11816. execCommand : function( cmdName, style,attrs,sourceCmdName ) {
  11817. var range = this.selection.getRange();
  11818. //闭合时单独处理
  11819. if(range.collapsed){
  11820. var txt = this.document.createTextNode('p');
  11821. range.insertNode(txt);
  11822. //去掉冗余的fillchar
  11823. if(browser.ie){
  11824. var node = txt.previousSibling;
  11825. if(node && domUtils.isWhitespace(node)){
  11826. domUtils.remove(node);
  11827. }
  11828. node = txt.nextSibling;
  11829. if(node && domUtils.isWhitespace(node)){
  11830. domUtils.remove(node);
  11831. }
  11832. }
  11833. }
  11834. range = doParagraph(range,style,attrs,sourceCmdName);
  11835. if(txt){
  11836. range.setStartBefore(txt).collapse(true);
  11837. pN = txt.parentNode;
  11838. domUtils.remove(txt);
  11839. if(domUtils.isBlockElm(pN)&&domUtils.isEmptyNode(pN)){
  11840. domUtils.fillNode(this.document,pN);
  11841. }
  11842. }
  11843. if(browser.gecko && range.collapsed && range.startContainer.nodeType == 1){
  11844. var child = range.startContainer.childNodes[range.startOffset];
  11845. if(child && child.nodeType == 1 && child.tagName.toLowerCase() == style){
  11846. range.setStart(child,0).collapse(true);
  11847. }
  11848. }
  11849. //trace:1097 原来有true,原因忘了,但去了就不能清除多余的占位符了
  11850. range.select();
  11851. return true;
  11852. },
  11853. queryCommandValue : function() {
  11854. var node = domUtils.filterNodeList(this.selection.getStartElementPath(),'p h1 h2 h3 h4 h5 h6');
  11855. return node ? node.tagName.toLowerCase() : '';
  11856. }
  11857. };
  11858. };
  11859. // plugins/directionality.js
  11860. /**
  11861. * 设置文字输入的方向的插件
  11862. * @file
  11863. * @since 1.2.6.1
  11864. */
  11865. (function() {
  11866. var block = domUtils.isBlockElm ,
  11867. getObj = function(editor){
  11868. // var startNode = editor.selection.getStart(),
  11869. // parents;
  11870. // if ( startNode ) {
  11871. // //查找所有的是block的父亲节点
  11872. // parents = domUtils.findParents( startNode, true, block, true );
  11873. // for ( var i = 0,ci; ci = parents[i++]; ) {
  11874. // if ( ci.getAttribute( 'dir' ) ) {
  11875. // return ci;
  11876. // }
  11877. // }
  11878. // }
  11879. return domUtils.filterNodeList(editor.selection.getStartElementPath(),function(n){return n && n.nodeType == 1 && n.getAttribute('dir')});
  11880. },
  11881. doDirectionality = function(range,editor,forward){
  11882. var bookmark,
  11883. filterFn = function( node ) {
  11884. return node.nodeType == 1 ? !domUtils.isBookmarkNode(node) : !domUtils.isWhitespace(node);
  11885. },
  11886. obj = getObj( editor );
  11887. if ( obj && range.collapsed ) {
  11888. obj.setAttribute( 'dir', forward );
  11889. return range;
  11890. }
  11891. bookmark = range.createBookmark();
  11892. range.enlarge( true );
  11893. var bookmark2 = range.createBookmark(),
  11894. current = domUtils.getNextDomNode( bookmark2.start, false, filterFn ),
  11895. tmpRange = range.cloneRange(),
  11896. tmpNode;
  11897. while ( current && !(domUtils.getPosition( current, bookmark2.end ) & domUtils.POSITION_FOLLOWING) ) {
  11898. if ( current.nodeType == 3 || !block( current ) ) {
  11899. tmpRange.setStartBefore( current );
  11900. while ( current && current !== bookmark2.end && !block( current ) ) {
  11901. tmpNode = current;
  11902. current = domUtils.getNextDomNode( current, false, null, function( node ) {
  11903. return !block( node );
  11904. } );
  11905. }
  11906. tmpRange.setEndAfter( tmpNode );
  11907. var common = tmpRange.getCommonAncestor();
  11908. if ( !domUtils.isBody( common ) && block( common ) ) {
  11909. //遍历到了block节点
  11910. common.setAttribute( 'dir', forward );
  11911. current = common;
  11912. } else {
  11913. //没有遍历到,添加一个block节点
  11914. var p = range.document.createElement( 'p' );
  11915. p.setAttribute( 'dir', forward );
  11916. var frag = tmpRange.extractContents();
  11917. p.appendChild( frag );
  11918. tmpRange.insertNode( p );
  11919. current = p;
  11920. }
  11921. current = domUtils.getNextDomNode( current, false, filterFn );
  11922. } else {
  11923. current = domUtils.getNextDomNode( current, true, filterFn );
  11924. }
  11925. }
  11926. return range.moveToBookmark( bookmark2 ).moveToBookmark( bookmark );
  11927. };
  11928. /**
  11929. * 文字输入方向
  11930. * @command directionality
  11931. * @method execCommand
  11932. * @param { String } cmdName 命令字符串
  11933. * @param { String } forward 传入'ltr'表示从左向右输入,传入'rtl'表示从右向左输入
  11934. * @example
  11935. * ```javascript
  11936. * editor.execCommand( 'directionality', 'ltr');
  11937. * ```
  11938. */
  11939. /**
  11940. * 查询当前选区的文字输入方向
  11941. * @command directionality
  11942. * @method queryCommandValue
  11943. * @param { String } cmdName 命令字符串
  11944. * @return { String } 返回'ltr'表示从左向右输入,返回'rtl'表示从右向左输入
  11945. * @example
  11946. * ```javascript
  11947. * editor.queryCommandValue( 'directionality');
  11948. * ```
  11949. */
  11950. UE.commands['directionality'] = {
  11951. execCommand : function( cmdName,forward ) {
  11952. var range = this.selection.getRange();
  11953. //闭合时单独处理
  11954. if(range.collapsed){
  11955. var txt = this.document.createTextNode('d');
  11956. range.insertNode(txt);
  11957. }
  11958. doDirectionality(range,this,forward);
  11959. if(txt){
  11960. range.setStartBefore(txt).collapse(true);
  11961. domUtils.remove(txt);
  11962. }
  11963. range.select();
  11964. return true;
  11965. },
  11966. queryCommandValue : function() {
  11967. var node = getObj(this);
  11968. return node ? node.getAttribute('dir') : 'ltr';
  11969. }
  11970. };
  11971. })();
  11972. // plugins/horizontal.js
  11973. /**
  11974. * 插入分割线插件
  11975. * @file
  11976. * @since 1.2.6.1
  11977. */
  11978. /**
  11979. * 插入分割线
  11980. * @command horizontal
  11981. * @method execCommand
  11982. * @param { String } cmdName 命令字符串
  11983. * @example
  11984. * ```javascript
  11985. * editor.execCommand( 'horizontal' );
  11986. * ```
  11987. */
  11988. UE.plugins['horizontal'] = function(){
  11989. var me = this;
  11990. me.commands['horizontal'] = {
  11991. execCommand : function( cmdName ) {
  11992. var me = this;
  11993. if(me.queryCommandState(cmdName)!==-1){
  11994. me.execCommand('insertHtml','<hr>');
  11995. var range = me.selection.getRange(),
  11996. start = range.startContainer;
  11997. if(start.nodeType == 1 && !start.childNodes[range.startOffset] ){
  11998. var tmp;
  11999. if(tmp = start.childNodes[range.startOffset - 1]){
  12000. if(tmp.nodeType == 1 && tmp.tagName == 'HR'){
  12001. if(me.options.enterTag == 'p'){
  12002. tmp = me.document.createElement('p');
  12003. range.insertNode(tmp);
  12004. range.setStart(tmp,0).setCursor();
  12005. }else{
  12006. tmp = me.document.createElement('br');
  12007. range.insertNode(tmp);
  12008. range.setStartBefore(tmp).setCursor();
  12009. }
  12010. }
  12011. }
  12012. }
  12013. return true;
  12014. }
  12015. },
  12016. //边界在table里不能加分隔线
  12017. queryCommandState : function() {
  12018. return domUtils.filterNodeList(this.selection.getStartElementPath(),'table') ? -1 : 0;
  12019. }
  12020. };
  12021. // me.addListener('delkeyup',function(){
  12022. // var rng = this.selection.getRange();
  12023. // if(browser.ie && browser.version > 8){
  12024. // rng.txtToElmBoundary(true);
  12025. // if(domUtils.isStartInblock(rng)){
  12026. // var tmpNode = rng.startContainer;
  12027. // var pre = tmpNode.previousSibling;
  12028. // if(pre && domUtils.isTagNode(pre,'hr')){
  12029. // domUtils.remove(pre);
  12030. // rng.select();
  12031. // return;
  12032. // }
  12033. // }
  12034. // }
  12035. // if(domUtils.isBody(rng.startContainer)){
  12036. // var hr = rng.startContainer.childNodes[rng.startOffset -1];
  12037. // if(hr && hr.nodeName == 'HR'){
  12038. // var next = hr.nextSibling;
  12039. // if(next){
  12040. // rng.setStart(next,0)
  12041. // }else if(hr.previousSibling){
  12042. // rng.setStartAtLast(hr.previousSibling)
  12043. // }else{
  12044. // var p = this.document.createElement('p');
  12045. // hr.parentNode.insertBefore(p,hr);
  12046. // domUtils.fillNode(this.document,p);
  12047. // rng.setStart(p,0);
  12048. // }
  12049. // domUtils.remove(hr);
  12050. // rng.setCursor(false,true);
  12051. // }
  12052. // }
  12053. // })
  12054. me.addListener('delkeydown',function(name,evt){
  12055. var rng = this.selection.getRange();
  12056. rng.txtToElmBoundary(true);
  12057. if(domUtils.isStartInblock(rng)){
  12058. var tmpNode = rng.startContainer;
  12059. var pre = tmpNode.previousSibling;
  12060. if(pre && domUtils.isTagNode(pre,'hr')){
  12061. domUtils.remove(pre);
  12062. rng.select();
  12063. domUtils.preventDefault(evt);
  12064. return true;
  12065. }
  12066. }
  12067. })
  12068. };
  12069. // plugins/time.js
  12070. /**
  12071. * 插入时间和日期
  12072. * @file
  12073. * @since 1.2.6.1
  12074. */
  12075. /**
  12076. * 插入时间,默认格式:12:59:59
  12077. * @command time
  12078. * @method execCommand
  12079. * @param { String } cmd 命令字符串
  12080. * @example
  12081. * ```javascript
  12082. * editor.execCommand( 'time');
  12083. * ```
  12084. */
  12085. /**
  12086. * 插入日期,默认格式:2013-08-30
  12087. * @command date
  12088. * @method execCommand
  12089. * @param { String } cmd 命令字符串
  12090. * @example
  12091. * ```javascript
  12092. * editor.execCommand( 'date');
  12093. * ```
  12094. */
  12095. UE.commands['time'] = UE.commands["date"] = {
  12096. execCommand : function(cmd, format){
  12097. var date = new Date;
  12098. function formatTime(date, format) {
  12099. var hh = ('0' + date.getHours()).slice(-2),
  12100. ii = ('0' + date.getMinutes()).slice(-2),
  12101. ss = ('0' + date.getSeconds()).slice(-2);
  12102. format = format || 'hh:ii:ss';
  12103. return format.replace(/hh/ig, hh).replace(/ii/ig, ii).replace(/ss/ig, ss);
  12104. }
  12105. function formatDate(date, format) {
  12106. var yyyy = ('000' + date.getFullYear()).slice(-4),
  12107. yy = yyyy.slice(-2),
  12108. mm = ('0' + (date.getMonth()+1)).slice(-2),
  12109. dd = ('0' + date.getDate()).slice(-2);
  12110. format = format || 'yyyy-mm-dd';
  12111. return format.replace(/yyyy/ig, yyyy).replace(/yy/ig, yy).replace(/mm/ig, mm).replace(/dd/ig, dd);
  12112. }
  12113. this.execCommand('insertHtml',cmd == "time" ? formatTime(date, format):formatDate(date, format) );
  12114. }
  12115. };
  12116. // plugins/rowspacing.js
  12117. /**
  12118. * 段前段后间距插件
  12119. * @file
  12120. * @since 1.2.6.1
  12121. */
  12122. /**
  12123. * 设置段间距
  12124. * @command rowspacing
  12125. * @method execCommand
  12126. * @param { String } cmd 命令字符串
  12127. * @param { String } value 段间距的值,以px为单位
  12128. * @param { String } dir 间距位置,top或bottom,分别表示段前和段后
  12129. * @example
  12130. * ```javascript
  12131. * editor.execCommand( 'rowspacing', '10', 'top' );
  12132. * ```
  12133. */
  12134. UE.plugins['rowspacing'] = function(){
  12135. var me = this;
  12136. me.setOpt({
  12137. 'rowspacingtop':['5', '10', '15', '20', '25'],
  12138. 'rowspacingbottom':['5', '10', '15', '20', '25']
  12139. });
  12140. me.commands['rowspacing'] = {
  12141. execCommand : function( cmdName,value,dir ) {
  12142. this.execCommand('paragraph','p',{style:'margin-'+dir+':'+value + 'px'});
  12143. return true;
  12144. },
  12145. queryCommandValue : function(cmdName,dir) {
  12146. var pN = domUtils.filterNodeList(this.selection.getStartElementPath(),function(node){return domUtils.isBlockElm(node) }),
  12147. value;
  12148. //trace:1026
  12149. if(pN){
  12150. value = domUtils.getComputedStyle(pN,'margin-'+dir).replace(/[^\d]/g,'');
  12151. return !value ? 0 : value;
  12152. }
  12153. return 0;
  12154. }
  12155. };
  12156. };
  12157. // plugins/lineheight.js
  12158. /**
  12159. * 设置行内间距
  12160. * @file
  12161. * @since 1.2.6.1
  12162. */
  12163. UE.plugins['lineheight'] = function(){
  12164. var me = this;
  12165. me.setOpt({'lineheight':['1', '1.5','1.75','2', '3', '4', '5']});
  12166. /**
  12167. * 行距
  12168. * @command lineheight
  12169. * @method execCommand
  12170. * @param { String } cmdName 命令字符串
  12171. * @param { String } value 传入的行高值, 该值是当前字体的倍数, 例如: 1.5, 1.75
  12172. * @example
  12173. * ```javascript
  12174. * editor.execCommand( 'lineheight', 1.5);
  12175. * ```
  12176. */
  12177. /**
  12178. * 查询当前选区内容的行高大小
  12179. * @command lineheight
  12180. * @method queryCommandValue
  12181. * @param { String } cmd 命令字符串
  12182. * @return { String } 返回当前行高大小
  12183. * @example
  12184. * ```javascript
  12185. * editor.queryCommandValue( 'lineheight' );
  12186. * ```
  12187. */
  12188. me.commands['lineheight'] = {
  12189. execCommand : function( cmdName,value ) {
  12190. this.execCommand('paragraph','p',{style:'line-height:'+ (value == "1" ? "normal" : value + 'em') });
  12191. return true;
  12192. },
  12193. queryCommandValue : function() {
  12194. var pN = domUtils.filterNodeList(this.selection.getStartElementPath(),function(node){return domUtils.isBlockElm(node)});
  12195. if(pN){
  12196. var value = domUtils.getComputedStyle(pN,'line-height');
  12197. return value == 'normal' ? 1 : value.replace(/[^\d.]*/ig,"");
  12198. }
  12199. }
  12200. };
  12201. };
  12202. // plugins/insertcode.js
  12203. /**
  12204. * 插入代码插件
  12205. * @file
  12206. * @since 1.2.6.1
  12207. */
  12208. UE.plugins['insertcode'] = function() {
  12209. var me = this;
  12210. me.ready(function(){
  12211. utils.cssRule('pre','pre{margin:.5em 0;padding:.4em .6em;border-radius:8px;background:#f8f8f8;}',
  12212. me.document)
  12213. });
  12214. me.setOpt('insertcode',{
  12215. 'as3':'ActionScript3',
  12216. 'bash':'Bash/Shell',
  12217. 'cpp':'C/C++',
  12218. 'css':'Css',
  12219. 'cf':'CodeFunction',
  12220. 'c#':'C#',
  12221. 'delphi':'Delphi',
  12222. 'diff':'Diff',
  12223. 'erlang':'Erlang',
  12224. 'groovy':'Groovy',
  12225. 'html':'Html',
  12226. 'java':'Java',
  12227. 'jfx':'JavaFx',
  12228. 'js':'Javascript',
  12229. 'pl':'Perl',
  12230. 'php':'Php',
  12231. 'plain':'Plain Text',
  12232. 'ps':'PowerShell',
  12233. 'python':'Python',
  12234. 'ruby':'Ruby',
  12235. 'scala':'Scala',
  12236. 'sql':'Sql',
  12237. 'vb':'Vb',
  12238. 'xml':'Xml'
  12239. });
  12240. /**
  12241. * 插入代码
  12242. * @command insertcode
  12243. * @method execCommand
  12244. * @param { String } cmd 命令字符串
  12245. * @param { String } lang 插入代码的语言
  12246. * @example
  12247. * ```javascript
  12248. * editor.execCommand( 'insertcode', 'javascript' );
  12249. * ```
  12250. */
  12251. /**
  12252. * 如果选区所在位置是插入插入代码区域,返回代码的语言
  12253. * @command insertcode
  12254. * @method queryCommandValue
  12255. * @param { String } cmd 命令字符串
  12256. * @return { String } 返回代码的语言
  12257. * @example
  12258. * ```javascript
  12259. * editor.queryCommandValue( 'insertcode' );
  12260. * ```
  12261. */
  12262. me.commands['insertcode'] = {
  12263. execCommand : function(cmd,lang){
  12264. var me = this,
  12265. rng = me.selection.getRange(),
  12266. pre = domUtils.findParentByTagName(rng.startContainer,'pre',true);
  12267. if(pre){
  12268. pre.className = 'brush:'+lang+';toolbar:false;';
  12269. }else{
  12270. var code = '';
  12271. if(rng.collapsed){
  12272. code = browser.ie && browser.ie11below ? (browser.version <= 8 ? '&nbsp;':''):'<br/>';
  12273. }else{
  12274. var frag = rng.extractContents();
  12275. var div = me.document.createElement('div');
  12276. div.appendChild(frag);
  12277. utils.each(UE.filterNode(UE.htmlparser(div.innerHTML.replace(/[\r\t]/g,'')),me.options.filterTxtRules).children,function(node){
  12278. if(browser.ie && browser.ie11below && browser.version > 8){
  12279. if(node.type =='element'){
  12280. if(node.tagName == 'br'){
  12281. code += '\n'
  12282. }else if(!dtd.$empty[node.tagName]){
  12283. utils.each(node.children,function(cn){
  12284. if(cn.type =='element'){
  12285. if(cn.tagName == 'br'){
  12286. code += '\n'
  12287. }else if(!dtd.$empty[node.tagName]){
  12288. code += cn.innerText();
  12289. }
  12290. }else{
  12291. code += cn.data
  12292. }
  12293. })
  12294. if(!/\n$/.test(code)){
  12295. code += '\n';
  12296. }
  12297. }
  12298. }else{
  12299. code += node.data + '\n'
  12300. }
  12301. if(!node.nextSibling() && /\n$/.test(code)){
  12302. code = code.replace(/\n$/,'');
  12303. }
  12304. }else{
  12305. if(browser.ie && browser.ie11below){
  12306. if(node.type =='element'){
  12307. if(node.tagName == 'br'){
  12308. code += '<br>'
  12309. }else if(!dtd.$empty[node.tagName]){
  12310. utils.each(node.children,function(cn){
  12311. if(cn.type =='element'){
  12312. if(cn.tagName == 'br'){
  12313. code += '<br>'
  12314. }else if(!dtd.$empty[node.tagName]){
  12315. code += cn.innerText();
  12316. }
  12317. }else{
  12318. code += cn.data
  12319. }
  12320. });
  12321. if(!/br>$/.test(code)){
  12322. code += '<br>';
  12323. }
  12324. }
  12325. }else{
  12326. code += node.data + '<br>'
  12327. }
  12328. if(!node.nextSibling() && /<br>$/.test(code)){
  12329. code = code.replace(/<br>$/,'');
  12330. }
  12331. }else{
  12332. code += (node.type == 'element' ? (dtd.$empty[node.tagName] ? '' : node.innerText()) : node.data);
  12333. if(!/br\/?\s*>$/.test(code)){
  12334. if(!node.nextSibling())
  12335. return;
  12336. code += '<br>'
  12337. }
  12338. }
  12339. }
  12340. });
  12341. }
  12342. me.execCommand('inserthtml','<pre id="coder"class="brush:'+lang+';toolbar:false">'+code+'</pre>',true);
  12343. pre = me.document.getElementById('coder');
  12344. domUtils.removeAttributes(pre,'id');
  12345. var tmpNode = pre.previousSibling;
  12346. if(tmpNode && (tmpNode.nodeType == 3 && tmpNode.nodeValue.length == 1 && browser.ie && browser.version == 6 || domUtils.isEmptyBlock(tmpNode))){
  12347. domUtils.remove(tmpNode)
  12348. }
  12349. var rng = me.selection.getRange();
  12350. if(domUtils.isEmptyBlock(pre)){
  12351. rng.setStart(pre,0).setCursor(false,true)
  12352. }else{
  12353. rng.selectNodeContents(pre).select()
  12354. }
  12355. }
  12356. },
  12357. queryCommandValue : function(){
  12358. var path = this.selection.getStartElementPath();
  12359. var lang = '';
  12360. utils.each(path,function(node){
  12361. if(node.nodeName =='PRE'){
  12362. var match = node.className.match(/brush:([^;]+)/);
  12363. lang = match && match[1] ? match[1] : '';
  12364. return false;
  12365. }
  12366. });
  12367. return lang;
  12368. }
  12369. };
  12370. me.addInputRule(function(root){
  12371. utils.each(root.getNodesByTagName('pre'),function(pre){
  12372. var brs = pre.getNodesByTagName('br');
  12373. if(brs.length){
  12374. browser.ie && browser.ie11below && browser.version > 8 && utils.each(brs,function(br){
  12375. var txt = UE.uNode.createText('\n');
  12376. br.parentNode.insertBefore(txt,br);
  12377. br.parentNode.removeChild(br);
  12378. });
  12379. return;
  12380. }
  12381. if(browser.ie && browser.ie11below && browser.version > 8)
  12382. return;
  12383. var code = pre.innerText().split(/\n/);
  12384. pre.innerHTML('');
  12385. utils.each(code,function(c){
  12386. if(c.length){
  12387. pre.appendChild(UE.uNode.createText(c));
  12388. }
  12389. pre.appendChild(UE.uNode.createElement('br'))
  12390. })
  12391. })
  12392. });
  12393. me.addOutputRule(function(root){
  12394. utils.each(root.getNodesByTagName('pre'),function(pre){
  12395. var code = '';
  12396. utils.each(pre.children,function(n){
  12397. if(n.type == 'text'){
  12398. //在ie下文本内容有可能末尾带有\n要去掉
  12399. //trace:3396
  12400. code += n.data.replace(/[ ]/g,'&nbsp;').replace(/\n$/,'');
  12401. }else{
  12402. if(n.tagName == 'br'){
  12403. code += '\n'
  12404. }else{
  12405. code += (!dtd.$empty[n.tagName] ? '' : n.innerText());
  12406. }
  12407. }
  12408. });
  12409. pre.innerText(code.replace(/(&nbsp;|\n)+$/,''))
  12410. })
  12411. });
  12412. //不需要判断highlight的command列表
  12413. me.notNeedCodeQuery ={
  12414. help:1,
  12415. undo:1,
  12416. redo:1,
  12417. source:1,
  12418. print:1,
  12419. searchreplace:1,
  12420. fullscreen:1,
  12421. preview:1,
  12422. insertparagraph:1,
  12423. elementpath:1,
  12424. insertcode:1,
  12425. inserthtml:1,
  12426. selectall:1
  12427. };
  12428. //将queyCommamndState重置
  12429. var orgQuery = me.queryCommandState;
  12430. me.queryCommandState = function(cmd){
  12431. var me = this;
  12432. if(!me.notNeedCodeQuery[cmd.toLowerCase()] && me.selection && me.queryCommandValue('insertcode')){
  12433. return -1;
  12434. }
  12435. return UE.Editor.prototype.queryCommandState.apply(this,arguments)
  12436. };
  12437. me.addListener('beforeenterkeydown',function(){
  12438. var rng = me.selection.getRange();
  12439. var pre = domUtils.findParentByTagName(rng.startContainer,'pre',true);
  12440. if(pre){
  12441. me.fireEvent('saveScene');
  12442. if(!rng.collapsed){
  12443. rng.deleteContents();
  12444. }
  12445. if(!browser.ie || browser.ie9above){
  12446. var tmpNode = me.document.createElement('br'),pre;
  12447. rng.insertNode(tmpNode).setStartAfter(tmpNode).collapse(true);
  12448. var next = tmpNode.nextSibling;
  12449. if(!next && (!browser.ie || browser.version > 10)){
  12450. rng.insertNode(tmpNode.cloneNode(false));
  12451. }else{
  12452. rng.setStartAfter(tmpNode);
  12453. }
  12454. pre = tmpNode.previousSibling;
  12455. var tmp;
  12456. while(pre ){
  12457. tmp = pre;
  12458. pre = pre.previousSibling;
  12459. if(!pre || pre.nodeName == 'BR'){
  12460. pre = tmp;
  12461. break;
  12462. }
  12463. }
  12464. if(pre){
  12465. var str = '';
  12466. while(pre && pre.nodeName != 'BR' && new RegExp('^[\\s'+domUtils.fillChar+']*$').test(pre.nodeValue)){
  12467. str += pre.nodeValue;
  12468. pre = pre.nextSibling;
  12469. }
  12470. if(pre.nodeName != 'BR'){
  12471. var match = pre.nodeValue.match(new RegExp('^([\\s'+domUtils.fillChar+']+)'));
  12472. if(match && match[1]){
  12473. str += match[1]
  12474. }
  12475. }
  12476. if(str){
  12477. str = me.document.createTextNode(str);
  12478. rng.insertNode(str).setStartAfter(str);
  12479. }
  12480. }
  12481. rng.collapse(true).select(true);
  12482. }else{
  12483. if(browser.version > 8){
  12484. var txt = me.document.createTextNode('\n');
  12485. var start = rng.startContainer;
  12486. if(rng.startOffset == 0){
  12487. var preNode = start.previousSibling;
  12488. if(preNode){
  12489. rng.insertNode(txt);
  12490. var fillchar = me.document.createTextNode(' ');
  12491. rng.setStartAfter(txt).insertNode(fillchar).setStart(fillchar,0).collapse(true).select(true)
  12492. }
  12493. }else{
  12494. rng.insertNode(txt).setStartAfter(txt);
  12495. var fillchar = me.document.createTextNode(' ');
  12496. start = rng.startContainer.childNodes[rng.startOffset];
  12497. if(start && !/^\n/.test(start.nodeValue)){
  12498. rng.setStartBefore(txt)
  12499. }
  12500. rng.insertNode(fillchar).setStart(fillchar,0).collapse(true).select(true)
  12501. }
  12502. }else{
  12503. var tmpNode = me.document.createElement('br');
  12504. rng.insertNode(tmpNode);
  12505. rng.insertNode(me.document.createTextNode(domUtils.fillChar));
  12506. rng.setStartAfter(tmpNode);
  12507. pre = tmpNode.previousSibling;
  12508. var tmp;
  12509. while(pre ){
  12510. tmp = pre;
  12511. pre = pre.previousSibling;
  12512. if(!pre || pre.nodeName == 'BR'){
  12513. pre = tmp;
  12514. break;
  12515. }
  12516. }
  12517. if(pre){
  12518. var str = '';
  12519. while(pre && pre.nodeName != 'BR' && new RegExp('^[ '+domUtils.fillChar+']*$').test(pre.nodeValue)){
  12520. str += pre.nodeValue;
  12521. pre = pre.nextSibling;
  12522. }
  12523. if(pre.nodeName != 'BR'){
  12524. var match = pre.nodeValue.match(new RegExp('^([ '+domUtils.fillChar+']+)'));
  12525. if(match && match[1]){
  12526. str += match[1]
  12527. }
  12528. }
  12529. str = me.document.createTextNode(str);
  12530. rng.insertNode(str).setStartAfter(str);
  12531. }
  12532. rng.collapse(true).select();
  12533. }
  12534. }
  12535. me.fireEvent('saveScene');
  12536. return true;
  12537. }
  12538. });
  12539. me.addListener('tabkeydown',function(cmd,evt){
  12540. var rng = me.selection.getRange();
  12541. var pre = domUtils.findParentByTagName(rng.startContainer,'pre',true);
  12542. if(pre){
  12543. me.fireEvent('saveScene');
  12544. if(evt.shiftKey){
  12545. }else{
  12546. if(!rng.collapsed){
  12547. var bk = rng.createBookmark();
  12548. var start = bk.start.previousSibling;
  12549. while(start){
  12550. if(pre.firstChild === start && !domUtils.isBr(start)){
  12551. pre.insertBefore(me.document.createTextNode(' '),start);
  12552. break;
  12553. }
  12554. if(domUtils.isBr(start)){
  12555. pre.insertBefore(me.document.createTextNode(' '),start.nextSibling);
  12556. break;
  12557. }
  12558. start = start.previousSibling;
  12559. }
  12560. var end = bk.end;
  12561. start = bk.start.nextSibling;
  12562. if(pre.firstChild === bk.start){
  12563. pre.insertBefore(me.document.createTextNode(' '),start.nextSibling)
  12564. }
  12565. while(start && start !== end){
  12566. if(domUtils.isBr(start) && start.nextSibling){
  12567. if(start.nextSibling === end){
  12568. break;
  12569. }
  12570. pre.insertBefore(me.document.createTextNode(' '),start.nextSibling)
  12571. }
  12572. start = start.nextSibling;
  12573. }
  12574. rng.moveToBookmark(bk).select();
  12575. }else{
  12576. var tmpNode = me.document.createTextNode(' ');
  12577. rng.insertNode(tmpNode).setStartAfter(tmpNode).collapse(true).select(true);
  12578. }
  12579. }
  12580. me.fireEvent('saveScene');
  12581. return true;
  12582. }
  12583. });
  12584. me.addListener('beforeinserthtml',function(evtName,html){
  12585. var me = this,
  12586. rng = me.selection.getRange(),
  12587. pre = domUtils.findParentByTagName(rng.startContainer,'pre',true);
  12588. if(pre){
  12589. if(!rng.collapsed){
  12590. rng.deleteContents()
  12591. }
  12592. var htmlstr = '';
  12593. if(browser.ie && browser.version > 8){
  12594. utils.each(UE.filterNode(UE.htmlparser(html),me.options.filterTxtRules).children,function(node){
  12595. if(node.type =='element'){
  12596. if(node.tagName == 'br'){
  12597. htmlstr += '\n'
  12598. }else if(!dtd.$empty[node.tagName]){
  12599. utils.each(node.children,function(cn){
  12600. if(cn.type =='element'){
  12601. if(cn.tagName == 'br'){
  12602. htmlstr += '\n'
  12603. }else if(!dtd.$empty[node.tagName]){
  12604. htmlstr += cn.innerText();
  12605. }
  12606. }else{
  12607. htmlstr += cn.data
  12608. }
  12609. })
  12610. if(!/\n$/.test(htmlstr)){
  12611. htmlstr += '\n';
  12612. }
  12613. }
  12614. }else{
  12615. htmlstr += node.data + '\n'
  12616. }
  12617. if(!node.nextSibling() && /\n$/.test(htmlstr)){
  12618. htmlstr = htmlstr.replace(/\n$/,'');
  12619. }
  12620. });
  12621. var tmpNode = me.document.createTextNode(utils.html(htmlstr.replace(/&nbsp;/g,' ')));
  12622. rng.insertNode(tmpNode).selectNode(tmpNode).select();
  12623. }else{
  12624. var frag = me.document.createDocumentFragment();
  12625. utils.each(UE.filterNode(UE.htmlparser(html),me.options.filterTxtRules).children,function(node){
  12626. if(node.type =='element'){
  12627. if(node.tagName == 'br'){
  12628. frag.appendChild(me.document.createElement('br'))
  12629. }else if(!dtd.$empty[node.tagName]){
  12630. utils.each(node.children,function(cn){
  12631. if(cn.type =='element'){
  12632. if(cn.tagName == 'br'){
  12633. frag.appendChild(me.document.createElement('br'))
  12634. }else if(!dtd.$empty[node.tagName]){
  12635. frag.appendChild(me.document.createTextNode(utils.html(cn.innerText().replace(/&nbsp;/g,' '))));
  12636. }
  12637. }else{
  12638. frag.appendChild(me.document.createTextNode(utils.html( cn.data.replace(/&nbsp;/g,' '))));
  12639. }
  12640. })
  12641. if(frag.lastChild.nodeName != 'BR'){
  12642. frag.appendChild(me.document.createElement('br'))
  12643. }
  12644. }
  12645. }else{
  12646. frag.appendChild(me.document.createTextNode(utils.html( node.data.replace(/&nbsp;/g,' '))));
  12647. }
  12648. if(!node.nextSibling() && frag.lastChild.nodeName == 'BR'){
  12649. frag.removeChild(frag.lastChild)
  12650. }
  12651. });
  12652. rng.insertNode(frag).select();
  12653. }
  12654. return true;
  12655. }
  12656. });
  12657. //方向键的处理
  12658. me.addListener('keydown',function(cmd,evt){
  12659. var me = this,keyCode = evt.keyCode || evt.which;
  12660. if(keyCode == 40){
  12661. var rng = me.selection.getRange(),pre,start = rng.startContainer;
  12662. if(rng.collapsed && (pre = domUtils.findParentByTagName(rng.startContainer,'pre',true)) && !pre.nextSibling){
  12663. var last = pre.lastChild
  12664. while(last && last.nodeName == 'BR'){
  12665. last = last.previousSibling;
  12666. }
  12667. if(last === start || rng.startContainer === pre && rng.startOffset == pre.childNodes.length){
  12668. me.execCommand('insertparagraph');
  12669. domUtils.preventDefault(evt)
  12670. }
  12671. }
  12672. }
  12673. });
  12674. //trace:3395
  12675. me.addListener('delkeydown',function(type,evt){
  12676. var rng = this.selection.getRange();
  12677. rng.txtToElmBoundary(true);
  12678. var start = rng.startContainer;
  12679. if(domUtils.isTagNode(start,'pre') && rng.collapsed && domUtils.isStartInblock(rng)){
  12680. var p = me.document.createElement('p');
  12681. domUtils.fillNode(me.document,p);
  12682. start.parentNode.insertBefore(p,start);
  12683. domUtils.remove(start);
  12684. rng.setStart(p,0).setCursor(false,true);
  12685. domUtils.preventDefault(evt);
  12686. return true;
  12687. }
  12688. })
  12689. };
  12690. // plugins/cleardoc.js
  12691. /**
  12692. * 清空文档插件
  12693. * @file
  12694. * @since 1.2.6.1
  12695. */
  12696. /**
  12697. * 清空文档
  12698. * @command cleardoc
  12699. * @method execCommand
  12700. * @param { String } cmd 命令字符串
  12701. * @example
  12702. * ```javascript
  12703. * //editor 是编辑器实例
  12704. * editor.execCommand('cleardoc');
  12705. * ```
  12706. */
  12707. UE.commands['cleardoc'] = {
  12708. execCommand : function( cmdName) {
  12709. var me = this,
  12710. enterTag = me.options.enterTag,
  12711. range = me.selection.getRange();
  12712. if(enterTag == "br"){
  12713. me.body.innerHTML = "<br/>";
  12714. range.setStart(me.body,0).setCursor();
  12715. }else{
  12716. me.body.innerHTML = "<p>"+(ie ? "" : "<br/>")+"</p>";
  12717. range.setStart(me.body.firstChild,0).setCursor(false,true);
  12718. }
  12719. setTimeout(function(){
  12720. me.fireEvent("clearDoc");
  12721. },0);
  12722. }
  12723. };
  12724. // plugins/anchor.js
  12725. /**
  12726. * 锚点插件,为UEditor提供插入锚点支持
  12727. * @file
  12728. * @since 1.2.6.1
  12729. */
  12730. UE.plugin.register('anchor', function (){
  12731. return {
  12732. bindEvents:{
  12733. 'ready':function(){
  12734. utils.cssRule('anchor',
  12735. '.anchorclass{background: url(\''
  12736. + this.options.themePath
  12737. + this.options.theme +'/images/anchor.gif\') no-repeat scroll left center transparent;cursor: auto;display: inline-block;height: 16px;width: 15px;}',
  12738. this.document);
  12739. }
  12740. },
  12741. outputRule: function(root){
  12742. utils.each(root.getNodesByTagName('img'),function(a){
  12743. var val;
  12744. if(val = a.getAttr('anchorname')){
  12745. a.tagName = 'a';
  12746. a.setAttr({
  12747. anchorname : '',
  12748. name : val,
  12749. 'class' : ''
  12750. })
  12751. }
  12752. })
  12753. },
  12754. inputRule:function(root){
  12755. utils.each(root.getNodesByTagName('a'),function(a){
  12756. var val;
  12757. if((val = a.getAttr('name')) && !a.getAttr('href')){
  12758. a.tagName = 'img';
  12759. a.setAttr({
  12760. anchorname :a.getAttr('name'),
  12761. 'class' : 'anchorclass'
  12762. });
  12763. a.setAttr('name')
  12764. }
  12765. })
  12766. },
  12767. commands:{
  12768. /**
  12769. * 插入锚点
  12770. * @command anchor
  12771. * @method execCommand
  12772. * @param { String } cmd 命令字符串
  12773. * @param { String } name 锚点名称字符串
  12774. * @example
  12775. * ```javascript
  12776. * //editor 是编辑器实例
  12777. * editor.execCommand('anchor', 'anchor1');
  12778. * ```
  12779. */
  12780. 'anchor':{
  12781. execCommand:function (cmd, name) {
  12782. var range = this.selection.getRange(),img = range.getClosedNode();
  12783. if (img && img.getAttribute('anchorname')) {
  12784. if (name) {
  12785. img.setAttribute('anchorname', name);
  12786. } else {
  12787. range.setStartBefore(img).setCursor();
  12788. domUtils.remove(img);
  12789. }
  12790. } else {
  12791. if (name) {
  12792. //只在选区的开始插入
  12793. var anchor = this.document.createElement('img');
  12794. range.collapse(true);
  12795. domUtils.setAttributes(anchor,{
  12796. 'anchorname':name,
  12797. 'class':'anchorclass'
  12798. });
  12799. range.insertNode(anchor).setStartAfter(anchor).setCursor(false,true);
  12800. }
  12801. }
  12802. }
  12803. }
  12804. }
  12805. }
  12806. });
  12807. // plugins/wordcount.js
  12808. ///import core
  12809. ///commands 字数统计
  12810. ///commandsName WordCount,wordCount
  12811. ///commandsTitle 字数统计
  12812. /*
  12813. * Created by JetBrains WebStorm.
  12814. * User: taoqili
  12815. * Date: 11-9-7
  12816. * Time: 下午8:18
  12817. * To change this template use File | Settings | File Templates.
  12818. */
  12819. UE.plugins['wordcount'] = function(){
  12820. var me = this;
  12821. me.setOpt('wordCount',true);
  12822. me.addListener('contentchange',function(){
  12823. me.fireEvent('wordcount');
  12824. });
  12825. var timer;
  12826. me.addListener('ready',function(){
  12827. var me = this;
  12828. domUtils.on(me.body,"keyup",function(evt){
  12829. var code = evt.keyCode||evt.which,
  12830. //忽略的按键,ctr,alt,shift,方向键
  12831. ignores = {"16":1,"18":1,"20":1,"37":1,"38":1,"39":1,"40":1};
  12832. if(code in ignores) return;
  12833. clearTimeout(timer);
  12834. timer = setTimeout(function(){
  12835. me.fireEvent('wordcount');
  12836. },200)
  12837. })
  12838. });
  12839. };
  12840. // plugins/pagebreak.js
  12841. /**
  12842. * 分页功能插件
  12843. * @file
  12844. * @since 1.2.6.1
  12845. */
  12846. UE.plugins['pagebreak'] = function () {
  12847. var me = this,
  12848. notBreakTags = ['td'];
  12849. me.setOpt('pageBreakTag','_ueditor_page_break_tag_');
  12850. function fillNode(node){
  12851. if(domUtils.isEmptyBlock(node)){
  12852. var firstChild = node.firstChild,tmpNode;
  12853. while(firstChild && firstChild.nodeType == 1 && domUtils.isEmptyBlock(firstChild)){
  12854. tmpNode = firstChild;
  12855. firstChild = firstChild.firstChild;
  12856. }
  12857. !tmpNode && (tmpNode = node);
  12858. domUtils.fillNode(me.document,tmpNode);
  12859. }
  12860. }
  12861. //分页符样式添加
  12862. me.ready(function(){
  12863. utils.cssRule('pagebreak','.pagebreak{display:block;clear:both !important;cursor:default !important;width: 100% !important;margin:0;}',me.document);
  12864. });
  12865. function isHr(node){
  12866. return node && node.nodeType == 1 && node.tagName == 'HR' && node.className == 'pagebreak';
  12867. }
  12868. me.addInputRule(function(root){
  12869. root.traversal(function(node){
  12870. if(node.type == 'text' && node.data == me.options.pageBreakTag){
  12871. var hr = UE.uNode.createElement('<hr class="pagebreak" noshade="noshade" size="5" style="-webkit-user-select: none;">');
  12872. node.parentNode.insertBefore(hr,node);
  12873. node.parentNode.removeChild(node)
  12874. }
  12875. })
  12876. });
  12877. me.addOutputRule(function(node){
  12878. utils.each(node.getNodesByTagName('hr'),function(n){
  12879. if(n.getAttr('class') == 'pagebreak'){
  12880. var txt = UE.uNode.createText(me.options.pageBreakTag);
  12881. n.parentNode.insertBefore(txt,n);
  12882. n.parentNode.removeChild(n);
  12883. }
  12884. })
  12885. });
  12886. /**
  12887. * 插入分页符
  12888. * @command pagebreak
  12889. * @method execCommand
  12890. * @param { String } cmd 命令字符串
  12891. * @remind 在表格中插入分页符会把表格切分成两部分
  12892. * @remind 获取编辑器内的数据时, 编辑器会把分页符转换成“_ueditor_page_break_tag_”字符串,
  12893. * 以便于提交数据到服务器端后处理分页。
  12894. * @example
  12895. * ```javascript
  12896. * editor.execCommand( 'pagebreak'); //插入一个hr标签,带有样式类名pagebreak
  12897. * ```
  12898. */
  12899. me.commands['pagebreak'] = {
  12900. execCommand:function () {
  12901. var range = me.selection.getRange(),hr = me.document.createElement('hr');
  12902. domUtils.setAttributes(hr,{
  12903. 'class' : 'pagebreak',
  12904. noshade:"noshade",
  12905. size:"5"
  12906. });
  12907. domUtils.unSelectable(hr);
  12908. //table单独处理
  12909. var node = domUtils.findParentByTagName(range.startContainer, notBreakTags, true),
  12910. parents = [], pN;
  12911. if (node) {
  12912. switch (node.tagName) {
  12913. case 'TD':
  12914. pN = node.parentNode;
  12915. if (!pN.previousSibling) {
  12916. var table = domUtils.findParentByTagName(pN, 'table');
  12917. // var tableWrapDiv = table.parentNode;
  12918. // if(tableWrapDiv && tableWrapDiv.nodeType == 1
  12919. // && tableWrapDiv.tagName == 'DIV'
  12920. // && tableWrapDiv.getAttribute('dropdrag')
  12921. // ){
  12922. // domUtils.remove(tableWrapDiv,true);
  12923. // }
  12924. table.parentNode.insertBefore(hr, table);
  12925. parents = domUtils.findParents(hr, true);
  12926. } else {
  12927. pN.parentNode.insertBefore(hr, pN);
  12928. parents = domUtils.findParents(hr);
  12929. }
  12930. pN = parents[1];
  12931. if (hr !== pN) {
  12932. domUtils.breakParent(hr, pN);
  12933. }
  12934. //table要重写绑定一下拖拽
  12935. me.fireEvent('afteradjusttable',me.document);
  12936. }
  12937. } else {
  12938. if (!range.collapsed) {
  12939. range.deleteContents();
  12940. var start = range.startContainer;
  12941. while ( !domUtils.isBody(start) && domUtils.isBlockElm(start) && domUtils.isEmptyNode(start)) {
  12942. range.setStartBefore(start).collapse(true);
  12943. domUtils.remove(start);
  12944. start = range.startContainer;
  12945. }
  12946. }
  12947. range.insertNode(hr);
  12948. var pN = hr.parentNode, nextNode;
  12949. while (!domUtils.isBody(pN)) {
  12950. domUtils.breakParent(hr, pN);
  12951. nextNode = hr.nextSibling;
  12952. if (nextNode && domUtils.isEmptyBlock(nextNode)) {
  12953. domUtils.remove(nextNode);
  12954. }
  12955. pN = hr.parentNode;
  12956. }
  12957. nextNode = hr.nextSibling;
  12958. var pre = hr.previousSibling;
  12959. if(isHr(pre)){
  12960. domUtils.remove(pre);
  12961. }else{
  12962. pre && fillNode(pre);
  12963. }
  12964. if(!nextNode){
  12965. var p = me.document.createElement('p');
  12966. hr.parentNode.appendChild(p);
  12967. domUtils.fillNode(me.document,p);
  12968. range.setStart(p,0).collapse(true);
  12969. }else{
  12970. if(isHr(nextNode)){
  12971. domUtils.remove(nextNode);
  12972. }else{
  12973. fillNode(nextNode);
  12974. }
  12975. range.setEndAfter(hr).collapse(false);
  12976. }
  12977. range.select(true);
  12978. }
  12979. }
  12980. };
  12981. };
  12982. // plugins/wordimage.js
  12983. ///import core
  12984. ///commands 本地图片引导上传
  12985. ///commandsName WordImage
  12986. ///commandsTitle 本地图片引导上传
  12987. ///commandsDialog dialogs\wordimage
  12988. UE.plugin.register('wordimage',function(){
  12989. var me = this,
  12990. images = [];
  12991. return {
  12992. commands : {
  12993. 'wordimage':{
  12994. execCommand:function () {
  12995. var images = domUtils.getElementsByTagName(me.body, "img");
  12996. var urlList = [];
  12997. for (var i = 0, ci; ci = images[i++];) {
  12998. var url = ci.getAttribute("word_img");
  12999. url && urlList.push(url);
  13000. }
  13001. return urlList;
  13002. },
  13003. queryCommandState:function () {
  13004. images = domUtils.getElementsByTagName(me.body, "img");
  13005. for (var i = 0, ci; ci = images[i++];) {
  13006. if (ci.getAttribute("word_img")) {
  13007. return 1;
  13008. }
  13009. }
  13010. return -1;
  13011. },
  13012. notNeedUndo:true
  13013. }
  13014. },
  13015. inputRule : function (root) {
  13016. utils.each(root.getNodesByTagName('img'), function (img) {
  13017. var attrs = img.attrs,
  13018. flag = parseInt(attrs.width) < 128 || parseInt(attrs.height) < 43,
  13019. opt = me.options,
  13020. src = opt.UEDITOR_HOME_URL + 'themes/default/images/spacer.gif';
  13021. if (attrs['src'] && /^(?:(file:\/+))/.test(attrs['src'])) {
  13022. img.setAttr({
  13023. width:attrs.width,
  13024. height:attrs.height,
  13025. alt:attrs.alt,
  13026. word_img: attrs.src,
  13027. src:src,
  13028. 'style':'background:url(' + ( flag ? opt.themePath + opt.theme + '/images/word.gif' : opt.langPath + opt.lang + '/images/localimage.png') + ') no-repeat center center;border:1px solid #ddd'
  13029. })
  13030. }
  13031. })
  13032. }
  13033. }
  13034. });
  13035. // plugins/dragdrop.js
  13036. UE.plugins['dragdrop'] = function (){
  13037. var me = this;
  13038. me.ready(function(){
  13039. domUtils.on(this.body,'dragend',function(){
  13040. var rng = me.selection.getRange();
  13041. var node = rng.getClosedNode()||me.selection.getStart();
  13042. if(node && node.tagName == 'IMG'){
  13043. var pre = node.previousSibling,next;
  13044. while(next = node.nextSibling){
  13045. if(next.nodeType == 1 && next.tagName == 'SPAN' && !next.firstChild){
  13046. domUtils.remove(next)
  13047. }else{
  13048. break;
  13049. }
  13050. }
  13051. if((pre && pre.nodeType == 1 && !domUtils.isEmptyBlock(pre) || !pre) && (!next || next && !domUtils.isEmptyBlock(next))){
  13052. if(pre && pre.tagName == 'P' && !domUtils.isEmptyBlock(pre)){
  13053. pre.appendChild(node);
  13054. domUtils.moveChild(next,pre);
  13055. domUtils.remove(next);
  13056. }else if(next && next.tagName == 'P' && !domUtils.isEmptyBlock(next)){
  13057. next.insertBefore(node,next.firstChild);
  13058. }
  13059. if(pre && pre.tagName == 'P' && domUtils.isEmptyBlock(pre)){
  13060. domUtils.remove(pre)
  13061. }
  13062. if(next && next.tagName == 'P' && domUtils.isEmptyBlock(next)){
  13063. domUtils.remove(next)
  13064. }
  13065. rng.selectNode(node).select();
  13066. me.fireEvent('saveScene');
  13067. }
  13068. }
  13069. })
  13070. });
  13071. me.addListener('keyup', function(type, evt) {
  13072. var keyCode = evt.keyCode || evt.which;
  13073. if (keyCode == 13) {
  13074. var rng = me.selection.getRange(),node;
  13075. if(node = domUtils.findParentByTagName(rng.startContainer,'p',true)){
  13076. if(domUtils.getComputedStyle(node,'text-align') == 'center'){
  13077. domUtils.removeStyle(node,'text-align')
  13078. }
  13079. }
  13080. }
  13081. })
  13082. };
  13083. // plugins/undo.js
  13084. /**
  13085. * undo redo
  13086. * @file
  13087. * @since 1.2.6.1
  13088. */
  13089. /**
  13090. * 撤销上一次执行的命令
  13091. * @command undo
  13092. * @method execCommand
  13093. * @param { String } cmd 命令字符串
  13094. * @example
  13095. * ```javascript
  13096. * editor.execCommand( 'undo' );
  13097. * ```
  13098. */
  13099. /**
  13100. * 重做上一次执行的命令
  13101. * @command redo
  13102. * @method execCommand
  13103. * @param { String } cmd 命令字符串
  13104. * @example
  13105. * ```javascript
  13106. * editor.execCommand( 'redo' );
  13107. * ```
  13108. */
  13109. UE.plugins['undo'] = function () {
  13110. var saveSceneTimer;
  13111. var me = this,
  13112. maxUndoCount = me.options.maxUndoCount || 20,
  13113. maxInputCount = me.options.maxInputCount || 20,
  13114. fillchar = new RegExp(domUtils.fillChar + '|<\/hr>', 'gi');// ie会产生多余的</hr>
  13115. var noNeedFillCharTags = {
  13116. ol:1,ul:1,table:1,tbody:1,tr:1,body:1
  13117. };
  13118. var orgState = me.options.autoClearEmptyNode;
  13119. function compareAddr(indexA, indexB) {
  13120. if (indexA.length != indexB.length)
  13121. return 0;
  13122. for (var i = 0, l = indexA.length; i < l; i++) {
  13123. if (indexA[i] != indexB[i])
  13124. return 0
  13125. }
  13126. return 1;
  13127. }
  13128. function compareRangeAddress(rngAddrA, rngAddrB) {
  13129. if (rngAddrA.collapsed != rngAddrB.collapsed) {
  13130. return 0;
  13131. }
  13132. if (!compareAddr(rngAddrA.startAddress, rngAddrB.startAddress) || !compareAddr(rngAddrA.endAddress, rngAddrB.endAddress)) {
  13133. return 0;
  13134. }
  13135. return 1;
  13136. }
  13137. function UndoManager() {
  13138. this.list = [];
  13139. this.index = 0;
  13140. this.hasUndo = false;
  13141. this.hasRedo = false;
  13142. this.undo = function () {
  13143. if (this.hasUndo) {
  13144. if (!this.list[this.index - 1] && this.list.length == 1) {
  13145. this.reset();
  13146. return;
  13147. }
  13148. while (this.list[this.index].content == this.list[this.index - 1].content) {
  13149. this.index--;
  13150. if (this.index == 0) {
  13151. return this.restore(0);
  13152. }
  13153. }
  13154. this.restore(--this.index);
  13155. }
  13156. };
  13157. this.redo = function () {
  13158. if (this.hasRedo) {
  13159. while (this.list[this.index].content == this.list[this.index + 1].content) {
  13160. this.index++;
  13161. if (this.index == this.list.length - 1) {
  13162. return this.restore(this.index);
  13163. }
  13164. }
  13165. this.restore(++this.index);
  13166. }
  13167. };
  13168. this.restore = function () {
  13169. var me = this.editor;
  13170. var scene = this.list[this.index];
  13171. var root = UE.htmlparser(scene.content.replace(fillchar, ''));
  13172. me.options.autoClearEmptyNode = false;
  13173. me.filterInputRule(root);
  13174. me.options.autoClearEmptyNode = orgState;
  13175. //trace:873
  13176. //去掉展位符
  13177. me.document.body.innerHTML = root.toHtml();
  13178. me.fireEvent('afterscencerestore');
  13179. //处理undo后空格不展位的问题
  13180. if (browser.ie) {
  13181. utils.each(domUtils.getElementsByTagName(me.document,'td th caption p'),function(node){
  13182. if(domUtils.isEmptyNode(node)){
  13183. domUtils.fillNode(me.document, node);
  13184. }
  13185. })
  13186. }
  13187. try{
  13188. var rng = new dom.Range(me.document).moveToAddress(scene.address);
  13189. rng.select(noNeedFillCharTags[rng.startContainer.nodeName.toLowerCase()]);
  13190. }catch(e){}
  13191. this.update();
  13192. this.clearKey();
  13193. //不能把自己reset了
  13194. me.fireEvent('reset', true);
  13195. };
  13196. this.getScene = function () {
  13197. var me = this.editor;
  13198. var rng = me.selection.getRange(),
  13199. rngAddress = rng.createAddress(false,true);
  13200. me.fireEvent('beforegetscene');
  13201. var root = UE.htmlparser(me.body.innerHTML);
  13202. me.options.autoClearEmptyNode = false;
  13203. me.filterOutputRule(root);
  13204. me.options.autoClearEmptyNode = orgState;
  13205. var cont = root.toHtml();
  13206. //trace:3461
  13207. //这个会引起回退时导致空格丢失的情况
  13208. // browser.ie && (cont = cont.replace(/>&nbsp;</g, '><').replace(/\s*</g, '<').replace(/>\s*/g, '>'));
  13209. me.fireEvent('aftergetscene');
  13210. return {
  13211. address:rngAddress,
  13212. content:cont
  13213. }
  13214. };
  13215. this.save = function (notCompareRange,notSetCursor) {
  13216. clearTimeout(saveSceneTimer);
  13217. var currentScene = this.getScene(notSetCursor),
  13218. lastScene = this.list[this.index];
  13219. if(lastScene && lastScene.content != currentScene.content){
  13220. me.trigger('contentchange')
  13221. }
  13222. //内容相同位置相同不存
  13223. if (lastScene && lastScene.content == currentScene.content &&
  13224. ( notCompareRange ? 1 : compareRangeAddress(lastScene.address, currentScene.address) )
  13225. ) {
  13226. return;
  13227. }
  13228. this.list = this.list.slice(0, this.index + 1);
  13229. this.list.push(currentScene);
  13230. //如果大于最大数量了,就把最前的剔除
  13231. if (this.list.length > maxUndoCount) {
  13232. this.list.shift();
  13233. }
  13234. this.index = this.list.length - 1;
  13235. this.clearKey();
  13236. //跟新undo/redo状态
  13237. this.update();
  13238. };
  13239. this.update = function () {
  13240. this.hasRedo = !!this.list[this.index + 1];
  13241. this.hasUndo = !!this.list[this.index - 1];
  13242. };
  13243. this.reset = function () {
  13244. this.list = [];
  13245. this.index = 0;
  13246. this.hasUndo = false;
  13247. this.hasRedo = false;
  13248. this.clearKey();
  13249. };
  13250. this.clearKey = function () {
  13251. keycont = 0;
  13252. lastKeyCode = null;
  13253. };
  13254. }
  13255. me.undoManger = new UndoManager();
  13256. me.undoManger.editor = me;
  13257. function saveScene() {
  13258. this.undoManger.save();
  13259. }
  13260. me.addListener('saveScene', function () {
  13261. var args = Array.prototype.splice.call(arguments,1);
  13262. this.undoManger.save.apply(this.undoManger,args);
  13263. });
  13264. // me.addListener('beforeexeccommand', saveScene);
  13265. // me.addListener('afterexeccommand', saveScene);
  13266. me.addListener('reset', function (type, exclude) {
  13267. if (!exclude) {
  13268. this.undoManger.reset();
  13269. }
  13270. });
  13271. me.commands['redo'] = me.commands['undo'] = {
  13272. execCommand:function (cmdName) {
  13273. this.undoManger[cmdName]();
  13274. },
  13275. queryCommandState:function (cmdName) {
  13276. return this.undoManger['has' + (cmdName.toLowerCase() == 'undo' ? 'Undo' : 'Redo')] ? 0 : -1;
  13277. },
  13278. notNeedUndo:1
  13279. };
  13280. var keys = {
  13281. // /*Backspace*/ 8:1, /*Delete*/ 46:1,
  13282. /*Shift*/ 16:1, /*Ctrl*/ 17:1, /*Alt*/ 18:1,
  13283. 37:1, 38:1, 39:1, 40:1
  13284. },
  13285. keycont = 0,
  13286. lastKeyCode;
  13287. //输入法状态下不计算字符数
  13288. var inputType = false;
  13289. me.addListener('ready', function () {
  13290. domUtils.on(this.body, 'compositionstart', function () {
  13291. inputType = true;
  13292. });
  13293. domUtils.on(this.body, 'compositionend', function () {
  13294. inputType = false;
  13295. })
  13296. });
  13297. //快捷键
  13298. me.addshortcutkey({
  13299. "Undo":"ctrl+90", //undo
  13300. "Redo":"ctrl+89" //redo
  13301. });
  13302. var isCollapsed = true;
  13303. me.addListener('keydown', function (type, evt) {
  13304. var me = this;
  13305. var keyCode = evt.keyCode || evt.which;
  13306. if (!keys[keyCode] && !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) {
  13307. if (inputType)
  13308. return;
  13309. if(!me.selection.getRange().collapsed){
  13310. me.undoManger.save(false,true);
  13311. isCollapsed = false;
  13312. return;
  13313. }
  13314. if (me.undoManger.list.length == 0) {
  13315. me.undoManger.save(true);
  13316. }
  13317. clearTimeout(saveSceneTimer);
  13318. function save(cont){
  13319. cont.undoManger.save(false,true);
  13320. cont.fireEvent('selectionchange');
  13321. }
  13322. saveSceneTimer = setTimeout(function(){
  13323. if(inputType){
  13324. var interalTimer = setInterval(function(){
  13325. if(!inputType){
  13326. save(me);
  13327. clearInterval(interalTimer)
  13328. }
  13329. },300)
  13330. return;
  13331. }
  13332. save(me);
  13333. },200);
  13334. lastKeyCode = keyCode;
  13335. keycont++;
  13336. if (keycont >= maxInputCount ) {
  13337. save(me)
  13338. }
  13339. }
  13340. });
  13341. me.addListener('keyup', function (type, evt) {
  13342. var keyCode = evt.keyCode || evt.which;
  13343. if (!keys[keyCode] && !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) {
  13344. if (inputType)
  13345. return;
  13346. if(!isCollapsed){
  13347. this.undoManger.save(false,true);
  13348. isCollapsed = true;
  13349. }
  13350. }
  13351. });
  13352. //扩展实例,添加关闭和开启命令undo
  13353. me.stopCmdUndo = function(){
  13354. me.__hasEnterExecCommand = true;
  13355. };
  13356. me.startCmdUndo = function(){
  13357. me.__hasEnterExecCommand = false;
  13358. }
  13359. };
  13360. // plugins/copy.js
  13361. UE.plugin.register('copy', function () {
  13362. var me = this;
  13363. function initZeroClipboard() {
  13364. ZeroClipboard.config({
  13365. debug: false,
  13366. swfPath: me.options.UEDITOR_HOME_URL + 'third-party/zeroclipboard/ZeroClipboard.swf'
  13367. });
  13368. var client = me.zeroclipboard = new ZeroClipboard();
  13369. // 复制内容
  13370. client.on('copy', function (e) {
  13371. var client = e.client,
  13372. rng = me.selection.getRange(),
  13373. div = document.createElement('div');
  13374. div.appendChild(rng.cloneContents());
  13375. client.setText(div.innerText || div.textContent);
  13376. client.setHtml(div.innerHTML);
  13377. rng.select();
  13378. });
  13379. // hover事件传递到target
  13380. client.on('mouseover mouseout', function (e) {
  13381. var target = e.target;
  13382. if (e.type == 'mouseover') {
  13383. domUtils.addClass(target, 'edui-state-hover');
  13384. } else if (e.type == 'mouseout') {
  13385. domUtils.removeClasses(target, 'edui-state-hover');
  13386. }
  13387. });
  13388. // flash加载不成功
  13389. client.on('wrongflash noflash', function () {
  13390. ZeroClipboard.destroy();
  13391. });
  13392. }
  13393. return {
  13394. bindEvents: {
  13395. 'ready': function () {
  13396. if (!browser.ie) {
  13397. if (window.ZeroClipboard) {
  13398. initZeroClipboard();
  13399. } else {
  13400. utils.loadFile(document, {
  13401. src: me.options.UEDITOR_HOME_URL + "third-party/zeroclipboard/ZeroClipboard.js",
  13402. tag: "script",
  13403. type: "text/javascript",
  13404. defer: "defer"
  13405. }, function () {
  13406. initZeroClipboard();
  13407. });
  13408. }
  13409. }
  13410. }
  13411. },
  13412. commands: {
  13413. 'copy': {
  13414. execCommand: function (cmd) {
  13415. if (!me.document.execCommand('copy')) {
  13416. alert(me.getLang('copymsg'));
  13417. }
  13418. }
  13419. }
  13420. }
  13421. }
  13422. });
  13423. // plugins/paste.js
  13424. ///import core
  13425. ///import plugins/inserthtml.js
  13426. ///import plugins/undo.js
  13427. ///import plugins/serialize.js
  13428. ///commands 粘贴
  13429. ///commandsName PastePlain
  13430. ///commandsTitle 纯文本粘贴模式
  13431. /**
  13432. * @description 粘贴
  13433. * @author zhanyi
  13434. */
  13435. UE.plugins['paste'] = function () {
  13436. function getClipboardData(callback) {
  13437. var doc = this.document;
  13438. if (doc.getElementById('baidu_pastebin')) {
  13439. return;
  13440. }
  13441. var range = this.selection.getRange(),
  13442. bk = range.createBookmark(),
  13443. //创建剪贴的容器div
  13444. pastebin = doc.createElement('div');
  13445. pastebin.id = 'baidu_pastebin';
  13446. // Safari 要求div必须有内容,才能粘贴内容进来
  13447. browser.webkit && pastebin.appendChild(doc.createTextNode(domUtils.fillChar + domUtils.fillChar));
  13448. doc.body.appendChild(pastebin);
  13449. //trace:717 隐藏的span不能得到top
  13450. //bk.start.innerHTML = '&nbsp;';
  13451. bk.start.style.display = '';
  13452. pastebin.style.cssText = "position:absolute;width:1px;height:1px;overflow:hidden;left:-1000px;white-space:nowrap;top:" +
  13453. //要在现在光标平行的位置加入,否则会出现跳动的问题
  13454. domUtils.getXY(bk.start).y + 'px';
  13455. range.selectNodeContents(pastebin).select(true);
  13456. setTimeout(function () {
  13457. if (browser.webkit) {
  13458. for (var i = 0, pastebins = doc.querySelectorAll('#baidu_pastebin'), pi; pi = pastebins[i++];) {
  13459. if (domUtils.isEmptyNode(pi)) {
  13460. domUtils.remove(pi);
  13461. } else {
  13462. pastebin = pi;
  13463. break;
  13464. }
  13465. }
  13466. }
  13467. try {
  13468. pastebin.parentNode.removeChild(pastebin);
  13469. } catch (e) {
  13470. }
  13471. range.moveToBookmark(bk).select(true);
  13472. callback(pastebin);
  13473. }, 0);
  13474. }
  13475. var me = this;
  13476. me.setOpt({
  13477. retainOnlyLabelPasted : false
  13478. });
  13479. var txtContent, htmlContent, address;
  13480. function getPureHtml(html){
  13481. return html.replace(/<(\/?)([\w\-]+)([^>]*)>/gi, function (a, b, tagName, attrs) {
  13482. tagName = tagName.toLowerCase();
  13483. if ({img: 1}[tagName]) {
  13484. return a;
  13485. }
  13486. attrs = attrs.replace(/([\w\-]*?)\s*=\s*(("([^"]*)")|('([^']*)')|([^\s>]+))/gi, function (str, atr, val) {
  13487. if ({
  13488. 'src': 1,
  13489. 'href': 1,
  13490. 'name': 1
  13491. }[atr.toLowerCase()]) {
  13492. return atr + '=' + val + ' '
  13493. }
  13494. return ''
  13495. });
  13496. if ({
  13497. 'span': 1,
  13498. 'div': 1
  13499. }[tagName]) {
  13500. return ''
  13501. } else {
  13502. return '<' + b + tagName + ' ' + utils.trim(attrs) + '>'
  13503. }
  13504. });
  13505. }
  13506. function filter(div) {
  13507. var html;
  13508. if (div.firstChild) {
  13509. //去掉cut中添加的边界值
  13510. var nodes = domUtils.getElementsByTagName(div, 'span');
  13511. for (var i = 0, ni; ni = nodes[i++];) {
  13512. if (ni.id == '_baidu_cut_start' || ni.id == '_baidu_cut_end') {
  13513. domUtils.remove(ni);
  13514. }
  13515. }
  13516. if (browser.webkit) {
  13517. var brs = div.querySelectorAll('div br');
  13518. for (var i = 0, bi; bi = brs[i++];) {
  13519. var pN = bi.parentNode;
  13520. if (pN.tagName == 'DIV' && pN.childNodes.length == 1) {
  13521. pN.innerHTML = '<p><br/></p>';
  13522. domUtils.remove(pN);
  13523. }
  13524. }
  13525. var divs = div.querySelectorAll('#baidu_pastebin');
  13526. for (var i = 0, di; di = divs[i++];) {
  13527. var tmpP = me.document.createElement('p');
  13528. di.parentNode.insertBefore(tmpP, di);
  13529. while (di.firstChild) {
  13530. tmpP.appendChild(di.firstChild);
  13531. }
  13532. domUtils.remove(di);
  13533. }
  13534. var metas = div.querySelectorAll('meta');
  13535. for (var i = 0, ci; ci = metas[i++];) {
  13536. domUtils.remove(ci);
  13537. }
  13538. var brs = div.querySelectorAll('br');
  13539. for (i = 0; ci = brs[i++];) {
  13540. if (/^apple-/i.test(ci.className)) {
  13541. domUtils.remove(ci);
  13542. }
  13543. }
  13544. }
  13545. if (browser.gecko) {
  13546. var dirtyNodes = div.querySelectorAll('[_moz_dirty]');
  13547. for (i = 0; ci = dirtyNodes[i++];) {
  13548. ci.removeAttribute('_moz_dirty');
  13549. }
  13550. }
  13551. if (!browser.ie) {
  13552. var spans = div.querySelectorAll('span.Apple-style-span');
  13553. for (var i = 0, ci; ci = spans[i++];) {
  13554. domUtils.remove(ci, true);
  13555. }
  13556. }
  13557. //ie下使用innerHTML会产生多余的\r\n字符,也会产生&nbsp;这里过滤掉
  13558. html = div.innerHTML;//.replace(/>(?:(\s|&nbsp;)*?)</g,'><');
  13559. //过滤word粘贴过来的冗余属性
  13560. html = UE.filterWord(html);
  13561. //取消了忽略空白的第二个参数,粘贴过来的有些是有空白的,会被套上相关的标签
  13562. var root = UE.htmlparser(html);
  13563. //如果给了过滤规则就先进行过滤
  13564. if (me.options.filterRules) {
  13565. UE.filterNode(root, me.options.filterRules);
  13566. }
  13567. //执行默认的处理
  13568. me.filterInputRule(root);
  13569. //针对chrome的处理
  13570. if (browser.webkit) {
  13571. var br = root.lastChild();
  13572. if (br && br.type == 'element' && br.tagName == 'br') {
  13573. root.removeChild(br)
  13574. }
  13575. utils.each(me.body.querySelectorAll('div'), function (node) {
  13576. if (domUtils.isEmptyBlock(node)) {
  13577. domUtils.remove(node,true)
  13578. }
  13579. })
  13580. }
  13581. html = {'html': root.toHtml()};
  13582. me.fireEvent('beforepaste', html, root);
  13583. //抢了默认的粘贴,那后边的内容就不执行了,比如表格粘贴
  13584. if(!html.html){
  13585. return;
  13586. }
  13587. root = UE.htmlparser(html.html,true);
  13588. //如果开启了纯文本模式
  13589. if (me.queryCommandState('pasteplain') === 1) {
  13590. me.execCommand('insertHtml', UE.filterNode(root, me.options.filterTxtRules).toHtml(), true);
  13591. } else {
  13592. //文本模式
  13593. UE.filterNode(root, me.options.filterTxtRules);
  13594. txtContent = root.toHtml();
  13595. //完全模式
  13596. htmlContent = html.html;
  13597. address = me.selection.getRange().createAddress(true);
  13598. me.execCommand('insertHtml', me.getOpt('retainOnlyLabelPasted') === true ? getPureHtml(htmlContent) : htmlContent, true);
  13599. }
  13600. me.fireEvent("afterpaste", html);
  13601. }
  13602. }
  13603. me.addListener('pasteTransfer', function (cmd, plainType) {
  13604. if (address && txtContent && htmlContent && txtContent != htmlContent) {
  13605. var range = me.selection.getRange();
  13606. range.moveToAddress(address, true);
  13607. if (!range.collapsed) {
  13608. while (!domUtils.isBody(range.startContainer)
  13609. ) {
  13610. var start = range.startContainer;
  13611. if(start.nodeType == 1){
  13612. start = start.childNodes[range.startOffset];
  13613. if(!start){
  13614. range.setStartBefore(range.startContainer);
  13615. continue;
  13616. }
  13617. var pre = start.previousSibling;
  13618. if(pre && pre.nodeType == 3 && new RegExp('^[\n\r\t '+domUtils.fillChar+']*$').test(pre.nodeValue)){
  13619. range.setStartBefore(pre)
  13620. }
  13621. }
  13622. if(range.startOffset == 0){
  13623. range.setStartBefore(range.startContainer);
  13624. }else{
  13625. break;
  13626. }
  13627. }
  13628. while (!domUtils.isBody(range.endContainer)
  13629. ) {
  13630. var end = range.endContainer;
  13631. if(end.nodeType == 1){
  13632. end = end.childNodes[range.endOffset];
  13633. if(!end){
  13634. range.setEndAfter(range.endContainer);
  13635. continue;
  13636. }
  13637. var next = end.nextSibling;
  13638. if(next && next.nodeType == 3 && new RegExp('^[\n\r\t'+domUtils.fillChar+']*$').test(next.nodeValue)){
  13639. range.setEndAfter(next)
  13640. }
  13641. }
  13642. if(range.endOffset == range.endContainer[range.endContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length){
  13643. range.setEndAfter(range.endContainer);
  13644. }else{
  13645. break;
  13646. }
  13647. }
  13648. }
  13649. range.deleteContents();
  13650. range.select(true);
  13651. me.__hasEnterExecCommand = true;
  13652. var html = htmlContent;
  13653. if (plainType === 2 ) {
  13654. html = getPureHtml(html);
  13655. } else if (plainType) {
  13656. html = txtContent;
  13657. }
  13658. me.execCommand('inserthtml', html, true);
  13659. me.__hasEnterExecCommand = false;
  13660. var rng = me.selection.getRange();
  13661. while (!domUtils.isBody(rng.startContainer) && !rng.startOffset &&
  13662. rng.startContainer[rng.startContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length
  13663. ) {
  13664. rng.setStartBefore(rng.startContainer);
  13665. }
  13666. var tmpAddress = rng.createAddress(true);
  13667. address.endAddress = tmpAddress.startAddress;
  13668. }
  13669. });
  13670. me.addListener('ready', function () {
  13671. domUtils.on(me.body, 'cut', function () {
  13672. var range = me.selection.getRange();
  13673. if (!range.collapsed && me.undoManger) {
  13674. me.undoManger.save();
  13675. }
  13676. });
  13677. //ie下beforepaste在点击右键时也会触发,所以用监控键盘才处理
  13678. domUtils.on(me.body, browser.ie || browser.opera ? 'keydown' : 'paste', function (e) {
  13679. if ((browser.ie || browser.opera) && ((!e.ctrlKey && !e.metaKey) || e.keyCode != '86')) {
  13680. return;
  13681. }
  13682. getClipboardData.call(me, function (div) {
  13683. filter(div);
  13684. });
  13685. });
  13686. });
  13687. me.commands['paste'] = {
  13688. execCommand: function (cmd) {
  13689. if (browser.ie) {
  13690. getClipboardData.call(me, function (div) {
  13691. filter(div);
  13692. });
  13693. me.document.execCommand('paste');
  13694. } else {
  13695. alert(me.getLang('pastemsg'));
  13696. }
  13697. }
  13698. }
  13699. };
  13700. // plugins/puretxtpaste.js
  13701. /**
  13702. * 纯文本粘贴插件
  13703. * @file
  13704. * @since 1.2.6.1
  13705. */
  13706. UE.plugins['pasteplain'] = function(){
  13707. var me = this;
  13708. me.setOpt({
  13709. 'pasteplain':false,
  13710. 'filterTxtRules' : function(){
  13711. function transP(node){
  13712. node.tagName = 'p';
  13713. node.setStyle();
  13714. }
  13715. function removeNode(node){
  13716. node.parentNode.removeChild(node,true)
  13717. }
  13718. return {
  13719. //直接删除及其字节点内容
  13720. '-' : 'script style object iframe embed input select',
  13721. 'p': {$:{}},
  13722. 'br':{$:{}},
  13723. div: function (node) {
  13724. var tmpNode, p = UE.uNode.createElement('p');
  13725. while (tmpNode = node.firstChild()) {
  13726. if (tmpNode.type == 'text' || !UE.dom.dtd.$block[tmpNode.tagName]) {
  13727. p.appendChild(tmpNode);
  13728. } else {
  13729. if (p.firstChild()) {
  13730. node.parentNode.insertBefore(p, node);
  13731. p = UE.uNode.createElement('p');
  13732. } else {
  13733. node.parentNode.insertBefore(tmpNode, node);
  13734. }
  13735. }
  13736. }
  13737. if (p.firstChild()) {
  13738. node.parentNode.insertBefore(p, node);
  13739. }
  13740. node.parentNode.removeChild(node);
  13741. },
  13742. ol: removeNode,
  13743. ul: removeNode,
  13744. dl:removeNode,
  13745. dt:removeNode,
  13746. dd:removeNode,
  13747. 'li':removeNode,
  13748. 'caption':transP,
  13749. 'th':transP,
  13750. 'tr':transP,
  13751. 'h1':transP,'h2':transP,'h3':transP,'h4':transP,'h5':transP,'h6':transP,
  13752. 'td':function(node){
  13753. //没有内容的td直接删掉
  13754. var txt = !!node.innerText();
  13755. if(txt){
  13756. node.parentNode.insertAfter(UE.uNode.createText(' &nbsp; &nbsp;'),node);
  13757. }
  13758. node.parentNode.removeChild(node,node.innerText())
  13759. }
  13760. }
  13761. }()
  13762. });
  13763. //暂时这里支持一下老版本的属性
  13764. var pasteplain = me.options.pasteplain;
  13765. /**
  13766. * 启用或取消纯文本粘贴模式
  13767. * @command pasteplain
  13768. * @method execCommand
  13769. * @param { String } cmd 命令字符串
  13770. * @example
  13771. * ```javascript
  13772. * editor.queryCommandState( 'pasteplain' );
  13773. * ```
  13774. */
  13775. /**
  13776. * 查询当前是否处于纯文本粘贴模式
  13777. * @command pasteplain
  13778. * @method queryCommandState
  13779. * @param { String } cmd 命令字符串
  13780. * @return { int } 如果处于纯文本模式,返回1,否则,返回0
  13781. * @example
  13782. * ```javascript
  13783. * editor.queryCommandState( 'pasteplain' );
  13784. * ```
  13785. */
  13786. me.commands['pasteplain'] = {
  13787. queryCommandState: function (){
  13788. return pasteplain ? 1 : 0;
  13789. },
  13790. execCommand: function (){
  13791. pasteplain = !pasteplain|0;
  13792. },
  13793. notNeedUndo : 1
  13794. };
  13795. };
  13796. // plugins/list.js
  13797. /**
  13798. * 有序列表,无序列表插件
  13799. * @file
  13800. * @since 1.2.6.1
  13801. */
  13802. UE.plugins['list'] = function () {
  13803. var me = this,
  13804. notExchange = {
  13805. 'TD':1,
  13806. 'PRE':1,
  13807. 'BLOCKQUOTE':1
  13808. };
  13809. var customStyle = {
  13810. 'cn' : 'cn-1-',
  13811. 'cn1' : 'cn-2-',
  13812. 'cn2' : 'cn-3-',
  13813. 'num': 'num-1-',
  13814. 'num1' : 'num-2-',
  13815. 'num2' : 'num-3-',
  13816. 'dash' : 'dash',
  13817. 'dot':'dot'
  13818. };
  13819. me.setOpt( {
  13820. 'autoTransWordToList':false,
  13821. 'insertorderedlist':{
  13822. 'num':'',
  13823. 'num1':'',
  13824. 'num2':'',
  13825. 'cn':'',
  13826. 'cn1':'',
  13827. 'cn2':'',
  13828. 'decimal':'',
  13829. 'lower-alpha':'',
  13830. 'lower-roman':'',
  13831. 'upper-alpha':'',
  13832. 'upper-roman':''
  13833. },
  13834. 'insertunorderedlist':{
  13835. 'circle':'',
  13836. 'disc':'',
  13837. 'square':'',
  13838. 'dash' : '',
  13839. 'dot':''
  13840. },
  13841. listDefaultPaddingLeft : '30',
  13842. listiconpath : 'http://bs.baidu.com/listicon/',
  13843. maxListLevel : -1,//-1不限制
  13844. disablePInList:false
  13845. } );
  13846. function listToArray(list){
  13847. var arr = [];
  13848. for(var p in list){
  13849. arr.push(p)
  13850. }
  13851. return arr;
  13852. }
  13853. var listStyle = {
  13854. 'OL':listToArray(me.options.insertorderedlist),
  13855. 'UL':listToArray(me.options.insertunorderedlist)
  13856. };
  13857. var liiconpath = me.options.listiconpath;
  13858. //根据用户配置,调整customStyle
  13859. for(var s in customStyle){
  13860. if(!me.options.insertorderedlist.hasOwnProperty(s) && !me.options.insertunorderedlist.hasOwnProperty(s)){
  13861. delete customStyle[s];
  13862. }
  13863. }
  13864. me.ready(function () {
  13865. var customCss = [];
  13866. for(var p in customStyle){
  13867. if(p == 'dash' || p == 'dot'){
  13868. customCss.push('li.list-' + customStyle[p] + '{background-image:url(' + liiconpath +customStyle[p]+'.gif)}');
  13869. customCss.push('ul.custom_'+p+'{list-style:none;}ul.custom_'+p+' li{background-position:0 3px;background-repeat:no-repeat}');
  13870. }else{
  13871. for(var i= 0;i<99;i++){
  13872. customCss.push('li.list-' + customStyle[p] + i + '{background-image:url(' + liiconpath + 'list-'+customStyle[p] + i + '.gif)}')
  13873. }
  13874. customCss.push('ol.custom_'+p+'{list-style:none;}ol.custom_'+p+' li{background-position:0 3px;background-repeat:no-repeat}');
  13875. }
  13876. switch(p){
  13877. case 'cn':
  13878. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:25px}');
  13879. customCss.push('li.list-'+p+'-paddingleft-2{padding-left:40px}');
  13880. customCss.push('li.list-'+p+'-paddingleft-3{padding-left:55px}');
  13881. break;
  13882. case 'cn1':
  13883. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:30px}');
  13884. customCss.push('li.list-'+p+'-paddingleft-2{padding-left:40px}');
  13885. customCss.push('li.list-'+p+'-paddingleft-3{padding-left:55px}');
  13886. break;
  13887. case 'cn2':
  13888. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:40px}');
  13889. customCss.push('li.list-'+p+'-paddingleft-2{padding-left:55px}');
  13890. customCss.push('li.list-'+p+'-paddingleft-3{padding-left:68px}');
  13891. break;
  13892. case 'num':
  13893. case 'num1':
  13894. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:25px}');
  13895. break;
  13896. case 'num2':
  13897. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:35px}');
  13898. customCss.push('li.list-'+p+'-paddingleft-2{padding-left:40px}');
  13899. break;
  13900. case 'dash':
  13901. customCss.push('li.list-'+p+'-paddingleft{padding-left:35px}');
  13902. break;
  13903. case 'dot':
  13904. customCss.push('li.list-'+p+'-paddingleft{padding-left:20px}');
  13905. }
  13906. }
  13907. customCss.push('.list-paddingleft-1{padding-left:0}');
  13908. customCss.push('.list-paddingleft-2{padding-left:'+me.options.listDefaultPaddingLeft+'px}');
  13909. customCss.push('.list-paddingleft-3{padding-left:'+me.options.listDefaultPaddingLeft*2+'px}');
  13910. //如果不给宽度会在自定应样式里出现滚动条
  13911. utils.cssRule('list', 'ol,ul{margin:0;pading:0;'+(browser.ie ? '' : 'width:95%')+'}li{clear:both;}'+customCss.join('\n'), me.document);
  13912. });
  13913. //单独处理剪切的问题
  13914. me.ready(function(){
  13915. domUtils.on(me.body,'cut',function(){
  13916. setTimeout(function(){
  13917. var rng = me.selection.getRange(),li;
  13918. //trace:3416
  13919. if(!rng.collapsed){
  13920. if(li = domUtils.findParentByTagName(rng.startContainer,'li',true)){
  13921. if(!li.nextSibling && domUtils.isEmptyBlock(li)){
  13922. var pn = li.parentNode,node;
  13923. if(node = pn.previousSibling){
  13924. domUtils.remove(pn);
  13925. rng.setStartAtLast(node).collapse(true);
  13926. rng.select(true);
  13927. }else if(node = pn.nextSibling){
  13928. domUtils.remove(pn);
  13929. rng.setStartAtFirst(node).collapse(true);
  13930. rng.select(true);
  13931. }else{
  13932. var tmpNode = me.document.createElement('p');
  13933. domUtils.fillNode(me.document,tmpNode);
  13934. pn.parentNode.insertBefore(tmpNode,pn);
  13935. domUtils.remove(pn);
  13936. rng.setStart(tmpNode,0).collapse(true);
  13937. rng.select(true);
  13938. }
  13939. }
  13940. }
  13941. }
  13942. })
  13943. })
  13944. });
  13945. function getStyle(node){
  13946. var cls = node.className;
  13947. if(domUtils.hasClass(node,/custom_/)){
  13948. return cls.match(/custom_(\w+)/)[1]
  13949. }
  13950. return domUtils.getStyle(node, 'list-style-type')
  13951. }
  13952. me.addListener('beforepaste',function(type,html){
  13953. var me = this,
  13954. rng = me.selection.getRange(),li;
  13955. var root = UE.htmlparser(html.html,true);
  13956. if(li = domUtils.findParentByTagName(rng.startContainer,'li',true)){
  13957. var list = li.parentNode,tagName = list.tagName == 'OL' ? 'ul':'ol';
  13958. utils.each(root.getNodesByTagName(tagName),function(n){
  13959. n.tagName = list.tagName;
  13960. n.setAttr();
  13961. if(n.parentNode === root){
  13962. type = getStyle(list) || (list.tagName == 'OL' ? 'decimal' : 'disc')
  13963. }else{
  13964. var className = n.parentNode.getAttr('class');
  13965. if(className && /custom_/.test(className)){
  13966. type = className.match(/custom_(\w+)/)[1]
  13967. }else{
  13968. type = n.parentNode.getStyle('list-style-type');
  13969. }
  13970. if(!type){
  13971. type = list.tagName == 'OL' ? 'decimal' : 'disc';
  13972. }
  13973. }
  13974. var index = utils.indexOf(listStyle[list.tagName], type);
  13975. if(n.parentNode !== root)
  13976. index = index + 1 == listStyle[list.tagName].length ? 0 : index + 1;
  13977. var currentStyle = listStyle[list.tagName][index];
  13978. if(customStyle[currentStyle]){
  13979. n.setAttr('class', 'custom_' + currentStyle)
  13980. }else{
  13981. n.setStyle('list-style-type',currentStyle)
  13982. }
  13983. })
  13984. }
  13985. html.html = root.toHtml();
  13986. });
  13987. //导出时,去掉p标签
  13988. me.getOpt('disablePInList') === true && me.addOutputRule(function(root){
  13989. utils.each(root.getNodesByTagName('li'),function(li){
  13990. var newChildrens = [],index=0;
  13991. utils.each(li.children,function(n){
  13992. if(n.tagName == 'p'){
  13993. var tmpNode;
  13994. while(tmpNode = n.children.pop()) {
  13995. newChildrens.splice(index,0,tmpNode);
  13996. tmpNode.parentNode = li;
  13997. lastNode = tmpNode;
  13998. }
  13999. tmpNode = newChildrens[newChildrens.length-1];
  14000. if(!tmpNode || tmpNode.type != 'element' || tmpNode.tagName != 'br'){
  14001. var br = UE.uNode.createElement('br');
  14002. br.parentNode = li;
  14003. newChildrens.push(br);
  14004. }
  14005. index = newChildrens.length;
  14006. }
  14007. });
  14008. if(newChildrens.length){
  14009. li.children = newChildrens;
  14010. }
  14011. });
  14012. });
  14013. //进入编辑器的li要套p标签
  14014. me.addInputRule(function(root){
  14015. utils.each(root.getNodesByTagName('li'),function(li){
  14016. var tmpP = UE.uNode.createElement('p');
  14017. for(var i= 0,ci;ci=li.children[i];){
  14018. if(ci.type == 'text' || dtd.p[ci.tagName]){
  14019. tmpP.appendChild(ci);
  14020. }else{
  14021. if(tmpP.firstChild()){
  14022. li.insertBefore(tmpP,ci);
  14023. tmpP = UE.uNode.createElement('p');
  14024. i = i + 2;
  14025. }else{
  14026. i++;
  14027. }
  14028. }
  14029. }
  14030. if(tmpP.firstChild() && !tmpP.parentNode || !li.firstChild()){
  14031. li.appendChild(tmpP);
  14032. }
  14033. //trace:3357
  14034. //p不能为空
  14035. if (!tmpP.firstChild()) {
  14036. tmpP.innerHTML(browser.ie ? '&nbsp;' : '<br/>')
  14037. }
  14038. //去掉末尾的空白
  14039. var p = li.firstChild();
  14040. var lastChild = p.lastChild();
  14041. if(lastChild && lastChild.type == 'text' && /^\s*$/.test(lastChild.data)){
  14042. p.removeChild(lastChild)
  14043. }
  14044. });
  14045. if(me.options.autoTransWordToList){
  14046. var orderlisttype = {
  14047. 'num1':/^\d+\)/,
  14048. 'decimal':/^\d+\./,
  14049. 'lower-alpha':/^[a-z]+\)/,
  14050. 'upper-alpha':/^[A-Z]+\./,
  14051. 'cn':/^[\u4E00\u4E8C\u4E09\u56DB\u516d\u4e94\u4e03\u516b\u4e5d]+[\u3001]/,
  14052. 'cn2':/^\([\u4E00\u4E8C\u4E09\u56DB\u516d\u4e94\u4e03\u516b\u4e5d]+\)/
  14053. },
  14054. unorderlisttype = {
  14055. 'square':'n'
  14056. };
  14057. function checkListType(content,container){
  14058. var span = container.firstChild();
  14059. if(span && span.type == 'element' && span.tagName == 'span' && /Wingdings|Symbol/.test(span.getStyle('font-family'))){
  14060. for(var p in unorderlisttype){
  14061. if(unorderlisttype[p] == span.data){
  14062. return p
  14063. }
  14064. }
  14065. return 'disc'
  14066. }
  14067. for(var p in orderlisttype){
  14068. if(orderlisttype[p].test(content)){
  14069. return p;
  14070. }
  14071. }
  14072. }
  14073. utils.each(root.getNodesByTagName('p'),function(node){
  14074. if(node.getAttr('class') != 'MsoListParagraph'){
  14075. return
  14076. }
  14077. //word粘贴过来的会带有margin要去掉,但这样也可能会误命中一些央视
  14078. node.setStyle('margin','');
  14079. node.setStyle('margin-left','');
  14080. node.setAttr('class','');
  14081. function appendLi(list,p,type){
  14082. if(list.tagName == 'ol'){
  14083. if(browser.ie){
  14084. var first = p.firstChild();
  14085. if(first.type =='element' && first.tagName == 'span' && orderlisttype[type].test(first.innerText())){
  14086. p.removeChild(first);
  14087. }
  14088. }else{
  14089. p.innerHTML(p.innerHTML().replace(orderlisttype[type],''));
  14090. }
  14091. }else{
  14092. p.removeChild(p.firstChild())
  14093. }
  14094. var li = UE.uNode.createElement('li');
  14095. li.appendChild(p);
  14096. list.appendChild(li);
  14097. }
  14098. var tmp = node,type,cacheNode = node;
  14099. if(node.parentNode.tagName != 'li' && (type = checkListType(node.innerText(),node))){
  14100. var list = UE.uNode.createElement(me.options.insertorderedlist.hasOwnProperty(type) ? 'ol' : 'ul');
  14101. if(customStyle[type]){
  14102. list.setAttr('class','custom_'+type)
  14103. }else{
  14104. list.setStyle('list-style-type',type)
  14105. }
  14106. while(node && node.parentNode.tagName != 'li' && checkListType(node.innerText(),node)){
  14107. tmp = node.nextSibling();
  14108. if(!tmp){
  14109. node.parentNode.insertBefore(list,node)
  14110. }
  14111. appendLi(list,node,type);
  14112. node = tmp;
  14113. }
  14114. if(!list.parentNode && node && node.parentNode){
  14115. node.parentNode.insertBefore(list,node)
  14116. }
  14117. }
  14118. var span = cacheNode.firstChild();
  14119. if(span && span.type == 'element' && span.tagName == 'span' && /^\s*(&nbsp;)+\s*$/.test(span.innerText())){
  14120. span.parentNode.removeChild(span)
  14121. }
  14122. })
  14123. }
  14124. });
  14125. //调整索引标签
  14126. me.addListener('contentchange',function(){
  14127. adjustListStyle(me.document)
  14128. });
  14129. function adjustListStyle(doc,ignore){
  14130. utils.each(domUtils.getElementsByTagName(doc,'ol ul'),function(node){
  14131. if(!domUtils.inDoc(node,doc))
  14132. return;
  14133. var parent = node.parentNode;
  14134. if(parent.tagName == node.tagName){
  14135. var nodeStyleType = getStyle(node) || (node.tagName == 'OL' ? 'decimal' : 'disc'),
  14136. parentStyleType = getStyle(parent) || (parent.tagName == 'OL' ? 'decimal' : 'disc');
  14137. if(nodeStyleType == parentStyleType){
  14138. var styleIndex = utils.indexOf(listStyle[node.tagName], nodeStyleType);
  14139. styleIndex = styleIndex + 1 == listStyle[node.tagName].length ? 0 : styleIndex + 1;
  14140. setListStyle(node,listStyle[node.tagName][styleIndex])
  14141. }
  14142. }
  14143. var index = 0,type = 2;
  14144. if( domUtils.hasClass(node,/custom_/)){
  14145. if(!(/[ou]l/i.test(parent.tagName) && domUtils.hasClass(parent,/custom_/))){
  14146. type = 1;
  14147. }
  14148. }else{
  14149. if(/[ou]l/i.test(parent.tagName) && domUtils.hasClass(parent,/custom_/)){
  14150. type = 3;
  14151. }
  14152. }
  14153. var style = domUtils.getStyle(node, 'list-style-type');
  14154. style && (node.style.cssText = 'list-style-type:' + style);
  14155. node.className = utils.trim(node.className.replace(/list-paddingleft-\w+/,'')) + ' list-paddingleft-' + type;
  14156. utils.each(domUtils.getElementsByTagName(node,'li'),function(li){
  14157. li.style.cssText && (li.style.cssText = '');
  14158. if(!li.firstChild){
  14159. domUtils.remove(li);
  14160. return;
  14161. }
  14162. if(li.parentNode !== node){
  14163. return;
  14164. }
  14165. index++;
  14166. if(domUtils.hasClass(node,/custom_/) ){
  14167. var paddingLeft = 1,currentStyle = getStyle(node);
  14168. if(node.tagName == 'OL'){
  14169. if(currentStyle){
  14170. switch(currentStyle){
  14171. case 'cn' :
  14172. case 'cn1':
  14173. case 'cn2':
  14174. if(index > 10 && (index % 10 == 0 || index > 10 && index < 20)){
  14175. paddingLeft = 2
  14176. }else if(index > 20){
  14177. paddingLeft = 3
  14178. }
  14179. break;
  14180. case 'num2' :
  14181. if(index > 9){
  14182. paddingLeft = 2
  14183. }
  14184. }
  14185. }
  14186. li.className = 'list-'+customStyle[currentStyle]+ index + ' ' + 'list-'+currentStyle+'-paddingleft-' + paddingLeft;
  14187. }else{
  14188. li.className = 'list-'+customStyle[currentStyle] + ' ' + 'list-'+currentStyle+'-paddingleft';
  14189. }
  14190. }else{
  14191. li.className = li.className.replace(/list-[\w\-]+/gi,'');
  14192. }
  14193. var className = li.getAttribute('class');
  14194. if(className !== null && !className.replace(/\s/g,'')){
  14195. domUtils.removeAttributes(li,'class')
  14196. }
  14197. });
  14198. !ignore && adjustList(node,node.tagName.toLowerCase(),getStyle(node)||domUtils.getStyle(node, 'list-style-type'),true);
  14199. })
  14200. }
  14201. function adjustList(list, tag, style,ignoreEmpty) {
  14202. var nextList = list.nextSibling;
  14203. if (nextList && nextList.nodeType == 1 && nextList.tagName.toLowerCase() == tag && (getStyle(nextList) || domUtils.getStyle(nextList, 'list-style-type') || (tag == 'ol' ? 'decimal' : 'disc')) == style) {
  14204. domUtils.moveChild(nextList, list);
  14205. if (nextList.childNodes.length == 0) {
  14206. domUtils.remove(nextList);
  14207. }
  14208. }
  14209. if(nextList && domUtils.isFillChar(nextList)){
  14210. domUtils.remove(nextList);
  14211. }
  14212. var preList = list.previousSibling;
  14213. if (preList && preList.nodeType == 1 && preList.tagName.toLowerCase() == tag && (getStyle(preList) || domUtils.getStyle(preList, 'list-style-type') || (tag == 'ol' ? 'decimal' : 'disc')) == style) {
  14214. domUtils.moveChild(list, preList);
  14215. }
  14216. if(preList && domUtils.isFillChar(preList)){
  14217. domUtils.remove(preList);
  14218. }
  14219. !ignoreEmpty && domUtils.isEmptyBlock(list) && domUtils.remove(list);
  14220. if(getStyle(list)){
  14221. adjustListStyle(list.ownerDocument,true)
  14222. }
  14223. }
  14224. function setListStyle(list,style){
  14225. if(customStyle[style]){
  14226. list.className = 'custom_' + style;
  14227. }
  14228. try{
  14229. domUtils.setStyle(list, 'list-style-type', style);
  14230. }catch(e){}
  14231. }
  14232. function clearEmptySibling(node) {
  14233. var tmpNode = node.previousSibling;
  14234. if (tmpNode && domUtils.isEmptyBlock(tmpNode)) {
  14235. domUtils.remove(tmpNode);
  14236. }
  14237. tmpNode = node.nextSibling;
  14238. if (tmpNode && domUtils.isEmptyBlock(tmpNode)) {
  14239. domUtils.remove(tmpNode);
  14240. }
  14241. }
  14242. me.addListener('keydown', function (type, evt) {
  14243. function preventAndSave() {
  14244. evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false);
  14245. me.fireEvent('contentchange');
  14246. me.undoManger && me.undoManger.save();
  14247. }
  14248. function findList(node,filterFn){
  14249. while(node && !domUtils.isBody(node)){
  14250. if(filterFn(node)){
  14251. return null
  14252. }
  14253. if(node.nodeType == 1 && /[ou]l/i.test(node.tagName)){
  14254. return node;
  14255. }
  14256. node = node.parentNode;
  14257. }
  14258. return null;
  14259. }
  14260. var keyCode = evt.keyCode || evt.which;
  14261. if (keyCode == 13 && !evt.shiftKey) {//回车
  14262. var rng = me.selection.getRange(),
  14263. parent = domUtils.findParent(rng.startContainer,function(node){return domUtils.isBlockElm(node)},true),
  14264. li = domUtils.findParentByTagName(rng.startContainer,'li',true);
  14265. if(parent && parent.tagName != 'PRE' && !li){
  14266. var html = parent.innerHTML.replace(new RegExp(domUtils.fillChar, 'g'),'');
  14267. if(/^\s*1\s*\.[^\d]/.test(html)){
  14268. parent.innerHTML = html.replace(/^\s*1\s*\./,'');
  14269. rng.setStartAtLast(parent).collapse(true).select();
  14270. me.__hasEnterExecCommand = true;
  14271. me.execCommand('insertorderedlist');
  14272. me.__hasEnterExecCommand = false;
  14273. }
  14274. }
  14275. var range = me.selection.getRange(),
  14276. start = findList(range.startContainer,function (node) {
  14277. return node.tagName == 'TABLE';
  14278. }),
  14279. end = range.collapsed ? start : findList(range.endContainer,function (node) {
  14280. return node.tagName == 'TABLE';
  14281. });
  14282. if (start && end && start === end) {
  14283. if (!range.collapsed) {
  14284. start = domUtils.findParentByTagName(range.startContainer, 'li', true);
  14285. end = domUtils.findParentByTagName(range.endContainer, 'li', true);
  14286. if (start && end && start === end) {
  14287. range.deleteContents();
  14288. li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  14289. if (li && domUtils.isEmptyBlock(li)) {
  14290. pre = li.previousSibling;
  14291. next = li.nextSibling;
  14292. p = me.document.createElement('p');
  14293. domUtils.fillNode(me.document, p);
  14294. parentList = li.parentNode;
  14295. if (pre && next) {
  14296. range.setStart(next, 0).collapse(true).select(true);
  14297. domUtils.remove(li);
  14298. } else {
  14299. if (!pre && !next || !pre) {
  14300. parentList.parentNode.insertBefore(p, parentList);
  14301. } else {
  14302. li.parentNode.parentNode.insertBefore(p, parentList.nextSibling);
  14303. }
  14304. domUtils.remove(li);
  14305. if (!parentList.firstChild) {
  14306. domUtils.remove(parentList);
  14307. }
  14308. range.setStart(p, 0).setCursor();
  14309. }
  14310. preventAndSave();
  14311. return;
  14312. }
  14313. } else {
  14314. var tmpRange = range.cloneRange(),
  14315. bk = tmpRange.collapse(false).createBookmark();
  14316. range.deleteContents();
  14317. tmpRange.moveToBookmark(bk);
  14318. var li = domUtils.findParentByTagName(tmpRange.startContainer, 'li', true);
  14319. clearEmptySibling(li);
  14320. tmpRange.select();
  14321. preventAndSave();
  14322. return;
  14323. }
  14324. }
  14325. li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  14326. if (li) {
  14327. if (domUtils.isEmptyBlock(li)) {
  14328. bk = range.createBookmark();
  14329. var parentList = li.parentNode;
  14330. if (li !== parentList.lastChild) {
  14331. domUtils.breakParent(li, parentList);
  14332. clearEmptySibling(li);
  14333. } else {
  14334. parentList.parentNode.insertBefore(li, parentList.nextSibling);
  14335. if (domUtils.isEmptyNode(parentList)) {
  14336. domUtils.remove(parentList);
  14337. }
  14338. }
  14339. //嵌套不处理
  14340. if (!dtd.$list[li.parentNode.tagName]) {
  14341. if (!domUtils.isBlockElm(li.firstChild)) {
  14342. p = me.document.createElement('p');
  14343. li.parentNode.insertBefore(p, li);
  14344. while (li.firstChild) {
  14345. p.appendChild(li.firstChild);
  14346. }
  14347. domUtils.remove(li);
  14348. } else {
  14349. domUtils.remove(li, true);
  14350. }
  14351. }
  14352. range.moveToBookmark(bk).select();
  14353. } else {
  14354. var first = li.firstChild;
  14355. if (!first || !domUtils.isBlockElm(first)) {
  14356. var p = me.document.createElement('p');
  14357. !li.firstChild && domUtils.fillNode(me.document, p);
  14358. while (li.firstChild) {
  14359. p.appendChild(li.firstChild);
  14360. }
  14361. li.appendChild(p);
  14362. first = p;
  14363. }
  14364. var span = me.document.createElement('span');
  14365. range.insertNode(span);
  14366. domUtils.breakParent(span, li);
  14367. var nextLi = span.nextSibling;
  14368. first = nextLi.firstChild;
  14369. if (!first) {
  14370. p = me.document.createElement('p');
  14371. domUtils.fillNode(me.document, p);
  14372. nextLi.appendChild(p);
  14373. first = p;
  14374. }
  14375. if (domUtils.isEmptyNode(first)) {
  14376. first.innerHTML = '';
  14377. domUtils.fillNode(me.document, first);
  14378. }
  14379. range.setStart(first, 0).collapse(true).shrinkBoundary().select();
  14380. domUtils.remove(span);
  14381. var pre = nextLi.previousSibling;
  14382. if (pre && domUtils.isEmptyBlock(pre)) {
  14383. pre.innerHTML = '<p></p>';
  14384. domUtils.fillNode(me.document, pre.firstChild);
  14385. }
  14386. }
  14387. // }
  14388. preventAndSave();
  14389. }
  14390. }
  14391. }
  14392. if (keyCode == 8) {
  14393. //修中ie中li下的问题
  14394. range = me.selection.getRange();
  14395. if (range.collapsed && domUtils.isStartInblock(range)) {
  14396. tmpRange = range.cloneRange().trimBoundary();
  14397. li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  14398. //要在li的最左边,才能处理
  14399. if (li && domUtils.isStartInblock(tmpRange)) {
  14400. start = domUtils.findParentByTagName(range.startContainer, 'p', true);
  14401. if (start && start !== li.firstChild) {
  14402. var parentList = domUtils.findParentByTagName(start,['ol','ul']);
  14403. domUtils.breakParent(start,parentList);
  14404. clearEmptySibling(start);
  14405. me.fireEvent('contentchange');
  14406. range.setStart(start,0).setCursor(false,true);
  14407. me.fireEvent('saveScene');
  14408. domUtils.preventDefault(evt);
  14409. return;
  14410. }
  14411. if (li && (pre = li.previousSibling)) {
  14412. if (keyCode == 46 && li.childNodes.length) {
  14413. return;
  14414. }
  14415. //有可能上边的兄弟节点是个2级菜单,要追加到2级菜单的最后的li
  14416. if (dtd.$list[pre.tagName]) {
  14417. pre = pre.lastChild;
  14418. }
  14419. me.undoManger && me.undoManger.save();
  14420. first = li.firstChild;
  14421. if (domUtils.isBlockElm(first)) {
  14422. if (domUtils.isEmptyNode(first)) {
  14423. // range.setEnd(pre, pre.childNodes.length).shrinkBoundary().collapse().select(true);
  14424. pre.appendChild(first);
  14425. range.setStart(first, 0).setCursor(false, true);
  14426. //first不是唯一的节点
  14427. while (li.firstChild) {
  14428. pre.appendChild(li.firstChild);
  14429. }
  14430. } else {
  14431. span = me.document.createElement('span');
  14432. range.insertNode(span);
  14433. //判断pre是否是空的节点,如果是<p><br/></p>类型的空节点,干掉p标签防止它占位
  14434. if (domUtils.isEmptyBlock(pre)) {
  14435. pre.innerHTML = '';
  14436. }
  14437. domUtils.moveChild(li, pre);
  14438. range.setStartBefore(span).collapse(true).select(true);
  14439. domUtils.remove(span);
  14440. }
  14441. } else {
  14442. if (domUtils.isEmptyNode(li)) {
  14443. var p = me.document.createElement('p');
  14444. pre.appendChild(p);
  14445. range.setStart(p, 0).setCursor();
  14446. // range.setEnd(pre, pre.childNodes.length).shrinkBoundary().collapse().select(true);
  14447. } else {
  14448. range.setEnd(pre, pre.childNodes.length).collapse().select(true);
  14449. while (li.firstChild) {
  14450. pre.appendChild(li.firstChild);
  14451. }
  14452. }
  14453. }
  14454. domUtils.remove(li);
  14455. me.fireEvent('contentchange');
  14456. me.fireEvent('saveScene');
  14457. domUtils.preventDefault(evt);
  14458. return;
  14459. }
  14460. //trace:980
  14461. if (li && !li.previousSibling) {
  14462. var parentList = li.parentNode;
  14463. var bk = range.createBookmark();
  14464. if(domUtils.isTagNode(parentList.parentNode,'ol ul')){
  14465. parentList.parentNode.insertBefore(li,parentList);
  14466. if(domUtils.isEmptyNode(parentList)){
  14467. domUtils.remove(parentList)
  14468. }
  14469. }else{
  14470. while(li.firstChild){
  14471. parentList.parentNode.insertBefore(li.firstChild,parentList);
  14472. }
  14473. domUtils.remove(li);
  14474. if(domUtils.isEmptyNode(parentList)){
  14475. domUtils.remove(parentList)
  14476. }
  14477. }
  14478. range.moveToBookmark(bk).setCursor(false,true);
  14479. me.fireEvent('contentchange');
  14480. me.fireEvent('saveScene');
  14481. domUtils.preventDefault(evt);
  14482. return;
  14483. }
  14484. }
  14485. }
  14486. }
  14487. });
  14488. me.addListener('keyup',function(type, evt){
  14489. var keyCode = evt.keyCode || evt.which;
  14490. if (keyCode == 8) {
  14491. var rng = me.selection.getRange(),list;
  14492. if(list = domUtils.findParentByTagName(rng.startContainer,['ol', 'ul'],true)){
  14493. adjustList(list,list.tagName.toLowerCase(),getStyle(list)||domUtils.getComputedStyle(list,'list-style-type'),true)
  14494. }
  14495. }
  14496. });
  14497. //处理tab键
  14498. me.addListener('tabkeydown',function(){
  14499. var range = me.selection.getRange();
  14500. //控制级数
  14501. function checkLevel(li){
  14502. if(me.options.maxListLevel != -1){
  14503. var level = li.parentNode,levelNum = 0;
  14504. while(/[ou]l/i.test(level.tagName)){
  14505. levelNum++;
  14506. level = level.parentNode;
  14507. }
  14508. if(levelNum >= me.options.maxListLevel){
  14509. return true;
  14510. }
  14511. }
  14512. }
  14513. //只以开始为准
  14514. //todo 后续改进
  14515. var li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  14516. if(li){
  14517. var bk;
  14518. if(range.collapsed){
  14519. if(checkLevel(li))
  14520. return true;
  14521. var parentLi = li.parentNode,
  14522. list = me.document.createElement(parentLi.tagName),
  14523. index = utils.indexOf(listStyle[list.tagName], getStyle(parentLi)||domUtils.getComputedStyle(parentLi, 'list-style-type'));
  14524. index = index + 1 == listStyle[list.tagName].length ? 0 : index + 1;
  14525. var currentStyle = listStyle[list.tagName][index];
  14526. setListStyle(list,currentStyle);
  14527. if(domUtils.isStartInblock(range)){
  14528. me.fireEvent('saveScene');
  14529. bk = range.createBookmark();
  14530. parentLi.insertBefore(list, li);
  14531. list.appendChild(li);
  14532. adjustList(list,list.tagName.toLowerCase(),currentStyle);
  14533. me.fireEvent('contentchange');
  14534. range.moveToBookmark(bk).select(true);
  14535. return true;
  14536. }
  14537. }else{
  14538. me.fireEvent('saveScene');
  14539. bk = range.createBookmark();
  14540. for(var i= 0,closeList,parents = domUtils.findParents(li),ci;ci=parents[i++];){
  14541. if(domUtils.isTagNode(ci,'ol ul')){
  14542. closeList = ci;
  14543. break;
  14544. }
  14545. }
  14546. var current = li;
  14547. if(bk.end){
  14548. while(current && !(domUtils.getPosition(current, bk.end) & domUtils.POSITION_FOLLOWING)){
  14549. if(checkLevel(current)){
  14550. current = domUtils.getNextDomNode(current,false,null,function(node){return node !== closeList});
  14551. continue;
  14552. }
  14553. var parentLi = current.parentNode,
  14554. list = me.document.createElement(parentLi.tagName),
  14555. index = utils.indexOf(listStyle[list.tagName], getStyle(parentLi)||domUtils.getComputedStyle(parentLi, 'list-style-type'));
  14556. var currentIndex = index + 1 == listStyle[list.tagName].length ? 0 : index + 1;
  14557. var currentStyle = listStyle[list.tagName][currentIndex];
  14558. setListStyle(list,currentStyle);
  14559. parentLi.insertBefore(list, current);
  14560. while(current && !(domUtils.getPosition(current, bk.end) & domUtils.POSITION_FOLLOWING)){
  14561. li = current.nextSibling;
  14562. list.appendChild(current);
  14563. if(!li || domUtils.isTagNode(li,'ol ul')){
  14564. if(li){
  14565. while(li = li.firstChild){
  14566. if(li.tagName == 'LI'){
  14567. break;
  14568. }
  14569. }
  14570. }else{
  14571. li = domUtils.getNextDomNode(current,false,null,function(node){return node !== closeList});
  14572. }
  14573. break;
  14574. }
  14575. current = li;
  14576. }
  14577. adjustList(list,list.tagName.toLowerCase(),currentStyle);
  14578. current = li;
  14579. }
  14580. }
  14581. me.fireEvent('contentchange');
  14582. range.moveToBookmark(bk).select();
  14583. return true;
  14584. }
  14585. }
  14586. });
  14587. function getLi(start){
  14588. while(start && !domUtils.isBody(start)){
  14589. if(start.nodeName == 'TABLE'){
  14590. return null;
  14591. }
  14592. if(start.nodeName == 'LI'){
  14593. return start
  14594. }
  14595. start = start.parentNode;
  14596. }
  14597. }
  14598. /**
  14599. * 有序列表,与“insertunorderedlist”命令互斥
  14600. * @command insertorderedlist
  14601. * @method execCommand
  14602. * @param { String } command 命令字符串
  14603. * @param { String } style 插入的有序列表类型,值为:decimal,lower-alpha,lower-roman,upper-alpha,upper-roman,cn,cn1,cn2,num,num1,num2
  14604. * @example
  14605. * ```javascript
  14606. * editor.execCommand( 'insertorderedlist','decimal');
  14607. * ```
  14608. */
  14609. /**
  14610. * 查询当前选区内容是否有序列表
  14611. * @command insertorderedlist
  14612. * @method queryCommandState
  14613. * @param { String } cmd 命令字符串
  14614. * @return { int } 如果当前选区是有序列表返回1,否则返回0
  14615. * @example
  14616. * ```javascript
  14617. * editor.queryCommandState( 'insertorderedlist' );
  14618. * ```
  14619. */
  14620. /**
  14621. * 查询当前选区内容是否有序列表
  14622. * @command insertorderedlist
  14623. * @method queryCommandValue
  14624. * @param { String } cmd 命令字符串
  14625. * @return { String } 返回当前有序列表的类型,值为null或decimal,lower-alpha,lower-roman,upper-alpha,upper-roman,cn,cn1,cn2,num,num1,num2
  14626. * @example
  14627. * ```javascript
  14628. * editor.queryCommandValue( 'insertorderedlist' );
  14629. * ```
  14630. */
  14631. /**
  14632. * 无序列表,与“insertorderedlist”命令互斥
  14633. * @command insertunorderedlist
  14634. * @method execCommand
  14635. * @param { String } command 命令字符串
  14636. * @param { String } style 插入的无序列表类型,值为:circle,disc,square,dash,dot
  14637. * @example
  14638. * ```javascript
  14639. * editor.execCommand( 'insertunorderedlist','circle');
  14640. * ```
  14641. */
  14642. /**
  14643. * 查询当前是否有word文档粘贴进来的图片
  14644. * @command insertunorderedlist
  14645. * @method insertunorderedlist
  14646. * @param { String } command 命令字符串
  14647. * @return { int } 如果当前选区是无序列表返回1,否则返回0
  14648. * @example
  14649. * ```javascript
  14650. * editor.queryCommandState( 'insertunorderedlist' );
  14651. * ```
  14652. */
  14653. /**
  14654. * 查询当前选区内容是否有序列表
  14655. * @command insertunorderedlist
  14656. * @method queryCommandValue
  14657. * @param { String } command 命令字符串
  14658. * @return { String } 返回当前无序列表的类型,值为null或circle,disc,square,dash,dot
  14659. * @example
  14660. * ```javascript
  14661. * editor.queryCommandValue( 'insertunorderedlist' );
  14662. * ```
  14663. */
  14664. me.commands['insertorderedlist'] =
  14665. me.commands['insertunorderedlist'] = {
  14666. execCommand:function (command, style) {
  14667. if (!style) {
  14668. style = command.toLowerCase() == 'insertorderedlist' ? 'decimal' : 'disc';
  14669. }
  14670. var me = this,
  14671. range = this.selection.getRange(),
  14672. filterFn = function (node) {
  14673. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' : !domUtils.isWhitespace(node);
  14674. },
  14675. tag = command.toLowerCase() == 'insertorderedlist' ? 'ol' : 'ul',
  14676. frag = me.document.createDocumentFragment();
  14677. //去掉是因为会出现选到末尾,导致adjustmentBoundary缩到ol/ul的位置
  14678. //range.shrinkBoundary();//.adjustmentBoundary();
  14679. range.adjustmentBoundary().shrinkBoundary();
  14680. var bko = range.createBookmark(true),
  14681. start = getLi(me.document.getElementById(bko.start)),
  14682. modifyStart = 0,
  14683. end = getLi(me.document.getElementById(bko.end)),
  14684. modifyEnd = 0,
  14685. startParent, endParent,
  14686. list, tmp;
  14687. if (start || end) {
  14688. start && (startParent = start.parentNode);
  14689. if (!bko.end) {
  14690. end = start;
  14691. }
  14692. end && (endParent = end.parentNode);
  14693. if (startParent === endParent) {
  14694. while (start !== end) {
  14695. tmp = start;
  14696. start = start.nextSibling;
  14697. if (!domUtils.isBlockElm(tmp.firstChild)) {
  14698. var p = me.document.createElement('p');
  14699. while (tmp.firstChild) {
  14700. p.appendChild(tmp.firstChild);
  14701. }
  14702. tmp.appendChild(p);
  14703. }
  14704. frag.appendChild(tmp);
  14705. }
  14706. tmp = me.document.createElement('span');
  14707. startParent.insertBefore(tmp, end);
  14708. if (!domUtils.isBlockElm(end.firstChild)) {
  14709. p = me.document.createElement('p');
  14710. while (end.firstChild) {
  14711. p.appendChild(end.firstChild);
  14712. }
  14713. end.appendChild(p);
  14714. }
  14715. frag.appendChild(end);
  14716. domUtils.breakParent(tmp, startParent);
  14717. if (domUtils.isEmptyNode(tmp.previousSibling)) {
  14718. domUtils.remove(tmp.previousSibling);
  14719. }
  14720. if (domUtils.isEmptyNode(tmp.nextSibling)) {
  14721. domUtils.remove(tmp.nextSibling)
  14722. }
  14723. var nodeStyle = getStyle(startParent) || domUtils.getComputedStyle(startParent, 'list-style-type') || (command.toLowerCase() == 'insertorderedlist' ? 'decimal' : 'disc');
  14724. if (startParent.tagName.toLowerCase() == tag && nodeStyle == style) {
  14725. for (var i = 0, ci, tmpFrag = me.document.createDocumentFragment(); ci = frag.firstChild;) {
  14726. if(domUtils.isTagNode(ci,'ol ul')){
  14727. // 删除时,子列表不处理
  14728. // utils.each(domUtils.getElementsByTagName(ci,'li'),function(li){
  14729. // while(li.firstChild){
  14730. // tmpFrag.appendChild(li.firstChild);
  14731. // }
  14732. //
  14733. // });
  14734. tmpFrag.appendChild(ci);
  14735. }else{
  14736. while (ci.firstChild) {
  14737. tmpFrag.appendChild(ci.firstChild);
  14738. domUtils.remove(ci);
  14739. }
  14740. }
  14741. }
  14742. tmp.parentNode.insertBefore(tmpFrag, tmp);
  14743. } else {
  14744. list = me.document.createElement(tag);
  14745. setListStyle(list,style);
  14746. list.appendChild(frag);
  14747. tmp.parentNode.insertBefore(list, tmp);
  14748. }
  14749. domUtils.remove(tmp);
  14750. list && adjustList(list, tag, style);
  14751. range.moveToBookmark(bko).select();
  14752. return;
  14753. }
  14754. //开始
  14755. if (start) {
  14756. while (start) {
  14757. tmp = start.nextSibling;
  14758. if (domUtils.isTagNode(start, 'ol ul')) {
  14759. frag.appendChild(start);
  14760. } else {
  14761. var tmpfrag = me.document.createDocumentFragment(),
  14762. hasBlock = 0;
  14763. while (start.firstChild) {
  14764. if (domUtils.isBlockElm(start.firstChild)) {
  14765. hasBlock = 1;
  14766. }
  14767. tmpfrag.appendChild(start.firstChild);
  14768. }
  14769. if (!hasBlock) {
  14770. var tmpP = me.document.createElement('p');
  14771. tmpP.appendChild(tmpfrag);
  14772. frag.appendChild(tmpP);
  14773. } else {
  14774. frag.appendChild(tmpfrag);
  14775. }
  14776. domUtils.remove(start);
  14777. }
  14778. start = tmp;
  14779. }
  14780. startParent.parentNode.insertBefore(frag, startParent.nextSibling);
  14781. if (domUtils.isEmptyNode(startParent)) {
  14782. range.setStartBefore(startParent);
  14783. domUtils.remove(startParent);
  14784. } else {
  14785. range.setStartAfter(startParent);
  14786. }
  14787. modifyStart = 1;
  14788. }
  14789. if (end && domUtils.inDoc(endParent, me.document)) {
  14790. //结束
  14791. start = endParent.firstChild;
  14792. while (start && start !== end) {
  14793. tmp = start.nextSibling;
  14794. if (domUtils.isTagNode(start, 'ol ul')) {
  14795. frag.appendChild(start);
  14796. } else {
  14797. tmpfrag = me.document.createDocumentFragment();
  14798. hasBlock = 0;
  14799. while (start.firstChild) {
  14800. if (domUtils.isBlockElm(start.firstChild)) {
  14801. hasBlock = 1;
  14802. }
  14803. tmpfrag.appendChild(start.firstChild);
  14804. }
  14805. if (!hasBlock) {
  14806. tmpP = me.document.createElement('p');
  14807. tmpP.appendChild(tmpfrag);
  14808. frag.appendChild(tmpP);
  14809. } else {
  14810. frag.appendChild(tmpfrag);
  14811. }
  14812. domUtils.remove(start);
  14813. }
  14814. start = tmp;
  14815. }
  14816. var tmpDiv = domUtils.createElement(me.document, 'div', {
  14817. 'tmpDiv':1
  14818. });
  14819. domUtils.moveChild(end, tmpDiv);
  14820. frag.appendChild(tmpDiv);
  14821. domUtils.remove(end);
  14822. endParent.parentNode.insertBefore(frag, endParent);
  14823. range.setEndBefore(endParent);
  14824. if (domUtils.isEmptyNode(endParent)) {
  14825. domUtils.remove(endParent);
  14826. }
  14827. modifyEnd = 1;
  14828. }
  14829. }
  14830. if (!modifyStart) {
  14831. range.setStartBefore(me.document.getElementById(bko.start));
  14832. }
  14833. if (bko.end && !modifyEnd) {
  14834. range.setEndAfter(me.document.getElementById(bko.end));
  14835. }
  14836. range.enlarge(true, function (node) {
  14837. return notExchange[node.tagName];
  14838. });
  14839. frag = me.document.createDocumentFragment();
  14840. var bk = range.createBookmark(),
  14841. current = domUtils.getNextDomNode(bk.start, false, filterFn),
  14842. tmpRange = range.cloneRange(),
  14843. tmpNode,
  14844. block = domUtils.isBlockElm;
  14845. while (current && current !== bk.end && (domUtils.getPosition(current, bk.end) & domUtils.POSITION_PRECEDING)) {
  14846. if (current.nodeType == 3 || dtd.li[current.tagName]) {
  14847. if (current.nodeType == 1 && dtd.$list[current.tagName]) {
  14848. while (current.firstChild) {
  14849. frag.appendChild(current.firstChild);
  14850. }
  14851. tmpNode = domUtils.getNextDomNode(current, false, filterFn);
  14852. domUtils.remove(current);
  14853. current = tmpNode;
  14854. continue;
  14855. }
  14856. tmpNode = current;
  14857. tmpRange.setStartBefore(current);
  14858. while (current && current !== bk.end && (!block(current) || domUtils.isBookmarkNode(current) )) {
  14859. tmpNode = current;
  14860. current = domUtils.getNextDomNode(current, false, null, function (node) {
  14861. return !notExchange[node.tagName];
  14862. });
  14863. }
  14864. if (current && block(current)) {
  14865. tmp = domUtils.getNextDomNode(tmpNode, false, filterFn);
  14866. if (tmp && domUtils.isBookmarkNode(tmp)) {
  14867. current = domUtils.getNextDomNode(tmp, false, filterFn);
  14868. tmpNode = tmp;
  14869. }
  14870. }
  14871. tmpRange.setEndAfter(tmpNode);
  14872. current = domUtils.getNextDomNode(tmpNode, false, filterFn);
  14873. var li = range.document.createElement('li');
  14874. li.appendChild(tmpRange.extractContents());
  14875. if(domUtils.isEmptyNode(li)){
  14876. var tmpNode = range.document.createElement('p');
  14877. while(li.firstChild){
  14878. tmpNode.appendChild(li.firstChild)
  14879. }
  14880. li.appendChild(tmpNode);
  14881. }
  14882. frag.appendChild(li);
  14883. } else {
  14884. current = domUtils.getNextDomNode(current, true, filterFn);
  14885. }
  14886. }
  14887. range.moveToBookmark(bk).collapse(true);
  14888. list = me.document.createElement(tag);
  14889. setListStyle(list,style);
  14890. list.appendChild(frag);
  14891. range.insertNode(list);
  14892. //当前list上下看能否合并
  14893. adjustList(list, tag, style);
  14894. //去掉冗余的tmpDiv
  14895. for (var i = 0, ci, tmpDivs = domUtils.getElementsByTagName(list, 'div'); ci = tmpDivs[i++];) {
  14896. if (ci.getAttribute('tmpDiv')) {
  14897. domUtils.remove(ci, true)
  14898. }
  14899. }
  14900. range.moveToBookmark(bko).select();
  14901. },
  14902. queryCommandState:function (command) {
  14903. var tag = command.toLowerCase() == 'insertorderedlist' ? 'ol' : 'ul';
  14904. var path = this.selection.getStartElementPath();
  14905. for(var i= 0,ci;ci = path[i++];){
  14906. if(ci.nodeName == 'TABLE'){
  14907. return 0
  14908. }
  14909. if(tag == ci.nodeName.toLowerCase()){
  14910. return 1
  14911. };
  14912. }
  14913. return 0;
  14914. },
  14915. queryCommandValue:function (command) {
  14916. var tag = command.toLowerCase() == 'insertorderedlist' ? 'ol' : 'ul';
  14917. var path = this.selection.getStartElementPath(),
  14918. node;
  14919. for(var i= 0,ci;ci = path[i++];){
  14920. if(ci.nodeName == 'TABLE'){
  14921. node = null;
  14922. break;
  14923. }
  14924. if(tag == ci.nodeName.toLowerCase()){
  14925. node = ci;
  14926. break;
  14927. };
  14928. }
  14929. return node ? getStyle(node) || domUtils.getComputedStyle(node, 'list-style-type') : null;
  14930. }
  14931. };
  14932. };
  14933. // plugins/source.js
  14934. /**
  14935. * 源码编辑插件
  14936. * @file
  14937. * @since 1.2.6.1
  14938. */
  14939. (function (){
  14940. var sourceEditors = {
  14941. textarea: function (editor, holder){
  14942. var textarea = holder.ownerDocument.createElement('textarea');
  14943. textarea.style.cssText = 'position:absolute;resize:none;width:100%;height:100%;border:0;padding:0;margin:0;overflow-y:auto;';
  14944. // todo: IE下只有onresize属性可用... 很纠结
  14945. if (browser.ie && browser.version < 8) {
  14946. textarea.style.width = holder.offsetWidth + 'px';
  14947. textarea.style.height = holder.offsetHeight + 'px';
  14948. holder.onresize = function (){
  14949. textarea.style.width = holder.offsetWidth + 'px';
  14950. textarea.style.height = holder.offsetHeight + 'px';
  14951. };
  14952. }
  14953. holder.appendChild(textarea);
  14954. return {
  14955. setContent: function (content){
  14956. textarea.value = content;
  14957. },
  14958. getContent: function (){
  14959. return textarea.value;
  14960. },
  14961. select: function (){
  14962. var range;
  14963. if (browser.ie) {
  14964. range = textarea.createTextRange();
  14965. range.collapse(true);
  14966. range.select();
  14967. } else {
  14968. //todo: chrome下无法设置焦点
  14969. textarea.setSelectionRange(0, 0);
  14970. textarea.focus();
  14971. }
  14972. },
  14973. dispose: function (){
  14974. holder.removeChild(textarea);
  14975. // todo
  14976. holder.onresize = null;
  14977. textarea = null;
  14978. holder = null;
  14979. }
  14980. };
  14981. },
  14982. codemirror: function (editor, holder){
  14983. var codeEditor = window.CodeMirror(holder, {
  14984. mode: "text/html",
  14985. tabMode: "indent",
  14986. lineNumbers: true,
  14987. lineWrapping:true
  14988. });
  14989. var dom = codeEditor.getWrapperElement();
  14990. dom.style.cssText = 'position:absolute;left:0;top:0;width:100%;height:100%;font-family:consolas,"Courier new",monospace;font-size:13px;';
  14991. codeEditor.getScrollerElement().style.cssText = 'position:absolute;left:0;top:0;width:100%;height:100%;';
  14992. codeEditor.refresh();
  14993. return {
  14994. getCodeMirror:function(){
  14995. return codeEditor;
  14996. },
  14997. setContent: function (content){
  14998. codeEditor.setValue(content);
  14999. },
  15000. getContent: function (){
  15001. return codeEditor.getValue();
  15002. },
  15003. select: function (){
  15004. codeEditor.focus();
  15005. },
  15006. dispose: function (){
  15007. holder.removeChild(dom);
  15008. dom = null;
  15009. codeEditor = null;
  15010. }
  15011. };
  15012. }
  15013. };
  15014. UE.plugins['source'] = function (){
  15015. var me = this;
  15016. var opt = this.options;
  15017. var sourceMode = false;
  15018. var sourceEditor;
  15019. var orgSetContent;
  15020. opt.sourceEditor = browser.ie ? 'textarea' : (opt.sourceEditor || 'codemirror');
  15021. me.setOpt({
  15022. sourceEditorFirst:false
  15023. });
  15024. function createSourceEditor(holder){
  15025. return sourceEditors[opt.sourceEditor == 'codemirror' && window.CodeMirror ? 'codemirror' : 'textarea'](me, holder);
  15026. }
  15027. var bakCssText;
  15028. //解决在源码模式下getContent不能得到最新的内容问题
  15029. var oldGetContent,
  15030. bakAddress;
  15031. /**
  15032. * 切换源码模式和编辑模式
  15033. * @command source
  15034. * @method execCommand
  15035. * @param { String } cmd 命令字符串
  15036. * @example
  15037. * ```javascript
  15038. * editor.execCommand( 'source');
  15039. * ```
  15040. */
  15041. /**
  15042. * 查询当前编辑区域的状态是源码模式还是可视化模式
  15043. * @command source
  15044. * @method queryCommandState
  15045. * @param { String } cmd 命令字符串
  15046. * @return { int } 如果当前是源码编辑模式,返回1,否则返回0
  15047. * @example
  15048. * ```javascript
  15049. * editor.queryCommandState( 'source' );
  15050. * ```
  15051. */
  15052. me.commands['source'] = {
  15053. execCommand: function (){
  15054. sourceMode = !sourceMode;
  15055. if (sourceMode) {
  15056. bakAddress = me.selection.getRange().createAddress(false,true);
  15057. me.undoManger && me.undoManger.save(true);
  15058. if(browser.gecko){
  15059. me.body.contentEditable = false;
  15060. }
  15061. bakCssText = me.iframe.style.cssText;
  15062. me.iframe.style.cssText += 'position:absolute;left:-32768px;top:-32768px;';
  15063. me.fireEvent('beforegetcontent');
  15064. var root = UE.htmlparser(me.body.innerHTML);
  15065. me.filterOutputRule(root);
  15066. root.traversal(function (node) {
  15067. if (node.type == 'element') {
  15068. switch (node.tagName) {
  15069. case 'td':
  15070. case 'th':
  15071. case 'caption':
  15072. if(node.children && node.children.length == 1){
  15073. if(node.firstChild().tagName == 'br' ){
  15074. node.removeChild(node.firstChild())
  15075. }
  15076. };
  15077. break;
  15078. case 'pre':
  15079. node.innerText(node.innerText().replace(/&nbsp;/g,' '))
  15080. }
  15081. }
  15082. });
  15083. me.fireEvent('aftergetcontent');
  15084. var content = root.toHtml(true);
  15085. sourceEditor = createSourceEditor(me.iframe.parentNode);
  15086. sourceEditor.setContent(content);
  15087. orgSetContent = me.setContent;
  15088. me.setContent = function(html){
  15089. //这里暂时不触发事件,防止报错
  15090. var root = UE.htmlparser(html);
  15091. me.filterInputRule(root);
  15092. html = root.toHtml();
  15093. sourceEditor.setContent(html);
  15094. };
  15095. setTimeout(function (){
  15096. sourceEditor.select();
  15097. me.addListener('fullscreenchanged', function(){
  15098. try{
  15099. sourceEditor.getCodeMirror().refresh()
  15100. }catch(e){}
  15101. });
  15102. });
  15103. //重置getContent,源码模式下取值也能是最新的数据
  15104. oldGetContent = me.getContent;
  15105. me.getContent = function (){
  15106. return sourceEditor.getContent() || '<p>' + (browser.ie ? '' : '<br/>')+'</p>';
  15107. };
  15108. } else {
  15109. me.iframe.style.cssText = bakCssText;
  15110. var cont = sourceEditor.getContent() || '<p>' + (browser.ie ? '' : '<br/>')+'</p>';
  15111. //处理掉block节点前后的空格,有可能会误命中,暂时不考虑
  15112. cont = cont.replace(new RegExp('[\\r\\t\\n ]*<\/?(\\w+)\\s*(?:[^>]*)>','g'), function(a,b){
  15113. if(b && !dtd.$inlineWithA[b.toLowerCase()]){
  15114. return a.replace(/(^[\n\r\t ]*)|([\n\r\t ]*$)/g,'');
  15115. }
  15116. return a.replace(/(^[\n\r\t]*)|([\n\r\t]*$)/g,'')
  15117. });
  15118. me.setContent = orgSetContent;
  15119. me.setContent(cont);
  15120. sourceEditor.dispose();
  15121. sourceEditor = null;
  15122. //还原getContent方法
  15123. me.getContent = oldGetContent;
  15124. var first = me.body.firstChild;
  15125. //trace:1106 都删除空了,下边会报错,所以补充一个p占位
  15126. if(!first){
  15127. me.body.innerHTML = '<p>'+(browser.ie?'':'<br/>')+'</p>';
  15128. first = me.body.firstChild;
  15129. }
  15130. //要在ifm为显示时ff才能取到selection,否则报错
  15131. //这里不能比较位置了
  15132. me.undoManger && me.undoManger.save(true);
  15133. if(browser.gecko){
  15134. var input = document.createElement('input');
  15135. input.style.cssText = 'position:absolute;left:0;top:-32768px';
  15136. document.body.appendChild(input);
  15137. me.body.contentEditable = false;
  15138. setTimeout(function(){
  15139. domUtils.setViewportOffset(input, { left: -32768, top: 0 });
  15140. input.focus();
  15141. setTimeout(function(){
  15142. me.body.contentEditable = true;
  15143. me.selection.getRange().moveToAddress(bakAddress).select(true);
  15144. domUtils.remove(input);
  15145. });
  15146. });
  15147. }else{
  15148. //ie下有可能报错,比如在代码顶头的情况
  15149. try{
  15150. me.selection.getRange().moveToAddress(bakAddress).select(true);
  15151. }catch(e){}
  15152. }
  15153. }
  15154. this.fireEvent('sourcemodechanged', sourceMode);
  15155. },
  15156. queryCommandState: function (){
  15157. return sourceMode|0;
  15158. },
  15159. notNeedUndo : 1
  15160. };
  15161. var oldQueryCommandState = me.queryCommandState;
  15162. me.queryCommandState = function (cmdName){
  15163. cmdName = cmdName.toLowerCase();
  15164. if (sourceMode) {
  15165. //源码模式下可以开启的命令
  15166. return cmdName in {
  15167. 'source' : 1,
  15168. 'fullscreen' : 1
  15169. } ? 1 : -1
  15170. }
  15171. return oldQueryCommandState.apply(this, arguments);
  15172. };
  15173. if(opt.sourceEditor == "codemirror"){
  15174. me.addListener("ready",function(){
  15175. utils.loadFile(document,{
  15176. src : opt.codeMirrorJsUrl || opt.UEDITOR_HOME_URL + "third-party/codemirror/codemirror.js",
  15177. tag : "script",
  15178. type : "text/javascript",
  15179. defer : "defer"
  15180. },function(){
  15181. if(opt.sourceEditorFirst){
  15182. setTimeout(function(){
  15183. me.execCommand("source");
  15184. },0);
  15185. }
  15186. });
  15187. utils.loadFile(document,{
  15188. tag : "link",
  15189. rel : "stylesheet",
  15190. type : "text/css",
  15191. href : opt.codeMirrorCssUrl || opt.UEDITOR_HOME_URL + "third-party/codemirror/codemirror.css"
  15192. });
  15193. });
  15194. }
  15195. };
  15196. })();
  15197. // plugins/enterkey.js
  15198. ///import core
  15199. ///import plugins/undo.js
  15200. ///commands 设置回车标签p或br
  15201. ///commandsName EnterKey
  15202. ///commandsTitle 设置回车标签p或br
  15203. /**
  15204. * @description 处理回车
  15205. * @author zhanyi
  15206. */
  15207. UE.plugins['enterkey'] = function() {
  15208. var hTag,
  15209. me = this,
  15210. tag = me.options.enterTag;
  15211. me.addListener('keyup', function(type, evt) {
  15212. var keyCode = evt.keyCode || evt.which;
  15213. if (keyCode == 13) {
  15214. var range = me.selection.getRange(),
  15215. start = range.startContainer,
  15216. doSave;
  15217. //修正在h1-h6里边回车后不能嵌套p的问题
  15218. if (!browser.ie) {
  15219. if (/h\d/i.test(hTag)) {
  15220. if (browser.gecko) {
  15221. var h = domUtils.findParentByTagName(start, [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6','blockquote','caption','table'], true);
  15222. if (!h) {
  15223. me.document.execCommand('formatBlock', false, '<p>');
  15224. doSave = 1;
  15225. }
  15226. } else {
  15227. //chrome remove div
  15228. if (start.nodeType == 1) {
  15229. var tmp = me.document.createTextNode(''),div;
  15230. range.insertNode(tmp);
  15231. div = domUtils.findParentByTagName(tmp, 'div', true);
  15232. if (div) {
  15233. var p = me.document.createElement('p');
  15234. while (div.firstChild) {
  15235. p.appendChild(div.firstChild);
  15236. }
  15237. div.parentNode.insertBefore(p, div);
  15238. domUtils.remove(div);
  15239. range.setStartBefore(tmp).setCursor();
  15240. doSave = 1;
  15241. }
  15242. domUtils.remove(tmp);
  15243. }
  15244. }
  15245. if (me.undoManger && doSave) {
  15246. me.undoManger.save();
  15247. }
  15248. }
  15249. //没有站位符,会出现多行的问题
  15250. browser.opera && range.select();
  15251. }else{
  15252. me.fireEvent('saveScene',true,true)
  15253. }
  15254. }
  15255. });
  15256. me.addListener('keydown', function(type, evt) {
  15257. var keyCode = evt.keyCode || evt.which;
  15258. if (keyCode == 13) {//回车
  15259. if(me.fireEvent('beforeenterkeydown')){
  15260. domUtils.preventDefault(evt);
  15261. return;
  15262. }
  15263. me.fireEvent('saveScene',true,true);
  15264. hTag = '';
  15265. var range = me.selection.getRange();
  15266. if (!range.collapsed) {
  15267. //跨td不能删
  15268. var start = range.startContainer,
  15269. end = range.endContainer,
  15270. startTd = domUtils.findParentByTagName(start, 'td', true),
  15271. endTd = domUtils.findParentByTagName(end, 'td', true);
  15272. if (startTd && endTd && startTd !== endTd || !startTd && endTd || startTd && !endTd) {
  15273. evt.preventDefault ? evt.preventDefault() : ( evt.returnValue = false);
  15274. return;
  15275. }
  15276. }
  15277. if (tag == 'p') {
  15278. if (!browser.ie) {
  15279. start = domUtils.findParentByTagName(range.startContainer, ['ol','ul','p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6','blockquote','caption'], true);
  15280. //opera下执行formatblock会在table的场景下有问题,回车在opera原生支持很好,所以暂时在opera去掉调用这个原生的command
  15281. //trace:2431
  15282. if (!start && !browser.opera) {
  15283. me.document.execCommand('formatBlock', false, '<p>');
  15284. if (browser.gecko) {
  15285. range = me.selection.getRange();
  15286. start = domUtils.findParentByTagName(range.startContainer, 'p', true);
  15287. start && domUtils.removeDirtyAttr(start);
  15288. }
  15289. } else {
  15290. hTag = start.tagName;
  15291. start.tagName.toLowerCase() == 'p' && browser.gecko && domUtils.removeDirtyAttr(start);
  15292. }
  15293. }
  15294. } else {
  15295. evt.preventDefault ? evt.preventDefault() : ( evt.returnValue = false);
  15296. if (!range.collapsed) {
  15297. range.deleteContents();
  15298. start = range.startContainer;
  15299. if (start.nodeType == 1 && (start = start.childNodes[range.startOffset])) {
  15300. while (start.nodeType == 1) {
  15301. if (dtd.$empty[start.tagName]) {
  15302. range.setStartBefore(start).setCursor();
  15303. if (me.undoManger) {
  15304. me.undoManger.save();
  15305. }
  15306. return false;
  15307. }
  15308. if (!start.firstChild) {
  15309. var br = range.document.createElement('br');
  15310. start.appendChild(br);
  15311. range.setStart(start, 0).setCursor();
  15312. if (me.undoManger) {
  15313. me.undoManger.save();
  15314. }
  15315. return false;
  15316. }
  15317. start = start.firstChild;
  15318. }
  15319. if (start === range.startContainer.childNodes[range.startOffset]) {
  15320. br = range.document.createElement('br');
  15321. range.insertNode(br).setCursor();
  15322. } else {
  15323. range.setStart(start, 0).setCursor();
  15324. }
  15325. } else {
  15326. br = range.document.createElement('br');
  15327. range.insertNode(br).setStartAfter(br).setCursor();
  15328. }
  15329. } else {
  15330. br = range.document.createElement('br');
  15331. range.insertNode(br);
  15332. var parent = br.parentNode;
  15333. if (parent.lastChild === br) {
  15334. br.parentNode.insertBefore(br.cloneNode(true), br);
  15335. range.setStartBefore(br);
  15336. } else {
  15337. range.setStartAfter(br);
  15338. }
  15339. range.setCursor();
  15340. }
  15341. }
  15342. }
  15343. });
  15344. };
  15345. // plugins/keystrokes.js
  15346. /* 处理特殊键的兼容性问题 */
  15347. UE.plugins['keystrokes'] = function() {
  15348. var me = this;
  15349. var collapsed = true;
  15350. me.addListener('keydown', function(type, evt) {
  15351. var keyCode = evt.keyCode || evt.which,
  15352. rng = me.selection.getRange();
  15353. //处理全选的情况
  15354. if(!rng.collapsed && !(evt.ctrlKey || evt.shiftKey || evt.altKey || evt.metaKey) && (keyCode >= 65 && keyCode <=90
  15355. || keyCode >= 48 && keyCode <= 57 ||
  15356. keyCode >= 96 && keyCode <= 111 || {
  15357. 13:1,
  15358. 8:1,
  15359. 46:1
  15360. }[keyCode])
  15361. ){
  15362. var tmpNode = rng.startContainer;
  15363. if(domUtils.isFillChar(tmpNode)){
  15364. rng.setStartBefore(tmpNode)
  15365. }
  15366. tmpNode = rng.endContainer;
  15367. if(domUtils.isFillChar(tmpNode)){
  15368. rng.setEndAfter(tmpNode)
  15369. }
  15370. rng.txtToElmBoundary();
  15371. //结束边界可能放到了br的前边,要把br包含进来
  15372. // x[xxx]<br/>
  15373. if(rng.endContainer && rng.endContainer.nodeType == 1){
  15374. tmpNode = rng.endContainer.childNodes[rng.endOffset];
  15375. if(tmpNode && domUtils.isBr(tmpNode)){
  15376. rng.setEndAfter(tmpNode);
  15377. }
  15378. }
  15379. if(rng.startOffset == 0){
  15380. tmpNode = rng.startContainer;
  15381. if(domUtils.isBoundaryNode(tmpNode,'firstChild') ){
  15382. tmpNode = rng.endContainer;
  15383. if(rng.endOffset == (tmpNode.nodeType == 3 ? tmpNode.nodeValue.length : tmpNode.childNodes.length) && domUtils.isBoundaryNode(tmpNode,'lastChild')){
  15384. me.fireEvent('saveScene');
  15385. me.body.innerHTML = '<p>'+(browser.ie ? '' : '<br/>')+'</p>';
  15386. rng.setStart(me.body.firstChild,0).setCursor(false,true);
  15387. me._selectionChange();
  15388. return;
  15389. }
  15390. }
  15391. }
  15392. }
  15393. //处理backspace
  15394. if (keyCode == keymap.Backspace) {
  15395. rng = me.selection.getRange();
  15396. collapsed = rng.collapsed;
  15397. if(me.fireEvent('delkeydown',evt)){
  15398. return;
  15399. }
  15400. var start,end;
  15401. //避免按两次删除才能生效的问题
  15402. if(rng.collapsed && rng.inFillChar()){
  15403. start = rng.startContainer;
  15404. if(domUtils.isFillChar(start)){
  15405. rng.setStartBefore(start).shrinkBoundary(true).collapse(true);
  15406. domUtils.remove(start)
  15407. }else{
  15408. start.nodeValue = start.nodeValue.replace(new RegExp('^' + domUtils.fillChar ),'');
  15409. rng.startOffset--;
  15410. rng.collapse(true).select(true)
  15411. }
  15412. }
  15413. //解决选中control元素不能删除的问题
  15414. if (start = rng.getClosedNode()) {
  15415. me.fireEvent('saveScene');
  15416. rng.setStartBefore(start);
  15417. domUtils.remove(start);
  15418. rng.setCursor();
  15419. me.fireEvent('saveScene');
  15420. domUtils.preventDefault(evt);
  15421. return;
  15422. }
  15423. //阻止在table上的删除
  15424. if (!browser.ie) {
  15425. start = domUtils.findParentByTagName(rng.startContainer, 'table', true);
  15426. end = domUtils.findParentByTagName(rng.endContainer, 'table', true);
  15427. if (start && !end || !start && end || start !== end) {
  15428. evt.preventDefault();
  15429. return;
  15430. }
  15431. }
  15432. }
  15433. //处理tab键的逻辑
  15434. if (keyCode == keymap.Tab) {
  15435. //不处理以下标签
  15436. var excludeTagNameForTabKey = {
  15437. 'ol' : 1,
  15438. 'ul' : 1,
  15439. 'table':1
  15440. };
  15441. //处理组件里的tab按下事件
  15442. if(me.fireEvent('tabkeydown',evt)){
  15443. domUtils.preventDefault(evt);
  15444. return;
  15445. }
  15446. var range = me.selection.getRange();
  15447. me.fireEvent('saveScene');
  15448. for (var i = 0,txt = '',tabSize = me.options.tabSize|| 4,tabNode = me.options.tabNode || '&nbsp;'; i < tabSize; i++) {
  15449. txt += tabNode;
  15450. }
  15451. var span = me.document.createElement('span');
  15452. span.innerHTML = txt + domUtils.fillChar;
  15453. if (range.collapsed) {
  15454. range.insertNode(span.cloneNode(true).firstChild).setCursor(true);
  15455. } else {
  15456. var filterFn = function(node) {
  15457. return domUtils.isBlockElm(node) && !excludeTagNameForTabKey[node.tagName.toLowerCase()]
  15458. };
  15459. //普通的情况
  15460. start = domUtils.findParent(range.startContainer, filterFn,true);
  15461. end = domUtils.findParent(range.endContainer, filterFn,true);
  15462. if (start && end && start === end) {
  15463. range.deleteContents();
  15464. range.insertNode(span.cloneNode(true).firstChild).setCursor(true);
  15465. } else {
  15466. var bookmark = range.createBookmark();
  15467. range.enlarge(true);
  15468. var bookmark2 = range.createBookmark(),
  15469. current = domUtils.getNextDomNode(bookmark2.start, false, filterFn);
  15470. while (current && !(domUtils.getPosition(current, bookmark2.end) & domUtils.POSITION_FOLLOWING)) {
  15471. current.insertBefore(span.cloneNode(true).firstChild, current.firstChild);
  15472. current = domUtils.getNextDomNode(current, false, filterFn);
  15473. }
  15474. range.moveToBookmark(bookmark2).moveToBookmark(bookmark).select();
  15475. }
  15476. }
  15477. domUtils.preventDefault(evt)
  15478. }
  15479. //trace:1634
  15480. //ff的del键在容器空的时候,也会删除
  15481. if(browser.gecko && keyCode == 46){
  15482. range = me.selection.getRange();
  15483. if(range.collapsed){
  15484. start = range.startContainer;
  15485. if(domUtils.isEmptyBlock(start)){
  15486. var parent = start.parentNode;
  15487. while(domUtils.getChildCount(parent) == 1 && !domUtils.isBody(parent)){
  15488. start = parent;
  15489. parent = parent.parentNode;
  15490. }
  15491. if(start === parent.lastChild)
  15492. evt.preventDefault();
  15493. return;
  15494. }
  15495. }
  15496. }
  15497. });
  15498. me.addListener('keyup', function(type, evt) {
  15499. var keyCode = evt.keyCode || evt.which,
  15500. rng,me = this;
  15501. if(keyCode == keymap.Backspace){
  15502. if(me.fireEvent('delkeyup')){
  15503. return;
  15504. }
  15505. rng = me.selection.getRange();
  15506. if(rng.collapsed){
  15507. var tmpNode,
  15508. autoClearTagName = ['h1','h2','h3','h4','h5','h6'];
  15509. if(tmpNode = domUtils.findParentByTagName(rng.startContainer,autoClearTagName,true)){
  15510. if(domUtils.isEmptyBlock(tmpNode)){
  15511. var pre = tmpNode.previousSibling;
  15512. if(pre && pre.nodeName != 'TABLE'){
  15513. domUtils.remove(tmpNode);
  15514. rng.setStartAtLast(pre).setCursor(false,true);
  15515. return;
  15516. }else{
  15517. var next = tmpNode.nextSibling;
  15518. if(next && next.nodeName != 'TABLE'){
  15519. domUtils.remove(tmpNode);
  15520. rng.setStartAtFirst(next).setCursor(false,true);
  15521. return;
  15522. }
  15523. }
  15524. }
  15525. }
  15526. //处理当删除到body时,要重新给p标签展位
  15527. if(domUtils.isBody(rng.startContainer)){
  15528. var tmpNode = domUtils.createElement(me.document,'p',{
  15529. 'innerHTML' : browser.ie ? domUtils.fillChar : '<br/>'
  15530. });
  15531. rng.insertNode(tmpNode).setStart(tmpNode,0).setCursor(false,true);
  15532. }
  15533. }
  15534. //chrome下如果删除了inline标签,浏览器会有记忆,在输入文字还是会套上刚才删除的标签,所以这里再选一次就不会了
  15535. if( !collapsed && (rng.startContainer.nodeType == 3 || rng.startContainer.nodeType == 1 && domUtils.isEmptyBlock(rng.startContainer))){
  15536. if(browser.ie){
  15537. var span = rng.document.createElement('span');
  15538. rng.insertNode(span).setStartBefore(span).collapse(true);
  15539. rng.select();
  15540. domUtils.remove(span)
  15541. }else{
  15542. rng.select()
  15543. }
  15544. }
  15545. }
  15546. })
  15547. };
  15548. // plugins/fiximgclick.js
  15549. ///import core
  15550. ///commands 修复chrome下图片不能点击的问题,出现八个角可改变大小
  15551. ///commandsName FixImgClick
  15552. ///commandsTitle 修复chrome下图片不能点击的问题,出现八个角可改变大小
  15553. //修复chrome下图片不能点击的问题,出现八个角可改变大小
  15554. UE.plugins['fiximgclick'] = (function () {
  15555. var elementUpdated = false;
  15556. function Scale() {
  15557. this.editor = null;
  15558. this.resizer = null;
  15559. this.cover = null;
  15560. this.doc = document;
  15561. this.prePos = {x: 0, y: 0};
  15562. this.startPos = {x: 0, y: 0};
  15563. }
  15564. (function () {
  15565. var rect = [
  15566. //[left, top, width, height]
  15567. [0, 0, -1, -1],
  15568. [0, 0, 0, -1],
  15569. [0, 0, 1, -1],
  15570. [0, 0, -1, 0],
  15571. [0, 0, 1, 0],
  15572. [0, 0, -1, 1],
  15573. [0, 0, 0, 1],
  15574. [0, 0, 1, 1]
  15575. ];
  15576. Scale.prototype = {
  15577. init: function (editor) {
  15578. var me = this;
  15579. me.editor = editor;
  15580. me.startPos = this.prePos = {x: 0, y: 0};
  15581. me.dragId = -1;
  15582. var hands = [],
  15583. cover = me.cover = document.createElement('div'),
  15584. resizer = me.resizer = document.createElement('div');
  15585. cover.id = me.editor.ui.id + '_imagescale_cover';
  15586. cover.style.cssText = 'position:absolute;display:none;z-index:' + (me.editor.options.zIndex) + ';filter:alpha(opacity=0); opacity:0;background:#CCC;';
  15587. domUtils.on(cover, 'mousedown click', function () {
  15588. me.hide();
  15589. });
  15590. for (i = 0; i < 8; i++) {
  15591. hands.push('<span class="edui-editor-imagescale-hand' + i + '"></span>');
  15592. }
  15593. resizer.id = me.editor.ui.id + '_imagescale';
  15594. resizer.className = 'edui-editor-imagescale';
  15595. resizer.innerHTML = hands.join('');
  15596. resizer.style.cssText += ';display:none;border:1px solid #3b77ff;z-index:' + (me.editor.options.zIndex) + ';';
  15597. me.editor.ui.getDom().appendChild(cover);
  15598. me.editor.ui.getDom().appendChild(resizer);
  15599. me.initStyle();
  15600. me.initEvents();
  15601. },
  15602. initStyle: function () {
  15603. utils.cssRule('imagescale', '.edui-editor-imagescale{display:none;position:absolute;border:1px solid #38B2CE;cursor:hand;-webkit-box-sizing: content-box;-moz-box-sizing: content-box;box-sizing: content-box;}' +
  15604. '.edui-editor-imagescale span{position:absolute;width:6px;height:6px;overflow:hidden;font-size:0px;display:block;background-color:#3C9DD0;}'
  15605. + '.edui-editor-imagescale .edui-editor-imagescale-hand0{cursor:nw-resize;top:0;margin-top:-4px;left:0;margin-left:-4px;}'
  15606. + '.edui-editor-imagescale .edui-editor-imagescale-hand1{cursor:n-resize;top:0;margin-top:-4px;left:50%;margin-left:-4px;}'
  15607. + '.edui-editor-imagescale .edui-editor-imagescale-hand2{cursor:ne-resize;top:0;margin-top:-4px;left:100%;margin-left:-3px;}'
  15608. + '.edui-editor-imagescale .edui-editor-imagescale-hand3{cursor:w-resize;top:50%;margin-top:-4px;left:0;margin-left:-4px;}'
  15609. + '.edui-editor-imagescale .edui-editor-imagescale-hand4{cursor:e-resize;top:50%;margin-top:-4px;left:100%;margin-left:-3px;}'
  15610. + '.edui-editor-imagescale .edui-editor-imagescale-hand5{cursor:sw-resize;top:100%;margin-top:-3px;left:0;margin-left:-4px;}'
  15611. + '.edui-editor-imagescale .edui-editor-imagescale-hand6{cursor:s-resize;top:100%;margin-top:-3px;left:50%;margin-left:-4px;}'
  15612. + '.edui-editor-imagescale .edui-editor-imagescale-hand7{cursor:se-resize;top:100%;margin-top:-3px;left:100%;margin-left:-3px;}');
  15613. },
  15614. initEvents: function () {
  15615. var me = this;
  15616. me.startPos.x = me.startPos.y = 0;
  15617. me.isDraging = false;
  15618. },
  15619. _eventHandler: function (e) {
  15620. var me = this;
  15621. switch (e.type) {
  15622. case 'mousedown':
  15623. var hand = e.target || e.srcElement, hand;
  15624. if (hand.className.indexOf('edui-editor-imagescale-hand') != -1 && me.dragId == -1) {
  15625. me.dragId = hand.className.slice(-1);
  15626. me.startPos.x = me.prePos.x = e.clientX;
  15627. me.startPos.y = me.prePos.y = e.clientY;
  15628. domUtils.on(me.doc,'mousemove', me.proxy(me._eventHandler, me));
  15629. }
  15630. break;
  15631. case 'mousemove':
  15632. if (me.dragId != -1) {
  15633. me.updateContainerStyle(me.dragId, {x: e.clientX - me.prePos.x, y: e.clientY - me.prePos.y});
  15634. me.prePos.x = e.clientX;
  15635. me.prePos.y = e.clientY;
  15636. elementUpdated = true;
  15637. me.updateTargetElement();
  15638. }
  15639. break;
  15640. case 'mouseup':
  15641. if (me.dragId != -1) {
  15642. me.updateContainerStyle(me.dragId, {x: e.clientX - me.prePos.x, y: e.clientY - me.prePos.y});
  15643. me.updateTargetElement();
  15644. if (me.target.parentNode) me.attachTo(me.target);
  15645. me.dragId = -1;
  15646. }
  15647. domUtils.un(me.doc,'mousemove', me.proxy(me._eventHandler, me));
  15648. //修复只是点击挪动点,但没有改变大小,不应该触发contentchange
  15649. if(elementUpdated){
  15650. elementUpdated = false;
  15651. me.editor.fireEvent('contentchange');
  15652. }
  15653. break;
  15654. default:
  15655. break;
  15656. }
  15657. },
  15658. updateTargetElement: function () {
  15659. var me = this;
  15660. domUtils.setStyles(me.target, {
  15661. 'width': me.resizer.style.width,
  15662. 'height': me.resizer.style.height
  15663. });
  15664. me.target.width = parseInt(me.resizer.style.width);
  15665. me.target.height = parseInt(me.resizer.style.height);
  15666. me.attachTo(me.target);
  15667. },
  15668. updateContainerStyle: function (dir, offset) {
  15669. var me = this,
  15670. dom = me.resizer, tmp;
  15671. if (rect[dir][0] != 0) {
  15672. tmp = parseInt(dom.style.left) + offset.x;
  15673. dom.style.left = me._validScaledProp('left', tmp) + 'px';
  15674. }
  15675. if (rect[dir][1] != 0) {
  15676. tmp = parseInt(dom.style.top) + offset.y;
  15677. dom.style.top = me._validScaledProp('top', tmp) + 'px';
  15678. }
  15679. if (rect[dir][2] != 0) {
  15680. tmp = dom.clientWidth + rect[dir][2] * offset.x;
  15681. dom.style.width = me._validScaledProp('width', tmp) + 'px';
  15682. }
  15683. if (rect[dir][3] != 0) {
  15684. tmp = dom.clientHeight + rect[dir][3] * offset.y;
  15685. dom.style.height = me._validScaledProp('height', tmp) + 'px';
  15686. }
  15687. },
  15688. _validScaledProp: function (prop, value) {
  15689. var ele = this.resizer,
  15690. wrap = document;
  15691. value = isNaN(value) ? 0 : value;
  15692. switch (prop) {
  15693. case 'left':
  15694. return value < 0 ? 0 : (value + ele.clientWidth) > wrap.clientWidth ? wrap.clientWidth - ele.clientWidth : value;
  15695. case 'top':
  15696. return value < 0 ? 0 : (value + ele.clientHeight) > wrap.clientHeight ? wrap.clientHeight - ele.clientHeight : value;
  15697. case 'width':
  15698. return value <= 0 ? 1 : (value + ele.offsetLeft) > wrap.clientWidth ? wrap.clientWidth - ele.offsetLeft : value;
  15699. case 'height':
  15700. return value <= 0 ? 1 : (value + ele.offsetTop) > wrap.clientHeight ? wrap.clientHeight - ele.offsetTop : value;
  15701. }
  15702. },
  15703. hideCover: function () {
  15704. this.cover.style.display = 'none';
  15705. },
  15706. showCover: function () {
  15707. var me = this,
  15708. editorPos = domUtils.getXY(me.editor.ui.getDom()),
  15709. iframePos = domUtils.getXY(me.editor.iframe);
  15710. domUtils.setStyles(me.cover, {
  15711. 'width': me.editor.iframe.offsetWidth + 'px',
  15712. 'height': me.editor.iframe.offsetHeight + 'px',
  15713. 'top': iframePos.y - editorPos.y + 'px',
  15714. 'left': iframePos.x - editorPos.x + 'px',
  15715. 'position': 'absolute',
  15716. 'display': ''
  15717. })
  15718. },
  15719. show: function (targetObj) {
  15720. var me = this;
  15721. me.resizer.style.display = 'block';
  15722. if(targetObj) me.attachTo(targetObj);
  15723. domUtils.on(this.resizer, 'mousedown', me.proxy(me._eventHandler, me));
  15724. domUtils.on(me.doc, 'mouseup', me.proxy(me._eventHandler, me));
  15725. me.showCover();
  15726. me.editor.fireEvent('afterscaleshow', me);
  15727. me.editor.fireEvent('saveScene');
  15728. },
  15729. hide: function () {
  15730. var me = this;
  15731. me.hideCover();
  15732. me.resizer.style.display = 'none';
  15733. domUtils.un(me.resizer, 'mousedown', me.proxy(me._eventHandler, me));
  15734. domUtils.un(me.doc, 'mouseup', me.proxy(me._eventHandler, me));
  15735. me.editor.fireEvent('afterscalehide', me);
  15736. },
  15737. proxy: function( fn, context ) {
  15738. return function(e) {
  15739. return fn.apply( context || this, arguments);
  15740. };
  15741. },
  15742. attachTo: function (targetObj) {
  15743. var me = this,
  15744. target = me.target = targetObj,
  15745. resizer = this.resizer,
  15746. imgPos = domUtils.getXY(target),
  15747. iframePos = domUtils.getXY(me.editor.iframe),
  15748. editorPos = domUtils.getXY(resizer.parentNode);
  15749. domUtils.setStyles(resizer, {
  15750. 'width': target.width + 'px',
  15751. 'height': target.height + 'px',
  15752. 'left': iframePos.x + imgPos.x - me.editor.document.body.scrollLeft - editorPos.x - parseInt(resizer.style.borderLeftWidth) + 'px',
  15753. 'top': iframePos.y + imgPos.y - me.editor.document.body.scrollTop - editorPos.y - parseInt(resizer.style.borderTopWidth) + 'px'
  15754. });
  15755. }
  15756. }
  15757. })();
  15758. return function () {
  15759. var me = this,
  15760. imageScale;
  15761. me.setOpt('imageScaleEnabled', true);
  15762. if ( !browser.ie && me.options.imageScaleEnabled) {
  15763. me.addListener('click', function (type, e) {
  15764. var range = me.selection.getRange(),
  15765. img = range.getClosedNode();
  15766. if (img && img.tagName == 'IMG' && me.body.contentEditable!="false") {
  15767. if (img.className.indexOf("edui-faked-music") != -1 ||
  15768. img.getAttribute("anchorname") ||
  15769. domUtils.hasClass(img, 'loadingclass') ||
  15770. domUtils.hasClass(img, 'loaderrorclass')) { return }
  15771. if (!imageScale) {
  15772. imageScale = new Scale();
  15773. imageScale.init(me);
  15774. me.ui.getDom().appendChild(imageScale.resizer);
  15775. var _keyDownHandler = function (e) {
  15776. imageScale.hide();
  15777. if(imageScale.target) me.selection.getRange().selectNode(imageScale.target).select();
  15778. }, _mouseDownHandler = function (e) {
  15779. var ele = e.target || e.srcElement;
  15780. if (ele && (ele.className===undefined || ele.className.indexOf('edui-editor-imagescale') == -1)) {
  15781. _keyDownHandler(e);
  15782. }
  15783. }, timer;
  15784. me.addListener('afterscaleshow', function (e) {
  15785. me.addListener('beforekeydown', _keyDownHandler);
  15786. me.addListener('beforemousedown', _mouseDownHandler);
  15787. domUtils.on(document, 'keydown', _keyDownHandler);
  15788. domUtils.on(document,'mousedown', _mouseDownHandler);
  15789. me.selection.getNative().removeAllRanges();
  15790. });
  15791. me.addListener('afterscalehide', function (e) {
  15792. me.removeListener('beforekeydown', _keyDownHandler);
  15793. me.removeListener('beforemousedown', _mouseDownHandler);
  15794. domUtils.un(document, 'keydown', _keyDownHandler);
  15795. domUtils.un(document,'mousedown', _mouseDownHandler);
  15796. var target = imageScale.target;
  15797. if (target.parentNode) {
  15798. me.selection.getRange().selectNode(target).select();
  15799. }
  15800. });
  15801. //TODO 有iframe的情况,mousedown不能往下传。。
  15802. domUtils.on(imageScale.resizer, 'mousedown', function (e) {
  15803. me.selection.getNative().removeAllRanges();
  15804. var ele = e.target || e.srcElement;
  15805. if (ele && ele.className.indexOf('edui-editor-imagescale-hand') == -1) {
  15806. timer = setTimeout(function () {
  15807. imageScale.hide();
  15808. if(imageScale.target) me.selection.getRange().selectNode(ele).select();
  15809. }, 200);
  15810. }
  15811. });
  15812. domUtils.on(imageScale.resizer, 'mouseup', function (e) {
  15813. var ele = e.target || e.srcElement;
  15814. if (ele && ele.className.indexOf('edui-editor-imagescale-hand') == -1) {
  15815. clearTimeout(timer);
  15816. }
  15817. });
  15818. }
  15819. imageScale.show(img);
  15820. } else {
  15821. if (imageScale && imageScale.resizer.style.display != 'none') imageScale.hide();
  15822. }
  15823. });
  15824. }
  15825. if (browser.webkit) {
  15826. me.addListener('click', function (type, e) {
  15827. if (e.target.tagName == 'IMG' && me.body.contentEditable!="false") {
  15828. var range = new dom.Range(me.document);
  15829. range.selectNode(e.target).select();
  15830. }
  15831. });
  15832. }
  15833. }
  15834. })();
  15835. // plugins/autolink.js
  15836. ///import core
  15837. ///commands 为非ie浏览器自动添加a标签
  15838. ///commandsName AutoLink
  15839. ///commandsTitle 自动增加链接
  15840. /**
  15841. * @description 为非ie浏览器自动添加a标签
  15842. * @author zhanyi
  15843. */
  15844. UE.plugin.register('autolink',function(){
  15845. var cont = 0;
  15846. return !browser.ie ? {
  15847. bindEvents:{
  15848. 'reset' : function(){
  15849. cont = 0;
  15850. },
  15851. 'keydown':function(type, evt) {
  15852. var me = this;
  15853. var keyCode = evt.keyCode || evt.which;
  15854. if (keyCode == 32 || keyCode == 13) {
  15855. var sel = me.selection.getNative(),
  15856. range = sel.getRangeAt(0).cloneRange(),
  15857. offset,
  15858. charCode;
  15859. var start = range.startContainer;
  15860. while (start.nodeType == 1 && range.startOffset > 0) {
  15861. start = range.startContainer.childNodes[range.startOffset - 1];
  15862. if (!start){
  15863. break;
  15864. }
  15865. range.setStart(start, start.nodeType == 1 ? start.childNodes.length : start.nodeValue.length);
  15866. range.collapse(true);
  15867. start = range.startContainer;
  15868. }
  15869. do{
  15870. if (range.startOffset == 0) {
  15871. start = range.startContainer.previousSibling;
  15872. while (start && start.nodeType == 1) {
  15873. start = start.lastChild;
  15874. }
  15875. if (!start || domUtils.isFillChar(start)){
  15876. break;
  15877. }
  15878. offset = start.nodeValue.length;
  15879. } else {
  15880. start = range.startContainer;
  15881. offset = range.startOffset;
  15882. }
  15883. range.setStart(start, offset - 1);
  15884. charCode = range.toString().charCodeAt(0);
  15885. } while (charCode != 160 && charCode != 32);
  15886. if (range.toString().replace(new RegExp(domUtils.fillChar, 'g'), '').match(/(?:https?:\/\/|ssh:\/\/|ftp:\/\/|file:\/|www\.)/i)) {
  15887. while(range.toString().length){
  15888. if(/^(?:https?:\/\/|ssh:\/\/|ftp:\/\/|file:\/|www\.)/i.test(range.toString())){
  15889. break;
  15890. }
  15891. try{
  15892. range.setStart(range.startContainer,range.startOffset+1);
  15893. }catch(e){
  15894. //trace:2121
  15895. var start = range.startContainer;
  15896. while(!(next = start.nextSibling)){
  15897. if(domUtils.isBody(start)){
  15898. return;
  15899. }
  15900. start = start.parentNode;
  15901. }
  15902. range.setStart(next,0);
  15903. }
  15904. }
  15905. //range的开始边界已经在a标签里的不再处理
  15906. if(domUtils.findParentByTagName(range.startContainer,'a',true)){
  15907. return;
  15908. }
  15909. var a = me.document.createElement('a'),text = me.document.createTextNode(' '),href;
  15910. me.undoManger && me.undoManger.save();
  15911. a.appendChild(range.extractContents());
  15912. a.href = a.innerHTML = a.innerHTML.replace(/<[^>]+>/g,'');
  15913. href = a.getAttribute("href").replace(new RegExp(domUtils.fillChar,'g'),'');
  15914. href = /^(?:https?:\/\/)/ig.test(href) ? href : "http://"+ href;
  15915. a.setAttribute('_src',utils.html(href));
  15916. a.href = utils.html(href);
  15917. range.insertNode(a);
  15918. a.parentNode.insertBefore(text, a.nextSibling);
  15919. range.setStart(text, 0);
  15920. range.collapse(true);
  15921. sel.removeAllRanges();
  15922. sel.addRange(range);
  15923. me.undoManger && me.undoManger.save();
  15924. }
  15925. }
  15926. }
  15927. }
  15928. }:{}
  15929. },function(){
  15930. var keyCodes = {
  15931. 37:1, 38:1, 39:1, 40:1,
  15932. 13:1,32:1
  15933. };
  15934. function checkIsCludeLink(node){
  15935. if(node.nodeType == 3){
  15936. return null
  15937. }
  15938. if(node.nodeName == 'A'){
  15939. return node;
  15940. }
  15941. var lastChild = node.lastChild;
  15942. while(lastChild){
  15943. if(lastChild.nodeName == 'A'){
  15944. return lastChild;
  15945. }
  15946. if(lastChild.nodeType == 3){
  15947. if(domUtils.isWhitespace(lastChild)){
  15948. lastChild = lastChild.previousSibling;
  15949. continue;
  15950. }
  15951. return null
  15952. }
  15953. lastChild = lastChild.lastChild;
  15954. }
  15955. }
  15956. browser.ie && this.addListener('keyup',function(cmd,evt){
  15957. var me = this,keyCode = evt.keyCode;
  15958. if(keyCodes[keyCode]){
  15959. var rng = me.selection.getRange();
  15960. var start = rng.startContainer;
  15961. if(keyCode == 13){
  15962. while(start && !domUtils.isBody(start) && !domUtils.isBlockElm(start)){
  15963. start = start.parentNode;
  15964. }
  15965. if(start && !domUtils.isBody(start) && start.nodeName == 'P'){
  15966. var pre = start.previousSibling;
  15967. if(pre && pre.nodeType == 1){
  15968. var pre = checkIsCludeLink(pre);
  15969. if(pre && !pre.getAttribute('_href')){
  15970. domUtils.remove(pre,true);
  15971. }
  15972. }
  15973. }
  15974. }else if(keyCode == 32 ){
  15975. if(start.nodeType == 3 && /^\s$/.test(start.nodeValue)){
  15976. start = start.previousSibling;
  15977. if(start && start.nodeName == 'A' && !start.getAttribute('_href')){
  15978. domUtils.remove(start,true);
  15979. }
  15980. }
  15981. }else {
  15982. start = domUtils.findParentByTagName(start,'a',true);
  15983. if(start && !start.getAttribute('_href')){
  15984. var bk = rng.createBookmark();
  15985. domUtils.remove(start,true);
  15986. rng.moveToBookmark(bk).select(true)
  15987. }
  15988. }
  15989. }
  15990. });
  15991. }
  15992. );
  15993. // plugins/autoheight.js
  15994. ///import core
  15995. ///commands 当输入内容超过编辑器高度时,编辑器自动增高
  15996. ///commandsName AutoHeight,autoHeightEnabled
  15997. ///commandsTitle 自动增高
  15998. /**
  15999. * @description 自动伸展
  16000. * @author zhanyi
  16001. */
  16002. UE.plugins['autoheight'] = function () {
  16003. var me = this;
  16004. //提供开关,就算加载也可以关闭
  16005. me.autoHeightEnabled = me.options.autoHeightEnabled !== false;
  16006. if (!me.autoHeightEnabled) {
  16007. return;
  16008. }
  16009. var bakOverflow,
  16010. lastHeight = 0,
  16011. options = me.options,
  16012. currentHeight,
  16013. timer;
  16014. function adjustHeight() {
  16015. var me = this;
  16016. clearTimeout(timer);
  16017. if(isFullscreen)return;
  16018. if (!me.queryCommandState || me.queryCommandState && me.queryCommandState('source') != 1) {
  16019. timer = setTimeout(function(){
  16020. var node = me.body.lastChild;
  16021. while(node && node.nodeType != 1){
  16022. node = node.previousSibling;
  16023. }
  16024. if(node && node.nodeType == 1){
  16025. node.style.clear = 'both';
  16026. currentHeight = Math.max(domUtils.getXY(node).y + node.offsetHeight + 25 ,Math.max(options.minFrameHeight, options.initialFrameHeight)) ;
  16027. if (currentHeight != lastHeight) {
  16028. if (currentHeight !== parseInt(me.iframe.parentNode.style.height)) {
  16029. me.iframe.parentNode.style.height = currentHeight + 'px';
  16030. }
  16031. me.body.style.height = currentHeight + 'px';
  16032. lastHeight = currentHeight;
  16033. }
  16034. domUtils.removeStyle(node,'clear');
  16035. }
  16036. },50)
  16037. }
  16038. }
  16039. var isFullscreen;
  16040. me.addListener('fullscreenchanged',function(cmd,f){
  16041. isFullscreen = f
  16042. });
  16043. me.addListener('destroy', function () {
  16044. me.removeListener('contentchange afterinserthtml keyup mouseup',adjustHeight)
  16045. });
  16046. me.enableAutoHeight = function () {
  16047. var me = this;
  16048. if (!me.autoHeightEnabled) {
  16049. return;
  16050. }
  16051. var doc = me.document;
  16052. me.autoHeightEnabled = true;
  16053. bakOverflow = doc.body.style.overflowY;
  16054. doc.body.style.overflowY = 'hidden';
  16055. me.addListener('contentchange afterinserthtml keyup mouseup',adjustHeight);
  16056. //ff不给事件算得不对
  16057. setTimeout(function () {
  16058. adjustHeight.call(me);
  16059. }, browser.gecko ? 100 : 0);
  16060. me.fireEvent('autoheightchanged', me.autoHeightEnabled);
  16061. };
  16062. me.disableAutoHeight = function () {
  16063. me.body.style.overflowY = bakOverflow || '';
  16064. me.removeListener('contentchange', adjustHeight);
  16065. me.removeListener('keyup', adjustHeight);
  16066. me.removeListener('mouseup', adjustHeight);
  16067. me.autoHeightEnabled = false;
  16068. me.fireEvent('autoheightchanged', me.autoHeightEnabled);
  16069. };
  16070. me.on('setHeight',function(){
  16071. me.disableAutoHeight()
  16072. });
  16073. me.addListener('ready', function () {
  16074. me.enableAutoHeight();
  16075. //trace:1764
  16076. var timer;
  16077. domUtils.on(browser.ie ? me.body : me.document, browser.webkit ? 'dragover' : 'drop', function () {
  16078. clearTimeout(timer);
  16079. timer = setTimeout(function () {
  16080. //trace:3681
  16081. adjustHeight.call(me);
  16082. }, 100);
  16083. });
  16084. //修复内容过多时,回到顶部,顶部内容被工具栏遮挡问题
  16085. var lastScrollY;
  16086. window.onscroll = function(){
  16087. if(lastScrollY === null){
  16088. lastScrollY = this.scrollY
  16089. }else if(this.scrollY == 0 && lastScrollY != 0){
  16090. me.window.scrollTo(0,0);
  16091. lastScrollY = null;
  16092. }
  16093. }
  16094. });
  16095. };
  16096. // plugins/autofloat.js
  16097. ///import core
  16098. ///commands 悬浮工具栏
  16099. ///commandsName AutoFloat,autoFloatEnabled
  16100. ///commandsTitle 悬浮工具栏
  16101. /**
  16102. * modified by chengchao01
  16103. * 注意: 引入此功能后,在IE6下会将body的背景图片覆盖掉!
  16104. */
  16105. UE.plugins['autofloat'] = function() {
  16106. var me = this,
  16107. lang = me.getLang();
  16108. me.setOpt({
  16109. topOffset:0
  16110. });
  16111. var optsAutoFloatEnabled = me.options.autoFloatEnabled !== false,
  16112. topOffset = me.options.topOffset;
  16113. //如果不固定toolbar的位置,则直接退出
  16114. if(!optsAutoFloatEnabled){
  16115. return;
  16116. }
  16117. var uiUtils = UE.ui.uiUtils,
  16118. LteIE6 = browser.ie && browser.version <= 6,
  16119. quirks = browser.quirks;
  16120. function checkHasUI(){
  16121. if(!UE.ui){
  16122. alert(lang.autofloatMsg);
  16123. return 0;
  16124. }
  16125. return 1;
  16126. }
  16127. function fixIE6FixedPos(){
  16128. var docStyle = document.body.style;
  16129. docStyle.backgroundImage = 'url("about:blank")';
  16130. docStyle.backgroundAttachment = 'fixed';
  16131. }
  16132. var bakCssText,
  16133. placeHolder = document.createElement('div'),
  16134. toolbarBox,orgTop,
  16135. getPosition,
  16136. flag =true; //ie7模式下需要偏移
  16137. function setFloating(){
  16138. var toobarBoxPos = domUtils.getXY(toolbarBox),
  16139. origalFloat = domUtils.getComputedStyle(toolbarBox,'position'),
  16140. origalLeft = domUtils.getComputedStyle(toolbarBox,'left');
  16141. toolbarBox.style.width = toolbarBox.offsetWidth + 'px';
  16142. toolbarBox.style.zIndex = me.options.zIndex * 1 + 1;
  16143. toolbarBox.parentNode.insertBefore(placeHolder, toolbarBox);
  16144. if (LteIE6 || (quirks && browser.ie)) {
  16145. if(toolbarBox.style.position != 'absolute'){
  16146. toolbarBox.style.position = 'absolute';
  16147. }
  16148. toolbarBox.style.top = (document.body.scrollTop||document.documentElement.scrollTop) - orgTop + topOffset + 'px';
  16149. } else {
  16150. if (browser.ie7Compat && flag) {
  16151. flag = false;
  16152. toolbarBox.style.left = domUtils.getXY(toolbarBox).x - document.documentElement.getBoundingClientRect().left+2 + 'px';
  16153. }
  16154. if(toolbarBox.style.position != 'fixed'){
  16155. toolbarBox.style.position = 'fixed';
  16156. toolbarBox.style.top = topOffset +"px";
  16157. ((origalFloat == 'absolute' || origalFloat == 'relative') && parseFloat(origalLeft)) && (toolbarBox.style.left = toobarBoxPos.x + 'px');
  16158. }
  16159. }
  16160. }
  16161. function unsetFloating(){
  16162. flag = true;
  16163. if(placeHolder.parentNode){
  16164. placeHolder.parentNode.removeChild(placeHolder);
  16165. }
  16166. toolbarBox.style.cssText = bakCssText;
  16167. }
  16168. function updateFloating(){
  16169. var rect3 = getPosition(me.container);
  16170. var offset=me.options.toolbarTopOffset||0;
  16171. if (rect3.top < 0 && rect3.bottom - toolbarBox.offsetHeight > offset) {
  16172. setFloating();
  16173. }else{
  16174. unsetFloating();
  16175. }
  16176. }
  16177. var defer_updateFloating = utils.defer(function(){
  16178. updateFloating();
  16179. },browser.ie ? 200 : 100,true);
  16180. me.addListener('destroy',function(){
  16181. domUtils.un(window, ['scroll','resize'], updateFloating);
  16182. me.removeListener('keydown', defer_updateFloating);
  16183. });
  16184. me.addListener('ready', function(){
  16185. if(checkHasUI(me)){
  16186. //加载了ui组件,但在new时,没有加载ui,导致编辑器实例上没有ui类,所以这里做判断
  16187. if(!me.ui){
  16188. return;
  16189. }
  16190. getPosition = uiUtils.getClientRect;
  16191. toolbarBox = me.ui.getDom('toolbarbox');
  16192. orgTop = getPosition(toolbarBox).top;
  16193. bakCssText = toolbarBox.style.cssText;
  16194. placeHolder.style.height = toolbarBox.offsetHeight + 'px';
  16195. if(LteIE6){
  16196. fixIE6FixedPos();
  16197. }
  16198. domUtils.on(window, ['scroll','resize'], updateFloating);
  16199. me.addListener('keydown', defer_updateFloating);
  16200. me.addListener('beforefullscreenchange', function (t, enabled){
  16201. if (enabled) {
  16202. unsetFloating();
  16203. }
  16204. });
  16205. me.addListener('fullscreenchanged', function (t, enabled){
  16206. if (!enabled) {
  16207. updateFloating();
  16208. }
  16209. });
  16210. me.addListener('sourcemodechanged', function (t, enabled){
  16211. setTimeout(function (){
  16212. updateFloating();
  16213. },0);
  16214. });
  16215. me.addListener("clearDoc",function(){
  16216. setTimeout(function(){
  16217. updateFloating();
  16218. },0);
  16219. })
  16220. }
  16221. });
  16222. };
  16223. // plugins/video.js
  16224. /**
  16225. * video插件, 为UEditor提供视频插入支持
  16226. * @file
  16227. * @since 1.2.6.1
  16228. */
  16229. UE.plugins['video'] = function (){
  16230. var me =this;
  16231. /**
  16232. * 创建插入视频字符窜
  16233. * @param url 视频地址
  16234. * @param width 视频宽度
  16235. * @param height 视频高度
  16236. * @param align 视频对齐
  16237. * @param toEmbed 是否以flash代替显示
  16238. * @param addParagraph 是否需要添加P 标签
  16239. */
  16240. function creatInsertStr(url,width,height,id,align,classname,type){
  16241. url = utils.unhtmlForUrl(url);
  16242. align = utils.unhtml(align);
  16243. classname = utils.unhtml(classname);
  16244. width = parseInt(width, 10) || 0;
  16245. height = parseInt(height, 10) || 0;
  16246. var str;
  16247. switch (type){
  16248. case 'image':
  16249. str = '<img ' + (id ? 'id="' + id+'"' : '') + ' width="'+ width +'" height="' + height + '" _url="'+url+'" class="' + classname.replace(/\bvideo-js\b/, '') + '"' +
  16250. ' src="' + me.options.UEDITOR_HOME_URL+'themes/default/images/spacer.gif" style="background:url('+me.options.UEDITOR_HOME_URL+'themes/default/images/videologo.gif) no-repeat center center; border:1px solid gray;'+(align ? 'float:' + align + ';': '')+'" />'
  16251. break;
  16252. case 'embed':
  16253. str = '<embed type="application/x-shockwave-flash" class="' + classname + '" pluginspage="http://www.macromedia.com/go/getflashplayer"' +
  16254. ' src="' + utils.html(url) + '" width="' + width + '" height="' + height + '"' + (align ? ' style="float:' + align + '"': '') +
  16255. ' wmode="transparent" play="true" loop="false" menu="false" allowscriptaccess="never" allowfullscreen="true" >';
  16256. break;
  16257. case 'video':
  16258. var ext = url.substr(url.lastIndexOf('.') + 1);
  16259. if(ext == 'ogv') ext = 'ogg';
  16260. //使之可以上传mp3
  16261. if(ext == 'mp3'){
  16262. str = '<audio' + (id ? ' id="' + id + '"' : '') + ' class=" audio-js" ' + (align ? ' style="float:' + align + '"': '') +
  16263. ' controls preload="none" width="' + width + '" height="' + height + '" src="' + url + '">" /></audio>';
  16264. }else{
  16265. str = '<video' + (id ? ' id="' + id + '"' : '') + ' class="' + classname + ' video-js" ' + (align ? ' style="float:' + align + '"': '') +
  16266. ' controls preload="none" width="' + width + '" height="' + height + '" src="' + url + '" data-setup="{}">' +
  16267. '<source src="' + url + '" type="video/' + ext + '" /></video>';}
  16268. break;
  16269. }
  16270. return str;
  16271. }
  16272. function switchImgAndVideo(root,img2video){
  16273. utils.each(root.getNodesByTagName(img2video ? 'img' : 'embed video'),function(node){
  16274. var className = node.getAttr('class');
  16275. if(className && className.indexOf('edui-faked-video') != -1){
  16276. var html = creatInsertStr( img2video ? node.getAttr('_url') : node.getAttr('src'),node.getAttr('width'),node.getAttr('height'),null,node.getStyle('float') || '',className,img2video ? 'embed':'image');
  16277. node.parentNode.replaceChild(UE.uNode.createElement(html),node);
  16278. }
  16279. if(className && className.indexOf('edui-upload-video') != -1){
  16280. var html = creatInsertStr( img2video ? node.getAttr('_url') : node.getAttr('src'),node.getAttr('width'),node.getAttr('height'),null,node.getStyle('float') || '',className,img2video ? 'video':'image');
  16281. node.parentNode.replaceChild(UE.uNode.createElement(html),node);
  16282. }
  16283. })
  16284. }
  16285. me.addOutputRule(function(root){
  16286. switchImgAndVideo(root,true)
  16287. });
  16288. me.addInputRule(function(root){
  16289. switchImgAndVideo(root)
  16290. });
  16291. /**
  16292. * 插入视频
  16293. * @command insertvideo
  16294. * @method execCommand
  16295. * @param { String } cmd 命令字符串
  16296. * @param { Object } videoAttr 键值对对象, 描述一个视频的所有属性
  16297. * @example
  16298. * ```javascript
  16299. *
  16300. * var videoAttr = {
  16301. * //视频地址
  16302. * url: 'http://www.youku.com/xxx',
  16303. * //视频宽高值, 单位px
  16304. * width: 200,
  16305. * height: 100
  16306. * };
  16307. *
  16308. * //editor 是编辑器实例
  16309. * //向编辑器插入单个视频
  16310. * editor.execCommand( 'insertvideo', videoAttr );
  16311. * ```
  16312. */
  16313. /**
  16314. * 插入视频
  16315. * @command insertvideo
  16316. * @method execCommand
  16317. * @param { String } cmd 命令字符串
  16318. * @param { Array } videoArr 需要插入的视频的数组, 其中的每一个元素都是一个键值对对象, 描述了一个视频的所有属性
  16319. * @example
  16320. * ```javascript
  16321. *
  16322. * var videoAttr1 = {
  16323. * //视频地址
  16324. * url: 'http://www.youku.com/xxx',
  16325. * //视频宽高值, 单位px
  16326. * width: 200,
  16327. * height: 100
  16328. * },
  16329. * videoAttr2 = {
  16330. * //视频地址
  16331. * url: 'http://www.youku.com/xxx',
  16332. * //视频宽高值, 单位px
  16333. * width: 200,
  16334. * height: 100
  16335. * }
  16336. *
  16337. * //editor 是编辑器实例
  16338. * //该方法将会向编辑器内插入两个视频
  16339. * editor.execCommand( 'insertvideo', [ videoAttr1, videoAttr2 ] );
  16340. * ```
  16341. */
  16342. /**
  16343. * 查询当前光标所在处是否是一个视频
  16344. * @command insertvideo
  16345. * @method queryCommandState
  16346. * @param { String } cmd 需要查询的命令字符串
  16347. * @return { int } 如果当前光标所在处的元素是一个视频对象, 则返回1,否则返回0
  16348. * @example
  16349. * ```javascript
  16350. *
  16351. * //editor 是编辑器实例
  16352. * editor.queryCommandState( 'insertvideo' );
  16353. * ```
  16354. */
  16355. me.commands["insertvideo"] = {
  16356. execCommand: function (cmd, videoObjs, type){
  16357. videoObjs = utils.isArray(videoObjs)?videoObjs:[videoObjs];
  16358. var html = [],id = 'tmpVedio', cl;
  16359. for(var i=0,vi,len = videoObjs.length;i<len;i++){
  16360. vi = videoObjs[i];
  16361. cl = (type == 'upload' ? 'edui-upload-video video-js vjs-default-skin':'edui-faked-video');
  16362. html.push(creatInsertStr( vi.url, vi.width || 420, vi.height || 280, id + i, null, cl, 'image'));
  16363. }
  16364. me.execCommand("inserthtml",html.join(""),true);
  16365. var rng = this.selection.getRange();
  16366. for(var i= 0,len=videoObjs.length;i<len;i++){
  16367. var img = this.document.getElementById('tmpVedio'+i);
  16368. domUtils.removeAttributes(img,'id');
  16369. rng.selectNode(img).select();
  16370. me.execCommand('imagefloat',videoObjs[i].align)
  16371. }
  16372. },
  16373. queryCommandState : function(){
  16374. var img = me.selection.getRange().getClosedNode(),
  16375. flag = img && (img.className == "edui-faked-video" || img.className.indexOf("edui-upload-video")!=-1);
  16376. return flag ? 1 : 0;
  16377. }
  16378. };
  16379. };
  16380. // plugins/table.core.js
  16381. /**
  16382. * Created with JetBrains WebStorm.
  16383. * User: taoqili
  16384. * Date: 13-1-18
  16385. * Time: 上午11:09
  16386. * To change this template use File | Settings | File Templates.
  16387. */
  16388. /**
  16389. * UE表格操作类
  16390. * @param table
  16391. * @constructor
  16392. */
  16393. (function () {
  16394. var UETable = UE.UETable = function (table) {
  16395. this.table = table;
  16396. this.indexTable = [];
  16397. this.selectedTds = [];
  16398. this.cellsRange = {};
  16399. this.update(table);
  16400. };
  16401. //===以下为静态工具方法===
  16402. UETable.removeSelectedClass = function (cells) {
  16403. utils.each(cells, function (cell) {
  16404. domUtils.removeClasses(cell, "selectTdClass");
  16405. })
  16406. };
  16407. UETable.addSelectedClass = function (cells) {
  16408. utils.each(cells, function (cell) {
  16409. domUtils.addClass(cell, "selectTdClass");
  16410. })
  16411. };
  16412. UETable.isEmptyBlock = function (node) {
  16413. var reg = new RegExp(domUtils.fillChar, 'g');
  16414. if (node[browser.ie ? 'innerText' : 'textContent'].replace(/^\s*$/, '').replace(reg, '').length > 0) {
  16415. return 0;
  16416. }
  16417. for (var i in dtd.$isNotEmpty) if (dtd.$isNotEmpty.hasOwnProperty(i)) {
  16418. if (node.getElementsByTagName(i).length) {
  16419. return 0;
  16420. }
  16421. }
  16422. return 1;
  16423. };
  16424. UETable.getWidth = function (cell) {
  16425. if (!cell)return 0;
  16426. return parseInt(domUtils.getComputedStyle(cell, "width"), 10);
  16427. };
  16428. /**
  16429. * 获取单元格或者单元格组的“对齐”状态。 如果当前的检测对象是一个单元格组, 只有在满足所有单元格的 水平和竖直 对齐属性都相同的
  16430. * 条件时才会返回其状态值,否则将返回null; 如果当前只检测了一个单元格, 则直接返回当前单元格的对齐状态;
  16431. * @param table cell or table cells , 支持单个单元格dom对象 或者 单元格dom对象数组
  16432. * @return { align: 'left' || 'right' || 'center', valign: 'top' || 'middle' || 'bottom' } 或者 null
  16433. */
  16434. UETable.getTableCellAlignState = function ( cells ) {
  16435. !utils.isArray( cells ) && ( cells = [cells] );
  16436. var result = {},
  16437. status = ['align', 'valign'],
  16438. tempStatus = null,
  16439. isSame = true;//状态是否相同
  16440. utils.each( cells, function( cellNode ){
  16441. utils.each( status, function( currentState ){
  16442. tempStatus = cellNode.getAttribute( currentState );
  16443. if( !result[ currentState ] && tempStatus ) {
  16444. result[ currentState ] = tempStatus;
  16445. } else if( !result[ currentState ] || ( tempStatus !== result[ currentState ] ) ) {
  16446. isSame = false;
  16447. return false;
  16448. }
  16449. } );
  16450. return isSame;
  16451. });
  16452. return isSame ? result : null;
  16453. };
  16454. /**
  16455. * 根据当前选区获取相关的table信息
  16456. * @return {Object}
  16457. */
  16458. UETable.getTableItemsByRange = function (editor) {
  16459. var start = editor.selection.getStart();
  16460. //ff下会选中bookmark
  16461. if( start && start.id && start.id.indexOf('_baidu_bookmark_start_') === 0 && start.nextSibling) {
  16462. start = start.nextSibling;
  16463. }
  16464. //在table或者td边缘有可能存在选中tr的情况
  16465. var cell = start && domUtils.findParentByTagName(start, ["td", "th"], true),
  16466. tr = cell && cell.parentNode,
  16467. caption = start && domUtils.findParentByTagName(start, 'caption', true),
  16468. table = caption ? caption.parentNode : tr && tr.parentNode.parentNode;
  16469. return {
  16470. cell:cell,
  16471. tr:tr,
  16472. table:table,
  16473. caption:caption
  16474. }
  16475. };
  16476. UETable.getUETableBySelected = function (editor) {
  16477. var table = UETable.getTableItemsByRange(editor).table;
  16478. if (table && table.ueTable && table.ueTable.selectedTds.length) {
  16479. return table.ueTable;
  16480. }
  16481. return null;
  16482. };
  16483. UETable.getDefaultValue = function (editor, table) {
  16484. var borderMap = {
  16485. thin:'0px',
  16486. medium:'1px',
  16487. thick:'2px'
  16488. },
  16489. tableBorder, tdPadding, tdBorder, tmpValue;
  16490. if (!table) {
  16491. table = editor.document.createElement('table');
  16492. table.insertRow(0).insertCell(0).innerHTML = 'xxx';
  16493. editor.body.appendChild(table);
  16494. var td = table.getElementsByTagName('td')[0];
  16495. tmpValue = domUtils.getComputedStyle(table, 'border-left-width');
  16496. tableBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  16497. tmpValue = domUtils.getComputedStyle(td, 'padding-left');
  16498. tdPadding = parseInt(borderMap[tmpValue] || tmpValue, 10);
  16499. tmpValue = domUtils.getComputedStyle(td, 'border-left-width');
  16500. tdBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  16501. domUtils.remove(table);
  16502. return {
  16503. tableBorder:tableBorder,
  16504. tdPadding:tdPadding,
  16505. tdBorder:tdBorder
  16506. };
  16507. } else {
  16508. td = table.getElementsByTagName('td')[0];
  16509. tmpValue = domUtils.getComputedStyle(table, 'border-left-width');
  16510. tableBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  16511. tmpValue = domUtils.getComputedStyle(td, 'padding-left');
  16512. tdPadding = parseInt(borderMap[tmpValue] || tmpValue, 10);
  16513. tmpValue = domUtils.getComputedStyle(td, 'border-left-width');
  16514. tdBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  16515. return {
  16516. tableBorder:tableBorder,
  16517. tdPadding:tdPadding,
  16518. tdBorder:tdBorder
  16519. };
  16520. }
  16521. };
  16522. /**
  16523. * 根据当前点击的td或者table获取索引对象
  16524. * @param tdOrTable
  16525. */
  16526. UETable.getUETable = function (tdOrTable) {
  16527. var tag = tdOrTable.tagName.toLowerCase();
  16528. tdOrTable = (tag == "td" || tag == "th" || tag == 'caption') ? domUtils.findParentByTagName(tdOrTable, "table", true) : tdOrTable;
  16529. if (!tdOrTable.ueTable) {
  16530. tdOrTable.ueTable = new UETable(tdOrTable);
  16531. }
  16532. return tdOrTable.ueTable;
  16533. };
  16534. UETable.cloneCell = function(cell,ignoreMerge,keepPro){
  16535. if (!cell || utils.isString(cell)) {
  16536. return this.table.ownerDocument.createElement(cell || 'td');
  16537. }
  16538. var flag = domUtils.hasClass(cell, "selectTdClass");
  16539. flag && domUtils.removeClasses(cell, "selectTdClass");
  16540. var tmpCell = cell.cloneNode(true);
  16541. if (ignoreMerge) {
  16542. tmpCell.rowSpan = tmpCell.colSpan = 1;
  16543. }
  16544. //去掉宽高
  16545. !keepPro && domUtils.removeAttributes(tmpCell,'width height');
  16546. !keepPro && domUtils.removeAttributes(tmpCell,'style');
  16547. tmpCell.style.borderLeftStyle = "";
  16548. tmpCell.style.borderTopStyle = "";
  16549. tmpCell.style.borderLeftColor = cell.style.borderRightColor;
  16550. tmpCell.style.borderLeftWidth = cell.style.borderRightWidth;
  16551. tmpCell.style.borderTopColor = cell.style.borderBottomColor;
  16552. tmpCell.style.borderTopWidth = cell.style.borderBottomWidth;
  16553. flag && domUtils.addClass(cell, "selectTdClass");
  16554. return tmpCell;
  16555. }
  16556. UETable.prototype = {
  16557. getMaxRows:function () {
  16558. var rows = this.table.rows, maxLen = 1;
  16559. for (var i = 0, row; row = rows[i]; i++) {
  16560. var currentMax = 1;
  16561. for (var j = 0, cj; cj = row.cells[j++];) {
  16562. currentMax = Math.max(cj.rowSpan || 1, currentMax);
  16563. }
  16564. maxLen = Math.max(currentMax + i, maxLen);
  16565. }
  16566. return maxLen;
  16567. },
  16568. /**
  16569. * 获取当前表格的最大列数
  16570. */
  16571. getMaxCols:function () {
  16572. var rows = this.table.rows, maxLen = 0, cellRows = {};
  16573. for (var i = 0, row; row = rows[i]; i++) {
  16574. var cellsNum = 0;
  16575. for (var j = 0, cj; cj = row.cells[j++];) {
  16576. cellsNum += (cj.colSpan || 1);
  16577. if (cj.rowSpan && cj.rowSpan > 1) {
  16578. for (var k = 1; k < cj.rowSpan; k++) {
  16579. if (!cellRows['row_' + (i + k)]) {
  16580. cellRows['row_' + (i + k)] = (cj.colSpan || 1);
  16581. } else {
  16582. cellRows['row_' + (i + k)]++
  16583. }
  16584. }
  16585. }
  16586. }
  16587. cellsNum += cellRows['row_' + i] || 0;
  16588. maxLen = Math.max(cellsNum, maxLen);
  16589. }
  16590. return maxLen;
  16591. },
  16592. getCellColIndex:function (cell) {
  16593. },
  16594. /**
  16595. * 获取当前cell旁边的单元格,
  16596. * @param cell
  16597. * @param right
  16598. */
  16599. getHSideCell:function (cell, right) {
  16600. try {
  16601. var cellInfo = this.getCellInfo(cell),
  16602. previewRowIndex, previewColIndex;
  16603. var len = this.selectedTds.length,
  16604. range = this.cellsRange;
  16605. //首行或者首列没有前置单元格
  16606. if ((!right && (!len ? !cellInfo.colIndex : !range.beginColIndex)) || (right && (!len ? (cellInfo.colIndex == (this.colsNum - 1)) : (range.endColIndex == this.colsNum - 1)))) return null;
  16607. previewRowIndex = !len ? cellInfo.rowIndex : range.beginRowIndex;
  16608. previewColIndex = !right ? ( !len ? (cellInfo.colIndex < 1 ? 0 : (cellInfo.colIndex - 1)) : range.beginColIndex - 1)
  16609. : ( !len ? cellInfo.colIndex + 1 : range.endColIndex + 1);
  16610. return this.getCell(this.indexTable[previewRowIndex][previewColIndex].rowIndex, this.indexTable[previewRowIndex][previewColIndex].cellIndex);
  16611. } catch (e) {
  16612. showError(e);
  16613. }
  16614. },
  16615. getTabNextCell:function (cell, preRowIndex) {
  16616. var cellInfo = this.getCellInfo(cell),
  16617. rowIndex = preRowIndex || cellInfo.rowIndex,
  16618. colIndex = cellInfo.colIndex + 1 + (cellInfo.colSpan - 1),
  16619. nextCell;
  16620. try {
  16621. nextCell = this.getCell(this.indexTable[rowIndex][colIndex].rowIndex, this.indexTable[rowIndex][colIndex].cellIndex);
  16622. } catch (e) {
  16623. try {
  16624. rowIndex = rowIndex * 1 + 1;
  16625. colIndex = 0;
  16626. nextCell = this.getCell(this.indexTable[rowIndex][colIndex].rowIndex, this.indexTable[rowIndex][colIndex].cellIndex);
  16627. } catch (e) {
  16628. }
  16629. }
  16630. return nextCell;
  16631. },
  16632. /**
  16633. * 获取视觉上的后置单元格
  16634. * @param cell
  16635. * @param bottom
  16636. */
  16637. getVSideCell:function (cell, bottom, ignoreRange) {
  16638. try {
  16639. var cellInfo = this.getCellInfo(cell),
  16640. nextRowIndex, nextColIndex;
  16641. var len = this.selectedTds.length && !ignoreRange,
  16642. range = this.cellsRange;
  16643. //末行或者末列没有后置单元格
  16644. if ((!bottom && (cellInfo.rowIndex == 0)) || (bottom && (!len ? (cellInfo.rowIndex + cellInfo.rowSpan > this.rowsNum - 1) : (range.endRowIndex == this.rowsNum - 1)))) return null;
  16645. nextRowIndex = !bottom ? ( !len ? cellInfo.rowIndex - 1 : range.beginRowIndex - 1)
  16646. : ( !len ? (cellInfo.rowIndex + cellInfo.rowSpan) : range.endRowIndex + 1);
  16647. nextColIndex = !len ? cellInfo.colIndex : range.beginColIndex;
  16648. return this.getCell(this.indexTable[nextRowIndex][nextColIndex].rowIndex, this.indexTable[nextRowIndex][nextColIndex].cellIndex);
  16649. } catch (e) {
  16650. showError(e);
  16651. }
  16652. },
  16653. /**
  16654. * 获取相同结束位置的单元格,xOrY指代了是获取x轴相同还是y轴相同
  16655. */
  16656. getSameEndPosCells:function (cell, xOrY) {
  16657. try {
  16658. var flag = (xOrY.toLowerCase() === "x"),
  16659. end = domUtils.getXY(cell)[flag ? 'x' : 'y'] + cell["offset" + (flag ? 'Width' : 'Height')],
  16660. rows = this.table.rows,
  16661. cells = null, returns = [];
  16662. for (var i = 0; i < this.rowsNum; i++) {
  16663. cells = rows[i].cells;
  16664. for (var j = 0, tmpCell; tmpCell = cells[j++];) {
  16665. var tmpEnd = domUtils.getXY(tmpCell)[flag ? 'x' : 'y'] + tmpCell["offset" + (flag ? 'Width' : 'Height')];
  16666. //对应行的td已经被上面行rowSpan了
  16667. if (tmpEnd > end && flag) break;
  16668. if (cell == tmpCell || end == tmpEnd) {
  16669. //只获取单一的单元格
  16670. //todo 仅获取单一单元格在特定情况下会造成returns为空,从而影响后续的拖拽实现,修正这个。需考虑性能
  16671. if (tmpCell[flag ? "colSpan" : "rowSpan"] == 1) {
  16672. returns.push(tmpCell);
  16673. }
  16674. if (flag) break;
  16675. }
  16676. }
  16677. }
  16678. return returns;
  16679. } catch (e) {
  16680. showError(e);
  16681. }
  16682. },
  16683. setCellContent:function (cell, content) {
  16684. cell.innerHTML = content || (browser.ie ? domUtils.fillChar : "<br />");
  16685. },
  16686. cloneCell:UETable.cloneCell,
  16687. /**
  16688. * 获取跟当前单元格的右边竖线为左边的所有未合并单元格
  16689. */
  16690. getSameStartPosXCells:function (cell) {
  16691. try {
  16692. var start = domUtils.getXY(cell).x + cell.offsetWidth,
  16693. rows = this.table.rows, cells , returns = [];
  16694. for (var i = 0; i < this.rowsNum; i++) {
  16695. cells = rows[i].cells;
  16696. for (var j = 0, tmpCell; tmpCell = cells[j++];) {
  16697. var tmpStart = domUtils.getXY(tmpCell).x;
  16698. if (tmpStart > start) break;
  16699. if (tmpStart == start && tmpCell.colSpan == 1) {
  16700. returns.push(tmpCell);
  16701. break;
  16702. }
  16703. }
  16704. }
  16705. return returns;
  16706. } catch (e) {
  16707. showError(e);
  16708. }
  16709. },
  16710. /**
  16711. * 更新table对应的索引表
  16712. */
  16713. update:function (table) {
  16714. this.table = table || this.table;
  16715. this.selectedTds = [];
  16716. this.cellsRange = {};
  16717. this.indexTable = [];
  16718. var rows = this.table.rows,
  16719. rowsNum = this.getMaxRows(),
  16720. dNum = rowsNum - rows.length,
  16721. colsNum = this.getMaxCols();
  16722. while (dNum--) {
  16723. this.table.insertRow(rows.length);
  16724. }
  16725. this.rowsNum = rowsNum;
  16726. this.colsNum = colsNum;
  16727. for (var i = 0, len = rows.length; i < len; i++) {
  16728. this.indexTable[i] = new Array(colsNum);
  16729. }
  16730. //填充索引表
  16731. for (var rowIndex = 0, row; row = rows[rowIndex]; rowIndex++) {
  16732. for (var cellIndex = 0, cell, cells = row.cells; cell = cells[cellIndex]; cellIndex++) {
  16733. //修正整行被rowSpan时导致的行数计算错误
  16734. if (cell.rowSpan > rowsNum) {
  16735. cell.rowSpan = rowsNum;
  16736. }
  16737. var colIndex = cellIndex,
  16738. rowSpan = cell.rowSpan || 1,
  16739. colSpan = cell.colSpan || 1;
  16740. //当已经被上一行rowSpan或者被前一列colSpan了,则跳到下一个单元格进行
  16741. while (this.indexTable[rowIndex][colIndex]) colIndex++;
  16742. for (var j = 0; j < rowSpan; j++) {
  16743. for (var k = 0; k < colSpan; k++) {
  16744. this.indexTable[rowIndex + j][colIndex + k] = {
  16745. rowIndex:rowIndex,
  16746. cellIndex:cellIndex,
  16747. colIndex:colIndex,
  16748. rowSpan:rowSpan,
  16749. colSpan:colSpan
  16750. }
  16751. }
  16752. }
  16753. }
  16754. }
  16755. //修复残缺td
  16756. for (j = 0; j < rowsNum; j++) {
  16757. for (k = 0; k < colsNum; k++) {
  16758. if (this.indexTable[j][k] === undefined) {
  16759. row = rows[j];
  16760. cell = row.cells[row.cells.length - 1];
  16761. cell = cell ? cell.cloneNode(true) : this.table.ownerDocument.createElement("td");
  16762. this.setCellContent(cell);
  16763. if (cell.colSpan !== 1)cell.colSpan = 1;
  16764. if (cell.rowSpan !== 1)cell.rowSpan = 1;
  16765. row.appendChild(cell);
  16766. this.indexTable[j][k] = {
  16767. rowIndex:j,
  16768. cellIndex:cell.cellIndex,
  16769. colIndex:k,
  16770. rowSpan:1,
  16771. colSpan:1
  16772. }
  16773. }
  16774. }
  16775. }
  16776. //当框选后删除行或者列后撤销,需要重建选区。
  16777. var tds = domUtils.getElementsByTagName(this.table, "td"),
  16778. selectTds = [];
  16779. utils.each(tds, function (td) {
  16780. if (domUtils.hasClass(td, "selectTdClass")) {
  16781. selectTds.push(td);
  16782. }
  16783. });
  16784. if (selectTds.length) {
  16785. var start = selectTds[0],
  16786. end = selectTds[selectTds.length - 1],
  16787. startInfo = this.getCellInfo(start),
  16788. endInfo = this.getCellInfo(end);
  16789. this.selectedTds = selectTds;
  16790. this.cellsRange = {
  16791. beginRowIndex:startInfo.rowIndex,
  16792. beginColIndex:startInfo.colIndex,
  16793. endRowIndex:endInfo.rowIndex + endInfo.rowSpan - 1,
  16794. endColIndex:endInfo.colIndex + endInfo.colSpan - 1
  16795. };
  16796. }
  16797. //给第一行设置firstRow的样式名称,在排序图标的样式上使用到
  16798. if(!domUtils.hasClass(this.table.rows[0], "firstRow")) {
  16799. domUtils.addClass(this.table.rows[0], "firstRow");
  16800. for(var i = 1; i< this.table.rows.length; i++) {
  16801. domUtils.removeClasses(this.table.rows[i], "firstRow");
  16802. }
  16803. }
  16804. },
  16805. /**
  16806. * 获取单元格的索引信息
  16807. */
  16808. getCellInfo:function (cell) {
  16809. if (!cell) return;
  16810. var cellIndex = cell.cellIndex,
  16811. rowIndex = cell.parentNode.rowIndex,
  16812. rowInfo = this.indexTable[rowIndex],
  16813. numCols = this.colsNum;
  16814. for (var colIndex = cellIndex; colIndex < numCols; colIndex++) {
  16815. var cellInfo = rowInfo[colIndex];
  16816. if (cellInfo.rowIndex === rowIndex && cellInfo.cellIndex === cellIndex) {
  16817. return cellInfo;
  16818. }
  16819. }
  16820. },
  16821. /**
  16822. * 根据行列号获取单元格
  16823. */
  16824. getCell:function (rowIndex, cellIndex) {
  16825. return rowIndex < this.rowsNum && this.table.rows[rowIndex].cells[cellIndex] || null;
  16826. },
  16827. /**
  16828. * 删除单元格
  16829. */
  16830. deleteCell:function (cell, rowIndex) {
  16831. rowIndex = typeof rowIndex == 'number' ? rowIndex : cell.parentNode.rowIndex;
  16832. var row = this.table.rows[rowIndex];
  16833. row.deleteCell(cell.cellIndex);
  16834. },
  16835. /**
  16836. * 根据始末两个单元格获取被框选的所有单元格范围
  16837. */
  16838. getCellsRange:function (cellA, cellB) {
  16839. function checkRange(beginRowIndex, beginColIndex, endRowIndex, endColIndex) {
  16840. var tmpBeginRowIndex = beginRowIndex,
  16841. tmpBeginColIndex = beginColIndex,
  16842. tmpEndRowIndex = endRowIndex,
  16843. tmpEndColIndex = endColIndex,
  16844. cellInfo, colIndex, rowIndex;
  16845. // 通过indexTable检查是否存在超出TableRange上边界的情况
  16846. if (beginRowIndex > 0) {
  16847. for (colIndex = beginColIndex; colIndex < endColIndex; colIndex++) {
  16848. cellInfo = me.indexTable[beginRowIndex][colIndex];
  16849. rowIndex = cellInfo.rowIndex;
  16850. if (rowIndex < beginRowIndex) {
  16851. tmpBeginRowIndex = Math.min(rowIndex, tmpBeginRowIndex);
  16852. }
  16853. }
  16854. }
  16855. // 通过indexTable检查是否存在超出TableRange右边界的情况
  16856. if (endColIndex < me.colsNum) {
  16857. for (rowIndex = beginRowIndex; rowIndex < endRowIndex; rowIndex++) {
  16858. cellInfo = me.indexTable[rowIndex][endColIndex];
  16859. colIndex = cellInfo.colIndex + cellInfo.colSpan - 1;
  16860. if (colIndex > endColIndex) {
  16861. tmpEndColIndex = Math.max(colIndex, tmpEndColIndex);
  16862. }
  16863. }
  16864. }
  16865. // 检查是否有超出TableRange下边界的情况
  16866. if (endRowIndex < me.rowsNum) {
  16867. for (colIndex = beginColIndex; colIndex < endColIndex; colIndex++) {
  16868. cellInfo = me.indexTable[endRowIndex][colIndex];
  16869. rowIndex = cellInfo.rowIndex + cellInfo.rowSpan - 1;
  16870. if (rowIndex > endRowIndex) {
  16871. tmpEndRowIndex = Math.max(rowIndex, tmpEndRowIndex);
  16872. }
  16873. }
  16874. }
  16875. // 检查是否有超出TableRange左边界的情况
  16876. if (beginColIndex > 0) {
  16877. for (rowIndex = beginRowIndex; rowIndex < endRowIndex; rowIndex++) {
  16878. cellInfo = me.indexTable[rowIndex][beginColIndex];
  16879. colIndex = cellInfo.colIndex;
  16880. if (colIndex < beginColIndex) {
  16881. tmpBeginColIndex = Math.min(cellInfo.colIndex, tmpBeginColIndex);
  16882. }
  16883. }
  16884. }
  16885. //递归调用直至所有完成所有框选单元格的扩展
  16886. if (tmpBeginRowIndex != beginRowIndex || tmpBeginColIndex != beginColIndex || tmpEndRowIndex != endRowIndex || tmpEndColIndex != endColIndex) {
  16887. return checkRange(tmpBeginRowIndex, tmpBeginColIndex, tmpEndRowIndex, tmpEndColIndex);
  16888. } else {
  16889. // 不需要扩展TableRange的情况
  16890. return {
  16891. beginRowIndex:beginRowIndex,
  16892. beginColIndex:beginColIndex,
  16893. endRowIndex:endRowIndex,
  16894. endColIndex:endColIndex
  16895. };
  16896. }
  16897. }
  16898. try {
  16899. var me = this,
  16900. cellAInfo = me.getCellInfo(cellA);
  16901. if (cellA === cellB) {
  16902. return {
  16903. beginRowIndex:cellAInfo.rowIndex,
  16904. beginColIndex:cellAInfo.colIndex,
  16905. endRowIndex:cellAInfo.rowIndex + cellAInfo.rowSpan - 1,
  16906. endColIndex:cellAInfo.colIndex + cellAInfo.colSpan - 1
  16907. };
  16908. }
  16909. var cellBInfo = me.getCellInfo(cellB);
  16910. // 计算TableRange的四个边
  16911. var beginRowIndex = Math.min(cellAInfo.rowIndex, cellBInfo.rowIndex),
  16912. beginColIndex = Math.min(cellAInfo.colIndex, cellBInfo.colIndex),
  16913. endRowIndex = Math.max(cellAInfo.rowIndex + cellAInfo.rowSpan - 1, cellBInfo.rowIndex + cellBInfo.rowSpan - 1),
  16914. endColIndex = Math.max(cellAInfo.colIndex + cellAInfo.colSpan - 1, cellBInfo.colIndex + cellBInfo.colSpan - 1);
  16915. return checkRange(beginRowIndex, beginColIndex, endRowIndex, endColIndex);
  16916. } catch (e) {
  16917. //throw e;
  16918. }
  16919. },
  16920. /**
  16921. * 依据cellsRange获取对应的单元格集合
  16922. */
  16923. getCells:function (range) {
  16924. //每次获取cells之前必须先清除上次的选择,否则会对后续获取操作造成影响
  16925. this.clearSelected();
  16926. var beginRowIndex = range.beginRowIndex,
  16927. beginColIndex = range.beginColIndex,
  16928. endRowIndex = range.endRowIndex,
  16929. endColIndex = range.endColIndex,
  16930. cellInfo, rowIndex, colIndex, tdHash = {}, returnTds = [];
  16931. for (var i = beginRowIndex; i <= endRowIndex; i++) {
  16932. for (var j = beginColIndex; j <= endColIndex; j++) {
  16933. cellInfo = this.indexTable[i][j];
  16934. rowIndex = cellInfo.rowIndex;
  16935. colIndex = cellInfo.colIndex;
  16936. // 如果Cells里已经包含了此Cell则跳过
  16937. var key = rowIndex + '|' + colIndex;
  16938. if (tdHash[key]) continue;
  16939. tdHash[key] = 1;
  16940. if (rowIndex < i || colIndex < j || rowIndex + cellInfo.rowSpan - 1 > endRowIndex || colIndex + cellInfo.colSpan - 1 > endColIndex) {
  16941. return null;
  16942. }
  16943. returnTds.push(this.getCell(rowIndex, cellInfo.cellIndex));
  16944. }
  16945. }
  16946. return returnTds;
  16947. },
  16948. /**
  16949. * 清理已经选中的单元格
  16950. */
  16951. clearSelected:function () {
  16952. UETable.removeSelectedClass(this.selectedTds);
  16953. this.selectedTds = [];
  16954. this.cellsRange = {};
  16955. },
  16956. /**
  16957. * 根据range设置已经选中的单元格
  16958. */
  16959. setSelected:function (range) {
  16960. var cells = this.getCells(range);
  16961. UETable.addSelectedClass(cells);
  16962. this.selectedTds = cells;
  16963. this.cellsRange = range;
  16964. },
  16965. isFullRow:function () {
  16966. var range = this.cellsRange;
  16967. return (range.endColIndex - range.beginColIndex + 1) == this.colsNum;
  16968. },
  16969. isFullCol:function () {
  16970. var range = this.cellsRange,
  16971. table = this.table,
  16972. ths = table.getElementsByTagName("th"),
  16973. rows = range.endRowIndex - range.beginRowIndex + 1;
  16974. return !ths.length ? rows == this.rowsNum : rows == this.rowsNum || (rows == this.rowsNum - 1);
  16975. },
  16976. /**
  16977. * 获取视觉上的前置单元格,默认是左边,top传入时
  16978. * @param cell
  16979. * @param top
  16980. */
  16981. getNextCell:function (cell, bottom, ignoreRange) {
  16982. try {
  16983. var cellInfo = this.getCellInfo(cell),
  16984. nextRowIndex, nextColIndex;
  16985. var len = this.selectedTds.length && !ignoreRange,
  16986. range = this.cellsRange;
  16987. //末行或者末列没有后置单元格
  16988. if ((!bottom && (cellInfo.rowIndex == 0)) || (bottom && (!len ? (cellInfo.rowIndex + cellInfo.rowSpan > this.rowsNum - 1) : (range.endRowIndex == this.rowsNum - 1)))) return null;
  16989. nextRowIndex = !bottom ? ( !len ? cellInfo.rowIndex - 1 : range.beginRowIndex - 1)
  16990. : ( !len ? (cellInfo.rowIndex + cellInfo.rowSpan) : range.endRowIndex + 1);
  16991. nextColIndex = !len ? cellInfo.colIndex : range.beginColIndex;
  16992. return this.getCell(this.indexTable[nextRowIndex][nextColIndex].rowIndex, this.indexTable[nextRowIndex][nextColIndex].cellIndex);
  16993. } catch (e) {
  16994. showError(e);
  16995. }
  16996. },
  16997. getPreviewCell:function (cell, top) {
  16998. try {
  16999. var cellInfo = this.getCellInfo(cell),
  17000. previewRowIndex, previewColIndex;
  17001. var len = this.selectedTds.length,
  17002. range = this.cellsRange;
  17003. //首行或者首列没有前置单元格
  17004. if ((!top && (!len ? !cellInfo.colIndex : !range.beginColIndex)) || (top && (!len ? (cellInfo.rowIndex > (this.colsNum - 1)) : (range.endColIndex == this.colsNum - 1)))) return null;
  17005. previewRowIndex = !top ? ( !len ? cellInfo.rowIndex : range.beginRowIndex )
  17006. : ( !len ? (cellInfo.rowIndex < 1 ? 0 : (cellInfo.rowIndex - 1)) : range.beginRowIndex);
  17007. previewColIndex = !top ? ( !len ? (cellInfo.colIndex < 1 ? 0 : (cellInfo.colIndex - 1)) : range.beginColIndex - 1)
  17008. : ( !len ? cellInfo.colIndex : range.endColIndex + 1);
  17009. return this.getCell(this.indexTable[previewRowIndex][previewColIndex].rowIndex, this.indexTable[previewRowIndex][previewColIndex].cellIndex);
  17010. } catch (e) {
  17011. showError(e);
  17012. }
  17013. },
  17014. /**
  17015. * 移动单元格中的内容
  17016. */
  17017. moveContent:function (cellTo, cellFrom) {
  17018. if (UETable.isEmptyBlock(cellFrom)) return;
  17019. if (UETable.isEmptyBlock(cellTo)) {
  17020. cellTo.innerHTML = cellFrom.innerHTML;
  17021. return;
  17022. }
  17023. var child = cellTo.lastChild;
  17024. if (child.nodeType == 3 || !dtd.$block[child.tagName]) {
  17025. cellTo.appendChild(cellTo.ownerDocument.createElement('br'))
  17026. }
  17027. while (child = cellFrom.firstChild) {
  17028. cellTo.appendChild(child);
  17029. }
  17030. },
  17031. /**
  17032. * 向右合并单元格
  17033. */
  17034. mergeRight:function (cell) {
  17035. var cellInfo = this.getCellInfo(cell),
  17036. rightColIndex = cellInfo.colIndex + cellInfo.colSpan,
  17037. rightCellInfo = this.indexTable[cellInfo.rowIndex][rightColIndex],
  17038. rightCell = this.getCell(rightCellInfo.rowIndex, rightCellInfo.cellIndex);
  17039. //合并
  17040. cell.colSpan = cellInfo.colSpan + rightCellInfo.colSpan;
  17041. //被合并的单元格不应存在宽度属性
  17042. cell.removeAttribute("width");
  17043. //移动内容
  17044. this.moveContent(cell, rightCell);
  17045. //删掉被合并的Cell
  17046. this.deleteCell(rightCell, rightCellInfo.rowIndex);
  17047. this.update();
  17048. },
  17049. /**
  17050. * 向下合并单元格
  17051. */
  17052. mergeDown:function (cell) {
  17053. var cellInfo = this.getCellInfo(cell),
  17054. downRowIndex = cellInfo.rowIndex + cellInfo.rowSpan,
  17055. downCellInfo = this.indexTable[downRowIndex][cellInfo.colIndex],
  17056. downCell = this.getCell(downCellInfo.rowIndex, downCellInfo.cellIndex);
  17057. cell.rowSpan = cellInfo.rowSpan + downCellInfo.rowSpan;
  17058. cell.removeAttribute("height");
  17059. this.moveContent(cell, downCell);
  17060. this.deleteCell(downCell, downCellInfo.rowIndex);
  17061. this.update();
  17062. },
  17063. /**
  17064. * 合并整个range中的内容
  17065. */
  17066. mergeRange:function () {
  17067. //由于合并操作可以在任意时刻进行,所以无法通过鼠标位置等信息实时生成range,只能通过缓存实例中的cellsRange对象来访问
  17068. var range = this.cellsRange,
  17069. leftTopCell = this.getCell(range.beginRowIndex, this.indexTable[range.beginRowIndex][range.beginColIndex].cellIndex);
  17070. if (leftTopCell.tagName == "TH" && range.endRowIndex !== range.beginRowIndex) {
  17071. var index = this.indexTable,
  17072. info = this.getCellInfo(leftTopCell);
  17073. leftTopCell = this.getCell(1, index[1][info.colIndex].cellIndex);
  17074. range = this.getCellsRange(leftTopCell, this.getCell(index[this.rowsNum - 1][info.colIndex].rowIndex, index[this.rowsNum - 1][info.colIndex].cellIndex));
  17075. }
  17076. // 删除剩余的Cells
  17077. var cells = this.getCells(range);
  17078. for(var i= 0,ci;ci=cells[i++];){
  17079. if (ci !== leftTopCell) {
  17080. this.moveContent(leftTopCell, ci);
  17081. this.deleteCell(ci);
  17082. }
  17083. }
  17084. // 修改左上角Cell的rowSpan和colSpan,并调整宽度属性设置
  17085. leftTopCell.rowSpan = range.endRowIndex - range.beginRowIndex + 1;
  17086. leftTopCell.rowSpan > 1 && leftTopCell.removeAttribute("height");
  17087. leftTopCell.colSpan = range.endColIndex - range.beginColIndex + 1;
  17088. leftTopCell.colSpan > 1 && leftTopCell.removeAttribute("width");
  17089. if (leftTopCell.rowSpan == this.rowsNum && leftTopCell.colSpan != 1) {
  17090. leftTopCell.colSpan = 1;
  17091. }
  17092. if (leftTopCell.colSpan == this.colsNum && leftTopCell.rowSpan != 1) {
  17093. var rowIndex = leftTopCell.parentNode.rowIndex;
  17094. //解决IE下的表格操作问题
  17095. if( this.table.deleteRow ) {
  17096. for (var i = rowIndex+ 1, curIndex=rowIndex+ 1, len=leftTopCell.rowSpan; i < len; i++) {
  17097. this.table.deleteRow(curIndex);
  17098. }
  17099. } else {
  17100. for (var i = 0, len=leftTopCell.rowSpan - 1; i < len; i++) {
  17101. var row = this.table.rows[rowIndex + 1];
  17102. row.parentNode.removeChild(row);
  17103. }
  17104. }
  17105. leftTopCell.rowSpan = 1;
  17106. }
  17107. this.update();
  17108. },
  17109. /**
  17110. * 插入一行单元格
  17111. */
  17112. insertRow:function (rowIndex, sourceCell) {
  17113. var numCols = this.colsNum,
  17114. table = this.table,
  17115. row = table.insertRow(rowIndex), cell,
  17116. isInsertTitle = typeof sourceCell == 'string' && sourceCell.toUpperCase() == 'TH';
  17117. function replaceTdToTh(colIndex, cell, tableRow) {
  17118. if (colIndex == 0) {
  17119. var tr = tableRow.nextSibling || tableRow.previousSibling,
  17120. th = tr.cells[colIndex];
  17121. if (th.tagName == 'TH') {
  17122. th = cell.ownerDocument.createElement("th");
  17123. th.appendChild(cell.firstChild);
  17124. tableRow.insertBefore(th, cell);
  17125. domUtils.remove(cell)
  17126. }
  17127. }else{
  17128. if (cell.tagName == 'TH') {
  17129. var td = cell.ownerDocument.createElement("td");
  17130. td.appendChild(cell.firstChild);
  17131. tableRow.insertBefore(td, cell);
  17132. domUtils.remove(cell)
  17133. }
  17134. }
  17135. }
  17136. //首行直接插入,无需考虑部分单元格被rowspan的情况
  17137. if (rowIndex == 0 || rowIndex == this.rowsNum) {
  17138. for (var colIndex = 0; colIndex < numCols; colIndex++) {
  17139. cell = this.cloneCell(sourceCell, true);
  17140. this.setCellContent(cell);
  17141. cell.getAttribute('vAlign') && cell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  17142. row.appendChild(cell);
  17143. if(!isInsertTitle) replaceTdToTh(colIndex, cell, row);
  17144. }
  17145. } else {
  17146. var infoRow = this.indexTable[rowIndex],
  17147. cellIndex = 0;
  17148. for (colIndex = 0; colIndex < numCols; colIndex++) {
  17149. var cellInfo = infoRow[colIndex];
  17150. //如果存在某个单元格的rowspan穿过待插入行的位置,则修改该单元格的rowspan即可,无需插入单元格
  17151. if (cellInfo.rowIndex < rowIndex) {
  17152. cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  17153. cell.rowSpan = cellInfo.rowSpan + 1;
  17154. } else {
  17155. cell = this.cloneCell(sourceCell, true);
  17156. this.setCellContent(cell);
  17157. row.appendChild(cell);
  17158. }
  17159. if(!isInsertTitle) replaceTdToTh(colIndex, cell, row);
  17160. }
  17161. }
  17162. //框选时插入不触发contentchange,需要手动更新索引。
  17163. this.update();
  17164. return row;
  17165. },
  17166. /**
  17167. * 删除一行单元格
  17168. * @param rowIndex
  17169. */
  17170. deleteRow:function (rowIndex) {
  17171. var row = this.table.rows[rowIndex],
  17172. infoRow = this.indexTable[rowIndex],
  17173. colsNum = this.colsNum,
  17174. count = 0; //处理计数
  17175. for (var colIndex = 0; colIndex < colsNum;) {
  17176. var cellInfo = infoRow[colIndex],
  17177. cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  17178. if (cell.rowSpan > 1) {
  17179. if (cellInfo.rowIndex == rowIndex) {
  17180. var clone = cell.cloneNode(true);
  17181. clone.rowSpan = cell.rowSpan - 1;
  17182. clone.innerHTML = "";
  17183. cell.rowSpan = 1;
  17184. var nextRowIndex = rowIndex + 1,
  17185. nextRow = this.table.rows[nextRowIndex],
  17186. insertCellIndex,
  17187. preMerged = this.getPreviewMergedCellsNum(nextRowIndex, colIndex) - count;
  17188. if (preMerged < colIndex) {
  17189. insertCellIndex = colIndex - preMerged - 1;
  17190. //nextRow.insertCell(insertCellIndex);
  17191. domUtils.insertAfter(nextRow.cells[insertCellIndex], clone);
  17192. } else {
  17193. if (nextRow.cells.length) nextRow.insertBefore(clone, nextRow.cells[0])
  17194. }
  17195. count += 1;
  17196. //cell.parentNode.removeChild(cell);
  17197. }
  17198. }
  17199. colIndex += cell.colSpan || 1;
  17200. }
  17201. var deleteTds = [], cacheMap = {};
  17202. for (colIndex = 0; colIndex < colsNum; colIndex++) {
  17203. var tmpRowIndex = infoRow[colIndex].rowIndex,
  17204. tmpCellIndex = infoRow[colIndex].cellIndex,
  17205. key = tmpRowIndex + "_" + tmpCellIndex;
  17206. if (cacheMap[key])continue;
  17207. cacheMap[key] = 1;
  17208. cell = this.getCell(tmpRowIndex, tmpCellIndex);
  17209. deleteTds.push(cell);
  17210. }
  17211. var mergeTds = [];
  17212. utils.each(deleteTds, function (td) {
  17213. if (td.rowSpan == 1) {
  17214. td.parentNode.removeChild(td);
  17215. } else {
  17216. mergeTds.push(td);
  17217. }
  17218. });
  17219. utils.each(mergeTds, function (td) {
  17220. td.rowSpan--;
  17221. });
  17222. row.parentNode.removeChild(row);
  17223. //浏览器方法本身存在bug,采用自定义方法删除
  17224. //this.table.deleteRow(rowIndex);
  17225. this.update();
  17226. },
  17227. insertCol:function (colIndex, sourceCell, defaultValue) {
  17228. var rowsNum = this.rowsNum,
  17229. rowIndex = 0,
  17230. tableRow, cell,
  17231. backWidth = parseInt((this.table.offsetWidth - (this.colsNum + 1) * 20 - (this.colsNum + 1)) / (this.colsNum + 1), 10),
  17232. isInsertTitleCol = typeof sourceCell == 'string' && sourceCell.toUpperCase() == 'TH';
  17233. function replaceTdToTh(rowIndex, cell, tableRow) {
  17234. if (rowIndex == 0) {
  17235. var th = cell.nextSibling || cell.previousSibling;
  17236. if (th.tagName == 'TH') {
  17237. th = cell.ownerDocument.createElement("th");
  17238. th.appendChild(cell.firstChild);
  17239. tableRow.insertBefore(th, cell);
  17240. domUtils.remove(cell)
  17241. }
  17242. }else{
  17243. if (cell.tagName == 'TH') {
  17244. var td = cell.ownerDocument.createElement("td");
  17245. td.appendChild(cell.firstChild);
  17246. tableRow.insertBefore(td, cell);
  17247. domUtils.remove(cell)
  17248. }
  17249. }
  17250. }
  17251. var preCell;
  17252. if (colIndex == 0 || colIndex == this.colsNum) {
  17253. for (; rowIndex < rowsNum; rowIndex++) {
  17254. tableRow = this.table.rows[rowIndex];
  17255. preCell = tableRow.cells[colIndex == 0 ? colIndex : tableRow.cells.length];
  17256. cell = this.cloneCell(sourceCell, true); //tableRow.insertCell(colIndex == 0 ? colIndex : tableRow.cells.length);
  17257. this.setCellContent(cell);
  17258. cell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  17259. preCell && cell.setAttribute('width', preCell.getAttribute('width'));
  17260. if (!colIndex) {
  17261. tableRow.insertBefore(cell, tableRow.cells[0]);
  17262. } else {
  17263. domUtils.insertAfter(tableRow.cells[tableRow.cells.length - 1], cell);
  17264. }
  17265. if(!isInsertTitleCol) replaceTdToTh(rowIndex, cell, tableRow)
  17266. }
  17267. } else {
  17268. for (; rowIndex < rowsNum; rowIndex++) {
  17269. var cellInfo = this.indexTable[rowIndex][colIndex];
  17270. if (cellInfo.colIndex < colIndex) {
  17271. cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  17272. cell.colSpan = cellInfo.colSpan + 1;
  17273. } else {
  17274. tableRow = this.table.rows[rowIndex];
  17275. preCell = tableRow.cells[cellInfo.cellIndex];
  17276. cell = this.cloneCell(sourceCell, true);//tableRow.insertCell(cellInfo.cellIndex);
  17277. this.setCellContent(cell);
  17278. cell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  17279. preCell && cell.setAttribute('width', preCell.getAttribute('width'));
  17280. //防止IE下报错
  17281. preCell ? tableRow.insertBefore(cell, preCell) : tableRow.appendChild(cell);
  17282. }
  17283. if(!isInsertTitleCol) replaceTdToTh(rowIndex, cell, tableRow);
  17284. }
  17285. }
  17286. //框选时插入不触发contentchange,需要手动更新索引
  17287. this.update();
  17288. this.updateWidth(backWidth, defaultValue || {tdPadding:10, tdBorder:1});
  17289. },
  17290. updateWidth:function (width, defaultValue) {
  17291. var table = this.table,
  17292. tmpWidth = UETable.getWidth(table) - defaultValue.tdPadding * 2 - defaultValue.tdBorder + width;
  17293. if (tmpWidth < table.ownerDocument.body.offsetWidth) {
  17294. table.setAttribute("width", tmpWidth);
  17295. return;
  17296. }
  17297. var tds = domUtils.getElementsByTagName(this.table, "td th");
  17298. utils.each(tds, function (td) {
  17299. td.setAttribute("width", width);
  17300. })
  17301. },
  17302. deleteCol:function (colIndex) {
  17303. var indexTable = this.indexTable,
  17304. tableRows = this.table.rows,
  17305. backTableWidth = this.table.getAttribute("width"),
  17306. backTdWidth = 0,
  17307. rowsNum = this.rowsNum,
  17308. cacheMap = {};
  17309. for (var rowIndex = 0; rowIndex < rowsNum;) {
  17310. var infoRow = indexTable[rowIndex],
  17311. cellInfo = infoRow[colIndex],
  17312. key = cellInfo.rowIndex + '_' + cellInfo.colIndex;
  17313. // 跳过已经处理过的Cell
  17314. if (cacheMap[key])continue;
  17315. cacheMap[key] = 1;
  17316. var cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  17317. if (!backTdWidth) backTdWidth = cell && parseInt(cell.offsetWidth / cell.colSpan, 10).toFixed(0);
  17318. // 如果Cell的colSpan大于1, 就修改colSpan, 否则就删掉这个Cell
  17319. if (cell.colSpan > 1) {
  17320. cell.colSpan--;
  17321. } else {
  17322. tableRows[rowIndex].deleteCell(cellInfo.cellIndex);
  17323. }
  17324. rowIndex += cellInfo.rowSpan || 1;
  17325. }
  17326. this.table.setAttribute("width", backTableWidth - backTdWidth);
  17327. this.update();
  17328. },
  17329. splitToCells:function (cell) {
  17330. var me = this,
  17331. cells = this.splitToRows(cell);
  17332. utils.each(cells, function (cell) {
  17333. me.splitToCols(cell);
  17334. })
  17335. },
  17336. splitToRows:function (cell) {
  17337. var cellInfo = this.getCellInfo(cell),
  17338. rowIndex = cellInfo.rowIndex,
  17339. colIndex = cellInfo.colIndex,
  17340. results = [];
  17341. // 修改Cell的rowSpan
  17342. cell.rowSpan = 1;
  17343. results.push(cell);
  17344. // 补齐单元格
  17345. for (var i = rowIndex, endRow = rowIndex + cellInfo.rowSpan; i < endRow; i++) {
  17346. if (i == rowIndex)continue;
  17347. var tableRow = this.table.rows[i],
  17348. tmpCell = tableRow.insertCell(colIndex - this.getPreviewMergedCellsNum(i, colIndex));
  17349. tmpCell.colSpan = cellInfo.colSpan;
  17350. this.setCellContent(tmpCell);
  17351. tmpCell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  17352. tmpCell.setAttribute('align', cell.getAttribute('align'));
  17353. if (cell.style.cssText) {
  17354. tmpCell.style.cssText = cell.style.cssText;
  17355. }
  17356. results.push(tmpCell);
  17357. }
  17358. this.update();
  17359. return results;
  17360. },
  17361. getPreviewMergedCellsNum:function (rowIndex, colIndex) {
  17362. var indexRow = this.indexTable[rowIndex],
  17363. num = 0;
  17364. for (var i = 0; i < colIndex;) {
  17365. var colSpan = indexRow[i].colSpan,
  17366. tmpRowIndex = indexRow[i].rowIndex;
  17367. num += (colSpan - (tmpRowIndex == rowIndex ? 1 : 0));
  17368. i += colSpan;
  17369. }
  17370. return num;
  17371. },
  17372. splitToCols:function (cell) {
  17373. var backWidth = (cell.offsetWidth / cell.colSpan - 22).toFixed(0),
  17374. cellInfo = this.getCellInfo(cell),
  17375. rowIndex = cellInfo.rowIndex,
  17376. colIndex = cellInfo.colIndex,
  17377. results = [];
  17378. // 修改Cell的rowSpan
  17379. cell.colSpan = 1;
  17380. cell.setAttribute("width", backWidth);
  17381. results.push(cell);
  17382. // 补齐单元格
  17383. for (var j = colIndex, endCol = colIndex + cellInfo.colSpan; j < endCol; j++) {
  17384. if (j == colIndex)continue;
  17385. var tableRow = this.table.rows[rowIndex],
  17386. tmpCell = tableRow.insertCell(this.indexTable[rowIndex][j].cellIndex + 1);
  17387. tmpCell.rowSpan = cellInfo.rowSpan;
  17388. this.setCellContent(tmpCell);
  17389. tmpCell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  17390. tmpCell.setAttribute('align', cell.getAttribute('align'));
  17391. tmpCell.setAttribute('width', backWidth);
  17392. if (cell.style.cssText) {
  17393. tmpCell.style.cssText = cell.style.cssText;
  17394. }
  17395. //处理th的情况
  17396. if (cell.tagName == 'TH') {
  17397. var th = cell.ownerDocument.createElement('th');
  17398. th.appendChild(tmpCell.firstChild);
  17399. th.setAttribute('vAlign', cell.getAttribute('vAlign'));
  17400. th.rowSpan = tmpCell.rowSpan;
  17401. tableRow.insertBefore(th, tmpCell);
  17402. domUtils.remove(tmpCell);
  17403. }
  17404. results.push(tmpCell);
  17405. }
  17406. this.update();
  17407. return results;
  17408. },
  17409. isLastCell:function (cell, rowsNum, colsNum) {
  17410. rowsNum = rowsNum || this.rowsNum;
  17411. colsNum = colsNum || this.colsNum;
  17412. var cellInfo = this.getCellInfo(cell);
  17413. return ((cellInfo.rowIndex + cellInfo.rowSpan) == rowsNum) &&
  17414. ((cellInfo.colIndex + cellInfo.colSpan) == colsNum);
  17415. },
  17416. getLastCell:function (cells) {
  17417. cells = cells || this.table.getElementsByTagName("td");
  17418. var firstInfo = this.getCellInfo(cells[0]);
  17419. var me = this, last = cells[0],
  17420. tr = last.parentNode,
  17421. cellsNum = 0, cols = 0, rows;
  17422. utils.each(cells, function (cell) {
  17423. if (cell.parentNode == tr)cols += cell.colSpan || 1;
  17424. cellsNum += cell.rowSpan * cell.colSpan || 1;
  17425. });
  17426. rows = cellsNum / cols;
  17427. utils.each(cells, function (cell) {
  17428. if (me.isLastCell(cell, rows, cols)) {
  17429. last = cell;
  17430. return false;
  17431. }
  17432. });
  17433. return last;
  17434. },
  17435. selectRow:function (rowIndex) {
  17436. var indexRow = this.indexTable[rowIndex],
  17437. start = this.getCell(indexRow[0].rowIndex, indexRow[0].cellIndex),
  17438. end = this.getCell(indexRow[this.colsNum - 1].rowIndex, indexRow[this.colsNum - 1].cellIndex),
  17439. range = this.getCellsRange(start, end);
  17440. this.setSelected(range);
  17441. },
  17442. selectTable:function () {
  17443. var tds = this.table.getElementsByTagName("td"),
  17444. range = this.getCellsRange(tds[0], tds[tds.length - 1]);
  17445. this.setSelected(range);
  17446. },
  17447. setBackground:function (cells, value) {
  17448. if (typeof value === "string") {
  17449. utils.each(cells, function (cell) {
  17450. cell.style.backgroundColor = value;
  17451. })
  17452. } else if (typeof value === "object") {
  17453. value = utils.extend({
  17454. repeat:true,
  17455. colorList:["#ddd", "#fff"]
  17456. }, value);
  17457. var rowIndex = this.getCellInfo(cells[0]).rowIndex,
  17458. count = 0,
  17459. colors = value.colorList,
  17460. getColor = function (list, index, repeat) {
  17461. return list[index] ? list[index] : repeat ? list[index % list.length] : "";
  17462. };
  17463. for (var i = 0, cell; cell = cells[i++];) {
  17464. var cellInfo = this.getCellInfo(cell);
  17465. cell.style.backgroundColor = getColor(colors, ((rowIndex + count) == cellInfo.rowIndex) ? count : ++count, value.repeat);
  17466. }
  17467. }
  17468. },
  17469. removeBackground:function (cells) {
  17470. utils.each(cells, function (cell) {
  17471. cell.style.backgroundColor = "";
  17472. })
  17473. }
  17474. };
  17475. function showError(e) {
  17476. }
  17477. })();
  17478. // plugins/table.cmds.js
  17479. /**
  17480. * Created with JetBrains PhpStorm.
  17481. * User: taoqili
  17482. * Date: 13-2-20
  17483. * Time: 下午6:25
  17484. * To change this template use File | Settings | File Templates.
  17485. */
  17486. ;
  17487. (function () {
  17488. var UT = UE.UETable,
  17489. getTableItemsByRange = function (editor) {
  17490. return UT.getTableItemsByRange(editor);
  17491. },
  17492. getUETableBySelected = function (editor) {
  17493. return UT.getUETableBySelected(editor)
  17494. },
  17495. getDefaultValue = function (editor, table) {
  17496. return UT.getDefaultValue(editor, table);
  17497. },
  17498. getUETable = function (tdOrTable) {
  17499. return UT.getUETable(tdOrTable);
  17500. };
  17501. UE.commands['inserttable'] = {
  17502. queryCommandState: function () {
  17503. return getTableItemsByRange(this).table ? -1 : 0;
  17504. },
  17505. execCommand: function (cmd, opt) {
  17506. function createTable(opt, tdWidth) {
  17507. var html = [],
  17508. rowsNum = opt.numRows,
  17509. colsNum = opt.numCols;
  17510. for (var r = 0; r < rowsNum; r++) {
  17511. html.push('<tr' + (r == 0 ? ' class="firstRow"':'') + '>');
  17512. for (var c = 0; c < colsNum; c++) {
  17513. html.push('<td width="' + tdWidth + '" vAlign="' + opt.tdvalign + '" >' + (browser.ie && browser.version < 11 ? domUtils.fillChar : '<br/>') + '</td>')
  17514. }
  17515. html.push('</tr>')
  17516. }
  17517. //禁止指定table-width
  17518. return '<table><tbody>' + html.join('') + '</tbody></table>'
  17519. }
  17520. if (!opt) {
  17521. opt = utils.extend({}, {
  17522. numCols: this.options.defaultCols,
  17523. numRows: this.options.defaultRows,
  17524. tdvalign: this.options.tdvalign
  17525. })
  17526. }
  17527. var me = this;
  17528. var range = this.selection.getRange(),
  17529. start = range.startContainer,
  17530. firstParentBlock = domUtils.findParent(start, function (node) {
  17531. return domUtils.isBlockElm(node);
  17532. }, true) || me.body;
  17533. var defaultValue = getDefaultValue(me),
  17534. tableWidth = firstParentBlock.offsetWidth,
  17535. tdWidth = Math.floor(tableWidth / opt.numCols - defaultValue.tdPadding * 2 - defaultValue.tdBorder);
  17536. //todo其他属性
  17537. !opt.tdvalign && (opt.tdvalign = me.options.tdvalign);
  17538. me.execCommand("inserthtml", createTable(opt, tdWidth));
  17539. }
  17540. };
  17541. UE.commands['insertparagraphbeforetable'] = {
  17542. queryCommandState: function () {
  17543. return getTableItemsByRange(this).cell ? 0 : -1;
  17544. },
  17545. execCommand: function () {
  17546. var table = getTableItemsByRange(this).table;
  17547. if (table) {
  17548. var p = this.document.createElement("p");
  17549. p.innerHTML = browser.ie ? '&nbsp;' : '<br />';
  17550. table.parentNode.insertBefore(p, table);
  17551. this.selection.getRange().setStart(p, 0).setCursor();
  17552. }
  17553. }
  17554. };
  17555. UE.commands['deletetable'] = {
  17556. queryCommandState: function () {
  17557. var rng = this.selection.getRange();
  17558. return domUtils.findParentByTagName(rng.startContainer, 'table', true) ? 0 : -1;
  17559. },
  17560. execCommand: function (cmd, table) {
  17561. var rng = this.selection.getRange();
  17562. table = table || domUtils.findParentByTagName(rng.startContainer, 'table', true);
  17563. if (table) {
  17564. var next = table.nextSibling;
  17565. if (!next) {
  17566. next = domUtils.createElement(this.document, 'p', {
  17567. 'innerHTML': browser.ie ? domUtils.fillChar : '<br/>'
  17568. });
  17569. table.parentNode.insertBefore(next, table);
  17570. }
  17571. domUtils.remove(table);
  17572. rng = this.selection.getRange();
  17573. if (next.nodeType == 3) {
  17574. rng.setStartBefore(next)
  17575. } else {
  17576. rng.setStart(next, 0)
  17577. }
  17578. rng.setCursor(false, true)
  17579. this.fireEvent("tablehasdeleted")
  17580. }
  17581. }
  17582. };
  17583. UE.commands['cellalign'] = {
  17584. queryCommandState: function () {
  17585. return getSelectedArr(this).length ? 0 : -1
  17586. },
  17587. execCommand: function (cmd, align) {
  17588. var selectedTds = getSelectedArr(this);
  17589. if (selectedTds.length) {
  17590. for (var i = 0, ci; ci = selectedTds[i++];) {
  17591. ci.setAttribute('align', align);
  17592. }
  17593. }
  17594. }
  17595. };
  17596. UE.commands['cellvalign'] = {
  17597. queryCommandState: function () {
  17598. return getSelectedArr(this).length ? 0 : -1;
  17599. },
  17600. execCommand: function (cmd, valign) {
  17601. var selectedTds = getSelectedArr(this);
  17602. if (selectedTds.length) {
  17603. for (var i = 0, ci; ci = selectedTds[i++];) {
  17604. ci.setAttribute('vAlign', valign);
  17605. }
  17606. }
  17607. }
  17608. };
  17609. UE.commands['insertcaption'] = {
  17610. queryCommandState: function () {
  17611. var table = getTableItemsByRange(this).table;
  17612. if (table) {
  17613. return table.getElementsByTagName('caption').length == 0 ? 1 : -1;
  17614. }
  17615. return -1;
  17616. },
  17617. execCommand: function () {
  17618. var table = getTableItemsByRange(this).table;
  17619. if (table) {
  17620. var caption = this.document.createElement('caption');
  17621. caption.innerHTML = browser.ie ? domUtils.fillChar : '<br/>';
  17622. table.insertBefore(caption, table.firstChild);
  17623. var range = this.selection.getRange();
  17624. range.setStart(caption, 0).setCursor();
  17625. }
  17626. }
  17627. };
  17628. UE.commands['deletecaption'] = {
  17629. queryCommandState: function () {
  17630. var rng = this.selection.getRange(),
  17631. table = domUtils.findParentByTagName(rng.startContainer, 'table');
  17632. if (table) {
  17633. return table.getElementsByTagName('caption').length == 0 ? -1 : 1;
  17634. }
  17635. return -1;
  17636. },
  17637. execCommand: function () {
  17638. var rng = this.selection.getRange(),
  17639. table = domUtils.findParentByTagName(rng.startContainer, 'table');
  17640. if (table) {
  17641. domUtils.remove(table.getElementsByTagName('caption')[0]);
  17642. var range = this.selection.getRange();
  17643. range.setStart(table.rows[0].cells[0], 0).setCursor();
  17644. }
  17645. }
  17646. };
  17647. UE.commands['inserttitle'] = {
  17648. queryCommandState: function () {
  17649. var table = getTableItemsByRange(this).table;
  17650. if (table) {
  17651. var firstRow = table.rows[0];
  17652. return firstRow.cells[firstRow.cells.length-1].tagName.toLowerCase() != 'th' ? 0 : -1
  17653. }
  17654. return -1;
  17655. },
  17656. execCommand: function () {
  17657. var table = getTableItemsByRange(this).table;
  17658. if (table) {
  17659. getUETable(table).insertRow(0, 'th');
  17660. }
  17661. var th = table.getElementsByTagName('th')[0];
  17662. this.selection.getRange().setStart(th, 0).setCursor(false, true);
  17663. }
  17664. };
  17665. UE.commands['deletetitle'] = {
  17666. queryCommandState: function () {
  17667. var table = getTableItemsByRange(this).table;
  17668. if (table) {
  17669. var firstRow = table.rows[0];
  17670. return firstRow.cells[firstRow.cells.length-1].tagName.toLowerCase() == 'th' ? 0 : -1
  17671. }
  17672. return -1;
  17673. },
  17674. execCommand: function () {
  17675. var table = getTableItemsByRange(this).table;
  17676. if (table) {
  17677. domUtils.remove(table.rows[0])
  17678. }
  17679. var td = table.getElementsByTagName('td')[0];
  17680. this.selection.getRange().setStart(td, 0).setCursor(false, true);
  17681. }
  17682. };
  17683. UE.commands['inserttitlecol'] = {
  17684. queryCommandState: function () {
  17685. var table = getTableItemsByRange(this).table;
  17686. if (table) {
  17687. var lastRow = table.rows[table.rows.length-1];
  17688. return lastRow.getElementsByTagName('th').length ? -1 : 0;
  17689. }
  17690. return -1;
  17691. },
  17692. execCommand: function (cmd) {
  17693. var table = getTableItemsByRange(this).table;
  17694. if (table) {
  17695. getUETable(table).insertCol(0, 'th');
  17696. }
  17697. resetTdWidth(table, this);
  17698. var th = table.getElementsByTagName('th')[0];
  17699. this.selection.getRange().setStart(th, 0).setCursor(false, true);
  17700. }
  17701. };
  17702. UE.commands['deletetitlecol'] = {
  17703. queryCommandState: function () {
  17704. var table = getTableItemsByRange(this).table;
  17705. if (table) {
  17706. var lastRow = table.rows[table.rows.length-1];
  17707. return lastRow.getElementsByTagName('th').length ? 0 : -1;
  17708. }
  17709. return -1;
  17710. },
  17711. execCommand: function () {
  17712. var table = getTableItemsByRange(this).table;
  17713. if (table) {
  17714. for(var i = 0; i< table.rows.length; i++ ){
  17715. domUtils.remove(table.rows[i].children[0])
  17716. }
  17717. }
  17718. resetTdWidth(table, this);
  17719. var td = table.getElementsByTagName('td')[0];
  17720. this.selection.getRange().setStart(td, 0).setCursor(false, true);
  17721. }
  17722. };
  17723. UE.commands["mergeright"] = {
  17724. queryCommandState: function (cmd) {
  17725. var tableItems = getTableItemsByRange(this),
  17726. table = tableItems.table,
  17727. cell = tableItems.cell;
  17728. if (!table || !cell) return -1;
  17729. var ut = getUETable(table);
  17730. if (ut.selectedTds.length) return -1;
  17731. var cellInfo = ut.getCellInfo(cell),
  17732. rightColIndex = cellInfo.colIndex + cellInfo.colSpan;
  17733. if (rightColIndex >= ut.colsNum) return -1; // 如果处于最右边则不能向右合并
  17734. var rightCellInfo = ut.indexTable[cellInfo.rowIndex][rightColIndex],
  17735. rightCell = table.rows[rightCellInfo.rowIndex].cells[rightCellInfo.cellIndex];
  17736. if (!rightCell || cell.tagName != rightCell.tagName) return -1; // TH和TD不能相互合并
  17737. // 当且仅当两个Cell的开始列号和结束列号一致时能进行合并
  17738. return (rightCellInfo.rowIndex == cellInfo.rowIndex && rightCellInfo.rowSpan == cellInfo.rowSpan) ? 0 : -1;
  17739. },
  17740. execCommand: function (cmd) {
  17741. var rng = this.selection.getRange(),
  17742. bk = rng.createBookmark(true);
  17743. var cell = getTableItemsByRange(this).cell,
  17744. ut = getUETable(cell);
  17745. ut.mergeRight(cell);
  17746. rng.moveToBookmark(bk).select();
  17747. }
  17748. };
  17749. UE.commands["mergedown"] = {
  17750. queryCommandState: function (cmd) {
  17751. var tableItems = getTableItemsByRange(this),
  17752. table = tableItems.table,
  17753. cell = tableItems.cell;
  17754. if (!table || !cell) return -1;
  17755. var ut = getUETable(table);
  17756. if (ut.selectedTds.length)return -1;
  17757. var cellInfo = ut.getCellInfo(cell),
  17758. downRowIndex = cellInfo.rowIndex + cellInfo.rowSpan;
  17759. if (downRowIndex >= ut.rowsNum) return -1; // 如果处于最下边则不能向下合并
  17760. var downCellInfo = ut.indexTable[downRowIndex][cellInfo.colIndex],
  17761. downCell = table.rows[downCellInfo.rowIndex].cells[downCellInfo.cellIndex];
  17762. if (!downCell || cell.tagName != downCell.tagName) return -1; // TH和TD不能相互合并
  17763. // 当且仅当两个Cell的开始列号和结束列号一致时能进行合并
  17764. return (downCellInfo.colIndex == cellInfo.colIndex && downCellInfo.colSpan == cellInfo.colSpan) ? 0 : -1;
  17765. },
  17766. execCommand: function () {
  17767. var rng = this.selection.getRange(),
  17768. bk = rng.createBookmark(true);
  17769. var cell = getTableItemsByRange(this).cell,
  17770. ut = getUETable(cell);
  17771. ut.mergeDown(cell);
  17772. rng.moveToBookmark(bk).select();
  17773. }
  17774. };
  17775. UE.commands["mergecells"] = {
  17776. queryCommandState: function () {
  17777. return getUETableBySelected(this) ? 0 : -1;
  17778. },
  17779. execCommand: function () {
  17780. var ut = getUETableBySelected(this);
  17781. if (ut && ut.selectedTds.length) {
  17782. var cell = ut.selectedTds[0];
  17783. ut.mergeRange();
  17784. var rng = this.selection.getRange();
  17785. if (domUtils.isEmptyBlock(cell)) {
  17786. rng.setStart(cell, 0).collapse(true)
  17787. } else {
  17788. rng.selectNodeContents(cell)
  17789. }
  17790. rng.select();
  17791. }
  17792. }
  17793. };
  17794. UE.commands["insertrow"] = {
  17795. queryCommandState: function () {
  17796. var tableItems = getTableItemsByRange(this),
  17797. cell = tableItems.cell;
  17798. return cell && (cell.tagName == "TD" || (cell.tagName == 'TH' && tableItems.tr !== tableItems.table.rows[0])) &&
  17799. getUETable(tableItems.table).rowsNum < this.options.maxRowNum ? 0 : -1;
  17800. },
  17801. execCommand: function () {
  17802. var rng = this.selection.getRange(),
  17803. bk = rng.createBookmark(true);
  17804. var tableItems = getTableItemsByRange(this),
  17805. cell = tableItems.cell,
  17806. table = tableItems.table,
  17807. ut = getUETable(table),
  17808. cellInfo = ut.getCellInfo(cell);
  17809. //ut.insertRow(!ut.selectedTds.length ? cellInfo.rowIndex:ut.cellsRange.beginRowIndex,'');
  17810. if (!ut.selectedTds.length) {
  17811. ut.insertRow(cellInfo.rowIndex, cell);
  17812. } else {
  17813. var range = ut.cellsRange;
  17814. for (var i = 0, len = range.endRowIndex - range.beginRowIndex + 1; i < len; i++) {
  17815. ut.insertRow(range.beginRowIndex, cell);
  17816. }
  17817. }
  17818. rng.moveToBookmark(bk).select();
  17819. if (table.getAttribute("interlaced") === "enabled")this.fireEvent("interlacetable", table);
  17820. }
  17821. };
  17822. //后插入行
  17823. UE.commands["insertrownext"] = {
  17824. queryCommandState: function () {
  17825. var tableItems = getTableItemsByRange(this),
  17826. cell = tableItems.cell;
  17827. return cell && (cell.tagName == "TD") && getUETable(tableItems.table).rowsNum < this.options.maxRowNum ? 0 : -1;
  17828. },
  17829. execCommand: function () {
  17830. var rng = this.selection.getRange(),
  17831. bk = rng.createBookmark(true);
  17832. var tableItems = getTableItemsByRange(this),
  17833. cell = tableItems.cell,
  17834. table = tableItems.table,
  17835. ut = getUETable(table),
  17836. cellInfo = ut.getCellInfo(cell);
  17837. //ut.insertRow(!ut.selectedTds.length? cellInfo.rowIndex + cellInfo.rowSpan : ut.cellsRange.endRowIndex + 1,'');
  17838. if (!ut.selectedTds.length) {
  17839. ut.insertRow(cellInfo.rowIndex + cellInfo.rowSpan, cell);
  17840. } else {
  17841. var range = ut.cellsRange;
  17842. for (var i = 0, len = range.endRowIndex - range.beginRowIndex + 1; i < len; i++) {
  17843. ut.insertRow(range.endRowIndex + 1, cell);
  17844. }
  17845. }
  17846. rng.moveToBookmark(bk).select();
  17847. if (table.getAttribute("interlaced") === "enabled")this.fireEvent("interlacetable", table);
  17848. }
  17849. };
  17850. UE.commands["deleterow"] = {
  17851. queryCommandState: function () {
  17852. var tableItems = getTableItemsByRange(this);
  17853. return tableItems.cell ? 0 : -1;
  17854. },
  17855. execCommand: function () {
  17856. var cell = getTableItemsByRange(this).cell,
  17857. ut = getUETable(cell),
  17858. cellsRange = ut.cellsRange,
  17859. cellInfo = ut.getCellInfo(cell),
  17860. preCell = ut.getVSideCell(cell),
  17861. nextCell = ut.getVSideCell(cell, true),
  17862. rng = this.selection.getRange();
  17863. if (utils.isEmptyObject(cellsRange)) {
  17864. ut.deleteRow(cellInfo.rowIndex);
  17865. } else {
  17866. for (var i = cellsRange.beginRowIndex; i < cellsRange.endRowIndex + 1; i++) {
  17867. ut.deleteRow(cellsRange.beginRowIndex);
  17868. }
  17869. }
  17870. var table = ut.table;
  17871. if (!table.getElementsByTagName('td').length) {
  17872. var nextSibling = table.nextSibling;
  17873. domUtils.remove(table);
  17874. if (nextSibling) {
  17875. rng.setStart(nextSibling, 0).setCursor(false, true);
  17876. }
  17877. } else {
  17878. if (cellInfo.rowSpan == 1 || cellInfo.rowSpan == cellsRange.endRowIndex - cellsRange.beginRowIndex + 1) {
  17879. if (nextCell || preCell) rng.selectNodeContents(nextCell || preCell).setCursor(false, true);
  17880. } else {
  17881. var newCell = ut.getCell(cellInfo.rowIndex, ut.indexTable[cellInfo.rowIndex][cellInfo.colIndex].cellIndex);
  17882. if (newCell) rng.selectNodeContents(newCell).setCursor(false, true);
  17883. }
  17884. }
  17885. if (table.getAttribute("interlaced") === "enabled")this.fireEvent("interlacetable", table);
  17886. }
  17887. };
  17888. UE.commands["insertcol"] = {
  17889. queryCommandState: function (cmd) {
  17890. var tableItems = getTableItemsByRange(this),
  17891. cell = tableItems.cell;
  17892. return cell && (cell.tagName == "TD" || (cell.tagName == 'TH' && cell !== tableItems.tr.cells[0])) &&
  17893. getUETable(tableItems.table).colsNum < this.options.maxColNum ? 0 : -1;
  17894. },
  17895. execCommand: function (cmd) {
  17896. var rng = this.selection.getRange(),
  17897. bk = rng.createBookmark(true);
  17898. if (this.queryCommandState(cmd) == -1)return;
  17899. var cell = getTableItemsByRange(this).cell,
  17900. ut = getUETable(cell),
  17901. cellInfo = ut.getCellInfo(cell);
  17902. //ut.insertCol(!ut.selectedTds.length ? cellInfo.colIndex:ut.cellsRange.beginColIndex);
  17903. if (!ut.selectedTds.length) {
  17904. ut.insertCol(cellInfo.colIndex, cell);
  17905. } else {
  17906. var range = ut.cellsRange;
  17907. for (var i = 0, len = range.endColIndex - range.beginColIndex + 1; i < len; i++) {
  17908. ut.insertCol(range.beginColIndex, cell);
  17909. }
  17910. }
  17911. rng.moveToBookmark(bk).select(true);
  17912. }
  17913. };
  17914. UE.commands["insertcolnext"] = {
  17915. queryCommandState: function () {
  17916. var tableItems = getTableItemsByRange(this),
  17917. cell = tableItems.cell;
  17918. return cell && getUETable(tableItems.table).colsNum < this.options.maxColNum ? 0 : -1;
  17919. },
  17920. execCommand: function () {
  17921. var rng = this.selection.getRange(),
  17922. bk = rng.createBookmark(true);
  17923. var cell = getTableItemsByRange(this).cell,
  17924. ut = getUETable(cell),
  17925. cellInfo = ut.getCellInfo(cell);
  17926. //ut.insertCol(!ut.selectedTds.length ? cellInfo.colIndex + cellInfo.colSpan:ut.cellsRange.endColIndex +1);
  17927. if (!ut.selectedTds.length) {
  17928. ut.insertCol(cellInfo.colIndex + cellInfo.colSpan, cell);
  17929. } else {
  17930. var range = ut.cellsRange;
  17931. for (var i = 0, len = range.endColIndex - range.beginColIndex + 1; i < len; i++) {
  17932. ut.insertCol(range.endColIndex + 1, cell);
  17933. }
  17934. }
  17935. rng.moveToBookmark(bk).select();
  17936. }
  17937. };
  17938. UE.commands["deletecol"] = {
  17939. queryCommandState: function () {
  17940. var tableItems = getTableItemsByRange(this);
  17941. return tableItems.cell ? 0 : -1;
  17942. },
  17943. execCommand: function () {
  17944. var cell = getTableItemsByRange(this).cell,
  17945. ut = getUETable(cell),
  17946. range = ut.cellsRange,
  17947. cellInfo = ut.getCellInfo(cell),
  17948. preCell = ut.getHSideCell(cell),
  17949. nextCell = ut.getHSideCell(cell, true);
  17950. if (utils.isEmptyObject(range)) {
  17951. ut.deleteCol(cellInfo.colIndex);
  17952. } else {
  17953. for (var i = range.beginColIndex; i < range.endColIndex + 1; i++) {
  17954. ut.deleteCol(range.beginColIndex);
  17955. }
  17956. }
  17957. var table = ut.table,
  17958. rng = this.selection.getRange();
  17959. if (!table.getElementsByTagName('td').length) {
  17960. var nextSibling = table.nextSibling;
  17961. domUtils.remove(table);
  17962. if (nextSibling) {
  17963. rng.setStart(nextSibling, 0).setCursor(false, true);
  17964. }
  17965. } else {
  17966. if (domUtils.inDoc(cell, this.document)) {
  17967. rng.setStart(cell, 0).setCursor(false, true);
  17968. } else {
  17969. if (nextCell && domUtils.inDoc(nextCell, this.document)) {
  17970. rng.selectNodeContents(nextCell).setCursor(false, true);
  17971. } else {
  17972. if (preCell && domUtils.inDoc(preCell, this.document)) {
  17973. rng.selectNodeContents(preCell).setCursor(true, true);
  17974. }
  17975. }
  17976. }
  17977. }
  17978. }
  17979. };
  17980. UE.commands["splittocells"] = {
  17981. queryCommandState: function () {
  17982. var tableItems = getTableItemsByRange(this),
  17983. cell = tableItems.cell;
  17984. if (!cell) return -1;
  17985. var ut = getUETable(tableItems.table);
  17986. if (ut.selectedTds.length > 0) return -1;
  17987. return cell && (cell.colSpan > 1 || cell.rowSpan > 1) ? 0 : -1;
  17988. },
  17989. execCommand: function () {
  17990. var rng = this.selection.getRange(),
  17991. bk = rng.createBookmark(true);
  17992. var cell = getTableItemsByRange(this).cell,
  17993. ut = getUETable(cell);
  17994. ut.splitToCells(cell);
  17995. rng.moveToBookmark(bk).select();
  17996. }
  17997. };
  17998. UE.commands["splittorows"] = {
  17999. queryCommandState: function () {
  18000. var tableItems = getTableItemsByRange(this),
  18001. cell = tableItems.cell;
  18002. if (!cell) return -1;
  18003. var ut = getUETable(tableItems.table);
  18004. if (ut.selectedTds.length > 0) return -1;
  18005. return cell && cell.rowSpan > 1 ? 0 : -1;
  18006. },
  18007. execCommand: function () {
  18008. var rng = this.selection.getRange(),
  18009. bk = rng.createBookmark(true);
  18010. var cell = getTableItemsByRange(this).cell,
  18011. ut = getUETable(cell);
  18012. ut.splitToRows(cell);
  18013. rng.moveToBookmark(bk).select();
  18014. }
  18015. };
  18016. UE.commands["splittocols"] = {
  18017. queryCommandState: function () {
  18018. var tableItems = getTableItemsByRange(this),
  18019. cell = tableItems.cell;
  18020. if (!cell) return -1;
  18021. var ut = getUETable(tableItems.table);
  18022. if (ut.selectedTds.length > 0) return -1;
  18023. return cell && cell.colSpan > 1 ? 0 : -1;
  18024. },
  18025. execCommand: function () {
  18026. var rng = this.selection.getRange(),
  18027. bk = rng.createBookmark(true);
  18028. var cell = getTableItemsByRange(this).cell,
  18029. ut = getUETable(cell);
  18030. ut.splitToCols(cell);
  18031. rng.moveToBookmark(bk).select();
  18032. }
  18033. };
  18034. UE.commands["adaptbytext"] =
  18035. UE.commands["adaptbywindow"] = {
  18036. queryCommandState: function () {
  18037. return getTableItemsByRange(this).table ? 0 : -1
  18038. },
  18039. execCommand: function (cmd) {
  18040. var tableItems = getTableItemsByRange(this),
  18041. table = tableItems.table;
  18042. if (table) {
  18043. if (cmd == 'adaptbywindow') {
  18044. resetTdWidth(table, this);
  18045. } else {
  18046. var cells = domUtils.getElementsByTagName(table, "td th");
  18047. utils.each(cells, function (cell) {
  18048. cell.removeAttribute("width");
  18049. });
  18050. table.removeAttribute("width");
  18051. }
  18052. }
  18053. }
  18054. };
  18055. //平均分配各列
  18056. UE.commands['averagedistributecol'] = {
  18057. queryCommandState: function () {
  18058. var ut = getUETableBySelected(this);
  18059. if (!ut) return -1;
  18060. return ut.isFullRow() || ut.isFullCol() ? 0 : -1;
  18061. },
  18062. execCommand: function (cmd) {
  18063. var me = this,
  18064. ut = getUETableBySelected(me);
  18065. function getAverageWidth() {
  18066. var tb = ut.table,
  18067. averageWidth, sumWidth = 0, colsNum = 0,
  18068. tbAttr = getDefaultValue(me, tb);
  18069. if (ut.isFullRow()) {
  18070. sumWidth = tb.offsetWidth;
  18071. colsNum = ut.colsNum;
  18072. } else {
  18073. var begin = ut.cellsRange.beginColIndex,
  18074. end = ut.cellsRange.endColIndex,
  18075. node;
  18076. for (var i = begin; i <= end;) {
  18077. node = ut.selectedTds[i];
  18078. sumWidth += node.offsetWidth;
  18079. i += node.colSpan;
  18080. colsNum += 1;
  18081. }
  18082. }
  18083. averageWidth = Math.ceil(sumWidth / colsNum) - tbAttr.tdBorder * 2 - tbAttr.tdPadding * 2;
  18084. return averageWidth;
  18085. }
  18086. function setAverageWidth(averageWidth) {
  18087. utils.each(domUtils.getElementsByTagName(ut.table, "th"), function (node) {
  18088. node.setAttribute("width", "");
  18089. });
  18090. var cells = ut.isFullRow() ? domUtils.getElementsByTagName(ut.table, "td") : ut.selectedTds;
  18091. utils.each(cells, function (node) {
  18092. if (node.colSpan == 1) {
  18093. node.setAttribute("width", averageWidth);
  18094. }
  18095. });
  18096. }
  18097. if (ut && ut.selectedTds.length) {
  18098. setAverageWidth(getAverageWidth());
  18099. }
  18100. }
  18101. };
  18102. //平均分配各行
  18103. UE.commands['averagedistributerow'] = {
  18104. queryCommandState: function () {
  18105. var ut = getUETableBySelected(this);
  18106. if (!ut) return -1;
  18107. if (ut.selectedTds && /th/ig.test(ut.selectedTds[0].tagName)) return -1;
  18108. return ut.isFullRow() || ut.isFullCol() ? 0 : -1;
  18109. },
  18110. execCommand: function (cmd) {
  18111. var me = this,
  18112. ut = getUETableBySelected(me);
  18113. function getAverageHeight() {
  18114. var averageHeight, rowNum, sumHeight = 0,
  18115. tb = ut.table,
  18116. tbAttr = getDefaultValue(me, tb),
  18117. tdpadding = parseInt(domUtils.getComputedStyle(tb.getElementsByTagName('td')[0], "padding-top"));
  18118. if (ut.isFullCol()) {
  18119. var captionArr = domUtils.getElementsByTagName(tb, "caption"),
  18120. thArr = domUtils.getElementsByTagName(tb, "th"),
  18121. captionHeight, thHeight;
  18122. if (captionArr.length > 0) {
  18123. captionHeight = captionArr[0].offsetHeight;
  18124. }
  18125. if (thArr.length > 0) {
  18126. thHeight = thArr[0].offsetHeight;
  18127. }
  18128. sumHeight = tb.offsetHeight - (captionHeight || 0) - (thHeight || 0);
  18129. rowNum = thArr.length == 0 ? ut.rowsNum : (ut.rowsNum - 1);
  18130. } else {
  18131. var begin = ut.cellsRange.beginRowIndex,
  18132. end = ut.cellsRange.endRowIndex,
  18133. count = 0,
  18134. trs = domUtils.getElementsByTagName(tb, "tr");
  18135. for (var i = begin; i <= end; i++) {
  18136. sumHeight += trs[i].offsetHeight;
  18137. count += 1;
  18138. }
  18139. rowNum = count;
  18140. }
  18141. //ie8下是混杂模式
  18142. if (browser.ie && browser.version < 9) {
  18143. averageHeight = Math.ceil(sumHeight / rowNum);
  18144. } else {
  18145. averageHeight = Math.ceil(sumHeight / rowNum) - tbAttr.tdBorder * 2 - tdpadding * 2;
  18146. }
  18147. return averageHeight;
  18148. }
  18149. function setAverageHeight(averageHeight) {
  18150. var cells = ut.isFullCol() ? domUtils.getElementsByTagName(ut.table, "td") : ut.selectedTds;
  18151. utils.each(cells, function (node) {
  18152. if (node.rowSpan == 1) {
  18153. node.setAttribute("height", averageHeight);
  18154. }
  18155. });
  18156. }
  18157. if (ut && ut.selectedTds.length) {
  18158. setAverageHeight(getAverageHeight());
  18159. }
  18160. }
  18161. };
  18162. //单元格对齐方式
  18163. UE.commands['cellalignment'] = {
  18164. queryCommandState: function () {
  18165. return getTableItemsByRange(this).table ? 0 : -1
  18166. },
  18167. execCommand: function (cmd, data) {
  18168. var me = this,
  18169. ut = getUETableBySelected(me);
  18170. if (!ut) {
  18171. var start = me.selection.getStart(),
  18172. cell = start && domUtils.findParentByTagName(start, ["td", "th", "caption"], true);
  18173. if (!/caption/ig.test(cell.tagName)) {
  18174. domUtils.setAttributes(cell, data);
  18175. } else {
  18176. cell.style.textAlign = data.align;
  18177. cell.style.verticalAlign = data.vAlign;
  18178. }
  18179. me.selection.getRange().setCursor(true);
  18180. } else {
  18181. utils.each(ut.selectedTds, function (cell) {
  18182. domUtils.setAttributes(cell, data);
  18183. });
  18184. }
  18185. },
  18186. /**
  18187. * 查询当前点击的单元格的对齐状态, 如果当前已经选择了多个单元格, 则会返回所有单元格经过统一协调过后的状态
  18188. * @see UE.UETable.getTableCellAlignState
  18189. */
  18190. queryCommandValue: function (cmd) {
  18191. var activeMenuCell = getTableItemsByRange( this).cell;
  18192. if( !activeMenuCell ) {
  18193. activeMenuCell = getSelectedArr(this)[0];
  18194. }
  18195. if (!activeMenuCell) {
  18196. return null;
  18197. } else {
  18198. //获取同时选中的其他单元格
  18199. var cells = UE.UETable.getUETable(activeMenuCell).selectedTds;
  18200. !cells.length && ( cells = activeMenuCell );
  18201. return UE.UETable.getTableCellAlignState(cells);
  18202. }
  18203. }
  18204. };
  18205. //表格对齐方式
  18206. UE.commands['tablealignment'] = {
  18207. queryCommandState: function () {
  18208. if (browser.ie && browser.version < 8) {
  18209. return -1;
  18210. }
  18211. return getTableItemsByRange(this).table ? 0 : -1
  18212. },
  18213. execCommand: function (cmd, value) {
  18214. var me = this,
  18215. start = me.selection.getStart(),
  18216. table = start && domUtils.findParentByTagName(start, ["table"], true);
  18217. if (table) {
  18218. table.setAttribute("align",value);
  18219. }
  18220. }
  18221. };
  18222. //表格属性
  18223. UE.commands['edittable'] = {
  18224. queryCommandState: function () {
  18225. return getTableItemsByRange(this).table ? 0 : -1
  18226. },
  18227. execCommand: function (cmd, color) {
  18228. var rng = this.selection.getRange(),
  18229. table = domUtils.findParentByTagName(rng.startContainer, 'table');
  18230. if (table) {
  18231. var arr = domUtils.getElementsByTagName(table, "td").concat(
  18232. domUtils.getElementsByTagName(table, "th"),
  18233. domUtils.getElementsByTagName(table, "caption")
  18234. );
  18235. utils.each(arr, function (node) {
  18236. node.style.borderColor = color;
  18237. });
  18238. }
  18239. }
  18240. };
  18241. //单元格属性
  18242. UE.commands['edittd'] = {
  18243. queryCommandState: function () {
  18244. return getTableItemsByRange(this).table ? 0 : -1
  18245. },
  18246. execCommand: function (cmd, bkColor) {
  18247. var me = this,
  18248. ut = getUETableBySelected(me);
  18249. if (!ut) {
  18250. var start = me.selection.getStart(),
  18251. cell = start && domUtils.findParentByTagName(start, ["td", "th", "caption"], true);
  18252. if (cell) {
  18253. cell.style.backgroundColor = bkColor;
  18254. }
  18255. } else {
  18256. utils.each(ut.selectedTds, function (cell) {
  18257. cell.style.backgroundColor = bkColor;
  18258. });
  18259. }
  18260. }
  18261. };
  18262. UE.commands["settablebackground"] = {
  18263. queryCommandState: function () {
  18264. return getSelectedArr(this).length > 1 ? 0 : -1;
  18265. },
  18266. execCommand: function (cmd, value) {
  18267. var cells, ut;
  18268. cells = getSelectedArr(this);
  18269. ut = getUETable(cells[0]);
  18270. ut.setBackground(cells, value);
  18271. }
  18272. };
  18273. UE.commands["cleartablebackground"] = {
  18274. queryCommandState: function () {
  18275. var cells = getSelectedArr(this);
  18276. if (!cells.length)return -1;
  18277. for (var i = 0, cell; cell = cells[i++];) {
  18278. if (cell.style.backgroundColor !== "") return 0;
  18279. }
  18280. return -1;
  18281. },
  18282. execCommand: function () {
  18283. var cells = getSelectedArr(this),
  18284. ut = getUETable(cells[0]);
  18285. ut.removeBackground(cells);
  18286. }
  18287. };
  18288. UE.commands["interlacetable"] = UE.commands["uninterlacetable"] = {
  18289. queryCommandState: function (cmd) {
  18290. var table = getTableItemsByRange(this).table;
  18291. if (!table) return -1;
  18292. var interlaced = table.getAttribute("interlaced");
  18293. if (cmd == "interlacetable") {
  18294. //TODO 待定
  18295. //是否需要待定,如果设置,则命令只能单次执行成功,但反射具备toggle效果;否则可以覆盖前次命令,但反射将不存在toggle效果
  18296. return (interlaced === "enabled") ? -1 : 0;
  18297. } else {
  18298. return (!interlaced || interlaced === "disabled") ? -1 : 0;
  18299. }
  18300. },
  18301. execCommand: function (cmd, classList) {
  18302. var table = getTableItemsByRange(this).table;
  18303. if (cmd == "interlacetable") {
  18304. table.setAttribute("interlaced", "enabled");
  18305. this.fireEvent("interlacetable", table, classList);
  18306. } else {
  18307. table.setAttribute("interlaced", "disabled");
  18308. this.fireEvent("uninterlacetable", table);
  18309. }
  18310. }
  18311. };
  18312. UE.commands["setbordervisible"] = {
  18313. queryCommandState: function (cmd) {
  18314. var table = getTableItemsByRange(this).table;
  18315. if (!table) return -1;
  18316. return 0;
  18317. },
  18318. execCommand: function () {
  18319. var table = getTableItemsByRange(this).table;
  18320. utils.each(domUtils.getElementsByTagName(table,'td'),function(td){
  18321. td.style.borderWidth = '1px';
  18322. td.style.borderStyle = 'solid';
  18323. })
  18324. }
  18325. };
  18326. function resetTdWidth(table, editor) {
  18327. var tds = domUtils.getElementsByTagName(table,'td th');
  18328. utils.each(tds, function (td) {
  18329. td.removeAttribute("width");
  18330. });
  18331. table.setAttribute('width', getTableWidth(editor, true, getDefaultValue(editor, table)));
  18332. var tdsWidths = [];
  18333. setTimeout(function () {
  18334. utils.each(tds, function (td) {
  18335. (td.colSpan == 1) && tdsWidths.push(td.offsetWidth)
  18336. })
  18337. utils.each(tds, function (td,i) {
  18338. (td.colSpan == 1) && td.setAttribute("width", tdsWidths[i] + "");
  18339. })
  18340. }, 0);
  18341. }
  18342. function getTableWidth(editor, needIEHack, defaultValue) {
  18343. var body = editor.body;
  18344. return body.offsetWidth - (needIEHack ? parseInt(domUtils.getComputedStyle(body, 'margin-left'), 10) * 2 : 0) - defaultValue.tableBorder * 2 - (editor.options.offsetWidth || 0);
  18345. }
  18346. function getSelectedArr(editor) {
  18347. var cell = getTableItemsByRange(editor).cell;
  18348. if (cell) {
  18349. var ut = getUETable(cell);
  18350. return ut.selectedTds.length ? ut.selectedTds : [cell];
  18351. } else {
  18352. return [];
  18353. }
  18354. }
  18355. })();
  18356. // plugins/table.action.js
  18357. /**
  18358. * Created with JetBrains PhpStorm.
  18359. * User: taoqili
  18360. * Date: 12-10-12
  18361. * Time: 上午10:05
  18362. * To change this template use File | Settings | File Templates.
  18363. */
  18364. UE.plugins['table'] = function () {
  18365. var me = this,
  18366. tabTimer = null,
  18367. //拖动计时器
  18368. tableDragTimer = null,
  18369. //双击计时器
  18370. tableResizeTimer = null,
  18371. //单元格最小宽度
  18372. cellMinWidth = 5,
  18373. isInResizeBuffer = false,
  18374. //单元格边框大小
  18375. cellBorderWidth = 5,
  18376. //鼠标偏移距离
  18377. offsetOfTableCell = 10,
  18378. //记录在有限时间内的点击状态, 共有3个取值, 0, 1, 2。 0代表未初始化, 1代表单击了1次,2代表2次
  18379. singleClickState = 0,
  18380. userActionStatus = null,
  18381. //双击允许的时间范围
  18382. dblclickTime = 360,
  18383. UT = UE.UETable,
  18384. getUETable = function (tdOrTable) {
  18385. return UT.getUETable(tdOrTable);
  18386. },
  18387. getUETableBySelected = function (editor) {
  18388. return UT.getUETableBySelected(editor);
  18389. },
  18390. getDefaultValue = function (editor, table) {
  18391. return UT.getDefaultValue(editor, table);
  18392. },
  18393. removeSelectedClass = function (cells) {
  18394. return UT.removeSelectedClass(cells);
  18395. };
  18396. function showError(e) {
  18397. // throw e;
  18398. }
  18399. me.ready(function(){
  18400. var me = this;
  18401. var orgGetText = me.selection.getText;
  18402. me.selection.getText = function(){
  18403. var table = getUETableBySelected(me);
  18404. if(table){
  18405. var str = '';
  18406. utils.each(table.selectedTds,function(td){
  18407. str += td[browser.ie?'innerText':'textContent'];
  18408. })
  18409. return str;
  18410. }else{
  18411. return orgGetText.call(me.selection)
  18412. }
  18413. }
  18414. })
  18415. //处理拖动及框选相关方法
  18416. var startTd = null, //鼠标按下时的锚点td
  18417. currentTd = null, //当前鼠标经过时的td
  18418. onDrag = "", //指示当前拖动状态,其值可为"","h","v" ,分别表示未拖动状态,横向拖动状态,纵向拖动状态,用于鼠标移动过程中的判断
  18419. onBorder = false, //检测鼠标按下时是否处在单元格边缘位置
  18420. dragButton = null,
  18421. dragOver = false,
  18422. dragLine = null, //模拟的拖动线
  18423. dragTd = null; //发生拖动的目标td
  18424. var mousedown = false,
  18425. //todo 判断混乱模式
  18426. needIEHack = true;
  18427. me.setOpt({
  18428. 'maxColNum':20,
  18429. 'maxRowNum':100,
  18430. 'defaultCols':5,
  18431. 'defaultRows':5,
  18432. 'tdvalign':'top',
  18433. 'cursorpath':me.options.UEDITOR_HOME_URL + "themes/default/images/cursor_",
  18434. 'tableDragable':false,
  18435. 'classList':["ue-table-interlace-color-single","ue-table-interlace-color-double"]
  18436. });
  18437. me.getUETable = getUETable;
  18438. var commands = {
  18439. 'deletetable':1,
  18440. 'inserttable':1,
  18441. 'cellvalign':1,
  18442. 'insertcaption':1,
  18443. 'deletecaption':1,
  18444. 'inserttitle':1,
  18445. 'deletetitle':1,
  18446. "mergeright":1,
  18447. "mergedown":1,
  18448. "mergecells":1,
  18449. "insertrow":1,
  18450. "insertrownext":1,
  18451. "deleterow":1,
  18452. "insertcol":1,
  18453. "insertcolnext":1,
  18454. "deletecol":1,
  18455. "splittocells":1,
  18456. "splittorows":1,
  18457. "splittocols":1,
  18458. "adaptbytext":1,
  18459. "adaptbywindow":1,
  18460. "adaptbycustomer":1,
  18461. "insertparagraph":1,
  18462. "insertparagraphbeforetable":1,
  18463. "averagedistributecol":1,
  18464. "averagedistributerow":1
  18465. };
  18466. me.ready(function () {
  18467. utils.cssRule('table',
  18468. //选中的td上的样式
  18469. '.selectTdClass{background-color:#edf5fa !important}' +
  18470. 'table.noBorderTable td,table.noBorderTable th,table.noBorderTable caption{border:1px dashed #ddd !important}' +
  18471. //插入的表格的默认样式
  18472. 'table{margin-bottom:10px;border-collapse:collapse;display:table;}' +
  18473. 'td,th{padding: 5px 10px;border: 1px solid #DDD;}' +
  18474. 'caption{border:1px dashed #DDD;border-bottom:0;padding:3px;text-align:center;}' +
  18475. 'th{border-top:1px solid #BBB;background-color:#F7F7F7;}' +
  18476. 'table tr.firstRow th{border-top-width:2px;}' +
  18477. '.ue-table-interlace-color-single{ background-color: #fcfcfc; } .ue-table-interlace-color-double{ background-color: #f7faff; }' +
  18478. 'td p{margin:0;padding:0;}', me.document);
  18479. var tableCopyList, isFullCol, isFullRow;
  18480. //注册del/backspace事件
  18481. me.addListener('keydown', function (cmd, evt) {
  18482. var me = this;
  18483. var keyCode = evt.keyCode || evt.which;
  18484. if (keyCode == 8) {
  18485. var ut = getUETableBySelected(me);
  18486. if (ut && ut.selectedTds.length) {
  18487. if (ut.isFullCol()) {
  18488. me.execCommand('deletecol')
  18489. } else if (ut.isFullRow()) {
  18490. me.execCommand('deleterow')
  18491. } else {
  18492. me.fireEvent('delcells');
  18493. }
  18494. domUtils.preventDefault(evt);
  18495. }
  18496. var caption = domUtils.findParentByTagName(me.selection.getStart(), 'caption', true),
  18497. range = me.selection.getRange();
  18498. if (range.collapsed && caption && isEmptyBlock(caption)) {
  18499. me.fireEvent('saveScene');
  18500. var table = caption.parentNode;
  18501. domUtils.remove(caption);
  18502. if (table) {
  18503. range.setStart(table.rows[0].cells[0], 0).setCursor(false, true);
  18504. }
  18505. me.fireEvent('saveScene');
  18506. }
  18507. }
  18508. if (keyCode == 46) {
  18509. ut = getUETableBySelected(me);
  18510. if (ut) {
  18511. me.fireEvent('saveScene');
  18512. for (var i = 0, ci; ci = ut.selectedTds[i++];) {
  18513. domUtils.fillNode(me.document, ci)
  18514. }
  18515. me.fireEvent('saveScene');
  18516. domUtils.preventDefault(evt);
  18517. }
  18518. }
  18519. if (keyCode == 13) {
  18520. var rng = me.selection.getRange(),
  18521. caption = domUtils.findParentByTagName(rng.startContainer, 'caption', true);
  18522. if (caption) {
  18523. var table = domUtils.findParentByTagName(caption, 'table');
  18524. if (!rng.collapsed) {
  18525. rng.deleteContents();
  18526. me.fireEvent('saveScene');
  18527. } else {
  18528. if (caption) {
  18529. rng.setStart(table.rows[0].cells[0], 0).setCursor(false, true);
  18530. }
  18531. }
  18532. domUtils.preventDefault(evt);
  18533. return;
  18534. }
  18535. if (rng.collapsed) {
  18536. var table = domUtils.findParentByTagName(rng.startContainer, 'table');
  18537. if (table) {
  18538. var cell = table.rows[0].cells[0],
  18539. start = domUtils.findParentByTagName(me.selection.getStart(), ['td', 'th'], true),
  18540. preNode = table.previousSibling;
  18541. if (cell === start && (!preNode || preNode.nodeType == 1 && preNode.tagName == 'TABLE' ) && domUtils.isStartInblock(rng)) {
  18542. var first = domUtils.findParent(me.selection.getStart(), function(n){return domUtils.isBlockElm(n)}, true);
  18543. if(first && ( /t(h|d)/i.test(first.tagName) || first === start.firstChild )){
  18544. me.execCommand('insertparagraphbeforetable');
  18545. domUtils.preventDefault(evt);
  18546. }
  18547. }
  18548. }
  18549. }
  18550. }
  18551. if ((evt.ctrlKey || evt.metaKey) && evt.keyCode == '67') {
  18552. tableCopyList = null;
  18553. var ut = getUETableBySelected(me);
  18554. if (ut) {
  18555. var tds = ut.selectedTds;
  18556. isFullCol = ut.isFullCol();
  18557. isFullRow = ut.isFullRow();
  18558. tableCopyList = [
  18559. [ut.cloneCell(tds[0],null,true)]
  18560. ];
  18561. for (var i = 1, ci; ci = tds[i]; i++) {
  18562. if (ci.parentNode !== tds[i - 1].parentNode) {
  18563. tableCopyList.push([ut.cloneCell(ci,null,true)]);
  18564. } else {
  18565. tableCopyList[tableCopyList.length - 1].push(ut.cloneCell(ci,null,true));
  18566. }
  18567. }
  18568. }
  18569. }
  18570. });
  18571. me.addListener("tablehasdeleted",function(){
  18572. toggleDraggableState(this, false, "", null);
  18573. if (dragButton)domUtils.remove(dragButton);
  18574. });
  18575. me.addListener('beforepaste', function (cmd, html) {
  18576. var me = this;
  18577. var rng = me.selection.getRange();
  18578. if (domUtils.findParentByTagName(rng.startContainer, 'caption', true)) {
  18579. var div = me.document.createElement("div");
  18580. div.innerHTML = html.html;
  18581. //trace:3729
  18582. html.html = div[browser.ie9below ? 'innerText' : 'textContent'];
  18583. return;
  18584. }
  18585. var table = getUETableBySelected(me);
  18586. if (tableCopyList) {
  18587. me.fireEvent('saveScene');
  18588. var rng = me.selection.getRange();
  18589. var td = domUtils.findParentByTagName(rng.startContainer, ['td', 'th'], true), tmpNode, preNode;
  18590. if (td) {
  18591. var ut = getUETable(td);
  18592. if (isFullRow) {
  18593. var rowIndex = ut.getCellInfo(td).rowIndex;
  18594. if (td.tagName == 'TH') {
  18595. rowIndex++;
  18596. }
  18597. for (var i = 0, ci; ci = tableCopyList[i++];) {
  18598. var tr = ut.insertRow(rowIndex++, "td");
  18599. for (var j = 0, cj; cj = ci[j]; j++) {
  18600. var cell = tr.cells[j];
  18601. if (!cell) {
  18602. cell = tr.insertCell(j)
  18603. }
  18604. cell.innerHTML = cj.innerHTML;
  18605. cj.getAttribute('width') && cell.setAttribute('width', cj.getAttribute('width'));
  18606. cj.getAttribute('vAlign') && cell.setAttribute('vAlign', cj.getAttribute('vAlign'));
  18607. cj.getAttribute('align') && cell.setAttribute('align', cj.getAttribute('align'));
  18608. cj.style.cssText && (cell.style.cssText = cj.style.cssText)
  18609. }
  18610. for (var j = 0, cj; cj = tr.cells[j]; j++) {
  18611. if (!ci[j])
  18612. break;
  18613. cj.innerHTML = ci[j].innerHTML;
  18614. ci[j].getAttribute('width') && cj.setAttribute('width', ci[j].getAttribute('width'));
  18615. ci[j].getAttribute('vAlign') && cj.setAttribute('vAlign', ci[j].getAttribute('vAlign'));
  18616. ci[j].getAttribute('align') && cj.setAttribute('align', ci[j].getAttribute('align'));
  18617. ci[j].style.cssText && (cj.style.cssText = ci[j].style.cssText)
  18618. }
  18619. }
  18620. } else {
  18621. if (isFullCol) {
  18622. cellInfo = ut.getCellInfo(td);
  18623. var maxColNum = 0;
  18624. for (var j = 0, ci = tableCopyList[0], cj; cj = ci[j++];) {
  18625. maxColNum += cj.colSpan || 1;
  18626. }
  18627. me.__hasEnterExecCommand = true;
  18628. for (i = 0; i < maxColNum; i++) {
  18629. me.execCommand('insertcol');
  18630. }
  18631. me.__hasEnterExecCommand = false;
  18632. td = ut.table.rows[0].cells[cellInfo.cellIndex];
  18633. if (td.tagName == 'TH') {
  18634. td = ut.table.rows[1].cells[cellInfo.cellIndex];
  18635. }
  18636. }
  18637. for (var i = 0, ci; ci = tableCopyList[i++];) {
  18638. tmpNode = td;
  18639. for (var j = 0, cj; cj = ci[j++];) {
  18640. if (td) {
  18641. td.innerHTML = cj.innerHTML;
  18642. //todo 定制处理
  18643. cj.getAttribute('width') && td.setAttribute('width', cj.getAttribute('width'));
  18644. cj.getAttribute('vAlign') && td.setAttribute('vAlign', cj.getAttribute('vAlign'));
  18645. cj.getAttribute('align') && td.setAttribute('align', cj.getAttribute('align'));
  18646. cj.style.cssText && (td.style.cssText = cj.style.cssText);
  18647. preNode = td;
  18648. td = td.nextSibling;
  18649. } else {
  18650. var cloneTd = cj.cloneNode(true);
  18651. domUtils.removeAttributes(cloneTd, ['class', 'rowSpan', 'colSpan']);
  18652. preNode.parentNode.appendChild(cloneTd)
  18653. }
  18654. }
  18655. td = ut.getNextCell(tmpNode, true, true);
  18656. if (!tableCopyList[i])
  18657. break;
  18658. if (!td) {
  18659. var cellInfo = ut.getCellInfo(tmpNode);
  18660. ut.table.insertRow(ut.table.rows.length);
  18661. ut.update();
  18662. td = ut.getVSideCell(tmpNode, true);
  18663. }
  18664. }
  18665. }
  18666. ut.update();
  18667. } else {
  18668. table = me.document.createElement('table');
  18669. for (var i = 0, ci; ci = tableCopyList[i++];) {
  18670. var tr = table.insertRow(table.rows.length);
  18671. for (var j = 0, cj; cj = ci[j++];) {
  18672. cloneTd = UT.cloneCell(cj,null,true);
  18673. domUtils.removeAttributes(cloneTd, ['class']);
  18674. tr.appendChild(cloneTd)
  18675. }
  18676. if (j == 2 && cloneTd.rowSpan > 1) {
  18677. cloneTd.rowSpan = 1;
  18678. }
  18679. }
  18680. var defaultValue = getDefaultValue(me),
  18681. width = me.body.offsetWidth -
  18682. (needIEHack ? parseInt(domUtils.getComputedStyle(me.body, 'margin-left'), 10) * 2 : 0) - defaultValue.tableBorder * 2 - (me.options.offsetWidth || 0);
  18683. me.execCommand('insertHTML', '<table ' +
  18684. ( isFullCol && isFullRow ? 'width="' + width + '"' : '') +
  18685. '>' + table.innerHTML.replace(/>\s*</g, '><').replace(/\bth\b/gi, "td") + '</table>')
  18686. }
  18687. me.fireEvent('contentchange');
  18688. me.fireEvent('saveScene');
  18689. html.html = '';
  18690. return true;
  18691. } else {
  18692. var div = me.document.createElement("div"), tables;
  18693. div.innerHTML = html.html;
  18694. tables = div.getElementsByTagName("table");
  18695. if (domUtils.findParentByTagName(me.selection.getStart(), 'table')) {
  18696. utils.each(tables, function (t) {
  18697. domUtils.remove(t)
  18698. });
  18699. if (domUtils.findParentByTagName(me.selection.getStart(), 'caption', true)) {
  18700. div.innerHTML = div[browser.ie ? 'innerText' : 'textContent'];
  18701. }
  18702. } else {
  18703. utils.each(tables, function (table) {
  18704. removeStyleSize(table, true);
  18705. domUtils.removeAttributes(table, ['style', 'border']);
  18706. utils.each(domUtils.getElementsByTagName(table, "td"), function (td) {
  18707. if (isEmptyBlock(td)) {
  18708. domUtils.fillNode(me.document, td);
  18709. }
  18710. removeStyleSize(td, true);
  18711. // domUtils.removeAttributes(td, ['style'])
  18712. });
  18713. });
  18714. }
  18715. html.html = div.innerHTML;
  18716. }
  18717. });
  18718. me.addListener('afterpaste', function () {
  18719. utils.each(domUtils.getElementsByTagName(me.body, "table"), function (table) {
  18720. if (table.offsetWidth > me.body.offsetWidth) {
  18721. var defaultValue = getDefaultValue(me, table);
  18722. table.style.width = me.body.offsetWidth - (needIEHack ? parseInt(domUtils.getComputedStyle(me.body, 'margin-left'), 10) * 2 : 0) - defaultValue.tableBorder * 2 - (me.options.offsetWidth || 0) + 'px'
  18723. }
  18724. })
  18725. });
  18726. me.addListener('blur', function () {
  18727. tableCopyList = null;
  18728. });
  18729. var timer;
  18730. me.addListener('keydown', function () {
  18731. clearTimeout(timer);
  18732. timer = setTimeout(function () {
  18733. var rng = me.selection.getRange(),
  18734. cell = domUtils.findParentByTagName(rng.startContainer, ['th', 'td'], true);
  18735. if (cell) {
  18736. var table = cell.parentNode.parentNode.parentNode;
  18737. if (table.offsetWidth > table.getAttribute("width")) {
  18738. cell.style.wordBreak = "break-all";
  18739. }
  18740. }
  18741. }, 100);
  18742. });
  18743. me.addListener("selectionchange", function () {
  18744. toggleDraggableState(me, false, "", null);
  18745. });
  18746. //内容变化时触发索引更新
  18747. //todo 可否考虑标记检测,如果不涉及表格的变化就不进行索引重建和更新
  18748. me.addListener("contentchange", function () {
  18749. var me = this;
  18750. //尽可能排除一些不需要更新的状况
  18751. hideDragLine(me);
  18752. if (getUETableBySelected(me))return;
  18753. var rng = me.selection.getRange();
  18754. var start = rng.startContainer;
  18755. start = domUtils.findParentByTagName(start, ['td', 'th'], true);
  18756. utils.each(domUtils.getElementsByTagName(me.document, 'table'), function (table) {
  18757. if (me.fireEvent("excludetable", table) === true) return;
  18758. table.ueTable = new UT(table);
  18759. //trace:3742
  18760. // utils.each(domUtils.getElementsByTagName(me.document, 'td'), function (td) {
  18761. //
  18762. // if (domUtils.isEmptyBlock(td) && td !== start) {
  18763. // domUtils.fillNode(me.document, td);
  18764. // if (browser.ie && browser.version == 6) {
  18765. // td.innerHTML = '&nbsp;'
  18766. // }
  18767. // }
  18768. // });
  18769. // utils.each(domUtils.getElementsByTagName(me.document, 'th'), function (th) {
  18770. // if (domUtils.isEmptyBlock(th) && th !== start) {
  18771. // domUtils.fillNode(me.document, th);
  18772. // if (browser.ie && browser.version == 6) {
  18773. // th.innerHTML = '&nbsp;'
  18774. // }
  18775. // }
  18776. // });
  18777. table.onmouseover = function () {
  18778. me.fireEvent('tablemouseover', table);
  18779. };
  18780. table.onmousemove = function () {
  18781. me.fireEvent('tablemousemove', table);
  18782. me.options.tableDragable && toggleDragButton(true, this, me);
  18783. utils.defer(function(){
  18784. me.fireEvent('contentchange',50)
  18785. },true)
  18786. };
  18787. table.onmouseout = function () {
  18788. me.fireEvent('tablemouseout', table);
  18789. toggleDraggableState(me, false, "", null);
  18790. hideDragLine(me);
  18791. };
  18792. table.onclick = function (evt) {
  18793. evt = me.window.event || evt;
  18794. var target = getParentTdOrTh(evt.target || evt.srcElement);
  18795. if (!target)return;
  18796. var ut = getUETable(target),
  18797. table = ut.table,
  18798. cellInfo = ut.getCellInfo(target),
  18799. cellsRange,
  18800. rng = me.selection.getRange();
  18801. // if ("topLeft" == inPosition(table, mouseCoords(evt))) {
  18802. // cellsRange = ut.getCellsRange(ut.table.rows[0].cells[0], ut.getLastCell());
  18803. // ut.setSelected(cellsRange);
  18804. // return;
  18805. // }
  18806. // if ("bottomRight" == inPosition(table, mouseCoords(evt))) {
  18807. //
  18808. // return;
  18809. // }
  18810. if (inTableSide(table, target, evt, true)) {
  18811. var endTdCol = ut.getCell(ut.indexTable[ut.rowsNum - 1][cellInfo.colIndex].rowIndex, ut.indexTable[ut.rowsNum - 1][cellInfo.colIndex].cellIndex);
  18812. if (evt.shiftKey && ut.selectedTds.length) {
  18813. if (ut.selectedTds[0] !== endTdCol) {
  18814. cellsRange = ut.getCellsRange(ut.selectedTds[0], endTdCol);
  18815. ut.setSelected(cellsRange);
  18816. } else {
  18817. rng && rng.selectNodeContents(endTdCol).select();
  18818. }
  18819. } else {
  18820. if (target !== endTdCol) {
  18821. cellsRange = ut.getCellsRange(target, endTdCol);
  18822. ut.setSelected(cellsRange);
  18823. } else {
  18824. rng && rng.selectNodeContents(endTdCol).select();
  18825. }
  18826. }
  18827. return;
  18828. }
  18829. if (inTableSide(table, target, evt)) {
  18830. var endTdRow = ut.getCell(ut.indexTable[cellInfo.rowIndex][ut.colsNum - 1].rowIndex, ut.indexTable[cellInfo.rowIndex][ut.colsNum - 1].cellIndex);
  18831. if (evt.shiftKey && ut.selectedTds.length) {
  18832. if (ut.selectedTds[0] !== endTdRow) {
  18833. cellsRange = ut.getCellsRange(ut.selectedTds[0], endTdRow);
  18834. ut.setSelected(cellsRange);
  18835. } else {
  18836. rng && rng.selectNodeContents(endTdRow).select();
  18837. }
  18838. } else {
  18839. if (target !== endTdRow) {
  18840. cellsRange = ut.getCellsRange(target, endTdRow);
  18841. ut.setSelected(cellsRange);
  18842. } else {
  18843. rng && rng.selectNodeContents(endTdRow).select();
  18844. }
  18845. }
  18846. }
  18847. };
  18848. });
  18849. switchBorderColor(me, true);
  18850. });
  18851. domUtils.on(me.document, "mousemove", mouseMoveEvent);
  18852. domUtils.on(me.document, "mouseout", function (evt) {
  18853. var target = evt.target || evt.srcElement;
  18854. if (target.tagName == "TABLE") {
  18855. toggleDraggableState(me, false, "", null);
  18856. }
  18857. });
  18858. /**
  18859. * 表格隔行变色
  18860. */
  18861. me.addListener("interlacetable",function(type,table,classList){
  18862. if(!table) return;
  18863. var me = this,
  18864. rows = table.rows,
  18865. len = rows.length,
  18866. getClass = function(list,index,repeat){
  18867. return list[index] ? list[index] : repeat ? list[index % list.length]: "";
  18868. };
  18869. for(var i = 0;i<len;i++){
  18870. rows[i].className = getClass( classList|| me.options.classList,i,true);
  18871. }
  18872. });
  18873. me.addListener("uninterlacetable",function(type,table){
  18874. if(!table) return;
  18875. var me = this,
  18876. rows = table.rows,
  18877. classList = me.options.classList,
  18878. len = rows.length;
  18879. for(var i = 0;i<len;i++){
  18880. domUtils.removeClasses( rows[i], classList );
  18881. }
  18882. });
  18883. me.addListener("mousedown", mouseDownEvent);
  18884. me.addListener("mouseup", mouseUpEvent);
  18885. //拖动的时候触发mouseup
  18886. domUtils.on( me.body, 'dragstart', function( evt ){
  18887. mouseUpEvent.call( me, 'dragstart', evt );
  18888. });
  18889. me.addOutputRule(function(root){
  18890. utils.each(root.getNodesByTagName('div'),function(n){
  18891. if (n.getAttr('id') == 'ue_tableDragLine') {
  18892. n.parentNode.removeChild(n);
  18893. }
  18894. });
  18895. });
  18896. var currentRowIndex = 0;
  18897. me.addListener("mousedown", function () {
  18898. currentRowIndex = 0;
  18899. });
  18900. me.addListener('tabkeydown', function () {
  18901. var range = this.selection.getRange(),
  18902. common = range.getCommonAncestor(true, true),
  18903. table = domUtils.findParentByTagName(common, 'table');
  18904. if (table) {
  18905. if (domUtils.findParentByTagName(common, 'caption', true)) {
  18906. var cell = domUtils.getElementsByTagName(table, 'th td');
  18907. if (cell && cell.length) {
  18908. range.setStart(cell[0], 0).setCursor(false, true)
  18909. }
  18910. } else {
  18911. var cell = domUtils.findParentByTagName(common, ['td', 'th'], true),
  18912. ua = getUETable(cell);
  18913. currentRowIndex = cell.rowSpan > 1 ? currentRowIndex : ua.getCellInfo(cell).rowIndex;
  18914. var nextCell = ua.getTabNextCell(cell, currentRowIndex);
  18915. if (nextCell) {
  18916. if (isEmptyBlock(nextCell)) {
  18917. range.setStart(nextCell, 0).setCursor(false, true)
  18918. } else {
  18919. range.selectNodeContents(nextCell).select()
  18920. }
  18921. } else {
  18922. me.fireEvent('saveScene');
  18923. me.__hasEnterExecCommand = true;
  18924. this.execCommand('insertrownext');
  18925. me.__hasEnterExecCommand = false;
  18926. range = this.selection.getRange();
  18927. range.setStart(table.rows[table.rows.length - 1].cells[0], 0).setCursor();
  18928. me.fireEvent('saveScene');
  18929. }
  18930. }
  18931. return true;
  18932. }
  18933. });
  18934. browser.ie && me.addListener('selectionchange', function () {
  18935. toggleDraggableState(this, false, "", null);
  18936. });
  18937. me.addListener("keydown", function (type, evt) {
  18938. var me = this;
  18939. //处理在表格的最后一个输入tab产生新的表格
  18940. var keyCode = evt.keyCode || evt.which;
  18941. if (keyCode == 8 || keyCode == 46) {
  18942. return;
  18943. }
  18944. var notCtrlKey = !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey;
  18945. notCtrlKey && removeSelectedClass(domUtils.getElementsByTagName(me.body, "td"));
  18946. var ut = getUETableBySelected(me);
  18947. if (!ut) return;
  18948. notCtrlKey && ut.clearSelected();
  18949. });
  18950. me.addListener("beforegetcontent", function () {
  18951. switchBorderColor(this, false);
  18952. browser.ie && utils.each(this.document.getElementsByTagName('caption'), function (ci) {
  18953. if (domUtils.isEmptyNode(ci)) {
  18954. ci.innerHTML = '&nbsp;'
  18955. }
  18956. });
  18957. });
  18958. me.addListener("aftergetcontent", function () {
  18959. switchBorderColor(this, true);
  18960. });
  18961. me.addListener("getAllHtml", function () {
  18962. removeSelectedClass(me.document.getElementsByTagName("td"));
  18963. });
  18964. //修正全屏状态下插入的表格宽度在非全屏状态下撑开编辑器的情况
  18965. me.addListener("fullscreenchanged", function (type, fullscreen) {
  18966. if (!fullscreen) {
  18967. var ratio = this.body.offsetWidth / document.body.offsetWidth,
  18968. tables = domUtils.getElementsByTagName(this.body, "table");
  18969. utils.each(tables, function (table) {
  18970. if (table.offsetWidth < me.body.offsetWidth) return false;
  18971. var tds = domUtils.getElementsByTagName(table, "td"),
  18972. backWidths = [];
  18973. utils.each(tds, function (td) {
  18974. backWidths.push(td.offsetWidth);
  18975. });
  18976. for (var i = 0, td; td = tds[i]; i++) {
  18977. td.setAttribute("width", Math.floor(backWidths[i] * ratio));
  18978. }
  18979. table.setAttribute("width", Math.floor(getTableWidth(me, needIEHack, getDefaultValue(me))))
  18980. });
  18981. }
  18982. });
  18983. //重写execCommand命令,用于处理框选时的处理
  18984. var oldExecCommand = me.execCommand;
  18985. me.execCommand = function (cmd, datatat) {
  18986. var me = this,
  18987. args = arguments;
  18988. cmd = cmd.toLowerCase();
  18989. var ut = getUETableBySelected(me), tds,
  18990. range = new dom.Range(me.document),
  18991. cmdFun = me.commands[cmd] || UE.commands[cmd],
  18992. result;
  18993. if (!cmdFun) return;
  18994. if (ut && !commands[cmd] && !cmdFun.notNeedUndo && !me.__hasEnterExecCommand) {
  18995. me.__hasEnterExecCommand = true;
  18996. me.fireEvent("beforeexeccommand", cmd);
  18997. tds = ut.selectedTds;
  18998. var lastState = -2, lastValue = -2, value, state;
  18999. for (var i = 0, td; td = tds[i]; i++) {
  19000. if (isEmptyBlock(td)) {
  19001. range.setStart(td, 0).setCursor(false, true)
  19002. } else {
  19003. range.selectNode(td).select(true);
  19004. }
  19005. state = me.queryCommandState(cmd);
  19006. value = me.queryCommandValue(cmd);
  19007. if (state != -1) {
  19008. if (lastState !== state || lastValue !== value) {
  19009. me._ignoreContentChange = true;
  19010. result = oldExecCommand.apply(me, arguments);
  19011. me._ignoreContentChange = false;
  19012. }
  19013. lastState = me.queryCommandState(cmd);
  19014. lastValue = me.queryCommandValue(cmd);
  19015. if (domUtils.isEmptyBlock(td)) {
  19016. domUtils.fillNode(me.document, td)
  19017. }
  19018. }
  19019. }
  19020. range.setStart(tds[0], 0).shrinkBoundary(true).setCursor(false, true);
  19021. me.fireEvent('contentchange');
  19022. me.fireEvent("afterexeccommand", cmd);
  19023. me.__hasEnterExecCommand = false;
  19024. me._selectionChange();
  19025. } else {
  19026. result = oldExecCommand.apply(me, arguments);
  19027. }
  19028. return result;
  19029. };
  19030. });
  19031. /**
  19032. * 删除obj的宽高style,改成属性宽高
  19033. * @param obj
  19034. * @param replaceToProperty
  19035. */
  19036. function removeStyleSize(obj, replaceToProperty) {
  19037. removeStyle(obj, "width", true);
  19038. removeStyle(obj, "height", true);
  19039. }
  19040. function removeStyle(obj, styleName, replaceToProperty) {
  19041. if (obj.style[styleName]) {
  19042. replaceToProperty && obj.setAttribute(styleName, parseInt(obj.style[styleName], 10));
  19043. obj.style[styleName] = "";
  19044. }
  19045. }
  19046. function getParentTdOrTh(ele) {
  19047. if (ele.tagName == "TD" || ele.tagName == "TH") return ele;
  19048. var td;
  19049. if (td = domUtils.findParentByTagName(ele, "td", true) || domUtils.findParentByTagName(ele, "th", true)) return td;
  19050. return null;
  19051. }
  19052. function isEmptyBlock(node) {
  19053. var reg = new RegExp(domUtils.fillChar, 'g');
  19054. if (node[browser.ie ? 'innerText' : 'textContent'].replace(/^\s*$/, '').replace(reg, '').length > 0) {
  19055. return 0;
  19056. }
  19057. for (var n in dtd.$isNotEmpty) {
  19058. if (node.getElementsByTagName(n).length) {
  19059. return 0;
  19060. }
  19061. }
  19062. return 1;
  19063. }
  19064. function mouseCoords(evt) {
  19065. if (evt.pageX || evt.pageY) {
  19066. return { x:evt.pageX, y:evt.pageY };
  19067. }
  19068. return {
  19069. x:evt.clientX + me.document.body.scrollLeft - me.document.body.clientLeft,
  19070. y:evt.clientY + me.document.body.scrollTop - me.document.body.clientTop
  19071. };
  19072. }
  19073. function mouseMoveEvent(evt) {
  19074. if( isEditorDisabled() ) {
  19075. return;
  19076. }
  19077. try {
  19078. //普通状态下鼠标移动
  19079. var target = getParentTdOrTh(evt.target || evt.srcElement),
  19080. pos;
  19081. //区分用户的行为是拖动还是双击
  19082. if( isInResizeBuffer ) {
  19083. me.body.style.webkitUserSelect = 'none';
  19084. if( Math.abs( userActionStatus.x - evt.clientX ) > offsetOfTableCell || Math.abs( userActionStatus.y - evt.clientY ) > offsetOfTableCell ) {
  19085. clearTableDragTimer();
  19086. isInResizeBuffer = false;
  19087. singleClickState = 0;
  19088. //drag action
  19089. tableBorderDrag(evt);
  19090. }
  19091. }
  19092. //修改单元格大小时的鼠标移动
  19093. if (onDrag && dragTd) {
  19094. singleClickState = 0;
  19095. me.body.style.webkitUserSelect = 'none';
  19096. me.selection.getNative()[browser.ie9below ? 'empty' : 'removeAllRanges']();
  19097. pos = mouseCoords(evt);
  19098. toggleDraggableState(me, true, onDrag, pos, target);
  19099. if (onDrag == "h") {
  19100. dragLine.style.left = getPermissionX(dragTd, evt) + "px";
  19101. } else if (onDrag == "v") {
  19102. dragLine.style.top = getPermissionY(dragTd, evt) + "px";
  19103. }
  19104. return;
  19105. }
  19106. //当鼠标处于table上时,修改移动过程中的光标状态
  19107. if (target) {
  19108. //针对使用table作为容器的组件不触发拖拽效果
  19109. if (me.fireEvent('excludetable', target) === true)
  19110. return;
  19111. pos = mouseCoords(evt);
  19112. var state = getRelation(target, pos),
  19113. table = domUtils.findParentByTagName(target, "table", true);
  19114. if (inTableSide(table, target, evt, true)) {
  19115. if (me.fireEvent("excludetable", table) === true) return;
  19116. me.body.style.cursor = "url(" + me.options.cursorpath + "h.png),pointer";
  19117. } else if (inTableSide(table, target, evt)) {
  19118. if (me.fireEvent("excludetable", table) === true) return;
  19119. me.body.style.cursor = "url(" + me.options.cursorpath + "v.png),pointer";
  19120. } else {
  19121. me.body.style.cursor = "text";
  19122. var curCell = target;
  19123. if (/\d/.test(state)) {
  19124. state = state.replace(/\d/, '');
  19125. target = getUETable(target).getPreviewCell(target, state == "v");
  19126. }
  19127. //位于第一行的顶部或者第一列的左边时不可拖动
  19128. toggleDraggableState(me, target ? !!state : false, target ? state : '', pos, target);
  19129. }
  19130. } else {
  19131. toggleDragButton(false, table, me);
  19132. }
  19133. } catch (e) {
  19134. showError(e);
  19135. }
  19136. }
  19137. var dragButtonTimer;
  19138. function toggleDragButton(show, table, editor) {
  19139. if (!show) {
  19140. if (dragOver)return;
  19141. dragButtonTimer = setTimeout(function () {
  19142. !dragOver && dragButton && dragButton.parentNode && dragButton.parentNode.removeChild(dragButton);
  19143. }, 2000);
  19144. } else {
  19145. createDragButton(table, editor);
  19146. }
  19147. }
  19148. function createDragButton(table, editor) {
  19149. var pos = domUtils.getXY(table),
  19150. doc = table.ownerDocument;
  19151. if (dragButton && dragButton.parentNode)return dragButton;
  19152. dragButton = doc.createElement("div");
  19153. dragButton.contentEditable = false;
  19154. dragButton.innerHTML = "";
  19155. dragButton.style.cssText = "width:15px;height:15px;background-image:url(" + editor.options.UEDITOR_HOME_URL + "dialogs/table/dragicon.png);position: absolute;cursor:move;top:" + (pos.y - 15) + "px;left:" + (pos.x) + "px;";
  19156. domUtils.unSelectable(dragButton);
  19157. dragButton.onmouseover = function (evt) {
  19158. dragOver = true;
  19159. };
  19160. dragButton.onmouseout = function (evt) {
  19161. dragOver = false;
  19162. };
  19163. domUtils.on(dragButton, 'click', function (type, evt) {
  19164. doClick(evt, this);
  19165. });
  19166. domUtils.on(dragButton, 'dblclick', function (type, evt) {
  19167. doDblClick(evt);
  19168. });
  19169. domUtils.on(dragButton, 'dragstart', function (type, evt) {
  19170. domUtils.preventDefault(evt);
  19171. });
  19172. var timer;
  19173. function doClick(evt, button) {
  19174. // 部分浏览器下需要清理
  19175. clearTimeout(timer);
  19176. timer = setTimeout(function () {
  19177. editor.fireEvent("tableClicked", table, button);
  19178. }, 300);
  19179. }
  19180. function doDblClick(evt) {
  19181. clearTimeout(timer);
  19182. var ut = getUETable(table),
  19183. start = table.rows[0].cells[0],
  19184. end = ut.getLastCell(),
  19185. range = ut.getCellsRange(start, end);
  19186. editor.selection.getRange().setStart(start, 0).setCursor(false, true);
  19187. ut.setSelected(range);
  19188. }
  19189. doc.body.appendChild(dragButton);
  19190. }
  19191. // function inPosition(table, pos) {
  19192. // var tablePos = domUtils.getXY(table),
  19193. // width = table.offsetWidth,
  19194. // height = table.offsetHeight;
  19195. // if (pos.x - tablePos.x < 5 && pos.y - tablePos.y < 5) {
  19196. // return "topLeft";
  19197. // } else if (tablePos.x + width - pos.x < 5 && tablePos.y + height - pos.y < 5) {
  19198. // return "bottomRight";
  19199. // }
  19200. // }
  19201. function inTableSide(table, cell, evt, top) {
  19202. var pos = mouseCoords(evt),
  19203. state = getRelation(cell, pos);
  19204. if (top) {
  19205. var caption = table.getElementsByTagName("caption")[0],
  19206. capHeight = caption ? caption.offsetHeight : 0;
  19207. return (state == "v1") && ((pos.y - domUtils.getXY(table).y - capHeight) < 8);
  19208. } else {
  19209. return (state == "h1") && ((pos.x - domUtils.getXY(table).x) < 8);
  19210. }
  19211. }
  19212. /**
  19213. * 获取拖动时允许的X轴坐标
  19214. * @param dragTd
  19215. * @param evt
  19216. */
  19217. function getPermissionX(dragTd, evt) {
  19218. var ut = getUETable(dragTd);
  19219. if (ut) {
  19220. var preTd = ut.getSameEndPosCells(dragTd, "x")[0],
  19221. nextTd = ut.getSameStartPosXCells(dragTd)[0],
  19222. mouseX = mouseCoords(evt).x,
  19223. left = (preTd ? domUtils.getXY(preTd).x : domUtils.getXY(ut.table).x) + 20 ,
  19224. right = nextTd ? domUtils.getXY(nextTd).x + nextTd.offsetWidth - 20 : (me.body.offsetWidth + 5 || parseInt(domUtils.getComputedStyle(me.body, "width"), 10));
  19225. left += cellMinWidth;
  19226. right -= cellMinWidth;
  19227. return mouseX < left ? left : mouseX > right ? right : mouseX;
  19228. }
  19229. }
  19230. /**
  19231. * 获取拖动时允许的Y轴坐标
  19232. */
  19233. function getPermissionY(dragTd, evt) {
  19234. try {
  19235. var top = domUtils.getXY(dragTd).y,
  19236. mousePosY = mouseCoords(evt).y;
  19237. return mousePosY < top ? top : mousePosY;
  19238. } catch (e) {
  19239. showError(e);
  19240. }
  19241. }
  19242. /**
  19243. * 移动状态切换
  19244. */
  19245. function toggleDraggableState(editor, draggable, dir, mousePos, cell) {
  19246. try {
  19247. editor.body.style.cursor = dir == "h" ? "col-resize" : dir == "v" ? "row-resize" : "text";
  19248. if (browser.ie) {
  19249. if (dir && !mousedown && !getUETableBySelected(editor)) {
  19250. getDragLine(editor, editor.document);
  19251. showDragLineAt(dir, cell);
  19252. } else {
  19253. hideDragLine(editor)
  19254. }
  19255. }
  19256. onBorder = draggable;
  19257. } catch (e) {
  19258. showError(e);
  19259. }
  19260. }
  19261. /**
  19262. * 获取与UETable相关的resize line
  19263. * @param uetable UETable对象
  19264. */
  19265. function getResizeLineByUETable() {
  19266. var lineId = '_UETableResizeLine',
  19267. line = this.document.getElementById( lineId );
  19268. if( !line ) {
  19269. line = this.document.createElement("div");
  19270. line.id = lineId;
  19271. line.contnetEditable = false;
  19272. line.setAttribute("unselectable", "on");
  19273. var styles = {
  19274. width: 2*cellBorderWidth + 1 + 'px',
  19275. position: 'absolute',
  19276. 'z-index': 100000,
  19277. cursor: 'col-resize',
  19278. background: 'red',
  19279. display: 'none'
  19280. };
  19281. //切换状态
  19282. line.onmouseout = function(){
  19283. this.style.display = 'none';
  19284. };
  19285. utils.extend( line.style, styles );
  19286. this.document.body.appendChild( line );
  19287. }
  19288. return line;
  19289. }
  19290. /**
  19291. * 更新resize-line
  19292. */
  19293. function updateResizeLine( cell, uetable ) {
  19294. var line = getResizeLineByUETable.call( this ),
  19295. table = uetable.table,
  19296. styles = {
  19297. top: domUtils.getXY( table ).y + 'px',
  19298. left: domUtils.getXY( cell).x + cell.offsetWidth - cellBorderWidth + 'px',
  19299. display: 'block',
  19300. height: table.offsetHeight + 'px'
  19301. };
  19302. utils.extend( line.style, styles );
  19303. }
  19304. /**
  19305. * 显示resize-line
  19306. */
  19307. function showResizeLine( cell ) {
  19308. var uetable = getUETable( cell );
  19309. updateResizeLine.call( this, cell, uetable );
  19310. }
  19311. /**
  19312. * 获取鼠标与当前单元格的相对位置
  19313. * @param ele
  19314. * @param mousePos
  19315. */
  19316. function getRelation(ele, mousePos) {
  19317. var elePos = domUtils.getXY(ele);
  19318. if( !elePos ) {
  19319. return '';
  19320. }
  19321. if (elePos.x + ele.offsetWidth - mousePos.x < cellBorderWidth) {
  19322. return "h";
  19323. }
  19324. if (mousePos.x - elePos.x < cellBorderWidth) {
  19325. return 'h1'
  19326. }
  19327. if (elePos.y + ele.offsetHeight - mousePos.y < cellBorderWidth) {
  19328. return "v";
  19329. }
  19330. if (mousePos.y - elePos.y < cellBorderWidth) {
  19331. return 'v1'
  19332. }
  19333. return '';
  19334. }
  19335. function mouseDownEvent(type, evt) {
  19336. if( isEditorDisabled() ) {
  19337. return ;
  19338. }
  19339. userActionStatus = {
  19340. x: evt.clientX,
  19341. y: evt.clientY
  19342. };
  19343. //右键菜单单独处理
  19344. if (evt.button == 2) {
  19345. var ut = getUETableBySelected(me),
  19346. flag = false;
  19347. if (ut) {
  19348. var td = getTargetTd(me, evt);
  19349. utils.each(ut.selectedTds, function (ti) {
  19350. if (ti === td) {
  19351. flag = true;
  19352. }
  19353. });
  19354. if (!flag) {
  19355. removeSelectedClass(domUtils.getElementsByTagName(me.body, "th td"));
  19356. ut.clearSelected()
  19357. } else {
  19358. td = ut.selectedTds[0];
  19359. setTimeout(function () {
  19360. me.selection.getRange().setStart(td, 0).setCursor(false, true);
  19361. }, 0);
  19362. }
  19363. }
  19364. } else {
  19365. tableClickHander( evt );
  19366. }
  19367. }
  19368. //清除表格的计时器
  19369. function clearTableTimer() {
  19370. tabTimer && clearTimeout( tabTimer );
  19371. tabTimer = null;
  19372. }
  19373. //双击收缩
  19374. function tableDbclickHandler(evt) {
  19375. singleClickState = 0;
  19376. evt = evt || me.window.event;
  19377. var target = getParentTdOrTh(evt.target || evt.srcElement);
  19378. if (target) {
  19379. var h;
  19380. if (h = getRelation(target, mouseCoords(evt))) {
  19381. hideDragLine( me );
  19382. if (h == 'h1') {
  19383. h = 'h';
  19384. if (inTableSide(domUtils.findParentByTagName(target, "table"), target, evt)) {
  19385. me.execCommand('adaptbywindow');
  19386. } else {
  19387. target = getUETable(target).getPreviewCell(target);
  19388. if (target) {
  19389. var rng = me.selection.getRange();
  19390. rng.selectNodeContents(target).setCursor(true, true)
  19391. }
  19392. }
  19393. }
  19394. if (h == 'h') {
  19395. var ut = getUETable(target),
  19396. table = ut.table,
  19397. cells = getCellsByMoveBorder( target, table, true );
  19398. cells = extractArray( cells, 'left' );
  19399. ut.width = ut.offsetWidth;
  19400. var oldWidth = [],
  19401. newWidth = [];
  19402. utils.each( cells, function( cell ){
  19403. oldWidth.push( cell.offsetWidth );
  19404. } );
  19405. utils.each( cells, function( cell ){
  19406. cell.removeAttribute("width");
  19407. } );
  19408. window.setTimeout( function(){
  19409. //是否允许改变
  19410. var changeable = true;
  19411. utils.each( cells, function( cell, index ){
  19412. var width = cell.offsetWidth;
  19413. if( width > oldWidth[index] ) {
  19414. changeable = false;
  19415. return false;
  19416. }
  19417. newWidth.push( width );
  19418. } );
  19419. var change = changeable ? newWidth : oldWidth;
  19420. utils.each( cells, function( cell, index ){
  19421. cell.width = change[index] - getTabcellSpace();
  19422. } );
  19423. }, 0 );
  19424. // minWidth -= cellMinWidth;
  19425. //
  19426. // table.removeAttribute("width");
  19427. // utils.each(cells, function (cell) {
  19428. // cell.style.width = "";
  19429. // cell.width -= minWidth;
  19430. // });
  19431. }
  19432. }
  19433. }
  19434. }
  19435. function tableClickHander( evt ) {
  19436. removeSelectedClass(domUtils.getElementsByTagName(me.body, "td th"));
  19437. //trace:3113
  19438. //选中单元格,点击table外部,不会清掉table上挂的ueTable,会引起getUETableBySelected方法返回值
  19439. utils.each(me.document.getElementsByTagName('table'), function (t) {
  19440. t.ueTable = null;
  19441. });
  19442. startTd = getTargetTd(me, evt);
  19443. if( !startTd ) return;
  19444. var table = domUtils.findParentByTagName(startTd, "table", true);
  19445. ut = getUETable(table);
  19446. ut && ut.clearSelected();
  19447. //判断当前鼠标状态
  19448. if (!onBorder) {
  19449. me.document.body.style.webkitUserSelect = '';
  19450. mousedown = true;
  19451. me.addListener('mouseover', mouseOverEvent);
  19452. } else {
  19453. //边框上的动作处理
  19454. borderActionHandler( evt );
  19455. }
  19456. }
  19457. //处理表格边框上的动作, 这里做延时处理,避免两种动作互相影响
  19458. function borderActionHandler( evt ) {
  19459. if ( browser.ie ) {
  19460. evt = reconstruct(evt );
  19461. }
  19462. clearTableDragTimer();
  19463. //是否正在等待resize的缓冲中
  19464. isInResizeBuffer = true;
  19465. tableDragTimer = setTimeout(function(){
  19466. tableBorderDrag( evt );
  19467. }, dblclickTime);
  19468. }
  19469. function extractArray( originArr, key ) {
  19470. var result = [],
  19471. tmp = null;
  19472. for( var i = 0, len = originArr.length; i<len; i++ ) {
  19473. tmp = originArr[ i ][ key ];
  19474. if( tmp ) {
  19475. result.push( tmp );
  19476. }
  19477. }
  19478. return result;
  19479. }
  19480. function clearTableDragTimer() {
  19481. tableDragTimer && clearTimeout(tableDragTimer);
  19482. tableDragTimer = null;
  19483. }
  19484. function reconstruct( obj ) {
  19485. var attrs = ['pageX', 'pageY', 'clientX', 'clientY', 'srcElement', 'target'],
  19486. newObj = {};
  19487. if( obj ) {
  19488. for( var i = 0, key, val; key = attrs[i]; i++ ) {
  19489. val=obj[ key ];
  19490. val && (newObj[ key ] = val);
  19491. }
  19492. }
  19493. return newObj;
  19494. }
  19495. //边框拖动
  19496. function tableBorderDrag( evt ) {
  19497. isInResizeBuffer = false;
  19498. startTd = evt.target || evt.srcElement;
  19499. if( !startTd ) return;
  19500. var state = getRelation(startTd, mouseCoords(evt));
  19501. if (/\d/.test(state)) {
  19502. state = state.replace(/\d/, '');
  19503. startTd = getUETable(startTd).getPreviewCell(startTd, state == 'v');
  19504. }
  19505. hideDragLine(me);
  19506. getDragLine(me, me.document);
  19507. me.fireEvent('saveScene');
  19508. showDragLineAt(state, startTd);
  19509. mousedown = true;
  19510. //拖动开始
  19511. onDrag = state;
  19512. dragTd = startTd;
  19513. }
  19514. function mouseUpEvent(type, evt) {
  19515. if( isEditorDisabled() ) {
  19516. return ;
  19517. }
  19518. clearTableDragTimer();
  19519. isInResizeBuffer = false;
  19520. if( onBorder ) {
  19521. singleClickState = ++singleClickState % 3;
  19522. userActionStatus = {
  19523. x: evt.clientX,
  19524. y: evt.clientY
  19525. };
  19526. tableResizeTimer = setTimeout(function(){
  19527. singleClickState > 0 && singleClickState--;
  19528. }, dblclickTime );
  19529. if( singleClickState === 2 ) {
  19530. singleClickState = 0;
  19531. tableDbclickHandler(evt);
  19532. return;
  19533. }
  19534. }
  19535. if (evt.button == 2)return;
  19536. var me = this;
  19537. //清除表格上原生跨选问题
  19538. var range = me.selection.getRange(),
  19539. start = domUtils.findParentByTagName(range.startContainer, 'table', true),
  19540. end = domUtils.findParentByTagName(range.endContainer, 'table', true);
  19541. if (start || end) {
  19542. if (start === end) {
  19543. start = domUtils.findParentByTagName(range.startContainer, ['td', 'th', 'caption'], true);
  19544. end = domUtils.findParentByTagName(range.endContainer, ['td', 'th', 'caption'], true);
  19545. if (start !== end) {
  19546. me.selection.clearRange()
  19547. }
  19548. } else {
  19549. me.selection.clearRange()
  19550. }
  19551. }
  19552. mousedown = false;
  19553. me.document.body.style.webkitUserSelect = '';
  19554. //拖拽状态下的mouseUP
  19555. if ( onDrag && dragTd ) {
  19556. me.selection.getNative()[browser.ie9below ? 'empty' : 'removeAllRanges']();
  19557. singleClickState = 0;
  19558. dragLine = me.document.getElementById('ue_tableDragLine');
  19559. // trace 3973
  19560. if (dragLine) {
  19561. var dragTdPos = domUtils.getXY(dragTd),
  19562. dragLinePos = domUtils.getXY(dragLine);
  19563. switch (onDrag) {
  19564. case "h":
  19565. changeColWidth(dragTd, dragLinePos.x - dragTdPos.x);
  19566. break;
  19567. case "v":
  19568. changeRowHeight(dragTd, dragLinePos.y - dragTdPos.y - dragTd.offsetHeight);
  19569. break;
  19570. default:
  19571. }
  19572. onDrag = "";
  19573. dragTd = null;
  19574. hideDragLine(me);
  19575. me.fireEvent('saveScene');
  19576. return;
  19577. }
  19578. }
  19579. //正常状态下的mouseup
  19580. if (!startTd) {
  19581. var target = domUtils.findParentByTagName(evt.target || evt.srcElement, "td", true);
  19582. if (!target) target = domUtils.findParentByTagName(evt.target || evt.srcElement, "th", true);
  19583. if (target && (target.tagName == "TD" || target.tagName == "TH")) {
  19584. if (me.fireEvent("excludetable", target) === true) return;
  19585. range = new dom.Range(me.document);
  19586. range.setStart(target, 0).setCursor(false, true);
  19587. }
  19588. } else {
  19589. var ut = getUETable(startTd),
  19590. cell = ut ? ut.selectedTds[0] : null;
  19591. if (cell) {
  19592. range = new dom.Range(me.document);
  19593. if (domUtils.isEmptyBlock(cell)) {
  19594. range.setStart(cell, 0).setCursor(false, true);
  19595. } else {
  19596. range.selectNodeContents(cell).shrinkBoundary().setCursor(false, true);
  19597. }
  19598. } else {
  19599. range = me.selection.getRange().shrinkBoundary();
  19600. if (!range.collapsed) {
  19601. var start = domUtils.findParentByTagName(range.startContainer, ['td', 'th'], true),
  19602. end = domUtils.findParentByTagName(range.endContainer, ['td', 'th'], true);
  19603. //在table里边的不能清除
  19604. if (start && !end || !start && end || start && end && start !== end) {
  19605. range.setCursor(false, true);
  19606. }
  19607. }
  19608. }
  19609. startTd = null;
  19610. me.removeListener('mouseover', mouseOverEvent);
  19611. }
  19612. me._selectionChange(250, evt);
  19613. }
  19614. function mouseOverEvent(type, evt) {
  19615. if( isEditorDisabled() ) {
  19616. return;
  19617. }
  19618. var me = this,
  19619. tar = evt.target || evt.srcElement;
  19620. currentTd = domUtils.findParentByTagName(tar, "td", true) || domUtils.findParentByTagName(tar, "th", true);
  19621. //需要判断两个TD是否位于同一个表格内
  19622. if (startTd && currentTd &&
  19623. ((startTd.tagName == "TD" && currentTd.tagName == "TD") || (startTd.tagName == "TH" && currentTd.tagName == "TH")) &&
  19624. domUtils.findParentByTagName(startTd, 'table') == domUtils.findParentByTagName(currentTd, 'table')) {
  19625. var ut = getUETable(currentTd);
  19626. if (startTd != currentTd) {
  19627. me.document.body.style.webkitUserSelect = 'none';
  19628. me.selection.getNative()[browser.ie9below ? 'empty' : 'removeAllRanges']();
  19629. var range = ut.getCellsRange(startTd, currentTd);
  19630. ut.setSelected(range);
  19631. } else {
  19632. me.document.body.style.webkitUserSelect = '';
  19633. ut.clearSelected();
  19634. }
  19635. }
  19636. evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false);
  19637. }
  19638. function setCellHeight(cell, height, backHeight) {
  19639. var lineHight = parseInt(domUtils.getComputedStyle(cell, "line-height"), 10),
  19640. tmpHeight = backHeight + height;
  19641. height = tmpHeight < lineHight ? lineHight : tmpHeight;
  19642. if (cell.style.height) cell.style.height = "";
  19643. cell.rowSpan == 1 ? cell.setAttribute("height", height) : (cell.removeAttribute && cell.removeAttribute("height"));
  19644. }
  19645. function getWidth(cell) {
  19646. if (!cell)return 0;
  19647. return parseInt(domUtils.getComputedStyle(cell, "width"), 10);
  19648. }
  19649. function changeColWidth(cell, changeValue) {
  19650. var ut = getUETable(cell);
  19651. if (ut) {
  19652. //根据当前移动的边框获取相关的单元格
  19653. var table = ut.table,
  19654. cells = getCellsByMoveBorder( cell, table );
  19655. table.style.width = "";
  19656. table.removeAttribute("width");
  19657. //修正改变量
  19658. changeValue = correctChangeValue( changeValue, cell, cells );
  19659. if (cell.nextSibling) {
  19660. var i=0;
  19661. utils.each( cells, function( cellGroup ){
  19662. cellGroup.left.width = (+cellGroup.left.width)+changeValue;
  19663. cellGroup.right && ( cellGroup.right.width = (+cellGroup.right.width)-changeValue );
  19664. } );
  19665. } else {
  19666. utils.each( cells, function( cellGroup ){
  19667. cellGroup.left.width -= -changeValue;
  19668. } );
  19669. }
  19670. }
  19671. }
  19672. function isEditorDisabled() {
  19673. return me.body.contentEditable === "false";
  19674. }
  19675. function changeRowHeight(td, changeValue) {
  19676. if (Math.abs(changeValue) < 10) return;
  19677. var ut = getUETable(td);
  19678. if (ut) {
  19679. var cells = ut.getSameEndPosCells(td, "y"),
  19680. //备份需要连带变化的td的原始高度,否则后期无法获取正确的值
  19681. backHeight = cells[0] ? cells[0].offsetHeight : 0;
  19682. for (var i = 0, cell; cell = cells[i++];) {
  19683. setCellHeight(cell, changeValue, backHeight);
  19684. }
  19685. }
  19686. }
  19687. /**
  19688. * 获取调整单元格大小的相关单元格
  19689. * @isContainMergeCell 返回的结果中是否包含发生合并后的单元格
  19690. */
  19691. function getCellsByMoveBorder( cell, table, isContainMergeCell ) {
  19692. if( !table ) {
  19693. table = domUtils.findParentByTagName( cell, 'table' );
  19694. }
  19695. if( !table ) {
  19696. return null;
  19697. }
  19698. //获取到该单元格所在行的序列号
  19699. var index = domUtils.getNodeIndex( cell ),
  19700. temp = cell,
  19701. rows = table.rows,
  19702. colIndex = 0;
  19703. while( temp ) {
  19704. //获取到当前单元格在未发生单元格合并时的序列
  19705. if( temp.nodeType === 1 ) {
  19706. colIndex += (temp.colSpan || 1);
  19707. }
  19708. temp = temp.previousSibling;
  19709. }
  19710. temp = null;
  19711. //记录想关的单元格
  19712. var borderCells = [];
  19713. utils.each(rows, function( tabRow ){
  19714. var cells = tabRow.cells,
  19715. currIndex = 0;
  19716. utils.each( cells, function( tabCell ){
  19717. currIndex += (tabCell.colSpan || 1);
  19718. if( currIndex === colIndex ) {
  19719. borderCells.push({
  19720. left: tabCell,
  19721. right: tabCell.nextSibling || null
  19722. });
  19723. return false;
  19724. } else if( currIndex > colIndex ) {
  19725. if( isContainMergeCell ) {
  19726. borderCells.push({
  19727. left: tabCell
  19728. });
  19729. }
  19730. return false;
  19731. }
  19732. } );
  19733. });
  19734. return borderCells;
  19735. }
  19736. /**
  19737. * 通过给定的单元格集合获取最小的单元格width
  19738. */
  19739. function getMinWidthByTableCells( cells ) {
  19740. var minWidth = Number.MAX_VALUE;
  19741. for( var i = 0, curCell; curCell = cells[ i ] ; i++ ) {
  19742. minWidth = Math.min( minWidth, curCell.width || getTableCellWidth( curCell ) );
  19743. }
  19744. return minWidth;
  19745. }
  19746. function correctChangeValue( changeValue, relatedCell, cells ) {
  19747. //为单元格的paading预留空间
  19748. changeValue -= getTabcellSpace();
  19749. if( changeValue < 0 ) {
  19750. return 0;
  19751. }
  19752. changeValue -= getTableCellWidth( relatedCell );
  19753. //确定方向
  19754. var direction = changeValue < 0 ? 'left':'right';
  19755. changeValue = Math.abs(changeValue);
  19756. //只关心非最后一个单元格就可以
  19757. utils.each( cells, function( cellGroup ){
  19758. var curCell = cellGroup[direction];
  19759. //为单元格保留最小空间
  19760. if( curCell ) {
  19761. changeValue = Math.min( changeValue, getTableCellWidth( curCell )-cellMinWidth );
  19762. }
  19763. } );
  19764. //修正越界
  19765. changeValue = changeValue < 0 ? 0 : changeValue;
  19766. return direction === 'left' ? -changeValue : changeValue;
  19767. }
  19768. function getTableCellWidth( cell ) {
  19769. var width = 0,
  19770. //偏移纠正量
  19771. offset = 0,
  19772. width = cell.offsetWidth - getTabcellSpace();
  19773. //最后一个节点纠正一下
  19774. if( !cell.nextSibling ) {
  19775. width -= getTableCellOffset( cell );
  19776. }
  19777. width = width < 0 ? 0 : width;
  19778. try {
  19779. cell.width = width;
  19780. } catch(e) {
  19781. }
  19782. return width;
  19783. }
  19784. /**
  19785. * 获取单元格所在表格的最末单元格的偏移量
  19786. */
  19787. function getTableCellOffset( cell ) {
  19788. tab = domUtils.findParentByTagName( cell, "table", false);
  19789. if( tab.offsetVal === undefined ) {
  19790. var prev = cell.previousSibling;
  19791. if( prev ) {
  19792. //最后一个单元格和前一个单元格的width diff结果 如果恰好为一个border width, 则条件成立
  19793. tab.offsetVal = cell.offsetWidth - prev.offsetWidth === UT.borderWidth ? UT.borderWidth : 0;
  19794. } else {
  19795. tab.offsetVal = 0;
  19796. }
  19797. }
  19798. return tab.offsetVal;
  19799. }
  19800. function getTabcellSpace() {
  19801. if( UT.tabcellSpace === undefined ) {
  19802. var cell = null,
  19803. tab = me.document.createElement("table"),
  19804. tbody = me.document.createElement("tbody"),
  19805. trow = me.document.createElement("tr"),
  19806. tabcell = me.document.createElement("td"),
  19807. mirror = null;
  19808. tabcell.style.cssText = 'border: 0;';
  19809. tabcell.width = 1;
  19810. trow.appendChild( tabcell );
  19811. trow.appendChild( mirror = tabcell.cloneNode( false ) );
  19812. tbody.appendChild( trow );
  19813. tab.appendChild( tbody );
  19814. tab.style.cssText = "visibility: hidden;";
  19815. me.body.appendChild( tab );
  19816. UT.paddingSpace = tabcell.offsetWidth - 1;
  19817. var tmpTabWidth = tab.offsetWidth;
  19818. tabcell.style.cssText = '';
  19819. mirror.style.cssText = '';
  19820. UT.borderWidth = ( tab.offsetWidth - tmpTabWidth ) / 3;
  19821. UT.tabcellSpace = UT.paddingSpace + UT.borderWidth;
  19822. me.body.removeChild( tab );
  19823. }
  19824. getTabcellSpace = function(){ return UT.tabcellSpace; };
  19825. return UT.tabcellSpace;
  19826. }
  19827. function getDragLine(editor, doc) {
  19828. if (mousedown)return;
  19829. dragLine = editor.document.createElement("div");
  19830. domUtils.setAttributes(dragLine, {
  19831. id:"ue_tableDragLine",
  19832. unselectable:'on',
  19833. contenteditable:false,
  19834. 'onresizestart':'return false',
  19835. 'ondragstart':'return false',
  19836. 'onselectstart':'return false',
  19837. style:"background-color:blue;position:absolute;padding:0;margin:0;background-image:none;border:0px none;opacity:0;filter:alpha(opacity=0)"
  19838. });
  19839. editor.body.appendChild(dragLine);
  19840. }
  19841. function hideDragLine(editor) {
  19842. if (mousedown)return;
  19843. var line;
  19844. while (line = editor.document.getElementById('ue_tableDragLine')) {
  19845. domUtils.remove(line)
  19846. }
  19847. }
  19848. /**
  19849. * 依据state(v|h)在cell位置显示横线
  19850. * @param state
  19851. * @param cell
  19852. */
  19853. function showDragLineAt(state, cell) {
  19854. if (!cell) return;
  19855. var table = domUtils.findParentByTagName(cell, "table"),
  19856. caption = table.getElementsByTagName('caption'),
  19857. width = table.offsetWidth,
  19858. height = table.offsetHeight - (caption.length > 0 ? caption[0].offsetHeight : 0),
  19859. tablePos = domUtils.getXY(table),
  19860. cellPos = domUtils.getXY(cell), css;
  19861. switch (state) {
  19862. case "h":
  19863. css = 'height:' + height + 'px;top:' + (tablePos.y + (caption.length > 0 ? caption[0].offsetHeight : 0)) + 'px;left:' + (cellPos.x + cell.offsetWidth);
  19864. dragLine.style.cssText = css + 'px;position: absolute;display:block;background-color:blue;width:1px;border:0; color:blue;opacity:.3;filter:alpha(opacity=30)';
  19865. break;
  19866. case "v":
  19867. css = 'width:' + width + 'px;left:' + tablePos.x + 'px;top:' + (cellPos.y + cell.offsetHeight );
  19868. //必须加上border:0和color:blue,否则低版ie不支持背景色显示
  19869. dragLine.style.cssText = css + 'px;overflow:hidden;position: absolute;display:block;background-color:blue;height:1px;border:0;color:blue;opacity:.2;filter:alpha(opacity=20)';
  19870. break;
  19871. default:
  19872. }
  19873. }
  19874. /**
  19875. * 当表格边框颜色为白色时设置为虚线,true为添加虚线
  19876. * @param editor
  19877. * @param flag
  19878. */
  19879. function switchBorderColor(editor, flag) {
  19880. var tableArr = domUtils.getElementsByTagName(editor.body, "table"), color;
  19881. for (var i = 0, node; node = tableArr[i++];) {
  19882. var td = domUtils.getElementsByTagName(node, "td");
  19883. if (td[0]) {
  19884. if (flag) {
  19885. color = (td[0].style.borderColor).replace(/\s/g, "");
  19886. if (/(#ffffff)|(rgb\(255,255,255\))/ig.test(color))
  19887. domUtils.addClass(node, "noBorderTable")
  19888. } else {
  19889. domUtils.removeClasses(node, "noBorderTable")
  19890. }
  19891. }
  19892. }
  19893. }
  19894. function getTableWidth(editor, needIEHack, defaultValue) {
  19895. var body = editor.body;
  19896. return body.offsetWidth - (needIEHack ? parseInt(domUtils.getComputedStyle(body, 'margin-left'), 10) * 2 : 0) - defaultValue.tableBorder * 2 - (editor.options.offsetWidth || 0);
  19897. }
  19898. /**
  19899. * 获取当前拖动的单元格
  19900. */
  19901. function getTargetTd(editor, evt) {
  19902. var target = domUtils.findParentByTagName(evt.target || evt.srcElement, ["td", "th"], true),
  19903. dir = null;
  19904. if( !target ) {
  19905. return null;
  19906. }
  19907. dir = getRelation( target, mouseCoords( evt ) );
  19908. //如果有前一个节点, 需要做一个修正, 否则可能会得到一个错误的td
  19909. if( !target ) {
  19910. return null;
  19911. }
  19912. if( dir === 'h1' && target.previousSibling ) {
  19913. var position = domUtils.getXY( target),
  19914. cellWidth = target.offsetWidth;
  19915. if( Math.abs( position.x + cellWidth - evt.clientX ) > cellWidth / 3 ) {
  19916. target = target.previousSibling;
  19917. }
  19918. } else if( dir === 'v1' && target.parentNode.previousSibling ) {
  19919. var position = domUtils.getXY( target),
  19920. cellHeight = target.offsetHeight;
  19921. if( Math.abs( position.y + cellHeight - evt.clientY ) > cellHeight / 3 ) {
  19922. target = target.parentNode.previousSibling.firstChild;
  19923. }
  19924. }
  19925. //排除了非td内部以及用于代码高亮部分的td
  19926. return target && !(editor.fireEvent("excludetable", target) === true) ? target : null;
  19927. }
  19928. };
  19929. // plugins/table.sort.js
  19930. /**
  19931. * Created with JetBrains PhpStorm.
  19932. * User: Jinqn
  19933. * Date: 13-10-12
  19934. * Time: 上午10:20
  19935. * To change this template use File | Settings | File Templates.
  19936. */
  19937. UE.UETable.prototype.sortTable = function (sortByCellIndex, compareFn) {
  19938. var table = this.table,
  19939. rows = table.rows,
  19940. trArray = [],
  19941. flag = rows[0].cells[0].tagName === "TH",
  19942. lastRowIndex = 0;
  19943. if(this.selectedTds.length){
  19944. var range = this.cellsRange,
  19945. len = range.endRowIndex + 1;
  19946. for (var i = range.beginRowIndex; i < len; i++) {
  19947. trArray[i] = rows[i];
  19948. }
  19949. trArray.splice(0,range.beginRowIndex);
  19950. lastRowIndex = (range.endRowIndex +1) === this.rowsNum ? 0 : range.endRowIndex +1;
  19951. }else{
  19952. for (var i = 0,len = rows.length; i < len; i++) {
  19953. trArray[i] = rows[i];
  19954. }
  19955. }
  19956. var Fn = {
  19957. 'reversecurrent': function(td1,td2){
  19958. return 1;
  19959. },
  19960. 'orderbyasc': function(td1,td2){
  19961. var value1 = td1.innerText||td1.textContent,
  19962. value2 = td2.innerText||td2.textContent;
  19963. return value1.localeCompare(value2);
  19964. },
  19965. 'reversebyasc': function(td1,td2){
  19966. var value1 = td1.innerHTML,
  19967. value2 = td2.innerHTML;
  19968. return value2.localeCompare(value1);
  19969. },
  19970. 'orderbynum': function(td1,td2){
  19971. var value1 = td1[browser.ie ? 'innerText':'textContent'].match(/\d+/),
  19972. value2 = td2[browser.ie ? 'innerText':'textContent'].match(/\d+/);
  19973. if(value1) value1 = +value1[0];
  19974. if(value2) value2 = +value2[0];
  19975. return (value1||0) - (value2||0);
  19976. },
  19977. 'reversebynum': function(td1,td2){
  19978. var value1 = td1[browser.ie ? 'innerText':'textContent'].match(/\d+/),
  19979. value2 = td2[browser.ie ? 'innerText':'textContent'].match(/\d+/);
  19980. if(value1) value1 = +value1[0];
  19981. if(value2) value2 = +value2[0];
  19982. return (value2||0) - (value1||0);
  19983. }
  19984. };
  19985. //对表格设置排序的标记data-sort-type
  19986. table.setAttribute('data-sort-type', compareFn && typeof compareFn === "string" && Fn[compareFn] ? compareFn:'');
  19987. //th不参与排序
  19988. flag && trArray.splice(0, 1);
  19989. trArray = utils.sort(trArray,function (tr1, tr2) {
  19990. var result;
  19991. if (compareFn && typeof compareFn === "function") {
  19992. result = compareFn.call(this, tr1.cells[sortByCellIndex], tr2.cells[sortByCellIndex]);
  19993. } else if (compareFn && typeof compareFn === "number") {
  19994. result = 1;
  19995. } else if (compareFn && typeof compareFn === "string" && Fn[compareFn]) {
  19996. result = Fn[compareFn].call(this, tr1.cells[sortByCellIndex], tr2.cells[sortByCellIndex]);
  19997. } else {
  19998. result = Fn['orderbyasc'].call(this, tr1.cells[sortByCellIndex], tr2.cells[sortByCellIndex]);
  19999. }
  20000. return result;
  20001. });
  20002. var fragment = table.ownerDocument.createDocumentFragment();
  20003. for (var j = 0, len = trArray.length; j < len; j++) {
  20004. fragment.appendChild(trArray[j]);
  20005. }
  20006. var tbody = table.getElementsByTagName("tbody")[0];
  20007. if(!lastRowIndex){
  20008. tbody.appendChild(fragment);
  20009. }else{
  20010. tbody.insertBefore(fragment,rows[lastRowIndex- range.endRowIndex + range.beginRowIndex - 1])
  20011. }
  20012. };
  20013. UE.plugins['tablesort'] = function () {
  20014. var me = this,
  20015. UT = UE.UETable,
  20016. getUETable = function (tdOrTable) {
  20017. return UT.getUETable(tdOrTable);
  20018. },
  20019. getTableItemsByRange = function (editor) {
  20020. return UT.getTableItemsByRange(editor);
  20021. };
  20022. me.ready(function () {
  20023. //添加表格可排序的样式
  20024. utils.cssRule('tablesort',
  20025. 'table.sortEnabled tr.firstRow th,table.sortEnabled tr.firstRow td{padding-right:20px;background-repeat: no-repeat;background-position: center right;' +
  20026. ' background-image:url(' + me.options.themePath + me.options.theme + '/images/sortable.png);}',
  20027. me.document);
  20028. //做单元格合并操作时,清除可排序标识
  20029. me.addListener("afterexeccommand", function (type, cmd) {
  20030. if( cmd == 'mergeright' || cmd == 'mergedown' || cmd == 'mergecells') {
  20031. this.execCommand('disablesort');
  20032. }
  20033. });
  20034. });
  20035. //表格排序
  20036. UE.commands['sorttable'] = {
  20037. queryCommandState: function () {
  20038. var me = this,
  20039. tableItems = getTableItemsByRange(me);
  20040. if (!tableItems.cell) return -1;
  20041. var table = tableItems.table,
  20042. cells = table.getElementsByTagName("td");
  20043. for (var i = 0, cell; cell = cells[i++];) {
  20044. if (cell.rowSpan != 1 || cell.colSpan != 1) return -1;
  20045. }
  20046. return 0;
  20047. },
  20048. execCommand: function (cmd, fn) {
  20049. var me = this,
  20050. range = me.selection.getRange(),
  20051. bk = range.createBookmark(true),
  20052. tableItems = getTableItemsByRange(me),
  20053. cell = tableItems.cell,
  20054. ut = getUETable(tableItems.table),
  20055. cellInfo = ut.getCellInfo(cell);
  20056. ut.sortTable(cellInfo.cellIndex, fn);
  20057. range.moveToBookmark(bk);
  20058. try{
  20059. range.select();
  20060. }catch(e){}
  20061. }
  20062. };
  20063. //设置表格可排序,清除表格可排序
  20064. UE.commands["enablesort"] = UE.commands["disablesort"] = {
  20065. queryCommandState: function (cmd) {
  20066. var table = getTableItemsByRange(this).table;
  20067. if(table && cmd=='enablesort') {
  20068. var cells = domUtils.getElementsByTagName(table, 'th td');
  20069. for(var i = 0; i<cells.length; i++) {
  20070. if(cells[i].getAttribute('colspan')>1 || cells[i].getAttribute('rowspan')>1) return -1;
  20071. }
  20072. }
  20073. return !table ? -1: cmd=='enablesort' ^ table.getAttribute('data-sort')!='sortEnabled' ? -1:0;
  20074. },
  20075. execCommand: function (cmd) {
  20076. var table = getTableItemsByRange(this).table;
  20077. table.setAttribute("data-sort", cmd == "enablesort" ? "sortEnabled" : "sortDisabled");
  20078. cmd == "enablesort" ? domUtils.addClass(table,"sortEnabled"):domUtils.removeClasses(table,"sortEnabled");
  20079. }
  20080. };
  20081. };
  20082. // plugins/contextmenu.js
  20083. ///import core
  20084. ///commands 右键菜单
  20085. ///commandsName ContextMenu
  20086. ///commandsTitle 右键菜单
  20087. /**
  20088. * 右键菜单
  20089. * @function
  20090. * @name baidu.editor.plugins.contextmenu
  20091. * @author zhanyi
  20092. */
  20093. UE.plugins['contextmenu'] = function () {
  20094. var me = this;
  20095. me.setOpt('enableContextMenu',true);
  20096. if(me.getOpt('enableContextMenu') === false){
  20097. return;
  20098. }
  20099. var lang = me.getLang( "contextMenu" ),
  20100. menu,
  20101. items = me.options.contextMenu || [
  20102. {label:lang['selectall'], cmdName:'selectall'},
  20103. {
  20104. label:lang.cleardoc,
  20105. cmdName:'cleardoc',
  20106. exec:function () {
  20107. if ( confirm( lang.confirmclear ) ) {
  20108. this.execCommand( 'cleardoc' );
  20109. }
  20110. }
  20111. },
  20112. '-',
  20113. {
  20114. label:lang.unlink,
  20115. cmdName:'unlink'
  20116. },
  20117. '-',
  20118. {
  20119. group:lang.paragraph,
  20120. icon:'justifyjustify',
  20121. subMenu:[
  20122. {
  20123. label:lang.justifyleft,
  20124. cmdName:'justify',
  20125. value:'left'
  20126. },
  20127. {
  20128. label:lang.justifyright,
  20129. cmdName:'justify',
  20130. value:'right'
  20131. },
  20132. {
  20133. label:lang.justifycenter,
  20134. cmdName:'justify',
  20135. value:'center'
  20136. },
  20137. {
  20138. label:lang.justifyjustify,
  20139. cmdName:'justify',
  20140. value:'justify'
  20141. }
  20142. ]
  20143. },
  20144. '-',
  20145. {
  20146. group:lang.table,
  20147. icon:'table',
  20148. subMenu:[
  20149. {
  20150. label:lang.inserttable,
  20151. cmdName:'inserttable'
  20152. },
  20153. {
  20154. label:lang.deletetable,
  20155. cmdName:'deletetable'
  20156. },
  20157. '-',
  20158. {
  20159. label:lang.deleterow,
  20160. cmdName:'deleterow'
  20161. },
  20162. {
  20163. label:lang.deletecol,
  20164. cmdName:'deletecol'
  20165. },
  20166. {
  20167. label:lang.insertcol,
  20168. cmdName:'insertcol'
  20169. },
  20170. {
  20171. label:lang.insertcolnext,
  20172. cmdName:'insertcolnext'
  20173. },
  20174. {
  20175. label:lang.insertrow,
  20176. cmdName:'insertrow'
  20177. },
  20178. {
  20179. label:lang.insertrownext,
  20180. cmdName:'insertrownext'
  20181. },
  20182. '-',
  20183. {
  20184. label:lang.insertcaption,
  20185. cmdName:'insertcaption'
  20186. },
  20187. {
  20188. label:lang.deletecaption,
  20189. cmdName:'deletecaption'
  20190. },
  20191. {
  20192. label:lang.inserttitle,
  20193. cmdName:'inserttitle'
  20194. },
  20195. {
  20196. label:lang.deletetitle,
  20197. cmdName:'deletetitle'
  20198. },
  20199. {
  20200. label:lang.inserttitlecol,
  20201. cmdName:'inserttitlecol'
  20202. },
  20203. {
  20204. label:lang.deletetitlecol,
  20205. cmdName:'deletetitlecol'
  20206. },
  20207. '-',
  20208. {
  20209. label:lang.mergecells,
  20210. cmdName:'mergecells'
  20211. },
  20212. {
  20213. label:lang.mergeright,
  20214. cmdName:'mergeright'
  20215. },
  20216. {
  20217. label:lang.mergedown,
  20218. cmdName:'mergedown'
  20219. },
  20220. '-',
  20221. {
  20222. label:lang.splittorows,
  20223. cmdName:'splittorows'
  20224. },
  20225. {
  20226. label:lang.splittocols,
  20227. cmdName:'splittocols'
  20228. },
  20229. {
  20230. label:lang.splittocells,
  20231. cmdName:'splittocells'
  20232. },
  20233. '-',
  20234. {
  20235. label:lang.averageDiseRow,
  20236. cmdName:'averagedistributerow'
  20237. },
  20238. {
  20239. label:lang.averageDisCol,
  20240. cmdName:'averagedistributecol'
  20241. },
  20242. '-',
  20243. {
  20244. label:lang.edittd,
  20245. cmdName:'edittd',
  20246. exec:function () {
  20247. if ( UE.ui['edittd'] ) {
  20248. new UE.ui['edittd']( this );
  20249. }
  20250. this.getDialog('edittd').open();
  20251. }
  20252. },
  20253. {
  20254. label:lang.edittable,
  20255. cmdName:'edittable',
  20256. exec:function () {
  20257. if ( UE.ui['edittable'] ) {
  20258. new UE.ui['edittable']( this );
  20259. }
  20260. this.getDialog('edittable').open();
  20261. }
  20262. },
  20263. {
  20264. label:lang.setbordervisible,
  20265. cmdName:'setbordervisible'
  20266. }
  20267. ]
  20268. },
  20269. {
  20270. group:lang.tablesort,
  20271. icon:'tablesort',
  20272. subMenu:[
  20273. {
  20274. label:lang.enablesort,
  20275. cmdName:'enablesort'
  20276. },
  20277. {
  20278. label:lang.disablesort,
  20279. cmdName:'disablesort'
  20280. },
  20281. '-',
  20282. {
  20283. label:lang.reversecurrent,
  20284. cmdName:'sorttable',
  20285. value:'reversecurrent'
  20286. },
  20287. {
  20288. label:lang.orderbyasc,
  20289. cmdName:'sorttable',
  20290. value:'orderbyasc'
  20291. },
  20292. {
  20293. label:lang.reversebyasc,
  20294. cmdName:'sorttable',
  20295. value:'reversebyasc'
  20296. },
  20297. {
  20298. label:lang.orderbynum,
  20299. cmdName:'sorttable',
  20300. value:'orderbynum'
  20301. },
  20302. {
  20303. label:lang.reversebynum,
  20304. cmdName:'sorttable',
  20305. value:'reversebynum'
  20306. }
  20307. ]
  20308. },
  20309. {
  20310. group:lang.borderbk,
  20311. icon:'borderBack',
  20312. subMenu:[
  20313. {
  20314. label:lang.setcolor,
  20315. cmdName:"interlacetable",
  20316. exec:function(){
  20317. this.execCommand("interlacetable");
  20318. }
  20319. },
  20320. {
  20321. label:lang.unsetcolor,
  20322. cmdName:"uninterlacetable",
  20323. exec:function(){
  20324. this.execCommand("uninterlacetable");
  20325. }
  20326. },
  20327. {
  20328. label:lang.setbackground,
  20329. cmdName:"settablebackground",
  20330. exec:function(){
  20331. this.execCommand("settablebackground",{repeat:true,colorList:["#bbb","#ccc"]});
  20332. }
  20333. },
  20334. {
  20335. label:lang.unsetbackground,
  20336. cmdName:"cleartablebackground",
  20337. exec:function(){
  20338. this.execCommand("cleartablebackground");
  20339. }
  20340. },
  20341. {
  20342. label:lang.redandblue,
  20343. cmdName:"settablebackground",
  20344. exec:function(){
  20345. this.execCommand("settablebackground",{repeat:true,colorList:["red","blue"]});
  20346. }
  20347. },
  20348. {
  20349. label:lang.threecolorgradient,
  20350. cmdName:"settablebackground",
  20351. exec:function(){
  20352. this.execCommand("settablebackground",{repeat:true,colorList:["#aaa","#bbb","#ccc"]});
  20353. }
  20354. }
  20355. ]
  20356. },
  20357. {
  20358. group:lang.aligntd,
  20359. icon:'aligntd',
  20360. subMenu:[
  20361. {
  20362. cmdName:'cellalignment',
  20363. value:{align:'left',vAlign:'top'}
  20364. },
  20365. {
  20366. cmdName:'cellalignment',
  20367. value:{align:'center',vAlign:'top'}
  20368. },
  20369. {
  20370. cmdName:'cellalignment',
  20371. value:{align:'right',vAlign:'top'}
  20372. },
  20373. {
  20374. cmdName:'cellalignment',
  20375. value:{align:'left',vAlign:'middle'}
  20376. },
  20377. {
  20378. cmdName:'cellalignment',
  20379. value:{align:'center',vAlign:'middle'}
  20380. },
  20381. {
  20382. cmdName:'cellalignment',
  20383. value:{align:'right',vAlign:'middle'}
  20384. },
  20385. {
  20386. cmdName:'cellalignment',
  20387. value:{align:'left',vAlign:'bottom'}
  20388. },
  20389. {
  20390. cmdName:'cellalignment',
  20391. value:{align:'center',vAlign:'bottom'}
  20392. },
  20393. {
  20394. cmdName:'cellalignment',
  20395. value:{align:'right',vAlign:'bottom'}
  20396. }
  20397. ]
  20398. },
  20399. {
  20400. group:lang.aligntable,
  20401. icon:'aligntable',
  20402. subMenu:[
  20403. {
  20404. cmdName:'tablealignment',
  20405. className: 'left',
  20406. label:lang.tableleft,
  20407. value:"left"
  20408. },
  20409. {
  20410. cmdName:'tablealignment',
  20411. className: 'center',
  20412. label:lang.tablecenter,
  20413. value:"center"
  20414. },
  20415. {
  20416. cmdName:'tablealignment',
  20417. className: 'right',
  20418. label:lang.tableright,
  20419. value:"right"
  20420. }
  20421. ]
  20422. },
  20423. '-',
  20424. {
  20425. label:lang.insertparagraphbefore,
  20426. cmdName:'insertparagraph',
  20427. value:true
  20428. },
  20429. {
  20430. label:lang.insertparagraphafter,
  20431. cmdName:'insertparagraph'
  20432. },
  20433. {
  20434. label:lang['copy'],
  20435. cmdName:'copy'
  20436. },
  20437. {
  20438. label:lang['paste'],
  20439. cmdName:'paste'
  20440. }
  20441. ];
  20442. if ( !items.length ) {
  20443. return;
  20444. }
  20445. var uiUtils = UE.ui.uiUtils;
  20446. me.addListener( 'contextmenu', function ( type, evt ) {
  20447. var offset = uiUtils.getViewportOffsetByEvent( evt );
  20448. me.fireEvent( 'beforeselectionchange' );
  20449. if ( menu ) {
  20450. menu.destroy();
  20451. }
  20452. for ( var i = 0, ti, contextItems = []; ti = items[i]; i++ ) {
  20453. var last;
  20454. (function ( item ) {
  20455. if ( item == '-' ) {
  20456. if ( (last = contextItems[contextItems.length - 1 ] ) && last !== '-' ) {
  20457. contextItems.push( '-' );
  20458. }
  20459. } else if ( item.hasOwnProperty( "group" ) ) {
  20460. for ( var j = 0, cj, subMenu = []; cj = item.subMenu[j]; j++ ) {
  20461. (function ( subItem ) {
  20462. if ( subItem == '-' ) {
  20463. if ( (last = subMenu[subMenu.length - 1 ] ) && last !== '-' ) {
  20464. subMenu.push( '-' );
  20465. }else{
  20466. subMenu.splice(subMenu.length-1);
  20467. }
  20468. } else {
  20469. if ( (me.commands[subItem.cmdName] || UE.commands[subItem.cmdName] || subItem.query) &&
  20470. (subItem.query ? subItem.query() : me.queryCommandState( subItem.cmdName )) > -1 ) {
  20471. subMenu.push( {
  20472. 'label':subItem.label || me.getLang( "contextMenu." + subItem.cmdName + (subItem.value || '') )||"",
  20473. 'className':'edui-for-' +subItem.cmdName + ( subItem.className ? ( ' edui-for-' + subItem.cmdName + '-' + subItem.className ) : '' ),
  20474. onclick:subItem.exec ? function () {
  20475. subItem.exec.call( me );
  20476. } : function () {
  20477. me.execCommand( subItem.cmdName, subItem.value );
  20478. }
  20479. } );
  20480. }
  20481. }
  20482. })( cj );
  20483. }
  20484. if ( subMenu.length ) {
  20485. function getLabel(){
  20486. switch (item.icon){
  20487. case "table":
  20488. return me.getLang( "contextMenu.table" );
  20489. case "justifyjustify":
  20490. return me.getLang( "contextMenu.paragraph" );
  20491. case "aligntd":
  20492. return me.getLang("contextMenu.aligntd");
  20493. case "aligntable":
  20494. return me.getLang("contextMenu.aligntable");
  20495. case "tablesort":
  20496. return lang.tablesort;
  20497. case "borderBack":
  20498. return lang.borderbk;
  20499. default :
  20500. return '';
  20501. }
  20502. }
  20503. contextItems.push( {
  20504. //todo 修正成自动获取方式
  20505. 'label':getLabel(),
  20506. className:'edui-for-' + item.icon,
  20507. 'subMenu':{
  20508. items:subMenu,
  20509. editor:me
  20510. }
  20511. } );
  20512. }
  20513. } else {
  20514. //有可能commmand没有加载右键不能出来,或者没有command也想能展示出来添加query方法
  20515. if ( (me.commands[item.cmdName] || UE.commands[item.cmdName] || item.query) &&
  20516. (item.query ? item.query.call(me) : me.queryCommandState( item.cmdName )) > -1 ) {
  20517. contextItems.push( {
  20518. 'label':item.label || me.getLang( "contextMenu." + item.cmdName ),
  20519. className:'edui-for-' + (item.icon ? item.icon : item.cmdName + (item.value || '')),
  20520. onclick:item.exec ? function () {
  20521. item.exec.call( me );
  20522. } : function () {
  20523. me.execCommand( item.cmdName, item.value );
  20524. }
  20525. } );
  20526. }
  20527. }
  20528. })( ti );
  20529. }
  20530. if ( contextItems[contextItems.length - 1] == '-' ) {
  20531. contextItems.pop();
  20532. }
  20533. menu = new UE.ui.Menu( {
  20534. items:contextItems,
  20535. className:"edui-contextmenu",
  20536. editor:me
  20537. } );
  20538. menu.render();
  20539. menu.showAt( offset );
  20540. me.fireEvent("aftershowcontextmenu",menu);
  20541. domUtils.preventDefault( evt );
  20542. if ( browser.ie ) {
  20543. var ieRange;
  20544. try {
  20545. ieRange = me.selection.getNative().createRange();
  20546. } catch ( e ) {
  20547. return;
  20548. }
  20549. if ( ieRange.item ) {
  20550. var range = new dom.Range( me.document );
  20551. range.selectNode( ieRange.item( 0 ) ).select( true, true );
  20552. }
  20553. }
  20554. });
  20555. // 添加复制的flash按钮
  20556. me.addListener('aftershowcontextmenu', function(type, menu) {
  20557. if (me.zeroclipboard) {
  20558. var items = menu.items;
  20559. for (var key in items) {
  20560. if (items[key].className == 'edui-for-copy') {
  20561. me.zeroclipboard.clip(items[key].getDom());
  20562. }
  20563. }
  20564. }
  20565. });
  20566. };
  20567. // plugins/shortcutmenu.js
  20568. ///import core
  20569. ///commands 弹出菜单
  20570. // commandsName popupmenu
  20571. ///commandsTitle 弹出菜单
  20572. /**
  20573. * 弹出菜单
  20574. * @function
  20575. * @name baidu.editor.plugins.popupmenu
  20576. * @author xuheng
  20577. */
  20578. UE.plugins['shortcutmenu'] = function () {
  20579. var me = this,
  20580. menu,
  20581. items = me.options.shortcutMenu || [];
  20582. if (!items.length) {
  20583. return;
  20584. }
  20585. me.addListener ('contextmenu mouseup' , function (type , e) {
  20586. var me = this,
  20587. customEvt = {
  20588. type : type ,
  20589. target : e.target || e.srcElement ,
  20590. screenX : e.screenX ,
  20591. screenY : e.screenY ,
  20592. clientX : e.clientX ,
  20593. clientY : e.clientY
  20594. };
  20595. setTimeout (function () {
  20596. var rng = me.selection.getRange ();
  20597. if (rng.collapsed === false || type == "contextmenu") {
  20598. if (!menu) {
  20599. menu = new baidu.editor.ui.ShortCutMenu ({
  20600. editor : me ,
  20601. items : items ,
  20602. theme : me.options.theme ,
  20603. className : 'edui-shortcutmenu'
  20604. });
  20605. menu.render ();
  20606. me.fireEvent ("afterrendershortcutmenu" , menu);
  20607. }
  20608. menu.show (customEvt , !!UE.plugins['contextmenu']);
  20609. }
  20610. });
  20611. if (type == 'contextmenu') {
  20612. domUtils.preventDefault (e);
  20613. if (browser.ie9below) {
  20614. var ieRange;
  20615. try {
  20616. ieRange = me.selection.getNative().createRange();
  20617. } catch (e) {
  20618. return;
  20619. }
  20620. if (ieRange.item) {
  20621. var range = new dom.Range (me.document);
  20622. range.selectNode (ieRange.item (0)).select (true , true);
  20623. }
  20624. }
  20625. }
  20626. });
  20627. me.addListener ('keydown' , function (type) {
  20628. if (type == "keydown") {
  20629. menu && !menu.isHidden && menu.hide ();
  20630. }
  20631. });
  20632. };
  20633. // plugins/basestyle.js
  20634. /**
  20635. * B、I、sub、super命令支持
  20636. * @file
  20637. * @since 1.2.6.1
  20638. */
  20639. UE.plugins['basestyle'] = function(){
  20640. /**
  20641. * 字体加粗
  20642. * @command bold
  20643. * @param { String } cmd 命令字符串
  20644. * @remind 对已加粗的文本内容执行该命令, 将取消加粗
  20645. * @method execCommand
  20646. * @example
  20647. * ```javascript
  20648. * //editor是编辑器实例
  20649. * //对当前选中的文本内容执行加粗操作
  20650. * //第一次执行, 文本内容加粗
  20651. * editor.execCommand( 'bold' );
  20652. *
  20653. * //第二次执行, 文本内容取消加粗
  20654. * editor.execCommand( 'bold' );
  20655. * ```
  20656. */
  20657. /**
  20658. * 字体倾斜
  20659. * @command italic
  20660. * @method execCommand
  20661. * @param { String } cmd 命令字符串
  20662. * @remind 对已倾斜的文本内容执行该命令, 将取消倾斜
  20663. * @example
  20664. * ```javascript
  20665. * //editor是编辑器实例
  20666. * //对当前选中的文本内容执行斜体操作
  20667. * //第一次操作, 文本内容将变成斜体
  20668. * editor.execCommand( 'italic' );
  20669. *
  20670. * //再次对同一文本内容执行, 则文本内容将恢复正常
  20671. * editor.execCommand( 'italic' );
  20672. * ```
  20673. */
  20674. /**
  20675. * 下标文本,与“superscript”命令互斥
  20676. * @command subscript
  20677. * @method execCommand
  20678. * @remind 把选中的文本内容切换成下标文本, 如果当前选中的文本已经是下标, 则该操作会把文本内容还原成正常文本
  20679. * @param { String } cmd 命令字符串
  20680. * @example
  20681. * ```javascript
  20682. * //editor是编辑器实例
  20683. * //对当前选中的文本内容执行下标操作
  20684. * //第一次操作, 文本内容将变成下标文本
  20685. * editor.execCommand( 'subscript' );
  20686. *
  20687. * //再次对同一文本内容执行, 则文本内容将恢复正常
  20688. * editor.execCommand( 'subscript' );
  20689. * ```
  20690. */
  20691. /**
  20692. * 上标文本,与“subscript”命令互斥
  20693. * @command superscript
  20694. * @method execCommand
  20695. * @remind 把选中的文本内容切换成上标文本, 如果当前选中的文本已经是上标, 则该操作会把文本内容还原成正常文本
  20696. * @param { String } cmd 命令字符串
  20697. * @example
  20698. * ```javascript
  20699. * //editor是编辑器实例
  20700. * //对当前选中的文本内容执行上标操作
  20701. * //第一次操作, 文本内容将变成上标文本
  20702. * editor.execCommand( 'superscript' );
  20703. *
  20704. * //再次对同一文本内容执行, 则文本内容将恢复正常
  20705. * editor.execCommand( 'superscript' );
  20706. * ```
  20707. */
  20708. var basestyles = {
  20709. 'bold':['strong','b'],
  20710. 'italic':['em','i'],
  20711. 'subscript':['sub'],
  20712. 'superscript':['sup']
  20713. },
  20714. getObj = function(editor,tagNames){
  20715. return domUtils.filterNodeList(editor.selection.getStartElementPath(),tagNames);
  20716. },
  20717. me = this;
  20718. //添加快捷键
  20719. me.addshortcutkey({
  20720. "Bold" : "ctrl+66",//^B
  20721. "Italic" : "ctrl+73", //^I
  20722. "Underline" : "ctrl+85"//^U
  20723. });
  20724. me.addInputRule(function(root){
  20725. utils.each(root.getNodesByTagName('b i'),function(node){
  20726. switch (node.tagName){
  20727. case 'b':
  20728. node.tagName = 'strong';
  20729. break;
  20730. case 'i':
  20731. node.tagName = 'em';
  20732. }
  20733. });
  20734. });
  20735. for ( var style in basestyles ) {
  20736. (function( cmd, tagNames ) {
  20737. me.commands[cmd] = {
  20738. execCommand : function( cmdName ) {
  20739. var range = me.selection.getRange(),obj = getObj(this,tagNames);
  20740. if ( range.collapsed ) {
  20741. if ( obj ) {
  20742. var tmpText = me.document.createTextNode('');
  20743. range.insertNode( tmpText ).removeInlineStyle( tagNames );
  20744. range.setStartBefore(tmpText);
  20745. domUtils.remove(tmpText);
  20746. } else {
  20747. var tmpNode = range.document.createElement( tagNames[0] );
  20748. if(cmdName == 'superscript' || cmdName == 'subscript'){
  20749. tmpText = me.document.createTextNode('');
  20750. range.insertNode(tmpText)
  20751. .removeInlineStyle(['sub','sup'])
  20752. .setStartBefore(tmpText)
  20753. .collapse(true);
  20754. }
  20755. range.insertNode( tmpNode ).setStart( tmpNode, 0 );
  20756. }
  20757. range.collapse( true );
  20758. } else {
  20759. if(cmdName == 'superscript' || cmdName == 'subscript'){
  20760. if(!obj || obj.tagName.toLowerCase() != cmdName){
  20761. range.removeInlineStyle(['sub','sup']);
  20762. }
  20763. }
  20764. obj ? range.removeInlineStyle( tagNames ) : range.applyInlineStyle( tagNames[0] );
  20765. }
  20766. range.select();
  20767. },
  20768. queryCommandState : function() {
  20769. return getObj(this,tagNames) ? 1 : 0;
  20770. }
  20771. };
  20772. })( style, basestyles[style] );
  20773. }
  20774. };
  20775. // plugins/elementpath.js
  20776. /**
  20777. * 选取路径命令
  20778. * @file
  20779. */
  20780. UE.plugins['elementpath'] = function(){
  20781. var currentLevel,
  20782. tagNames,
  20783. me = this;
  20784. me.setOpt('elementPathEnabled',true);
  20785. if(!me.options.elementPathEnabled){
  20786. return;
  20787. }
  20788. me.commands['elementpath'] = {
  20789. execCommand : function( cmdName, level ) {
  20790. var start = tagNames[level],
  20791. range = me.selection.getRange();
  20792. currentLevel = level*1;
  20793. range.selectNode(start).select();
  20794. },
  20795. queryCommandValue : function() {
  20796. //产生一个副本,不能修改原来的startElementPath;
  20797. var parents = [].concat(this.selection.getStartElementPath()).reverse(),
  20798. names = [];
  20799. tagNames = parents;
  20800. for(var i=0,ci;ci=parents[i];i++){
  20801. if(ci.nodeType == 3) {
  20802. continue;
  20803. }
  20804. var name = ci.tagName.toLowerCase();
  20805. if(name == 'img' && ci.getAttribute('anchorname')){
  20806. name = 'anchor';
  20807. }
  20808. names[i] = name;
  20809. if(currentLevel == i){
  20810. currentLevel = -1;
  20811. break;
  20812. }
  20813. }
  20814. return names;
  20815. }
  20816. };
  20817. };
  20818. // plugins/formatmatch.js
  20819. /**
  20820. * 格式刷,只格式inline的
  20821. * @file
  20822. * @since 1.2.6.1
  20823. */
  20824. /**
  20825. * 格式刷
  20826. * @command formatmatch
  20827. * @method execCommand
  20828. * @remind 该操作不能复制段落格式
  20829. * @param { String } cmd 命令字符串
  20830. * @example
  20831. * ```javascript
  20832. * //editor是编辑器实例
  20833. * //获取格式刷
  20834. * editor.execCommand( 'formatmatch' );
  20835. * ```
  20836. */
  20837. UE.plugins['formatmatch'] = function(){
  20838. var me = this,
  20839. list = [],img,
  20840. flag = 0;
  20841. me.addListener('reset',function(){
  20842. list = [];
  20843. flag = 0;
  20844. });
  20845. function addList(type,evt){
  20846. if(browser.webkit){
  20847. var target = evt.target.tagName == 'IMG' ? evt.target : null;
  20848. }
  20849. function addFormat(range){
  20850. if(text){
  20851. range.selectNode(text);
  20852. }
  20853. return range.applyInlineStyle(list[list.length-1].tagName,null,list);
  20854. }
  20855. me.undoManger && me.undoManger.save();
  20856. var range = me.selection.getRange(),
  20857. imgT = target || range.getClosedNode();
  20858. if(img && imgT && imgT.tagName == 'IMG'){
  20859. //trace:964
  20860. imgT.style.cssText += ';float:' + (img.style.cssFloat || img.style.styleFloat ||'none') + ';display:' + (img.style.display||'inline');
  20861. img = null;
  20862. }else{
  20863. if(!img){
  20864. var collapsed = range.collapsed;
  20865. if(collapsed){
  20866. var text = me.document.createTextNode('match');
  20867. range.insertNode(text).select();
  20868. }
  20869. me.__hasEnterExecCommand = true;
  20870. //不能把block上的属性干掉
  20871. //trace:1553
  20872. var removeFormatAttributes = me.options.removeFormatAttributes;
  20873. me.options.removeFormatAttributes = '';
  20874. me.execCommand('removeformat');
  20875. me.options.removeFormatAttributes = removeFormatAttributes;
  20876. me.__hasEnterExecCommand = false;
  20877. //trace:969
  20878. range = me.selection.getRange();
  20879. if(list.length){
  20880. addFormat(range);
  20881. }
  20882. if(text){
  20883. range.setStartBefore(text).collapse(true);
  20884. }
  20885. range.select();
  20886. text && domUtils.remove(text);
  20887. }
  20888. }
  20889. me.undoManger && me.undoManger.save();
  20890. me.removeListener('mouseup',addList);
  20891. flag = 0;
  20892. }
  20893. me.commands['formatmatch'] = {
  20894. execCommand : function( cmdName ) {
  20895. if(flag){
  20896. flag = 0;
  20897. list = [];
  20898. me.removeListener('mouseup',addList);
  20899. return;
  20900. }
  20901. var range = me.selection.getRange();
  20902. img = range.getClosedNode();
  20903. if(!img || img.tagName != 'IMG'){
  20904. range.collapse(true).shrinkBoundary();
  20905. var start = range.startContainer;
  20906. list = domUtils.findParents(start,true,function(node){
  20907. return !domUtils.isBlockElm(node) && node.nodeType == 1;
  20908. });
  20909. //a不能加入格式刷, 并且克隆节点
  20910. for(var i=0,ci;ci=list[i];i++){
  20911. if(ci.tagName == 'A'){
  20912. list.splice(i,1);
  20913. break;
  20914. }
  20915. }
  20916. }
  20917. me.addListener('mouseup',addList);
  20918. flag = 1;
  20919. },
  20920. queryCommandState : function() {
  20921. return flag;
  20922. },
  20923. notNeedUndo : 1
  20924. };
  20925. };
  20926. // plugins/searchreplace.js
  20927. ///import core
  20928. ///commands 查找替换
  20929. ///commandsName SearchReplace
  20930. ///commandsTitle 查询替换
  20931. ///commandsDialog dialogs\searchreplace
  20932. /**
  20933. * @description 查找替换
  20934. * @author zhanyi
  20935. */
  20936. UE.plugin.register('searchreplace',function(){
  20937. var me = this;
  20938. var _blockElm = {'table':1,'tbody':1,'tr':1,'ol':1,'ul':1};
  20939. function findTextInString(textContent,opt,currentIndex){
  20940. var str = opt.searchStr;
  20941. if(opt.dir == -1){
  20942. textContent = textContent.split('').reverse().join('');
  20943. str = str.split('').reverse().join('');
  20944. currentIndex = textContent.length - currentIndex;
  20945. }
  20946. var reg = new RegExp(str,'g' + (opt.casesensitive ? '' : 'i')),match;
  20947. while(match = reg.exec(textContent)){
  20948. if(match.index >= currentIndex){
  20949. return opt.dir == -1 ? textContent.length - match.index - opt.searchStr.length : match.index;
  20950. }
  20951. }
  20952. return -1
  20953. }
  20954. function findTextBlockElm(node,currentIndex,opt){
  20955. var textContent,index,methodName = opt.all || opt.dir == 1 ? 'getNextDomNode' : 'getPreDomNode';
  20956. if(domUtils.isBody(node)){
  20957. node = node.firstChild;
  20958. }
  20959. var first = 1;
  20960. while(node){
  20961. textContent = node.nodeType == 3 ? node.nodeValue : node[browser.ie ? 'innerText' : 'textContent'];
  20962. index = findTextInString(textContent,opt,currentIndex );
  20963. first = 0;
  20964. if(index!=-1){
  20965. return {
  20966. 'node':node,
  20967. 'index':index
  20968. }
  20969. }
  20970. node = domUtils[methodName](node);
  20971. while(node && _blockElm[node.nodeName.toLowerCase()]){
  20972. node = domUtils[methodName](node,true);
  20973. }
  20974. if(node){
  20975. currentIndex = opt.dir == -1 ? (node.nodeType == 3 ? node.nodeValue : node[browser.ie ? 'innerText' : 'textContent']).length : 0;
  20976. }
  20977. }
  20978. }
  20979. function findNTextInBlockElm(node,index,str){
  20980. var currentIndex = 0,
  20981. currentNode = node.firstChild,
  20982. currentNodeLength = 0,
  20983. result;
  20984. while(currentNode){
  20985. if(currentNode.nodeType == 3){
  20986. currentNodeLength = currentNode.nodeValue.replace(/(^[\t\r\n]+)|([\t\r\n]+$)/,'').length;
  20987. currentIndex += currentNodeLength;
  20988. if(currentIndex >= index){
  20989. return {
  20990. 'node':currentNode,
  20991. 'index': currentNodeLength - (currentIndex - index)
  20992. }
  20993. }
  20994. }else if(!dtd.$empty[currentNode.tagName]){
  20995. currentNodeLength = currentNode[browser.ie ? 'innerText' : 'textContent'].replace(/(^[\t\r\n]+)|([\t\r\n]+$)/,'').length
  20996. currentIndex += currentNodeLength;
  20997. if(currentIndex >= index){
  20998. result = findNTextInBlockElm(currentNode,currentNodeLength - (currentIndex - index),str);
  20999. if(result){
  21000. return result;
  21001. }
  21002. }
  21003. }
  21004. currentNode = domUtils.getNextDomNode(currentNode);
  21005. }
  21006. }
  21007. function searchReplace(me,opt){
  21008. var rng = me.selection.getRange(),
  21009. startBlockNode,
  21010. searchStr = opt.searchStr,
  21011. span = me.document.createElement('span');
  21012. span.innerHTML = '$$ueditor_searchreplace_key$$';
  21013. rng.shrinkBoundary(true);
  21014. //判断是不是第一次选中
  21015. if(!rng.collapsed){
  21016. rng.select();
  21017. var rngText = me.selection.getText();
  21018. if(new RegExp('^' + opt.searchStr + '$',(opt.casesensitive ? '' : 'i')).test(rngText)){
  21019. if(opt.replaceStr != undefined){
  21020. replaceText(rng,opt.replaceStr);
  21021. rng.select();
  21022. return true;
  21023. }else{
  21024. rng.collapse(opt.dir == -1)
  21025. }
  21026. }
  21027. }
  21028. rng.insertNode(span);
  21029. rng.enlargeToBlockElm(true);
  21030. startBlockNode = rng.startContainer;
  21031. var currentIndex = startBlockNode[browser.ie ? 'innerText' : 'textContent'].indexOf('$$ueditor_searchreplace_key$$');
  21032. rng.setStartBefore(span);
  21033. domUtils.remove(span);
  21034. var result = findTextBlockElm(startBlockNode,currentIndex,opt);
  21035. if(result){
  21036. var rngStart = findNTextInBlockElm(result.node,result.index,searchStr);
  21037. var rngEnd = findNTextInBlockElm(result.node,result.index + searchStr.length,searchStr);
  21038. rng.setStart(rngStart.node,rngStart.index).setEnd(rngEnd.node,rngEnd.index);
  21039. if(opt.replaceStr !== undefined){
  21040. replaceText(rng,opt.replaceStr)
  21041. }
  21042. rng.select();
  21043. return true;
  21044. }else{
  21045. rng.setCursor()
  21046. }
  21047. }
  21048. function replaceText(rng,str){
  21049. str = me.document.createTextNode(str);
  21050. rng.deleteContents().insertNode(str);
  21051. }
  21052. return {
  21053. commands:{
  21054. 'searchreplace':{
  21055. execCommand:function(cmdName,opt){
  21056. utils.extend(opt,{
  21057. all : false,
  21058. casesensitive : false,
  21059. dir : 1
  21060. },true);
  21061. var num = 0;
  21062. if(opt.all){
  21063. var rng = me.selection.getRange(),
  21064. first = me.body.firstChild;
  21065. if(first && first.nodeType == 1){
  21066. rng.setStart(first,0);
  21067. rng.shrinkBoundary(true);
  21068. }else if(first.nodeType == 3){
  21069. rng.setStartBefore(first)
  21070. }
  21071. rng.collapse(true).select(true);
  21072. if(opt.replaceStr !== undefined){
  21073. me.fireEvent('saveScene');
  21074. }
  21075. while(searchReplace(this,opt)){
  21076. num++;
  21077. }
  21078. if(num){
  21079. me.fireEvent('saveScene');
  21080. }
  21081. }else{
  21082. if(opt.replaceStr !== undefined){
  21083. me.fireEvent('saveScene');
  21084. }
  21085. if(searchReplace(this,opt)){
  21086. num++
  21087. }
  21088. if(num){
  21089. me.fireEvent('saveScene');
  21090. }
  21091. }
  21092. return num;
  21093. },
  21094. notNeedUndo:1
  21095. }
  21096. }
  21097. }
  21098. });
  21099. // plugins/customstyle.js
  21100. /**
  21101. * 自定义样式
  21102. * @file
  21103. * @since 1.2.6.1
  21104. */
  21105. /**
  21106. * 根据config配置文件里“customstyle”选项的值对匹配的标签执行样式替换。
  21107. * @command customstyle
  21108. * @method execCommand
  21109. * @param { String } cmd 命令字符串
  21110. * @example
  21111. * ```javascript
  21112. * editor.execCommand( 'customstyle' );
  21113. * ```
  21114. */
  21115. UE.plugins['customstyle'] = function() {
  21116. var me = this;
  21117. me.setOpt({ 'customstyle':[
  21118. {tag:'h1',name:'tc', style:'font-size:32px;font-weight:bold;border-bottom:#ccc 2px solid;padding:0 4px 0 0;text-align:center;margin:0 0 20px 0;'},
  21119. {tag:'h1',name:'tl', style:'font-size:32px;font-weight:bold;border-bottom:#ccc 2px solid;padding:0 4px 0 0;text-align:left;margin:0 0 10px 0;'},
  21120. {tag:'span',name:'im', style:'font-size:16px;font-style:italic;font-weight:bold;line-height:18px;'},
  21121. {tag:'span',name:'hi', style:'font-size:16px;font-style:italic;font-weight:bold;color:rgb(51, 153, 204);line-height:18px;'}
  21122. ]});
  21123. me.commands['customstyle'] = {
  21124. execCommand : function(cmdName, obj) {
  21125. var me = this,
  21126. tagName = obj.tag,
  21127. node = domUtils.findParent(me.selection.getStart(), function(node) {
  21128. return node.getAttribute('label');
  21129. }, true),
  21130. range,bk,tmpObj = {};
  21131. for (var p in obj) {
  21132. if(obj[p]!==undefined)
  21133. tmpObj[p] = obj[p];
  21134. }
  21135. delete tmpObj.tag;
  21136. if (node && node.getAttribute('label') == obj.label) {
  21137. range = this.selection.getRange();
  21138. bk = range.createBookmark();
  21139. if (range.collapsed) {
  21140. //trace:1732 删掉自定义标签,要有p来回填站位
  21141. if(dtd.$block[node.tagName]){
  21142. var fillNode = me.document.createElement('p');
  21143. domUtils.moveChild(node, fillNode);
  21144. node.parentNode.insertBefore(fillNode, node);
  21145. domUtils.remove(node);
  21146. }else{
  21147. domUtils.remove(node,true);
  21148. }
  21149. } else {
  21150. var common = domUtils.getCommonAncestor(bk.start, bk.end),
  21151. nodes = domUtils.getElementsByTagName(common, tagName);
  21152. if(new RegExp(tagName,'i').test(common.tagName)){
  21153. nodes.push(common);
  21154. }
  21155. for (var i = 0,ni; ni = nodes[i++];) {
  21156. if (ni.getAttribute('label') == obj.label) {
  21157. var ps = domUtils.getPosition(ni, bk.start),pe = domUtils.getPosition(ni, bk.end);
  21158. if ((ps & domUtils.POSITION_FOLLOWING || ps & domUtils.POSITION_CONTAINS)
  21159. &&
  21160. (pe & domUtils.POSITION_PRECEDING || pe & domUtils.POSITION_CONTAINS)
  21161. )
  21162. if (dtd.$block[tagName]) {
  21163. var fillNode = me.document.createElement('p');
  21164. domUtils.moveChild(ni, fillNode);
  21165. ni.parentNode.insertBefore(fillNode, ni);
  21166. }
  21167. domUtils.remove(ni, true);
  21168. }
  21169. }
  21170. node = domUtils.findParent(common, function(node) {
  21171. return node.getAttribute('label') == obj.label;
  21172. }, true);
  21173. if (node) {
  21174. domUtils.remove(node, true);
  21175. }
  21176. }
  21177. range.moveToBookmark(bk).select();
  21178. } else {
  21179. if (dtd.$block[tagName]) {
  21180. this.execCommand('paragraph', tagName, tmpObj,'customstyle');
  21181. range = me.selection.getRange();
  21182. if (!range.collapsed) {
  21183. range.collapse();
  21184. node = domUtils.findParent(me.selection.getStart(), function(node) {
  21185. return node.getAttribute('label') == obj.label;
  21186. }, true);
  21187. var pNode = me.document.createElement('p');
  21188. domUtils.insertAfter(node, pNode);
  21189. domUtils.fillNode(me.document, pNode);
  21190. range.setStart(pNode, 0).setCursor();
  21191. }
  21192. } else {
  21193. range = me.selection.getRange();
  21194. if (range.collapsed) {
  21195. node = me.document.createElement(tagName);
  21196. domUtils.setAttributes(node, tmpObj);
  21197. range.insertNode(node).setStart(node, 0).setCursor();
  21198. return;
  21199. }
  21200. bk = range.createBookmark();
  21201. range.applyInlineStyle(tagName, tmpObj).moveToBookmark(bk).select();
  21202. }
  21203. }
  21204. },
  21205. queryCommandValue : function() {
  21206. var parent = domUtils.filterNodeList(
  21207. this.selection.getStartElementPath(),
  21208. function(node){return node.getAttribute('label')}
  21209. );
  21210. return parent ? parent.getAttribute('label') : '';
  21211. }
  21212. };
  21213. //当去掉customstyle是,如果是块元素,用p代替
  21214. me.addListener('keyup', function(type, evt) {
  21215. var keyCode = evt.keyCode || evt.which;
  21216. if (keyCode == 32 || keyCode == 13) {
  21217. var range = me.selection.getRange();
  21218. if (range.collapsed) {
  21219. var node = domUtils.findParent(me.selection.getStart(), function(node) {
  21220. return node.getAttribute('label');
  21221. }, true);
  21222. if (node && dtd.$block[node.tagName] && domUtils.isEmptyNode(node)) {
  21223. var p = me.document.createElement('p');
  21224. domUtils.insertAfter(node, p);
  21225. domUtils.fillNode(me.document, p);
  21226. domUtils.remove(node);
  21227. range.setStart(p, 0).setCursor();
  21228. }
  21229. }
  21230. }
  21231. });
  21232. };
  21233. // plugins/catchremoteimage.js
  21234. ///import core
  21235. ///commands 远程图片抓取
  21236. ///commandsName catchRemoteImage,catchremoteimageenable
  21237. ///commandsTitle 远程图片抓取
  21238. /**
  21239. * 远程图片抓取,当开启本插件时所有不符合本地域名的图片都将被抓取成为本地服务器上的图片
  21240. */
  21241. UE.plugins['catchremoteimage'] = function () {
  21242. var me = this,
  21243. ajax = UE.ajax;
  21244. /* 设置默认值 */
  21245. if (me.options.catchRemoteImageEnable === false) return;
  21246. me.setOpt({
  21247. catchRemoteImageEnable: false
  21248. });
  21249. me.addListener("afterpaste", function () {
  21250. me.fireEvent("catchRemoteImage");
  21251. });
  21252. me.addListener("catchRemoteImage", function () {
  21253. var catcherLocalDomain = me.getOpt('catcherLocalDomain'),
  21254. catcherActionUrl = me.getActionUrl(me.getOpt('catcherActionName')),
  21255. catcherUrlPrefix = me.getOpt('catcherUrlPrefix'),
  21256. catcherFieldName = me.getOpt('catcherFieldName');
  21257. var remoteImages = [],
  21258. imgs = domUtils.getElementsByTagName(me.document, "img"),
  21259. test = function (src, urls) {
  21260. if (src.indexOf(location.host) != -1 || /(^\.)|(^\/)/.test(src)) {
  21261. return true;
  21262. }
  21263. if (urls) {
  21264. for (var j = 0, url; url = urls[j++];) {
  21265. if (src.indexOf(url) !== -1) {
  21266. return true;
  21267. }
  21268. }
  21269. }
  21270. return false;
  21271. };
  21272. for (var i = 0, ci; ci = imgs[i++];) {
  21273. if (ci.getAttribute("word_img")) {
  21274. continue;
  21275. }
  21276. var src = ci.getAttribute("_src") || ci.src || "";
  21277. if (/^(https?|ftp):/i.test(src) && !test(src, catcherLocalDomain)) {
  21278. remoteImages.push(src);
  21279. }
  21280. }
  21281. if (remoteImages.length) {
  21282. catchremoteimage(remoteImages, {
  21283. //成功抓取
  21284. success: function (r) {
  21285. try {
  21286. var info = r.state !== undefined ? r:eval("(" + r.responseText + ")");
  21287. } catch (e) {
  21288. return;
  21289. }
  21290. /* 获取源路径和新路径 */
  21291. var i, j, ci, cj, oldSrc, newSrc, list = info.list;
  21292. for (i = 0; ci = imgs[i++];) {
  21293. oldSrc = ci.getAttribute("_src") || ci.src || "";
  21294. for (j = 0; cj = list[j++];) {
  21295. if (oldSrc == cj.source && cj.state == "SUCCESS") { //抓取失败时不做替换处理
  21296. newSrc = catcherUrlPrefix + cj.url;
  21297. domUtils.setAttributes(ci, {
  21298. "src": newSrc,
  21299. "_src": newSrc
  21300. });
  21301. break;
  21302. }
  21303. }
  21304. }
  21305. me.fireEvent('catchremotesuccess')
  21306. },
  21307. //回调失败,本次请求超时
  21308. error: function () {
  21309. me.fireEvent("catchremoteerror");
  21310. }
  21311. });
  21312. }
  21313. function catchremoteimage(imgs, callbacks) {
  21314. var params = utils.serializeParam(me.queryCommandValue('serverparam')) || '',
  21315. url = utils.formatUrl(catcherActionUrl + (catcherActionUrl.indexOf('?') == -1 ? '?':'&') + params),
  21316. isJsonp = utils.isCrossDomainUrl(url),
  21317. opt = {
  21318. 'method': 'POST',
  21319. 'dataType': isJsonp ? 'jsonp':'',
  21320. 'timeout': 60000, //单位:毫秒,回调请求超时设置。目标用户如果网速不是很快的话此处建议设置一个较大的数值
  21321. 'onsuccess': callbacks["success"],
  21322. 'onerror': callbacks["error"]
  21323. };
  21324. opt[catcherFieldName] = imgs;
  21325. ajax.request(url, opt);
  21326. }
  21327. });
  21328. };
  21329. // plugins/snapscreen.js
  21330. /**
  21331. * 截屏插件,为UEditor提供插入支持
  21332. * @file
  21333. * @since 1.4.2
  21334. */
  21335. UE.plugin.register('snapscreen', function (){
  21336. var me = this;
  21337. var snapplugin;
  21338. function getLocation(url){
  21339. var search,
  21340. a = document.createElement('a'),
  21341. params = utils.serializeParam(me.queryCommandValue('serverparam')) || '';
  21342. a.href = url;
  21343. if (browser.ie) {
  21344. a.href = a.href;
  21345. }
  21346. search = a.search;
  21347. if (params) {
  21348. search = search + (search.indexOf('?') == -1 ? '?':'&')+ params;
  21349. search = search.replace(/[&]+/ig, '&');
  21350. }
  21351. return {
  21352. 'port': a.port,
  21353. 'hostname': a.hostname,
  21354. 'path': a.pathname + search || + a.hash
  21355. }
  21356. }
  21357. return {
  21358. commands:{
  21359. /**
  21360. * 字体背景颜色
  21361. * @command snapscreen
  21362. * @method execCommand
  21363. * @param { String } cmd 命令字符串
  21364. * @example
  21365. * ```javascript
  21366. * editor.execCommand('snapscreen');
  21367. * ```
  21368. */
  21369. 'snapscreen':{
  21370. execCommand:function (cmd) {
  21371. var url, local, res;
  21372. var lang = me.getLang("snapScreen_plugin");
  21373. if(!snapplugin){
  21374. var container = me.container;
  21375. var doc = me.container.ownerDocument || me.container.document;
  21376. snapplugin = doc.createElement("object");
  21377. try{snapplugin.type = "application/x-pluginbaidusnap";}catch(e){
  21378. return;
  21379. }
  21380. snapplugin.style.cssText = "position:absolute;left:-9999px;width:0;height:0;";
  21381. snapplugin.setAttribute("width","0");
  21382. snapplugin.setAttribute("height","0");
  21383. container.appendChild(snapplugin);
  21384. }
  21385. function onSuccess(rs){
  21386. try{
  21387. rs = eval("("+ rs +")");
  21388. if(rs.state == 'SUCCESS'){
  21389. var opt = me.options;
  21390. me.execCommand('insertimage', {
  21391. src: opt.snapscreenUrlPrefix + rs.url,
  21392. _src: opt.snapscreenUrlPrefix + rs.url,
  21393. alt: rs.title || '',
  21394. floatStyle: opt.snapscreenImgAlign
  21395. });
  21396. } else {
  21397. alert(rs.state);
  21398. }
  21399. }catch(e){
  21400. alert(lang.callBackErrorMsg);
  21401. }
  21402. }
  21403. url = me.getActionUrl(me.getOpt('snapscreenActionName'));
  21404. local = getLocation(url);
  21405. setTimeout(function () {
  21406. try{
  21407. res =snapplugin.saveSnapshot(local.hostname, local.path, local.port);
  21408. }catch(e){
  21409. me.ui._dialogs['snapscreenDialog'].open();
  21410. return;
  21411. }
  21412. onSuccess(res);
  21413. }, 50);
  21414. },
  21415. queryCommandState: function(){
  21416. return (navigator.userAgent.indexOf("Windows",0) != -1) ? 0:-1;
  21417. }
  21418. }
  21419. }
  21420. }
  21421. });
  21422. // plugins/insertparagraph.js
  21423. /**
  21424. * 插入段落
  21425. * @file
  21426. * @since 1.2.6.1
  21427. */
  21428. /**
  21429. * 插入段落
  21430. * @command insertparagraph
  21431. * @method execCommand
  21432. * @param { String } cmd 命令字符串
  21433. * @example
  21434. * ```javascript
  21435. * //editor是编辑器实例
  21436. * editor.execCommand( 'insertparagraph' );
  21437. * ```
  21438. */
  21439. UE.commands['insertparagraph'] = {
  21440. execCommand : function( cmdName,front) {
  21441. var me = this,
  21442. range = me.selection.getRange(),
  21443. start = range.startContainer,tmpNode;
  21444. while(start ){
  21445. if(domUtils.isBody(start)){
  21446. break;
  21447. }
  21448. tmpNode = start;
  21449. start = start.parentNode;
  21450. }
  21451. if(tmpNode){
  21452. var p = me.document.createElement('p');
  21453. if(front){
  21454. tmpNode.parentNode.insertBefore(p,tmpNode)
  21455. }else{
  21456. tmpNode.parentNode.insertBefore(p,tmpNode.nextSibling)
  21457. }
  21458. domUtils.fillNode(me.document,p);
  21459. range.setStart(p,0).setCursor(false,true);
  21460. }
  21461. }
  21462. };
  21463. // plugins/webapp.js
  21464. /**
  21465. * 百度应用
  21466. * @file
  21467. * @since 1.2.6.1
  21468. */
  21469. /**
  21470. * 插入百度应用
  21471. * @command webapp
  21472. * @method execCommand
  21473. * @remind 需要百度APPKey
  21474. * @remind 百度应用主页: <a href="http://app.baidu.com/" target="_blank">http://app.baidu.com/</a>
  21475. * @param { Object } appOptions 应用所需的参数项, 支持的key有: title=>应用标题, width=>应用容器宽度,
  21476. * height=>应用容器高度,logo=>应用logo,url=>应用地址
  21477. * @example
  21478. * ```javascript
  21479. * //editor是编辑器实例
  21480. * //在编辑器里插入一个“植物大战僵尸”的APP
  21481. * editor.execCommand( 'webapp' , {
  21482. * title: '植物大战僵尸',
  21483. * width: 560,
  21484. * height: 465,
  21485. * logo: '应用展示的图片',
  21486. * url: '百度应用的地址'
  21487. * } );
  21488. * ```
  21489. */
  21490. //UE.plugins['webapp'] = function () {
  21491. // var me = this;
  21492. // function createInsertStr( obj, toIframe, addParagraph ) {
  21493. // return !toIframe ?
  21494. // (addParagraph ? '<p>' : '') + '<img title="'+obj.title+'" width="' + obj.width + '" height="' + obj.height + '"' +
  21495. // ' src="' + me.options.UEDITOR_HOME_URL + 'themes/default/images/spacer.gif" style="background:url(' + obj.logo+') no-repeat center center; border:1px solid gray;" class="edui-faked-webapp" _url="' + obj.url + '" />' +
  21496. // (addParagraph ? '</p>' : '')
  21497. // :
  21498. // '<iframe class="edui-faked-webapp" title="'+obj.title+'" width="' + obj.width + '" height="' + obj.height + '" scrolling="no" frameborder="0" src="' + obj.url + '" logo_url = '+obj.logo+'></iframe>';
  21499. // }
  21500. //
  21501. // function switchImgAndIframe( img2frame ) {
  21502. // var tmpdiv,
  21503. // nodes = domUtils.getElementsByTagName( me.document, !img2frame ? "iframe" : "img" );
  21504. // for ( var i = 0, node; node = nodes[i++]; ) {
  21505. // if ( node.className != "edui-faked-webapp" ){
  21506. // continue;
  21507. // }
  21508. // tmpdiv = me.document.createElement( "div" );
  21509. // tmpdiv.innerHTML = createInsertStr( img2frame ? {url:node.getAttribute( "_url" ), width:node.width, height:node.height,title:node.title,logo:node.style.backgroundImage.replace("url(","").replace(")","")} : {url:node.getAttribute( "src", 2 ),title:node.title, width:node.width, height:node.height,logo:node.getAttribute("logo_url")}, img2frame ? true : false,false );
  21510. // node.parentNode.replaceChild( tmpdiv.firstChild, node );
  21511. // }
  21512. // }
  21513. //
  21514. // me.addListener( "beforegetcontent", function () {
  21515. // switchImgAndIframe( true );
  21516. // } );
  21517. // me.addListener( 'aftersetcontent', function () {
  21518. // switchImgAndIframe( false );
  21519. // } );
  21520. // me.addListener( 'aftergetcontent', function ( cmdName ) {
  21521. // if ( cmdName == 'aftergetcontent' && me.queryCommandState( 'source' ) ){
  21522. // return;
  21523. // }
  21524. // switchImgAndIframe( false );
  21525. // } );
  21526. //
  21527. // me.commands['webapp'] = {
  21528. // execCommand:function ( cmd, obj ) {
  21529. // me.execCommand( "inserthtml", createInsertStr( obj, false,true ) );
  21530. // }
  21531. // };
  21532. //};
  21533. UE.plugin.register('webapp', function (){
  21534. var me = this;
  21535. function createInsertStr(obj,toEmbed){
  21536. return !toEmbed ?
  21537. '<img title="'+obj.title+'" width="' + obj.width + '" height="' + obj.height + '"' +
  21538. ' src="' + me.options.UEDITOR_HOME_URL + 'themes/default/images/spacer.gif" _logo_url="'+obj.logo+'" style="background:url(' + obj.logo
  21539. +') no-repeat center center; border:1px solid gray;" class="edui-faked-webapp" _url="' + obj.url + '" ' +
  21540. (obj.align && !obj.cssfloat? 'align="' + obj.align + '"' : '') +
  21541. (obj.cssfloat ? 'style="float:' + obj.cssfloat + '"' : '') +
  21542. '/>'
  21543. :
  21544. '<iframe class="edui-faked-webapp" title="'+obj.title+'" ' +
  21545. (obj.align && !obj.cssfloat? 'align="' + obj.align + '"' : '') +
  21546. (obj.cssfloat ? 'style="float:' + obj.cssfloat + '"' : '') +
  21547. 'width="' + obj.width + '" height="' + obj.height + '" scrolling="no" frameborder="0" src="' + obj.url + '" logo_url = "'+obj.logo+'"></iframe>'
  21548. }
  21549. return {
  21550. outputRule: function(root){
  21551. utils.each(root.getNodesByTagName('img'),function(node){
  21552. var html;
  21553. if(node.getAttr('class') == 'edui-faked-webapp'){
  21554. html = createInsertStr({
  21555. title:node.getAttr('title'),
  21556. 'width':node.getAttr('width'),
  21557. 'height':node.getAttr('height'),
  21558. 'align':node.getAttr('align'),
  21559. 'cssfloat':node.getStyle('float'),
  21560. 'url':node.getAttr("_url"),
  21561. 'logo':node.getAttr('_logo_url')
  21562. },true);
  21563. var embed = UE.uNode.createElement(html);
  21564. node.parentNode.replaceChild(embed,node);
  21565. }
  21566. })
  21567. },
  21568. inputRule:function(root){
  21569. utils.each(root.getNodesByTagName('iframe'),function(node){
  21570. if(node.getAttr('class') == 'edui-faked-webapp'){
  21571. var img = UE.uNode.createElement(createInsertStr({
  21572. title:node.getAttr('title'),
  21573. 'width':node.getAttr('width'),
  21574. 'height':node.getAttr('height'),
  21575. 'align':node.getAttr('align'),
  21576. 'cssfloat':node.getStyle('float'),
  21577. 'url':node.getAttr("src"),
  21578. 'logo':node.getAttr('logo_url')
  21579. }));
  21580. node.parentNode.replaceChild(img,node);
  21581. }
  21582. })
  21583. },
  21584. commands:{
  21585. /**
  21586. * 插入百度应用
  21587. * @command webapp
  21588. * @method execCommand
  21589. * @remind 需要百度APPKey
  21590. * @remind 百度应用主页: <a href="http://app.baidu.com/" target="_blank">http://app.baidu.com/</a>
  21591. * @param { Object } appOptions 应用所需的参数项, 支持的key有: title=>应用标题, width=>应用容器宽度,
  21592. * height=>应用容器高度,logo=>应用logo,url=>应用地址
  21593. * @example
  21594. * ```javascript
  21595. * //editor是编辑器实例
  21596. * //在编辑器里插入一个“植物大战僵尸”的APP
  21597. * editor.execCommand( 'webapp' , {
  21598. * title: '植物大战僵尸',
  21599. * width: 560,
  21600. * height: 465,
  21601. * logo: '应用展示的图片',
  21602. * url: '百度应用的地址'
  21603. * } );
  21604. * ```
  21605. */
  21606. 'webapp':{
  21607. execCommand:function (cmd, obj) {
  21608. var me = this,
  21609. str = createInsertStr(utils.extend(obj,{
  21610. align:'none'
  21611. }), false);
  21612. me.execCommand("inserthtml",str);
  21613. },
  21614. queryCommandState:function () {
  21615. var me = this,
  21616. img = me.selection.getRange().getClosedNode(),
  21617. flag = img && (img.className == "edui-faked-webapp");
  21618. return flag ? 1 : 0;
  21619. }
  21620. }
  21621. }
  21622. }
  21623. });
  21624. // plugins/template.js
  21625. ///import core
  21626. ///import plugins\inserthtml.js
  21627. ///import plugins\cleardoc.js
  21628. ///commands 模板
  21629. ///commandsName template
  21630. ///commandsTitle 模板
  21631. ///commandsDialog dialogs\template
  21632. UE.plugins['template'] = function () {
  21633. UE.commands['template'] = {
  21634. execCommand:function (cmd, obj) {
  21635. obj.html && this.execCommand("inserthtml", obj.html);
  21636. }
  21637. };
  21638. this.addListener("click", function (type, evt) {
  21639. var el = evt.target || evt.srcElement,
  21640. range = this.selection.getRange();
  21641. var tnode = domUtils.findParent(el, function (node) {
  21642. if (node.className && domUtils.hasClass(node, "ue_t")) {
  21643. return node;
  21644. }
  21645. }, true);
  21646. tnode && range.selectNode(tnode).shrinkBoundary().select();
  21647. });
  21648. this.addListener("keydown", function (type, evt) {
  21649. var range = this.selection.getRange();
  21650. if (!range.collapsed) {
  21651. if (!evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) {
  21652. var tnode = domUtils.findParent(range.startContainer, function (node) {
  21653. if (node.className && domUtils.hasClass(node, "ue_t")) {
  21654. return node;
  21655. }
  21656. }, true);
  21657. if (tnode) {
  21658. domUtils.removeClasses(tnode, ["ue_t"]);
  21659. }
  21660. }
  21661. }
  21662. });
  21663. };
  21664. // plugins/music.js
  21665. /**
  21666. * 插入音乐命令
  21667. * @file
  21668. */
  21669. UE.plugin.register('music', function (){
  21670. var me = this;
  21671. function creatInsertStr(url,width,height,align,cssfloat,toEmbed){
  21672. return !toEmbed ?
  21673. '<img ' +
  21674. (align && !cssfloat? 'align="' + align + '"' : '') +
  21675. (cssfloat ? 'style="float:' + cssfloat + '"' : '') +
  21676. ' width="'+ width +'" height="' + height + '" _url="'+url+'" class="edui-faked-music"' +
  21677. ' src="'+me.options.langPath+me.options.lang+'/images/music.png" />'
  21678. :
  21679. '<embed type="application/x-shockwave-flash" class="edui-faked-music" pluginspage="http://www.macromedia.com/go/getflashplayer"' +
  21680. ' src="' + url + '" width="' + width + '" height="' + height + '" '+ (align && !cssfloat? 'align="' + align + '"' : '') +
  21681. (cssfloat ? 'style="float:' + cssfloat + '"' : '') +
  21682. ' wmode="transparent" play="true" loop="false" menu="false" allowscriptaccess="never" allowfullscreen="true" >';
  21683. }
  21684. return {
  21685. outputRule: function(root){
  21686. utils.each(root.getNodesByTagName('img'),function(node){
  21687. var html;
  21688. if(node.getAttr('class') == 'edui-faked-music'){
  21689. var cssfloat = node.getStyle('float');
  21690. var align = node.getAttr('align');
  21691. html = creatInsertStr(node.getAttr("_url"), node.getAttr('width'), node.getAttr('height'), align, cssfloat, true);
  21692. var embed = UE.uNode.createElement(html);
  21693. node.parentNode.replaceChild(embed,node);
  21694. }
  21695. })
  21696. },
  21697. inputRule:function(root){
  21698. utils.each(root.getNodesByTagName('embed'),function(node){
  21699. if(node.getAttr('class') == 'edui-faked-music'){
  21700. var cssfloat = node.getStyle('float');
  21701. var align = node.getAttr('align');
  21702. html = creatInsertStr(node.getAttr("src"), node.getAttr('width'), node.getAttr('height'), align, cssfloat,false);
  21703. var img = UE.uNode.createElement(html);
  21704. node.parentNode.replaceChild(img,node);
  21705. }
  21706. })
  21707. },
  21708. commands:{
  21709. /**
  21710. * 插入音乐
  21711. * @command music
  21712. * @method execCommand
  21713. * @param { Object } musicOptions 插入音乐的参数项, 支持的key有: url=>音乐地址;
  21714. * width=>音乐容器宽度;height=>音乐容器高度;align=>音乐文件的对齐方式, 可选值有: left, center, right, none
  21715. * @example
  21716. * ```javascript
  21717. * //editor是编辑器实例
  21718. * //在编辑器里插入一个“植物大战僵尸”的APP
  21719. * editor.execCommand( 'music' , {
  21720. * width: 400,
  21721. * height: 95,
  21722. * align: "center",
  21723. * url: "音乐地址"
  21724. * } );
  21725. * ```
  21726. */
  21727. 'music':{
  21728. execCommand:function (cmd, musicObj) {
  21729. var me = this,
  21730. str = creatInsertStr(musicObj.url, musicObj.width || 400, musicObj.height || 95, "none", false);
  21731. me.execCommand("inserthtml",str);
  21732. },
  21733. queryCommandState:function () {
  21734. var me = this,
  21735. img = me.selection.getRange().getClosedNode(),
  21736. flag = img && (img.className == "edui-faked-music");
  21737. return flag ? 1 : 0;
  21738. }
  21739. }
  21740. }
  21741. }
  21742. });
  21743. // plugins/autoupload.js
  21744. /**
  21745. * @description
  21746. * 1.拖放文件到编辑区域,自动上传并插入到选区
  21747. * 2.插入粘贴板的图片,自动上传并插入到选区
  21748. * @author Jinqn
  21749. * @date 2013-10-14
  21750. */
  21751. UE.plugin.register('autoupload', function (){
  21752. function sendAndInsertFile(file, editor) {
  21753. var me = editor;
  21754. //模拟数据
  21755. var fieldName, urlPrefix, maxSize, allowFiles, actionUrl,
  21756. loadingHtml, errorHandler, successHandler,
  21757. filetype = /image\/\w+/i.test(file.type) ? 'image':'file',
  21758. loadingId = 'loading_' + (+new Date()).toString(36);
  21759. fieldName = me.getOpt(filetype + 'FieldName');
  21760. urlPrefix = me.getOpt(filetype + 'UrlPrefix');
  21761. maxSize = me.getOpt(filetype + 'MaxSize');
  21762. allowFiles = me.getOpt(filetype + 'AllowFiles');
  21763. actionUrl = me.getActionUrl(me.getOpt(filetype + 'ActionName'));
  21764. errorHandler = function(title) {
  21765. var loader = me.document.getElementById(loadingId);
  21766. loader && domUtils.remove(loader);
  21767. me.fireEvent('showmessage', {
  21768. 'id': loadingId,
  21769. 'content': title,
  21770. 'type': 'error',
  21771. 'timeout': 4000
  21772. });
  21773. };
  21774. if (filetype == 'image') {
  21775. loadingHtml = '<img class="loadingclass" id="' + loadingId + '" src="' +
  21776. me.options.themePath + me.options.theme +
  21777. '/images/spacer.gif" title="' + (me.getLang('autoupload.loading') || '') + '" >';
  21778. successHandler = function(data) {
  21779. var link = urlPrefix + data.url,
  21780. loader = me.document.getElementById(loadingId);
  21781. if (loader) {
  21782. loader.setAttribute('src', link);
  21783. loader.setAttribute('_src', link);
  21784. loader.setAttribute('title', data.title || '');
  21785. loader.setAttribute('alt', data.original || '');
  21786. loader.removeAttribute('id');
  21787. domUtils.removeClasses(loader, 'loadingclass');
  21788. }
  21789. };
  21790. } else {
  21791. loadingHtml = '<p>' +
  21792. '<img class="loadingclass" id="' + loadingId + '" src="' +
  21793. me.options.themePath + me.options.theme +
  21794. '/images/spacer.gif" title="' + (me.getLang('autoupload.loading') || '') + '" >' +
  21795. '</p>';
  21796. successHandler = function(data) {
  21797. var link = urlPrefix + data.url,
  21798. loader = me.document.getElementById(loadingId);
  21799. var rng = me.selection.getRange(),
  21800. bk = rng.createBookmark();
  21801. rng.selectNode(loader).select();
  21802. me.execCommand('insertfile', {'url': link});
  21803. rng.moveToBookmark(bk).select();
  21804. };
  21805. }
  21806. /* 插入loading的占位符 */
  21807. me.execCommand('inserthtml', loadingHtml);
  21808. /* 判断后端配置是否没有加载成功 */
  21809. if (!me.getOpt(filetype + 'ActionName')) {
  21810. errorHandler(me.getLang('autoupload.errorLoadConfig'));
  21811. return;
  21812. }
  21813. /* 判断文件大小是否超出限制 */
  21814. if(file.size > maxSize) {
  21815. errorHandler(me.getLang('autoupload.exceedSizeError'));
  21816. return;
  21817. }
  21818. /* 判断文件格式是否超出允许 */
  21819. var fileext = file.name ? file.name.substr(file.name.lastIndexOf('.')):'';
  21820. if ((fileext && filetype != 'image') || (allowFiles && (allowFiles.join('') + '.').indexOf(fileext.toLowerCase() + '.') == -1)) {
  21821. errorHandler(me.getLang('autoupload.exceedTypeError'));
  21822. return;
  21823. }
  21824. /* 创建Ajax并提交 */
  21825. var xhr = new XMLHttpRequest(),
  21826. fd = new FormData(),
  21827. params = utils.serializeParam(me.queryCommandValue('serverparam')) || '',
  21828. url = utils.formatUrl(actionUrl + (actionUrl.indexOf('?') == -1 ? '?':'&') + params);
  21829. fd.append(fieldName, file, file.name || ('blob.' + file.type.substr('image/'.length)));
  21830. fd.append('type', 'ajax');
  21831. xhr.open("post", url, true);
  21832. xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
  21833. xhr.addEventListener('load', function (e) {
  21834. try{
  21835. var json = (new Function("return " + utils.trim(e.target.response)))();
  21836. if (json.state == 'SUCCESS' && json.url) {
  21837. successHandler(json);
  21838. } else {
  21839. errorHandler(json.state);
  21840. }
  21841. }catch(er){
  21842. errorHandler(me.getLang('autoupload.loadError'));
  21843. }
  21844. });
  21845. xhr.send(fd);
  21846. }
  21847. function getPasteImage(e){
  21848. return e.clipboardData && e.clipboardData.items && e.clipboardData.items.length == 1 && /^image\//.test(e.clipboardData.items[0].type) ? e.clipboardData.items:null;
  21849. }
  21850. function getDropImage(e){
  21851. return e.dataTransfer && e.dataTransfer.files ? e.dataTransfer.files:null;
  21852. }
  21853. return {
  21854. outputRule: function(root){
  21855. utils.each(root.getNodesByTagName('img'),function(n){
  21856. if (/\b(loaderrorclass)|(bloaderrorclass)\b/.test(n.getAttr('class'))) {
  21857. n.parentNode.removeChild(n);
  21858. }
  21859. });
  21860. utils.each(root.getNodesByTagName('p'),function(n){
  21861. if (/\bloadpara\b/.test(n.getAttr('class'))) {
  21862. n.parentNode.removeChild(n);
  21863. }
  21864. });
  21865. },
  21866. bindEvents:{
  21867. //插入粘贴板的图片,拖放插入图片
  21868. 'ready':function(e){
  21869. var me = this;
  21870. if(window.FormData && window.FileReader) {
  21871. domUtils.on(me.body, 'paste drop', function(e){
  21872. var hasImg = false,
  21873. items;
  21874. //获取粘贴板文件列表或者拖放文件列表
  21875. items = e.type == 'paste' ? getPasteImage(e):getDropImage(e);
  21876. if(items){
  21877. var len = items.length,
  21878. file;
  21879. while (len--){
  21880. file = items[len];
  21881. if(file.getAsFile) file = file.getAsFile();
  21882. if(file && file.size > 0) {
  21883. sendAndInsertFile(file, me);
  21884. hasImg = true;
  21885. }
  21886. }
  21887. hasImg && e.preventDefault();
  21888. }
  21889. });
  21890. //取消拖放图片时出现的文字光标位置提示
  21891. domUtils.on(me.body, 'dragover', function (e) {
  21892. if(e.dataTransfer.types[0] == 'Files') {
  21893. e.preventDefault();
  21894. }
  21895. });
  21896. //设置loading的样式
  21897. utils.cssRule('loading',
  21898. '.loadingclass{display:inline-block;cursor:default;background: url(\''
  21899. + this.options.themePath
  21900. + this.options.theme +'/images/loading.gif\') no-repeat center center transparent;border:1px solid #cccccc;margin-left:1px;height: 22px;width: 22px;}\n' +
  21901. '.loaderrorclass{display:inline-block;cursor:default;background: url(\''
  21902. + this.options.themePath
  21903. + this.options.theme +'/images/loaderror.png\') no-repeat center center transparent;border:1px solid #cccccc;margin-right:1px;height: 22px;width: 22px;' +
  21904. '}',
  21905. this.document);
  21906. }
  21907. }
  21908. }
  21909. }
  21910. });
  21911. // plugins/autosave.js
  21912. UE.plugin.register('autosave', function (){
  21913. var me = this,
  21914. //无限循环保护
  21915. lastSaveTime = new Date(),
  21916. //最小保存间隔时间
  21917. MIN_TIME = 20,
  21918. //auto save key
  21919. saveKey = null;
  21920. function save ( editor ) {
  21921. var saveData;
  21922. if ( new Date() - lastSaveTime < MIN_TIME ) {
  21923. return;
  21924. }
  21925. if ( !editor.hasContents() ) {
  21926. //这里不能调用命令来删除, 会造成事件死循环
  21927. saveKey && me.removePreferences( saveKey );
  21928. return;
  21929. }
  21930. lastSaveTime = new Date();
  21931. editor._saveFlag = null;
  21932. saveData = me.body.innerHTML;
  21933. if ( editor.fireEvent( "beforeautosave", {
  21934. content: saveData
  21935. } ) === false ) {
  21936. return;
  21937. }
  21938. me.setPreferences( saveKey, saveData );
  21939. editor.fireEvent( "afterautosave", {
  21940. content: saveData
  21941. } );
  21942. }
  21943. return {
  21944. defaultOptions: {
  21945. //默认间隔时间
  21946. saveInterval: 500
  21947. },
  21948. bindEvents:{
  21949. 'ready':function(){
  21950. var _suffix = "-drafts-data",
  21951. key = null;
  21952. if ( me.key ) {
  21953. key = me.key + _suffix;
  21954. } else {
  21955. key = ( me.container.parentNode.id || 'ue-common' ) + _suffix;
  21956. }
  21957. //页面地址+编辑器ID 保持唯一
  21958. saveKey = ( location.protocol + location.host + location.pathname ).replace( /[.:\/]/g, '_' ) + key;
  21959. },
  21960. 'contentchange': function () {
  21961. if ( !saveKey ) {
  21962. return;
  21963. }
  21964. if ( me._saveFlag ) {
  21965. window.clearTimeout( me._saveFlag );
  21966. }
  21967. if ( me.options.saveInterval > 0 ) {
  21968. me._saveFlag = window.setTimeout( function () {
  21969. save( me );
  21970. }, me.options.saveInterval );
  21971. } else {
  21972. save(me);
  21973. }
  21974. }
  21975. },
  21976. commands:{
  21977. 'clearlocaldata':{
  21978. execCommand:function (cmd, name) {
  21979. if ( saveKey && me.getPreferences( saveKey ) ) {
  21980. me.removePreferences( saveKey )
  21981. }
  21982. },
  21983. notNeedUndo: true,
  21984. ignoreContentChange:true
  21985. },
  21986. 'getlocaldata':{
  21987. execCommand:function (cmd, name) {
  21988. return saveKey ? me.getPreferences( saveKey ) || '' : '';
  21989. },
  21990. notNeedUndo: true,
  21991. ignoreContentChange:true
  21992. },
  21993. 'drafts':{
  21994. execCommand:function (cmd, name) {
  21995. if ( saveKey ) {
  21996. me.body.innerHTML = me.getPreferences( saveKey ) || '<p>'+domUtils.fillHtml+'</p>';
  21997. me.focus(true);
  21998. }
  21999. },
  22000. queryCommandState: function () {
  22001. return saveKey ? ( me.getPreferences( saveKey ) === null ? -1 : 0 ) : -1;
  22002. },
  22003. notNeedUndo: true,
  22004. ignoreContentChange:true
  22005. }
  22006. }
  22007. }
  22008. });
  22009. // plugins/charts.js
  22010. UE.plugin.register('charts', function (){
  22011. var me = this;
  22012. return {
  22013. bindEvents: {
  22014. 'chartserror': function () {
  22015. }
  22016. },
  22017. commands:{
  22018. 'charts': {
  22019. execCommand: function ( cmd, data ) {
  22020. var tableNode = domUtils.findParentByTagName(this.selection.getRange().startContainer, 'table', true),
  22021. flagText = [],
  22022. config = {};
  22023. if ( !tableNode ) {
  22024. return false;
  22025. }
  22026. if ( !validData( tableNode ) ) {
  22027. me.fireEvent( "chartserror" );
  22028. return false;
  22029. }
  22030. config.title = data.title || '';
  22031. config.subTitle = data.subTitle || '';
  22032. config.xTitle = data.xTitle || '';
  22033. config.yTitle = data.yTitle || '';
  22034. config.suffix = data.suffix || '';
  22035. config.tip = data.tip || '';
  22036. //数据对齐方式
  22037. config.dataFormat = data.tableDataFormat || '';
  22038. //图表类型
  22039. config.chartType = data.chartType || 0;
  22040. for ( var key in config ) {
  22041. if ( !config.hasOwnProperty( key ) ) {
  22042. continue;
  22043. }
  22044. flagText.push( key+":"+config[ key ] );
  22045. }
  22046. tableNode.setAttribute( "data-chart", flagText.join( ";" ) );
  22047. domUtils.addClass( tableNode, "edui-charts-table" );
  22048. },
  22049. queryCommandState: function ( cmd, name ) {
  22050. var tableNode = domUtils.findParentByTagName(this.selection.getRange().startContainer, 'table', true);
  22051. return tableNode && validData( tableNode ) ? 0 : -1;
  22052. }
  22053. }
  22054. },
  22055. inputRule:function(root){
  22056. utils.each(root.getNodesByTagName('table'),function( tableNode ){
  22057. if ( tableNode.getAttr("data-chart") !== undefined ) {
  22058. tableNode.setAttr("style");
  22059. }
  22060. })
  22061. },
  22062. outputRule:function(root){
  22063. utils.each(root.getNodesByTagName('table'),function( tableNode ){
  22064. if ( tableNode.getAttr("data-chart") !== undefined ) {
  22065. tableNode.setAttr("style", "display: none;");
  22066. }
  22067. })
  22068. }
  22069. }
  22070. function validData ( table ) {
  22071. var firstRows = null,
  22072. cellCount = 0;
  22073. //行数不够
  22074. if ( table.rows.length < 2 ) {
  22075. return false;
  22076. }
  22077. //列数不够
  22078. if ( table.rows[0].cells.length < 2 ) {
  22079. return false;
  22080. }
  22081. //第一行所有cell必须是th
  22082. firstRows = table.rows[ 0 ].cells;
  22083. cellCount = firstRows.length;
  22084. for ( var i = 0, cell; cell = firstRows[ i ]; i++ ) {
  22085. if ( cell.tagName.toLowerCase() !== 'th' ) {
  22086. return false;
  22087. }
  22088. }
  22089. for ( var i = 1, row; row = table.rows[ i ]; i++ ) {
  22090. //每行单元格数不匹配, 返回false
  22091. if ( row.cells.length != cellCount ) {
  22092. return false;
  22093. }
  22094. //第一列不是th也返回false
  22095. if ( row.cells[0].tagName.toLowerCase() !== 'th' ) {
  22096. return false;
  22097. }
  22098. for ( var j = 1, cell; cell = row.cells[ j ]; j++ ) {
  22099. var value = utils.trim( ( cell.innerText || cell.textContent || '' ) );
  22100. value = value.replace( new RegExp( UE.dom.domUtils.fillChar, 'g' ), '' ).replace( /^\s+|\s+$/g, '' );
  22101. //必须是数字
  22102. if ( !/^\d*\.?\d+$/.test( value ) ) {
  22103. return false;
  22104. }
  22105. }
  22106. }
  22107. return true;
  22108. }
  22109. });
  22110. // plugins/section.js
  22111. /**
  22112. * 目录大纲支持插件
  22113. * @file
  22114. * @since 1.3.0
  22115. */
  22116. UE.plugin.register('section', function (){
  22117. /* 目录节点对象 */
  22118. function Section(option){
  22119. this.tag = '';
  22120. this.level = -1,
  22121. this.dom = null;
  22122. this.nextSection = null;
  22123. this.previousSection = null;
  22124. this.parentSection = null;
  22125. this.startAddress = [];
  22126. this.endAddress = [];
  22127. this.children = [];
  22128. }
  22129. function getSection(option) {
  22130. var section = new Section();
  22131. return utils.extend(section, option);
  22132. }
  22133. function getNodeFromAddress(startAddress, root) {
  22134. var current = root;
  22135. for(var i = 0;i < startAddress.length; i++) {
  22136. if(!current.childNodes) return null;
  22137. current = current.childNodes[startAddress[i]];
  22138. }
  22139. return current;
  22140. }
  22141. var me = this;
  22142. return {
  22143. bindMultiEvents:{
  22144. type: 'aftersetcontent afterscencerestore',
  22145. handler: function(){
  22146. me.fireEvent('updateSections');
  22147. }
  22148. },
  22149. bindEvents:{
  22150. /* 初始化、拖拽、粘贴、执行setcontent之后 */
  22151. 'ready': function (){
  22152. me.fireEvent('updateSections');
  22153. domUtils.on(me.body, 'drop paste', function(){
  22154. me.fireEvent('updateSections');
  22155. });
  22156. },
  22157. /* 执行paragraph命令之后 */
  22158. 'afterexeccommand': function (type, cmd) {
  22159. if(cmd == 'paragraph') {
  22160. me.fireEvent('updateSections');
  22161. }
  22162. },
  22163. /* 部分键盘操作,触发updateSections事件 */
  22164. 'keyup': function (type, e) {
  22165. var me = this,
  22166. range = me.selection.getRange();
  22167. if(range.collapsed != true) {
  22168. me.fireEvent('updateSections');
  22169. } else {
  22170. var keyCode = e.keyCode || e.which;
  22171. if(keyCode == 13 || keyCode == 8 || keyCode == 46) {
  22172. me.fireEvent('updateSections');
  22173. }
  22174. }
  22175. }
  22176. },
  22177. commands:{
  22178. 'getsections': {
  22179. execCommand: function (cmd, levels) {
  22180. var levelFn = levels || ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'];
  22181. for (var i = 0; i < levelFn.length; i++) {
  22182. if (typeof levelFn[i] == 'string') {
  22183. levelFn[i] = function(fn){
  22184. return function(node){
  22185. return node.tagName == fn.toUpperCase()
  22186. };
  22187. }(levelFn[i]);
  22188. } else if (typeof levelFn[i] != 'function') {
  22189. levelFn[i] = function (node) {
  22190. return null;
  22191. }
  22192. }
  22193. }
  22194. function getSectionLevel(node) {
  22195. for (var i = 0; i < levelFn.length; i++) {
  22196. if (levelFn[i](node)) return i;
  22197. }
  22198. return -1;
  22199. }
  22200. var me = this,
  22201. Directory = getSection({'level':-1, 'title':'root'}),
  22202. previous = Directory;
  22203. function traversal(node, Directory) {
  22204. var level,
  22205. tmpSection = null,
  22206. parent,
  22207. child,
  22208. children = node.childNodes;
  22209. for (var i = 0, len = children.length; i < len; i++) {
  22210. child = children[i];
  22211. level = getSectionLevel(child);
  22212. if (level >= 0) {
  22213. var address = me.selection.getRange().selectNode(child).createAddress(true).startAddress,
  22214. current = getSection({
  22215. 'tag': child.tagName,
  22216. 'title': child.innerText || child.textContent || '',
  22217. 'level': level,
  22218. 'dom': child,
  22219. 'startAddress': utils.clone(address, []),
  22220. 'endAddress': utils.clone(address, []),
  22221. 'children': []
  22222. });
  22223. previous.nextSection = current;
  22224. current.previousSection = previous;
  22225. parent = previous;
  22226. while(level <= parent.level){
  22227. parent = parent.parentSection;
  22228. }
  22229. current.parentSection = parent;
  22230. parent.children.push(current);
  22231. tmpSection = previous = current;
  22232. } else {
  22233. child.nodeType === 1 && traversal(child, Directory);
  22234. tmpSection && tmpSection.endAddress[tmpSection.endAddress.length - 1] ++;
  22235. }
  22236. }
  22237. }
  22238. traversal(me.body, Directory);
  22239. return Directory;
  22240. },
  22241. notNeedUndo: true
  22242. },
  22243. 'movesection': {
  22244. execCommand: function (cmd, sourceSection, targetSection, isAfter) {
  22245. var me = this,
  22246. targetAddress,
  22247. target;
  22248. if(!sourceSection || !targetSection || targetSection.level == -1) return;
  22249. targetAddress = isAfter ? targetSection.endAddress:targetSection.startAddress;
  22250. target = getNodeFromAddress(targetAddress, me.body);
  22251. /* 判断目标地址是否被源章节包含 */
  22252. if(!targetAddress || !target || isContainsAddress(sourceSection.startAddress, sourceSection.endAddress, targetAddress)) return;
  22253. var startNode = getNodeFromAddress(sourceSection.startAddress, me.body),
  22254. endNode = getNodeFromAddress(sourceSection.endAddress, me.body),
  22255. current,
  22256. nextNode;
  22257. if(isAfter) {
  22258. current = endNode;
  22259. while ( current && !(domUtils.getPosition( startNode, current ) & domUtils.POSITION_FOLLOWING) ) {
  22260. nextNode = current.previousSibling;
  22261. domUtils.insertAfter(target, current);
  22262. if(current == startNode) break;
  22263. current = nextNode;
  22264. }
  22265. } else {
  22266. current = startNode;
  22267. while ( current && !(domUtils.getPosition( current, endNode ) & domUtils.POSITION_FOLLOWING) ) {
  22268. nextNode = current.nextSibling;
  22269. target.parentNode.insertBefore(current, target);
  22270. if(current == endNode) break;
  22271. current = nextNode;
  22272. }
  22273. }
  22274. me.fireEvent('updateSections');
  22275. /* 获取地址的包含关系 */
  22276. function isContainsAddress(startAddress, endAddress, addressTarget){
  22277. var isAfterStartAddress = false,
  22278. isBeforeEndAddress = false;
  22279. for(var i = 0; i< startAddress.length; i++){
  22280. if(i >= addressTarget.length) break;
  22281. if(addressTarget[i] > startAddress[i]) {
  22282. isAfterStartAddress = true;
  22283. break;
  22284. } else if(addressTarget[i] < startAddress[i]) {
  22285. break;
  22286. }
  22287. }
  22288. for(var i = 0; i< endAddress.length; i++){
  22289. if(i >= addressTarget.length) break;
  22290. if(addressTarget[i] < startAddress[i]) {
  22291. isBeforeEndAddress = true;
  22292. break;
  22293. } else if(addressTarget[i] > startAddress[i]) {
  22294. break;
  22295. }
  22296. }
  22297. return isAfterStartAddress && isBeforeEndAddress;
  22298. }
  22299. }
  22300. },
  22301. 'deletesection': {
  22302. execCommand: function (cmd, section, keepChildren) {
  22303. var me = this;
  22304. if(!section) return;
  22305. function getNodeFromAddress(startAddress) {
  22306. var current = me.body;
  22307. for(var i = 0;i < startAddress.length; i++) {
  22308. if(!current.childNodes) return null;
  22309. current = current.childNodes[startAddress[i]];
  22310. }
  22311. return current;
  22312. }
  22313. var startNode = getNodeFromAddress(section.startAddress),
  22314. endNode = getNodeFromAddress(section.endAddress),
  22315. current = startNode,
  22316. nextNode;
  22317. if(!keepChildren) {
  22318. while ( current && domUtils.inDoc(endNode, me.document) && !(domUtils.getPosition( current, endNode ) & domUtils.POSITION_FOLLOWING) ) {
  22319. nextNode = current.nextSibling;
  22320. domUtils.remove(current);
  22321. current = nextNode;
  22322. }
  22323. } else {
  22324. domUtils.remove(current);
  22325. }
  22326. me.fireEvent('updateSections');
  22327. }
  22328. },
  22329. 'selectsection': {
  22330. execCommand: function (cmd, section) {
  22331. if(!section && !section.dom) return false;
  22332. var me = this,
  22333. range = me.selection.getRange(),
  22334. address = {
  22335. 'startAddress':utils.clone(section.startAddress, []),
  22336. 'endAddress':utils.clone(section.endAddress, [])
  22337. };
  22338. address.endAddress[address.endAddress.length - 1]++;
  22339. range.moveToAddress(address).select().scrollToView();
  22340. return true;
  22341. },
  22342. notNeedUndo: true
  22343. },
  22344. 'scrolltosection': {
  22345. execCommand: function (cmd, section) {
  22346. if(!section && !section.dom) return false;
  22347. var me = this,
  22348. range = me.selection.getRange(),
  22349. address = {
  22350. 'startAddress':section.startAddress,
  22351. 'endAddress':section.endAddress
  22352. };
  22353. address.endAddress[address.endAddress.length - 1]++;
  22354. range.moveToAddress(address).scrollToView();
  22355. return true;
  22356. },
  22357. notNeedUndo: true
  22358. }
  22359. }
  22360. }
  22361. });
  22362. // plugins/simpleupload.js
  22363. /**
  22364. * @description
  22365. * 简单上传:点击按钮,直接选择文件上传
  22366. * @author Jinqn
  22367. * @date 2014-03-31
  22368. */
  22369. UE.plugin.register('simpleupload', function (){
  22370. var me = this,
  22371. isLoaded = false,
  22372. containerBtn;
  22373. function initUploadBtn(){
  22374. var w = containerBtn.offsetWidth || 20,
  22375. h = containerBtn.offsetHeight || 20,
  22376. btnIframe = document.createElement('iframe'),
  22377. btnStyle = 'display:block;width:' + w + 'px;height:' + h + 'px;overflow:hidden;border:0;margin:0;padding:0;position:absolute;top:0;left:0;filter:alpha(opacity=0);-moz-opacity:0;-khtml-opacity: 0;opacity: 0;cursor:pointer;';
  22378. domUtils.on(btnIframe, 'load', function(){
  22379. var timestrap = (+new Date()).toString(36),
  22380. wrapper,
  22381. btnIframeDoc,
  22382. btnIframeBody;
  22383. btnIframeDoc = (btnIframe.contentDocument || btnIframe.contentWindow.document);
  22384. btnIframeBody = btnIframeDoc.body;
  22385. wrapper = btnIframeDoc.createElement('div');
  22386. wrapper.innerHTML = '<form id="edui_form_' + timestrap + '" target="edui_iframe_' + timestrap + '" method="POST" enctype="multipart/form-data" action="' + me.getOpt('serverUrl') + '" ' +
  22387. 'style="' + btnStyle + '">' +
  22388. '<input id="edui_input_' + timestrap + '" type="file" accept="image/*" name="' + me.options.imageFieldName + '" ' +
  22389. 'style="' + btnStyle + '">' +
  22390. '</form>' +
  22391. '<iframe id="edui_iframe_' + timestrap + '" name="edui_iframe_' + timestrap + '" style="display:none;width:0;height:0;border:0;margin:0;padding:0;position:absolute;"></iframe>';
  22392. wrapper.className = 'edui-' + me.options.theme;
  22393. wrapper.id = me.ui.id + '_iframeupload';
  22394. btnIframeBody.style.cssText = btnStyle;
  22395. btnIframeBody.style.width = w + 'px';
  22396. btnIframeBody.style.height = h + 'px';
  22397. btnIframeBody.appendChild(wrapper);
  22398. if (btnIframeBody.parentNode) {
  22399. btnIframeBody.parentNode.style.width = w + 'px';
  22400. btnIframeBody.parentNode.style.height = w + 'px';
  22401. }
  22402. var form = btnIframeDoc.getElementById('edui_form_' + timestrap);
  22403. var input = btnIframeDoc.getElementById('edui_input_' + timestrap);
  22404. var iframe = btnIframeDoc.getElementById('edui_iframe_' + timestrap);
  22405. domUtils.on(input, 'change', function(){
  22406. if(!input.value) return;
  22407. var loadingId = 'loading_' + (+new Date()).toString(36);
  22408. var params = utils.serializeParam(me.queryCommandValue('serverparam')) || '';
  22409. var imageActionUrl = me.getActionUrl(me.getOpt('imageActionName'));
  22410. var allowFiles = me.getOpt('imageAllowFiles');
  22411. me.focus();
  22412. me.execCommand('inserthtml', '<img class="loadingclass" id="' + loadingId + '" src="' + me.options.themePath + me.options.theme +'/images/spacer.gif" title="' + (me.getLang('simpleupload.loading') || '') + '" >');
  22413. function callback(){
  22414. try{
  22415. var link, json, loader,
  22416. body = (iframe.contentDocument || iframe.contentWindow.document).body,
  22417. result = body.innerText || body.textContent || '';
  22418. json = (new Function("return " + result))();
  22419. link = me.options.imageUrlPrefix + json.url;
  22420. if(json.state == 'SUCCESS' && json.url) {
  22421. loader = me.document.getElementById(loadingId);
  22422. loader.setAttribute('src', link);
  22423. loader.setAttribute('_src', link);
  22424. loader.setAttribute('title', json.title || '');
  22425. loader.setAttribute('alt', json.original || '');
  22426. loader.removeAttribute('id');
  22427. domUtils.removeClasses(loader, 'loadingclass');
  22428. } else {
  22429. showErrorLoader && showErrorLoader(json.state);
  22430. }
  22431. }catch(er){
  22432. showErrorLoader && showErrorLoader(me.getLang('simpleupload.loadError'));
  22433. }
  22434. form.reset();
  22435. domUtils.un(iframe, 'load', callback);
  22436. }
  22437. function showErrorLoader(title){
  22438. if(loadingId) {
  22439. var loader = me.document.getElementById(loadingId);
  22440. loader && domUtils.remove(loader);
  22441. me.fireEvent('showmessage', {
  22442. 'id': loadingId,
  22443. 'content': title,
  22444. 'type': 'error',
  22445. 'timeout': 4000
  22446. });
  22447. }
  22448. }
  22449. /* 判断后端配置是否没有加载成功 */
  22450. if (!me.getOpt('imageActionName')) {
  22451. errorHandler(me.getLang('autoupload.errorLoadConfig'));
  22452. return;
  22453. }
  22454. // 判断文件格式是否错误
  22455. var filename = input.value,
  22456. fileext = filename ? filename.substr(filename.lastIndexOf('.')):'';
  22457. if (!fileext || (allowFiles && (allowFiles.join('') + '.').indexOf(fileext.toLowerCase() + '.') == -1)) {
  22458. showErrorLoader(me.getLang('simpleupload.exceedTypeError'));
  22459. return;
  22460. }
  22461. domUtils.on(iframe, 'load', callback);
  22462. form.action = utils.formatUrl(imageActionUrl + (imageActionUrl.indexOf('?') == -1 ? '?':'&') + params);
  22463. form.submit();
  22464. });
  22465. var stateTimer;
  22466. me.addListener('selectionchange', function () {
  22467. clearTimeout(stateTimer);
  22468. stateTimer = setTimeout(function() {
  22469. var state = me.queryCommandState('simpleupload');
  22470. if (state == -1) {
  22471. input.disabled = 'disabled';
  22472. } else {
  22473. input.disabled = false;
  22474. }
  22475. }, 400);
  22476. });
  22477. isLoaded = true;
  22478. });
  22479. btnIframe.style.cssText = btnStyle;
  22480. containerBtn.appendChild(btnIframe);
  22481. }
  22482. return {
  22483. bindEvents:{
  22484. 'ready': function() {
  22485. //设置loading的样式
  22486. utils.cssRule('loading',
  22487. '.loadingclass{display:inline-block;cursor:default;background: url(\''
  22488. + this.options.themePath
  22489. + this.options.theme +'/images/loading.gif\') no-repeat center center transparent;border:1px solid #cccccc;margin-right:1px;height: 22px;width: 22px;}\n' +
  22490. '.loaderrorclass{display:inline-block;cursor:default;background: url(\''
  22491. + this.options.themePath
  22492. + this.options.theme +'/images/loaderror.png\') no-repeat center center transparent;border:1px solid #cccccc;margin-right:1px;height: 22px;width: 22px;' +
  22493. '}',
  22494. this.document);
  22495. },
  22496. /* 初始化简单上传按钮 */
  22497. 'simpleuploadbtnready': function(type, container) {
  22498. containerBtn = container;
  22499. me.afterConfigReady(initUploadBtn);
  22500. }
  22501. },
  22502. outputRule: function(root){
  22503. utils.each(root.getNodesByTagName('img'),function(n){
  22504. if (/\b(loaderrorclass)|(bloaderrorclass)\b/.test(n.getAttr('class'))) {
  22505. n.parentNode.removeChild(n);
  22506. }
  22507. });
  22508. },
  22509. commands: {
  22510. 'simpleupload': {
  22511. queryCommandState: function () {
  22512. return isLoaded ? 0:-1;
  22513. }
  22514. }
  22515. }
  22516. }
  22517. });
  22518. // plugins/serverparam.js
  22519. /**
  22520. * 服务器提交的额外参数列表设置插件
  22521. * @file
  22522. * @since 1.2.6.1
  22523. */
  22524. UE.plugin.register('serverparam', function (){
  22525. var me = this,
  22526. serverParam = {};
  22527. return {
  22528. commands:{
  22529. /**
  22530. * 修改服务器提交的额外参数列表,清除所有项
  22531. * @command serverparam
  22532. * @method execCommand
  22533. * @param { String } cmd 命令字符串
  22534. * @example
  22535. * ```javascript
  22536. * editor.execCommand('serverparam');
  22537. * editor.queryCommandValue('serverparam'); //返回空
  22538. * ```
  22539. */
  22540. /**
  22541. * 修改服务器提交的额外参数列表,删除指定项
  22542. * @command serverparam
  22543. * @method execCommand
  22544. * @param { String } cmd 命令字符串
  22545. * @param { String } key 要清除的属性
  22546. * @example
  22547. * ```javascript
  22548. * editor.execCommand('serverparam', 'name'); //删除属性name
  22549. * ```
  22550. */
  22551. /**
  22552. * 修改服务器提交的额外参数列表,使用键值添加项
  22553. * @command serverparam
  22554. * @method execCommand
  22555. * @param { String } cmd 命令字符串
  22556. * @param { String } key 要添加的属性
  22557. * @param { String } value 要添加属性的值
  22558. * @example
  22559. * ```javascript
  22560. * editor.execCommand('serverparam', 'name', 'hello');
  22561. * editor.queryCommandValue('serverparam'); //返回对象 {'name': 'hello'}
  22562. * ```
  22563. */
  22564. /**
  22565. * 修改服务器提交的额外参数列表,传入键值对对象添加多项
  22566. * @command serverparam
  22567. * @method execCommand
  22568. * @param { String } cmd 命令字符串
  22569. * @param { Object } key 传入的键值对对象
  22570. * @example
  22571. * ```javascript
  22572. * editor.execCommand('serverparam', {'name': 'hello'});
  22573. * editor.queryCommandValue('serverparam'); //返回对象 {'name': 'hello'}
  22574. * ```
  22575. */
  22576. /**
  22577. * 修改服务器提交的额外参数列表,使用自定义函数添加多项
  22578. * @command serverparam
  22579. * @method execCommand
  22580. * @param { String } cmd 命令字符串
  22581. * @param { Function } key 自定义获取参数的函数
  22582. * @example
  22583. * ```javascript
  22584. * editor.execCommand('serverparam', function(editor){
  22585. * return {'key': 'value'};
  22586. * });
  22587. * editor.queryCommandValue('serverparam'); //返回对象 {'key': 'value'}
  22588. * ```
  22589. */
  22590. /**
  22591. * 获取服务器提交的额外参数列表
  22592. * @command serverparam
  22593. * @method queryCommandValue
  22594. * @param { String } cmd 命令字符串
  22595. * @example
  22596. * ```javascript
  22597. * editor.queryCommandValue( 'serverparam' ); //返回对象 {'key': 'value'}
  22598. * ```
  22599. */
  22600. 'serverparam':{
  22601. execCommand:function (cmd, key, value) {
  22602. if (key === undefined || key === null) { //不传参数,清空列表
  22603. serverParam = {};
  22604. } else if (utils.isString(key)) { //传入键值
  22605. if(value === undefined || value === null) {
  22606. delete serverParam[key];
  22607. } else {
  22608. serverParam[key] = value;
  22609. }
  22610. } else if (utils.isObject(key)) { //传入对象,覆盖列表项
  22611. utils.extend(serverParam, key, true);
  22612. } else if (utils.isFunction(key)){ //传入函数,添加列表项
  22613. utils.extend(serverParam, key(), true);
  22614. }
  22615. },
  22616. queryCommandValue: function(){
  22617. return serverParam || {};
  22618. }
  22619. }
  22620. }
  22621. }
  22622. });
  22623. // plugins/insertfile.js
  22624. /**
  22625. * 插入附件
  22626. */
  22627. UE.plugin.register('insertfile', function (){
  22628. var me = this;
  22629. function getFileIcon(url){
  22630. var ext = url.substr(url.lastIndexOf('.') + 1).toLowerCase(),
  22631. maps = {
  22632. "rar":"icon_rar.gif",
  22633. "zip":"icon_rar.gif",
  22634. "tar":"icon_rar.gif",
  22635. "gz":"icon_rar.gif",
  22636. "bz2":"icon_rar.gif",
  22637. "doc":"icon_doc.gif",
  22638. "docx":"icon_doc.gif",
  22639. "pdf":"icon_pdf.gif",
  22640. "mp3":"icon_mp3.gif",
  22641. "xls":"icon_xls.gif",
  22642. "chm":"icon_chm.gif",
  22643. "ppt":"icon_ppt.gif",
  22644. "pptx":"icon_ppt.gif",
  22645. "avi":"icon_mv.gif",
  22646. "rmvb":"icon_mv.gif",
  22647. "wmv":"icon_mv.gif",
  22648. "flv":"icon_mv.gif",
  22649. "swf":"icon_mv.gif",
  22650. "rm":"icon_mv.gif",
  22651. "exe":"icon_exe.gif",
  22652. "psd":"icon_psd.gif",
  22653. "txt":"icon_txt.gif",
  22654. "jpg":"icon_jpg.gif",
  22655. "png":"icon_jpg.gif",
  22656. "jpeg":"icon_jpg.gif",
  22657. "gif":"icon_jpg.gif",
  22658. "ico":"icon_jpg.gif",
  22659. "bmp":"icon_jpg.gif"
  22660. };
  22661. return maps[ext] ? maps[ext]:maps['txt'];
  22662. }
  22663. return {
  22664. commands:{
  22665. 'insertfile': {
  22666. execCommand: function (command, filelist){
  22667. filelist = utils.isArray(filelist) ? filelist : [filelist];
  22668. var i, item, icon, title,
  22669. html = '',
  22670. URL = me.getOpt('UEDITOR_HOME_URL'),
  22671. iconDir = URL + (URL.substr(URL.length - 1) == '/' ? '':'/') + 'dialogs/attachment/fileTypeImages/';
  22672. for (i = 0; i < filelist.length; i++) {
  22673. item = filelist[i];
  22674. icon = iconDir + getFileIcon(item.url);
  22675. title = item.title || item.url.substr(item.url.lastIndexOf('/') + 1);
  22676. html += '<p style="line-height: 16px;">' +
  22677. '<img style="vertical-align: middle; margin-right: 2px;" src="'+ icon + '" _src="' + icon + '" />' +
  22678. '<a style="font-size:12px; color:#0066cc;" href="' + item.url +'" title="' + title + '">' + title + '</a>' +
  22679. '</p>';
  22680. }
  22681. me.execCommand('insertHtml', html);
  22682. }
  22683. }
  22684. }
  22685. }
  22686. });
  22687. // plugins/xssFilter.js
  22688. /**
  22689. * @file xssFilter.js
  22690. * @desc xss过滤器
  22691. * @author robbenmu
  22692. */
  22693. UE.plugins.xssFilter = function() {
  22694. var config = UEDITOR_CONFIG;
  22695. var whitList = config.whitList;
  22696. function filter(node) {
  22697. var tagName = node.tagName;
  22698. var attrs = node.attrs;
  22699. if (!whitList.hasOwnProperty(tagName)) {
  22700. node.parentNode.removeChild(node);
  22701. return false;
  22702. }
  22703. UE.utils.each(attrs, function (val, key) {
  22704. if (whitList[tagName].indexOf(key) === -1) {
  22705. node.setAttr(key);
  22706. }
  22707. });
  22708. }
  22709. // 添加inserthtml\paste等操作用的过滤规则
  22710. if (whitList && config.xssFilterRules) {
  22711. this.options.filterRules = function () {
  22712. var result = {};
  22713. UE.utils.each(whitList, function(val, key) {
  22714. result[key] = function (node) {
  22715. return filter(node);
  22716. };
  22717. });
  22718. return result;
  22719. }();
  22720. }
  22721. var tagList = [];
  22722. UE.utils.each(whitList, function (val, key) {
  22723. tagList.push(key);
  22724. });
  22725. // 添加input过滤规则
  22726. //
  22727. if (whitList && config.inputXssFilter) {
  22728. this.addInputRule(function (root) {
  22729. root.traversal(function(node) {
  22730. if (node.type !== 'element') {
  22731. return false;
  22732. }
  22733. filter(node);
  22734. });
  22735. });
  22736. }
  22737. // 添加output过滤规则
  22738. //
  22739. if (whitList && config.outputXssFilter) {
  22740. this.addOutputRule(function (root) {
  22741. root.traversal(function(node) {
  22742. if (node.type !== 'element') {
  22743. return false;
  22744. }
  22745. filter(node);
  22746. });
  22747. });
  22748. }
  22749. };
  22750. // ui/ui.js
  22751. var baidu = baidu || {};
  22752. baidu.editor = baidu.editor || {};
  22753. UE.ui = baidu.editor.ui = {};
  22754. // ui/uiutils.js
  22755. (function (){
  22756. var browser = baidu.editor.browser,
  22757. domUtils = baidu.editor.dom.domUtils;
  22758. var magic = '$EDITORUI';
  22759. var root = window[magic] = {};
  22760. var uidMagic = 'ID' + magic;
  22761. var uidCount = 0;
  22762. var uiUtils = baidu.editor.ui.uiUtils = {
  22763. uid: function (obj){
  22764. return (obj ? obj[uidMagic] || (obj[uidMagic] = ++ uidCount) : ++ uidCount);
  22765. },
  22766. hook: function ( fn, callback ) {
  22767. var dg;
  22768. if (fn && fn._callbacks) {
  22769. dg = fn;
  22770. } else {
  22771. dg = function (){
  22772. var q;
  22773. if (fn) {
  22774. q = fn.apply(this, arguments);
  22775. }
  22776. var callbacks = dg._callbacks;
  22777. var k = callbacks.length;
  22778. while (k --) {
  22779. var r = callbacks[k].apply(this, arguments);
  22780. if (q === undefined) {
  22781. q = r;
  22782. }
  22783. }
  22784. return q;
  22785. };
  22786. dg._callbacks = [];
  22787. }
  22788. dg._callbacks.push(callback);
  22789. return dg;
  22790. },
  22791. createElementByHtml: function (html){
  22792. var el = document.createElement('div');
  22793. el.innerHTML = html;
  22794. el = el.firstChild;
  22795. el.parentNode.removeChild(el);
  22796. return el;
  22797. },
  22798. getViewportElement: function (){
  22799. return (browser.ie && browser.quirks) ?
  22800. document.body : document.documentElement;
  22801. },
  22802. getClientRect: function (element){
  22803. var bcr;
  22804. //trace IE6下在控制编辑器显隐时可能会报错,catch一下
  22805. try{
  22806. bcr = element.getBoundingClientRect();
  22807. }catch(e){
  22808. bcr={left:0,top:0,height:0,width:0}
  22809. }
  22810. var rect = {
  22811. left: Math.round(bcr.left),
  22812. top: Math.round(bcr.top),
  22813. height: Math.round(bcr.bottom - bcr.top),
  22814. width: Math.round(bcr.right - bcr.left)
  22815. };
  22816. var doc;
  22817. while ((doc = element.ownerDocument) !== document &&
  22818. (element = domUtils.getWindow(doc).frameElement)) {
  22819. bcr = element.getBoundingClientRect();
  22820. rect.left += bcr.left;
  22821. rect.top += bcr.top;
  22822. }
  22823. rect.bottom = rect.top + rect.height;
  22824. rect.right = rect.left + rect.width;
  22825. return rect;
  22826. },
  22827. getViewportRect: function (){
  22828. var viewportEl = uiUtils.getViewportElement();
  22829. var width = (window.innerWidth || viewportEl.clientWidth) | 0;
  22830. var height = (window.innerHeight ||viewportEl.clientHeight) | 0;
  22831. return {
  22832. left: 0,
  22833. top: 0,
  22834. height: height,
  22835. width: width,
  22836. bottom: height,
  22837. right: width
  22838. };
  22839. },
  22840. setViewportOffset: function (element, offset){
  22841. var rect;
  22842. var fixedLayer = uiUtils.getFixedLayer();
  22843. if (element.parentNode === fixedLayer) {
  22844. element.style.left = offset.left + 'px';
  22845. element.style.top = offset.top + 'px';
  22846. } else {
  22847. domUtils.setViewportOffset(element, offset);
  22848. }
  22849. },
  22850. getEventOffset: function (evt){
  22851. var el = evt.target || evt.srcElement;
  22852. var rect = uiUtils.getClientRect(el);
  22853. var offset = uiUtils.getViewportOffsetByEvent(evt);
  22854. return {
  22855. left: offset.left - rect.left,
  22856. top: offset.top - rect.top
  22857. };
  22858. },
  22859. getViewportOffsetByEvent: function (evt){
  22860. var el = evt.target || evt.srcElement;
  22861. var frameEl = domUtils.getWindow(el).frameElement;
  22862. var offset = {
  22863. left: evt.clientX,
  22864. top: evt.clientY
  22865. };
  22866. if (frameEl && el.ownerDocument !== document) {
  22867. var rect = uiUtils.getClientRect(frameEl);
  22868. offset.left += rect.left;
  22869. offset.top += rect.top;
  22870. }
  22871. return offset;
  22872. },
  22873. setGlobal: function (id, obj){
  22874. root[id] = obj;
  22875. return magic + '["' + id + '"]';
  22876. },
  22877. unsetGlobal: function (id){
  22878. delete root[id];
  22879. },
  22880. copyAttributes: function (tgt, src){
  22881. var attributes = src.attributes;
  22882. var k = attributes.length;
  22883. while (k --) {
  22884. var attrNode = attributes[k];
  22885. if ( attrNode.nodeName != 'style' && attrNode.nodeName != 'class' && (!browser.ie || attrNode.specified) ) {
  22886. tgt.setAttribute(attrNode.nodeName, attrNode.nodeValue);
  22887. }
  22888. }
  22889. if (src.className) {
  22890. domUtils.addClass(tgt,src.className);
  22891. }
  22892. if (src.style.cssText) {
  22893. tgt.style.cssText += ';' + src.style.cssText;
  22894. }
  22895. },
  22896. removeStyle: function (el, styleName){
  22897. if (el.style.removeProperty) {
  22898. el.style.removeProperty(styleName);
  22899. } else if (el.style.removeAttribute) {
  22900. el.style.removeAttribute(styleName);
  22901. } else throw '';
  22902. },
  22903. contains: function (elA, elB){
  22904. return elA && elB && (elA === elB ? false : (
  22905. elA.contains ? elA.contains(elB) :
  22906. elA.compareDocumentPosition(elB) & 16
  22907. ));
  22908. },
  22909. startDrag: function (evt, callbacks,doc){
  22910. var doc = doc || document;
  22911. var startX = evt.clientX;
  22912. var startY = evt.clientY;
  22913. function handleMouseMove(evt){
  22914. var x = evt.clientX - startX;
  22915. var y = evt.clientY - startY;
  22916. callbacks.ondragmove(x, y,evt);
  22917. if (evt.stopPropagation) {
  22918. evt.stopPropagation();
  22919. } else {
  22920. evt.cancelBubble = true;
  22921. }
  22922. }
  22923. if (doc.addEventListener) {
  22924. function handleMouseUp(evt){
  22925. doc.removeEventListener('mousemove', handleMouseMove, true);
  22926. doc.removeEventListener('mouseup', handleMouseUp, true);
  22927. window.removeEventListener('mouseup', handleMouseUp, true);
  22928. callbacks.ondragstop();
  22929. }
  22930. doc.addEventListener('mousemove', handleMouseMove, true);
  22931. doc.addEventListener('mouseup', handleMouseUp, true);
  22932. window.addEventListener('mouseup', handleMouseUp, true);
  22933. evt.preventDefault();
  22934. } else {
  22935. var elm = evt.srcElement;
  22936. elm.setCapture();
  22937. function releaseCaptrue(){
  22938. elm.releaseCapture();
  22939. elm.detachEvent('onmousemove', handleMouseMove);
  22940. elm.detachEvent('onmouseup', releaseCaptrue);
  22941. elm.detachEvent('onlosecaptrue', releaseCaptrue);
  22942. callbacks.ondragstop();
  22943. }
  22944. elm.attachEvent('onmousemove', handleMouseMove);
  22945. elm.attachEvent('onmouseup', releaseCaptrue);
  22946. elm.attachEvent('onlosecaptrue', releaseCaptrue);
  22947. evt.returnValue = false;
  22948. }
  22949. callbacks.ondragstart();
  22950. },
  22951. getFixedLayer: function (){
  22952. var layer = document.getElementById('edui_fixedlayer');
  22953. if (layer == null) {
  22954. layer = document.createElement('div');
  22955. layer.id = 'edui_fixedlayer';
  22956. document.body.appendChild(layer);
  22957. if (browser.ie && browser.version <= 8) {
  22958. layer.style.position = 'absolute';
  22959. bindFixedLayer();
  22960. setTimeout(updateFixedOffset);
  22961. } else {
  22962. layer.style.position = 'fixed';
  22963. }
  22964. layer.style.left = '0';
  22965. layer.style.top = '0';
  22966. layer.style.width = '0';
  22967. layer.style.height = '0';
  22968. }
  22969. return layer;
  22970. },
  22971. makeUnselectable: function (element){
  22972. if (browser.opera || (browser.ie && browser.version < 9)) {
  22973. element.unselectable = 'on';
  22974. if (element.hasChildNodes()) {
  22975. for (var i=0; i<element.childNodes.length; i++) {
  22976. if (element.childNodes[i].nodeType == 1) {
  22977. uiUtils.makeUnselectable(element.childNodes[i]);
  22978. }
  22979. }
  22980. }
  22981. } else {
  22982. if (element.style.MozUserSelect !== undefined) {
  22983. element.style.MozUserSelect = 'none';
  22984. } else if (element.style.WebkitUserSelect !== undefined) {
  22985. element.style.WebkitUserSelect = 'none';
  22986. } else if (element.style.KhtmlUserSelect !== undefined) {
  22987. element.style.KhtmlUserSelect = 'none';
  22988. }
  22989. }
  22990. }
  22991. };
  22992. function updateFixedOffset(){
  22993. var layer = document.getElementById('edui_fixedlayer');
  22994. uiUtils.setViewportOffset(layer, {
  22995. left: 0,
  22996. top: 0
  22997. });
  22998. // layer.style.display = 'none';
  22999. // layer.style.display = 'block';
  23000. //#trace: 1354
  23001. // setTimeout(updateFixedOffset);
  23002. }
  23003. function bindFixedLayer(adjOffset){
  23004. domUtils.on(window, 'scroll', updateFixedOffset);
  23005. domUtils.on(window, 'resize', baidu.editor.utils.defer(updateFixedOffset, 0, true));
  23006. }
  23007. })();
  23008. // ui/uibase.js
  23009. (function () {
  23010. var utils = baidu.editor.utils,
  23011. uiUtils = baidu.editor.ui.uiUtils,
  23012. EventBase = baidu.editor.EventBase,
  23013. UIBase = baidu.editor.ui.UIBase = function () {
  23014. };
  23015. UIBase.prototype = {
  23016. className:'',
  23017. uiName:'',
  23018. initOptions:function (options) {
  23019. var me = this;
  23020. for (var k in options) {
  23021. me[k] = options[k];
  23022. }
  23023. this.id = this.id || 'edui' + uiUtils.uid();
  23024. },
  23025. initUIBase:function () {
  23026. this._globalKey = utils.unhtml(uiUtils.setGlobal(this.id, this));
  23027. },
  23028. render:function (holder) {
  23029. var html = this.renderHtml();
  23030. var el = uiUtils.createElementByHtml(html);
  23031. //by xuheng 给每个node添加class
  23032. var list = domUtils.getElementsByTagName(el, "*");
  23033. var theme = "edui-" + (this.theme || this.editor.options.theme);
  23034. var layer = document.getElementById('edui_fixedlayer');
  23035. for (var i = 0, node; node = list[i++];) {
  23036. domUtils.addClass(node, theme);
  23037. }
  23038. domUtils.addClass(el, theme);
  23039. if(layer){
  23040. layer.className="";
  23041. domUtils.addClass(layer,theme);
  23042. }
  23043. var seatEl = this.getDom();
  23044. if (seatEl != null) {
  23045. seatEl.parentNode.replaceChild(el, seatEl);
  23046. uiUtils.copyAttributes(el, seatEl);
  23047. } else {
  23048. if (typeof holder == 'string') {
  23049. holder = document.getElementById(holder);
  23050. }
  23051. holder = holder || uiUtils.getFixedLayer();
  23052. domUtils.addClass(holder, theme);
  23053. holder.appendChild(el);
  23054. }
  23055. this.postRender();
  23056. },
  23057. getDom:function (name) {
  23058. if (!name) {
  23059. return document.getElementById(this.id);
  23060. } else {
  23061. return document.getElementById(this.id + '_' + name);
  23062. }
  23063. },
  23064. postRender:function () {
  23065. this.fireEvent('postrender');
  23066. },
  23067. getHtmlTpl:function () {
  23068. return '';
  23069. },
  23070. formatHtml:function (tpl) {
  23071. var prefix = 'edui-' + this.uiName;
  23072. return (tpl
  23073. .replace(/##/g, this.id)
  23074. .replace(/%%-/g, this.uiName ? prefix + '-' : '')
  23075. .replace(/%%/g, (this.uiName ? prefix : '') + ' ' + this.className)
  23076. .replace(/\$\$/g, this._globalKey));
  23077. },
  23078. renderHtml:function () {
  23079. return this.formatHtml(this.getHtmlTpl());
  23080. },
  23081. dispose:function () {
  23082. var box = this.getDom();
  23083. if (box) baidu.editor.dom.domUtils.remove(box);
  23084. uiUtils.unsetGlobal(this.id);
  23085. }
  23086. };
  23087. utils.inherits(UIBase, EventBase);
  23088. })();
  23089. // ui/separator.js
  23090. (function (){
  23091. var utils = baidu.editor.utils,
  23092. UIBase = baidu.editor.ui.UIBase,
  23093. Separator = baidu.editor.ui.Separator = function (options){
  23094. this.initOptions(options);
  23095. this.initSeparator();
  23096. };
  23097. Separator.prototype = {
  23098. uiName: 'separator',
  23099. initSeparator: function (){
  23100. this.initUIBase();
  23101. },
  23102. getHtmlTpl: function (){
  23103. return '<div id="##" class="edui-box %%"></div>';
  23104. }
  23105. };
  23106. utils.inherits(Separator, UIBase);
  23107. })();
  23108. // ui/mask.js
  23109. ///import core
  23110. ///import uicore
  23111. (function (){
  23112. var utils = baidu.editor.utils,
  23113. domUtils = baidu.editor.dom.domUtils,
  23114. UIBase = baidu.editor.ui.UIBase,
  23115. uiUtils = baidu.editor.ui.uiUtils;
  23116. var Mask = baidu.editor.ui.Mask = function (options){
  23117. this.initOptions(options);
  23118. this.initUIBase();
  23119. };
  23120. Mask.prototype = {
  23121. getHtmlTpl: function (){
  23122. return '<div id="##" class="edui-mask %%" onclick="return $$._onClick(event, this);" onmousedown="return $$._onMouseDown(event, this);"></div>';
  23123. },
  23124. postRender: function (){
  23125. var me = this;
  23126. domUtils.on(window, 'resize', function (){
  23127. setTimeout(function (){
  23128. if (!me.isHidden()) {
  23129. me._fill();
  23130. }
  23131. });
  23132. });
  23133. },
  23134. show: function (zIndex){
  23135. this._fill();
  23136. this.getDom().style.display = '';
  23137. this.getDom().style.zIndex = zIndex;
  23138. },
  23139. hide: function (){
  23140. this.getDom().style.display = 'none';
  23141. this.getDom().style.zIndex = '';
  23142. },
  23143. isHidden: function (){
  23144. return this.getDom().style.display == 'none';
  23145. },
  23146. _onMouseDown: function (){
  23147. return false;
  23148. },
  23149. _onClick: function (e, target){
  23150. this.fireEvent('click', e, target);
  23151. },
  23152. _fill: function (){
  23153. var el = this.getDom();
  23154. var vpRect = uiUtils.getViewportRect();
  23155. el.style.width = vpRect.width + 'px';
  23156. el.style.height = vpRect.height + 'px';
  23157. }
  23158. };
  23159. utils.inherits(Mask, UIBase);
  23160. })();
  23161. // ui/popup.js
  23162. ///import core
  23163. ///import uicore
  23164. (function () {
  23165. var utils = baidu.editor.utils,
  23166. uiUtils = baidu.editor.ui.uiUtils,
  23167. domUtils = baidu.editor.dom.domUtils,
  23168. UIBase = baidu.editor.ui.UIBase,
  23169. Popup = baidu.editor.ui.Popup = function (options){
  23170. this.initOptions(options);
  23171. this.initPopup();
  23172. };
  23173. var allPopups = [];
  23174. function closeAllPopup( evt,el ){
  23175. for ( var i = 0; i < allPopups.length; i++ ) {
  23176. var pop = allPopups[i];
  23177. if (!pop.isHidden()) {
  23178. if (pop.queryAutoHide(el) !== false) {
  23179. if(evt&&/scroll/ig.test(evt.type)&&pop.className=="edui-wordpastepop") return;
  23180. pop.hide();
  23181. }
  23182. }
  23183. }
  23184. if(allPopups.length)
  23185. pop.editor.fireEvent("afterhidepop");
  23186. }
  23187. Popup.postHide = closeAllPopup;
  23188. var ANCHOR_CLASSES = ['edui-anchor-topleft','edui-anchor-topright',
  23189. 'edui-anchor-bottomleft','edui-anchor-bottomright'];
  23190. Popup.prototype = {
  23191. SHADOW_RADIUS: 5,
  23192. content: null,
  23193. _hidden: false,
  23194. autoRender: true,
  23195. canSideLeft: true,
  23196. canSideUp: true,
  23197. initPopup: function (){
  23198. this.initUIBase();
  23199. allPopups.push( this );
  23200. },
  23201. getHtmlTpl: function (){
  23202. return '<div id="##" class="edui-popup %%" onmousedown="return false;">' +
  23203. ' <div id="##_body" class="edui-popup-body">' +
  23204. ' <iframe style="position:absolute;z-index:-1;left:0;top:0;background-color: transparent;" frameborder="0" width="100%" height="100%" src="about:blank"></iframe>' +
  23205. ' <div class="edui-shadow"></div>' +
  23206. ' <div id="##_content" class="edui-popup-content">' +
  23207. this.getContentHtmlTpl() +
  23208. ' </div>' +
  23209. ' </div>' +
  23210. '</div>';
  23211. },
  23212. getContentHtmlTpl: function (){
  23213. if(this.content){
  23214. if (typeof this.content == 'string') {
  23215. return this.content;
  23216. }
  23217. return this.content.renderHtml();
  23218. }else{
  23219. return ''
  23220. }
  23221. },
  23222. _UIBase_postRender: UIBase.prototype.postRender,
  23223. postRender: function (){
  23224. if (this.content instanceof UIBase) {
  23225. this.content.postRender();
  23226. }
  23227. //捕获鼠标滚轮
  23228. if( this.captureWheel && !this.captured ) {
  23229. this.captured = true;
  23230. var winHeight = ( document.documentElement.clientHeight || document.body.clientHeight ) - 80,
  23231. _height = this.getDom().offsetHeight,
  23232. _top = uiUtils.getClientRect( this.combox.getDom() ).top,
  23233. content = this.getDom('content'),
  23234. ifr = this.getDom('body').getElementsByTagName('iframe'),
  23235. me = this;
  23236. ifr.length && ( ifr = ifr[0] );
  23237. while( _top + _height > winHeight ) {
  23238. _height -= 30;
  23239. }
  23240. content.style.height = _height + 'px';
  23241. //同步更改iframe高度
  23242. ifr && ( ifr.style.height = _height + 'px' );
  23243. //阻止在combox上的鼠标滚轮事件, 防止用户的正常操作被误解
  23244. if( window.XMLHttpRequest ) {
  23245. domUtils.on( content, ( 'onmousewheel' in document.body ) ? 'mousewheel' :'DOMMouseScroll' , function(e){
  23246. if(e.preventDefault) {
  23247. e.preventDefault();
  23248. } else {
  23249. e.returnValue = false;
  23250. }
  23251. if( e.wheelDelta ) {
  23252. content.scrollTop -= ( e.wheelDelta / 120 )*60;
  23253. } else {
  23254. content.scrollTop -= ( e.detail / -3 )*60;
  23255. }
  23256. });
  23257. } else {
  23258. //ie6
  23259. domUtils.on( this.getDom(), 'mousewheel' , function(e){
  23260. e.returnValue = false;
  23261. me.getDom('content').scrollTop -= ( e.wheelDelta / 120 )*60;
  23262. });
  23263. }
  23264. }
  23265. this.fireEvent('postRenderAfter');
  23266. this.hide(true);
  23267. this._UIBase_postRender();
  23268. },
  23269. _doAutoRender: function (){
  23270. if (!this.getDom() && this.autoRender) {
  23271. this.render();
  23272. }
  23273. },
  23274. mesureSize: function (){
  23275. var box = this.getDom('content');
  23276. return uiUtils.getClientRect(box);
  23277. },
  23278. fitSize: function (){
  23279. if( this.captureWheel && this.sized ) {
  23280. return this.__size;
  23281. }
  23282. this.sized = true;
  23283. var popBodyEl = this.getDom('body');
  23284. popBodyEl.style.width = '';
  23285. popBodyEl.style.height = '';
  23286. var size = this.mesureSize();
  23287. if( this.captureWheel ) {
  23288. popBodyEl.style.width = -(-20 -size.width) + 'px';
  23289. var height = parseInt( this.getDom('content').style.height, 10 );
  23290. !window.isNaN( height ) && ( size.height = height );
  23291. } else {
  23292. popBodyEl.style.width = size.width + 'px';
  23293. }
  23294. popBodyEl.style.height = size.height + 'px';
  23295. this.__size = size;
  23296. this.captureWheel && (this.getDom('content').style.overflow = 'auto');
  23297. return size;
  23298. },
  23299. showAnchor: function ( element, hoz ){
  23300. this.showAnchorRect( uiUtils.getClientRect( element ), hoz );
  23301. },
  23302. showAnchorRect: function ( rect, hoz, adj ){
  23303. this._doAutoRender();
  23304. var vpRect = uiUtils.getViewportRect();
  23305. this.getDom().style.visibility = 'hidden';
  23306. this._show();
  23307. var popSize = this.fitSize();
  23308. var sideLeft, sideUp, left, top;
  23309. if (hoz) {
  23310. sideLeft = this.canSideLeft && (rect.right + popSize.width > vpRect.right && rect.left > popSize.width);
  23311. sideUp = this.canSideUp && (rect.top + popSize.height > vpRect.bottom && rect.bottom > popSize.height);
  23312. left = (sideLeft ? rect.left - popSize.width : rect.right);
  23313. top = (sideUp ? rect.bottom - popSize.height : rect.top);
  23314. } else {
  23315. sideLeft = this.canSideLeft && (rect.right + popSize.width > vpRect.right && rect.left > popSize.width);
  23316. sideUp = this.canSideUp && (rect.top + popSize.height > vpRect.bottom && rect.bottom > popSize.height);
  23317. left = (sideLeft ? rect.right - popSize.width : rect.left);
  23318. top = (sideUp ? rect.top - popSize.height : rect.bottom);
  23319. }
  23320. var popEl = this.getDom();
  23321. uiUtils.setViewportOffset(popEl, {
  23322. left: left,
  23323. top: top
  23324. });
  23325. domUtils.removeClasses(popEl, ANCHOR_CLASSES);
  23326. popEl.className += ' ' + ANCHOR_CLASSES[(sideUp ? 1 : 0) * 2 + (sideLeft ? 1 : 0)];
  23327. if(this.editor){
  23328. popEl.style.zIndex = this.editor.container.style.zIndex * 1 + 10;
  23329. baidu.editor.ui.uiUtils.getFixedLayer().style.zIndex = popEl.style.zIndex - 1;
  23330. }
  23331. this.getDom().style.visibility = 'visible';
  23332. },
  23333. showAt: function (offset) {
  23334. var left = offset.left;
  23335. var top = offset.top;
  23336. var rect = {
  23337. left: left,
  23338. top: top,
  23339. right: left,
  23340. bottom: top,
  23341. height: 0,
  23342. width: 0
  23343. };
  23344. this.showAnchorRect(rect, false, true);
  23345. },
  23346. _show: function (){
  23347. if (this._hidden) {
  23348. var box = this.getDom();
  23349. box.style.display = '';
  23350. this._hidden = false;
  23351. // if (box.setActive) {
  23352. // box.setActive();
  23353. // }
  23354. this.fireEvent('show');
  23355. }
  23356. },
  23357. isHidden: function (){
  23358. return this._hidden;
  23359. },
  23360. show: function (){
  23361. this._doAutoRender();
  23362. this._show();
  23363. },
  23364. hide: function (notNofity){
  23365. if (!this._hidden && this.getDom()) {
  23366. this.getDom().style.display = 'none';
  23367. this._hidden = true;
  23368. if (!notNofity) {
  23369. this.fireEvent('hide');
  23370. }
  23371. }
  23372. },
  23373. queryAutoHide: function (el){
  23374. return !el || !uiUtils.contains(this.getDom(), el);
  23375. }
  23376. };
  23377. utils.inherits(Popup, UIBase);
  23378. domUtils.on( document, 'mousedown', function ( evt ) {
  23379. var el = evt.target || evt.srcElement;
  23380. closeAllPopup( evt,el );
  23381. } );
  23382. domUtils.on( window, 'scroll', function (evt,el) {
  23383. closeAllPopup( evt,el );
  23384. } );
  23385. })();
  23386. // ui/colorpicker.js
  23387. ///import core
  23388. ///import uicore
  23389. (function (){
  23390. var utils = baidu.editor.utils,
  23391. UIBase = baidu.editor.ui.UIBase,
  23392. ColorPicker = baidu.editor.ui.ColorPicker = function (options){
  23393. this.initOptions(options);
  23394. this.noColorText = this.noColorText || this.editor.getLang("clearColor");
  23395. this.initUIBase();
  23396. };
  23397. ColorPicker.prototype = {
  23398. getHtmlTpl: function (){
  23399. return genColorPicker(this.noColorText,this.editor);
  23400. },
  23401. _onTableClick: function (evt){
  23402. var tgt = evt.target || evt.srcElement;
  23403. var color = tgt.getAttribute('data-color');
  23404. if (color) {
  23405. this.fireEvent('pickcolor', color);
  23406. }
  23407. },
  23408. _onTableOver: function (evt){
  23409. var tgt = evt.target || evt.srcElement;
  23410. var color = tgt.getAttribute('data-color');
  23411. if (color) {
  23412. this.getDom('preview').style.backgroundColor = color;
  23413. }
  23414. },
  23415. _onTableOut: function (){
  23416. this.getDom('preview').style.backgroundColor = '';
  23417. },
  23418. _onPickNoColor: function (){
  23419. this.fireEvent('picknocolor');
  23420. }
  23421. };
  23422. utils.inherits(ColorPicker, UIBase);
  23423. var COLORS = (
  23424. 'ffffff,000000,eeece1,1f497d,4f81bd,c0504d,9bbb59,8064a2,4bacc6,f79646,' +
  23425. 'f2f2f2,7f7f7f,ddd9c3,c6d9f0,dbe5f1,f2dcdb,ebf1dd,e5e0ec,dbeef3,fdeada,' +
  23426. 'd8d8d8,595959,c4bd97,8db3e2,b8cce4,e5b9b7,d7e3bc,ccc1d9,b7dde8,fbd5b5,' +
  23427. 'bfbfbf,3f3f3f,938953,548dd4,95b3d7,d99694,c3d69b,b2a2c7,92cddc,fac08f,' +
  23428. 'a5a5a5,262626,494429,17365d,366092,953734,76923c,5f497a,31859b,e36c09,' +
  23429. '7f7f7f,0c0c0c,1d1b10,0f243e,244061,632423,4f6128,3f3151,205867,974806,' +
  23430. 'c00000,ff0000,ffc000,ffff00,92d050,00b050,00b0f0,0070c0,002060,7030a0,').split(',');
  23431. function genColorPicker(noColorText,editor){
  23432. var html = '<div id="##" class="edui-colorpicker %%">' +
  23433. '<div class="edui-colorpicker-topbar edui-clearfix">' +
  23434. '<div unselectable="on" id="##_preview" class="edui-colorpicker-preview"></div>' +
  23435. '<div unselectable="on" class="edui-colorpicker-nocolor" onclick="$$._onPickNoColor(event, this);">'+ noColorText +'</div>' +
  23436. '</div>' +
  23437. '<table class="edui-box" style="border-collapse: collapse;" onmouseover="$$._onTableOver(event, this);" onmouseout="$$._onTableOut(event, this);" onclick="return $$._onTableClick(event, this);" cellspacing="0" cellpadding="0">' +
  23438. '<tr style="border-bottom: 1px solid #ddd;font-size: 13px;line-height: 25px;color:#39C;padding-top: 2px"><td colspan="10">'+editor.getLang("themeColor")+'</td> </tr>'+
  23439. '<tr class="edui-colorpicker-tablefirstrow" >';
  23440. for (var i=0; i<COLORS.length; i++) {
  23441. if (i && i%10 === 0) {
  23442. html += '</tr>'+(i==60?'<tr style="border-bottom: 1px solid #ddd;font-size: 13px;line-height: 25px;color:#39C;"><td colspan="10">'+editor.getLang("standardColor")+'</td></tr>':'')+'<tr'+(i==60?' class="edui-colorpicker-tablefirstrow"':'')+'>';
  23443. }
  23444. html += i<70 ? '<td style="padding: 0 2px;"><a hidefocus title="'+COLORS[i]+'" onclick="return false;" href="javascript:" unselectable="on" class="edui-box edui-colorpicker-colorcell"' +
  23445. ' data-color="#'+ COLORS[i] +'"'+
  23446. ' style="background-color:#'+ COLORS[i] +';border:solid #ccc;'+
  23447. (i<10 || i>=60?'border-width:1px;':
  23448. i>=10&&i<20?'border-width:1px 1px 0 1px;':
  23449. 'border-width:0 1px 0 1px;')+
  23450. '"' +
  23451. '></a></td>':'';
  23452. }
  23453. html += '</tr></table></div>';
  23454. return html;
  23455. }
  23456. })();
  23457. // ui/tablepicker.js
  23458. ///import core
  23459. ///import uicore
  23460. (function (){
  23461. var utils = baidu.editor.utils,
  23462. uiUtils = baidu.editor.ui.uiUtils,
  23463. UIBase = baidu.editor.ui.UIBase;
  23464. var TablePicker = baidu.editor.ui.TablePicker = function (options){
  23465. this.initOptions(options);
  23466. this.initTablePicker();
  23467. };
  23468. TablePicker.prototype = {
  23469. defaultNumRows: 10,
  23470. defaultNumCols: 10,
  23471. maxNumRows: 20,
  23472. maxNumCols: 20,
  23473. numRows: 10,
  23474. numCols: 10,
  23475. lengthOfCellSide: 22,
  23476. initTablePicker: function (){
  23477. this.initUIBase();
  23478. },
  23479. getHtmlTpl: function (){
  23480. var me = this;
  23481. return '<div id="##" class="edui-tablepicker %%">' +
  23482. '<div class="edui-tablepicker-body">' +
  23483. '<div class="edui-infoarea">' +
  23484. '<span id="##_label" class="edui-label"></span>' +
  23485. '</div>' +
  23486. '<div class="edui-pickarea"' +
  23487. ' onmousemove="$$._onMouseMove(event, this);"' +
  23488. ' onmouseover="$$._onMouseOver(event, this);"' +
  23489. ' onmouseout="$$._onMouseOut(event, this);"' +
  23490. ' onclick="$$._onClick(event, this);"' +
  23491. '>' +
  23492. '<div id="##_overlay" class="edui-overlay"></div>' +
  23493. '</div>' +
  23494. '</div>' +
  23495. '</div>';
  23496. },
  23497. _UIBase_render: UIBase.prototype.render,
  23498. render: function (holder){
  23499. this._UIBase_render(holder);
  23500. this.getDom('label').innerHTML = '0'+this.editor.getLang("t_row")+' x 0'+this.editor.getLang("t_col");
  23501. },
  23502. _track: function (numCols, numRows){
  23503. var style = this.getDom('overlay').style;
  23504. var sideLen = this.lengthOfCellSide;
  23505. style.width = numCols * sideLen + 'px';
  23506. style.height = numRows * sideLen + 'px';
  23507. var label = this.getDom('label');
  23508. label.innerHTML = numCols +this.editor.getLang("t_col")+' x ' + numRows + this.editor.getLang("t_row");
  23509. this.numCols = numCols;
  23510. this.numRows = numRows;
  23511. },
  23512. _onMouseOver: function (evt, el){
  23513. var rel = evt.relatedTarget || evt.fromElement;
  23514. if (!uiUtils.contains(el, rel) && el !== rel) {
  23515. this.getDom('label').innerHTML = '0'+this.editor.getLang("t_col")+' x 0'+this.editor.getLang("t_row");
  23516. this.getDom('overlay').style.visibility = '';
  23517. }
  23518. },
  23519. _onMouseOut: function (evt, el){
  23520. var rel = evt.relatedTarget || evt.toElement;
  23521. if (!uiUtils.contains(el, rel) && el !== rel) {
  23522. this.getDom('label').innerHTML = '0'+this.editor.getLang("t_col")+' x 0'+this.editor.getLang("t_row");
  23523. this.getDom('overlay').style.visibility = 'hidden';
  23524. }
  23525. },
  23526. _onMouseMove: function (evt, el){
  23527. var style = this.getDom('overlay').style;
  23528. var offset = uiUtils.getEventOffset(evt);
  23529. var sideLen = this.lengthOfCellSide;
  23530. var numCols = Math.ceil(offset.left / sideLen);
  23531. var numRows = Math.ceil(offset.top / sideLen);
  23532. this._track(numCols, numRows);
  23533. },
  23534. _onClick: function (){
  23535. this.fireEvent('picktable', this.numCols, this.numRows);
  23536. }
  23537. };
  23538. utils.inherits(TablePicker, UIBase);
  23539. })();
  23540. // ui/stateful.js
  23541. (function (){
  23542. var browser = baidu.editor.browser,
  23543. domUtils = baidu.editor.dom.domUtils,
  23544. uiUtils = baidu.editor.ui.uiUtils;
  23545. var TPL_STATEFUL = 'onmousedown="$$.Stateful_onMouseDown(event, this);"' +
  23546. ' onmouseup="$$.Stateful_onMouseUp(event, this);"' +
  23547. ( browser.ie ? (
  23548. ' onmouseenter="$$.Stateful_onMouseEnter(event, this);"' +
  23549. ' onmouseleave="$$.Stateful_onMouseLeave(event, this);"' )
  23550. : (
  23551. ' onmouseover="$$.Stateful_onMouseOver(event, this);"' +
  23552. ' onmouseout="$$.Stateful_onMouseOut(event, this);"' ));
  23553. baidu.editor.ui.Stateful = {
  23554. alwalysHoverable: false,
  23555. target:null,//目标元素和this指向dom不一样
  23556. Stateful_init: function (){
  23557. this._Stateful_dGetHtmlTpl = this.getHtmlTpl;
  23558. this.getHtmlTpl = this.Stateful_getHtmlTpl;
  23559. },
  23560. Stateful_getHtmlTpl: function (){
  23561. var tpl = this._Stateful_dGetHtmlTpl();
  23562. // 使用function避免$转义
  23563. return tpl.replace(/stateful/g, function (){ return TPL_STATEFUL; });
  23564. },
  23565. Stateful_onMouseEnter: function (evt, el){
  23566. this.target=el;
  23567. if (!this.isDisabled() || this.alwalysHoverable) {
  23568. this.addState('hover');
  23569. this.fireEvent('over');
  23570. }
  23571. },
  23572. Stateful_onMouseLeave: function (evt, el){
  23573. if (!this.isDisabled() || this.alwalysHoverable) {
  23574. this.removeState('hover');
  23575. this.removeState('active');
  23576. this.fireEvent('out');
  23577. }
  23578. },
  23579. Stateful_onMouseOver: function (evt, el){
  23580. var rel = evt.relatedTarget;
  23581. if (!uiUtils.contains(el, rel) && el !== rel) {
  23582. this.Stateful_onMouseEnter(evt, el);
  23583. }
  23584. },
  23585. Stateful_onMouseOut: function (evt, el){
  23586. var rel = evt.relatedTarget;
  23587. if (!uiUtils.contains(el, rel) && el !== rel) {
  23588. this.Stateful_onMouseLeave(evt, el);
  23589. }
  23590. },
  23591. Stateful_onMouseDown: function (evt, el){
  23592. if (!this.isDisabled()) {
  23593. this.addState('active');
  23594. }
  23595. },
  23596. Stateful_onMouseUp: function (evt, el){
  23597. if (!this.isDisabled()) {
  23598. this.removeState('active');
  23599. }
  23600. },
  23601. Stateful_postRender: function (){
  23602. if (this.disabled && !this.hasState('disabled')) {
  23603. this.addState('disabled');
  23604. }
  23605. },
  23606. hasState: function (state){
  23607. return domUtils.hasClass(this.getStateDom(), 'edui-state-' + state);
  23608. },
  23609. addState: function (state){
  23610. if (!this.hasState(state)) {
  23611. this.getStateDom().className += ' edui-state-' + state;
  23612. }
  23613. },
  23614. removeState: function (state){
  23615. if (this.hasState(state)) {
  23616. domUtils.removeClasses(this.getStateDom(), ['edui-state-' + state]);
  23617. }
  23618. },
  23619. getStateDom: function (){
  23620. return this.getDom('state');
  23621. },
  23622. isChecked: function (){
  23623. return this.hasState('checked');
  23624. },
  23625. setChecked: function (checked){
  23626. if (!this.isDisabled() && checked) {
  23627. this.addState('checked');
  23628. } else {
  23629. this.removeState('checked');
  23630. }
  23631. },
  23632. isDisabled: function (){
  23633. return this.hasState('disabled');
  23634. },
  23635. setDisabled: function (disabled){
  23636. if (disabled) {
  23637. this.removeState('hover');
  23638. this.removeState('checked');
  23639. this.removeState('active');
  23640. this.addState('disabled');
  23641. } else {
  23642. this.removeState('disabled');
  23643. }
  23644. }
  23645. };
  23646. })();
  23647. // ui/button.js
  23648. ///import core
  23649. ///import uicore
  23650. ///import ui/stateful.js
  23651. (function (){
  23652. var utils = baidu.editor.utils,
  23653. UIBase = baidu.editor.ui.UIBase,
  23654. Stateful = baidu.editor.ui.Stateful,
  23655. Button = baidu.editor.ui.Button = function (options){
  23656. if(options.name){
  23657. var btnName = options.name;
  23658. var cssRules = options.cssRules;
  23659. if(!options.className){
  23660. options.className = 'edui-for-' + btnName;
  23661. }
  23662. options.cssRules = '.edui-default .edui-for-'+ btnName +' .edui-icon {'+ cssRules +'}'
  23663. }
  23664. this.initOptions(options);
  23665. this.initButton();
  23666. };
  23667. Button.prototype = {
  23668. uiName: 'button',
  23669. label: '',
  23670. title: '',
  23671. showIcon: true,
  23672. showText: true,
  23673. cssRules:'',
  23674. initButton: function (){
  23675. this.initUIBase();
  23676. this.Stateful_init();
  23677. if(this.cssRules){
  23678. utils.cssRule('edui-customize-'+this.name+'-style',this.cssRules);
  23679. }
  23680. },
  23681. getHtmlTpl: function (){
  23682. return '<div id="##" class="edui-box %%">' +
  23683. '<div id="##_state" stateful>' +
  23684. '<div class="%%-wrap"><div id="##_body" unselectable="on" ' + (this.title ? 'title="' + this.title + '"' : '') +
  23685. ' class="%%-body" onmousedown="return $$._onMouseDown(event, this);" onclick="return $$._onClick(event, this);">' +
  23686. (this.showIcon ? '<div class="edui-box edui-icon"></div>' : '') +
  23687. (this.showText ? '<div class="edui-box edui-label">' + this.label + '</div>' : '') +
  23688. '</div>' +
  23689. '</div>' +
  23690. '</div></div>';
  23691. },
  23692. postRender: function (){
  23693. this.Stateful_postRender();
  23694. this.setDisabled(this.disabled)
  23695. },
  23696. _onMouseDown: function (e){
  23697. var target = e.target || e.srcElement,
  23698. tagName = target && target.tagName && target.tagName.toLowerCase();
  23699. if (tagName == 'input' || tagName == 'object' || tagName == 'object') {
  23700. return false;
  23701. }
  23702. },
  23703. _onClick: function (){
  23704. if (!this.isDisabled()) {
  23705. this.fireEvent('click');
  23706. }
  23707. },
  23708. setTitle: function(text){
  23709. var label = this.getDom('label');
  23710. label.innerHTML = text;
  23711. }
  23712. };
  23713. utils.inherits(Button, UIBase);
  23714. utils.extend(Button.prototype, Stateful);
  23715. })();
  23716. // ui/splitbutton.js
  23717. ///import core
  23718. ///import uicore
  23719. ///import ui/stateful.js
  23720. (function (){
  23721. var utils = baidu.editor.utils,
  23722. uiUtils = baidu.editor.ui.uiUtils,
  23723. domUtils = baidu.editor.dom.domUtils,
  23724. UIBase = baidu.editor.ui.UIBase,
  23725. Stateful = baidu.editor.ui.Stateful,
  23726. SplitButton = baidu.editor.ui.SplitButton = function (options){
  23727. this.initOptions(options);
  23728. this.initSplitButton();
  23729. };
  23730. SplitButton.prototype = {
  23731. popup: null,
  23732. uiName: 'splitbutton',
  23733. title: '',
  23734. initSplitButton: function (){
  23735. this.initUIBase();
  23736. this.Stateful_init();
  23737. var me = this;
  23738. if (this.popup != null) {
  23739. var popup = this.popup;
  23740. this.popup = null;
  23741. this.setPopup(popup);
  23742. }
  23743. },
  23744. _UIBase_postRender: UIBase.prototype.postRender,
  23745. postRender: function (){
  23746. this.Stateful_postRender();
  23747. this._UIBase_postRender();
  23748. },
  23749. setPopup: function (popup){
  23750. if (this.popup === popup) return;
  23751. if (this.popup != null) {
  23752. this.popup.dispose();
  23753. }
  23754. popup.addListener('show', utils.bind(this._onPopupShow, this));
  23755. popup.addListener('hide', utils.bind(this._onPopupHide, this));
  23756. popup.addListener('postrender', utils.bind(function (){
  23757. popup.getDom('body').appendChild(
  23758. uiUtils.createElementByHtml('<div id="' +
  23759. this.popup.id + '_bordereraser" class="edui-bordereraser edui-background" style="width:' +
  23760. (uiUtils.getClientRect(this.getDom()).width + 20) + 'px"></div>')
  23761. );
  23762. popup.getDom().className += ' ' + this.className;
  23763. }, this));
  23764. this.popup = popup;
  23765. },
  23766. _onPopupShow: function (){
  23767. this.addState('opened');
  23768. },
  23769. _onPopupHide: function (){
  23770. this.removeState('opened');
  23771. },
  23772. getHtmlTpl: function (){
  23773. return '<div id="##" class="edui-box %%">' +
  23774. '<div '+ (this.title ? 'title="' + this.title + '"' : '') +' id="##_state" stateful><div class="%%-body">' +
  23775. '<div id="##_button_body" class="edui-box edui-button-body" onclick="$$._onButtonClick(event, this);">' +
  23776. '<div class="edui-box edui-icon"></div>' +
  23777. '</div>' +
  23778. '<div class="edui-box edui-splitborder"></div>' +
  23779. '<div class="edui-box edui-arrow" onclick="$$._onArrowClick();"></div>' +
  23780. '</div></div></div>';
  23781. },
  23782. showPopup: function (){
  23783. // 当popup往上弹出的时候,做特殊处理
  23784. var rect = uiUtils.getClientRect(this.getDom());
  23785. rect.top -= this.popup.SHADOW_RADIUS;
  23786. rect.height += this.popup.SHADOW_RADIUS;
  23787. this.popup.showAnchorRect(rect);
  23788. },
  23789. _onArrowClick: function (event, el){
  23790. if (!this.isDisabled()) {
  23791. this.showPopup();
  23792. }
  23793. },
  23794. _onButtonClick: function (){
  23795. if (!this.isDisabled()) {
  23796. this.fireEvent('buttonclick');
  23797. }
  23798. }
  23799. };
  23800. utils.inherits(SplitButton, UIBase);
  23801. utils.extend(SplitButton.prototype, Stateful, true);
  23802. })();
  23803. // ui/colorbutton.js
  23804. ///import core
  23805. ///import uicore
  23806. ///import ui/colorpicker.js
  23807. ///import ui/popup.js
  23808. ///import ui/splitbutton.js
  23809. (function (){
  23810. var utils = baidu.editor.utils,
  23811. uiUtils = baidu.editor.ui.uiUtils,
  23812. ColorPicker = baidu.editor.ui.ColorPicker,
  23813. Popup = baidu.editor.ui.Popup,
  23814. SplitButton = baidu.editor.ui.SplitButton,
  23815. ColorButton = baidu.editor.ui.ColorButton = function (options){
  23816. this.initOptions(options);
  23817. this.initColorButton();
  23818. };
  23819. ColorButton.prototype = {
  23820. initColorButton: function (){
  23821. var me = this;
  23822. this.popup = new Popup({
  23823. content: new ColorPicker({
  23824. noColorText: me.editor.getLang("clearColor"),
  23825. editor:me.editor,
  23826. onpickcolor: function (t, color){
  23827. me._onPickColor(color);
  23828. },
  23829. onpicknocolor: function (t, color){
  23830. me._onPickNoColor(color);
  23831. }
  23832. }),
  23833. editor:me.editor
  23834. });
  23835. this.initSplitButton();
  23836. },
  23837. _SplitButton_postRender: SplitButton.prototype.postRender,
  23838. postRender: function (){
  23839. this._SplitButton_postRender();
  23840. this.getDom('button_body').appendChild(
  23841. uiUtils.createElementByHtml('<div id="' + this.id + '_colorlump" class="edui-colorlump"></div>')
  23842. );
  23843. this.getDom().className += ' edui-colorbutton';
  23844. },
  23845. setColor: function (color){
  23846. this.getDom('colorlump').style.backgroundColor = color;
  23847. this.color = color;
  23848. },
  23849. _onPickColor: function (color){
  23850. if (this.fireEvent('pickcolor', color) !== false) {
  23851. this.setColor(color);
  23852. this.popup.hide();
  23853. }
  23854. },
  23855. _onPickNoColor: function (color){
  23856. if (this.fireEvent('picknocolor') !== false) {
  23857. this.popup.hide();
  23858. }
  23859. }
  23860. };
  23861. utils.inherits(ColorButton, SplitButton);
  23862. })();
  23863. // ui/tablebutton.js
  23864. ///import core
  23865. ///import uicore
  23866. ///import ui/popup.js
  23867. ///import ui/tablepicker.js
  23868. ///import ui/splitbutton.js
  23869. (function (){
  23870. var utils = baidu.editor.utils,
  23871. Popup = baidu.editor.ui.Popup,
  23872. TablePicker = baidu.editor.ui.TablePicker,
  23873. SplitButton = baidu.editor.ui.SplitButton,
  23874. TableButton = baidu.editor.ui.TableButton = function (options){
  23875. this.initOptions(options);
  23876. this.initTableButton();
  23877. };
  23878. TableButton.prototype = {
  23879. initTableButton: function (){
  23880. var me = this;
  23881. this.popup = new Popup({
  23882. content: new TablePicker({
  23883. editor:me.editor,
  23884. onpicktable: function (t, numCols, numRows){
  23885. me._onPickTable(numCols, numRows);
  23886. }
  23887. }),
  23888. 'editor':me.editor
  23889. });
  23890. this.initSplitButton();
  23891. },
  23892. _onPickTable: function (numCols, numRows){
  23893. if (this.fireEvent('picktable', numCols, numRows) !== false) {
  23894. this.popup.hide();
  23895. }
  23896. }
  23897. };
  23898. utils.inherits(TableButton, SplitButton);
  23899. })();
  23900. // ui/autotypesetpicker.js
  23901. ///import core
  23902. ///import uicore
  23903. (function () {
  23904. var utils = baidu.editor.utils,
  23905. UIBase = baidu.editor.ui.UIBase;
  23906. var AutoTypeSetPicker = baidu.editor.ui.AutoTypeSetPicker = function (options) {
  23907. this.initOptions(options);
  23908. this.initAutoTypeSetPicker();
  23909. };
  23910. AutoTypeSetPicker.prototype = {
  23911. initAutoTypeSetPicker:function () {
  23912. this.initUIBase();
  23913. },
  23914. getHtmlTpl:function () {
  23915. var me = this.editor,
  23916. opt = me.options.autotypeset,
  23917. lang = me.getLang("autoTypeSet");
  23918. var textAlignInputName = 'textAlignValue' + me.uid,
  23919. imageBlockInputName = 'imageBlockLineValue' + me.uid,
  23920. symbolConverInputName = 'symbolConverValue' + me.uid;
  23921. return '<div id="##" class="edui-autotypesetpicker %%">' +
  23922. '<div class="edui-autotypesetpicker-body">' +
  23923. '<table >' +
  23924. '<tr><td nowrap><input type="checkbox" name="mergeEmptyline" ' + (opt["mergeEmptyline"] ? "checked" : "" ) + '>' + lang.mergeLine + '</td><td colspan="2"><input type="checkbox" name="removeEmptyline" ' + (opt["removeEmptyline"] ? "checked" : "" ) + '>' + lang.delLine + '</td></tr>' +
  23925. '<tr><td nowrap><input type="checkbox" name="removeClass" ' + (opt["removeClass"] ? "checked" : "" ) + '>' + lang.removeFormat + '</td><td colspan="2"><input type="checkbox" name="indent" ' + (opt["indent"] ? "checked" : "" ) + '>' + lang.indent + '</td></tr>' +
  23926. '<tr>' +
  23927. '<td nowrap><input type="checkbox" name="textAlign" ' + (opt["textAlign"] ? "checked" : "" ) + '>' + lang.alignment + '</td>' +
  23928. '<td colspan="2" id="' + textAlignInputName + '">' +
  23929. '<input type="radio" name="'+ textAlignInputName +'" value="left" ' + ((opt["textAlign"] && opt["textAlign"] == "left") ? "checked" : "") + '>' + me.getLang("justifyleft") +
  23930. '<input type="radio" name="'+ textAlignInputName +'" value="center" ' + ((opt["textAlign"] && opt["textAlign"] == "center") ? "checked" : "") + '>' + me.getLang("justifycenter") +
  23931. '<input type="radio" name="'+ textAlignInputName +'" value="right" ' + ((opt["textAlign"] && opt["textAlign"] == "right") ? "checked" : "") + '>' + me.getLang("justifyright") +
  23932. '</td>' +
  23933. '</tr>' +
  23934. '<tr>' +
  23935. '<td nowrap><input type="checkbox" name="imageBlockLine" ' + (opt["imageBlockLine"] ? "checked" : "" ) + '>' + lang.imageFloat + '</td>' +
  23936. '<td nowrap id="'+ imageBlockInputName +'">' +
  23937. '<input type="radio" name="'+ imageBlockInputName +'" value="none" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "none") ? "checked" : "") + '>' + me.getLang("default") +
  23938. '<input type="radio" name="'+ imageBlockInputName +'" value="left" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "left") ? "checked" : "") + '>' + me.getLang("justifyleft") +
  23939. '<input type="radio" name="'+ imageBlockInputName +'" value="center" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "center") ? "checked" : "") + '>' + me.getLang("justifycenter") +
  23940. '<input type="radio" name="'+ imageBlockInputName +'" value="right" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "right") ? "checked" : "") + '>' + me.getLang("justifyright") +
  23941. '</td>' +
  23942. '</tr>' +
  23943. '<tr><td nowrap><input type="checkbox" name="clearFontSize" ' + (opt["clearFontSize"] ? "checked" : "" ) + '>' + lang.removeFontsize + '</td><td colspan="2"><input type="checkbox" name="clearFontFamily" ' + (opt["clearFontFamily"] ? "checked" : "" ) + '>' + lang.removeFontFamily + '</td></tr>' +
  23944. '<tr><td nowrap colspan="3"><input type="checkbox" name="removeEmptyNode" ' + (opt["removeEmptyNode"] ? "checked" : "" ) + '>' + lang.removeHtml + '</td></tr>' +
  23945. '<tr><td nowrap colspan="3"><input type="checkbox" name="pasteFilter" ' + (opt["pasteFilter"] ? "checked" : "" ) + '>' + lang.pasteFilter + '</td></tr>' +
  23946. '<tr>' +
  23947. '<td nowrap><input type="checkbox" name="symbolConver" ' + (opt["bdc2sb"] || opt["tobdc"] ? "checked" : "" ) + '>' + lang.symbol + '</td>' +
  23948. '<td id="' + symbolConverInputName + '">' +
  23949. '<input type="radio" name="bdc" value="bdc2sb" ' + (opt["bdc2sb"] ? "checked" : "" ) + '>' + lang.bdc2sb +
  23950. '<input type="radio" name="bdc" value="tobdc" ' + (opt["tobdc"] ? "checked" : "" ) + '>' + lang.tobdc + '' +
  23951. '</td>' +
  23952. '<td nowrap align="right"><button >' + lang.run + '</button></td>' +
  23953. '</tr>' +
  23954. '</table>' +
  23955. '</div>' +
  23956. '</div>';
  23957. },
  23958. _UIBase_render:UIBase.prototype.render
  23959. };
  23960. utils.inherits(AutoTypeSetPicker, UIBase);
  23961. })();
  23962. // ui/autotypesetbutton.js
  23963. ///import core
  23964. ///import uicore
  23965. ///import ui/popup.js
  23966. ///import ui/autotypesetpicker.js
  23967. ///import ui/splitbutton.js
  23968. (function (){
  23969. var utils = baidu.editor.utils,
  23970. Popup = baidu.editor.ui.Popup,
  23971. AutoTypeSetPicker = baidu.editor.ui.AutoTypeSetPicker,
  23972. SplitButton = baidu.editor.ui.SplitButton,
  23973. AutoTypeSetButton = baidu.editor.ui.AutoTypeSetButton = function (options){
  23974. this.initOptions(options);
  23975. this.initAutoTypeSetButton();
  23976. };
  23977. function getPara(me){
  23978. var opt = {},
  23979. cont = me.getDom(),
  23980. editorId = me.editor.uid,
  23981. inputType = null,
  23982. attrName = null,
  23983. ipts = domUtils.getElementsByTagName(cont,"input");
  23984. for(var i=ipts.length-1,ipt;ipt=ipts[i--];){
  23985. inputType = ipt.getAttribute("type");
  23986. if(inputType=="checkbox"){
  23987. attrName = ipt.getAttribute("name");
  23988. opt[attrName] && delete opt[attrName];
  23989. if(ipt.checked){
  23990. var attrValue = document.getElementById( attrName + "Value" + editorId );
  23991. if(attrValue){
  23992. if(/input/ig.test(attrValue.tagName)){
  23993. opt[attrName] = attrValue.value;
  23994. } else {
  23995. var iptChilds = attrValue.getElementsByTagName("input");
  23996. for(var j=iptChilds.length-1,iptchild;iptchild=iptChilds[j--];){
  23997. if(iptchild.checked){
  23998. opt[attrName] = iptchild.value;
  23999. break;
  24000. }
  24001. }
  24002. }
  24003. } else {
  24004. opt[attrName] = true;
  24005. }
  24006. } else {
  24007. opt[attrName] = false;
  24008. }
  24009. } else {
  24010. opt[ipt.getAttribute("value")] = ipt.checked;
  24011. }
  24012. }
  24013. var selects = domUtils.getElementsByTagName(cont,"select");
  24014. for(var i=0,si;si=selects[i++];){
  24015. var attr = si.getAttribute('name');
  24016. opt[attr] = opt[attr] ? si.value : '';
  24017. }
  24018. utils.extend(me.editor.options.autotypeset,opt);
  24019. me.editor.setPreferences('autotypeset', opt);
  24020. }
  24021. AutoTypeSetButton.prototype = {
  24022. initAutoTypeSetButton: function (){
  24023. var me = this;
  24024. this.popup = new Popup({
  24025. //传入配置参数
  24026. content: new AutoTypeSetPicker({editor:me.editor}),
  24027. 'editor':me.editor,
  24028. hide : function(){
  24029. if (!this._hidden && this.getDom()) {
  24030. getPara(this);
  24031. this.getDom().style.display = 'none';
  24032. this._hidden = true;
  24033. this.fireEvent('hide');
  24034. }
  24035. }
  24036. });
  24037. var flag = 0;
  24038. this.popup.addListener('postRenderAfter',function(){
  24039. var popupUI = this;
  24040. if(flag)return;
  24041. var cont = this.getDom(),
  24042. btn = cont.getElementsByTagName('button')[0];
  24043. btn.onclick = function(){
  24044. getPara(popupUI);
  24045. me.editor.execCommand('autotypeset');
  24046. popupUI.hide()
  24047. };
  24048. domUtils.on(cont, 'click', function(e) {
  24049. var target = e.target || e.srcElement,
  24050. editorId = me.editor.uid;
  24051. if (target && target.tagName == 'INPUT') {
  24052. // 点击图片浮动的checkbox,去除对应的radio
  24053. if (target.name == 'imageBlockLine' || target.name == 'textAlign' || target.name == 'symbolConver') {
  24054. var checked = target.checked,
  24055. radioTd = document.getElementById( target.name + 'Value' + editorId),
  24056. radios = radioTd.getElementsByTagName('input'),
  24057. defalutSelect = {
  24058. 'imageBlockLine': 'none',
  24059. 'textAlign': 'left',
  24060. 'symbolConver': 'tobdc'
  24061. };
  24062. for (var i = 0; i < radios.length; i++) {
  24063. if (checked) {
  24064. if (radios[i].value == defalutSelect[target.name]) {
  24065. radios[i].checked = 'checked';
  24066. }
  24067. } else {
  24068. radios[i].checked = false;
  24069. }
  24070. }
  24071. }
  24072. // 点击radio,选中对应的checkbox
  24073. if (target.name == ('imageBlockLineValue' + editorId) || target.name == ('textAlignValue' + editorId) || target.name == 'bdc') {
  24074. var checkboxs = target.parentNode.previousSibling.getElementsByTagName('input');
  24075. checkboxs && (checkboxs[0].checked = true);
  24076. }
  24077. getPara(popupUI);
  24078. }
  24079. });
  24080. flag = 1;
  24081. });
  24082. this.initSplitButton();
  24083. }
  24084. };
  24085. utils.inherits(AutoTypeSetButton, SplitButton);
  24086. })();
  24087. // ui/cellalignpicker.js
  24088. ///import core
  24089. ///import uicore
  24090. (function () {
  24091. var utils = baidu.editor.utils,
  24092. Popup = baidu.editor.ui.Popup,
  24093. Stateful = baidu.editor.ui.Stateful,
  24094. UIBase = baidu.editor.ui.UIBase;
  24095. /**
  24096. * 该参数将新增一个参数: selected, 参数类型为一个Object, 形如{ 'align': 'center', 'valign': 'top' }, 表示单元格的初始
  24097. * 对齐状态为: 竖直居上,水平居中; 其中 align的取值为:'center', 'left', 'right'; valign的取值为: 'top', 'middle', 'bottom'
  24098. * @update 2013/4/2 hancong03@baidu.com
  24099. */
  24100. var CellAlignPicker = baidu.editor.ui.CellAlignPicker = function (options) {
  24101. this.initOptions(options);
  24102. this.initSelected();
  24103. this.initCellAlignPicker();
  24104. };
  24105. CellAlignPicker.prototype = {
  24106. //初始化选中状态, 该方法将根据传递进来的参数获取到应该选中的对齐方式图标的索引
  24107. initSelected: function(){
  24108. var status = {
  24109. valign: {
  24110. top: 0,
  24111. middle: 1,
  24112. bottom: 2
  24113. },
  24114. align: {
  24115. left: 0,
  24116. center: 1,
  24117. right: 2
  24118. },
  24119. count: 3
  24120. },
  24121. result = -1;
  24122. if( this.selected ) {
  24123. this.selectedIndex = status.valign[ this.selected.valign ] * status.count + status.align[ this.selected.align ];
  24124. }
  24125. },
  24126. initCellAlignPicker:function () {
  24127. this.initUIBase();
  24128. this.Stateful_init();
  24129. },
  24130. getHtmlTpl:function () {
  24131. var alignType = [ 'left', 'center', 'right' ],
  24132. COUNT = 9,
  24133. tempClassName = null,
  24134. tempIndex = -1,
  24135. tmpl = [];
  24136. for( var i= 0; i<COUNT; i++ ) {
  24137. tempClassName = this.selectedIndex === i ? ' class="edui-cellalign-selected" ' : '';
  24138. tempIndex = i % 3;
  24139. tempIndex === 0 && tmpl.push('<tr>');
  24140. tmpl.push( '<td index="'+ i +'" ' + tempClassName + ' stateful><div class="edui-icon edui-'+ alignType[ tempIndex ] +'"></div></td>' );
  24141. tempIndex === 2 && tmpl.push('</tr>');
  24142. }
  24143. return '<div id="##" class="edui-cellalignpicker %%">' +
  24144. '<div class="edui-cellalignpicker-body">' +
  24145. '<table onclick="$$._onClick(event);">' +
  24146. tmpl.join('') +
  24147. '</table>' +
  24148. '</div>' +
  24149. '</div>';
  24150. },
  24151. getStateDom: function (){
  24152. return this.target;
  24153. },
  24154. _onClick: function (evt){
  24155. var target= evt.target || evt.srcElement;
  24156. if(/icon/.test(target.className)){
  24157. this.items[target.parentNode.getAttribute("index")].onclick();
  24158. Popup.postHide(evt);
  24159. }
  24160. },
  24161. _UIBase_render:UIBase.prototype.render
  24162. };
  24163. utils.inherits(CellAlignPicker, UIBase);
  24164. utils.extend(CellAlignPicker.prototype, Stateful,true);
  24165. })();
  24166. // ui/pastepicker.js
  24167. ///import core
  24168. ///import uicore
  24169. (function () {
  24170. var utils = baidu.editor.utils,
  24171. Stateful = baidu.editor.ui.Stateful,
  24172. uiUtils = baidu.editor.ui.uiUtils,
  24173. UIBase = baidu.editor.ui.UIBase;
  24174. var PastePicker = baidu.editor.ui.PastePicker = function (options) {
  24175. this.initOptions(options);
  24176. this.initPastePicker();
  24177. };
  24178. PastePicker.prototype = {
  24179. initPastePicker:function () {
  24180. this.initUIBase();
  24181. this.Stateful_init();
  24182. },
  24183. getHtmlTpl:function () {
  24184. return '<div class="edui-pasteicon" onclick="$$._onClick(this)"></div>' +
  24185. '<div class="edui-pastecontainer">' +
  24186. '<div class="edui-title">' + this.editor.getLang("pasteOpt") + '</div>' +
  24187. '<div class="edui-button">' +
  24188. '<div title="' + this.editor.getLang("pasteSourceFormat") + '" onclick="$$.format(false)" stateful>' +
  24189. '<div class="edui-richtxticon"></div></div>' +
  24190. '<div title="' + this.editor.getLang("tagFormat") + '" onclick="$$.format(2)" stateful>' +
  24191. '<div class="edui-tagicon"></div></div>' +
  24192. '<div title="' + this.editor.getLang("pasteTextFormat") + '" onclick="$$.format(true)" stateful>' +
  24193. '<div class="edui-plaintxticon"></div></div>' +
  24194. '</div>' +
  24195. '</div>' +
  24196. '</div>'
  24197. },
  24198. getStateDom:function () {
  24199. return this.target;
  24200. },
  24201. format:function (param) {
  24202. this.editor.ui._isTransfer = true;
  24203. this.editor.fireEvent('pasteTransfer', param);
  24204. },
  24205. _onClick:function (cur) {
  24206. var node = domUtils.getNextDomNode(cur),
  24207. screenHt = uiUtils.getViewportRect().height,
  24208. subPop = uiUtils.getClientRect(node);
  24209. if ((subPop.top + subPop.height) > screenHt)
  24210. node.style.top = (-subPop.height - cur.offsetHeight) + "px";
  24211. else
  24212. node.style.top = "";
  24213. if (/hidden/ig.test(domUtils.getComputedStyle(node, "visibility"))) {
  24214. node.style.visibility = "visible";
  24215. domUtils.addClass(cur, "edui-state-opened");
  24216. } else {
  24217. node.style.visibility = "hidden";
  24218. domUtils.removeClasses(cur, "edui-state-opened")
  24219. }
  24220. },
  24221. _UIBase_render:UIBase.prototype.render
  24222. };
  24223. utils.inherits(PastePicker, UIBase);
  24224. utils.extend(PastePicker.prototype, Stateful, true);
  24225. })();
  24226. // ui/toolbar.js
  24227. (function (){
  24228. var utils = baidu.editor.utils,
  24229. uiUtils = baidu.editor.ui.uiUtils,
  24230. UIBase = baidu.editor.ui.UIBase,
  24231. Toolbar = baidu.editor.ui.Toolbar = function (options){
  24232. this.initOptions(options);
  24233. this.initToolbar();
  24234. };
  24235. Toolbar.prototype = {
  24236. items: null,
  24237. initToolbar: function (){
  24238. this.items = this.items || [];
  24239. this.initUIBase();
  24240. },
  24241. add: function (item,index){
  24242. if(index === undefined){
  24243. this.items.push(item);
  24244. }else{
  24245. this.items.splice(index,0,item)
  24246. }
  24247. },
  24248. getHtmlTpl: function (){
  24249. var buff = [];
  24250. for (var i=0; i<this.items.length; i++) {
  24251. buff[i] = this.items[i].renderHtml();
  24252. }
  24253. return '<div id="##" class="edui-toolbar %%" onselectstart="return false;" onmousedown="return $$._onMouseDown(event, this);">' +
  24254. buff.join('') +
  24255. '</div>'
  24256. },
  24257. postRender: function (){
  24258. var box = this.getDom();
  24259. for (var i=0; i<this.items.length; i++) {
  24260. this.items[i].postRender();
  24261. }
  24262. uiUtils.makeUnselectable(box);
  24263. },
  24264. _onMouseDown: function (e){
  24265. var target = e.target || e.srcElement,
  24266. tagName = target && target.tagName && target.tagName.toLowerCase();
  24267. if (tagName == 'input' || tagName == 'object' || tagName == 'object') {
  24268. return false;
  24269. }
  24270. }
  24271. };
  24272. utils.inherits(Toolbar, UIBase);
  24273. })();
  24274. // ui/menu.js
  24275. ///import core
  24276. ///import uicore
  24277. ///import ui\popup.js
  24278. ///import ui\stateful.js
  24279. (function () {
  24280. var utils = baidu.editor.utils,
  24281. domUtils = baidu.editor.dom.domUtils,
  24282. uiUtils = baidu.editor.ui.uiUtils,
  24283. UIBase = baidu.editor.ui.UIBase,
  24284. Popup = baidu.editor.ui.Popup,
  24285. Stateful = baidu.editor.ui.Stateful,
  24286. CellAlignPicker = baidu.editor.ui.CellAlignPicker,
  24287. Menu = baidu.editor.ui.Menu = function (options) {
  24288. this.initOptions(options);
  24289. this.initMenu();
  24290. };
  24291. var menuSeparator = {
  24292. renderHtml:function () {
  24293. return '<div class="edui-menuitem edui-menuseparator"><div class="edui-menuseparator-inner"></div></div>';
  24294. },
  24295. postRender:function () {
  24296. },
  24297. queryAutoHide:function () {
  24298. return true;
  24299. }
  24300. };
  24301. Menu.prototype = {
  24302. items:null,
  24303. uiName:'menu',
  24304. initMenu:function () {
  24305. this.items = this.items || [];
  24306. this.initPopup();
  24307. this.initItems();
  24308. },
  24309. initItems:function () {
  24310. for (var i = 0; i < this.items.length; i++) {
  24311. var item = this.items[i];
  24312. if (item == '-') {
  24313. this.items[i] = this.getSeparator();
  24314. } else if (!(item instanceof MenuItem)) {
  24315. item.editor = this.editor;
  24316. item.theme = this.editor.options.theme;
  24317. this.items[i] = this.createItem(item);
  24318. }
  24319. }
  24320. },
  24321. getSeparator:function () {
  24322. return menuSeparator;
  24323. },
  24324. createItem:function (item) {
  24325. //新增一个参数menu, 该参数存储了menuItem所对应的menu引用
  24326. item.menu = this;
  24327. return new MenuItem(item);
  24328. },
  24329. _Popup_getContentHtmlTpl:Popup.prototype.getContentHtmlTpl,
  24330. getContentHtmlTpl:function () {
  24331. if (this.items.length == 0) {
  24332. return this._Popup_getContentHtmlTpl();
  24333. }
  24334. var buff = [];
  24335. for (var i = 0; i < this.items.length; i++) {
  24336. var item = this.items[i];
  24337. buff[i] = item.renderHtml();
  24338. }
  24339. return ('<div class="%%-body">' + buff.join('') + '</div>');
  24340. },
  24341. _Popup_postRender:Popup.prototype.postRender,
  24342. postRender:function () {
  24343. var me = this;
  24344. for (var i = 0; i < this.items.length; i++) {
  24345. var item = this.items[i];
  24346. item.ownerMenu = this;
  24347. item.postRender();
  24348. }
  24349. domUtils.on(this.getDom(), 'mouseover', function (evt) {
  24350. evt = evt || event;
  24351. var rel = evt.relatedTarget || evt.fromElement;
  24352. var el = me.getDom();
  24353. if (!uiUtils.contains(el, rel) && el !== rel) {
  24354. me.fireEvent('over');
  24355. }
  24356. });
  24357. this._Popup_postRender();
  24358. },
  24359. queryAutoHide:function (el) {
  24360. if (el) {
  24361. if (uiUtils.contains(this.getDom(), el)) {
  24362. return false;
  24363. }
  24364. for (var i = 0; i < this.items.length; i++) {
  24365. var item = this.items[i];
  24366. if (item.queryAutoHide(el) === false) {
  24367. return false;
  24368. }
  24369. }
  24370. }
  24371. },
  24372. clearItems:function () {
  24373. for (var i = 0; i < this.items.length; i++) {
  24374. var item = this.items[i];
  24375. clearTimeout(item._showingTimer);
  24376. clearTimeout(item._closingTimer);
  24377. if (item.subMenu) {
  24378. item.subMenu.destroy();
  24379. }
  24380. }
  24381. this.items = [];
  24382. },
  24383. destroy:function () {
  24384. if (this.getDom()) {
  24385. domUtils.remove(this.getDom());
  24386. }
  24387. this.clearItems();
  24388. },
  24389. dispose:function () {
  24390. this.destroy();
  24391. }
  24392. };
  24393. utils.inherits(Menu, Popup);
  24394. /**
  24395. * @update 2013/04/03 hancong03 新增一个参数menu, 该参数存储了menuItem所对应的menu引用
  24396. * @type {Function}
  24397. */
  24398. var MenuItem = baidu.editor.ui.MenuItem = function (options) {
  24399. this.initOptions(options);
  24400. this.initUIBase();
  24401. this.Stateful_init();
  24402. if (this.subMenu && !(this.subMenu instanceof Menu)) {
  24403. if (options.className && options.className.indexOf("aligntd") != -1) {
  24404. var me = this;
  24405. //获取单元格对齐初始状态
  24406. this.subMenu.selected = this.editor.queryCommandValue( 'cellalignment' );
  24407. this.subMenu = new Popup({
  24408. content:new CellAlignPicker(this.subMenu),
  24409. parentMenu:me,
  24410. editor:me.editor,
  24411. destroy:function () {
  24412. if (this.getDom()) {
  24413. domUtils.remove(this.getDom());
  24414. }
  24415. }
  24416. });
  24417. this.subMenu.addListener("postRenderAfter", function () {
  24418. domUtils.on(this.getDom(), "mouseover", function () {
  24419. me.addState('opened');
  24420. });
  24421. });
  24422. } else {
  24423. this.subMenu = new Menu(this.subMenu);
  24424. }
  24425. }
  24426. };
  24427. MenuItem.prototype = {
  24428. label:'',
  24429. subMenu:null,
  24430. ownerMenu:null,
  24431. uiName:'menuitem',
  24432. alwalysHoverable:true,
  24433. getHtmlTpl:function () {
  24434. return '<div id="##" class="%%" stateful onclick="$$._onClick(event, this);">' +
  24435. '<div class="%%-body">' +
  24436. this.renderLabelHtml() +
  24437. '</div>' +
  24438. '</div>';
  24439. },
  24440. postRender:function () {
  24441. var me = this;
  24442. this.addListener('over', function () {
  24443. me.ownerMenu.fireEvent('submenuover', me);
  24444. if (me.subMenu) {
  24445. me.delayShowSubMenu();
  24446. }
  24447. });
  24448. if (this.subMenu) {
  24449. this.getDom().className += ' edui-hassubmenu';
  24450. this.subMenu.render();
  24451. this.addListener('out', function () {
  24452. me.delayHideSubMenu();
  24453. });
  24454. this.subMenu.addListener('over', function () {
  24455. clearTimeout(me._closingTimer);
  24456. me._closingTimer = null;
  24457. me.addState('opened');
  24458. });
  24459. this.ownerMenu.addListener('hide', function () {
  24460. me.hideSubMenu();
  24461. });
  24462. this.ownerMenu.addListener('submenuover', function (t, subMenu) {
  24463. if (subMenu !== me) {
  24464. me.delayHideSubMenu();
  24465. }
  24466. });
  24467. this.subMenu._bakQueryAutoHide = this.subMenu.queryAutoHide;
  24468. this.subMenu.queryAutoHide = function (el) {
  24469. if (el && uiUtils.contains(me.getDom(), el)) {
  24470. return false;
  24471. }
  24472. return this._bakQueryAutoHide(el);
  24473. };
  24474. }
  24475. this.getDom().style.tabIndex = '-1';
  24476. uiUtils.makeUnselectable(this.getDom());
  24477. this.Stateful_postRender();
  24478. },
  24479. delayShowSubMenu:function () {
  24480. var me = this;
  24481. if (!me.isDisabled()) {
  24482. me.addState('opened');
  24483. clearTimeout(me._showingTimer);
  24484. clearTimeout(me._closingTimer);
  24485. me._closingTimer = null;
  24486. me._showingTimer = setTimeout(function () {
  24487. me.showSubMenu();
  24488. }, 250);
  24489. }
  24490. },
  24491. delayHideSubMenu:function () {
  24492. var me = this;
  24493. if (!me.isDisabled()) {
  24494. me.removeState('opened');
  24495. clearTimeout(me._showingTimer);
  24496. if (!me._closingTimer) {
  24497. me._closingTimer = setTimeout(function () {
  24498. if (!me.hasState('opened')) {
  24499. me.hideSubMenu();
  24500. }
  24501. me._closingTimer = null;
  24502. }, 400);
  24503. }
  24504. }
  24505. },
  24506. renderLabelHtml:function () {
  24507. return '<div class="edui-arrow"></div>' +
  24508. '<div class="edui-box edui-icon"></div>' +
  24509. '<div class="edui-box edui-label %%-label">' + (this.label || '') + '</div>';
  24510. },
  24511. getStateDom:function () {
  24512. return this.getDom();
  24513. },
  24514. queryAutoHide:function (el) {
  24515. if (this.subMenu && this.hasState('opened')) {
  24516. return this.subMenu.queryAutoHide(el);
  24517. }
  24518. },
  24519. _onClick:function (event, this_) {
  24520. if (this.hasState('disabled')) return;
  24521. if (this.fireEvent('click', event, this_) !== false) {
  24522. if (this.subMenu) {
  24523. this.showSubMenu();
  24524. } else {
  24525. Popup.postHide(event);
  24526. }
  24527. }
  24528. },
  24529. showSubMenu:function () {
  24530. var rect = uiUtils.getClientRect(this.getDom());
  24531. rect.right -= 5;
  24532. rect.left += 2;
  24533. rect.width -= 7;
  24534. rect.top -= 4;
  24535. rect.bottom += 4;
  24536. rect.height += 8;
  24537. this.subMenu.showAnchorRect(rect, true, true);
  24538. },
  24539. hideSubMenu:function () {
  24540. this.subMenu.hide();
  24541. }
  24542. };
  24543. utils.inherits(MenuItem, UIBase);
  24544. utils.extend(MenuItem.prototype, Stateful, true);
  24545. })();
  24546. // ui/combox.js
  24547. ///import core
  24548. ///import uicore
  24549. ///import ui/menu.js
  24550. ///import ui/splitbutton.js
  24551. (function (){
  24552. // todo: menu和item提成通用list
  24553. var utils = baidu.editor.utils,
  24554. uiUtils = baidu.editor.ui.uiUtils,
  24555. Menu = baidu.editor.ui.Menu,
  24556. SplitButton = baidu.editor.ui.SplitButton,
  24557. Combox = baidu.editor.ui.Combox = function (options){
  24558. this.initOptions(options);
  24559. this.initCombox();
  24560. };
  24561. Combox.prototype = {
  24562. uiName: 'combox',
  24563. onbuttonclick:function () {
  24564. this.showPopup();
  24565. },
  24566. initCombox: function (){
  24567. var me = this;
  24568. this.items = this.items || [];
  24569. for (var i=0; i<this.items.length; i++) {
  24570. var item = this.items[i];
  24571. item.uiName = 'listitem';
  24572. item.index = i;
  24573. item.onclick = function (){
  24574. me.selectByIndex(this.index);
  24575. };
  24576. }
  24577. this.popup = new Menu({
  24578. items: this.items,
  24579. uiName: 'list',
  24580. editor:this.editor,
  24581. captureWheel: true,
  24582. combox: this
  24583. });
  24584. this.initSplitButton();
  24585. },
  24586. _SplitButton_postRender: SplitButton.prototype.postRender,
  24587. postRender: function (){
  24588. this._SplitButton_postRender();
  24589. this.setLabel(this.label || '');
  24590. this.setValue(this.initValue || '');
  24591. },
  24592. showPopup: function (){
  24593. var rect = uiUtils.getClientRect(this.getDom());
  24594. rect.top += 1;
  24595. rect.bottom -= 1;
  24596. rect.height -= 2;
  24597. this.popup.showAnchorRect(rect);
  24598. },
  24599. getValue: function (){
  24600. return this.value;
  24601. },
  24602. setValue: function (value){
  24603. var index = this.indexByValue(value);
  24604. if (index != -1) {
  24605. this.selectedIndex = index;
  24606. this.setLabel(this.items[index].label);
  24607. this.value = this.items[index].value;
  24608. } else {
  24609. this.selectedIndex = -1;
  24610. this.setLabel(this.getLabelForUnknowValue(value));
  24611. this.value = value;
  24612. }
  24613. },
  24614. setLabel: function (label){
  24615. this.getDom('button_body').innerHTML = label;
  24616. this.label = label;
  24617. },
  24618. getLabelForUnknowValue: function (value){
  24619. return value;
  24620. },
  24621. indexByValue: function (value){
  24622. for (var i=0; i<this.items.length; i++) {
  24623. if (value == this.items[i].value) {
  24624. return i;
  24625. }
  24626. }
  24627. return -1;
  24628. },
  24629. getItem: function (index){
  24630. return this.items[index];
  24631. },
  24632. selectByIndex: function (index){
  24633. if (index < this.items.length && this.fireEvent('select', index) !== false) {
  24634. this.selectedIndex = index;
  24635. this.value = this.items[index].value;
  24636. this.setLabel(this.items[index].label);
  24637. }
  24638. }
  24639. };
  24640. utils.inherits(Combox, SplitButton);
  24641. })();
  24642. // ui/dialog.js
  24643. ///import core
  24644. ///import uicore
  24645. ///import ui/mask.js
  24646. ///import ui/button.js
  24647. (function (){
  24648. var utils = baidu.editor.utils,
  24649. domUtils = baidu.editor.dom.domUtils,
  24650. uiUtils = baidu.editor.ui.uiUtils,
  24651. Mask = baidu.editor.ui.Mask,
  24652. UIBase = baidu.editor.ui.UIBase,
  24653. Button = baidu.editor.ui.Button,
  24654. Dialog = baidu.editor.ui.Dialog = function (options){
  24655. if(options.name){
  24656. var name = options.name;
  24657. var cssRules = options.cssRules;
  24658. if(!options.className){
  24659. options.className = 'edui-for-' + name;
  24660. }
  24661. if(cssRules){
  24662. options.cssRules = '.edui-default .edui-for-'+ name +' .edui-dialog-content {'+ cssRules +'}'
  24663. }
  24664. }
  24665. this.initOptions(utils.extend({
  24666. autoReset: true,
  24667. draggable: true,
  24668. onok: function (){},
  24669. oncancel: function (){},
  24670. onclose: function (t, ok){
  24671. return ok ? this.onok() : this.oncancel();
  24672. },
  24673. //是否控制dialog中的scroll事件, 默认为不阻止
  24674. holdScroll: false
  24675. },options));
  24676. this.initDialog();
  24677. };
  24678. var modalMask;
  24679. var dragMask;
  24680. var activeDialog;
  24681. Dialog.prototype = {
  24682. draggable: false,
  24683. uiName: 'dialog',
  24684. initDialog: function (){
  24685. var me = this,
  24686. theme=this.editor.options.theme;
  24687. if(this.cssRules){
  24688. utils.cssRule('edui-customize-'+this.name+'-style',this.cssRules);
  24689. }
  24690. this.initUIBase();
  24691. this.modalMask = (modalMask || (modalMask = new Mask({
  24692. className: 'edui-dialog-modalmask',
  24693. theme:theme,
  24694. onclick: function (){
  24695. activeDialog && activeDialog.close(false);
  24696. }
  24697. })));
  24698. this.dragMask = (dragMask || (dragMask = new Mask({
  24699. className: 'edui-dialog-dragmask',
  24700. theme:theme
  24701. })));
  24702. this.closeButton = new Button({
  24703. className: 'edui-dialog-closebutton',
  24704. title: me.closeDialog,
  24705. theme:theme,
  24706. onclick: function (){
  24707. me.close(false);
  24708. }
  24709. });
  24710. this.fullscreen && this.initResizeEvent();
  24711. if (this.buttons) {
  24712. for (var i=0; i<this.buttons.length; i++) {
  24713. if (!(this.buttons[i] instanceof Button)) {
  24714. this.buttons[i] = new Button(utils.extend(this.buttons[i],{
  24715. editor : this.editor
  24716. },true));
  24717. }
  24718. }
  24719. }
  24720. },
  24721. initResizeEvent: function () {
  24722. var me = this;
  24723. domUtils.on( window, "resize", function () {
  24724. if ( me._hidden || me._hidden === undefined ) {
  24725. return;
  24726. }
  24727. if ( me.__resizeTimer ) {
  24728. window.clearTimeout( me.__resizeTimer );
  24729. }
  24730. me.__resizeTimer = window.setTimeout( function () {
  24731. me.__resizeTimer = null;
  24732. var dialogWrapNode = me.getDom(),
  24733. contentNode = me.getDom('content'),
  24734. wrapRect = UE.ui.uiUtils.getClientRect( dialogWrapNode ),
  24735. contentRect = UE.ui.uiUtils.getClientRect( contentNode ),
  24736. vpRect = uiUtils.getViewportRect();
  24737. contentNode.style.width = ( vpRect.width - wrapRect.width + contentRect.width ) + "px";
  24738. contentNode.style.height = ( vpRect.height - wrapRect.height + contentRect.height ) + "px";
  24739. dialogWrapNode.style.width = vpRect.width + "px";
  24740. dialogWrapNode.style.height = vpRect.height + "px";
  24741. me.fireEvent( "resize" );
  24742. }, 100 );
  24743. } );
  24744. },
  24745. fitSize: function (){
  24746. var popBodyEl = this.getDom('body');
  24747. // if (!(baidu.editor.browser.ie && baidu.editor.browser.version == 7)) {
  24748. // uiUtils.removeStyle(popBodyEl, 'width');
  24749. // uiUtils.removeStyle(popBodyEl, 'height');
  24750. // }
  24751. var size = this.mesureSize();
  24752. popBodyEl.style.width = size.width + 'px';
  24753. popBodyEl.style.height = size.height + 'px';
  24754. return size;
  24755. },
  24756. safeSetOffset: function (offset){
  24757. var me = this;
  24758. var el = me.getDom();
  24759. var vpRect = uiUtils.getViewportRect();
  24760. var rect = uiUtils.getClientRect(el);
  24761. var left = offset.left;
  24762. if (left + rect.width > vpRect.right) {
  24763. left = vpRect.right - rect.width;
  24764. }
  24765. var top = offset.top;
  24766. if (top + rect.height > vpRect.bottom) {
  24767. top = vpRect.bottom - rect.height;
  24768. }
  24769. el.style.left = Math.max(left, 0) + 'px';
  24770. el.style.top = Math.max(top, 0) + 'px';
  24771. },
  24772. showAtCenter: function (){
  24773. var vpRect = uiUtils.getViewportRect();
  24774. if ( !this.fullscreen ) {
  24775. this.getDom().style.display = '';
  24776. var popSize = this.fitSize();
  24777. var titleHeight = this.getDom('titlebar').offsetHeight | 0;
  24778. var left = vpRect.width / 2 - popSize.width / 2;
  24779. var top = vpRect.height / 2 - (popSize.height - titleHeight) / 2 - titleHeight;
  24780. var popEl = this.getDom();
  24781. this.safeSetOffset({
  24782. left: Math.max(left | 0, 0),
  24783. top: Math.max(top | 0, 0)
  24784. });
  24785. if (!domUtils.hasClass(popEl, 'edui-state-centered')) {
  24786. popEl.className += ' edui-state-centered';
  24787. }
  24788. } else {
  24789. var dialogWrapNode = this.getDom(),
  24790. contentNode = this.getDom('content');
  24791. dialogWrapNode.style.display = "block";
  24792. var wrapRect = UE.ui.uiUtils.getClientRect( dialogWrapNode ),
  24793. contentRect = UE.ui.uiUtils.getClientRect( contentNode );
  24794. dialogWrapNode.style.left = "-100000px";
  24795. contentNode.style.width = ( vpRect.width - wrapRect.width + contentRect.width ) + "px";
  24796. contentNode.style.height = ( vpRect.height - wrapRect.height + contentRect.height ) + "px";
  24797. dialogWrapNode.style.width = vpRect.width + "px";
  24798. dialogWrapNode.style.height = vpRect.height + "px";
  24799. dialogWrapNode.style.left = 0;
  24800. //保存环境的overflow值
  24801. this._originalContext = {
  24802. html: {
  24803. overflowX: document.documentElement.style.overflowX,
  24804. overflowY: document.documentElement.style.overflowY
  24805. },
  24806. body: {
  24807. overflowX: document.body.style.overflowX,
  24808. overflowY: document.body.style.overflowY
  24809. }
  24810. };
  24811. document.documentElement.style.overflowX = 'hidden';
  24812. document.documentElement.style.overflowY = 'hidden';
  24813. document.body.style.overflowX = 'hidden';
  24814. document.body.style.overflowY = 'hidden';
  24815. }
  24816. this._show();
  24817. },
  24818. getContentHtml: function (){
  24819. var contentHtml = '';
  24820. if (typeof this.content == 'string') {
  24821. contentHtml = this.content;
  24822. } else if (this.iframeUrl) {
  24823. contentHtml = '<span id="'+ this.id +'_contmask" class="dialogcontmask"></span><iframe id="'+ this.id +
  24824. '_iframe" class="%%-iframe" height="100%" width="100%" frameborder="0" src="'+ this.iframeUrl +'"></iframe>';
  24825. }
  24826. return contentHtml;
  24827. },
  24828. getHtmlTpl: function (){
  24829. var footHtml = '';
  24830. if (this.buttons) {
  24831. var buff = [];
  24832. for (var i=0; i<this.buttons.length; i++) {
  24833. buff[i] = this.buttons[i].renderHtml();
  24834. }
  24835. footHtml = '<div class="%%-foot">' +
  24836. '<div id="##_buttons" class="%%-buttons">' + buff.join('') + '</div>' +
  24837. '</div>';
  24838. }
  24839. return '<div id="##" class="%%"><div '+ ( !this.fullscreen ? 'class="%%"' : 'class="%%-wrap edui-dialog-fullscreen-flag"' ) +'><div id="##_body" class="%%-body">' +
  24840. '<div class="%%-shadow"></div>' +
  24841. '<div id="##_titlebar" class="%%-titlebar">' +
  24842. '<div class="%%-draghandle" onmousedown="$$._onTitlebarMouseDown(event, this);">' +
  24843. '<span class="%%-caption">' + (this.title || '') + '</span>' +
  24844. '</div>' +
  24845. this.closeButton.renderHtml() +
  24846. '</div>' +
  24847. '<div id="##_content" class="%%-content">'+ ( this.autoReset ? '' : this.getContentHtml()) +'</div>' +
  24848. footHtml +
  24849. '</div></div></div>';
  24850. },
  24851. postRender: function (){
  24852. // todo: 保持居中/记住上次关闭位置选项
  24853. if (!this.modalMask.getDom()) {
  24854. this.modalMask.render();
  24855. this.modalMask.hide();
  24856. }
  24857. if (!this.dragMask.getDom()) {
  24858. this.dragMask.render();
  24859. this.dragMask.hide();
  24860. }
  24861. var me = this;
  24862. this.addListener('show', function (){
  24863. me.modalMask.show(this.getDom().style.zIndex - 2);
  24864. });
  24865. this.addListener('hide', function (){
  24866. me.modalMask.hide();
  24867. });
  24868. if (this.buttons) {
  24869. for (var i=0; i<this.buttons.length; i++) {
  24870. this.buttons[i].postRender();
  24871. }
  24872. }
  24873. domUtils.on(window, 'resize', function (){
  24874. setTimeout(function (){
  24875. if (!me.isHidden()) {
  24876. me.safeSetOffset(uiUtils.getClientRect(me.getDom()));
  24877. }
  24878. });
  24879. });
  24880. //hold住scroll事件,防止dialog的滚动影响页面
  24881. // if( this.holdScroll ) {
  24882. //
  24883. // if( !me.iframeUrl ) {
  24884. // domUtils.on( document.getElementById( me.id + "_iframe"), !browser.gecko ? "mousewheel" : "DOMMouseScroll", function(e){
  24885. // domUtils.preventDefault(e);
  24886. // } );
  24887. // } else {
  24888. // me.addListener('dialogafterreset', function(){
  24889. // window.setTimeout(function(){
  24890. // var iframeWindow = document.getElementById( me.id + "_iframe").contentWindow;
  24891. //
  24892. // if( browser.ie ) {
  24893. //
  24894. // var timer = window.setInterval(function(){
  24895. //
  24896. // if( iframeWindow.document && iframeWindow.document.body ) {
  24897. // window.clearInterval( timer );
  24898. // timer = null;
  24899. // domUtils.on( iframeWindow.document.body, !browser.gecko ? "mousewheel" : "DOMMouseScroll", function(e){
  24900. // domUtils.preventDefault(e);
  24901. // } );
  24902. // }
  24903. //
  24904. // }, 100);
  24905. //
  24906. // } else {
  24907. // domUtils.on( iframeWindow, !browser.gecko ? "mousewheel" : "DOMMouseScroll", function(e){
  24908. // domUtils.preventDefault(e);
  24909. // } );
  24910. // }
  24911. //
  24912. // }, 1);
  24913. // });
  24914. // }
  24915. //
  24916. // }
  24917. this._hide();
  24918. },
  24919. mesureSize: function (){
  24920. var body = this.getDom('body');
  24921. var width = uiUtils.getClientRect(this.getDom('content')).width;
  24922. var dialogBodyStyle = body.style;
  24923. dialogBodyStyle.width = width;
  24924. return uiUtils.getClientRect(body);
  24925. },
  24926. _onTitlebarMouseDown: function (evt, el){
  24927. if (this.draggable) {
  24928. var rect;
  24929. var vpRect = uiUtils.getViewportRect();
  24930. var me = this;
  24931. uiUtils.startDrag(evt, {
  24932. ondragstart: function (){
  24933. rect = uiUtils.getClientRect(me.getDom());
  24934. me.getDom('contmask').style.visibility = 'visible';
  24935. me.dragMask.show(me.getDom().style.zIndex - 1);
  24936. },
  24937. ondragmove: function (x, y){
  24938. var left = rect.left + x;
  24939. var top = rect.top + y;
  24940. me.safeSetOffset({
  24941. left: left,
  24942. top: top
  24943. });
  24944. },
  24945. ondragstop: function (){
  24946. me.getDom('contmask').style.visibility = 'hidden';
  24947. domUtils.removeClasses(me.getDom(), ['edui-state-centered']);
  24948. me.dragMask.hide();
  24949. }
  24950. });
  24951. }
  24952. },
  24953. reset: function (){
  24954. this.getDom('content').innerHTML = this.getContentHtml();
  24955. this.fireEvent('dialogafterreset');
  24956. },
  24957. _show: function (){
  24958. if (this._hidden) {
  24959. this.getDom().style.display = '';
  24960. //要高过编辑器的zindxe
  24961. this.editor.container.style.zIndex && (this.getDom().style.zIndex = this.editor.container.style.zIndex * 1 + 10);
  24962. this._hidden = false;
  24963. this.fireEvent('show');
  24964. baidu.editor.ui.uiUtils.getFixedLayer().style.zIndex = this.getDom().style.zIndex - 4;
  24965. }
  24966. },
  24967. isHidden: function (){
  24968. return this._hidden;
  24969. },
  24970. _hide: function (){
  24971. if (!this._hidden) {
  24972. var wrapNode = this.getDom();
  24973. wrapNode.style.display = 'none';
  24974. wrapNode.style.zIndex = '';
  24975. wrapNode.style.width = '';
  24976. wrapNode.style.height = '';
  24977. this._hidden = true;
  24978. this.fireEvent('hide');
  24979. }
  24980. },
  24981. open: function (){
  24982. if (this.autoReset) {
  24983. //有可能还没有渲染
  24984. try{
  24985. this.reset();
  24986. }catch(e){
  24987. this.render();
  24988. this.open()
  24989. }
  24990. }
  24991. this.showAtCenter();
  24992. if (this.iframeUrl) {
  24993. try {
  24994. this.getDom('iframe').focus();
  24995. } catch(ex){}
  24996. }
  24997. activeDialog = this;
  24998. },
  24999. _onCloseButtonClick: function (evt, el){
  25000. this.close(false);
  25001. },
  25002. close: function (ok){
  25003. if (this.fireEvent('close', ok) !== false) {
  25004. //还原环境
  25005. if ( this.fullscreen ) {
  25006. document.documentElement.style.overflowX = this._originalContext.html.overflowX;
  25007. document.documentElement.style.overflowY = this._originalContext.html.overflowY;
  25008. document.body.style.overflowX = this._originalContext.body.overflowX;
  25009. document.body.style.overflowY = this._originalContext.body.overflowY;
  25010. delete this._originalContext;
  25011. }
  25012. this._hide();
  25013. //销毁content
  25014. var content = this.getDom('content');
  25015. var iframe = this.getDom('iframe');
  25016. if (content && iframe) {
  25017. var doc = iframe.contentDocument || iframe.contentWindow.document;
  25018. doc && (doc.body.innerHTML = '');
  25019. domUtils.remove(content);
  25020. }
  25021. }
  25022. }
  25023. };
  25024. utils.inherits(Dialog, UIBase);
  25025. })();
  25026. // ui/menubutton.js
  25027. ///import core
  25028. ///import uicore
  25029. ///import ui/menu.js
  25030. ///import ui/splitbutton.js
  25031. (function (){
  25032. var utils = baidu.editor.utils,
  25033. Menu = baidu.editor.ui.Menu,
  25034. SplitButton = baidu.editor.ui.SplitButton,
  25035. MenuButton = baidu.editor.ui.MenuButton = function (options){
  25036. this.initOptions(options);
  25037. this.initMenuButton();
  25038. };
  25039. MenuButton.prototype = {
  25040. initMenuButton: function (){
  25041. var me = this;
  25042. this.uiName = "menubutton";
  25043. this.popup = new Menu({
  25044. items: me.items,
  25045. className: me.className,
  25046. editor:me.editor
  25047. });
  25048. this.popup.addListener('show', function (){
  25049. var list = this;
  25050. for (var i=0; i<list.items.length; i++) {
  25051. list.items[i].removeState('checked');
  25052. if (list.items[i].value == me._value) {
  25053. list.items[i].addState('checked');
  25054. this.value = me._value;
  25055. }
  25056. }
  25057. });
  25058. this.initSplitButton();
  25059. },
  25060. setValue : function(value){
  25061. this._value = value;
  25062. }
  25063. };
  25064. utils.inherits(MenuButton, SplitButton);
  25065. })();
  25066. // ui/multiMenu.js
  25067. ///import core
  25068. ///import uicore
  25069. ///commands 表情
  25070. (function(){
  25071. var utils = baidu.editor.utils,
  25072. Popup = baidu.editor.ui.Popup,
  25073. SplitButton = baidu.editor.ui.SplitButton,
  25074. MultiMenuPop = baidu.editor.ui.MultiMenuPop = function(options){
  25075. this.initOptions(options);
  25076. this.initMultiMenu();
  25077. };
  25078. MultiMenuPop.prototype = {
  25079. initMultiMenu: function (){
  25080. var me = this;
  25081. this.popup = new Popup({
  25082. content: '',
  25083. editor : me.editor,
  25084. iframe_rendered: false,
  25085. onshow: function (){
  25086. if (!this.iframe_rendered) {
  25087. this.iframe_rendered = true;
  25088. this.getDom('content').innerHTML = '<iframe id="'+me.id+'_iframe" src="'+ me.iframeUrl +'" frameborder="0"></iframe>';
  25089. me.editor.container.style.zIndex && (this.getDom().style.zIndex = me.editor.container.style.zIndex * 1 + 1);
  25090. }
  25091. }
  25092. // canSideUp:false,
  25093. // canSideLeft:false
  25094. });
  25095. this.onbuttonclick = function(){
  25096. this.showPopup();
  25097. };
  25098. this.initSplitButton();
  25099. }
  25100. };
  25101. utils.inherits(MultiMenuPop, SplitButton);
  25102. })();
  25103. // ui/shortcutmenu.js
  25104. (function () {
  25105. var UI = baidu.editor.ui,
  25106. UIBase = UI.UIBase,
  25107. uiUtils = UI.uiUtils,
  25108. utils = baidu.editor.utils,
  25109. domUtils = baidu.editor.dom.domUtils;
  25110. var allMenus = [],//存储所有快捷菜单
  25111. timeID,
  25112. isSubMenuShow = false;//是否有子pop显示
  25113. var ShortCutMenu = UI.ShortCutMenu = function (options) {
  25114. this.initOptions (options);
  25115. this.initShortCutMenu ();
  25116. };
  25117. ShortCutMenu.postHide = hideAllMenu;
  25118. ShortCutMenu.prototype = {
  25119. isHidden : true ,
  25120. SPACE : 5 ,
  25121. initShortCutMenu : function () {
  25122. this.items = this.items || [];
  25123. this.initUIBase ();
  25124. this.initItems ();
  25125. this.initEvent ();
  25126. allMenus.push (this);
  25127. } ,
  25128. initEvent : function () {
  25129. var me = this,
  25130. doc = me.editor.document;
  25131. domUtils.on (doc , "mousemove" , function (e) {
  25132. if (me.isHidden === false) {
  25133. //有pop显示就不隐藏快捷菜单
  25134. if (me.getSubMenuMark () || me.eventType == "contextmenu") return;
  25135. var flag = true,
  25136. el = me.getDom (),
  25137. wt = el.offsetWidth,
  25138. ht = el.offsetHeight,
  25139. distanceX = wt / 2 + me.SPACE,//距离中心X标准
  25140. distanceY = ht / 2,//距离中心Y标准
  25141. x = Math.abs (e.screenX - me.left),//离中心距离横坐标
  25142. y = Math.abs (e.screenY - me.top);//离中心距离纵坐标
  25143. clearTimeout (timeID);
  25144. timeID = setTimeout (function () {
  25145. if (y > 0 && y < distanceY) {
  25146. me.setOpacity (el , "1");
  25147. } else if (y > distanceY && y < distanceY + 70) {
  25148. me.setOpacity (el , "0.5");
  25149. flag = false;
  25150. } else if (y > distanceY + 70 && y < distanceY + 140) {
  25151. me.hide ();
  25152. }
  25153. if (flag && x > 0 && x < distanceX) {
  25154. me.setOpacity (el , "1")
  25155. } else if (x > distanceX && x < distanceX + 70) {
  25156. me.setOpacity (el , "0.5")
  25157. } else if (x > distanceX + 70 && x < distanceX + 140) {
  25158. me.hide ();
  25159. }
  25160. });
  25161. }
  25162. });
  25163. //ie\ff下 mouseout不准
  25164. if (browser.chrome) {
  25165. domUtils.on (doc , "mouseout" , function (e) {
  25166. var relatedTgt = e.relatedTarget || e.toElement;
  25167. if (relatedTgt == null || relatedTgt.tagName == "HTML") {
  25168. me.hide ();
  25169. }
  25170. });
  25171. }
  25172. me.editor.addListener ("afterhidepop" , function () {
  25173. if (!me.isHidden) {
  25174. isSubMenuShow = true;
  25175. }
  25176. });
  25177. } ,
  25178. initItems : function () {
  25179. if (utils.isArray (this.items)) {
  25180. for (var i = 0, len = this.items.length ; i < len ; i++) {
  25181. var item = this.items[i].toLowerCase ();
  25182. if (UI[item]) {
  25183. this.items[i] = new UI[item] (this.editor);
  25184. this.items[i].className += " edui-shortcutsubmenu ";
  25185. }
  25186. }
  25187. }
  25188. } ,
  25189. setOpacity : function (el , value) {
  25190. if (browser.ie && browser.version < 9) {
  25191. el.style.filter = "alpha(opacity = " + parseFloat (value) * 100 + ");"
  25192. } else {
  25193. el.style.opacity = value;
  25194. }
  25195. } ,
  25196. getSubMenuMark : function () {
  25197. isSubMenuShow = false;
  25198. var layerEle = uiUtils.getFixedLayer ();
  25199. var list = domUtils.getElementsByTagName (layerEle , "div" , function (node) {
  25200. return domUtils.hasClass (node , "edui-shortcutsubmenu edui-popup")
  25201. });
  25202. for (var i = 0, node ; node = list[i++] ;) {
  25203. if (node.style.display != "none") {
  25204. isSubMenuShow = true;
  25205. }
  25206. }
  25207. return isSubMenuShow;
  25208. } ,
  25209. show : function (e , hasContextmenu) {
  25210. var me = this,
  25211. offset = {},
  25212. el = this.getDom (),
  25213. fixedlayer = uiUtils.getFixedLayer ();
  25214. function setPos (offset) {
  25215. if (offset.left < 0) {
  25216. offset.left = 0;
  25217. }
  25218. if (offset.top < 0) {
  25219. offset.top = 0;
  25220. }
  25221. el.style.cssText = "position:absolute;left:" + offset.left + "px;top:" + offset.top + "px;";
  25222. }
  25223. function setPosByCxtMenu (menu) {
  25224. if (!menu.tagName) {
  25225. menu = menu.getDom ();
  25226. }
  25227. offset.left = parseInt (menu.style.left);
  25228. offset.top = parseInt (menu.style.top);
  25229. offset.top -= el.offsetHeight + 15;
  25230. setPos (offset);
  25231. }
  25232. me.eventType = e.type;
  25233. el.style.cssText = "display:block;left:-9999px";
  25234. if (e.type == "contextmenu" && hasContextmenu) {
  25235. var menu = domUtils.getElementsByTagName (fixedlayer , "div" , "edui-contextmenu")[0];
  25236. if (menu) {
  25237. setPosByCxtMenu (menu)
  25238. } else {
  25239. me.editor.addListener ("aftershowcontextmenu" , function (type , menu) {
  25240. setPosByCxtMenu (menu);
  25241. });
  25242. }
  25243. } else {
  25244. offset = uiUtils.getViewportOffsetByEvent (e);
  25245. offset.top -= el.offsetHeight + me.SPACE;
  25246. offset.left += me.SPACE + 20;
  25247. setPos (offset);
  25248. me.setOpacity (el , 0.2);
  25249. }
  25250. me.isHidden = false;
  25251. me.left = e.screenX + el.offsetWidth / 2 - me.SPACE;
  25252. me.top = e.screenY - (el.offsetHeight / 2) - me.SPACE;
  25253. if (me.editor) {
  25254. el.style.zIndex = me.editor.container.style.zIndex * 1 + 10;
  25255. fixedlayer.style.zIndex = el.style.zIndex - 1;
  25256. }
  25257. } ,
  25258. hide : function () {
  25259. if (this.getDom ()) {
  25260. this.getDom ().style.display = "none";
  25261. }
  25262. this.isHidden = true;
  25263. } ,
  25264. postRender : function () {
  25265. if (utils.isArray (this.items)) {
  25266. for (var i = 0, item ; item = this.items[i++] ;) {
  25267. item.postRender ();
  25268. }
  25269. }
  25270. } ,
  25271. getHtmlTpl : function () {
  25272. var buff;
  25273. if (utils.isArray (this.items)) {
  25274. buff = [];
  25275. for (var i = 0 ; i < this.items.length ; i++) {
  25276. buff[i] = this.items[i].renderHtml ();
  25277. }
  25278. buff = buff.join ("");
  25279. } else {
  25280. buff = this.items;
  25281. }
  25282. return '<div id="##" class="%% edui-toolbar" data-src="shortcutmenu" onmousedown="return false;" onselectstart="return false;" >' +
  25283. buff +
  25284. '</div>';
  25285. }
  25286. };
  25287. utils.inherits (ShortCutMenu , UIBase);
  25288. function hideAllMenu (e) {
  25289. var tgt = e.target || e.srcElement,
  25290. cur = domUtils.findParent (tgt , function (node) {
  25291. return domUtils.hasClass (node , "edui-shortcutmenu") || domUtils.hasClass (node , "edui-popup");
  25292. } , true);
  25293. if (!cur) {
  25294. for (var i = 0, menu ; menu = allMenus[i++] ;) {
  25295. menu.hide ()
  25296. }
  25297. }
  25298. }
  25299. domUtils.on (document , 'mousedown' , function (e) {
  25300. hideAllMenu (e);
  25301. });
  25302. domUtils.on (window , 'scroll' , function (e) {
  25303. hideAllMenu (e);
  25304. });
  25305. }) ();
  25306. // ui/breakline.js
  25307. (function (){
  25308. var utils = baidu.editor.utils,
  25309. UIBase = baidu.editor.ui.UIBase,
  25310. Breakline = baidu.editor.ui.Breakline = function (options){
  25311. this.initOptions(options);
  25312. this.initSeparator();
  25313. };
  25314. Breakline.prototype = {
  25315. uiName: 'Breakline',
  25316. initSeparator: function (){
  25317. this.initUIBase();
  25318. },
  25319. getHtmlTpl: function (){
  25320. return '<br/>';
  25321. }
  25322. };
  25323. utils.inherits(Breakline, UIBase);
  25324. })();
  25325. // ui/message.js
  25326. ///import core
  25327. ///import uicore
  25328. (function () {
  25329. var utils = baidu.editor.utils,
  25330. domUtils = baidu.editor.dom.domUtils,
  25331. UIBase = baidu.editor.ui.UIBase,
  25332. Message = baidu.editor.ui.Message = function (options){
  25333. this.initOptions(options);
  25334. this.initMessage();
  25335. };
  25336. Message.prototype = {
  25337. initMessage: function (){
  25338. this.initUIBase();
  25339. },
  25340. getHtmlTpl: function (){
  25341. return '<div id="##" class="edui-message %%">' +
  25342. ' <div id="##_closer" class="edui-message-closer">×</div>' +
  25343. ' <div id="##_body" class="edui-message-body edui-message-type-info">' +
  25344. ' <iframe style="position:absolute;z-index:-1;left:0;top:0;background-color: transparent;" frameborder="0" width="100%" height="100%" src="about:blank"></iframe>' +
  25345. ' <div class="edui-shadow"></div>' +
  25346. ' <div id="##_content" class="edui-message-content">' +
  25347. ' </div>' +
  25348. ' </div>' +
  25349. '</div>';
  25350. },
  25351. reset: function(opt){
  25352. var me = this;
  25353. if (!opt.keepshow) {
  25354. clearTimeout(this.timer);
  25355. me.timer = setTimeout(function(){
  25356. me.hide();
  25357. }, opt.timeout || 4000);
  25358. }
  25359. opt.content !== undefined && me.setContent(opt.content);
  25360. opt.type !== undefined && me.setType(opt.type);
  25361. me.show();
  25362. },
  25363. postRender: function(){
  25364. var me = this,
  25365. closer = this.getDom('closer');
  25366. closer && domUtils.on(closer, 'click', function(){
  25367. me.hide();
  25368. });
  25369. },
  25370. setContent: function(content){
  25371. this.getDom('content').innerHTML = content;
  25372. },
  25373. setType: function(type){
  25374. type = type || 'info';
  25375. var body = this.getDom('body');
  25376. body.className = body.className.replace(/edui-message-type-[\w-]+/, 'edui-message-type-' + type);
  25377. },
  25378. getContent: function(){
  25379. return this.getDom('content').innerHTML;
  25380. },
  25381. getType: function(){
  25382. var arr = this.getDom('body').match(/edui-message-type-([\w-]+)/);
  25383. return arr ? arr[1]:'';
  25384. },
  25385. show: function (){
  25386. this.getDom().style.display = 'block';
  25387. },
  25388. hide: function (){
  25389. var dom = this.getDom();
  25390. if (dom) {
  25391. dom.style.display = 'none';
  25392. dom.parentNode && dom.parentNode.removeChild(dom);
  25393. }
  25394. }
  25395. };
  25396. utils.inherits(Message, UIBase);
  25397. })();
  25398. // adapter/editorui.js
  25399. //ui跟编辑器的适配層
  25400. //那个按钮弹出是dialog,是下拉筐等都是在这个js中配置
  25401. //自己写的ui也要在这里配置,放到baidu.editor.ui下边,当编辑器实例化的时候会根据ueditor.config中的toolbars找到相应的进行实例化
  25402. (function () {
  25403. var utils = baidu.editor.utils;
  25404. var editorui = baidu.editor.ui;
  25405. var _Dialog = editorui.Dialog;
  25406. editorui.buttons = {};
  25407. editorui.Dialog = function (options) {
  25408. var dialog = new _Dialog(options);
  25409. dialog.addListener('hide', function () {
  25410. if (dialog.editor) {
  25411. var editor = dialog.editor;
  25412. try {
  25413. if (browser.gecko) {
  25414. var y = editor.window.scrollY,
  25415. x = editor.window.scrollX;
  25416. editor.body.focus();
  25417. editor.window.scrollTo(x, y);
  25418. } else {
  25419. editor.focus();
  25420. }
  25421. } catch (ex) {
  25422. }
  25423. }
  25424. });
  25425. return dialog;
  25426. };
  25427. var iframeUrlMap = {
  25428. 'anchor':'~/dialogs/anchor/anchor.html',
  25429. 'insertimage':'~/dialogs/image/image.html',
  25430. 'link':'~/dialogs/link/link.html',
  25431. 'spechars':'~/dialogs/spechars/spechars.html',
  25432. 'searchreplace':'~/dialogs/searchreplace/searchreplace.html',
  25433. 'map':'~/dialogs/map/map.html',
  25434. 'gmap':'~/dialogs/gmap/gmap.html',
  25435. 'insertvideo':'~/dialogs/video/video.html',
  25436. 'help':'~/dialogs/help/help.html',
  25437. 'preview':'~/dialogs/preview/preview.html',
  25438. 'emotion':'~/dialogs/emotion/emotion.html',
  25439. 'wordimage':'~/dialogs/wordimage/wordimage.html',
  25440. 'attachment':'~/dialogs/attachment/attachment.html',
  25441. 'insertframe':'~/dialogs/insertframe/insertframe.html',
  25442. 'edittip':'~/dialogs/table/edittip.html',
  25443. 'edittable':'~/dialogs/table/edittable.html',
  25444. 'edittd':'~/dialogs/table/edittd.html',
  25445. 'webapp':'~/dialogs/webapp/webapp.html',
  25446. 'snapscreen':'~/dialogs/snapscreen/snapscreen.html',
  25447. 'scrawl':'~/dialogs/scrawl/scrawl.html',
  25448. 'music':'~/dialogs/music/music.html',
  25449. 'template':'~/dialogs/template/template.html',
  25450. 'background':'~/dialogs/background/background.html',
  25451. 'charts': '~/dialogs/charts/charts.html'
  25452. };
  25453. //为工具栏添加按钮,以下都是统一的按钮触发命令,所以写在一起
  25454. var btnCmds = ['undo', 'redo', 'formatmatch',
  25455. 'bold', 'italic', 'underline', 'fontborder', 'touppercase', 'tolowercase',
  25456. 'strikethrough', 'subscript', 'superscript', 'source', 'indent', 'outdent',
  25457. 'blockquote', 'pasteplain', 'pagebreak',
  25458. 'selectall', 'print','horizontal', 'removeformat', 'time', 'date', 'unlink',
  25459. 'insertparagraphbeforetable', 'insertrow', 'insertcol', 'mergeright', 'mergedown', 'deleterow',
  25460. 'deletecol', 'splittorows', 'splittocols', 'splittocells', 'mergecells', 'deletetable', 'drafts'];
  25461. for (var i = 0, ci; ci = btnCmds[i++];) {
  25462. ci = ci.toLowerCase();
  25463. editorui[ci] = function (cmd) {
  25464. return function (editor) {
  25465. var ui = new editorui.Button({
  25466. className:'edui-for-' + cmd,
  25467. title:editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd) || '',
  25468. onclick:function () {
  25469. editor.execCommand(cmd);
  25470. },
  25471. theme:editor.options.theme,
  25472. showText:false
  25473. });
  25474. editorui.buttons[cmd] = ui;
  25475. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  25476. var state = editor.queryCommandState(cmd);
  25477. if (state == -1) {
  25478. ui.setDisabled(true);
  25479. ui.setChecked(false);
  25480. } else {
  25481. if (!uiReady) {
  25482. ui.setDisabled(false);
  25483. ui.setChecked(state);
  25484. }
  25485. }
  25486. });
  25487. return ui;
  25488. };
  25489. }(ci);
  25490. }
  25491. //清除文档
  25492. editorui.cleardoc = function (editor) {
  25493. var ui = new editorui.Button({
  25494. className:'edui-for-cleardoc',
  25495. title:editor.options.labelMap.cleardoc || editor.getLang("labelMap.cleardoc") || '',
  25496. theme:editor.options.theme,
  25497. onclick:function () {
  25498. if (confirm(editor.getLang("confirmClear"))) {
  25499. editor.execCommand('cleardoc');
  25500. }
  25501. }
  25502. });
  25503. editorui.buttons["cleardoc"] = ui;
  25504. editor.addListener('selectionchange', function () {
  25505. ui.setDisabled(editor.queryCommandState('cleardoc') == -1);
  25506. });
  25507. return ui;
  25508. };
  25509. //排版,图片排版,文字方向
  25510. var typeset = {
  25511. 'justify':['left', 'right', 'center', 'justify'],
  25512. 'imagefloat':['none', 'left', 'center', 'right'],
  25513. 'directionality':['ltr', 'rtl']
  25514. };
  25515. for (var p in typeset) {
  25516. (function (cmd, val) {
  25517. for (var i = 0, ci; ci = val[i++];) {
  25518. (function (cmd2) {
  25519. editorui[cmd.replace('float', '') + cmd2] = function (editor) {
  25520. var ui = new editorui.Button({
  25521. className:'edui-for-' + cmd.replace('float', '') + cmd2,
  25522. title:editor.options.labelMap[cmd.replace('float', '') + cmd2] || editor.getLang("labelMap." + cmd.replace('float', '') + cmd2) || '',
  25523. theme:editor.options.theme,
  25524. onclick:function () {
  25525. editor.execCommand(cmd, cmd2);
  25526. }
  25527. });
  25528. editorui.buttons[cmd] = ui;
  25529. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  25530. ui.setDisabled(editor.queryCommandState(cmd) == -1);
  25531. ui.setChecked(editor.queryCommandValue(cmd) == cmd2 && !uiReady);
  25532. });
  25533. return ui;
  25534. };
  25535. })(ci)
  25536. }
  25537. })(p, typeset[p])
  25538. }
  25539. //字体颜色和背景颜色
  25540. for (var i = 0, ci; ci = ['backcolor', 'forecolor'][i++];) {
  25541. editorui[ci] = function (cmd) {
  25542. return function (editor) {
  25543. var ui = new editorui.ColorButton({
  25544. className:'edui-for-' + cmd,
  25545. color:'default',
  25546. title:editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd) || '',
  25547. editor:editor,
  25548. onpickcolor:function (t, color) {
  25549. editor.execCommand(cmd, color);
  25550. },
  25551. onpicknocolor:function () {
  25552. editor.execCommand(cmd, 'default');
  25553. this.setColor('transparent');
  25554. this.color = 'default';
  25555. },
  25556. onbuttonclick:function () {
  25557. editor.execCommand(cmd, this.color);
  25558. }
  25559. });
  25560. editorui.buttons[cmd] = ui;
  25561. editor.addListener('selectionchange', function () {
  25562. ui.setDisabled(editor.queryCommandState(cmd) == -1);
  25563. });
  25564. return ui;
  25565. };
  25566. }(ci);
  25567. }
  25568. var dialogBtns = {
  25569. noOk:['searchreplace', 'help', 'spechars', 'webapp','preview'],
  25570. ok:['attachment', 'anchor', 'link', 'insertimage', 'map', 'gmap', 'insertframe', 'wordimage',
  25571. 'insertvideo', 'insertframe', 'edittip', 'edittable', 'edittd', 'scrawl', 'template', 'music', 'background', 'charts']
  25572. };
  25573. for (var p in dialogBtns) {
  25574. (function (type, vals) {
  25575. for (var i = 0, ci; ci = vals[i++];) {
  25576. //todo opera下存在问题
  25577. if (browser.opera && ci === "searchreplace") {
  25578. continue;
  25579. }
  25580. (function (cmd) {
  25581. editorui[cmd] = function (editor, iframeUrl, title) {
  25582. iframeUrl = iframeUrl || (editor.options.iframeUrlMap || {})[cmd] || iframeUrlMap[cmd];
  25583. title = editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd) || '';
  25584. var dialog;
  25585. //没有iframeUrl不创建dialog
  25586. if (iframeUrl) {
  25587. dialog = new editorui.Dialog(utils.extend({
  25588. iframeUrl:editor.ui.mapUrl(iframeUrl),
  25589. editor:editor,
  25590. className:'edui-for-' + cmd,
  25591. title:title,
  25592. holdScroll: cmd === 'insertimage',
  25593. fullscreen: /charts|preview/.test(cmd),
  25594. closeDialog:editor.getLang("closeDialog")
  25595. }, type == 'ok' ? {
  25596. buttons:[
  25597. {
  25598. className:'edui-okbutton',
  25599. label:editor.getLang("ok"),
  25600. editor:editor,
  25601. onclick:function () {
  25602. dialog.close(true);
  25603. }
  25604. },
  25605. {
  25606. className:'edui-cancelbutton',
  25607. label:editor.getLang("cancel"),
  25608. editor:editor,
  25609. onclick:function () {
  25610. dialog.close(false);
  25611. }
  25612. }
  25613. ]
  25614. } : {}));
  25615. editor.ui._dialogs[cmd + "Dialog"] = dialog;
  25616. }
  25617. var ui = new editorui.Button({
  25618. className:'edui-for-' + cmd,
  25619. title:title,
  25620. onclick:function () {
  25621. if (dialog) {
  25622. switch (cmd) {
  25623. case "wordimage":
  25624. var images = editor.execCommand("wordimage");
  25625. if (images && images.length) {
  25626. dialog.render();
  25627. dialog.open();
  25628. }
  25629. break;
  25630. case "scrawl":
  25631. if (editor.queryCommandState("scrawl") != -1) {
  25632. dialog.render();
  25633. dialog.open();
  25634. }
  25635. break;
  25636. default:
  25637. dialog.render();
  25638. dialog.open();
  25639. }
  25640. }
  25641. },
  25642. theme:editor.options.theme,
  25643. disabled:(cmd == 'scrawl' && editor.queryCommandState("scrawl") == -1) || ( cmd == 'charts' )
  25644. });
  25645. editorui.buttons[cmd] = ui;
  25646. editor.addListener('selectionchange', function () {
  25647. //只存在于右键菜单而无工具栏按钮的ui不需要检测状态
  25648. var unNeedCheckState = {'edittable':1};
  25649. if (cmd in unNeedCheckState)return;
  25650. var state = editor.queryCommandState(cmd);
  25651. if (ui.getDom()) {
  25652. ui.setDisabled(state == -1);
  25653. ui.setChecked(state);
  25654. }
  25655. });
  25656. return ui;
  25657. };
  25658. })(ci.toLowerCase())
  25659. }
  25660. })(p, dialogBtns[p]);
  25661. }
  25662. editorui.snapscreen = function (editor, iframeUrl, title) {
  25663. title = editor.options.labelMap['snapscreen'] || editor.getLang("labelMap.snapscreen") || '';
  25664. var ui = new editorui.Button({
  25665. className:'edui-for-snapscreen',
  25666. title:title,
  25667. onclick:function () {
  25668. editor.execCommand("snapscreen");
  25669. },
  25670. theme:editor.options.theme
  25671. });
  25672. editorui.buttons['snapscreen'] = ui;
  25673. iframeUrl = iframeUrl || (editor.options.iframeUrlMap || {})["snapscreen"] || iframeUrlMap["snapscreen"];
  25674. if (iframeUrl) {
  25675. var dialog = new editorui.Dialog({
  25676. iframeUrl:editor.ui.mapUrl(iframeUrl),
  25677. editor:editor,
  25678. className:'edui-for-snapscreen',
  25679. title:title,
  25680. buttons:[
  25681. {
  25682. className:'edui-okbutton',
  25683. label:editor.getLang("ok"),
  25684. editor:editor,
  25685. onclick:function () {
  25686. dialog.close(true);
  25687. }
  25688. },
  25689. {
  25690. className:'edui-cancelbutton',
  25691. label:editor.getLang("cancel"),
  25692. editor:editor,
  25693. onclick:function () {
  25694. dialog.close(false);
  25695. }
  25696. }
  25697. ]
  25698. });
  25699. dialog.render();
  25700. editor.ui._dialogs["snapscreenDialog"] = dialog;
  25701. }
  25702. editor.addListener('selectionchange', function () {
  25703. ui.setDisabled(editor.queryCommandState('snapscreen') == -1);
  25704. });
  25705. return ui;
  25706. };
  25707. editorui.insertcode = function (editor, list, title) {
  25708. list = editor.options['insertcode'] || [];
  25709. title = editor.options.labelMap['insertcode'] || editor.getLang("labelMap.insertcode") || '';
  25710. // if (!list.length) return;
  25711. var items = [];
  25712. utils.each(list,function(key,val){
  25713. items.push({
  25714. label:key,
  25715. value:val,
  25716. theme:editor.options.theme,
  25717. renderLabelHtml:function () {
  25718. return '<div class="edui-label %%-label" >' + (this.label || '') + '</div>';
  25719. }
  25720. });
  25721. });
  25722. var ui = new editorui.Combox({
  25723. editor:editor,
  25724. items:items,
  25725. onselect:function (t, index) {
  25726. editor.execCommand('insertcode', this.items[index].value);
  25727. },
  25728. onbuttonclick:function () {
  25729. this.showPopup();
  25730. },
  25731. title:title,
  25732. initValue:title,
  25733. className:'edui-for-insertcode',
  25734. indexByValue:function (value) {
  25735. if (value) {
  25736. for (var i = 0, ci; ci = this.items[i]; i++) {
  25737. if (ci.value.indexOf(value) != -1)
  25738. return i;
  25739. }
  25740. }
  25741. return -1;
  25742. }
  25743. });
  25744. editorui.buttons['insertcode'] = ui;
  25745. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  25746. if (!uiReady) {
  25747. var state = editor.queryCommandState('insertcode');
  25748. if (state == -1) {
  25749. ui.setDisabled(true);
  25750. } else {
  25751. ui.setDisabled(false);
  25752. var value = editor.queryCommandValue('insertcode');
  25753. if(!value){
  25754. ui.setValue(title);
  25755. return;
  25756. }
  25757. //trace:1871 ie下从源码模式切换回来时,字体会带单引号,而且会有逗号
  25758. value && (value = value.replace(/['"]/g, '').split(',')[0]);
  25759. ui.setValue(value);
  25760. }
  25761. }
  25762. });
  25763. return ui;
  25764. };
  25765. editorui.fontfamily = function (editor, list, title) {
  25766. list = editor.options['fontfamily'] || [];
  25767. title = editor.options.labelMap['fontfamily'] || editor.getLang("labelMap.fontfamily") || '';
  25768. if (!list.length) return;
  25769. for (var i = 0, ci, items = []; ci = list[i]; i++) {
  25770. var langLabel = editor.getLang('fontfamily')[ci.name] || "";
  25771. (function (key, val) {
  25772. items.push({
  25773. label:key,
  25774. value:val,
  25775. theme:editor.options.theme,
  25776. renderLabelHtml:function () {
  25777. return '<div class="edui-label %%-label" style="font-family:' +
  25778. utils.unhtml(this.value) + '">' + (this.label || '') + '</div>';
  25779. }
  25780. });
  25781. })(ci.label || langLabel, ci.val)
  25782. }
  25783. var ui = new editorui.Combox({
  25784. editor:editor,
  25785. items:items,
  25786. onselect:function (t, index) {
  25787. editor.execCommand('FontFamily', this.items[index].value);
  25788. },
  25789. onbuttonclick:function () {
  25790. this.showPopup();
  25791. },
  25792. title:title,
  25793. initValue:title,
  25794. className:'edui-for-fontfamily',
  25795. indexByValue:function (value) {
  25796. if (value) {
  25797. for (var i = 0, ci; ci = this.items[i]; i++) {
  25798. if (ci.value.indexOf(value) != -1)
  25799. return i;
  25800. }
  25801. }
  25802. return -1;
  25803. }
  25804. });
  25805. editorui.buttons['fontfamily'] = ui;
  25806. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  25807. if (!uiReady) {
  25808. var state = editor.queryCommandState('FontFamily');
  25809. if (state == -1) {
  25810. ui.setDisabled(true);
  25811. } else {
  25812. ui.setDisabled(false);
  25813. var value = editor.queryCommandValue('FontFamily');
  25814. //trace:1871 ie下从源码模式切换回来时,字体会带单引号,而且会有逗号
  25815. value && (value = value.replace(/['"]/g, '').split(',')[0]);
  25816. ui.setValue(value);
  25817. }
  25818. }
  25819. });
  25820. return ui;
  25821. };
  25822. editorui.fontsize = function (editor, list, title) {
  25823. title = editor.options.labelMap['fontsize'] || editor.getLang("labelMap.fontsize") || '';
  25824. list = list || editor.options['fontsize'] || [];
  25825. if (!list.length) return;
  25826. var items = [];
  25827. for (var i = 0; i < list.length; i++) {
  25828. var size = list[i] + 'px';
  25829. items.push({
  25830. label:size,
  25831. value:size,
  25832. theme:editor.options.theme,
  25833. renderLabelHtml:function () {
  25834. return '<div class="edui-label %%-label" style="line-height:1;font-size:' +
  25835. this.value + '">' + (this.label || '') + '</div>';
  25836. }
  25837. });
  25838. }
  25839. var ui = new editorui.Combox({
  25840. editor:editor,
  25841. items:items,
  25842. title:title,
  25843. initValue:title,
  25844. onselect:function (t, index) {
  25845. editor.execCommand('FontSize', this.items[index].value);
  25846. },
  25847. onbuttonclick:function () {
  25848. this.showPopup();
  25849. },
  25850. className:'edui-for-fontsize'
  25851. });
  25852. editorui.buttons['fontsize'] = ui;
  25853. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  25854. if (!uiReady) {
  25855. var state = editor.queryCommandState('FontSize');
  25856. if (state == -1) {
  25857. ui.setDisabled(true);
  25858. } else {
  25859. ui.setDisabled(false);
  25860. ui.setValue(editor.queryCommandValue('FontSize'));
  25861. }
  25862. }
  25863. });
  25864. return ui;
  25865. };
  25866. editorui.paragraph = function (editor, list, title) {
  25867. title = editor.options.labelMap['paragraph'] || editor.getLang("labelMap.paragraph") || '';
  25868. list = editor.options['paragraph'] || [];
  25869. if (utils.isEmptyObject(list)) return;
  25870. var items = [];
  25871. for (var i in list) {
  25872. items.push({
  25873. value:i,
  25874. label:list[i] || editor.getLang("paragraph")[i],
  25875. theme:editor.options.theme,
  25876. renderLabelHtml:function () {
  25877. return '<div class="edui-label %%-label"><span class="edui-for-' + this.value + '">' + (this.label || '') + '</span></div>';
  25878. }
  25879. })
  25880. }
  25881. var ui = new editorui.Combox({
  25882. editor:editor,
  25883. items:items,
  25884. title:title,
  25885. initValue:title,
  25886. className:'edui-for-paragraph',
  25887. onselect:function (t, index) {
  25888. editor.execCommand('Paragraph', this.items[index].value);
  25889. },
  25890. onbuttonclick:function () {
  25891. this.showPopup();
  25892. }
  25893. });
  25894. editorui.buttons['paragraph'] = ui;
  25895. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  25896. if (!uiReady) {
  25897. var state = editor.queryCommandState('Paragraph');
  25898. if (state == -1) {
  25899. ui.setDisabled(true);
  25900. } else {
  25901. ui.setDisabled(false);
  25902. var value = editor.queryCommandValue('Paragraph');
  25903. var index = ui.indexByValue(value);
  25904. if (index != -1) {
  25905. ui.setValue(value);
  25906. } else {
  25907. ui.setValue(ui.initValue);
  25908. }
  25909. }
  25910. }
  25911. });
  25912. return ui;
  25913. };
  25914. //自定义标题
  25915. editorui.customstyle = function (editor) {
  25916. var list = editor.options['customstyle'] || [],
  25917. title = editor.options.labelMap['customstyle'] || editor.getLang("labelMap.customstyle") || '';
  25918. if (!list.length)return;
  25919. var langCs = editor.getLang('customstyle');
  25920. for (var i = 0, items = [], t; t = list[i++];) {
  25921. (function (t) {
  25922. var ck = {};
  25923. ck.label = t.label ? t.label : langCs[t.name];
  25924. ck.style = t.style;
  25925. ck.className = t.className;
  25926. ck.tag = t.tag;
  25927. items.push({
  25928. label:ck.label,
  25929. value:ck,
  25930. theme:editor.options.theme,
  25931. renderLabelHtml:function () {
  25932. return '<div class="edui-label %%-label">' + '<' + ck.tag + ' ' + (ck.className ? ' class="' + ck.className + '"' : "")
  25933. + (ck.style ? ' style="' + ck.style + '"' : "") + '>' + ck.label + "<\/" + ck.tag + ">"
  25934. + '</div>';
  25935. }
  25936. });
  25937. })(t);
  25938. }
  25939. var ui = new editorui.Combox({
  25940. editor:editor,
  25941. items:items,
  25942. title:title,
  25943. initValue:title,
  25944. className:'edui-for-customstyle',
  25945. onselect:function (t, index) {
  25946. editor.execCommand('customstyle', this.items[index].value);
  25947. },
  25948. onbuttonclick:function () {
  25949. this.showPopup();
  25950. },
  25951. indexByValue:function (value) {
  25952. for (var i = 0, ti; ti = this.items[i++];) {
  25953. if (ti.label == value) {
  25954. return i - 1
  25955. }
  25956. }
  25957. return -1;
  25958. }
  25959. });
  25960. editorui.buttons['customstyle'] = ui;
  25961. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  25962. if (!uiReady) {
  25963. var state = editor.queryCommandState('customstyle');
  25964. if (state == -1) {
  25965. ui.setDisabled(true);
  25966. } else {
  25967. ui.setDisabled(false);
  25968. var value = editor.queryCommandValue('customstyle');
  25969. var index = ui.indexByValue(value);
  25970. if (index != -1) {
  25971. ui.setValue(value);
  25972. } else {
  25973. ui.setValue(ui.initValue);
  25974. }
  25975. }
  25976. }
  25977. });
  25978. return ui;
  25979. };
  25980. editorui.inserttable = function (editor, iframeUrl, title) {
  25981. title = editor.options.labelMap['inserttable'] || editor.getLang("labelMap.inserttable") || '';
  25982. var ui = new editorui.TableButton({
  25983. editor:editor,
  25984. title:title,
  25985. className:'edui-for-inserttable',
  25986. onpicktable:function (t, numCols, numRows) {
  25987. editor.execCommand('InsertTable', {numRows:numRows, numCols:numCols, border:1});
  25988. },
  25989. onbuttonclick:function () {
  25990. this.showPopup();
  25991. }
  25992. });
  25993. editorui.buttons['inserttable'] = ui;
  25994. editor.addListener('selectionchange', function () {
  25995. ui.setDisabled(editor.queryCommandState('inserttable') == -1);
  25996. });
  25997. return ui;
  25998. };
  25999. editorui.lineheight = function (editor) {
  26000. var val = editor.options.lineheight || [];
  26001. if (!val.length)return;
  26002. for (var i = 0, ci, items = []; ci = val[i++];) {
  26003. items.push({
  26004. //todo:写死了
  26005. label:ci,
  26006. value:ci,
  26007. theme:editor.options.theme,
  26008. onclick:function () {
  26009. editor.execCommand("lineheight", this.value);
  26010. }
  26011. })
  26012. }
  26013. var ui = new editorui.MenuButton({
  26014. editor:editor,
  26015. className:'edui-for-lineheight',
  26016. title:editor.options.labelMap['lineheight'] || editor.getLang("labelMap.lineheight") || '',
  26017. items:items,
  26018. onbuttonclick:function () {
  26019. var value = editor.queryCommandValue('LineHeight') || this.value;
  26020. editor.execCommand("LineHeight", value);
  26021. }
  26022. });
  26023. editorui.buttons['lineheight'] = ui;
  26024. editor.addListener('selectionchange', function () {
  26025. var state = editor.queryCommandState('LineHeight');
  26026. if (state == -1) {
  26027. ui.setDisabled(true);
  26028. } else {
  26029. ui.setDisabled(false);
  26030. var value = editor.queryCommandValue('LineHeight');
  26031. value && ui.setValue((value + '').replace(/cm/, ''));
  26032. ui.setChecked(state)
  26033. }
  26034. });
  26035. return ui;
  26036. };
  26037. var rowspacings = ['top', 'bottom'];
  26038. for (var r = 0, ri; ri = rowspacings[r++];) {
  26039. (function (cmd) {
  26040. editorui['rowspacing' + cmd] = function (editor) {
  26041. var val = editor.options['rowspacing' + cmd] || [];
  26042. if (!val.length) return null;
  26043. for (var i = 0, ci, items = []; ci = val[i++];) {
  26044. items.push({
  26045. label:ci,
  26046. value:ci,
  26047. theme:editor.options.theme,
  26048. onclick:function () {
  26049. editor.execCommand("rowspacing", this.value, cmd);
  26050. }
  26051. })
  26052. }
  26053. var ui = new editorui.MenuButton({
  26054. editor:editor,
  26055. className:'edui-for-rowspacing' + cmd,
  26056. title:editor.options.labelMap['rowspacing' + cmd] || editor.getLang("labelMap.rowspacing" + cmd) || '',
  26057. items:items,
  26058. onbuttonclick:function () {
  26059. var value = editor.queryCommandValue('rowspacing', cmd) || this.value;
  26060. editor.execCommand("rowspacing", value, cmd);
  26061. }
  26062. });
  26063. editorui.buttons[cmd] = ui;
  26064. editor.addListener('selectionchange', function () {
  26065. var state = editor.queryCommandState('rowspacing', cmd);
  26066. if (state == -1) {
  26067. ui.setDisabled(true);
  26068. } else {
  26069. ui.setDisabled(false);
  26070. var value = editor.queryCommandValue('rowspacing', cmd);
  26071. value && ui.setValue((value + '').replace(/%/, ''));
  26072. ui.setChecked(state)
  26073. }
  26074. });
  26075. return ui;
  26076. }
  26077. })(ri)
  26078. }
  26079. //有序,无序列表
  26080. var lists = ['insertorderedlist', 'insertunorderedlist'];
  26081. for (var l = 0, cl; cl = lists[l++];) {
  26082. (function (cmd) {
  26083. editorui[cmd] = function (editor) {
  26084. var vals = editor.options[cmd],
  26085. _onMenuClick = function () {
  26086. editor.execCommand(cmd, this.value);
  26087. }, items = [];
  26088. for (var i in vals) {
  26089. items.push({
  26090. label:vals[i] || editor.getLang()[cmd][i] || "",
  26091. value:i,
  26092. theme:editor.options.theme,
  26093. onclick:_onMenuClick
  26094. })
  26095. }
  26096. var ui = new editorui.MenuButton({
  26097. editor:editor,
  26098. className:'edui-for-' + cmd,
  26099. title:editor.getLang("labelMap." + cmd) || '',
  26100. 'items':items,
  26101. onbuttonclick:function () {
  26102. var value = editor.queryCommandValue(cmd) || this.value;
  26103. editor.execCommand(cmd, value);
  26104. }
  26105. });
  26106. editorui.buttons[cmd] = ui;
  26107. editor.addListener('selectionchange', function () {
  26108. var state = editor.queryCommandState(cmd);
  26109. if (state == -1) {
  26110. ui.setDisabled(true);
  26111. } else {
  26112. ui.setDisabled(false);
  26113. var value = editor.queryCommandValue(cmd);
  26114. ui.setValue(value);
  26115. ui.setChecked(state)
  26116. }
  26117. });
  26118. return ui;
  26119. };
  26120. })(cl)
  26121. }
  26122. editorui.fullscreen = function (editor, title) {
  26123. title = editor.options.labelMap['fullscreen'] || editor.getLang("labelMap.fullscreen") || '';
  26124. var ui = new editorui.Button({
  26125. className:'edui-for-fullscreen',
  26126. title:title,
  26127. theme:editor.options.theme,
  26128. onclick:function () {
  26129. if (editor.ui) {
  26130. editor.ui.setFullScreen(!editor.ui.isFullScreen());
  26131. }
  26132. this.setChecked(editor.ui.isFullScreen());
  26133. }
  26134. });
  26135. editorui.buttons['fullscreen'] = ui;
  26136. editor.addListener('selectionchange', function () {
  26137. var state = editor.queryCommandState('fullscreen');
  26138. ui.setDisabled(state == -1);
  26139. ui.setChecked(editor.ui.isFullScreen());
  26140. });
  26141. return ui;
  26142. };
  26143. // 表情
  26144. editorui["emotion"] = function (editor, iframeUrl) {
  26145. var cmd = "emotion";
  26146. var ui = new editorui.MultiMenuPop({
  26147. title:editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd + "") || '',
  26148. editor:editor,
  26149. className:'edui-for-' + cmd,
  26150. iframeUrl:editor.ui.mapUrl(iframeUrl || (editor.options.iframeUrlMap || {})[cmd] || iframeUrlMap[cmd])
  26151. });
  26152. editorui.buttons[cmd] = ui;
  26153. editor.addListener('selectionchange', function () {
  26154. ui.setDisabled(editor.queryCommandState(cmd) == -1)
  26155. });
  26156. return ui;
  26157. };
  26158. editorui.autotypeset = function (editor) {
  26159. var ui = new editorui.AutoTypeSetButton({
  26160. editor:editor,
  26161. title:editor.options.labelMap['autotypeset'] || editor.getLang("labelMap.autotypeset") || '',
  26162. className:'edui-for-autotypeset',
  26163. onbuttonclick:function () {
  26164. editor.execCommand('autotypeset')
  26165. }
  26166. });
  26167. editorui.buttons['autotypeset'] = ui;
  26168. editor.addListener('selectionchange', function () {
  26169. ui.setDisabled(editor.queryCommandState('autotypeset') == -1);
  26170. });
  26171. return ui;
  26172. };
  26173. /* 简单上传插件 */
  26174. editorui["simpleupload"] = function (editor) {
  26175. var name = 'simpleupload',
  26176. ui = new editorui.Button({
  26177. className:'edui-for-' + name,
  26178. title:editor.options.labelMap[name] || editor.getLang("labelMap." + name) || '',
  26179. onclick:function () {},
  26180. theme:editor.options.theme,
  26181. showText:false
  26182. });
  26183. editorui.buttons[name] = ui;
  26184. editor.addListener('ready', function() {
  26185. var b = ui.getDom('body'),
  26186. iconSpan = b.children[0];
  26187. editor.fireEvent('simpleuploadbtnready', iconSpan);
  26188. });
  26189. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  26190. var state = editor.queryCommandState(name);
  26191. if (state == -1) {
  26192. ui.setDisabled(true);
  26193. ui.setChecked(false);
  26194. } else {
  26195. if (!uiReady) {
  26196. ui.setDisabled(false);
  26197. ui.setChecked(state);
  26198. }
  26199. }
  26200. });
  26201. return ui;
  26202. };
  26203. })();
  26204. // adapter/editor.js
  26205. ///import core
  26206. ///commands 全屏
  26207. ///commandsName FullScreen
  26208. ///commandsTitle 全屏
  26209. (function () {
  26210. var utils = baidu.editor.utils,
  26211. uiUtils = baidu.editor.ui.uiUtils,
  26212. UIBase = baidu.editor.ui.UIBase,
  26213. domUtils = baidu.editor.dom.domUtils;
  26214. var nodeStack = [];
  26215. function EditorUI(options) {
  26216. this.initOptions(options);
  26217. this.initEditorUI();
  26218. }
  26219. EditorUI.prototype = {
  26220. uiName:'editor',
  26221. initEditorUI:function () {
  26222. this.editor.ui = this;
  26223. this._dialogs = {};
  26224. this.initUIBase();
  26225. this._initToolbars();
  26226. var editor = this.editor,
  26227. me = this;
  26228. editor.addListener('ready', function () {
  26229. //提供getDialog方法
  26230. editor.getDialog = function (name) {
  26231. return editor.ui._dialogs[name + "Dialog"];
  26232. };
  26233. domUtils.on(editor.window, 'scroll', function (evt) {
  26234. baidu.editor.ui.Popup.postHide(evt);
  26235. });
  26236. //提供编辑器实时宽高(全屏时宽高不变化)
  26237. editor.ui._actualFrameWidth = editor.options.initialFrameWidth;
  26238. UE.browser.ie && UE.browser.version === 6 && editor.container.ownerDocument.execCommand("BackgroundImageCache", false, true);
  26239. //display bottom-bar label based on config
  26240. if (editor.options.elementPathEnabled) {
  26241. editor.ui.getDom('elementpath').innerHTML = '<div class="edui-editor-breadcrumb">' + editor.getLang("elementPathTip") + ':</div>';
  26242. }
  26243. if (editor.options.wordCount) {
  26244. function countFn() {
  26245. setCount(editor,me);
  26246. domUtils.un(editor.document, "click", arguments.callee);
  26247. }
  26248. domUtils.on(editor.document, "click", countFn);
  26249. editor.ui.getDom('wordcount').innerHTML = editor.getLang("wordCountTip");
  26250. }
  26251. editor.ui._scale();
  26252. if (editor.options.scaleEnabled) {
  26253. if (editor.autoHeightEnabled) {
  26254. editor.disableAutoHeight();
  26255. }
  26256. me.enableScale();
  26257. } else {
  26258. me.disableScale();
  26259. }
  26260. if (!editor.options.elementPathEnabled && !editor.options.wordCount && !editor.options.scaleEnabled) {
  26261. editor.ui.getDom('elementpath').style.display = "none";
  26262. editor.ui.getDom('wordcount').style.display = "none";
  26263. editor.ui.getDom('scale').style.display = "none";
  26264. }
  26265. if (!editor.selection.isFocus())return;
  26266. editor.fireEvent('selectionchange', false, true);
  26267. });
  26268. editor.addListener('mousedown', function (t, evt) {
  26269. var el = evt.target || evt.srcElement;
  26270. baidu.editor.ui.Popup.postHide(evt, el);
  26271. baidu.editor.ui.ShortCutMenu.postHide(evt);
  26272. });
  26273. editor.addListener("delcells", function () {
  26274. if (UE.ui['edittip']) {
  26275. new UE.ui['edittip'](editor);
  26276. }
  26277. editor.getDialog('edittip').open();
  26278. });
  26279. var pastePop, isPaste = false, timer;
  26280. editor.addListener("afterpaste", function () {
  26281. if(editor.queryCommandState('pasteplain'))
  26282. return;
  26283. if(baidu.editor.ui.PastePicker){
  26284. pastePop = new baidu.editor.ui.Popup({
  26285. content:new baidu.editor.ui.PastePicker({editor:editor}),
  26286. editor:editor,
  26287. className:'edui-wordpastepop'
  26288. });
  26289. pastePop.render();
  26290. }
  26291. isPaste = true;
  26292. });
  26293. editor.addListener("afterinserthtml", function () {
  26294. clearTimeout(timer);
  26295. timer = setTimeout(function () {
  26296. if (pastePop && (isPaste || editor.ui._isTransfer)) {
  26297. if(pastePop.isHidden()){
  26298. var span = domUtils.createElement(editor.document, 'span', {
  26299. 'style':"line-height:0px;",
  26300. 'innerHTML':'\ufeff'
  26301. }),
  26302. range = editor.selection.getRange();
  26303. range.insertNode(span);
  26304. var tmp= getDomNode(span, 'firstChild', 'previousSibling');
  26305. tmp && pastePop.showAnchor(tmp.nodeType == 3 ? tmp.parentNode : tmp);
  26306. domUtils.remove(span);
  26307. }else{
  26308. pastePop.show();
  26309. }
  26310. delete editor.ui._isTransfer;
  26311. isPaste = false;
  26312. }
  26313. }, 200)
  26314. });
  26315. editor.addListener('contextmenu', function (t, evt) {
  26316. baidu.editor.ui.Popup.postHide(evt);
  26317. });
  26318. editor.addListener('keydown', function (t, evt) {
  26319. if (pastePop) pastePop.dispose(evt);
  26320. var keyCode = evt.keyCode || evt.which;
  26321. if(evt.altKey&&keyCode==90){
  26322. UE.ui.buttons['fullscreen'].onclick();
  26323. }
  26324. });
  26325. editor.addListener('wordcount', function (type) {
  26326. setCount(this,me);
  26327. });
  26328. function setCount(editor,ui) {
  26329. editor.setOpt({
  26330. wordCount:true,
  26331. maximumWords:10000,
  26332. wordCountMsg:editor.options.wordCountMsg || editor.getLang("wordCountMsg"),
  26333. wordOverFlowMsg:editor.options.wordOverFlowMsg || editor.getLang("wordOverFlowMsg")
  26334. });
  26335. var opt = editor.options,
  26336. max = opt.maximumWords,
  26337. msg = opt.wordCountMsg ,
  26338. errMsg = opt.wordOverFlowMsg,
  26339. countDom = ui.getDom('wordcount');
  26340. if (!opt.wordCount) {
  26341. return;
  26342. }
  26343. var count = editor.getContentLength(true);
  26344. if (count > max) {
  26345. countDom.innerHTML = errMsg;
  26346. editor.fireEvent("wordcountoverflow");
  26347. } else {
  26348. countDom.innerHTML = msg.replace("{#leave}", max - count).replace("{#count}", count);
  26349. }
  26350. }
  26351. editor.addListener('selectionchange', function () {
  26352. if (editor.options.elementPathEnabled) {
  26353. me[(editor.queryCommandState('elementpath') == -1 ? 'dis' : 'en') + 'ableElementPath']()
  26354. }
  26355. if (editor.options.scaleEnabled) {
  26356. me[(editor.queryCommandState('scale') == -1 ? 'dis' : 'en') + 'ableScale']();
  26357. }
  26358. });
  26359. var popup = new baidu.editor.ui.Popup({
  26360. editor:editor,
  26361. content:'',
  26362. className:'edui-bubble',
  26363. _onEditButtonClick:function () {
  26364. this.hide();
  26365. editor.ui._dialogs.linkDialog.open();
  26366. },
  26367. _onImgEditButtonClick:function (name) {
  26368. this.hide();
  26369. editor.ui._dialogs[name] && editor.ui._dialogs[name].open();
  26370. },
  26371. _onImgSetFloat:function (value) {
  26372. this.hide();
  26373. editor.execCommand("imagefloat", value);
  26374. },
  26375. _setIframeAlign:function (value) {
  26376. var frame = popup.anchorEl;
  26377. var newFrame = frame.cloneNode(true);
  26378. switch (value) {
  26379. case -2:
  26380. newFrame.setAttribute("align", "");
  26381. break;
  26382. case -1:
  26383. newFrame.setAttribute("align", "left");
  26384. break;
  26385. case 1:
  26386. newFrame.setAttribute("align", "right");
  26387. break;
  26388. }
  26389. frame.parentNode.insertBefore(newFrame, frame);
  26390. domUtils.remove(frame);
  26391. popup.anchorEl = newFrame;
  26392. popup.showAnchor(popup.anchorEl);
  26393. },
  26394. _updateIframe:function () {
  26395. var frame = editor._iframe = popup.anchorEl;
  26396. if(domUtils.hasClass(frame, 'ueditor_baidumap')) {
  26397. editor.selection.getRange().selectNode(frame).select();
  26398. editor.ui._dialogs.mapDialog.open();
  26399. popup.hide();
  26400. } else {
  26401. editor.ui._dialogs.insertframeDialog.open();
  26402. popup.hide();
  26403. }
  26404. },
  26405. _onRemoveButtonClick:function (cmdName) {
  26406. editor.execCommand(cmdName);
  26407. this.hide();
  26408. },
  26409. queryAutoHide:function (el) {
  26410. if (el && el.ownerDocument == editor.document) {
  26411. if (el.tagName.toLowerCase() == 'img' || domUtils.findParentByTagName(el, 'a', true)) {
  26412. return el !== popup.anchorEl;
  26413. }
  26414. }
  26415. return baidu.editor.ui.Popup.prototype.queryAutoHide.call(this, el);
  26416. }
  26417. });
  26418. popup.render();
  26419. if (editor.options.imagePopup) {
  26420. editor.addListener('mouseover', function (t, evt) {
  26421. evt = evt || window.event;
  26422. var el = evt.target || evt.srcElement;
  26423. if (editor.ui._dialogs.insertframeDialog && /iframe/ig.test(el.tagName)) {
  26424. var html = popup.formatHtml(
  26425. '<nobr>' + editor.getLang("property") + ': <span onclick=$$._setIframeAlign(-2) class="edui-clickable">' + editor.getLang("default") + '</span>&nbsp;&nbsp;<span onclick=$$._setIframeAlign(-1) class="edui-clickable">' + editor.getLang("justifyleft") + '</span>&nbsp;&nbsp;<span onclick=$$._setIframeAlign(1) class="edui-clickable">' + editor.getLang("justifyright") + '</span>&nbsp;&nbsp;' +
  26426. ' <span onclick="$$._updateIframe( this);" class="edui-clickable">' + editor.getLang("modify") + '</span></nobr>');
  26427. if (html) {
  26428. popup.getDom('content').innerHTML = html;
  26429. popup.anchorEl = el;
  26430. popup.showAnchor(popup.anchorEl);
  26431. } else {
  26432. popup.hide();
  26433. }
  26434. }
  26435. });
  26436. editor.addListener('selectionchange', function (t, causeByUi) {
  26437. if (!causeByUi) return;
  26438. var html = '', str = "",
  26439. img = editor.selection.getRange().getClosedNode(),
  26440. dialogs = editor.ui._dialogs;
  26441. if (img && img.tagName == 'IMG') {
  26442. var dialogName = 'insertimageDialog';
  26443. if (img.className.indexOf("edui-faked-video") != -1 || img.className.indexOf("edui-upload-video") != -1) {
  26444. dialogName = "insertvideoDialog"
  26445. }
  26446. if (img.className.indexOf("edui-faked-webapp") != -1) {
  26447. dialogName = "webappDialog"
  26448. }
  26449. if (img.src.indexOf("http://api.map.baidu.com") != -1) {
  26450. dialogName = "mapDialog"
  26451. }
  26452. if (img.className.indexOf("edui-faked-music") != -1) {
  26453. dialogName = "musicDialog"
  26454. }
  26455. if (img.src.indexOf("http://maps.google.com/maps/api/staticmap") != -1) {
  26456. dialogName = "gmapDialog"
  26457. }
  26458. if (img.getAttribute("anchorname")) {
  26459. dialogName = "anchorDialog";
  26460. html = popup.formatHtml(
  26461. '<nobr>' + editor.getLang("property") + ': <span onclick=$$._onImgEditButtonClick("anchorDialog") class="edui-clickable">' + editor.getLang("modify") + '</span>&nbsp;&nbsp;' +
  26462. '<span onclick=$$._onRemoveButtonClick(\'anchor\') class="edui-clickable">' + editor.getLang("delete") + '</span></nobr>');
  26463. }
  26464. if (img.getAttribute("word_img")) {
  26465. //todo 放到dialog去做查询
  26466. editor.word_img = [img.getAttribute("word_img")];
  26467. dialogName = "wordimageDialog"
  26468. }
  26469. if(domUtils.hasClass(img, 'loadingclass') || domUtils.hasClass(img, 'loaderrorclass')) {
  26470. dialogName = "";
  26471. }
  26472. if (!dialogs[dialogName]) {
  26473. return;
  26474. }
  26475. str = '<nobr>' + editor.getLang("property") + ': '+
  26476. '<span onclick=$$._onImgSetFloat("none") class="edui-clickable">' + editor.getLang("default") + '</span>&nbsp;&nbsp;' +
  26477. '<span onclick=$$._onImgSetFloat("left") class="edui-clickable">' + editor.getLang("justifyleft") + '</span>&nbsp;&nbsp;' +
  26478. '<span onclick=$$._onImgSetFloat("right") class="edui-clickable">' + editor.getLang("justifyright") + '</span>&nbsp;&nbsp;' +
  26479. '<span onclick=$$._onImgSetFloat("center") class="edui-clickable">' + editor.getLang("justifycenter") + '</span>&nbsp;&nbsp;'+
  26480. '<span onclick="$$._onImgEditButtonClick(\'' + dialogName + '\');" class="edui-clickable">' + editor.getLang("modify") + '</span></nobr>';
  26481. !html && (html = popup.formatHtml(str))
  26482. }
  26483. if (editor.ui._dialogs.linkDialog) {
  26484. var link = editor.queryCommandValue('link');
  26485. var url;
  26486. if (link && (url = (link.getAttribute('_href') || link.getAttribute('href', 2)))) {
  26487. var txt = url;
  26488. if (url.length > 30) {
  26489. txt = url.substring(0, 20) + "...";
  26490. }
  26491. if (html) {
  26492. html += '<div style="height:5px;"></div>'
  26493. }
  26494. html += popup.formatHtml(
  26495. '<nobr>' + editor.getLang("anthorMsg") + ': <a target="_blank" href="' + url + '" title="' + url + '" >' + txt + '</a>' +
  26496. ' <span class="edui-clickable" onclick="$$._onEditButtonClick();">' + editor.getLang("modify") + '</span>' +
  26497. ' <span class="edui-clickable" onclick="$$._onRemoveButtonClick(\'unlink\');"> ' + editor.getLang("clear") + '</span></nobr>');
  26498. popup.showAnchor(link);
  26499. }
  26500. }
  26501. if (html) {
  26502. popup.getDom('content').innerHTML = html;
  26503. popup.anchorEl = img || link;
  26504. popup.showAnchor(popup.anchorEl);
  26505. } else {
  26506. popup.hide();
  26507. }
  26508. });
  26509. }
  26510. },
  26511. _initToolbars:function () {
  26512. var editor = this.editor;
  26513. var toolbars = this.toolbars || [];
  26514. var toolbarUis = [];
  26515. for (var i = 0; i < toolbars.length; i++) {
  26516. var toolbar = toolbars[i];
  26517. var toolbarUi = new baidu.editor.ui.Toolbar({theme:editor.options.theme});
  26518. for (var j = 0; j < toolbar.length; j++) {
  26519. var toolbarItem = toolbar[j];
  26520. var toolbarItemUi = null;
  26521. if (typeof toolbarItem == 'string') {
  26522. toolbarItem = toolbarItem.toLowerCase();
  26523. if (toolbarItem == '|') {
  26524. toolbarItem = 'Separator';
  26525. }
  26526. if(toolbarItem == '||'){
  26527. toolbarItem = 'Breakline';
  26528. }
  26529. if (baidu.editor.ui[toolbarItem]) {
  26530. toolbarItemUi = new baidu.editor.ui[toolbarItem](editor);
  26531. }
  26532. //fullscreen这里单独处理一下,放到首行去
  26533. if (toolbarItem == 'fullscreen') {
  26534. if (toolbarUis && toolbarUis[0]) {
  26535. toolbarUis[0].items.splice(0, 0, toolbarItemUi);
  26536. } else {
  26537. toolbarItemUi && toolbarUi.items.splice(0, 0, toolbarItemUi);
  26538. }
  26539. continue;
  26540. }
  26541. } else {
  26542. toolbarItemUi = toolbarItem;
  26543. }
  26544. if (toolbarItemUi && toolbarItemUi.id) {
  26545. toolbarUi.add(toolbarItemUi);
  26546. }
  26547. }
  26548. toolbarUis[i] = toolbarUi;
  26549. }
  26550. //接受外部定制的UI
  26551. utils.each(UE._customizeUI,function(obj,key){
  26552. var itemUI,index;
  26553. if(obj.id && obj.id != editor.key){
  26554. return false;
  26555. }
  26556. itemUI = obj.execFn.call(editor,editor,key);
  26557. if(itemUI){
  26558. index = obj.index;
  26559. if(index === undefined){
  26560. index = toolbarUi.items.length;
  26561. }
  26562. toolbarUi.add(itemUI,index)
  26563. }
  26564. });
  26565. this.toolbars = toolbarUis;
  26566. },
  26567. getHtmlTpl:function () {
  26568. return '<div id="##" class="%%">' +
  26569. '<div id="##_toolbarbox" class="%%-toolbarbox">' +
  26570. (this.toolbars.length ?
  26571. '<div id="##_toolbarboxouter" class="%%-toolbarboxouter"><div class="%%-toolbarboxinner">' +
  26572. this.renderToolbarBoxHtml() +
  26573. '</div></div>' : '') +
  26574. '<div id="##_toolbarmsg" class="%%-toolbarmsg" style="display:none;">' +
  26575. '<div id = "##_upload_dialog" class="%%-toolbarmsg-upload" onclick="$$.showWordImageDialog();">' + this.editor.getLang("clickToUpload") + '</div>' +
  26576. '<div class="%%-toolbarmsg-close" onclick="$$.hideToolbarMsg();">x</div>' +
  26577. '<div id="##_toolbarmsg_label" class="%%-toolbarmsg-label"></div>' +
  26578. '<div style="height:0;overflow:hidden;clear:both;"></div>' +
  26579. '</div>' +
  26580. '<div id="##_message_holder" class="%%-messageholder"></div>' +
  26581. '</div>' +
  26582. '<div id="##_iframeholder" class="%%-iframeholder">' +
  26583. '</div>' +
  26584. //modify wdcount by matao
  26585. '<div id="##_bottombar" class="%%-bottomContainer"><table><tr>' +
  26586. '<td id="##_elementpath" class="%%-bottombar"></td>' +
  26587. '<td id="##_wordcount" class="%%-wordcount"></td>' +
  26588. '<td id="##_scale" class="%%-scale"><div class="%%-icon"></div></td>' +
  26589. '</tr></table></div>' +
  26590. '<div id="##_scalelayer"></div>' +
  26591. '</div>';
  26592. },
  26593. showWordImageDialog:function () {
  26594. this._dialogs['wordimageDialog'].open();
  26595. },
  26596. renderToolbarBoxHtml:function () {
  26597. var buff = [];
  26598. for (var i = 0; i < this.toolbars.length; i++) {
  26599. buff.push(this.toolbars[i].renderHtml());
  26600. }
  26601. return buff.join('');
  26602. },
  26603. setFullScreen:function (fullscreen) {
  26604. var editor = this.editor,
  26605. container = editor.container.parentNode.parentNode;
  26606. if (this._fullscreen != fullscreen) {
  26607. this._fullscreen = fullscreen;
  26608. this.editor.fireEvent('beforefullscreenchange', fullscreen);
  26609. if (baidu.editor.browser.gecko) {
  26610. var bk = editor.selection.getRange().createBookmark();
  26611. }
  26612. if (fullscreen) {
  26613. while (container.tagName != "BODY") {
  26614. var position = baidu.editor.dom.domUtils.getComputedStyle(container, "position");
  26615. nodeStack.push(position);
  26616. container.style.position = "static";
  26617. container = container.parentNode;
  26618. }
  26619. this._bakHtmlOverflow = document.documentElement.style.overflow;
  26620. this._bakBodyOverflow = document.body.style.overflow;
  26621. this._bakAutoHeight = this.editor.autoHeightEnabled;
  26622. this._bakScrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
  26623. this._bakEditorContaninerWidth = editor.iframe.parentNode.offsetWidth;
  26624. if (this._bakAutoHeight) {
  26625. //当全屏时不能执行自动长高
  26626. editor.autoHeightEnabled = false;
  26627. this.editor.disableAutoHeight();
  26628. }
  26629. document.documentElement.style.overflow = 'hidden';
  26630. //修复,滚动条不收起的问题
  26631. window.scrollTo(0,window.scrollY);
  26632. this._bakCssText = this.getDom().style.cssText;
  26633. this._bakCssText1 = this.getDom('iframeholder').style.cssText;
  26634. editor.iframe.parentNode.style.width = '';
  26635. this._updateFullScreen();
  26636. } else {
  26637. while (container.tagName != "BODY") {
  26638. container.style.position = nodeStack.shift();
  26639. container = container.parentNode;
  26640. }
  26641. this.getDom().style.cssText = this._bakCssText;
  26642. this.getDom('iframeholder').style.cssText = this._bakCssText1;
  26643. if (this._bakAutoHeight) {
  26644. editor.autoHeightEnabled = true;
  26645. this.editor.enableAutoHeight();
  26646. }
  26647. document.documentElement.style.overflow = this._bakHtmlOverflow;
  26648. document.body.style.overflow = this._bakBodyOverflow;
  26649. editor.iframe.parentNode.style.width = this._bakEditorContaninerWidth + 'px';
  26650. window.scrollTo(0, this._bakScrollTop);
  26651. }
  26652. if (browser.gecko && editor.body.contentEditable === 'true') {
  26653. var input = document.createElement('input');
  26654. document.body.appendChild(input);
  26655. editor.body.contentEditable = false;
  26656. setTimeout(function () {
  26657. input.focus();
  26658. setTimeout(function () {
  26659. editor.body.contentEditable = true;
  26660. editor.fireEvent('fullscreenchanged', fullscreen);
  26661. editor.selection.getRange().moveToBookmark(bk).select(true);
  26662. baidu.editor.dom.domUtils.remove(input);
  26663. fullscreen && window.scroll(0, 0);
  26664. }, 0)
  26665. }, 0)
  26666. }
  26667. if(editor.body.contentEditable === 'true'){
  26668. this.editor.fireEvent('fullscreenchanged', fullscreen);
  26669. this.triggerLayout();
  26670. }
  26671. }
  26672. },
  26673. _updateFullScreen:function () {
  26674. if (this._fullscreen) {
  26675. var vpRect = uiUtils.getViewportRect();
  26676. this.getDom().style.cssText = 'border:0;position:absolute;left:0;top:' + (this.editor.options.topOffset || 0) + 'px;width:' + vpRect.width + 'px;height:' + vpRect.height + 'px;z-index:' + (this.getDom().style.zIndex * 1 + 100);
  26677. uiUtils.setViewportOffset(this.getDom(), { left:0, top:this.editor.options.topOffset || 0 });
  26678. this.editor.setHeight(vpRect.height - this.getDom('toolbarbox').offsetHeight - this.getDom('bottombar').offsetHeight - (this.editor.options.topOffset || 0),true);
  26679. //不手动调一下,会导致全屏失效
  26680. if(browser.gecko){
  26681. try{
  26682. window.onresize();
  26683. }catch(e){
  26684. }
  26685. }
  26686. }
  26687. },
  26688. _updateElementPath:function () {
  26689. var bottom = this.getDom('elementpath'), list;
  26690. if (this.elementPathEnabled && (list = this.editor.queryCommandValue('elementpath'))) {
  26691. var buff = [];
  26692. for (var i = 0, ci; ci = list[i]; i++) {
  26693. buff[i] = this.formatHtml('<span unselectable="on" onclick="$$.editor.execCommand(&quot;elementpath&quot;, &quot;' + i + '&quot;);">' + ci + '</span>');
  26694. }
  26695. bottom.innerHTML = '<div class="edui-editor-breadcrumb" onmousedown="return false;">' + this.editor.getLang("elementPathTip") + ': ' + buff.join(' &gt; ') + '</div>';
  26696. } else {
  26697. bottom.style.display = 'none'
  26698. }
  26699. },
  26700. disableElementPath:function () {
  26701. var bottom = this.getDom('elementpath');
  26702. bottom.innerHTML = '';
  26703. bottom.style.display = 'none';
  26704. this.elementPathEnabled = false;
  26705. },
  26706. enableElementPath:function () {
  26707. var bottom = this.getDom('elementpath');
  26708. bottom.style.display = '';
  26709. this.elementPathEnabled = true;
  26710. this._updateElementPath();
  26711. },
  26712. _scale:function () {
  26713. var doc = document,
  26714. editor = this.editor,
  26715. editorHolder = editor.container,
  26716. editorDocument = editor.document,
  26717. toolbarBox = this.getDom("toolbarbox"),
  26718. bottombar = this.getDom("bottombar"),
  26719. scale = this.getDom("scale"),
  26720. scalelayer = this.getDom("scalelayer");
  26721. var isMouseMove = false,
  26722. position = null,
  26723. minEditorHeight = 0,
  26724. minEditorWidth = editor.options.minFrameWidth,
  26725. pageX = 0,
  26726. pageY = 0,
  26727. scaleWidth = 0,
  26728. scaleHeight = 0;
  26729. function down() {
  26730. position = domUtils.getXY(editorHolder);
  26731. if (!minEditorHeight) {
  26732. minEditorHeight = editor.options.minFrameHeight + toolbarBox.offsetHeight + bottombar.offsetHeight;
  26733. }
  26734. scalelayer.style.cssText = "position:absolute;left:0;display:;top:0;background-color:#41ABFF;opacity:0.4;filter: Alpha(opacity=40);width:" + editorHolder.offsetWidth + "px;height:"
  26735. + editorHolder.offsetHeight + "px;z-index:" + (editor.options.zIndex + 1);
  26736. domUtils.on(doc, "mousemove", move);
  26737. domUtils.on(editorDocument, "mouseup", up);
  26738. domUtils.on(doc, "mouseup", up);
  26739. }
  26740. var me = this;
  26741. //by xuheng 全屏时关掉缩放
  26742. this.editor.addListener('fullscreenchanged', function (e, fullScreen) {
  26743. if (fullScreen) {
  26744. me.disableScale();
  26745. } else {
  26746. if (me.editor.options.scaleEnabled) {
  26747. me.enableScale();
  26748. var tmpNode = me.editor.document.createElement('span');
  26749. me.editor.body.appendChild(tmpNode);
  26750. me.editor.body.style.height = Math.max(domUtils.getXY(tmpNode).y, me.editor.iframe.offsetHeight - 20) + 'px';
  26751. domUtils.remove(tmpNode)
  26752. }
  26753. }
  26754. });
  26755. function move(event) {
  26756. clearSelection();
  26757. var e = event || window.event;
  26758. pageX = e.pageX || (doc.documentElement.scrollLeft + e.clientX);
  26759. pageY = e.pageY || (doc.documentElement.scrollTop + e.clientY);
  26760. scaleWidth = pageX - position.x;
  26761. scaleHeight = pageY - position.y;
  26762. if (scaleWidth >= minEditorWidth) {
  26763. isMouseMove = true;
  26764. scalelayer.style.width = scaleWidth + 'px';
  26765. }
  26766. if (scaleHeight >= minEditorHeight) {
  26767. isMouseMove = true;
  26768. scalelayer.style.height = scaleHeight + "px";
  26769. }
  26770. }
  26771. function up() {
  26772. if (isMouseMove) {
  26773. isMouseMove = false;
  26774. editor.ui._actualFrameWidth = scalelayer.offsetWidth - 2;
  26775. editorHolder.style.width = editor.ui._actualFrameWidth + 'px';
  26776. editor.setHeight(scalelayer.offsetHeight - bottombar.offsetHeight - toolbarBox.offsetHeight - 2,true);
  26777. }
  26778. if (scalelayer) {
  26779. scalelayer.style.display = "none";
  26780. }
  26781. clearSelection();
  26782. domUtils.un(doc, "mousemove", move);
  26783. domUtils.un(editorDocument, "mouseup", up);
  26784. domUtils.un(doc, "mouseup", up);
  26785. }
  26786. function clearSelection() {
  26787. if (browser.ie)
  26788. doc.selection.clear();
  26789. else
  26790. window.getSelection().removeAllRanges();
  26791. }
  26792. this.enableScale = function () {
  26793. //trace:2868
  26794. if (editor.queryCommandState("source") == 1) return;
  26795. scale.style.display = "";
  26796. this.scaleEnabled = true;
  26797. domUtils.on(scale, "mousedown", down);
  26798. };
  26799. this.disableScale = function () {
  26800. scale.style.display = "none";
  26801. this.scaleEnabled = false;
  26802. domUtils.un(scale, "mousedown", down);
  26803. };
  26804. },
  26805. isFullScreen:function () {
  26806. return this._fullscreen;
  26807. },
  26808. postRender:function () {
  26809. UIBase.prototype.postRender.call(this);
  26810. for (var i = 0; i < this.toolbars.length; i++) {
  26811. this.toolbars[i].postRender();
  26812. }
  26813. var me = this;
  26814. var timerId,
  26815. domUtils = baidu.editor.dom.domUtils,
  26816. updateFullScreenTime = function () {
  26817. clearTimeout(timerId);
  26818. timerId = setTimeout(function () {
  26819. me._updateFullScreen();
  26820. });
  26821. };
  26822. domUtils.on(window, 'resize', updateFullScreenTime);
  26823. me.addListener('destroy', function () {
  26824. domUtils.un(window, 'resize', updateFullScreenTime);
  26825. clearTimeout(timerId);
  26826. })
  26827. },
  26828. showToolbarMsg:function (msg, flag) {
  26829. this.getDom('toolbarmsg_label').innerHTML = msg;
  26830. this.getDom('toolbarmsg').style.display = '';
  26831. //
  26832. if (!flag) {
  26833. var w = this.getDom('upload_dialog');
  26834. w.style.display = 'none';
  26835. }
  26836. },
  26837. hideToolbarMsg:function () {
  26838. this.getDom('toolbarmsg').style.display = 'none';
  26839. },
  26840. mapUrl:function (url) {
  26841. return url ? url.replace('~/', this.editor.options.UEDITOR_HOME_URL || '') : ''
  26842. },
  26843. triggerLayout:function () {
  26844. var dom = this.getDom();
  26845. if (dom.style.zoom == '1') {
  26846. dom.style.zoom = '100%';
  26847. } else {
  26848. dom.style.zoom = '1';
  26849. }
  26850. }
  26851. };
  26852. utils.inherits(EditorUI, baidu.editor.ui.UIBase);
  26853. var instances = {};
  26854. UE.ui.Editor = function (options) {
  26855. var editor = new UE.Editor(options);
  26856. editor.options.editor = editor;
  26857. utils.loadFile(document, {
  26858. href:editor.options.themePath + editor.options.theme + "/css/ueditor.css",
  26859. tag:"link",
  26860. type:"text/css",
  26861. rel:"stylesheet"
  26862. });
  26863. var oldRender = editor.render;
  26864. editor.render = function (holder) {
  26865. if (holder.constructor === String) {
  26866. editor.key = holder;
  26867. instances[holder] = editor;
  26868. }
  26869. utils.domReady(function () {
  26870. editor.langIsReady ? renderUI() : editor.addListener("langReady", renderUI);
  26871. function renderUI() {
  26872. editor.setOpt({
  26873. labelMap:editor.options.labelMap || editor.getLang('labelMap')
  26874. });
  26875. new EditorUI(editor.options);
  26876. if (holder) {
  26877. if (holder.constructor === String) {
  26878. holder = document.getElementById(holder);
  26879. }
  26880. holder && holder.getAttribute('name') && ( editor.options.textarea = holder.getAttribute('name'));
  26881. if (holder && /script|textarea/ig.test(holder.tagName)) {
  26882. var newDiv = document.createElement('div');
  26883. holder.parentNode.insertBefore(newDiv, holder);
  26884. var cont = holder.value || holder.innerHTML;
  26885. editor.options.initialContent = /^[\t\r\n ]*$/.test(cont) ? editor.options.initialContent :
  26886. cont.replace(/>[\n\r\t]+([ ]{4})+/g, '>')
  26887. .replace(/[\n\r\t]+([ ]{4})+</g, '<')
  26888. .replace(/>[\n\r\t]+</g, '><');
  26889. holder.className && (newDiv.className = holder.className);
  26890. holder.style.cssText && (newDiv.style.cssText = holder.style.cssText);
  26891. if (/textarea/i.test(holder.tagName)) {
  26892. editor.textarea = holder;
  26893. editor.textarea.style.display = 'none';
  26894. } else {
  26895. holder.parentNode.removeChild(holder);
  26896. }
  26897. if(holder.id){
  26898. newDiv.id = holder.id;
  26899. domUtils.removeAttributes(holder,'id');
  26900. }
  26901. holder = newDiv;
  26902. holder.innerHTML = '';
  26903. }
  26904. }
  26905. domUtils.addClass(holder, "edui-" + editor.options.theme);
  26906. editor.ui.render(holder);
  26907. var opt = editor.options;
  26908. //给实例添加一个编辑器的容器引用
  26909. editor.container = editor.ui.getDom();
  26910. var parents = domUtils.findParents(holder,true);
  26911. var displays = [];
  26912. for(var i = 0 ,ci;ci=parents[i];i++){
  26913. displays[i] = ci.style.display;
  26914. ci.style.display = 'block'
  26915. }
  26916. if (opt.initialFrameWidth) {
  26917. opt.minFrameWidth = opt.initialFrameWidth;
  26918. } else {
  26919. opt.minFrameWidth = opt.initialFrameWidth = holder.offsetWidth;
  26920. var styleWidth = holder.style.width;
  26921. if(/%$/.test(styleWidth)) {
  26922. opt.initialFrameWidth = styleWidth;
  26923. }
  26924. }
  26925. if (opt.initialFrameHeight) {
  26926. opt.minFrameHeight = opt.initialFrameHeight;
  26927. } else {
  26928. opt.initialFrameHeight = opt.minFrameHeight = holder.offsetHeight;
  26929. }
  26930. for(var i = 0 ,ci;ci=parents[i];i++){
  26931. ci.style.display = displays[i]
  26932. }
  26933. //编辑器最外容器设置了高度,会导致,编辑器不占位
  26934. //todo 先去掉,没有找到原因
  26935. if(holder.style.height){
  26936. holder.style.height = ''
  26937. }
  26938. editor.container.style.width = opt.initialFrameWidth + (/%$/.test(opt.initialFrameWidth) ? '' : 'px');
  26939. editor.container.style.zIndex = opt.zIndex;
  26940. oldRender.call(editor, editor.ui.getDom('iframeholder'));
  26941. editor.fireEvent("afteruiready");
  26942. }
  26943. })
  26944. };
  26945. return editor;
  26946. };
  26947. /**
  26948. * @file
  26949. * @name UE
  26950. * @short UE
  26951. * @desc UEditor的顶部命名空间
  26952. */
  26953. /**
  26954. * @name getEditor
  26955. * @since 1.2.4+
  26956. * @grammar UE.getEditor(id,[opt]) => Editor实例
  26957. * @desc 提供一个全局的方法得到编辑器实例
  26958. *
  26959. * * ''id'' 放置编辑器的容器id, 如果容器下的编辑器已经存在,就直接返回
  26960. * * ''opt'' 编辑器的可选参数
  26961. * @example
  26962. * UE.getEditor('containerId',{onready:function(){//创建一个编辑器实例
  26963. * this.setContent('hello')
  26964. * }});
  26965. * UE.getEditor('containerId'); //返回刚创建的实例
  26966. *
  26967. */
  26968. UE.getEditor = function (id, opt) {
  26969. var editor = instances[id];
  26970. if (!editor) {
  26971. editor = instances[id] = new UE.ui.Editor(opt);
  26972. editor.render(id);
  26973. }
  26974. return editor;
  26975. };
  26976. UE.delEditor = function (id) {
  26977. var editor;
  26978. if (editor = instances[id]) {
  26979. editor.key && editor.destroy();
  26980. delete instances[id]
  26981. }
  26982. };
  26983. UE.registerUI = function(uiName,fn,index,editorId){
  26984. utils.each(uiName.split(/\s+/), function (name) {
  26985. UE._customizeUI[name] = {
  26986. id : editorId,
  26987. execFn:fn,
  26988. index:index
  26989. };
  26990. })
  26991. }
  26992. })();
  26993. // adapter/message.js
  26994. UE.registerUI('message', function(editor) {
  26995. var editorui = baidu.editor.ui;
  26996. var Message = editorui.Message;
  26997. var holder;
  26998. var _messageItems = [];
  26999. var me = editor;
  27000. me.addListener('ready', function(){
  27001. holder = document.getElementById(me.ui.id + '_message_holder');
  27002. updateHolderPos();
  27003. setTimeout(function(){
  27004. updateHolderPos();
  27005. }, 500);
  27006. });
  27007. me.addListener('showmessage', function(type, opt){
  27008. opt = utils.isString(opt) ? {
  27009. 'content': opt
  27010. } : opt;
  27011. var message = new Message({
  27012. 'timeout': opt.timeout,
  27013. 'type': opt.type,
  27014. 'content': opt.content,
  27015. 'keepshow': opt.keepshow,
  27016. 'editor': me
  27017. }),
  27018. mid = opt.id || ('msg_' + (+new Date()).toString(36));
  27019. message.render(holder);
  27020. _messageItems[mid] = message;
  27021. message.reset(opt);
  27022. updateHolderPos();
  27023. return mid;
  27024. });
  27025. me.addListener('updatemessage',function(type, id, opt){
  27026. opt = utils.isString(opt) ? {
  27027. 'content': opt
  27028. } : opt;
  27029. var message = _messageItems[id];
  27030. message.render(holder);
  27031. message && message.reset(opt);
  27032. });
  27033. me.addListener('hidemessage',function(type, id){
  27034. var message = _messageItems[id];
  27035. message && message.hide();
  27036. });
  27037. function updateHolderPos(){
  27038. var toolbarbox = me.ui.getDom('toolbarbox');
  27039. if (toolbarbox) {
  27040. holder.style.top = toolbarbox.offsetHeight + 3 + 'px';
  27041. }
  27042. holder.style.zIndex = Math.max(me.options.zIndex, me.iframe.style.zIndex) + 1;
  27043. }
  27044. });
  27045. // adapter/autosave.js
  27046. UE.registerUI('autosave', function(editor) {
  27047. var timer = null,uid = null;
  27048. editor.on('afterautosave',function(){
  27049. clearTimeout(timer);
  27050. timer = setTimeout(function(){
  27051. if(uid){
  27052. editor.trigger('hidemessage',uid);
  27053. }
  27054. uid = editor.trigger('showmessage',{
  27055. content : editor.getLang('autosave.success'),
  27056. timeout : 2000
  27057. });
  27058. },2000)
  27059. })
  27060. });
  27061. })();